ExportCsv.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. /**
  3. * CSV export code
  4. */
  5. declare(strict_types=1);
  6. namespace PhpMyAdmin\Plugins\Export;
  7. use PhpMyAdmin\DatabaseInterface;
  8. use PhpMyAdmin\Plugins\ExportPlugin;
  9. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyMainGroup;
  10. use PhpMyAdmin\Properties\Options\Groups\OptionsPropertyRootGroup;
  11. use PhpMyAdmin\Properties\Options\Items\BoolPropertyItem;
  12. use PhpMyAdmin\Properties\Options\Items\HiddenPropertyItem;
  13. use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
  14. use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
  15. use function __;
  16. use function mb_strtolower;
  17. use function mb_substr;
  18. use function preg_replace;
  19. use function str_replace;
  20. use function stripslashes;
  21. use function trim;
  22. /**
  23. * Handles the export for the CSV format
  24. */
  25. class ExportCsv extends ExportPlugin
  26. {
  27. /**
  28. * @psalm-return non-empty-lowercase-string
  29. */
  30. public function getName(): string
  31. {
  32. return 'csv';
  33. }
  34. protected function setProperties(): ExportPluginProperties
  35. {
  36. $exportPluginProperties = new ExportPluginProperties();
  37. $exportPluginProperties->setText('CSV');
  38. $exportPluginProperties->setExtension('csv');
  39. $exportPluginProperties->setMimeType('text/comma-separated-values');
  40. $exportPluginProperties->setOptionsText(__('Options'));
  41. // create the root group that will be the options field for
  42. // $exportPluginProperties
  43. // this will be shown as "Format specific options"
  44. $exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
  45. // general options main group
  46. $generalOptions = new OptionsPropertyMainGroup('general_opts');
  47. // create leaf items and add them to the group
  48. $leaf = new TextPropertyItem(
  49. 'separator',
  50. __('Columns separated with:')
  51. );
  52. $generalOptions->addProperty($leaf);
  53. $leaf = new TextPropertyItem(
  54. 'enclosed',
  55. __('Columns enclosed with:')
  56. );
  57. $generalOptions->addProperty($leaf);
  58. $leaf = new TextPropertyItem(
  59. 'escaped',
  60. __('Columns escaped with:')
  61. );
  62. $generalOptions->addProperty($leaf);
  63. $leaf = new TextPropertyItem(
  64. 'terminated',
  65. __('Lines terminated with:')
  66. );
  67. $generalOptions->addProperty($leaf);
  68. $leaf = new TextPropertyItem(
  69. 'null',
  70. __('Replace NULL with:')
  71. );
  72. $generalOptions->addProperty($leaf);
  73. $leaf = new BoolPropertyItem(
  74. 'removeCRLF',
  75. __('Remove carriage return/line feed characters within columns')
  76. );
  77. $generalOptions->addProperty($leaf);
  78. $leaf = new BoolPropertyItem(
  79. 'columns',
  80. __('Put columns names in the first row')
  81. );
  82. $generalOptions->addProperty($leaf);
  83. $leaf = new HiddenPropertyItem('structure_or_data');
  84. $generalOptions->addProperty($leaf);
  85. // add the main group to the root group
  86. $exportSpecificOptions->addProperty($generalOptions);
  87. // set the options for the export plugin property item
  88. $exportPluginProperties->setOptions($exportSpecificOptions);
  89. return $exportPluginProperties;
  90. }
  91. /**
  92. * Outputs export header
  93. */
  94. public function exportHeader(): bool
  95. {
  96. global $what, $csv_terminated, $csv_separator, $csv_enclosed, $csv_escaped;
  97. // Here we just prepare some values for export
  98. if ($what === 'excel') {
  99. $csv_terminated = "\015\012";
  100. switch ($GLOBALS['excel_edition']) {
  101. case 'win':
  102. // as tested on Windows with Excel 2002 and Excel 2007
  103. $csv_separator = ';';
  104. break;
  105. case 'mac_excel2003':
  106. $csv_separator = ';';
  107. break;
  108. case 'mac_excel2008':
  109. $csv_separator = ',';
  110. break;
  111. }
  112. $csv_enclosed = '"';
  113. $csv_escaped = '"';
  114. if (isset($GLOBALS['excel_columns'])) {
  115. $GLOBALS['csv_columns'] = true;
  116. }
  117. } else {
  118. if (empty($csv_terminated) || mb_strtolower($csv_terminated) === 'auto') {
  119. $csv_terminated = $GLOBALS['crlf'];
  120. } else {
  121. $csv_terminated = str_replace(
  122. [
  123. '\\r',
  124. '\\n',
  125. '\\t',
  126. ],
  127. [
  128. "\015",
  129. "\012",
  130. "\011",
  131. ],
  132. $csv_terminated
  133. );
  134. }
  135. $csv_separator = str_replace('\\t', "\011", $csv_separator);
  136. }
  137. return true;
  138. }
  139. /**
  140. * Outputs export footer
  141. */
  142. public function exportFooter(): bool
  143. {
  144. return true;
  145. }
  146. /**
  147. * Outputs database header
  148. *
  149. * @param string $db Database name
  150. * @param string $dbAlias Alias of db
  151. */
  152. public function exportDBHeader($db, $dbAlias = ''): bool
  153. {
  154. return true;
  155. }
  156. /**
  157. * Outputs database footer
  158. *
  159. * @param string $db Database name
  160. */
  161. public function exportDBFooter($db): bool
  162. {
  163. return true;
  164. }
  165. /**
  166. * Outputs CREATE DATABASE statement
  167. *
  168. * @param string $db Database name
  169. * @param string $exportType 'server', 'database', 'table'
  170. * @param string $dbAlias Aliases of db
  171. */
  172. public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
  173. {
  174. return true;
  175. }
  176. /**
  177. * Outputs the content of a table in CSV format
  178. *
  179. * @param string $db database name
  180. * @param string $table table name
  181. * @param string $crlf the end of line sequence
  182. * @param string $errorUrl the url to go back in case of error
  183. * @param string $sqlQuery SQL query for obtaining data
  184. * @param array $aliases Aliases of db/table/columns
  185. */
  186. public function exportData(
  187. $db,
  188. $table,
  189. $crlf,
  190. $errorUrl,
  191. $sqlQuery,
  192. array $aliases = []
  193. ): bool {
  194. global $what, $csv_terminated, $csv_separator, $csv_enclosed, $csv_escaped, $dbi;
  195. $db_alias = $db;
  196. $table_alias = $table;
  197. $this->initAlias($aliases, $db_alias, $table_alias);
  198. // Gets the data from the database
  199. $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
  200. $fields_cnt = $result->numFields();
  201. // If required, get fields name at the first line
  202. if (isset($GLOBALS['csv_columns']) && $GLOBALS['csv_columns']) {
  203. $schema_insert = '';
  204. foreach ($result->getFieldNames() as $col_as) {
  205. if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
  206. $col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
  207. }
  208. $col_as = stripslashes($col_as);
  209. if ($csv_enclosed == '') {
  210. $schema_insert .= $col_as;
  211. } else {
  212. $schema_insert .= $csv_enclosed
  213. . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $col_as)
  214. . $csv_enclosed;
  215. }
  216. $schema_insert .= $csv_separator;
  217. }
  218. $schema_insert = trim(mb_substr($schema_insert, 0, -1));
  219. if (! $this->export->outputHandler($schema_insert . $csv_terminated)) {
  220. return false;
  221. }
  222. }
  223. // Format the data
  224. while ($row = $result->fetchRow()) {
  225. $schema_insert = '';
  226. for ($j = 0; $j < $fields_cnt; $j++) {
  227. if (! isset($row[$j])) {
  228. $schema_insert .= $GLOBALS[$what . '_null'];
  229. } elseif ($row[$j] == '0' || $row[$j] != '') {
  230. // always enclose fields
  231. if ($what === 'excel') {
  232. $row[$j] = preg_replace("/\015(\012)?/", "\012", $row[$j]);
  233. }
  234. // remove CRLF characters within field
  235. if (isset($GLOBALS[$what . '_removeCRLF']) && $GLOBALS[$what . '_removeCRLF']) {
  236. $row[$j] = str_replace(
  237. [
  238. "\r",
  239. "\n",
  240. ],
  241. '',
  242. $row[$j]
  243. );
  244. }
  245. if ($csv_enclosed == '') {
  246. $schema_insert .= $row[$j];
  247. } else {
  248. // also double the escape string if found in the data
  249. if ($csv_escaped != $csv_enclosed) {
  250. $schema_insert .= $csv_enclosed
  251. . str_replace(
  252. $csv_enclosed,
  253. $csv_escaped . $csv_enclosed,
  254. str_replace(
  255. $csv_escaped,
  256. $csv_escaped . $csv_escaped,
  257. $row[$j]
  258. )
  259. )
  260. . $csv_enclosed;
  261. } else {
  262. // avoid a problem when escape string equals enclose
  263. $schema_insert .= $csv_enclosed
  264. . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j])
  265. . $csv_enclosed;
  266. }
  267. }
  268. } else {
  269. $schema_insert .= '';
  270. }
  271. if ($j >= $fields_cnt - 1) {
  272. continue;
  273. }
  274. $schema_insert .= $csv_separator;
  275. }
  276. if (! $this->export->outputHandler($schema_insert . $csv_terminated)) {
  277. return false;
  278. }
  279. }
  280. return true;
  281. }
  282. /**
  283. * Outputs result of raw query in CSV format
  284. *
  285. * @param string $errorUrl the url to go back in case of error
  286. * @param string|null $db the database where the query is executed
  287. * @param string $sqlQuery the rawquery to output
  288. * @param string $crlf the end of line sequence
  289. */
  290. public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
  291. {
  292. global $dbi;
  293. if ($db !== null) {
  294. $dbi->selectDb($db);
  295. }
  296. return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
  297. }
  298. }