Routines.php 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  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. global $param_directions, $param_opts_num, $titles;
  648. if ($index === null) {
  649. // template row for AJAX request
  650. $i = 0;
  651. $index = '%s';
  652. $drop_class = '';
  653. $routine = array(
  654. 'item_param_dir' => array(0 => ''),
  655. 'item_param_name' => array(0 => ''),
  656. 'item_param_type' => array(0 => ''),
  657. 'item_param_length' => array(0 => ''),
  658. 'item_param_opts_num' => array(0 => ''),
  659. 'item_param_opts_text' => array(0 => '')
  660. );
  661. } elseif (! empty($routine)) {
  662. // regular row for routine editor
  663. $drop_class = ' hide';
  664. $i = $index;
  665. } else {
  666. // No input data. This shouldn't happen,
  667. // but better be safe than sorry.
  668. return '';
  669. }
  670. // Create the output
  671. $retval = "";
  672. $retval .= " <tr>\n";
  673. $retval .= " <td class='dragHandle'>"
  674. . "<span class='ui-icon ui-icon-arrowthick-2-n-s'></span>"
  675. . "</td>\n";
  676. $retval .= " <td class='routine_direction_cell$class'>\n";
  677. $retval .= " <select name='item_param_dir[$index]'>\n";
  678. foreach ($param_directions as $key => $value) {
  679. $selected = "";
  680. if (! empty($routine['item_param_dir'][$i])
  681. && $routine['item_param_dir'][$i] == $value
  682. ) {
  683. $selected = " selected='selected'";
  684. }
  685. $retval .= " <option$selected>$value</option>\n";
  686. }
  687. $retval .= " </select>\n";
  688. $retval .= " </td>\n";
  689. $retval .= " <td><input name='item_param_name[$index]' type='text'\n"
  690. . " value='{$routine['item_param_name'][$i]}' /></td>\n";
  691. $retval .= " <td><select name='item_param_type[$index]'>";
  692. $retval .= Util::getSupportedDatatypes(
  693. true, $routine['item_param_type'][$i]
  694. ) . "\n";
  695. $retval .= " </select></td>\n";
  696. $retval .= " <td>\n";
  697. $retval .= " <input id='item_param_length_$index'\n"
  698. . " name='item_param_length[$index]' type='text'\n"
  699. . " value='{$routine['item_param_length'][$i]}' />\n";
  700. $retval .= " <div class='enum_hint'>\n";
  701. $retval .= " <a href='#' class='open_enum_editor'>\n";
  702. $retval .= " "
  703. . Util::getImage('b_edit', '', array('title'=>__('ENUM/SET editor')))
  704. . "\n";
  705. $retval .= " </a>\n";
  706. $retval .= " </div>\n";
  707. $retval .= " </td>\n";
  708. $retval .= " <td class='hide no_len'>---</td>\n";
  709. $retval .= " <td class='routine_param_opts_text'>\n";
  710. $retval .= Charsets::getCharsetDropdownBox(
  711. $GLOBALS['dbi'],
  712. $GLOBALS['cfg']['Server']['DisableIS'],
  713. "item_param_opts_text[$index]",
  714. null,
  715. $routine['item_param_opts_text'][$i]
  716. );
  717. $retval .= " </td>\n";
  718. $retval .= " <td class='hide no_opts'>---</td>\n";
  719. $retval .= " <td class='routine_param_opts_num'>\n";
  720. $retval .= " <select name='item_param_opts_num[$index]'>\n";
  721. $retval .= " <option value=''></option>";
  722. foreach ($param_opts_num as $key => $value) {
  723. $selected = "";
  724. if (! empty($routine['item_param_opts_num'][$i])
  725. && $routine['item_param_opts_num'][$i] == $value
  726. ) {
  727. $selected = " selected='selected'";
  728. }
  729. $retval .= "<option$selected>$value</option>";
  730. }
  731. $retval .= "\n </select>\n";
  732. $retval .= " </td>\n";
  733. $retval .= " <td class='routine_param_remove$drop_class'>\n";
  734. $retval .= " <a href='#' class='routine_param_remove_anchor'>\n";
  735. $retval .= " {$titles['Drop']}\n";
  736. $retval .= " </a>\n";
  737. $retval .= " </td>\n";
  738. $retval .= " </tr>\n";
  739. return $retval;
  740. } // end self::getParameterRow()
  741. /**
  742. * Displays a form used to add/edit a routine
  743. *
  744. * @param string $mode If the editor will be used to edit a routine
  745. * or add a new one: 'edit' or 'add'.
  746. * @param string $operation If the editor was previously invoked with
  747. * JS turned off, this will hold the name of
  748. * the current operation
  749. * @param array $routine Data for the routine returned by
  750. * self::getDataFromRequest() or
  751. * self::getDataFromName()
  752. *
  753. * @return string HTML code for the editor.
  754. */
  755. public static function getEditorForm($mode, $operation, array $routine)
  756. {
  757. global $db, $errors, $param_sqldataaccess, $param_opts_num;
  758. $response = Response::getInstance();
  759. // Escape special characters
  760. $need_escape = array(
  761. 'item_original_name',
  762. 'item_name',
  763. 'item_returnlength',
  764. 'item_definition',
  765. 'item_definer',
  766. 'item_comment'
  767. );
  768. foreach ($need_escape as $key => $index) {
  769. $routine[$index] = htmlentities($routine[$index], ENT_QUOTES, 'UTF-8');
  770. }
  771. for ($i = 0; $i < $routine['item_num_params']; $i++) {
  772. $routine['item_param_name'][$i] = htmlentities(
  773. $routine['item_param_name'][$i],
  774. ENT_QUOTES
  775. );
  776. $routine['item_param_length'][$i] = htmlentities(
  777. $routine['item_param_length'][$i],
  778. ENT_QUOTES
  779. );
  780. }
  781. // Handle some logic first
  782. if ($operation == 'change') {
  783. if ($routine['item_type'] == 'PROCEDURE') {
  784. $routine['item_type'] = 'FUNCTION';
  785. $routine['item_type_toggle'] = 'PROCEDURE';
  786. } else {
  787. $routine['item_type'] = 'PROCEDURE';
  788. $routine['item_type_toggle'] = 'FUNCTION';
  789. }
  790. } elseif ($operation == 'add'
  791. || ($routine['item_num_params'] == 0 && $mode == 'add' && ! $errors)
  792. ) {
  793. $routine['item_param_dir'][] = '';
  794. $routine['item_param_name'][] = '';
  795. $routine['item_param_type'][] = '';
  796. $routine['item_param_length'][] = '';
  797. $routine['item_param_opts_num'][] = '';
  798. $routine['item_param_opts_text'][] = '';
  799. $routine['item_num_params']++;
  800. } elseif ($operation == 'remove') {
  801. unset($routine['item_param_dir'][$routine['item_num_params'] - 1]);
  802. unset($routine['item_param_name'][$routine['item_num_params'] - 1]);
  803. unset($routine['item_param_type'][$routine['item_num_params'] - 1]);
  804. unset($routine['item_param_length'][$routine['item_num_params'] - 1]);
  805. unset($routine['item_param_opts_num'][$routine['item_num_params'] - 1]);
  806. unset($routine['item_param_opts_text'][$routine['item_num_params'] - 1]);
  807. $routine['item_num_params']--;
  808. }
  809. $disableRemoveParam = '';
  810. if (! $routine['item_num_params']) {
  811. $disableRemoveParam = " color: gray;' disabled='disabled";
  812. }
  813. $original_routine = '';
  814. if ($mode == 'edit') {
  815. $original_routine = "<input name='item_original_name' "
  816. . "type='hidden' "
  817. . "value='{$routine['item_original_name']}'/>\n"
  818. . "<input name='item_original_type' "
  819. . "type='hidden' "
  820. . "value='{$routine['item_original_type']}'/>\n";
  821. }
  822. $isfunction_class = '';
  823. $isprocedure_class = '';
  824. $isfunction_select = '';
  825. $isprocedure_select = '';
  826. if ($routine['item_type'] == 'PROCEDURE') {
  827. $isfunction_class = ' hide';
  828. $isprocedure_select = " selected='selected'";
  829. } else {
  830. $isprocedure_class = ' hide';
  831. $isfunction_select = " selected='selected'";
  832. }
  833. // Create the output
  834. $retval = "";
  835. $retval .= "<!-- START " . mb_strtoupper($mode)
  836. . " ROUTINE FORM -->\n\n";
  837. $retval .= "<form class='rte_form' action='db_routines.php' method='post'>\n";
  838. $retval .= "<input name='{$mode}_item' type='hidden' value='1' />\n";
  839. $retval .= $original_routine;
  840. $retval .= Url::getHiddenInputs($db) . "\n";
  841. $retval .= "<fieldset>\n";
  842. $retval .= "<legend>" . __('Details') . "</legend>\n";
  843. $retval .= "<table class='rte_table' style='width: 100%'>\n";
  844. $retval .= "<tr>\n";
  845. $retval .= " <td style='width: 20%;'>" . __('Routine name') . "</td>\n";
  846. $retval .= " <td><input type='text' name='item_name' maxlength='64'\n";
  847. $retval .= " value='{$routine['item_name']}' /></td>\n";
  848. $retval .= "</tr>\n";
  849. $retval .= "<tr>\n";
  850. $retval .= " <td>" . __('Type') . "</td>\n";
  851. $retval .= " <td>\n";
  852. if ($response->isAjax()) {
  853. $retval .= " <select name='item_type'>\n"
  854. . "<option value='PROCEDURE'$isprocedure_select>PROCEDURE</option>\n"
  855. . "<option value='FUNCTION'$isfunction_select>FUNCTION</option>\n"
  856. . "</select>\n";
  857. } else {
  858. $retval .= "<input name='item_type' type='hidden'"
  859. . " value='{$routine['item_type']}' />\n"
  860. . "<div class='floatleft center' style='width: 49%;"
  861. . " font-weight: bold;'>\n"
  862. . $routine['item_type'] . "\n"
  863. . "</div>\n"
  864. . "<input style='width: 49%;' type='submit' name='routine_changetype'\n"
  865. . " value='" . sprintf(__('Change to %s'), $routine['item_type_toggle'])
  866. . "' />\n";
  867. }
  868. $retval .= " </td>\n";
  869. $retval .= "</tr>\n";
  870. $retval .= "<tr>\n";
  871. $retval .= " <td>" . __('Parameters') . "</td>\n";
  872. $retval .= " <td>\n";
  873. // parameter handling start
  874. $retval .= " <table class='routine_params_table'>\n";
  875. $retval .= " <thead>\n";
  876. $retval .= " <tr>\n";
  877. $retval .= " <td></td>\n";
  878. $retval .= " <th class='routine_direction_cell$isprocedure_class'>"
  879. . __('Direction') . "</th>\n";
  880. $retval .= " <th>" . __('Name') . "</th>\n";
  881. $retval .= " <th>" . __('Type') . "</th>\n";
  882. $retval .= " <th>" . __('Length/Values') . "</th>\n";
  883. $retval .= " <th colspan='2'>" . __('Options') . "</th>\n";
  884. $retval .= " <th class='routine_param_remove hide'>&nbsp;</th>\n";
  885. $retval .= " </tr>";
  886. $retval .= " </thead>\n";
  887. $retval .= " <tbody>\n";
  888. for ($i = 0; $i < $routine['item_num_params']; $i++) { // each parameter
  889. $retval .= self::getParameterRow($routine, $i, $isprocedure_class);
  890. }
  891. $retval .= " </tbody>\n";
  892. $retval .= " </table>";
  893. $retval .= " </td>";
  894. $retval .= "</tr>";
  895. $retval .= "<tr>";
  896. $retval .= " <td>&nbsp;</td>";
  897. $retval .= " <td>";
  898. $retval .= " <input style='width: 49%;' type='button'";
  899. $retval .= " name='routine_addparameter'";
  900. $retval .= " value='" . __('Add parameter') . "' />";
  901. $retval .= " <input style='width: 49%;" . $disableRemoveParam . "'";
  902. $retval .= " type='submit' ";
  903. $retval .= " name='routine_removeparameter'";
  904. $retval .= " value='" . __('Remove last parameter') . "' />";
  905. $retval .= " </td>";
  906. $retval .= "</tr>";
  907. // parameter handling end
  908. $retval .= "<tr class='routine_return_row" . $isfunction_class . "'>";
  909. $retval .= " <td>" . __('Return type') . "</td>";
  910. $retval .= " <td><select name='item_returntype'>";
  911. $retval .= Util::getSupportedDatatypes(true, $routine['item_returntype']);
  912. $retval .= " </select></td>";
  913. $retval .= "</tr>";
  914. $retval .= "<tr class='routine_return_row" . $isfunction_class . "'>";
  915. $retval .= " <td>" . __('Return length/values') . "</td>";
  916. $retval .= " <td><input type='text' name='item_returnlength'";
  917. $retval .= " value='" . $routine['item_returnlength'] . "' /></td>";
  918. $retval .= " <td class='hide no_len'>---</td>";
  919. $retval .= "</tr>";
  920. $retval .= "<tr class='routine_return_row" . $isfunction_class . "'>";
  921. $retval .= " <td>" . __('Return options') . "</td>";
  922. $retval .= " <td><div>";
  923. $retval .= Charsets::getCharsetDropdownBox(
  924. $GLOBALS['dbi'],
  925. $GLOBALS['cfg']['Server']['DisableIS'],
  926. "item_returnopts_text",
  927. null,
  928. $routine['item_returnopts_text']
  929. );
  930. $retval .= " </div>";
  931. $retval .= " <div><select name='item_returnopts_num'>";
  932. $retval .= " <option value=''></option>";
  933. foreach ($param_opts_num as $key => $value) {
  934. $selected = "";
  935. if (! empty($routine['item_returnopts_num'])
  936. && $routine['item_returnopts_num'] == $value
  937. ) {
  938. $selected = " selected='selected'";
  939. }
  940. $retval .= "<option" . $selected . ">" . $value . "</option>";
  941. }
  942. $retval .= " </select></div>";
  943. $retval .= " <div class='hide no_opts'>---</div>";
  944. $retval .= "</td>";
  945. $retval .= "</tr>";
  946. $retval .= "<tr>";
  947. $retval .= " <td>" . __('Definition') . "</td>";
  948. $retval .= " <td><textarea name='item_definition' rows='15' cols='40'>";
  949. $retval .= $routine['item_definition'];
  950. $retval .= "</textarea></td>";
  951. $retval .= "</tr>";
  952. $retval .= "<tr>";
  953. $retval .= " <td>" . __('Is deterministic') . "</td>";
  954. $retval .= " <td><input type='checkbox' name='item_isdeterministic'"
  955. . $routine['item_isdeterministic'] . " /></td>";
  956. $retval .= "</tr>";
  957. if (isset($_REQUEST['edit_item'])
  958. && ! empty($_REQUEST['edit_item'])
  959. ) {
  960. $retval .= "<tr>";
  961. $retval .= " <td>" . __('Adjust privileges');
  962. $retval .= Util::showDocu('faq', 'faq6-39');
  963. $retval .= "</td>";
  964. if ($GLOBALS['proc_priv']
  965. && $GLOBALS['is_reload_priv']
  966. ) {
  967. $retval .= " <td><input type='checkbox' "
  968. . "name='item_adjust_privileges' value='1' checked /></td>";
  969. } else {
  970. $retval .= " <td><input type='checkbox' "
  971. . "name='item_adjust_privileges' value='1' title='" . __(
  972. "You do not have sufficient privileges to perform this "
  973. . "operation; Please refer to the documentation for more "
  974. . "details"
  975. )
  976. . "' disabled/></td>";
  977. }
  978. $retval .= "</tr>";
  979. }
  980. $retval .= "<tr>";
  981. $retval .= " <td>" . __('Definer') . "</td>";
  982. $retval .= " <td><input type='text' name='item_definer'";
  983. $retval .= " value='" . $routine['item_definer'] . "' /></td>";
  984. $retval .= "</tr>";
  985. $retval .= "<tr>";
  986. $retval .= " <td>" . __('Security type') . "</td>";
  987. $retval .= " <td><select name='item_securitytype'>";
  988. $retval .= " <option value='DEFINER'"
  989. . $routine['item_securitytype_definer'] . ">DEFINER</option>";
  990. $retval .= " <option value='INVOKER'"
  991. . $routine['item_securitytype_invoker'] . ">INVOKER</option>";
  992. $retval .= " </select></td>";
  993. $retval .= "</tr>";
  994. $retval .= "<tr>";
  995. $retval .= " <td>" . __('SQL data access') . "</td>";
  996. $retval .= " <td><select name='item_sqldataaccess'>";
  997. foreach ($param_sqldataaccess as $key => $value) {
  998. $selected = "";
  999. if ($routine['item_sqldataaccess'] == $value) {
  1000. $selected = " selected='selected'";
  1001. }
  1002. $retval .= " <option" . $selected . ">" . $value . "</option>";
  1003. }
  1004. $retval .= " </select></td>";
  1005. $retval .= "</tr>";
  1006. $retval .= "<tr>";
  1007. $retval .= " <td>" . __('Comment') . "</td>";
  1008. $retval .= " <td><input type='text' name='item_comment' maxlength='64'";
  1009. $retval .= " value='" . $routine['item_comment'] . "' /></td>";
  1010. $retval .= "</tr>";
  1011. $retval .= "</table>";
  1012. $retval .= "</fieldset>";
  1013. if ($response->isAjax()) {
  1014. $retval .= "<input type='hidden' name='editor_process_" . $mode . "'";
  1015. $retval .= " value='true' />";
  1016. $retval .= "<input type='hidden' name='ajax_request' value='true' />";
  1017. } else {
  1018. $retval .= "<fieldset class='tblFooters'>";
  1019. $retval .= " <input type='submit' name='editor_process_" . $mode . "'";
  1020. $retval .= " value='" . __('Go') . "' />";
  1021. $retval .= "</fieldset>";
  1022. }
  1023. $retval .= "</form>";
  1024. $retval .= "<!-- END " . mb_strtoupper($mode) . " ROUTINE FORM -->";
  1025. return $retval;
  1026. } // end self::getEditorForm()
  1027. /**
  1028. * Composes the query necessary to create a routine from an HTTP request.
  1029. *
  1030. * @return string The CREATE [ROUTINE | PROCEDURE] query.
  1031. */
  1032. public static function getQueryFromRequest()
  1033. {
  1034. global $_REQUEST, $errors, $param_sqldataaccess, $param_directions, $dbi;
  1035. $_POST['item_type'] = isset($_POST['item_type'])
  1036. ? $_POST['item_type'] : '';
  1037. $query = 'CREATE ';
  1038. if (! empty($_POST['item_definer'])) {
  1039. if (mb_strpos($_POST['item_definer'], '@') !== false) {
  1040. $arr = explode('@', $_POST['item_definer']);
  1041. $do_backquote = true;
  1042. if (substr($arr[0], 0, 1) === "`"
  1043. && substr($arr[0], -1) === "`"
  1044. ) {
  1045. $do_backquote = false;
  1046. }
  1047. $query .= 'DEFINER=' . Util::backquote($arr[0], $do_backquote);
  1048. $do_backquote = true;
  1049. if (substr($arr[1], 0, 1) === "`"
  1050. && substr($arr[1], -1) === "`"
  1051. ) {
  1052. $do_backquote = false;
  1053. }
  1054. $query .= '@' . Util::backquote($arr[1], $do_backquote) . ' ';
  1055. } else {
  1056. $errors[] = __('The definer must be in the "username@hostname" format!');
  1057. }
  1058. }
  1059. if ($_POST['item_type'] == 'FUNCTION'
  1060. || $_POST['item_type'] == 'PROCEDURE'
  1061. ) {
  1062. $query .= $_POST['item_type'] . ' ';
  1063. } else {
  1064. $errors[] = sprintf(
  1065. __('Invalid routine type: "%s"'),
  1066. htmlspecialchars($_POST['item_type'])
  1067. );
  1068. }
  1069. if (! empty($_POST['item_name'])) {
  1070. $query .= Util::backquote($_POST['item_name']);
  1071. } else {
  1072. $errors[] = __('You must provide a routine name!');
  1073. }
  1074. $params = '';
  1075. $warned_about_dir = false;
  1076. $warned_about_length = false;
  1077. if (! empty($_POST['item_param_name'])
  1078. && ! empty($_POST['item_param_type'])
  1079. && ! empty($_POST['item_param_length'])
  1080. && is_array($_POST['item_param_name'])
  1081. && is_array($_POST['item_param_type'])
  1082. && is_array($_POST['item_param_length'])
  1083. ) {
  1084. $item_param_name = $_POST['item_param_name'];
  1085. $item_param_type = $_POST['item_param_type'];
  1086. $item_param_length = $_POST['item_param_length'];
  1087. for ($i=0, $nb = count($item_param_name); $i < $nb; $i++) {
  1088. if (! empty($item_param_name[$i])
  1089. && ! empty($item_param_type[$i])
  1090. ) {
  1091. if ($_POST['item_type'] == 'PROCEDURE'
  1092. && ! empty($_POST['item_param_dir'][$i])
  1093. && in_array($_POST['item_param_dir'][$i], $param_directions)
  1094. ) {
  1095. $params .= $_POST['item_param_dir'][$i] . " "
  1096. . Util::backquote($item_param_name[$i])
  1097. . " " . $item_param_type[$i];
  1098. } elseif ($_POST['item_type'] == 'FUNCTION') {
  1099. $params .= Util::backquote($item_param_name[$i])
  1100. . " " . $item_param_type[$i];
  1101. } elseif (! $warned_about_dir) {
  1102. $warned_about_dir = true;
  1103. $errors[] = sprintf(
  1104. __('Invalid direction "%s" given for parameter.'),
  1105. htmlspecialchars($_POST['item_param_dir'][$i])
  1106. );
  1107. }
  1108. if ($item_param_length[$i] != ''
  1109. && !preg_match(
  1110. '@^(DATE|TINYBLOB|TINYTEXT|BLOB|TEXT|'
  1111. . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|'
  1112. . 'SERIAL|BOOLEAN)$@i',
  1113. $item_param_type[$i]
  1114. )
  1115. ) {
  1116. $params .= "(" . $item_param_length[$i] . ")";
  1117. } elseif ($item_param_length[$i] == ''
  1118. && preg_match(
  1119. '@^(ENUM|SET|VARCHAR|VARBINARY)$@i',
  1120. $item_param_type[$i]
  1121. )
  1122. ) {
  1123. if (! $warned_about_length) {
  1124. $warned_about_length = true;
  1125. $errors[] = __(
  1126. 'You must provide length/values for routine parameters'
  1127. . ' of type ENUM, SET, VARCHAR and VARBINARY.'
  1128. );
  1129. }
  1130. }
  1131. if (! empty($_POST['item_param_opts_text'][$i])) {
  1132. if ($dbi->types->getTypeClass($item_param_type[$i]) == 'CHAR') {
  1133. if(! in_array($item_param_type[$i], array('VARBINARY', 'BINARY'))) {
  1134. $params .= ' CHARSET '
  1135. . mb_strtolower(
  1136. $_POST['item_param_opts_text'][$i]
  1137. );
  1138. }
  1139. }
  1140. }
  1141. if (! empty($_POST['item_param_opts_num'][$i])) {
  1142. if ($dbi->types->getTypeClass($item_param_type[$i]) == 'NUMBER') {
  1143. $params .= ' '
  1144. . mb_strtoupper(
  1145. $_POST['item_param_opts_num'][$i]
  1146. );
  1147. }
  1148. }
  1149. if ($i != (count($item_param_name) - 1)) {
  1150. $params .= ", ";
  1151. }
  1152. } else {
  1153. $errors[] = __(
  1154. 'You must provide a name and a type for each routine parameter.'
  1155. );
  1156. break;
  1157. }
  1158. }
  1159. }
  1160. $query .= "(" . $params . ") ";
  1161. if ($_POST['item_type'] == 'FUNCTION') {
  1162. $item_returntype = isset($_POST['item_returntype'])
  1163. ? $_POST['item_returntype']
  1164. : null;
  1165. if (! empty($item_returntype)
  1166. && in_array(
  1167. $item_returntype, Util::getSupportedDatatypes()
  1168. )
  1169. ) {
  1170. $query .= "RETURNS " . $item_returntype;
  1171. } else {
  1172. $errors[] = __('You must provide a valid return type for the routine.');
  1173. }
  1174. if (! empty($_POST['item_returnlength'])
  1175. && !preg_match(
  1176. '@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|'
  1177. . 'MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN)$@i',
  1178. $item_returntype
  1179. )
  1180. ) {
  1181. $query .= "(" . $_POST['item_returnlength'] . ")";
  1182. } elseif (empty($_POST['item_returnlength'])
  1183. && preg_match(
  1184. '@^(ENUM|SET|VARCHAR|VARBINARY)$@i', $item_returntype
  1185. )
  1186. ) {
  1187. if (! $warned_about_length) {
  1188. $errors[] = __(
  1189. 'You must provide length/values for routine parameters'
  1190. . ' of type ENUM, SET, VARCHAR and VARBINARY.'
  1191. );
  1192. }
  1193. }
  1194. if (! empty($_POST['item_returnopts_text'])) {
  1195. if ($dbi->types->getTypeClass($item_returntype) == 'CHAR') {
  1196. $query .= ' CHARSET '
  1197. . mb_strtolower($_POST['item_returnopts_text']);
  1198. }
  1199. }
  1200. if (! empty($_POST['item_returnopts_num'])) {
  1201. if ($dbi->types->getTypeClass($item_returntype) == 'NUMBER') {
  1202. $query .= ' '
  1203. . mb_strtoupper($_POST['item_returnopts_num']);
  1204. }
  1205. }
  1206. $query .= ' ';
  1207. }
  1208. if (! empty($_POST['item_comment'])) {
  1209. $query .= "COMMENT '" . $GLOBALS['dbi']->escapeString($_POST['item_comment'])
  1210. . "' ";
  1211. }
  1212. if (isset($_POST['item_isdeterministic'])) {
  1213. $query .= 'DETERMINISTIC ';
  1214. } else {
  1215. $query .= 'NOT DETERMINISTIC ';
  1216. }
  1217. if (! empty($_POST['item_sqldataaccess'])
  1218. && in_array($_POST['item_sqldataaccess'], $param_sqldataaccess)
  1219. ) {
  1220. $query .= $_POST['item_sqldataaccess'] . ' ';
  1221. }
  1222. if (! empty($_POST['item_securitytype'])) {
  1223. if ($_POST['item_securitytype'] == 'DEFINER'
  1224. || $_POST['item_securitytype'] == 'INVOKER'
  1225. ) {
  1226. $query .= 'SQL SECURITY ' . $_POST['item_securitytype'] . ' ';
  1227. }
  1228. }
  1229. if (! empty($_POST['item_definition'])) {
  1230. $query .= $_POST['item_definition'];
  1231. } else {
  1232. $errors[] = __('You must provide a routine definition.');
  1233. }
  1234. return $query;
  1235. } // end self::getQueryFromRequest()
  1236. /**
  1237. * Handles requests for executing a routine
  1238. *
  1239. * @return void
  1240. */
  1241. public static function handleExecute()
  1242. {
  1243. global $_GET, $_POST, $_REQUEST, $GLOBALS, $db;
  1244. $response = Response::getInstance();
  1245. /**
  1246. * Handle all user requests other than the default of listing routines
  1247. */
  1248. if (! empty($_POST['execute_routine']) && ! empty($_POST['item_name'])) {
  1249. // Build the queries
  1250. $routine = self::getDataFromName(
  1251. $_POST['item_name'], $_POST['item_type'], false
  1252. );
  1253. if ($routine === false) {
  1254. $message = __('Error in processing request:') . ' ';
  1255. $message .= sprintf(
  1256. Words::get('not_found'),
  1257. htmlspecialchars(Util::backquote($_POST['item_name'])),
  1258. htmlspecialchars(Util::backquote($db))
  1259. );
  1260. $message = Message::error($message);
  1261. if ($response->isAjax()) {
  1262. $response->setRequestStatus(false);
  1263. $response->addJSON('message', $message);
  1264. exit;
  1265. } else {
  1266. echo $message->getDisplay();
  1267. unset($_POST);
  1268. }
  1269. }
  1270. $queries = array();
  1271. $end_query = array();
  1272. $args = array();
  1273. $all_functions = $GLOBALS['dbi']->types->getAllFunctions();
  1274. for ($i = 0; $i < $routine['item_num_params']; $i++) {
  1275. if (isset($_POST['params'][$routine['item_param_name'][$i]])) {
  1276. $value = $_POST['params'][$routine['item_param_name'][$i]];
  1277. if (is_array($value)) { // is SET type
  1278. $value = implode(',', $value);
  1279. }
  1280. $value = $GLOBALS['dbi']->escapeString($value);
  1281. if (! empty($_POST['funcs'][$routine['item_param_name'][$i]])
  1282. && in_array(
  1283. $_POST['funcs'][$routine['item_param_name'][$i]],
  1284. $all_functions
  1285. )
  1286. ) {
  1287. $queries[] = "SET @p$i="
  1288. . $_POST['funcs'][$routine['item_param_name'][$i]]
  1289. . "('$value');\n";
  1290. } else {
  1291. $queries[] = "SET @p$i='$value';\n";
  1292. }
  1293. $args[] = "@p$i";
  1294. } else {
  1295. $args[] = "@p$i";
  1296. }
  1297. if ($routine['item_type'] == 'PROCEDURE') {
  1298. if ($routine['item_param_dir'][$i] == 'OUT'
  1299. || $routine['item_param_dir'][$i] == 'INOUT'
  1300. ) {
  1301. $end_query[] = "@p$i AS "
  1302. . Util::backquote($routine['item_param_name'][$i]);
  1303. }
  1304. }
  1305. }
  1306. if ($routine['item_type'] == 'PROCEDURE') {
  1307. $queries[] = "CALL " . Util::backquote($routine['item_name'])
  1308. . "(" . implode(', ', $args) . ");\n";
  1309. if (count($end_query)) {
  1310. $queries[] = "SELECT " . implode(', ', $end_query) . ";\n";
  1311. }
  1312. } else {
  1313. $queries[] = "SELECT " . Util::backquote($routine['item_name'])
  1314. . "(" . implode(', ', $args) . ") "
  1315. . "AS " . Util::backquote($routine['item_name'])
  1316. . ";\n";
  1317. }
  1318. // Get all the queries as one SQL statement
  1319. $multiple_query = implode("", $queries);
  1320. $outcome = true;
  1321. $affected = 0;
  1322. // Execute query
  1323. if (! $GLOBALS['dbi']->tryMultiQuery($multiple_query)) {
  1324. $outcome = false;
  1325. }
  1326. // Generate output
  1327. if ($outcome) {
  1328. // Pass the SQL queries through the "pretty printer"
  1329. $output = Util::formatSql(implode($queries, "\n"));
  1330. // Display results
  1331. $output .= "<fieldset><legend>";
  1332. $output .= sprintf(
  1333. __('Execution results of routine %s'),
  1334. Util::backquote(htmlspecialchars($routine['item_name']))
  1335. );
  1336. $output .= "</legend>";
  1337. $nbResultsetToDisplay = 0;
  1338. do {
  1339. $result = $GLOBALS['dbi']->storeResult();
  1340. $num_rows = $GLOBALS['dbi']->numRows($result);
  1341. if (($result !== false) && ($num_rows > 0)) {
  1342. $output .= "<table><tr>";
  1343. foreach ($GLOBALS['dbi']->getFieldsMeta($result) as $field) {
  1344. $output .= "<th>";
  1345. $output .= htmlspecialchars($field->name);
  1346. $output .= "</th>";
  1347. }
  1348. $output .= "</tr>";
  1349. while ($row = $GLOBALS['dbi']->fetchAssoc($result)) {
  1350. $output .= "<tr>" . self::browseRow($row) . "</tr>";
  1351. }
  1352. $output .= "</table>";
  1353. $nbResultsetToDisplay++;
  1354. $affected = $num_rows;
  1355. }
  1356. if (! $GLOBALS['dbi']->moreResults()) {
  1357. break;
  1358. }
  1359. $output .= "<br/>";
  1360. $GLOBALS['dbi']->freeResult($result);
  1361. } while ($outcome = $GLOBALS['dbi']->nextResult());
  1362. }
  1363. if ($outcome) {
  1364. $output .= "</fieldset>";
  1365. $message = __('Your SQL query has been executed successfully.');
  1366. if ($routine['item_type'] == 'PROCEDURE') {
  1367. $message .= '<br />';
  1368. // TODO : message need to be modified according to the
  1369. // output from the routine
  1370. $message .= sprintf(
  1371. _ngettext(
  1372. '%d row affected by the last statement inside the '
  1373. . 'procedure.',
  1374. '%d rows affected by the last statement inside the '
  1375. . 'procedure.',
  1376. $affected
  1377. ),
  1378. $affected
  1379. );
  1380. }
  1381. $message = Message::success($message);
  1382. if ($nbResultsetToDisplay == 0) {
  1383. $notice = __(
  1384. 'MySQL returned an empty result set (i.e. zero rows).'
  1385. );
  1386. $output .= Message::notice($notice)->getDisplay();
  1387. }
  1388. } else {
  1389. $output = '';
  1390. $message = Message::error(
  1391. sprintf(
  1392. __('The following query has failed: "%s"'),
  1393. htmlspecialchars($multiple_query)
  1394. )
  1395. . '<br /><br />'
  1396. . __('MySQL said: ') . $GLOBALS['dbi']->getError()
  1397. );
  1398. }
  1399. // Print/send output
  1400. if ($response->isAjax()) {
  1401. $response->setRequestStatus($message->isSuccess());
  1402. $response->addJSON('message', $message->getDisplay() . $output);
  1403. $response->addJSON('dialog', false);
  1404. exit;
  1405. } else {
  1406. echo $message->getDisplay() , $output;
  1407. if ($message->isError()) {
  1408. // At least one query has failed, so shouldn't
  1409. // execute any more queries, so we quit.
  1410. exit;
  1411. }
  1412. unset($_POST);
  1413. // Now deliberately fall through to displaying the routines list
  1414. }
  1415. return;
  1416. } elseif (! empty($_GET['execute_dialog']) && ! empty($_GET['item_name'])) {
  1417. /**
  1418. * Display the execute form for a routine.
  1419. */
  1420. $routine = self::getDataFromName(
  1421. $_GET['item_name'], $_GET['item_type'], true
  1422. );
  1423. if ($routine !== false) {
  1424. $form = self::getExecuteForm($routine);
  1425. if ($response->isAjax()) {
  1426. $title = __("Execute routine") . " " . Util::backquote(
  1427. htmlentities($_GET['item_name'], ENT_QUOTES)
  1428. );
  1429. $response->addJSON('message', $form);
  1430. $response->addJSON('title', $title);
  1431. $response->addJSON('dialog', true);
  1432. } else {
  1433. echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n";
  1434. echo $form;
  1435. }
  1436. exit;
  1437. } elseif (($response->isAjax())) {
  1438. $message = __('Error in processing request:') . ' ';
  1439. $message .= sprintf(
  1440. Words::get('not_found'),
  1441. htmlspecialchars(Util::backquote($_GET['item_name'])),
  1442. htmlspecialchars(Util::backquote($db))
  1443. );
  1444. $message = Message::error($message);
  1445. $response->setRequestStatus(false);
  1446. $response->addJSON('message', $message);
  1447. exit;
  1448. }
  1449. }
  1450. }
  1451. /**
  1452. * Browse row array
  1453. *
  1454. * @param array $row Columns
  1455. *
  1456. * @return string
  1457. */
  1458. private static function browseRow(array $row)
  1459. {
  1460. $output = null;
  1461. foreach ($row as $value) {
  1462. if ($value === null) {
  1463. $value = '<i>NULL</i>';
  1464. } else {
  1465. $value = htmlspecialchars($value);
  1466. }
  1467. $output .= "<td>" . $value . "</td>";
  1468. }
  1469. return $output;
  1470. }
  1471. /**
  1472. * Creates the HTML code that shows the routine execution dialog.
  1473. *
  1474. * @param array $routine Data for the routine returned by
  1475. * self::getDataFromName()
  1476. *
  1477. * @return string HTML code for the routine execution dialog.
  1478. */
  1479. public static function getExecuteForm(array $routine)
  1480. {
  1481. global $db, $cfg;
  1482. $response = Response::getInstance();
  1483. // Escape special characters
  1484. $routine['item_name'] = htmlentities($routine['item_name'], ENT_QUOTES);
  1485. for ($i = 0; $i < $routine['item_num_params']; $i++) {
  1486. $routine['item_param_name'][$i] = htmlentities(
  1487. $routine['item_param_name'][$i],
  1488. ENT_QUOTES
  1489. );
  1490. }
  1491. // Create the output
  1492. $retval = "";
  1493. $retval .= "<!-- START ROUTINE EXECUTE FORM -->\n\n";
  1494. $retval .= "<form action='db_routines.php' method='post'\n";
  1495. $retval .= " class='rte_form ajax' onsubmit='return false'>\n";
  1496. $retval .= "<input type='hidden' name='item_name'\n";
  1497. $retval .= " value='{$routine['item_name']}' />\n";
  1498. $retval .= "<input type='hidden' name='item_type'\n";
  1499. $retval .= " value='{$routine['item_type']}' />\n";
  1500. $retval .= Url::getHiddenInputs($db) . "\n";
  1501. $retval .= "<fieldset>\n";
  1502. if (! $response->isAjax()) {
  1503. $retval .= "<legend>{$routine['item_name']}</legend>\n";
  1504. $retval .= "<table class='rte_table'>\n";
  1505. $retval .= "<caption class='tblHeaders'>\n";
  1506. $retval .= __('Routine parameters');
  1507. $retval .= "</caption>\n";
  1508. } else {
  1509. $retval .= "<legend>" . __('Routine parameters') . "</legend>\n";
  1510. $retval .= "<table class='rte_table' style='width: 100%;'>\n";
  1511. }
  1512. $retval .= "<tr>\n";
  1513. $retval .= "<th>" . __('Name') . "</th>\n";
  1514. $retval .= "<th>" . __('Type') . "</th>\n";
  1515. if ($cfg['ShowFunctionFields']) {
  1516. $retval .= "<th>" . __('Function') . "</th>\n";
  1517. }
  1518. $retval .= "<th>" . __('Value') . "</th>\n";
  1519. $retval .= "</tr>\n";
  1520. // Get a list of data types that are not yet supported.
  1521. $no_support_types = Util::unsupportedDatatypes();
  1522. for ($i = 0; $i < $routine['item_num_params']; $i++) { // Each parameter
  1523. if ($routine['item_type'] == 'PROCEDURE'
  1524. && $routine['item_param_dir'][$i] == 'OUT'
  1525. ) {
  1526. continue;
  1527. }
  1528. $retval .= "\n<tr>\n";
  1529. $retval .= "<td>{$routine['item_param_name'][$i]}</td>\n";
  1530. $retval .= "<td>{$routine['item_param_type'][$i]}</td>\n";
  1531. if ($cfg['ShowFunctionFields']) {
  1532. $retval .= "<td>\n";
  1533. if (stristr($routine['item_param_type'][$i], 'enum')
  1534. || stristr($routine['item_param_type'][$i], 'set')
  1535. || in_array(
  1536. mb_strtolower($routine['item_param_type'][$i]),
  1537. $no_support_types
  1538. )
  1539. ) {
  1540. $retval .= "--\n";
  1541. } else {
  1542. $field = array(
  1543. 'True_Type' => mb_strtolower(
  1544. $routine['item_param_type'][$i]
  1545. ),
  1546. 'Type' => '',
  1547. 'Key' => '',
  1548. 'Field' => '',
  1549. 'Default' => '',
  1550. 'first_timestamp' => false
  1551. );
  1552. $retval .= "<select name='funcs["
  1553. . $routine['item_param_name'][$i] . "]'>";
  1554. $retval .= Util::getFunctionsForField($field, false, array());
  1555. $retval .= "</select>";
  1556. }
  1557. $retval .= "</td>\n";
  1558. }
  1559. // Append a class to date/time fields so that
  1560. // jQuery can attach a datepicker to them
  1561. $class = '';
  1562. if ($routine['item_param_type'][$i] == 'DATETIME'
  1563. || $routine['item_param_type'][$i] == 'TIMESTAMP'
  1564. ) {
  1565. $class = 'datetimefield';
  1566. } elseif ($routine['item_param_type'][$i] == 'DATE') {
  1567. $class = 'datefield';
  1568. }
  1569. $retval .= "<td class='nowrap'>\n";
  1570. if (in_array($routine['item_param_type'][$i], array('ENUM', 'SET'))) {
  1571. if ($routine['item_param_type'][$i] == 'ENUM') {
  1572. $input_type = 'radio';
  1573. } else {
  1574. $input_type = 'checkbox';
  1575. }
  1576. foreach ($routine['item_param_length_arr'][$i] as $value) {
  1577. $value = htmlentities(Util::unquote($value), ENT_QUOTES);
  1578. $retval .= "<input name='params["
  1579. . $routine['item_param_name'][$i] . "][]' "
  1580. . "value='" . $value . "' type='"
  1581. . $input_type . "' />"
  1582. . $value . "<br />\n";
  1583. }
  1584. } elseif (in_array(
  1585. mb_strtolower($routine['item_param_type'][$i]),
  1586. $no_support_types
  1587. )) {
  1588. $retval .= "\n";
  1589. } else {
  1590. $retval .= "<input class='$class' type='text' name='params["
  1591. . $routine['item_param_name'][$i] . "]' />\n";
  1592. }
  1593. $retval .= "</td>\n";
  1594. $retval .= "</tr>\n";
  1595. }
  1596. $retval .= "\n</table>\n";
  1597. if (! $response->isAjax()) {
  1598. $retval .= "</fieldset>\n\n";
  1599. $retval .= "<fieldset class='tblFooters'>\n";
  1600. $retval .= " <input type='submit' name='execute_routine'\n";
  1601. $retval .= " value='" . __('Go') . "' />\n";
  1602. $retval .= "</fieldset>\n";
  1603. } else {
  1604. $retval .= "<input type='hidden' name='execute_routine' value='true' />";
  1605. $retval .= "<input type='hidden' name='ajax_request' value='true' />";
  1606. }
  1607. $retval .= "</form>\n\n";
  1608. $retval .= "<!-- END ROUTINE EXECUTE FORM -->\n\n";
  1609. return $retval;
  1610. } // end self::getExecuteForm()
  1611. }