FeedsCSVParser.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. <?php
  2. /**
  3. * @file
  4. * Contains the FeedsCSVParser class.
  5. */
  6. /**
  7. * Parses a given file as a CSV file.
  8. */
  9. class FeedsCSVParser extends FeedsParser {
  10. /**
  11. * Implements FeedsParser::parse().
  12. */
  13. public function parse(FeedsSource $source, FeedsFetcherResult $fetcher_result) {
  14. $source_config = $source->getConfigFor($this);
  15. $state = $source->state(FEEDS_PARSE);
  16. // Load and configure parser.
  17. feeds_include_library('ParserCSV.inc', 'ParserCSV');
  18. $parser = new ParserCSV();
  19. $delimiter = $this->getDelimiterChar($source_config);
  20. $parser->setDelimiter($delimiter);
  21. if (isset($source_config['encoding'])) {
  22. // Encoding can only be set when the mbstring extension is loaded.
  23. $parser->setEncoding($source_config['encoding']);
  24. }
  25. $iterator = new ParserCSVIterator($fetcher_result->getFilePath());
  26. if (empty($source_config['no_headers'])) {
  27. // Get first line and use it for column names, convert them to lower case.
  28. $header = $this->parseHeader($parser, $iterator);
  29. if (!$header) {
  30. drupal_set_message(t('The CSV file is empty.'), 'warning', FALSE);
  31. return new FeedsParserResult();
  32. }
  33. $parser->setColumnNames($header);
  34. }
  35. // Determine section to parse, parse.
  36. $start = $state->pointer ? $state->pointer : $parser->lastLinePos();
  37. $limit = $source->importer->getLimit();
  38. $rows = $this->parseItems($parser, $iterator, $start, $limit);
  39. // Report progress.
  40. $state->total = filesize($fetcher_result->getFilePath());
  41. $state->pointer = $parser->lastLinePos();
  42. $progress = $parser->lastLinePos() ? $parser->lastLinePos() : $state->total;
  43. $state->progress($state->total, $progress);
  44. // Create a result object and return it.
  45. return new FeedsParserResult($rows, $source->feed_nid);
  46. }
  47. /**
  48. * Get first line and use it for column names, convert them to lower case.
  49. * Be aware that the $parser and iterator objects can be modified in this
  50. * function since they are passed in by reference
  51. *
  52. * @param ParserCSV $parser
  53. * @param ParserCSVIterator $iterator
  54. * @return
  55. * An array of lower-cased column names to use as keys for the parsed items.
  56. */
  57. protected function parseHeader(ParserCSV $parser, ParserCSVIterator $iterator) {
  58. $parser->setLineLimit(1);
  59. $rows = $parser->parse($iterator);
  60. if (!count($rows)) {
  61. return FALSE;
  62. }
  63. $header = array_shift($rows);
  64. foreach ($header as $i => $title) {
  65. $header[$i] = trim(drupal_strtolower($title));
  66. }
  67. return $header;
  68. }
  69. /**
  70. * Parse all of the items from the CSV.
  71. *
  72. * @param ParserCSV $parser
  73. * @param ParserCSVIterator $iterator
  74. * @return
  75. * An array of rows of the CSV keyed by the column names previously set
  76. */
  77. protected function parseItems(ParserCSV $parser, ParserCSVIterator $iterator, $start = 0, $limit = 0) {
  78. $parser->setLineLimit($limit);
  79. $parser->setStartByte($start);
  80. $rows = $parser->parse($iterator);
  81. return $rows;
  82. }
  83. /**
  84. * Override parent::getMappingSources().
  85. */
  86. public function getMappingSources() {
  87. return FALSE;
  88. }
  89. /**
  90. * Override parent::getSourceElement() to use only lower keys.
  91. */
  92. public function getSourceElement(FeedsSource $source, FeedsParserResult $result, $element_key) {
  93. return parent::getSourceElement($source, $result, drupal_strtolower($element_key));
  94. }
  95. /**
  96. * Override parent::getMappingSourceList() to use only lower keys.
  97. */
  98. public function getMappingSourceList() {
  99. return array_map('drupal_strtolower', parent::getMappingSourceList());
  100. }
  101. /**
  102. * Define defaults.
  103. */
  104. public function sourceDefaults() {
  105. return array(
  106. 'delimiter' => $this->config['delimiter'],
  107. 'encoding' => $this->config['encoding'],
  108. 'no_headers' => $this->config['no_headers'],
  109. );
  110. }
  111. /**
  112. * Source form.
  113. *
  114. * Show mapping configuration as a guidance for import form users.
  115. */
  116. public function sourceForm($source_config) {
  117. $form = array();
  118. $form['#weight'] = -10;
  119. $mappings = feeds_importer($this->id)->processor->config['mappings'];
  120. $sources = $uniques = array();
  121. foreach ($mappings as $mapping) {
  122. if (strpos($mapping['source'], ',') !== FALSE) {
  123. $sources[] = '"' . $mapping['source'] . '"';
  124. }
  125. else {
  126. $sources[] = $mapping['source'];
  127. }
  128. if (!empty($mapping['unique'])) {
  129. $uniques[] = $mapping['source'];
  130. }
  131. }
  132. $sources = array_unique($sources);
  133. $output = t('Import !csv_files with one or more of these columns: @columns.', array('!csv_files' => l(t('CSV files'), 'http://en.wikipedia.org/wiki/Comma-separated_values'), '@columns' => implode(', ', $sources)));
  134. $items = array();
  135. $items[] = format_plural(count($uniques), 'Column <strong>@columns</strong> is mandatory and considered unique: only one item per @columns value will be created.', 'Columns <strong>@columns</strong> are mandatory and values in these columns are considered unique: only one entry per value in one of these column will be created.', array('@columns' => implode(', ', $uniques)));
  136. $items[] = l(t('Download a template'), 'import/' . $this->id . '/template');
  137. $form['help'] = array(
  138. '#prefix' => '<div class="help">',
  139. '#suffix' => '</div>',
  140. 'description' => array(
  141. '#prefix' => '<p>',
  142. '#markup' => $output,
  143. '#suffix' => '</p>',
  144. ),
  145. 'list' => array(
  146. '#theme' => 'item_list',
  147. '#items' => $items,
  148. ),
  149. );
  150. $form['delimiter'] = array(
  151. '#type' => 'select',
  152. '#title' => t('Delimiter'),
  153. '#description' => t('The character that delimits fields in the CSV file.'),
  154. '#options' => $this->getAllDelimiterTypes(),
  155. '#default_value' => isset($source_config['delimiter']) ? $source_config['delimiter'] : ',',
  156. );
  157. $form['no_headers'] = array(
  158. '#type' => 'checkbox',
  159. '#title' => t('No Headers'),
  160. '#description' => t('Check if the imported CSV file does not start with a header row. If checked, mapping sources must be named \'0\', \'1\', \'2\' etc.'),
  161. '#default_value' => isset($source_config['no_headers']) ? $source_config['no_headers'] : 0,
  162. );
  163. $form['encoding'] = $this->configEncodingForm();
  164. if (isset($source_config['encoding'])) {
  165. $form['encoding']['#default_value'] = $source_config['encoding'];
  166. }
  167. return $form;
  168. }
  169. /**
  170. * Define default configuration.
  171. */
  172. public function configDefaults() {
  173. return array(
  174. 'delimiter' => ',',
  175. 'encoding' => 'UTF-8',
  176. 'no_headers' => 0,
  177. );
  178. }
  179. /**
  180. * Build configuration form.
  181. */
  182. public function configForm(&$form_state) {
  183. $form = array();
  184. $form['delimiter'] = array(
  185. '#type' => 'select',
  186. '#title' => t('Default delimiter'),
  187. '#description' => t('Default field delimiter.'),
  188. '#options' => $this->getAllDelimiterTypes(),
  189. '#default_value' => $this->config['delimiter'],
  190. );
  191. $form['no_headers'] = array(
  192. '#type' => 'checkbox',
  193. '#title' => t('No headers'),
  194. '#description' => t('Check if the imported CSV file does not start with a header row. If checked, mapping sources must be named \'0\', \'1\', \'2\' etc.'),
  195. '#default_value' => $this->config['no_headers'],
  196. );
  197. $form['encoding'] = $this->configEncodingForm();
  198. return $form;
  199. }
  200. /**
  201. * Builds configuration field for setting file encoding.
  202. *
  203. * If the mbstring extension is not available a markup render array
  204. * will be returned instead.
  205. *
  206. * @return array
  207. * A renderable array.
  208. */
  209. public function configEncodingForm() {
  210. if (extension_loaded('mbstring') && variable_get('feeds_use_mbstring', TRUE)) {
  211. // Get the system's list of available encodings.
  212. $options = mb_list_encodings();
  213. // Make the key/values the same in the array.
  214. $options = array_combine($options, $options);
  215. // Sort alphabetically not-case sensitive.
  216. natcasesort($options);
  217. return array(
  218. '#type' => 'select',
  219. '#title' => t('File encoding'),
  220. '#description' => t('Performs character encoding conversion from selected option to UTF-8.'),
  221. '#options' => $options,
  222. '#default_value' => $this->config['encoding'],
  223. );
  224. }
  225. else {
  226. return array(
  227. '#markup' => '<em>' . t('PHP mbstring extension must be available for character encoding conversion.') . '</em>',
  228. );
  229. }
  230. }
  231. public function getTemplate() {
  232. $mappings = feeds_importer($this->id)->processor->config['mappings'];
  233. $sources = $uniques = array();
  234. foreach ($mappings as $mapping) {
  235. if (in_array($mapping['source'], $uniques) || in_array($mapping['source'], $sources)) {
  236. // Skip columns we've already seen.
  237. continue;
  238. }
  239. if (!empty($mapping['unique'])) {
  240. $uniques[] = $mapping['source'];
  241. }
  242. else {
  243. $sources[] = $mapping['source'];
  244. }
  245. }
  246. $sep = $this->getDelimiterChar($this->config);
  247. $columns = array();
  248. foreach (array_merge($uniques, $sources) as $col) {
  249. if (strpos($col, $sep) !== FALSE) {
  250. $col = '"' . str_replace('"', '""', $col) . '"';
  251. }
  252. $columns[] = $col;
  253. }
  254. $template_file_details = $this->getTemplateFileDetails($this->config);
  255. $filename = "{$this->id}_template.{$template_file_details['extension']}";
  256. $cache_control = 'max-age=60, must-revalidate';
  257. $content_disposition = 'attachment; filename="' . $filename . '"';
  258. $content_type = "{$template_file_details['mime_type']}; charset=utf-8";
  259. drupal_add_http_header('Cache-Control', $cache_control);
  260. drupal_add_http_header('Content-Disposition', $content_disposition);
  261. drupal_add_http_header('Content-type', $content_type);
  262. print implode($sep, $columns);
  263. }
  264. /**
  265. * Gets an associative array of the delimiters supported by this parser.
  266. *
  267. * The keys represent the value that is persisted into the database, and the
  268. * value represents the text that is shown in the admins UI.
  269. *
  270. * @return array
  271. * The associative array of delimiter types to display name.
  272. */
  273. protected function getAllDelimiterTypes() {
  274. $delimiters = array(
  275. ',',
  276. ';',
  277. 'TAB',
  278. '|',
  279. '+',
  280. );
  281. return array_combine($delimiters, $delimiters);
  282. }
  283. /**
  284. * Gets the appropriate delimiter character for the delimiter in the config.
  285. *
  286. * @param array $config
  287. * The configuration for the parser.
  288. *
  289. * @return string
  290. * The delimiter character.
  291. */
  292. protected function getDelimiterChar(array $config) {
  293. $config_delimiter = $config['delimiter'];
  294. switch ($config_delimiter) {
  295. case 'TAB':
  296. $delimiter = "\t";
  297. break;
  298. default:
  299. $delimiter = $config_delimiter;
  300. break;
  301. }
  302. return $delimiter;
  303. }
  304. /**
  305. * Gets details about the template file, for the delimiter in the config.
  306. *
  307. * The resulting details indicate the file extension and mime type for the
  308. * delimiter type.
  309. *
  310. * @param array $config
  311. * The configuration for the parser.
  312. *
  313. * @return array
  314. * An array with the following information:
  315. * - 'extension': The file extension for the template ('tsv', 'csv', etc).
  316. * - 'mime-type': The mime type for the template
  317. * ('text/tab-separated-values', 'text/csv', etc).
  318. */
  319. protected function getTemplateFileDetails(array $config) {
  320. switch ($config['delimiter']) {
  321. case 'TAB':
  322. $extension = 'tsv';
  323. $mime_type = 'text/tab-separated-values';
  324. break;
  325. default:
  326. $extension = 'csv';
  327. $mime_type = 'text/csv';
  328. break;
  329. }
  330. return array(
  331. 'extension' => $extension,
  332. 'mime_type' => $mime_type,
  333. );
  334. }
  335. }