Triggers.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Functions for trigger management.
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin\Rte;
  9. use PhpMyAdmin\Message;
  10. use PhpMyAdmin\Response;
  11. use PhpMyAdmin\Rte\Export;
  12. use PhpMyAdmin\Rte\Footer;
  13. use PhpMyAdmin\Rte\General;
  14. use PhpMyAdmin\Rte\RteList;
  15. use PhpMyAdmin\Rte\Words;
  16. use PhpMyAdmin\Url;
  17. use PhpMyAdmin\Util;
  18. /**
  19. * PhpMyAdmin\Rte\Triggers class
  20. *
  21. * @package PhpMyAdmin
  22. */
  23. class Triggers
  24. {
  25. /**
  26. * Sets required globals
  27. *
  28. * @return void
  29. */
  30. public static function setGlobals()
  31. {
  32. global $action_timings, $event_manipulations;
  33. // Some definitions for triggers
  34. $action_timings = array('BEFORE',
  35. 'AFTER');
  36. $event_manipulations = array('INSERT',
  37. 'UPDATE',
  38. 'DELETE');
  39. }
  40. /**
  41. * Main function for the triggers functionality
  42. *
  43. * @return void
  44. */
  45. public static function main()
  46. {
  47. global $db, $table;
  48. self::setGlobals();
  49. /**
  50. * Process all requests
  51. */
  52. self::handleEditor();
  53. Export::triggers();
  54. /**
  55. * Display a list of available triggers
  56. */
  57. $items = $GLOBALS['dbi']->getTriggers($db, $table);
  58. echo RteList::get('trigger', $items);
  59. /**
  60. * Display a link for adding a new trigger,
  61. * if the user has the necessary privileges
  62. */
  63. echo Footer::triggers();
  64. } // end self::main()
  65. /**
  66. * Handles editor requests for adding or editing an item
  67. *
  68. * @return void
  69. */
  70. public static function handleEditor()
  71. {
  72. global $_REQUEST, $_POST, $errors, $db, $table;
  73. if (! empty($_POST['editor_process_add'])
  74. || ! empty($_POST['editor_process_edit'])
  75. ) {
  76. $sql_query = '';
  77. $item_query = self::getQueryFromRequest();
  78. if (! count($errors)) { // set by PhpMyAdmin\Rte\Routines::getQueryFromRequest()
  79. // Execute the created query
  80. if (! empty($_POST['editor_process_edit'])) {
  81. // Backup the old trigger, in case something goes wrong
  82. $trigger = self::getDataFromName($_POST['item_original_name']);
  83. $create_item = $trigger['create'];
  84. $drop_item = $trigger['drop'] . ';';
  85. $result = $GLOBALS['dbi']->tryQuery($drop_item);
  86. if (! $result) {
  87. $errors[] = sprintf(
  88. __('The following query has failed: "%s"'),
  89. htmlspecialchars($drop_item)
  90. )
  91. . '<br />'
  92. . __('MySQL said: ') . $GLOBALS['dbi']->getError();
  93. } else {
  94. $result = $GLOBALS['dbi']->tryQuery($item_query);
  95. if (! $result) {
  96. $errors[] = sprintf(
  97. __('The following query has failed: "%s"'),
  98. htmlspecialchars($item_query)
  99. )
  100. . '<br />'
  101. . __('MySQL said: ') . $GLOBALS['dbi']->getError();
  102. // We dropped the old item, but were unable to create the
  103. // new one. Try to restore the backup query.
  104. $result = $GLOBALS['dbi']->tryQuery($create_item);
  105. $errors = General::checkResult(
  106. $result,
  107. __(
  108. 'Sorry, we failed to restore the dropped trigger.'
  109. ),
  110. $create_item,
  111. $errors
  112. );
  113. } else {
  114. $message = Message::success(
  115. __('Trigger %1$s has been modified.')
  116. );
  117. $message->addParam(
  118. Util::backquote($_POST['item_name'])
  119. );
  120. $sql_query = $drop_item . $item_query;
  121. }
  122. }
  123. } else {
  124. // 'Add a new item' mode
  125. $result = $GLOBALS['dbi']->tryQuery($item_query);
  126. if (! $result) {
  127. $errors[] = sprintf(
  128. __('The following query has failed: "%s"'),
  129. htmlspecialchars($item_query)
  130. )
  131. . '<br /><br />'
  132. . __('MySQL said: ') . $GLOBALS['dbi']->getError();
  133. } else {
  134. $message = Message::success(
  135. __('Trigger %1$s has been created.')
  136. );
  137. $message->addParam(
  138. Util::backquote($_POST['item_name'])
  139. );
  140. $sql_query = $item_query;
  141. }
  142. }
  143. }
  144. if (count($errors)) {
  145. $message = Message::error(
  146. '<b>'
  147. . __(
  148. 'One or more errors have occurred while processing your request:'
  149. )
  150. . '</b>'
  151. );
  152. $message->addHtml('<ul>');
  153. foreach ($errors as $string) {
  154. $message->addHtml('<li>' . $string . '</li>');
  155. }
  156. $message->addHtml('</ul>');
  157. }
  158. $output = Util::getMessage($message, $sql_query);
  159. $response = Response::getInstance();
  160. if ($response->isAjax()) {
  161. if ($message->isSuccess()) {
  162. $items = $GLOBALS['dbi']->getTriggers($db, $table, '');
  163. $trigger = false;
  164. foreach ($items as $value) {
  165. if ($value['name'] == $_POST['item_name']) {
  166. $trigger = $value;
  167. }
  168. }
  169. $insert = false;
  170. if (empty($table)
  171. || ($trigger !== false && $table == $trigger['table'])
  172. ) {
  173. $insert = true;
  174. $response->addJSON('new_row', RteList::getTriggerRow($trigger));
  175. $response->addJSON(
  176. 'name',
  177. htmlspecialchars(
  178. mb_strtoupper(
  179. $_POST['item_name']
  180. )
  181. )
  182. );
  183. }
  184. $response->addJSON('insert', $insert);
  185. $response->addJSON('message', $output);
  186. } else {
  187. $response->addJSON('message', $message);
  188. $response->setRequestStatus(false);
  189. }
  190. exit;
  191. }
  192. }
  193. /**
  194. * Display a form used to add/edit a trigger, if necessary
  195. */
  196. if (count($errors)
  197. || (empty($_POST['editor_process_add'])
  198. && empty($_POST['editor_process_edit'])
  199. && (! empty($_REQUEST['add_item'])
  200. || ! empty($_REQUEST['edit_item']))) // FIXME: this must be simpler than that
  201. ) {
  202. // Get the data for the form (if any)
  203. if (! empty($_REQUEST['add_item'])) {
  204. $title = Words::get('add');
  205. $item = self::getDataFromRequest();
  206. $mode = 'add';
  207. } elseif (! empty($_REQUEST['edit_item'])) {
  208. $title = __("Edit trigger");
  209. if (! empty($_REQUEST['item_name'])
  210. && empty($_POST['editor_process_edit'])
  211. ) {
  212. $item = self::getDataFromName($_REQUEST['item_name']);
  213. if ($item !== false) {
  214. $item['item_original_name'] = $item['item_name'];
  215. }
  216. } else {
  217. $item = self::getDataFromRequest();
  218. }
  219. $mode = 'edit';
  220. }
  221. General::sendEditor('TRI', $mode, $item, $title, $db);
  222. }
  223. } // end self::handleEditor()
  224. /**
  225. * This function will generate the values that are required to for the editor
  226. *
  227. * @return array Data necessary to create the editor.
  228. */
  229. public static function getDataFromRequest()
  230. {
  231. $retval = array();
  232. $indices = array('item_name',
  233. 'item_table',
  234. 'item_original_name',
  235. 'item_action_timing',
  236. 'item_event_manipulation',
  237. 'item_definition',
  238. 'item_definer');
  239. foreach ($indices as $index) {
  240. $retval[$index] = isset($_POST[$index]) ? $_POST[$index] : '';
  241. }
  242. return $retval;
  243. } // end self::getDataFromRequest()
  244. /**
  245. * This function will generate the values that are required to complete
  246. * the "Edit trigger" form given the name of a trigger.
  247. *
  248. * @param string $name The name of the trigger.
  249. *
  250. * @return array Data necessary to create the editor.
  251. */
  252. public static function getDataFromName($name)
  253. {
  254. global $db, $table, $_REQUEST;
  255. $temp = array();
  256. $items = $GLOBALS['dbi']->getTriggers($db, $table, '');
  257. foreach ($items as $value) {
  258. if ($value['name'] == $name) {
  259. $temp = $value;
  260. }
  261. }
  262. if (empty($temp)) {
  263. return false;
  264. } else {
  265. $retval = array();
  266. $retval['create'] = $temp['create'];
  267. $retval['drop'] = $temp['drop'];
  268. $retval['item_name'] = $temp['name'];
  269. $retval['item_table'] = $temp['table'];
  270. $retval['item_action_timing'] = $temp['action_timing'];
  271. $retval['item_event_manipulation'] = $temp['event_manipulation'];
  272. $retval['item_definition'] = $temp['definition'];
  273. $retval['item_definer'] = $temp['definer'];
  274. return $retval;
  275. }
  276. } // end self::getDataFromName()
  277. /**
  278. * Displays a form used to add/edit a trigger
  279. *
  280. * @param string $mode If the editor will be used to edit a trigger
  281. * or add a new one: 'edit' or 'add'.
  282. * @param array $item Data for the trigger returned by self::getDataFromRequest()
  283. * or self::getDataFromName()
  284. *
  285. * @return string HTML code for the editor.
  286. */
  287. public static function getEditorForm($mode, array $item)
  288. {
  289. global $db, $table, $event_manipulations, $action_timings;
  290. $modeToUpper = mb_strtoupper($mode);
  291. $response = Response::getInstance();
  292. // Escape special characters
  293. $need_escape = array(
  294. 'item_original_name',
  295. 'item_name',
  296. 'item_definition',
  297. 'item_definer'
  298. );
  299. foreach ($need_escape as $key => $index) {
  300. $item[$index] = htmlentities($item[$index], ENT_QUOTES, 'UTF-8');
  301. }
  302. $original_data = '';
  303. if ($mode == 'edit') {
  304. $original_data = "<input name='item_original_name' "
  305. . "type='hidden' value='{$item['item_original_name']}'/>\n";
  306. }
  307. $query = "SELECT `TABLE_NAME` FROM `INFORMATION_SCHEMA`.`TABLES` ";
  308. $query .= "WHERE `TABLE_SCHEMA`='" . $GLOBALS['dbi']->escapeString($db) . "' ";
  309. $query .= "AND `TABLE_TYPE` IN ('BASE TABLE', 'SYSTEM VERSIONED')";
  310. $tables = $GLOBALS['dbi']->fetchResult($query);
  311. // Create the output
  312. $retval = "";
  313. $retval .= "<!-- START " . $modeToUpper . " TRIGGER FORM -->\n\n";
  314. $retval .= "<form class='rte_form' action='db_triggers.php' method='post'>\n";
  315. $retval .= "<input name='{$mode}_item' type='hidden' value='1' />\n";
  316. $retval .= $original_data;
  317. $retval .= Url::getHiddenInputs($db, $table) . "\n";
  318. $retval .= "<fieldset>\n";
  319. $retval .= "<legend>" . __('Details') . "</legend>\n";
  320. $retval .= "<table class='rte_table' style='width: 100%'>\n";
  321. $retval .= "<tr>\n";
  322. $retval .= " <td style='width: 20%;'>" . __('Trigger name') . "</td>\n";
  323. $retval .= " <td><input type='text' name='item_name' maxlength='64'\n";
  324. $retval .= " value='{$item['item_name']}' /></td>\n";
  325. $retval .= "</tr>\n";
  326. $retval .= "<tr>\n";
  327. $retval .= " <td>" . __('Table') . "</td>\n";
  328. $retval .= " <td>\n";
  329. $retval .= " <select name='item_table'>\n";
  330. foreach ($tables as $key => $value) {
  331. $selected = "";
  332. if ($mode == 'add' && $value == $table) {
  333. $selected = " selected='selected'";
  334. } elseif ($mode == 'edit' && $value == $item['item_table']) {
  335. $selected = " selected='selected'";
  336. }
  337. $retval .= "<option$selected>";
  338. $retval .= htmlspecialchars($value);
  339. $retval .= "</option>\n";
  340. }
  341. $retval .= " </select>\n";
  342. $retval .= " </td>\n";
  343. $retval .= "</tr>\n";
  344. $retval .= "<tr>\n";
  345. $retval .= " <td>" . _pgettext('Trigger action time', 'Time') . "</td>\n";
  346. $retval .= " <td><select name='item_timing'>\n";
  347. foreach ($action_timings as $key => $value) {
  348. $selected = "";
  349. if (! empty($item['item_action_timing'])
  350. && $item['item_action_timing'] == $value
  351. ) {
  352. $selected = " selected='selected'";
  353. }
  354. $retval .= "<option$selected>$value</option>";
  355. }
  356. $retval .= " </select></td>\n";
  357. $retval .= "</tr>\n";
  358. $retval .= "<tr>\n";
  359. $retval .= " <td>" . __('Event') . "</td>\n";
  360. $retval .= " <td><select name='item_event'>\n";
  361. foreach ($event_manipulations as $key => $value) {
  362. $selected = "";
  363. if (! empty($item['item_event_manipulation'])
  364. && $item['item_event_manipulation'] == $value
  365. ) {
  366. $selected = " selected='selected'";
  367. }
  368. $retval .= "<option$selected>$value</option>";
  369. }
  370. $retval .= " </select></td>\n";
  371. $retval .= "</tr>\n";
  372. $retval .= "<tr>\n";
  373. $retval .= " <td>" . __('Definition') . "</td>\n";
  374. $retval .= " <td><textarea name='item_definition' rows='15' cols='40'>";
  375. $retval .= $item['item_definition'];
  376. $retval .= "</textarea></td>\n";
  377. $retval .= "</tr>\n";
  378. $retval .= "<tr>\n";
  379. $retval .= " <td>" . __('Definer') . "</td>\n";
  380. $retval .= " <td><input type='text' name='item_definer'\n";
  381. $retval .= " value='{$item['item_definer']}' /></td>\n";
  382. $retval .= "</tr>\n";
  383. $retval .= "</table>\n";
  384. $retval .= "</fieldset>\n";
  385. if ($response->isAjax()) {
  386. $retval .= "<input type='hidden' name='editor_process_{$mode}'\n";
  387. $retval .= " value='true' />\n";
  388. $retval .= "<input type='hidden' name='ajax_request' value='true' />\n";
  389. } else {
  390. $retval .= "<fieldset class='tblFooters'>\n";
  391. $retval .= " <input type='submit' name='editor_process_{$mode}'\n";
  392. $retval .= " value='" . __('Go') . "' />\n";
  393. $retval .= "</fieldset>\n";
  394. }
  395. $retval .= "</form>\n\n";
  396. $retval .= "<!-- END " . $modeToUpper . " TRIGGER FORM -->\n\n";
  397. return $retval;
  398. } // end self::getEditorForm()
  399. /**
  400. * Composes the query necessary to create a trigger from an HTTP request.
  401. *
  402. * @return string The CREATE TRIGGER query.
  403. */
  404. public static function getQueryFromRequest()
  405. {
  406. global $_REQUEST, $db, $errors, $action_timings, $event_manipulations;
  407. $query = 'CREATE ';
  408. if (! empty($_POST['item_definer'])) {
  409. if (mb_strpos($_POST['item_definer'], '@') !== false
  410. ) {
  411. $arr = explode('@', $_POST['item_definer']);
  412. $query .= 'DEFINER=' . Util::backquote($arr[0]);
  413. $query .= '@' . Util::backquote($arr[1]) . ' ';
  414. } else {
  415. $errors[] = __('The definer must be in the "username@hostname" format!');
  416. }
  417. }
  418. $query .= 'TRIGGER ';
  419. if (! empty($_POST['item_name'])) {
  420. $query .= Util::backquote($_POST['item_name']) . ' ';
  421. } else {
  422. $errors[] = __('You must provide a trigger name!');
  423. }
  424. if (! empty($_POST['item_timing'])
  425. && in_array($_POST['item_timing'], $action_timings)
  426. ) {
  427. $query .= $_POST['item_timing'] . ' ';
  428. } else {
  429. $errors[] = __('You must provide a valid timing for the trigger!');
  430. }
  431. if (! empty($_POST['item_event'])
  432. && in_array($_POST['item_event'], $event_manipulations)
  433. ) {
  434. $query .= $_POST['item_event'] . ' ';
  435. } else {
  436. $errors[] = __('You must provide a valid event for the trigger!');
  437. }
  438. $query .= 'ON ';
  439. if (! empty($_POST['item_table'])
  440. && in_array($_POST['item_table'], $GLOBALS['dbi']->getTables($db))
  441. ) {
  442. $query .= Util::backquote($_POST['item_table']);
  443. } else {
  444. $errors[] = __('You must provide a valid table name!');
  445. }
  446. $query .= ' FOR EACH ROW ';
  447. if (! empty($_POST['item_definition'])) {
  448. $query .= $_POST['item_definition'];
  449. } else {
  450. $errors[] = __('You must provide a trigger definition.');
  451. }
  452. return $query;
  453. } // end self::getQueryFromRequest()
  454. }