Routines.php 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Functions for routine management.
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin\Rte;
  9. use PhpMyAdmin\Charsets;
  10. use PhpMyAdmin\Core;
  11. use PhpMyAdmin\DatabaseInterface;
  12. use PhpMyAdmin\Message;
  13. use PhpMyAdmin\Response;
  14. use PhpMyAdmin\Rte\Export;
  15. use PhpMyAdmin\Rte\Footer;
  16. use PhpMyAdmin\Rte\General;
  17. use PhpMyAdmin\Rte\RteList;
  18. use PhpMyAdmin\Rte\Words;
  19. use PhpMyAdmin\SqlParser\Parser;
  20. use PhpMyAdmin\SqlParser\Statements\CreateStatement;
  21. use PhpMyAdmin\SqlParser\Utils\Routine;
  22. use PhpMyAdmin\Url;
  23. use PhpMyAdmin\Util;
  24. /**
  25. * PhpMyAdmin\Rte\Routines class
  26. *
  27. * @package PhpMyAdmin
  28. */
  29. class Routines
  30. {
  31. /**
  32. * Sets required globals
  33. *
  34. * @return void
  35. */
  36. public static function setGlobals()
  37. {
  38. global $param_directions, $param_opts_num, $param_sqldataaccess;
  39. $param_directions = array('IN',
  40. 'OUT',
  41. 'INOUT');
  42. $param_opts_num = array('UNSIGNED',
  43. 'ZEROFILL',
  44. 'UNSIGNED ZEROFILL');
  45. $param_sqldataaccess = array('NO SQL',
  46. 'CONTAINS SQL',
  47. 'READS SQL DATA',
  48. 'MODIFIES SQL DATA');
  49. }
  50. /**
  51. * Main function for the routines functionality
  52. *
  53. * @param string $type 'FUNCTION' for functions,
  54. * 'PROCEDURE' for procedures,
  55. * null for both
  56. *
  57. * @return void
  58. */
  59. public static function main($type)
  60. {
  61. global $db;
  62. self::setGlobals();
  63. /**
  64. * Process all requests
  65. */
  66. self::handleEditor();
  67. self::handleExecute();
  68. Export::routines();
  69. /**
  70. * Display a list of available routines
  71. */
  72. if (! Core::isValid($type, array('FUNCTION','PROCEDURE'))) {
  73. $type = null;
  74. }
  75. $items = $GLOBALS['dbi']->getRoutines($db, $type);
  76. echo RteList::get('routine', $items);
  77. /**
  78. * Display the form for adding a new routine, if the user has the privileges.
  79. */
  80. echo Footer::routines();
  81. /**
  82. * Display a warning for users with PHP's old "mysql" extension.
  83. */
  84. if (! DatabaseInterface::checkDbExtension('mysqli')) {
  85. trigger_error(
  86. __(
  87. 'You are using PHP\'s deprecated \'mysql\' extension, '
  88. . 'which is not capable of handling multi queries. '
  89. . '[strong]The execution of some stored routines may fail![/strong] '
  90. . 'Please use the improved \'mysqli\' extension to '
  91. . 'avoid any problems.'
  92. ),
  93. E_USER_WARNING
  94. );
  95. }
  96. } // end self::main()
  97. /**
  98. * Handles editor requests for adding or editing an item
  99. *
  100. * @return void
  101. */
  102. public static function handleEditor()
  103. {
  104. global $_GET, $_POST, $_REQUEST, $GLOBALS, $db, $errors;
  105. $errors = self::handleRequestCreateOrEdit($errors, $db);
  106. $response = Response::getInstance();
  107. /**
  108. * Display a form used to add/edit a routine, if necessary
  109. */
  110. // FIXME: this must be simpler than that
  111. if (count($errors)
  112. || ( empty($_POST['editor_process_add'])
  113. && empty($_POST['editor_process_edit'])
  114. && (! empty($_REQUEST['add_item']) || ! empty($_REQUEST['edit_item'])
  115. || ! empty($_POST['routine_addparameter'])
  116. || ! empty($_POST['routine_removeparameter'])
  117. || ! empty($_POST['routine_changetype'])))
  118. ) {
  119. // Handle requests to add/remove parameters and changing routine type
  120. // This is necessary when JS is disabled
  121. $operation = '';
  122. if (! empty($_POST['routine_addparameter'])) {
  123. $operation = 'add';
  124. } elseif (! empty($_POST['routine_removeparameter'])) {
  125. $operation = 'remove';
  126. } elseif (! empty($_POST['routine_changetype'])) {
  127. $operation = 'change';
  128. }
  129. // Get the data for the form (if any)
  130. if (! empty($_REQUEST['add_item'])) {
  131. $title = Words::get('add');
  132. $routine = self::getDataFromRequest();
  133. $mode = 'add';
  134. } elseif (! empty($_REQUEST['edit_item'])) {
  135. $title = __("Edit routine");
  136. if (! $operation && ! empty($_GET['item_name'])
  137. && empty($_POST['editor_process_edit'])
  138. ) {
  139. $routine = self::getDataFromName(
  140. $_GET['item_name'], $_GET['item_type']
  141. );
  142. if ($routine !== false) {
  143. $routine['item_original_name'] = $routine['item_name'];
  144. $routine['item_original_type'] = $routine['item_type'];
  145. }
  146. } else {
  147. $routine = self::getDataFromRequest();
  148. }
  149. $mode = 'edit';
  150. }
  151. if ($routine !== false) {
  152. // Show form
  153. $editor = self::getEditorForm($mode, $operation, $routine);
  154. if ($response->isAjax()) {
  155. $response->addJSON('message', $editor);
  156. $response->addJSON('title', $title);
  157. $response->addJSON('param_template', self::getParameterRow());
  158. $response->addJSON('type', $routine['item_type']);
  159. } else {
  160. echo "\n\n<h2>$title</h2>\n\n$editor";
  161. }
  162. exit;
  163. } else {
  164. $message = __('Error in processing request:') . ' ';
  165. $message .= sprintf(
  166. Words::get('no_edit'),
  167. htmlspecialchars(
  168. Util::backquote($_REQUEST['item_name'])
  169. ),
  170. htmlspecialchars(Util::backquote($db))
  171. );
  172. $message = Message::error($message);
  173. if ($response->isAjax()) {
  174. $response->setRequestStatus(false);
  175. $response->addJSON('message', $message);
  176. exit;
  177. } else {
  178. $message->display();
  179. }
  180. }
  181. }
  182. }
  183. /**
  184. * Handle request to create or edit a routine
  185. *
  186. * @param array $errors Errors
  187. * @param string $db DB name
  188. *
  189. * @return array
  190. */
  191. public static function handleRequestCreateOrEdit(array $errors, $db)
  192. {
  193. if (empty($_POST['editor_process_add'])
  194. && empty($_POST['editor_process_edit'])
  195. ) {
  196. return $errors;
  197. }
  198. $sql_query = '';
  199. $routine_query = self::getQueryFromRequest();
  200. if (!count($errors)) { // set by self::getQueryFromRequest()
  201. // Execute the created query
  202. if (!empty($_POST['editor_process_edit'])) {
  203. $isProcOrFunc = in_array(
  204. $_POST['item_original_type'],
  205. array('PROCEDURE', 'FUNCTION')
  206. );
  207. if (!$isProcOrFunc) {
  208. $errors[] = sprintf(
  209. __('Invalid routine type: "%s"'),
  210. htmlspecialchars($_POST['item_original_type'])
  211. );
  212. } else {
  213. // Backup the old routine, in case something goes wrong
  214. $create_routine = $GLOBALS['dbi']->getDefinition(
  215. $db,
  216. $_POST['item_original_type'],
  217. $_POST['item_original_name']
  218. );
  219. $privilegesBackup = self::backupPrivileges();
  220. $drop_routine = "DROP {$_POST['item_original_type']} "
  221. . Util::backquote($_POST['item_original_name'])
  222. . ";\n";
  223. $result = $GLOBALS['dbi']->tryQuery($drop_routine);
  224. if (!$result) {
  225. $errors[] = sprintf(
  226. __('The following query has failed: "%s"'),
  227. htmlspecialchars($drop_routine)
  228. )
  229. . '<br />'
  230. . __('MySQL said: ') . $GLOBALS['dbi']->getError();
  231. } else {
  232. list($newErrors, $message) = self::create(
  233. $routine_query,
  234. $create_routine,
  235. $privilegesBackup
  236. );
  237. if (empty($newErrors)) {
  238. $sql_query = $drop_routine . $routine_query;
  239. } else {
  240. $errors = array_merge($errors, $newErrors);
  241. }
  242. unset($newErrors);
  243. if (null === $message) {
  244. unset($message);
  245. }
  246. }
  247. }
  248. } else {
  249. // 'Add a new routine' mode
  250. $result = $GLOBALS['dbi']->tryQuery($routine_query);
  251. if (!$result) {
  252. $errors[] = sprintf(
  253. __('The following query has failed: "%s"'),
  254. htmlspecialchars($routine_query)
  255. )
  256. . '<br /><br />'
  257. . __('MySQL said: ') . $GLOBALS['dbi']->getError();
  258. } else {
  259. $message = Message::success(
  260. __('Routine %1$s has been created.')
  261. );
  262. $message->addParam(
  263. Util::backquote($_POST['item_name'])
  264. );
  265. $sql_query = $routine_query;
  266. }
  267. }
  268. }
  269. if (count($errors)) {
  270. $message = Message::error(
  271. __(
  272. 'One or more errors have occurred while'
  273. . ' processing your request:'
  274. )
  275. );
  276. $message->addHtml('<ul>');
  277. foreach ($errors as $string) {
  278. $message->addHtml('<li>' . $string . '</li>');
  279. }
  280. $message->addHtml('</ul>');
  281. }
  282. $output = Util::getMessage($message, $sql_query);
  283. $response = Response::getInstance();
  284. if (!$response->isAjax()) {
  285. return $errors;
  286. }
  287. if (!$message->isSuccess()) {
  288. $response->setRequestStatus(false);
  289. $response->addJSON('message', $output);
  290. exit;
  291. }
  292. $routines = $GLOBALS['dbi']->getRoutines(
  293. $db,
  294. $_POST['item_type'],
  295. $_POST['item_name']
  296. );
  297. $routine = $routines[0];
  298. $response->addJSON(
  299. 'name',
  300. htmlspecialchars(
  301. mb_strtoupper($_POST['item_name'])
  302. )
  303. );
  304. $response->addJSON('new_row', RteList::getRoutineRow($routine));
  305. $response->addJSON('insert', !empty($routine));
  306. $response->addJSON('message', $output);
  307. exit;
  308. }
  309. /**
  310. * Backup the privileges
  311. *
  312. * @return array
  313. */
  314. public static function backupPrivileges()
  315. {
  316. if (! $GLOBALS['proc_priv'] || ! $GLOBALS['is_reload_priv']) {
  317. return array();
  318. }
  319. // Backup the Old Privileges before dropping
  320. // if $_POST['item_adjust_privileges'] set
  321. if (! isset($_POST['item_adjust_privileges'])
  322. || empty($_POST['item_adjust_privileges'])
  323. ) {
  324. return array();
  325. }
  326. $privilegesBackupQuery = 'SELECT * FROM ' . Util::backquote(
  327. 'mysql'
  328. )
  329. . '.' . Util::backquote('procs_priv')
  330. . ' where Routine_name = "' . $_POST['item_original_name']
  331. . '" AND Routine_type = "' . $_POST['item_original_type']
  332. . '";';
  333. $privilegesBackup = $GLOBALS['dbi']->fetchResult(
  334. $privilegesBackupQuery,
  335. 0
  336. );
  337. return $privilegesBackup;
  338. }
  339. /**
  340. * Create the routine
  341. *
  342. * @param string $routine_query Query to create routine
  343. * @param string $create_routine Query to restore routine
  344. * @param array $privilegesBackup Privileges backup
  345. *
  346. * @return array
  347. */
  348. public static function create(
  349. $routine_query,
  350. $create_routine,
  351. array $privilegesBackup
  352. ) {
  353. $result = $GLOBALS['dbi']->tryQuery($routine_query);
  354. if (!$result) {
  355. $errors = array();
  356. $errors[] = sprintf(
  357. __('The following query has failed: "%s"'),
  358. htmlspecialchars($routine_query)
  359. )
  360. . '<br />'
  361. . __('MySQL said: ') . $GLOBALS['dbi']->getError();
  362. // We dropped the old routine,
  363. // but were unable to create the new one
  364. // Try to restore the backup query
  365. $result = $GLOBALS['dbi']->tryQuery($create_routine);
  366. $errors = General::checkResult(
  367. $result,
  368. __(
  369. 'Sorry, we failed to restore'
  370. . ' the dropped routine.'
  371. ),
  372. $create_routine,
  373. $errors
  374. );
  375. return array($errors, null);
  376. }
  377. // Default value
  378. $resultAdjust = false;
  379. if ($GLOBALS['proc_priv']
  380. && $GLOBALS['is_reload_priv']
  381. ) {
  382. // Insert all the previous privileges
  383. // but with the new name and the new type
  384. foreach ($privilegesBackup as $priv) {
  385. $adjustProcPrivilege = 'INSERT INTO '
  386. . Util::backquote('mysql') . '.'
  387. . Util::backquote('procs_priv')
  388. . ' VALUES("' . $priv[0] . '", "'
  389. . $priv[1] . '", "' . $priv[2] . '", "'
  390. . $_POST['item_name'] . '", "'
  391. . $_POST['item_type'] . '", "'
  392. . $priv[5] . '", "'
  393. . $priv[6] . '", "'
  394. . $priv[7] . '");';
  395. $resultAdjust = $GLOBALS['dbi']->query(
  396. $adjustProcPrivilege
  397. );
  398. }
  399. }
  400. $message = self::flushPrivileges($resultAdjust);
  401. return array(array(), $message);
  402. }
  403. /**
  404. * Flush privileges and get message
  405. *
  406. * @param bool $flushPrivileges Flush privileges
  407. *
  408. * @return Message
  409. */
  410. public static function flushPrivileges($flushPrivileges)
  411. {
  412. if ($flushPrivileges) {
  413. // Flush the Privileges
  414. $flushPrivQuery = 'FLUSH PRIVILEGES;';
  415. $GLOBALS['dbi']->query($flushPrivQuery);
  416. $message = Message::success(
  417. __(
  418. 'Routine %1$s has been modified. Privileges have been adjusted.'
  419. )
  420. );
  421. } else {
  422. $message = Message::success(
  423. __('Routine %1$s has been modified.')
  424. );
  425. }
  426. $message->addParam(
  427. Util::backquote($_POST['item_name'])
  428. );
  429. return $message;
  430. } // end self::handleEditor()
  431. /**
  432. * This function will generate the values that are required to
  433. * complete the editor form. It is especially necessary to handle
  434. * the 'Add another parameter', 'Remove last parameter' and
  435. * 'Change routine type' functionalities when JS is disabled.
  436. *
  437. * @return array Data necessary to create the routine editor.
  438. */
  439. public static function getDataFromRequest()
  440. {
  441. global $_REQUEST, $param_directions, $param_sqldataaccess;
  442. $retval = array();
  443. $indices = array('item_name',
  444. 'item_original_name',
  445. 'item_returnlength',
  446. 'item_returnopts_num',
  447. 'item_returnopts_text',
  448. 'item_definition',
  449. 'item_comment',
  450. 'item_definer');
  451. foreach ($indices as $index) {
  452. $retval[$index] = isset($_POST[$index]) ? $_POST[$index] : '';
  453. }
  454. $retval['item_type'] = 'PROCEDURE';
  455. $retval['item_type_toggle'] = 'FUNCTION';
  456. if (isset($_REQUEST['item_type']) && $_REQUEST['item_type'] == 'FUNCTION') {
  457. $retval['item_type'] = 'FUNCTION';
  458. $retval['item_type_toggle'] = 'PROCEDURE';
  459. }
  460. $retval['item_original_type'] = 'PROCEDURE';
  461. if (isset($_POST['item_original_type'])
  462. && $_POST['item_original_type'] == 'FUNCTION'
  463. ) {
  464. $retval['item_original_type'] = 'FUNCTION';
  465. }
  466. $retval['item_num_params'] = 0;
  467. $retval['item_param_dir'] = array();
  468. $retval['item_param_name'] = array();
  469. $retval['item_param_type'] = array();
  470. $retval['item_param_length'] = array();
  471. $retval['item_param_opts_num'] = array();
  472. $retval['item_param_opts_text'] = array();
  473. if (isset($_POST['item_param_name'])
  474. && isset($_POST['item_param_type'])
  475. && isset($_POST['item_param_length'])
  476. && isset($_POST['item_param_opts_num'])
  477. && isset($_POST['item_param_opts_text'])
  478. && is_array($_POST['item_param_name'])
  479. && is_array($_POST['item_param_type'])
  480. && is_array($_POST['item_param_length'])
  481. && is_array($_POST['item_param_opts_num'])
  482. && is_array($_POST['item_param_opts_text'])
  483. ) {
  484. if ($_POST['item_type'] == 'PROCEDURE') {
  485. $retval['item_param_dir'] = $_POST['item_param_dir'];
  486. foreach ($retval['item_param_dir'] as $key => $value) {
  487. if (! in_array($value, $param_directions, true)) {
  488. $retval['item_param_dir'][$key] = '';
  489. }
  490. }
  491. }
  492. $retval['item_param_name'] = $_POST['item_param_name'];
  493. $retval['item_param_type'] = $_POST['item_param_type'];
  494. foreach ($retval['item_param_type'] as $key => $value) {
  495. if (! in_array($value, Util::getSupportedDatatypes(), true)) {
  496. $retval['item_param_type'][$key] = '';
  497. }
  498. }
  499. $retval['item_param_length'] = $_POST['item_param_length'];
  500. $retval['item_param_opts_num'] = $_POST['item_param_opts_num'];
  501. $retval['item_param_opts_text'] = $_POST['item_param_opts_text'];
  502. $retval['item_num_params'] = max(
  503. count($retval['item_param_name']),
  504. count($retval['item_param_type']),
  505. count($retval['item_param_length']),
  506. count($retval['item_param_opts_num']),
  507. count($retval['item_param_opts_text'])
  508. );
  509. }
  510. $retval['item_returntype'] = '';
  511. if (isset($_POST['item_returntype'])
  512. && in_array($_POST['item_returntype'], Util::getSupportedDatatypes())
  513. ) {
  514. $retval['item_returntype'] = $_POST['item_returntype'];
  515. }
  516. $retval['item_isdeterministic'] = '';
  517. if (isset($_POST['item_isdeterministic'])
  518. && mb_strtolower($_POST['item_isdeterministic']) == 'on'
  519. ) {
  520. $retval['item_isdeterministic'] = " checked='checked'";
  521. }
  522. $retval['item_securitytype_definer'] = '';
  523. $retval['item_securitytype_invoker'] = '';
  524. if (isset($_POST['item_securitytype'])) {
  525. if ($_POST['item_securitytype'] === 'DEFINER') {
  526. $retval['item_securitytype_definer'] = " selected='selected'";
  527. } elseif ($_POST['item_securitytype'] === 'INVOKER') {
  528. $retval['item_securitytype_invoker'] = " selected='selected'";
  529. }
  530. }
  531. $retval['item_sqldataaccess'] = '';
  532. if (isset($_POST['item_sqldataaccess'])
  533. && in_array($_POST['item_sqldataaccess'], $param_sqldataaccess, true)
  534. ) {
  535. $retval['item_sqldataaccess'] = $_POST['item_sqldataaccess'];
  536. }
  537. return $retval;
  538. } // end self::getDataFromRequest()
  539. /**
  540. * This function will generate the values that are required to complete
  541. * the "Edit routine" form given the name of a routine.
  542. *
  543. * @param string $name The name of the routine.
  544. * @param string $type Type of routine (ROUTINE|PROCEDURE)
  545. * @param bool $all Whether to return all data or just the info about parameters.
  546. *
  547. * @return array Data necessary to create the routine editor.
  548. */
  549. public static function getDataFromName($name, $type, $all = true)
  550. {
  551. global $db;
  552. $retval = array();
  553. // Build and execute the query
  554. $fields = "SPECIFIC_NAME, ROUTINE_TYPE, DTD_IDENTIFIER, "
  555. . "ROUTINE_DEFINITION, IS_DETERMINISTIC, SQL_DATA_ACCESS, "
  556. . "ROUTINE_COMMENT, SECURITY_TYPE";
  557. $where = "ROUTINE_SCHEMA " . Util::getCollateForIS() . "="
  558. . "'" . $GLOBALS['dbi']->escapeString($db) . "' "
  559. . "AND SPECIFIC_NAME='" . $GLOBALS['dbi']->escapeString($name) . "'"
  560. . "AND ROUTINE_TYPE='" . $GLOBALS['dbi']->escapeString($type) . "'";
  561. $query = "SELECT $fields FROM INFORMATION_SCHEMA.ROUTINES WHERE $where;";
  562. $routine = $GLOBALS['dbi']->fetchSingleRow($query, 'ASSOC');
  563. if (! $routine) {
  564. return false;
  565. }
  566. // Get required data
  567. $retval['item_name'] = $routine['SPECIFIC_NAME'];
  568. $retval['item_type'] = $routine['ROUTINE_TYPE'];
  569. $definition
  570. = $GLOBALS['dbi']->getDefinition(
  571. $db,
  572. $routine['ROUTINE_TYPE'],
  573. $routine['SPECIFIC_NAME']
  574. );
  575. if ($definition == null) {
  576. return false;
  577. }
  578. $parser = new Parser($definition);
  579. /**
  580. * @var CreateStatement $stmt
  581. */
  582. $stmt = $parser->statements[0];
  583. $params = Routine::getParameters($stmt);
  584. $retval['item_num_params'] = $params['num'];
  585. $retval['item_param_dir'] = $params['dir'];
  586. $retval['item_param_name'] = $params['name'];
  587. $retval['item_param_type'] = $params['type'];
  588. $retval['item_param_length'] = $params['length'];
  589. $retval['item_param_length_arr'] = $params['length_arr'];
  590. $retval['item_param_opts_num'] = $params['opts'];
  591. $retval['item_param_opts_text'] = $params['opts'];
  592. // Get extra data
  593. if (!$all) {
  594. return $retval;
  595. }
  596. if ($retval['item_type'] == 'FUNCTION') {
  597. $retval['item_type_toggle'] = 'PROCEDURE';
  598. } else {
  599. $retval['item_type_toggle'] = 'FUNCTION';
  600. }
  601. $retval['item_returntype'] = '';
  602. $retval['item_returnlength'] = '';
  603. $retval['item_returnopts_num'] = '';
  604. $retval['item_returnopts_text'] = '';
  605. if (! empty($routine['DTD_IDENTIFIER'])) {
  606. $options = array();
  607. foreach ($stmt->return->options->options as $opt) {
  608. $options[] = is_string($opt) ? $opt : $opt['value'];
  609. }
  610. $retval['item_returntype'] = $stmt->return->name;
  611. $retval['item_returnlength'] = implode(',', $stmt->return->parameters);
  612. $retval['item_returnopts_num'] = implode(' ', $options);
  613. $retval['item_returnopts_text'] = implode(' ', $options);
  614. }
  615. $retval['item_definer'] = $stmt->options->has('DEFINER');
  616. $retval['item_definition'] = $routine['ROUTINE_DEFINITION'];
  617. $retval['item_isdeterministic'] = '';
  618. if ($routine['IS_DETERMINISTIC'] == 'YES') {
  619. $retval['item_isdeterministic'] = " checked='checked'";
  620. }
  621. $retval['item_securitytype_definer'] = '';
  622. $retval['item_securitytype_invoker'] = '';
  623. if ($routine['SECURITY_TYPE'] == 'DEFINER') {
  624. $retval['item_securitytype_definer'] = " selected='selected'";
  625. } elseif ($routine['SECURITY_TYPE'] == 'INVOKER') {
  626. $retval['item_securitytype_invoker'] = " selected='selected'";
  627. }
  628. $retval['item_sqldataaccess'] = $routine['SQL_DATA_ACCESS'];
  629. $retval['item_comment'] = $routine['ROUTINE_COMMENT'];
  630. return $retval;
  631. } // self::getDataFromName()
  632. /**
  633. * Creates one row for the parameter table used in the routine editor.
  634. *
  635. * @param array $routine Data for the routine returned by
  636. * self::getDataFromRequest() or
  637. * self::getDataFromName()
  638. * @param mixed $index Either a numeric index of the row being processed
  639. * or NULL to create a template row for AJAX request
  640. * @param string $class Class used to hide the direction column, if the
  641. * row is for a stored function.
  642. *
  643. * @return string HTML code of one row of parameter table for the editor.
  644. */
  645. public static function getParameterRow(array $routine = array(), $index = null, $class = '')
  646. {
  647. $titles = Util::buildActionTitles();
  648. global $param_directions, $param_opts_num;
  649. if ($index === null) {
  650. // template row for AJAX request
  651. $i = 0;
  652. $index = '%s';
  653. $drop_class = '';
  654. $routine = array(
  655. 'item_param_dir' => array(0 => ''),
  656. 'item_param_name' => array(0 => ''),
  657. 'item_param_type' => array(0 => ''),
  658. 'item_param_length' => array(0 => ''),
  659. 'item_param_opts_num' => array(0 => ''),
  660. 'item_param_opts_text' => array(0 => '')
  661. );
  662. } elseif (! empty($routine)) {
  663. // regular row for routine editor
  664. $drop_class = ' hide';
  665. $i = $index;
  666. } else {
  667. // No input data. This shouldn't happen,
  668. // but better be safe than sorry.
  669. return '';
  670. }
  671. // Create the output
  672. $retval = "";
  673. $retval .= " <tr>\n";
  674. $retval .= " <td class='dragHandle'>"
  675. . "<span class='ui-icon ui-icon-arrowthick-2-n-s'></span>"
  676. . "</td>\n";
  677. $retval .= " <td class='routine_direction_cell$class'>\n";
  678. $retval .= " <select name='item_param_dir[$index]'>\n";
  679. foreach ($param_directions as $key => $value) {
  680. $selected = "";
  681. if (! empty($routine['item_param_dir'][$i])
  682. && $routine['item_param_dir'][$i] == $value
  683. ) {
  684. $selected = " selected='selected'";
  685. }
  686. $retval .= " <option$selected>$value</option>\n";
  687. }
  688. $retval .= " </select>\n";
  689. $retval .= " </td>\n";
  690. $retval .= " <td><input name='item_param_name[$index]' type='text'\n"
  691. . " value='{$routine['item_param_name'][$i]}' /></td>\n";
  692. $retval .= " <td><select name='item_param_type[$index]'>";
  693. $retval .= Util::getSupportedDatatypes(
  694. true, $routine['item_param_type'][$i]
  695. ) . "\n";
  696. $retval .= " </select></td>\n";
  697. $retval .= " <td>\n";
  698. $retval .= " <input id='item_param_length_$index'\n"
  699. . " name='item_param_length[$index]' type='text'\n"
  700. . " value='{$routine['item_param_length'][$i]}' />\n";
  701. $retval .= " <div class='enum_hint'>\n";
  702. $retval .= " <a href='#' class='open_enum_editor'>\n";
  703. $retval .= " "
  704. . Util::getImage('b_edit', '', array('title'=>__('ENUM/SET editor')))
  705. . "\n";
  706. $retval .= " </a>\n";
  707. $retval .= " </div>\n";
  708. $retval .= " </td>\n";
  709. $retval .= " <td class='hide no_len'>---</td>\n";
  710. $retval .= " <td class='routine_param_opts_text'>\n";
  711. $retval .= Charsets::getCharsetDropdownBox(
  712. $GLOBALS['dbi'],
  713. $GLOBALS['cfg']['Server']['DisableIS'],
  714. "item_param_opts_text[$index]",
  715. null,
  716. $routine['item_param_opts_text'][$i]
  717. );
  718. $retval .= " </td>\n";
  719. $retval .= " <td class='hide no_opts'>---</td>\n";
  720. $retval .= " <td class='routine_param_opts_num'>\n";
  721. $retval .= " <select name='item_param_opts_num[$index]'>\n";
  722. $retval .= " <option value=''></option>";
  723. foreach ($param_opts_num as $key => $value) {
  724. $selected = "";
  725. if (! empty($routine['item_param_opts_num'][$i])
  726. && $routine['item_param_opts_num'][$i] == $value
  727. ) {
  728. $selected = " selected='selected'";
  729. }
  730. $retval .= "<option$selected>$value</option>";
  731. }
  732. $retval .= "\n </select>\n";
  733. $retval .= " </td>\n";
  734. $retval .= " <td class='routine_param_remove$drop_class'>\n";
  735. $retval .= " <a href='#' class='routine_param_remove_anchor'>\n";
  736. $retval .= " {$titles['Drop']}\n";
  737. $retval .= " </a>\n";
  738. $retval .= " </td>\n";
  739. $retval .= " </tr>\n";
  740. return $retval;
  741. } // end self::getParameterRow()
  742. /**
  743. * Displays a form used to add/edit a routine
  744. *
  745. * @param string $mode If the editor will be used to edit a routine
  746. * or add a new one: 'edit' or 'add'.
  747. * @param string $operation If the editor was previously invoked with
  748. * JS turned off, this will hold the name of
  749. * the current operation
  750. * @param array $routine Data for the routine returned by
  751. * self::getDataFromRequest() or
  752. * self::getDataFromName()
  753. *
  754. * @return string HTML code for the editor.
  755. */
  756. public static function getEditorForm($mode, $operation, array $routine)
  757. {
  758. global $db, $errors, $param_sqldataaccess, $param_opts_num;
  759. $response = Response::getInstance();
  760. // Escape special characters
  761. $need_escape = array(
  762. 'item_original_name',
  763. 'item_name',
  764. 'item_returnlength',
  765. 'item_definition',
  766. 'item_definer',
  767. 'item_comment'
  768. );
  769. foreach ($need_escape as $key => $index) {
  770. $routine[$index] = htmlentities($routine[$index], ENT_QUOTES, 'UTF-8');
  771. }
  772. for ($i = 0; $i < $routine['item_num_params']; $i++) {
  773. $routine['item_param_name'][$i] = htmlentities(
  774. $routine['item_param_name'][$i],
  775. ENT_QUOTES
  776. );
  777. $routine['item_param_length'][$i] = htmlentities(
  778. $routine['item_param_length'][$i],
  779. ENT_QUOTES
  780. );
  781. }
  782. // Handle some logic first
  783. if ($operation == 'change') {
  784. if ($routine['item_type'] == 'PROCEDURE') {
  785. $routine['item_type'] = 'FUNCTION';
  786. $routine['item_type_toggle'] = 'PROCEDURE';
  787. } else {
  788. $routine['item_type'] = 'PROCEDURE';
  789. $routine['item_type_toggle'] = 'FUNCTION';
  790. }
  791. } elseif ($operation == 'add'
  792. || ($routine['item_num_params'] == 0 && $mode == 'add' && ! $errors)
  793. ) {
  794. $routine['item_param_dir'][] = '';
  795. $routine['item_param_name'][] = '';
  796. $routine['item_param_type'][] = '';
  797. $routine['item_param_length'][] = '';
  798. $routine['item_param_opts_num'][] = '';
  799. $routine['item_param_opts_text'][] = '';
  800. $routine['item_num_params']++;
  801. } elseif ($operation == 'remove') {
  802. unset($routine['item_param_dir'][$routine['item_num_params'] - 1]);
  803. unset($routine['item_param_name'][$routine['item_num_params'] - 1]);
  804. unset($routine['item_param_type'][$routine['item_num_params'] - 1]);
  805. unset($routine['item_param_length'][$routine['item_num_params'] - 1]);
  806. unset($routine['item_param_opts_num'][$routine['item_num_params'] - 1]);
  807. unset($routine['item_param_opts_text'][$routine['item_num_params'] - 1]);
  808. $routine['item_num_params']--;
  809. }
  810. $disableRemoveParam = '';
  811. if (! $routine['item_num_params']) {
  812. $disableRemoveParam = " color: gray;' disabled='disabled";
  813. }
  814. $original_routine = '';
  815. if ($mode == 'edit') {
  816. $original_routine = "<input name='item_original_name' "
  817. . "type='hidden' "
  818. . "value='{$routine['item_original_name']}'/>\n"
  819. . "<input name='item_original_type' "
  820. . "type='hidden' "
  821. . "value='{$routine['item_original_type']}'/>\n";
  822. }
  823. $isfunction_class = '';
  824. $isprocedure_class = '';
  825. $isfunction_select = '';
  826. $isprocedure_select = '';
  827. if ($routine['item_type'] == 'PROCEDURE') {
  828. $isfunction_class = ' hide';
  829. $isprocedure_select = " selected='selected'";
  830. } else {
  831. $isprocedure_class = ' hide';
  832. $isfunction_select = " selected='selected'";
  833. }
  834. // Create the output
  835. $retval = "";
  836. $retval .= "<!-- START " . mb_strtoupper($mode)
  837. . " ROUTINE FORM -->\n\n";
  838. $retval .= "<form class='rte_form' action='db_routines.php' method='post'>\n";
  839. $retval .= "<input name='{$mode}_item' type='hidden' value='1' />\n";
  840. $retval .= $original_routine;
  841. $retval .= Url::getHiddenInputs($db) . "\n";
  842. $retval .= "<fieldset>\n";
  843. $retval .= "<legend>" . __('Details') . "</legend>\n";
  844. $retval .= "<table class='rte_table' style='width: 100%'>\n";
  845. $retval .= "<tr>\n";
  846. $retval .= " <td style='width: 20%;'>" . __('Routine name') . "</td>\n";
  847. $retval .= " <td><input type='text' name='item_name' maxlength='64'\n";
  848. $retval .= " value='{$routine['item_name']}' /></td>\n";
  849. $retval .= "</tr>\n";
  850. $retval .= "<tr>\n";
  851. $retval .= " <td>" . __('Type') . "</td>\n";
  852. $retval .= " <td>\n";
  853. if ($response->isAjax()) {
  854. $retval .= " <select name='item_type'>\n"
  855. . "<option value='PROCEDURE'$isprocedure_select>PROCEDURE</option>\n"
  856. . "<option value='FUNCTION'$isfunction_select>FUNCTION</option>\n"
  857. . "</select>\n";
  858. } else {
  859. $retval .= "<input name='item_type' type='hidden'"
  860. . " value='{$routine['item_type']}' />\n"
  861. . "<div class='floatleft center' style='width: 49%;"
  862. . " font-weight: bold;'>\n"
  863. . $routine['item_type'] . "\n"
  864. . "</div>\n"
  865. . "<input style='width: 49%;' type='submit' name='routine_changetype'\n"
  866. . " value='" . sprintf(__('Change to %s'), $routine['item_type_toggle'])
  867. . "' />\n";
  868. }
  869. $retval .= " </td>\n";
  870. $retval .= "</tr>\n";
  871. $retval .= "<tr>\n";
  872. $retval .= " <td>" . __('Parameters') . "</td>\n";
  873. $retval .= " <td>\n";
  874. // parameter handling start
  875. $retval .= " <table class='routine_params_table'>\n";
  876. $retval .= " <thead>\n";
  877. $retval .= " <tr>\n";
  878. $retval .= " <td></td>\n";
  879. $retval .= " <th class='routine_direction_cell$isprocedure_class'>"
  880. . __('Direction') . "</th>\n";
  881. $retval .= " <th>" . __('Name') . "</th>\n";
  882. $retval .= " <th>" . __('Type') . "</th>\n";
  883. $retval .= " <th>" . __('Length/Values') . "</th>\n";
  884. $retval .= " <th colspan='2'>" . __('Options') . "</th>\n";
  885. $retval .= " <th class='routine_param_remove hide'>&nbsp;</th>\n";
  886. $retval .= " </tr>";
  887. $retval .= " </thead>\n";
  888. $retval .= " <tbody>\n";
  889. for ($i = 0; $i < $routine['item_num_params']; $i++) { // each parameter
  890. $retval .= self::getParameterRow($routine, $i, $isprocedure_class);
  891. }
  892. $retval .= " </tbody>\n";
  893. $retval .= " </table>";
  894. $retval .= " </td>";
  895. $retval .= "</tr>";
  896. $retval .= "<tr>";
  897. $retval .= " <td>&nbsp;</td>";
  898. $retval .= " <td>";
  899. $retval .= " <input style='width: 49%;' type='button'";
  900. $retval .= " name='routine_addparameter'";
  901. $retval .= " value='" . __('Add parameter') . "' />";
  902. $retval .= " <input style='width: 49%;" . $disableRemoveParam . "'";
  903. $retval .= " type='submit' ";
  904. $retval .= " name='routine_removeparameter'";
  905. $retval .= " value='" . __('Remove last parameter') . "' />";
  906. $retval .= " </td>";
  907. $retval .= "</tr>";
  908. // parameter handling end
  909. $retval .= "<tr class='routine_return_row" . $isfunction_class . "'>";
  910. $retval .= " <td>" . __('Return type') . "</td>";
  911. $retval .= " <td><select name='item_returntype'>";
  912. $retval .= Util::getSupportedDatatypes(true, $routine['item_returntype']);
  913. $retval .= " </select></td>";
  914. $retval .= "</tr>";
  915. $retval .= "<tr class='routine_return_row" . $isfunction_class . "'>";
  916. $retval .= " <td>" . __('Return length/values') . "</td>";
  917. $retval .= " <td><input type='text' name='item_returnlength'";
  918. $retval .= " value='" . $routine['item_returnlength'] . "' /></td>";
  919. $retval .= " <td class='hide no_len'>---</td>";
  920. $retval .= "</tr>";
  921. $retval .= "<tr class='routine_return_row" . $isfunction_class . "'>";
  922. $retval .= " <td>" . __('Return options') . "</td>";
  923. $retval .= " <td><div>";
  924. $retval .= Charsets::getCharsetDropdownBox(
  925. $GLOBALS['dbi'],
  926. $GLOBALS['cfg']['Server']['DisableIS'],
  927. "item_returnopts_text",
  928. null,
  929. $routine['item_returnopts_text']
  930. );
  931. $retval .= " </div>";
  932. $retval .= " <div><select name='item_returnopts_num'>";
  933. $retval .= " <option value=''></option>";
  934. foreach ($param_opts_num as $key => $value) {
  935. $selected = "";
  936. if (! empty($routine['item_returnopts_num'])
  937. && $routine['item_returnopts_num'] == $value
  938. ) {
  939. $selected = " selected='selected'";
  940. }
  941. $retval .= "<option" . $selected . ">" . $value . "</option>";
  942. }
  943. $retval .= " </select></div>";
  944. $retval .= " <div class='hide no_opts'>---</div>";
  945. $retval .= "</td>";
  946. $retval .= "</tr>";
  947. $retval .= "<tr>";
  948. $retval .= " <td>" . __('Definition') . "</td>";
  949. $retval .= " <td><textarea name='item_definition' rows='15' cols='40'>";
  950. $retval .= $routine['item_definition'];
  951. $retval .= "</textarea></td>";
  952. $retval .= "</tr>";
  953. $retval .= "<tr>";
  954. $retval .= " <td>" . __('Is deterministic') . "</td>";
  955. $retval .= " <td><input type='checkbox' name='item_isdeterministic'"
  956. . $routine['item_isdeterministic'] . " /></td>";
  957. $retval .= "</tr>";
  958. if (isset($_REQUEST['edit_item'])
  959. && ! empty($_REQUEST['edit_item'])
  960. ) {
  961. $retval .= "<tr>";
  962. $retval .= " <td>" . __('Adjust privileges');
  963. $retval .= Util::showDocu('faq', 'faq6-39');
  964. $retval .= "</td>";
  965. if ($GLOBALS['proc_priv']
  966. && $GLOBALS['is_reload_priv']
  967. ) {
  968. $retval .= " <td><input type='checkbox' "
  969. . "name='item_adjust_privileges' value='1' checked /></td>";
  970. } else {
  971. $retval .= " <td><input type='checkbox' "
  972. . "name='item_adjust_privileges' value='1' title='" . __(
  973. "You do not have sufficient privileges to perform this "
  974. . "operation; Please refer to the documentation for more "
  975. . "details"
  976. )
  977. . "' disabled/></td>";
  978. }
  979. $retval .= "</tr>";
  980. }
  981. $retval .= "<tr>";
  982. $retval .= " <td>" . __('Definer') . "</td>";
  983. $retval .= " <td><input type='text' name='item_definer'";
  984. $retval .= " value='" . $routine['item_definer'] . "' /></td>";
  985. $retval .= "</tr>";
  986. $retval .= "<tr>";
  987. $retval .= " <td>" . __('Security type') . "</td>";
  988. $retval .= " <td><select name='item_securitytype'>";
  989. $retval .= " <option value='DEFINER'"
  990. . $routine['item_securitytype_definer'] . ">DEFINER</option>";
  991. $retval .= " <option value='INVOKER'"
  992. . $routine['item_securitytype_invoker'] . ">INVOKER</option>";
  993. $retval .= " </select></td>";
  994. $retval .= "</tr>";
  995. $retval .= "<tr>";
  996. $retval .= " <td>" . __('SQL data access') . "</td>";
  997. $retval .= " <td><select name='item_sqldataaccess'>";
  998. foreach ($param_sqldataaccess as $key => $value) {
  999. $selected = "";
  1000. if ($routine['item_sqldataaccess'] == $value) {
  1001. $selected = " selected='selected'";
  1002. }
  1003. $retval .= " <option" . $selected . ">" . $value . "</option>";
  1004. }
  1005. $retval .= " </select></td>";
  1006. $retval .= "</tr>";
  1007. $retval .= "<tr>";
  1008. $retval .= " <td>" . __('Comment') . "</td>";
  1009. $retval .= " <td><input type='text' name='item_comment' maxlength='64'";
  1010. $retval .= " value='" . $routine['item_comment'] . "' /></td>";
  1011. $retval .= "</tr>";
  1012. $retval .= "</table>";
  1013. $retval .= "</fieldset>";
  1014. if ($response->isAjax()) {
  1015. $retval .= "<input type='hidden' name='editor_process_" . $mode . "'";
  1016. $retval .= " value='true' />";
  1017. $retval .= "<input type='hidden' name='ajax_request' value='true' />";
  1018. } else {
  1019. $retval .= "<fieldset class='tblFooters'>";
  1020. $retval .= " <input type='submit' name='editor_process_" . $mode . "'";
  1021. $retval .= " value='" . __('Go') . "' />";
  1022. $retval .= "</fieldset>";
  1023. }
  1024. $retval .= "</form>";
  1025. $retval .= "<!-- END " . mb_strtoupper($mode) . " ROUTINE FORM -->";
  1026. return $retval;
  1027. } // end self::getEditorForm()
  1028. /**
  1029. * Composes the query necessary to create a routine from an HTTP request.
  1030. *
  1031. * @return string The CREATE [ROUTINE | PROCEDURE] query.
  1032. */
  1033. public static function getQueryFromRequest()
  1034. {
  1035. global $_REQUEST, $errors, $param_sqldataaccess, $param_directions, $dbi;
  1036. $_POST['item_type'] = isset($_POST['item_type'])
  1037. ? $_POST['item_type'] : '';
  1038. $query = 'CREATE ';
  1039. if (! empty($_POST['item_definer'])) {
  1040. if (mb_strpos($_POST['item_definer'], '@') !== false) {
  1041. $arr = explode('@', $_POST['item_definer']);
  1042. $do_backquote = true;
  1043. if (substr($arr[0], 0, 1) === "`"
  1044. && substr($arr[0], -1) === "`"
  1045. ) {
  1046. $do_backquote = false;
  1047. }
  1048. $query .= 'DEFINER=' . Util::backquote($arr[0], $do_backquote);
  1049. $do_backquote = true;
  1050. if (substr($arr[1], 0, 1) === "`"
  1051. && substr($arr[1], -1) === "`"
  1052. ) {
  1053. $do_backquote = false;
  1054. }
  1055. $query .= '@' . Util::backquote($arr[1], $do_backquote) . ' ';
  1056. } else {
  1057. $errors[] = __('The definer must be in the "username@hostname" format!');
  1058. }
  1059. }
  1060. if ($_POST['item_type'] == 'FUNCTION'
  1061. || $_POST['item_type'] == 'PROCEDURE'
  1062. ) {
  1063. $query .= $_POST['item_type'] . ' ';
  1064. } else {
  1065. $errors[] = sprintf(
  1066. __('Invalid routine type: "%s"'),
  1067. htmlspecialchars($_POST['item_type'])
  1068. );
  1069. }
  1070. if (! empty($_POST['item_name'])) {
  1071. $query .= Util::backquote($_POST['item_name']);
  1072. } else {
  1073. $errors[] = __('You must provide a routine name!');
  1074. }
  1075. $params = '';
  1076. $warned_about_dir = false;
  1077. $warned_about_length = false;
  1078. if (! empty($_POST['item_param_name'])
  1079. && ! empty($_POST['item_param_type'])
  1080. && ! empty($_POST['item_param_length'])
  1081. && is_array($_POST['item_param_name'])
  1082. && is_array($_POST['item_param_type'])
  1083. && is_array($_POST['item_param_length'])
  1084. ) {
  1085. $item_param_name = $_POST['item_param_name'];
  1086. $item_param_type = $_POST['item_param_type'];
  1087. $item_param_length = $_POST['item_param_length'];
  1088. for ($i=0, $nb = count($item_param_name); $i < $nb; $i++) {
  1089. if (! empty($item_param_name[$i])
  1090. && ! empty($item_param_type[$i])
  1091. ) {
  1092. if ($_POST['item_type'] == 'PROCEDURE'
  1093. && ! empty($_POST['item_param_dir'][$i])
  1094. && in_array($_POST['item_param_dir'][$i], $param_directions)
  1095. ) {
  1096. $params .= $_POST['item_param_dir'][$i] . " "
  1097. . Util::backquote($item_param_name[$i])
  1098. . " " . $item_param_type[$i];
  1099. } elseif ($_POST['item_type'] == 'FUNCTION') {
  1100. $params .= Util::backquote($item_param_name[$i])
  1101. . " " . $item_param_type[$i];
  1102. } elseif (! $warned_about_dir) {
  1103. $warned_about_dir = true;
  1104. $errors[] = sprintf(
  1105. __('Invalid direction "%s" given for parameter.'),
  1106. htmlspecialchars($_POST['item_param_dir'][$i])
  1107. );
  1108. }
  1109. if ($item_param_length[$i] != ''
  1110. && !preg_match(
  1111. '@^(DATE|TINYBLOB|TINYTEXT|BLOB|TEXT|'
  1112. . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|'
  1113. . 'SERIAL|BOOLEAN)$@i',
  1114. $item_param_type[$i]
  1115. )
  1116. ) {
  1117. $params .= "(" . $item_param_length[$i] . ")";
  1118. } elseif ($item_param_length[$i] == ''
  1119. && preg_match(
  1120. '@^(ENUM|SET|VARCHAR|VARBINARY)$@i',
  1121. $item_param_type[$i]
  1122. )
  1123. ) {
  1124. if (! $warned_about_length) {
  1125. $warned_about_length = true;
  1126. $errors[] = __(
  1127. 'You must provide length/values for routine parameters'
  1128. . ' of type ENUM, SET, VARCHAR and VARBINARY.'
  1129. );
  1130. }
  1131. }
  1132. if (! empty($_POST['item_param_opts_text'][$i])) {
  1133. if ($dbi->types->getTypeClass($item_param_type[$i]) == 'CHAR') {
  1134. if(! in_array($item_param_type[$i], array('VARBINARY', 'BINARY'))) {
  1135. $params .= ' CHARSET '
  1136. . mb_strtolower(
  1137. $_POST['item_param_opts_text'][$i]
  1138. );
  1139. }
  1140. }
  1141. }
  1142. if (! empty($_POST['item_param_opts_num'][$i])) {
  1143. if ($dbi->types->getTypeClass($item_param_type[$i]) == 'NUMBER') {
  1144. $params .= ' '
  1145. . mb_strtoupper(
  1146. $_POST['item_param_opts_num'][$i]
  1147. );
  1148. }
  1149. }
  1150. if ($i != (count($item_param_name) - 1)) {
  1151. $params .= ", ";
  1152. }
  1153. } else {
  1154. $errors[] = __(
  1155. 'You must provide a name and a type for each routine parameter.'
  1156. );
  1157. break;
  1158. }
  1159. }
  1160. }
  1161. $query .= "(" . $params . ") ";
  1162. if ($_POST['item_type'] == 'FUNCTION') {
  1163. $item_returntype = isset($_POST['item_returntype'])
  1164. ? $_POST['item_returntype']
  1165. : null;
  1166. if (! empty($item_returntype)
  1167. && in_array(
  1168. $item_returntype, Util::getSupportedDatatypes()
  1169. )
  1170. ) {
  1171. $query .= "RETURNS " . $item_returntype;
  1172. } else {
  1173. $errors[] = __('You must provide a valid return type for the routine.');
  1174. }
  1175. if (! empty($_POST['item_returnlength'])
  1176. && !preg_match(
  1177. '@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|'
  1178. . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN)$@i',
  1179. $item_returntype
  1180. )
  1181. ) {
  1182. $query .= "(" . $_POST['item_returnlength'] . ")";
  1183. } elseif (empty($_POST['item_returnlength'])
  1184. && preg_match(
  1185. '@^(ENUM|SET|VARCHAR|VARBINARY)$@i', $item_returntype
  1186. )
  1187. ) {
  1188. if (! $warned_about_length) {
  1189. $errors[] = __(
  1190. 'You must provide length/values for routine parameters'
  1191. . ' of type ENUM, SET, VARCHAR and VARBINARY.'
  1192. );
  1193. }
  1194. }
  1195. if (! empty($_POST['item_returnopts_text'])) {
  1196. if ($dbi->types->getTypeClass($item_returntype) == 'CHAR') {
  1197. $query .= ' CHARSET '
  1198. . mb_strtolower($_POST['item_returnopts_text']);
  1199. }
  1200. }
  1201. if (! empty($_POST['item_returnopts_num'])) {
  1202. if ($dbi->types->getTypeClass($item_returntype) == 'NUMBER') {
  1203. $query .= ' '
  1204. . mb_strtoupper($_POST['item_returnopts_num']);
  1205. }
  1206. }
  1207. $query .= ' ';
  1208. }
  1209. if (! empty($_POST['item_comment'])) {
  1210. $query .= "COMMENT '" . $GLOBALS['dbi']->escapeString($_POST['item_comment'])
  1211. . "' ";
  1212. }
  1213. if (isset($_POST['item_isdeterministic'])) {
  1214. $query .= 'DETERMINISTIC ';
  1215. } else {
  1216. $query .= 'NOT DETERMINISTIC ';
  1217. }
  1218. if (! empty($_POST['item_sqldataaccess'])
  1219. && in_array($_POST['item_sqldataaccess'], $param_sqldataaccess)
  1220. ) {
  1221. $query .= $_POST['item_sqldataaccess'] . ' ';
  1222. }
  1223. if (! empty($_POST['item_securitytype'])) {
  1224. if ($_POST['item_securitytype'] == 'DEFINER'
  1225. || $_POST['item_securitytype'] == 'INVOKER'
  1226. ) {
  1227. $query .= 'SQL SECURITY ' . $_POST['item_securitytype'] . ' ';
  1228. }
  1229. }
  1230. if (! empty($_POST['item_definition'])) {
  1231. $query .= $_POST['item_definition'];
  1232. } else {
  1233. $errors[] = __('You must provide a routine definition.');
  1234. }
  1235. return $query;
  1236. } // end self::getQueryFromRequest()
  1237. /**
  1238. * Handles requests for executing a routine
  1239. *
  1240. * @return void
  1241. */
  1242. public static function handleExecute()
  1243. {
  1244. global $_GET, $_POST, $_REQUEST, $GLOBALS, $db;
  1245. $response = Response::getInstance();
  1246. /**
  1247. * Handle all user requests other than the default of listing routines
  1248. */
  1249. if (! empty($_POST['execute_routine']) && ! empty($_POST['item_name'])) {
  1250. // Build the queries
  1251. $routine = self::getDataFromName(
  1252. $_POST['item_name'], $_POST['item_type'], false
  1253. );
  1254. if ($routine === false) {
  1255. $message = __('Error in processing request:') . ' ';
  1256. $message .= sprintf(
  1257. Words::get('not_found'),
  1258. htmlspecialchars(Util::backquote($_POST['item_name'])),
  1259. htmlspecialchars(Util::backquote($db))
  1260. );
  1261. $message = Message::error($message);
  1262. if ($response->isAjax()) {
  1263. $response->setRequestStatus(false);
  1264. $response->addJSON('message', $message);
  1265. exit;
  1266. } else {
  1267. echo $message->getDisplay();
  1268. unset($_POST);
  1269. }
  1270. }
  1271. $queries = array();
  1272. $end_query = array();
  1273. $args = array();
  1274. $all_functions = $GLOBALS['dbi']->types->getAllFunctions();
  1275. for ($i = 0; $i < $routine['item_num_params']; $i++) {
  1276. if (isset($_POST['params'][$routine['item_param_name'][$i]])) {
  1277. $value = $_POST['params'][$routine['item_param_name'][$i]];
  1278. if (is_array($value)) { // is SET type
  1279. $value = implode(',', $value);
  1280. }
  1281. $value = $GLOBALS['dbi']->escapeString($value);
  1282. if (! empty($_POST['funcs'][$routine['item_param_name'][$i]])
  1283. && in_array(
  1284. $_POST['funcs'][$routine['item_param_name'][$i]],
  1285. $all_functions
  1286. )
  1287. ) {
  1288. $queries[] = "SET @p$i="
  1289. . $_POST['funcs'][$routine['item_param_name'][$i]]
  1290. . "('$value');\n";
  1291. } else {
  1292. $queries[] = "SET @p$i='$value';\n";
  1293. }
  1294. $args[] = "@p$i";
  1295. } else {
  1296. $args[] = "@p$i";
  1297. }
  1298. if ($routine['item_type'] == 'PROCEDURE') {
  1299. if ($routine['item_param_dir'][$i] == 'OUT'
  1300. || $routine['item_param_dir'][$i] == 'INOUT'
  1301. ) {
  1302. $end_query[] = "@p$i AS "
  1303. . Util::backquote($routine['item_param_name'][$i]);
  1304. }
  1305. }
  1306. }
  1307. if ($routine['item_type'] == 'PROCEDURE') {
  1308. $queries[] = "CALL " . Util::backquote($routine['item_name'])
  1309. . "(" . implode(', ', $args) . ");\n";
  1310. if (count($end_query)) {
  1311. $queries[] = "SELECT " . implode(', ', $end_query) . ";\n";
  1312. }
  1313. } else {
  1314. $queries[] = "SELECT " . Util::backquote($routine['item_name'])
  1315. . "(" . implode(', ', $args) . ") "
  1316. . "AS " . Util::backquote($routine['item_name'])
  1317. . ";\n";
  1318. }
  1319. // Get all the queries as one SQL statement
  1320. $multiple_query = implode("", $queries);
  1321. $outcome = true;
  1322. $affected = 0;
  1323. // Execute query
  1324. if (! $GLOBALS['dbi']->tryMultiQuery($multiple_query)) {
  1325. $outcome = false;
  1326. }
  1327. // Generate output
  1328. if ($outcome) {
  1329. // Pass the SQL queries through the "pretty printer"
  1330. $output = Util::formatSql(implode($queries, "\n"));
  1331. // Display results
  1332. $output .= "<fieldset><legend>";
  1333. $output .= sprintf(
  1334. __('Execution results of routine %s'),
  1335. Util::backquote(htmlspecialchars($routine['item_name']))
  1336. );
  1337. $output .= "</legend>";
  1338. $nbResultsetToDisplay = 0;
  1339. do {
  1340. $result = $GLOBALS['dbi']->storeResult();
  1341. $num_rows = $GLOBALS['dbi']->numRows($result);
  1342. if (($result !== false) && ($num_rows > 0)) {
  1343. $output .= "<table><tr>";
  1344. foreach ($GLOBALS['dbi']->getFieldsMeta($result) as $field) {
  1345. $output .= "<th>";
  1346. $output .= htmlspecialchars($field->name);
  1347. $output .= "</th>";
  1348. }
  1349. $output .= "</tr>";
  1350. while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
  1351. $output .= "<tr>" . self::browseRow($row) . "</tr>";
  1352. }
  1353. $output .= "</table>";
  1354. $nbResultsetToDisplay++;
  1355. $affected = $num_rows;
  1356. }
  1357. if (! $GLOBALS['dbi']->moreResults()) {
  1358. break;
  1359. }
  1360. $output .= "<br/>";
  1361. $GLOBALS['dbi']->freeResult($result);
  1362. } while ($outcome = $GLOBALS['dbi']->nextResult());
  1363. }
  1364. if ($outcome) {
  1365. $output .= "</fieldset>";
  1366. $message = __('Your SQL query has been executed successfully.');
  1367. if ($routine['item_type'] == 'PROCEDURE') {
  1368. $message .= '<br />';
  1369. // TODO : message need to be modified according to the
  1370. // output from the routine
  1371. $message .= sprintf(
  1372. _ngettext(
  1373. '%d row affected by the last statement inside the '
  1374. . 'procedure.',
  1375. '%d rows affected by the last statement inside the '
  1376. . 'procedure.',
  1377. $affected
  1378. ),
  1379. $affected
  1380. );
  1381. }
  1382. $message = Message::success($message);
  1383. if ($nbResultsetToDisplay == 0) {
  1384. $notice = __(
  1385. 'MySQL returned an empty result set (i.e. zero rows).'
  1386. );
  1387. $output .= Message::notice($notice)->getDisplay();
  1388. }
  1389. } else {
  1390. $output = '';
  1391. $message = Message::error(
  1392. sprintf(
  1393. __('The following query has failed: "%s"'),
  1394. htmlspecialchars($multiple_query)
  1395. )
  1396. . '<br /><br />'
  1397. . __('MySQL said: ') . $GLOBALS['dbi']->getError()
  1398. );
  1399. }
  1400. // Print/send output
  1401. if ($response->isAjax()) {
  1402. $response->setRequestStatus($message->isSuccess());
  1403. $response->addJSON('message', $message->getDisplay() . $output);
  1404. $response->addJSON('dialog', false);
  1405. exit;
  1406. } else {
  1407. echo $message->getDisplay() , $output;
  1408. if ($message->isError()) {
  1409. // At least one query has failed, so shouldn't
  1410. // execute any more queries, so we quit.
  1411. exit;
  1412. }
  1413. unset($_POST);
  1414. // Now deliberately fall through to displaying the routines list
  1415. }
  1416. return;
  1417. } elseif (! empty($_GET['execute_dialog']) && ! empty($_GET['item_name'])) {
  1418. /**
  1419. * Display the execute form for a routine.
  1420. */
  1421. $routine = self::getDataFromName(
  1422. $_GET['item_name'], $_GET['item_type'], true
  1423. );
  1424. if ($routine !== false) {
  1425. $form = self::getExecuteForm($routine);
  1426. if ($response->isAjax()) {
  1427. $title = __("Execute routine") . " " . Util::backquote(
  1428. htmlentities($_GET['item_name'], ENT_QUOTES)
  1429. );
  1430. $response->addJSON('message', $form);
  1431. $response->addJSON('title', $title);
  1432. $response->addJSON('dialog', true);
  1433. } else {
  1434. echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n";
  1435. echo $form;
  1436. }
  1437. exit;
  1438. } elseif (($response->isAjax())) {
  1439. $message = __('Error in processing request:') . ' ';
  1440. $message .= sprintf(
  1441. Words::get('not_found'),
  1442. htmlspecialchars(Util::backquote($_GET['item_name'])),
  1443. htmlspecialchars(Util::backquote($db))
  1444. );
  1445. $message = Message::error($message);
  1446. $response->setRequestStatus(false);
  1447. $response->addJSON('message', $message);
  1448. exit;
  1449. }
  1450. }
  1451. }
  1452. /**
  1453. * Browse row array
  1454. *
  1455. * @param array $row Columns
  1456. *
  1457. * @return string
  1458. */
  1459. private static function browseRow(array $row)
  1460. {
  1461. $output = null;
  1462. foreach ($row as $value) {
  1463. if ($value === null) {
  1464. $value = '<i>NULL</i>';
  1465. } else {
  1466. $value = htmlspecialchars($value);
  1467. }
  1468. $output .= "<td>" . $value . "</td>";
  1469. }
  1470. return $output;
  1471. }
  1472. /**
  1473. * Creates the HTML code that shows the routine execution dialog.
  1474. *
  1475. * @param array $routine Data for the routine returned by
  1476. * self::getDataFromName()
  1477. *
  1478. * @return string HTML code for the routine execution dialog.
  1479. */
  1480. public static function getExecuteForm(array $routine)
  1481. {
  1482. global $db, $cfg;
  1483. $response = Response::getInstance();
  1484. // Escape special characters
  1485. $routine['item_name'] = htmlentities($routine['item_name'], ENT_QUOTES);
  1486. for ($i = 0; $i < $routine['item_num_params']; $i++) {
  1487. $routine['item_param_name'][$i] = htmlentities(
  1488. $routine['item_param_name'][$i],
  1489. ENT_QUOTES
  1490. );
  1491. }
  1492. // Create the output
  1493. $retval = "";
  1494. $retval .= "<!-- START ROUTINE EXECUTE FORM -->\n\n";
  1495. $retval .= "<form action='db_routines.php' method='post'\n";
  1496. $retval .= " class='rte_form ajax' onsubmit='return false'>\n";
  1497. $retval .= "<input type='hidden' name='item_name'\n";
  1498. $retval .= " value='{$routine['item_name']}' />\n";
  1499. $retval .= "<input type='hidden' name='item_type'\n";
  1500. $retval .= " value='{$routine['item_type']}' />\n";
  1501. $retval .= Url::getHiddenInputs($db) . "\n";
  1502. $retval .= "<fieldset>\n";
  1503. if (! $response->isAjax()) {
  1504. $retval .= "<legend>{$routine['item_name']}</legend>\n";
  1505. $retval .= "<table class='rte_table'>\n";
  1506. $retval .= "<caption class='tblHeaders'>\n";
  1507. $retval .= __('Routine parameters');
  1508. $retval .= "</caption>\n";
  1509. } else {
  1510. $retval .= "<legend>" . __('Routine parameters') . "</legend>\n";
  1511. $retval .= "<table class='rte_table' style='width: 100%;'>\n";
  1512. }
  1513. $retval .= "<tr>\n";
  1514. $retval .= "<th>" . __('Name') . "</th>\n";
  1515. $retval .= "<th>" . __('Type') . "</th>\n";
  1516. if ($cfg['ShowFunctionFields']) {
  1517. $retval .= "<th>" . __('Function') . "</th>\n";
  1518. }
  1519. $retval .= "<th>" . __('Value') . "</th>\n";
  1520. $retval .= "</tr>\n";
  1521. // Get a list of data types that are not yet supported.
  1522. $no_support_types = Util::unsupportedDatatypes();
  1523. for ($i = 0; $i < $routine['item_num_params']; $i++) { // Each parameter
  1524. if ($routine['item_type'] == 'PROCEDURE'
  1525. && $routine['item_param_dir'][$i] == 'OUT'
  1526. ) {
  1527. continue;
  1528. }
  1529. $retval .= "\n<tr>\n";
  1530. $retval .= "<td>{$routine['item_param_name'][$i]}</td>\n";
  1531. $retval .= "<td>{$routine['item_param_type'][$i]}</td>\n";
  1532. if ($cfg['ShowFunctionFields']) {
  1533. $retval .= "<td>\n";
  1534. if (stristr($routine['item_param_type'][$i], 'enum')
  1535. || stristr($routine['item_param_type'][$i], 'set')
  1536. || in_array(
  1537. mb_strtolower($routine['item_param_type'][$i]),
  1538. $no_support_types
  1539. )
  1540. ) {
  1541. $retval .= "--\n";
  1542. } else {
  1543. $field = array(
  1544. 'True_Type' => mb_strtolower(
  1545. $routine['item_param_type'][$i]
  1546. ),
  1547. 'Type' => '',
  1548. 'Key' => '',
  1549. 'Field' => '',
  1550. 'Default' => '',
  1551. 'first_timestamp' => false
  1552. );
  1553. $retval .= "<select name='funcs["
  1554. . $routine['item_param_name'][$i] . "]'>";
  1555. $retval .= Util::getFunctionsForField($field, false, array());
  1556. $retval .= "</select>";
  1557. }
  1558. $retval .= "</td>\n";
  1559. }
  1560. // Append a class to date/time fields so that
  1561. // jQuery can attach a datepicker to them
  1562. $class = '';
  1563. if ($routine['item_param_type'][$i] == 'DATETIME'
  1564. || $routine['item_param_type'][$i] == 'TIMESTAMP'
  1565. ) {
  1566. $class = 'datetimefield';
  1567. } elseif ($routine['item_param_type'][$i] == 'DATE') {
  1568. $class = 'datefield';
  1569. }
  1570. $retval .= "<td class='nowrap'>\n";
  1571. if (in_array($routine['item_param_type'][$i], array('ENUM', 'SET'))) {
  1572. if ($routine['item_param_type'][$i] == 'ENUM') {
  1573. $input_type = 'radio';
  1574. } else {
  1575. $input_type = 'checkbox';
  1576. }
  1577. foreach ($routine['item_param_length_arr'][$i] as $value) {
  1578. $value = htmlentities(Util::unquote($value), ENT_QUOTES);
  1579. $retval .= "<input name='params["
  1580. . $routine['item_param_name'][$i] . "][]' "
  1581. . "value='" . $value . "' type='"
  1582. . $input_type . "' />"
  1583. . $value . "<br />\n";
  1584. }
  1585. } elseif (in_array(
  1586. mb_strtolower($routine['item_param_type'][$i]),
  1587. $no_support_types
  1588. )) {
  1589. $retval .= "\n";
  1590. } else {
  1591. $retval .= "<input class='$class' type='text' name='params["
  1592. . $routine['item_param_name'][$i] . "]' />\n";
  1593. }
  1594. $retval .= "</td>\n";
  1595. $retval .= "</tr>\n";
  1596. }
  1597. $retval .= "\n</table>\n";
  1598. if (! $response->isAjax()) {
  1599. $retval .= "</fieldset>\n\n";
  1600. $retval .= "<fieldset class='tblFooters'>\n";
  1601. $retval .= " <input type='submit' name='execute_routine'\n";
  1602. $retval .= " value='" . __('Go') . "' />\n";
  1603. $retval .= "</fieldset>\n";
  1604. } else {
  1605. $retval .= "<input type='hidden' name='execute_routine' value='true' />";
  1606. $retval .= "<input type='hidden' name='ajax_request' value='true' />";
  1607. }
  1608. $retval .= "</form>\n\n";
  1609. $retval .= "<!-- END ROUTINE EXECUTE FORM -->\n\n";
  1610. return $retval;
  1611. } // end self::getExecuteForm()
  1612. }