ExportTexytext.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. <?php
  2. /**
  3. * Export to Texy! text.
  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\RadioPropertyItem;
  13. use PhpMyAdmin\Properties\Options\Items\TextPropertyItem;
  14. use PhpMyAdmin\Properties\Plugins\ExportPluginProperties;
  15. use PhpMyAdmin\Util;
  16. use function __;
  17. use function htmlspecialchars;
  18. use function in_array;
  19. use function str_replace;
  20. use function stripslashes;
  21. /**
  22. * Handles the export for the Texy! text class
  23. */
  24. class ExportTexytext extends ExportPlugin
  25. {
  26. /**
  27. * @psalm-return non-empty-lowercase-string
  28. */
  29. public function getName(): string
  30. {
  31. return 'texytext';
  32. }
  33. protected function setProperties(): ExportPluginProperties
  34. {
  35. $exportPluginProperties = new ExportPluginProperties();
  36. $exportPluginProperties->setText('Texy! text');
  37. $exportPluginProperties->setExtension('txt');
  38. $exportPluginProperties->setMimeType('text/plain');
  39. $exportPluginProperties->setOptionsText(__('Options'));
  40. // create the root group that will be the options field for
  41. // $exportPluginProperties
  42. // this will be shown as "Format specific options"
  43. $exportSpecificOptions = new OptionsPropertyRootGroup('Format Specific Options');
  44. // what to dump (structure/data/both) main group
  45. $dumpWhat = new OptionsPropertyMainGroup(
  46. 'general_opts',
  47. __('Dump table')
  48. );
  49. // create primary items and add them to the group
  50. $leaf = new RadioPropertyItem('structure_or_data');
  51. $leaf->setValues(
  52. [
  53. 'structure' => __('structure'),
  54. 'data' => __('data'),
  55. 'structure_and_data' => __('structure and data'),
  56. ]
  57. );
  58. $dumpWhat->addProperty($leaf);
  59. // add the main group to the root group
  60. $exportSpecificOptions->addProperty($dumpWhat);
  61. // data options main group
  62. $dataOptions = new OptionsPropertyMainGroup(
  63. 'data',
  64. __('Data dump options')
  65. );
  66. $dataOptions->setForce('structure');
  67. // create primary items and add them to the group
  68. $leaf = new BoolPropertyItem(
  69. 'columns',
  70. __('Put columns names in the first row')
  71. );
  72. $dataOptions->addProperty($leaf);
  73. $leaf = new TextPropertyItem(
  74. 'null',
  75. __('Replace NULL with:')
  76. );
  77. $dataOptions->addProperty($leaf);
  78. // add the main group to the root group
  79. $exportSpecificOptions->addProperty($dataOptions);
  80. // set the options for the export plugin property item
  81. $exportPluginProperties->setOptions($exportSpecificOptions);
  82. return $exportPluginProperties;
  83. }
  84. /**
  85. * Outputs export header
  86. */
  87. public function exportHeader(): bool
  88. {
  89. return true;
  90. }
  91. /**
  92. * Outputs export footer
  93. */
  94. public function exportFooter(): bool
  95. {
  96. return true;
  97. }
  98. /**
  99. * Outputs database header
  100. *
  101. * @param string $db Database name
  102. * @param string $dbAlias Alias of db
  103. */
  104. public function exportDBHeader($db, $dbAlias = ''): bool
  105. {
  106. if (empty($dbAlias)) {
  107. $dbAlias = $db;
  108. }
  109. return $this->export->outputHandler(
  110. '===' . __('Database') . ' ' . $dbAlias . "\n\n"
  111. );
  112. }
  113. /**
  114. * Outputs database footer
  115. *
  116. * @param string $db Database name
  117. */
  118. public function exportDBFooter($db): bool
  119. {
  120. return true;
  121. }
  122. /**
  123. * Outputs CREATE DATABASE statement
  124. *
  125. * @param string $db Database name
  126. * @param string $exportType 'server', 'database', 'table'
  127. * @param string $dbAlias Aliases of db
  128. */
  129. public function exportDBCreate($db, $exportType, $dbAlias = ''): bool
  130. {
  131. return true;
  132. }
  133. /**
  134. * Outputs the content of a table in NHibernate format
  135. *
  136. * @param string $db database name
  137. * @param string $table table name
  138. * @param string $crlf the end of line sequence
  139. * @param string $errorUrl the url to go back in case of error
  140. * @param string $sqlQuery SQL query for obtaining data
  141. * @param array $aliases Aliases of db/table/columns
  142. */
  143. public function exportData(
  144. $db,
  145. $table,
  146. $crlf,
  147. $errorUrl,
  148. $sqlQuery,
  149. array $aliases = []
  150. ): bool {
  151. global $what, $dbi;
  152. $db_alias = $db;
  153. $table_alias = $table;
  154. $this->initAlias($aliases, $db_alias, $table_alias);
  155. if (
  156. ! $this->export->outputHandler(
  157. $table_alias != ''
  158. ? '== ' . __('Dumping data for table') . ' ' . $table_alias . "\n\n"
  159. : '==' . __('Dumping data for query result') . "\n\n"
  160. )
  161. ) {
  162. return false;
  163. }
  164. // Gets the data from the database
  165. $result = $dbi->query($sqlQuery, DatabaseInterface::CONNECT_USER, DatabaseInterface::QUERY_UNBUFFERED);
  166. $fields_cnt = $result->numFields();
  167. // If required, get fields name at the first line
  168. if (isset($GLOBALS[$what . '_columns'])) {
  169. $text_output = "|------\n";
  170. foreach ($result->getFieldNames() as $col_as) {
  171. if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
  172. $col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
  173. }
  174. $text_output .= '|'
  175. . htmlspecialchars(stripslashes($col_as));
  176. }
  177. $text_output .= "\n|------\n";
  178. if (! $this->export->outputHandler($text_output)) {
  179. return false;
  180. }
  181. }
  182. // Format the data
  183. while ($row = $result->fetchRow()) {
  184. $text_output = '';
  185. for ($j = 0; $j < $fields_cnt; $j++) {
  186. if (! isset($row[$j])) {
  187. $value = $GLOBALS[$what . '_null'];
  188. } elseif ($row[$j] == '0' || $row[$j] != '') {
  189. $value = $row[$j];
  190. } else {
  191. $value = ' ';
  192. }
  193. $text_output .= '|'
  194. . str_replace(
  195. '|',
  196. '&#124;',
  197. htmlspecialchars($value)
  198. );
  199. }
  200. $text_output .= "\n";
  201. if (! $this->export->outputHandler($text_output)) {
  202. return false;
  203. }
  204. }
  205. return true;
  206. }
  207. /**
  208. * Outputs result raw query in TexyText format
  209. *
  210. * @param string $errorUrl the url to go back in case of error
  211. * @param string|null $db the database where the query is executed
  212. * @param string $sqlQuery the rawquery to output
  213. * @param string $crlf the end of line sequence
  214. */
  215. public function exportRawQuery(string $errorUrl, ?string $db, string $sqlQuery, string $crlf): bool
  216. {
  217. global $dbi;
  218. if ($db !== null) {
  219. $dbi->selectDb($db);
  220. }
  221. return $this->exportData($db ?? '', '', $crlf, $errorUrl, $sqlQuery);
  222. }
  223. /**
  224. * Returns a stand-in CREATE definition to resolve view dependencies
  225. *
  226. * @param string $db the database name
  227. * @param string $view the view name
  228. * @param string $crlf the end of line sequence
  229. * @param array $aliases Aliases of db/table/columns
  230. *
  231. * @return string resulting definition
  232. */
  233. public function getTableDefStandIn($db, $view, $crlf, $aliases = [])
  234. {
  235. global $dbi;
  236. $text_output = '';
  237. /**
  238. * Get the unique keys in the table
  239. */
  240. $unique_keys = [];
  241. $keys = $dbi->getTableIndexes($db, $view);
  242. foreach ($keys as $key) {
  243. if ($key['Non_unique'] != 0) {
  244. continue;
  245. }
  246. $unique_keys[] = $key['Column_name'];
  247. }
  248. /**
  249. * Gets fields properties
  250. */
  251. $dbi->selectDb($db);
  252. /**
  253. * Displays the table structure
  254. */
  255. $text_output .= "|------\n"
  256. . '|' . __('Column')
  257. . '|' . __('Type')
  258. . '|' . __('Null')
  259. . '|' . __('Default')
  260. . "\n|------\n";
  261. $columns = $dbi->getColumns($db, $view);
  262. foreach ($columns as $column) {
  263. $col_as = $column['Field'] ?? null;
  264. if (! empty($aliases[$db]['tables'][$view]['columns'][$col_as])) {
  265. $col_as = $aliases[$db]['tables'][$view]['columns'][$col_as];
  266. }
  267. $text_output .= $this->formatOneColumnDefinition($column, $unique_keys, $col_as);
  268. $text_output .= "\n";
  269. }
  270. return $text_output;
  271. }
  272. /**
  273. * Returns $table's CREATE definition
  274. *
  275. * @param string $db the database name
  276. * @param string $table the table name
  277. * @param string $crlf the end of line sequence
  278. * @param string $error_url the url to go back in case of error
  279. * @param bool $do_relation whether to include relation comments
  280. * @param bool $do_comments whether to include the pmadb-style column
  281. * comments as comments in the structure;
  282. * this is deprecated but the parameter is
  283. * left here because /export calls
  284. * $this->exportStructure() also for other
  285. * export types which use this parameter
  286. * @param bool $do_mime whether to include mime comments
  287. * @param bool $show_dates whether to include creation/update/check dates
  288. * @param bool $add_semicolon whether to add semicolon and end-of-line
  289. * at the end
  290. * @param bool $view whether we're handling a view
  291. * @param array $aliases Aliases of db/table/columns
  292. *
  293. * @return string resulting schema
  294. */
  295. public function getTableDef(
  296. $db,
  297. $table,
  298. $crlf,
  299. $error_url,
  300. $do_relation,
  301. $do_comments,
  302. $do_mime,
  303. $show_dates = false,
  304. $add_semicolon = true,
  305. $view = false,
  306. array $aliases = []
  307. ) {
  308. global $dbi;
  309. $relationParameters = $this->relation->getRelationParameters();
  310. $text_output = '';
  311. /**
  312. * Get the unique keys in the table
  313. */
  314. $unique_keys = [];
  315. $keys = $dbi->getTableIndexes($db, $table);
  316. foreach ($keys as $key) {
  317. if ($key['Non_unique'] != 0) {
  318. continue;
  319. }
  320. $unique_keys[] = $key['Column_name'];
  321. }
  322. /**
  323. * Gets fields properties
  324. */
  325. $dbi->selectDb($db);
  326. // Check if we can use Relations
  327. [$res_rel, $have_rel] = $this->relation->getRelationsAndStatus(
  328. $do_relation && $relationParameters->relationFeature !== null,
  329. $db,
  330. $table
  331. );
  332. /**
  333. * Displays the table structure
  334. */
  335. $text_output .= "|------\n";
  336. $text_output .= '|' . __('Column');
  337. $text_output .= '|' . __('Type');
  338. $text_output .= '|' . __('Null');
  339. $text_output .= '|' . __('Default');
  340. if ($do_relation && $have_rel) {
  341. $text_output .= '|' . __('Links to');
  342. }
  343. if ($do_comments) {
  344. $text_output .= '|' . __('Comments');
  345. $comments = $this->relation->getComments($db, $table);
  346. }
  347. if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
  348. $text_output .= '|' . __('Media type');
  349. $mime_map = $this->transformations->getMime($db, $table, true);
  350. }
  351. $text_output .= "\n|------\n";
  352. $columns = $dbi->getColumns($db, $table);
  353. foreach ($columns as $column) {
  354. $col_as = $column['Field'];
  355. if (! empty($aliases[$db]['tables'][$table]['columns'][$col_as])) {
  356. $col_as = $aliases[$db]['tables'][$table]['columns'][$col_as];
  357. }
  358. $text_output .= $this->formatOneColumnDefinition($column, $unique_keys, $col_as);
  359. $field_name = $column['Field'];
  360. if ($do_relation && $have_rel) {
  361. $text_output .= '|' . htmlspecialchars(
  362. $this->getRelationString(
  363. $res_rel,
  364. $field_name,
  365. $db,
  366. $aliases
  367. )
  368. );
  369. }
  370. if ($do_comments && $relationParameters->columnCommentsFeature !== null) {
  371. $text_output .= '|'
  372. . (isset($comments[$field_name])
  373. ? htmlspecialchars($comments[$field_name])
  374. : '');
  375. }
  376. if ($do_mime && $relationParameters->browserTransformationFeature !== null) {
  377. $text_output .= '|'
  378. . (isset($mime_map[$field_name])
  379. ? htmlspecialchars(
  380. str_replace('_', '/', $mime_map[$field_name]['mimetype'])
  381. )
  382. : '');
  383. }
  384. $text_output .= "\n";
  385. }
  386. return $text_output;
  387. }
  388. /**
  389. * Outputs triggers
  390. *
  391. * @param string $db database name
  392. * @param string $table table name
  393. *
  394. * @return string Formatted triggers list
  395. */
  396. public function getTriggers($db, $table)
  397. {
  398. global $dbi;
  399. $dump = "|------\n";
  400. $dump .= '|' . __('Name');
  401. $dump .= '|' . __('Time');
  402. $dump .= '|' . __('Event');
  403. $dump .= '|' . __('Definition');
  404. $dump .= "\n|------\n";
  405. $triggers = $dbi->getTriggers($db, $table);
  406. foreach ($triggers as $trigger) {
  407. $dump .= '|' . $trigger['name'];
  408. $dump .= '|' . $trigger['action_timing'];
  409. $dump .= '|' . $trigger['event_manipulation'];
  410. $dump .= '|' .
  411. str_replace(
  412. '|',
  413. '&#124;',
  414. htmlspecialchars($trigger['definition'])
  415. );
  416. $dump .= "\n";
  417. }
  418. return $dump;
  419. }
  420. /**
  421. * Outputs table's structure
  422. *
  423. * @param string $db database name
  424. * @param string $table table name
  425. * @param string $crlf the end of line sequence
  426. * @param string $errorUrl the url to go back in case of error
  427. * @param string $exportMode 'create_table', 'triggers', 'create_view',
  428. * 'stand_in'
  429. * @param string $exportType 'server', 'database', 'table'
  430. * @param bool $do_relation whether to include relation comments
  431. * @param bool $do_comments whether to include the pmadb-style column
  432. * comments as comments in the structure;
  433. * this is deprecated but the parameter is
  434. * left here because /export calls
  435. * $this->exportStructure() also for other
  436. * export types which use this parameter
  437. * @param bool $do_mime whether to include mime comments
  438. * @param bool $dates whether to include creation/update/check dates
  439. * @param array $aliases Aliases of db/table/columns
  440. */
  441. public function exportStructure(
  442. $db,
  443. $table,
  444. $crlf,
  445. $errorUrl,
  446. $exportMode,
  447. $exportType,
  448. $do_relation = false,
  449. $do_comments = false,
  450. $do_mime = false,
  451. $dates = false,
  452. array $aliases = []
  453. ): bool {
  454. global $dbi;
  455. $db_alias = $db;
  456. $table_alias = $table;
  457. $this->initAlias($aliases, $db_alias, $table_alias);
  458. $dump = '';
  459. switch ($exportMode) {
  460. case 'create_table':
  461. $dump .= '== ' . __('Table structure for table') . ' '
  462. . $table_alias . "\n\n";
  463. $dump .= $this->getTableDef(
  464. $db,
  465. $table,
  466. $crlf,
  467. $errorUrl,
  468. $do_relation,
  469. $do_comments,
  470. $do_mime,
  471. $dates,
  472. true,
  473. false,
  474. $aliases
  475. );
  476. break;
  477. case 'triggers':
  478. $dump = '';
  479. $triggers = $dbi->getTriggers($db, $table);
  480. if ($triggers) {
  481. $dump .= '== ' . __('Triggers') . ' ' . $table_alias . "\n\n";
  482. $dump .= $this->getTriggers($db, $table);
  483. }
  484. break;
  485. case 'create_view':
  486. $dump .= '== ' . __('Structure for view') . ' ' . $table_alias . "\n\n";
  487. $dump .= $this->getTableDef(
  488. $db,
  489. $table,
  490. $crlf,
  491. $errorUrl,
  492. $do_relation,
  493. $do_comments,
  494. $do_mime,
  495. $dates,
  496. true,
  497. true,
  498. $aliases
  499. );
  500. break;
  501. case 'stand_in':
  502. $dump .= '== ' . __('Stand-in structure for view')
  503. . ' ' . $table . "\n\n";
  504. // export a stand-in definition to resolve view dependencies
  505. $dump .= $this->getTableDefStandIn($db, $table, $crlf, $aliases);
  506. }
  507. return $this->export->outputHandler($dump);
  508. }
  509. /**
  510. * Formats the definition for one column
  511. *
  512. * @param array $column info about this column
  513. * @param array $unique_keys unique keys for this table
  514. * @param string $col_alias Column Alias
  515. *
  516. * @return string Formatted column definition
  517. */
  518. public function formatOneColumnDefinition(
  519. $column,
  520. $unique_keys,
  521. $col_alias = ''
  522. ) {
  523. if (empty($col_alias)) {
  524. $col_alias = $column['Field'];
  525. }
  526. $extracted_columnspec = Util::extractColumnSpec($column['Type']);
  527. $type = $extracted_columnspec['print_type'];
  528. if (empty($type)) {
  529. $type = '&nbsp;';
  530. }
  531. if (! isset($column['Default'])) {
  532. if ($column['Null'] !== 'NO') {
  533. $column['Default'] = 'NULL';
  534. }
  535. }
  536. $fmt_pre = '';
  537. $fmt_post = '';
  538. if (in_array($column['Field'], $unique_keys)) {
  539. $fmt_pre = '**' . $fmt_pre;
  540. $fmt_post .= '**';
  541. }
  542. if ($column['Key'] === 'PRI') {
  543. $fmt_pre = '//' . $fmt_pre;
  544. $fmt_post .= '//';
  545. }
  546. $definition = '|'
  547. . $fmt_pre . htmlspecialchars($col_alias) . $fmt_post;
  548. $definition .= '|' . htmlspecialchars($type);
  549. $definition .= '|'
  550. . ($column['Null'] == '' || $column['Null'] === 'NO'
  551. ? __('No') : __('Yes'));
  552. $definition .= '|'
  553. . htmlspecialchars($column['Default'] ?? '');
  554. return $definition;
  555. }
  556. }