Fixed: 'Browse foreign values' not working properly
[phpmyadmin/ammaryasirr.git] / libraries / rte / rte_routines.lib.php
blob8cd052923e2984aaf0173a01e3b2ac00dea92e1c
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Functions for routine management.
6 * @package phpMyAdmin
7 */
8 if (! defined('PHPMYADMIN')) {
9 exit;
12 /**
13 * Sets required globals
15 function PMA_RTN_setGlobals()
17 global $param_directions, $param_opts_num, $param_sqldataaccess;
19 $param_directions = array('IN',
20 'OUT',
21 'INOUT');
22 $param_opts_num = array('UNSIGNED',
23 'ZEROFILL',
24 'UNSIGNED ZEROFILL');
25 $param_sqldataaccess = array('NO SQL',
26 'CONTAINS SQL',
27 'READS SQL DATA',
28 'MODIFIES SQL DATA');
31 /**
32 * Main function for the routines functionality
34 function PMA_RTN_main()
36 global $db;
38 PMA_RTN_setGlobals();
39 /**
40 * Process all requests
42 PMA_RTN_handleEditor();
43 PMA_RTN_handleExecute();
44 PMA_RTN_handleExport();
45 /**
46 * Display a list of available routines
48 $columns = "`SPECIFIC_NAME`, `ROUTINE_NAME`, `ROUTINE_TYPE`, ";
49 $columns .= "`DTD_IDENTIFIER`, `ROUTINE_DEFINITION`";
50 $where = "ROUTINE_SCHEMA='" . PMA_sqlAddSlashes($db) . "'";
51 $items = PMA_DBI_fetch_result(
52 "SELECT $columns FROM `INFORMATION_SCHEMA`.`ROUTINES` WHERE $where;"
54 echo PMA_RTE_getList('routine', $items);
55 /**
56 * Display the form for adding a new routine, if the user has the privileges.
58 echo PMA_RTN_getFooterLinks();
59 /**
60 * Display a warning for users with PHP's old "mysql" extension.
62 if ($GLOBALS['cfg']['Server']['extension'] === 'mysql') {
63 trigger_error(
64 __('You are using PHP\'s deprecated \'mysql\' extension, '
65 . 'which is not capable of handling multi queries. '
66 . '<b>The execution of some stored routines may fail!</b> '
67 . 'Please use the improved \'mysqli\' extension to '
68 . 'avoid any problems.'),
69 E_USER_WARNING
72 } // end PMA_RTN_main()
74 /**
75 * This function parses a string containing one parameter of a routine,
76 * as returned by PMA_RTN_parseAllParameters() and returns an array containing
77 * the information about this parameter.
79 * @param string $value A string containing one parameter of a routine
81 * @return array Parsed information about the input parameter
83 function PMA_RTN_parseOneParameter($value)
85 global $param_directions;
87 $retval = array(0 => '',
88 1 => '',
89 2 => '',
90 3 => '',
91 4 => '');
92 $parsed_param = PMA_SQP_parse($value);
93 $pos = 0;
94 if (in_array(strtoupper($parsed_param[$pos]['data']), $param_directions)) {
95 $retval[0] = strtoupper($parsed_param[0]['data']);
96 $pos++;
98 if ($parsed_param[$pos]['type'] == 'alpha_identifier'
99 || $parsed_param[$pos]['type'] == 'quote_backtick'
101 $retval[1] = PMA_unQuote($parsed_param[$pos]['data']);
102 $pos++;
104 $depth = 0;
105 $param_length = '';
106 $param_opts = array();
107 for ($i=$pos; $i<$parsed_param['len']; $i++) {
108 if (($parsed_param[$i]['type'] == 'alpha_columnType'
109 || $parsed_param[$i]['type'] == 'alpha_functionName') && $depth == 0 // "CHAR" seems to be mistaken for a function by the parser
111 $retval[2] = strtoupper($parsed_param[$i]['data']);
112 } else if ($parsed_param[$i]['type'] == 'punct_bracket_open_round' && $depth == 0) {
113 $depth = 1;
114 } else if ($parsed_param[$i]['type'] == 'punct_bracket_close_round' && $depth == 1) {
115 $depth = 0;
116 } else if ($depth == 1) {
117 $param_length .= $parsed_param[$i]['data'];
118 } else if ($parsed_param[$i]['type'] == 'alpha_reservedWord' && strtoupper($parsed_param[$i]['data']) == 'CHARSET' && $depth == 0) {
119 if ($parsed_param[$i+1]['type'] == 'alpha_charset' || $parsed_param[$i+1]['type'] == 'alpha_identifier') {
120 $param_opts[] = strtolower($parsed_param[$i+1]['data']);
122 } else if ($parsed_param[$i]['type'] == 'alpha_columnAttrib' && $depth == 0) {
123 $param_opts[] = strtoupper($parsed_param[$i]['data']);
126 $retval[3] = $param_length;
127 sort($param_opts);
128 $retval[4] = implode(' ', $param_opts);
130 return $retval;
131 } // end PMA_RTN_parseOneParameter()
134 * This function looks through the contents of a parsed
135 * SHOW CREATE [PROCEDURE | FUNCTION] query and extracts
136 * information about the routine's parameters.
138 * @param array $parsed_query Parsed query, returned by by PMA_SQP_parse()
139 * @param string $routine_type Routine type: 'PROCEDURE' or 'FUNCTION'
141 * @return array Information about the parameteres of a routine.
143 function PMA_RTN_parseAllParameters($parsed_query, $routine_type)
145 global $param_directions;
147 $retval = array();
148 $retval['num'] = 0;
150 // First get the list of parameters from the query
151 $buffer = '';
152 $params = array();
153 $fetching = false;
154 $depth = 0;
155 for ($i=0; $i<$parsed_query['len']; $i++) {
156 if ($parsed_query[$i]['type'] == 'alpha_reservedWord' && $parsed_query[$i]['data'] == $routine_type) {
157 $fetching = true;
158 } else if ($fetching == true && $parsed_query[$i]['type'] == 'punct_bracket_open_round') {
159 $depth++;
160 if ($depth > 1) {
161 $buffer .= $parsed_query[$i]['data'] . ' ';
163 } else if ($fetching == true && $parsed_query[$i]['type'] == 'punct_bracket_close_round') {
164 $depth--;
165 if ($depth > 0) {
166 $buffer .= $parsed_query[$i]['data'] . ' ';
167 } else {
168 break;
170 } else if ($parsed_query[$i]['type'] == 'punct_listsep' && $depth == 1) {
171 $params[] = $buffer;
172 $retval['num']++;
173 $buffer = '';
174 } else if ($fetching == true && $depth > 0) {
175 $buffer .= $parsed_query[$i]['data'] . ' ';
178 if (! empty($buffer)) {
179 $params[] = $buffer;
180 $retval['num']++;
182 // Now parse each parameter individually
183 foreach ($params as $key => $value) {
184 list($retval['dir'][],
185 $retval['name'][],
186 $retval['type'][],
187 $retval['length'][],
188 $retval['opts'][]) = PMA_RTN_parseOneParameter($value);
190 // Since some indices of $retval may be still undefined, we fill
191 // them each with an empty array to avoid E_ALL errors in PHP.
192 foreach (array('dir', 'name', 'type', 'length', 'opts') as $key => $index) {
193 if (! isset($retval[$index])) {
194 $retval[$index] = array();
198 return $retval;
199 } // end PMA_RTN_parseAllParameters()
202 * This function looks through the contents of a parsed
203 * SHOW CREATE [PROCEDURE | FUNCTION] query and extracts
204 * information about the routine's definer.
206 * @param array $parsed_query Parsed query, returned by PMA_SQP_parse()
208 * @return string The definer of a routine.
210 function PMA_RTN_parseRoutineDefiner($parsed_query)
212 $retval = '';
213 $fetching = false;
214 for ($i=0; $i<$parsed_query['len']; $i++) {
215 if ($parsed_query[$i]['type'] == 'alpha_reservedWord' && $parsed_query[$i]['data'] == 'DEFINER') {
216 $fetching = true;
217 } else if ($fetching == true && ($parsed_query[$i]['type'] != 'quote_backtick' && substr($parsed_query[$i]['type'], 0, 5) != 'punct')) {
218 break;
219 } else if ($fetching == true && $parsed_query[$i]['type'] == 'quote_backtick') {
220 $retval .= PMA_unQuote($parsed_query[$i]['data']);
221 } else if ($fetching == true && $parsed_query[$i]['type'] == 'punct_user') {
222 $retval .= $parsed_query[$i]['data'];
225 return $retval;
226 } // end PMA_RTN_parseRoutineDefiner()
229 * Handles editor requests for adding or editing an item
231 function PMA_RTN_handleEditor()
233 global $_GET, $_POST, $_REQUEST, $GLOBALS, $db, $cfg, $errors;
235 if (! empty($_REQUEST['editor_process_add'])
236 || ! empty($_REQUEST['editor_process_edit'])
239 * Handle a request to create/edit a routine
241 $sql_query = '';
242 $routine_query = PMA_RTN_getQueryFromRequest();
243 if (! count($errors)) { // set by PMA_RTN_getQueryFromRequest()
244 // Execute the created query
245 if (! empty($_REQUEST['editor_process_edit'])) {
246 if (! in_array($_REQUEST['item_original_type'], array('PROCEDURE', 'FUNCTION'))) {
247 $errors[] = sprintf(__('Invalid routine type: "%s"'), htmlspecialchars($_REQUEST['item_original_type']));
248 } else {
249 // Backup the old routine, in case something goes wrong
250 $create_routine = PMA_DBI_get_definition($db, $_REQUEST['item_original_type'], $_REQUEST['item_original_name']);
251 $drop_routine = "DROP {$_REQUEST['item_original_type']} " . PMA_backquote($_REQUEST['item_original_name']) . ";\n";
252 $result = PMA_DBI_try_query($drop_routine);
253 if (! $result) {
254 $errors[] = sprintf(__('The following query has failed: "%s"'), $drop_routine) . '<br />'
255 . __('MySQL said: ') . PMA_DBI_getError(null);
256 } else {
257 $result = PMA_DBI_try_query($routine_query);
258 if (! $result) {
259 $errors[] = sprintf(__('The following query has failed: "%s"'), $routine_query) . '<br />'
260 . __('MySQL said: ') . PMA_DBI_getError(null);
261 // We dropped the old routine, but were unable to create the new one
262 // Try to restore the backup query
263 $result = PMA_DBI_try_query($create_routine);
264 if (! $result) {
265 // OMG, this is really bad! We dropped the query, failed to create a new one
266 // and now even the backup query does not execute!
267 // This should not happen, but we better handle this just in case.
268 $errors[] = __('Sorry, we failed to restore the dropped routine.') . '<br />'
269 . __('The backed up query was:') . "\"$create_routine\"" . '<br />'
270 . __('MySQL said: ') . PMA_DBI_getError(null);
272 } else {
273 $message = PMA_Message::success(__('Routine %1$s has been modified.'));
274 $message->addParam(PMA_backquote($_REQUEST['item_name']));
275 $sql_query = $drop_routine . $routine_query;
279 } else {
280 // 'Add a new routine' mode
281 $result = PMA_DBI_try_query($routine_query);
282 if (! $result) {
283 $errors[] = sprintf(__('The following query has failed: "%s"'), $routine_query) . '<br /><br />'
284 . __('MySQL said: ') . PMA_DBI_getError(null);
285 } else {
286 $message = PMA_Message::success(__('Routine %1$s has been created.'));
287 $message->addParam(PMA_backquote($_REQUEST['item_name']));
288 $sql_query = $routine_query;
293 if (count($errors)) {
294 $message = PMA_Message::error(__('<b>One or more errors have occured while processing your request:</b>'));
295 $message->addString('<ul>');
296 foreach ($errors as $num => $string) {
297 $message->addString('<li>' . $string . '</li>');
299 $message->addString('</ul>');
302 $output = PMA_showMessage($message, $sql_query);
303 if ($GLOBALS['is_ajax_request']) {
304 $extra_data = array();
305 if ($message->isSuccess()) {
306 $columns = "`SPECIFIC_NAME`, `ROUTINE_NAME`, `ROUTINE_TYPE`, `DTD_IDENTIFIER`, `ROUTINE_DEFINITION`";
307 $where = "ROUTINE_SCHEMA='" . PMA_sqlAddSlashes($db) . "' "
308 . "AND ROUTINE_NAME='" . PMA_sqlAddSlashes($_REQUEST['item_name']) . "'"
309 . "AND ROUTINE_TYPE='" . PMA_sqlAddSlashes($_REQUEST['item_type']) . "'";
310 $routine = PMA_DBI_fetch_single_row("SELECT $columns FROM `INFORMATION_SCHEMA`.`ROUTINES` WHERE $where;");
311 $extra_data['name'] = htmlspecialchars(strtoupper($_REQUEST['item_name']));
312 $extra_data['new_row'] = PMA_RTN_getRowForList($routine);
313 $extra_data['insert'] = ! empty($routine);
314 $response = $output;
315 } else {
316 $response = $message;
318 PMA_ajaxResponse($response, $message->isSuccess(), $extra_data);
323 * Display a form used to add/edit a routine, if necessary
325 if (count($errors) || ( empty($_REQUEST['editor_process_add']) && empty($_REQUEST['editor_process_edit'])
326 && (! empty($_REQUEST['add_item']) || ! empty($_REQUEST['edit_item'])
327 || ! empty($_REQUEST['routine_addparameter']) || ! empty($_REQUEST['routine_removeparameter'])
328 || ! empty($_REQUEST['routine_changetype']))) // FIXME: this must be simpler than that
330 // Handle requests to add/remove parameters and changing routine type
331 // This is necessary when JS is disabled
332 $operation = '';
333 if (! empty($_REQUEST['routine_addparameter'])) {
334 $operation = 'add';
335 } else if (! empty($_REQUEST['routine_removeparameter'])) {
336 $operation = 'remove';
337 } else if (! empty($_REQUEST['routine_changetype'])) {
338 $operation = 'change';
340 // Get the data for the form (if any)
341 if (! empty($_REQUEST['add_item'])) {
342 $title = PMA_RTE_getWord('add');
343 $routine = PMA_RTN_getDataFromRequest();
344 $mode = 'add';
345 } else if (! empty($_REQUEST['edit_item'])) {
346 $title = __("Edit routine");
347 if (! $operation && ! empty($_REQUEST['item_name']) && empty($_REQUEST['editor_process_edit'])) {
348 $routine = PMA_RTN_getDataFromName($_REQUEST['item_name'], $_REQUEST['item_type']);
349 if ($routine !== false) {
350 $routine['item_original_name'] = $routine['item_name'];
351 $routine['item_original_type'] = $routine['item_type'];
353 } else {
354 $routine = PMA_RTN_getDataFromRequest();
356 $mode = 'edit';
358 if ($routine !== false) {
359 // Show form
360 $editor = PMA_RTN_getEditorForm($mode, $operation, $routine);
361 if ($GLOBALS['is_ajax_request']) {
362 $template = PMA_RTN_getParameterRow();
363 $extra_data = array('title' => $title,
364 'param_template' => $template,
365 'type' => $routine['item_type']);
366 PMA_ajaxResponse($editor, true, $extra_data);
368 echo "\n\n<h2>$title</h2>\n\n$editor";
369 require './libraries/footer.inc.php';
370 // exit;
371 } else {
372 $message = __('Error in processing request') . ' : ';
373 $message .= sprintf(
374 PMA_RTE_getWord('not_found'),
375 htmlspecialchars(PMA_backquote($_REQUEST['item_name'])),
376 htmlspecialchars(PMA_backquote($db))
378 $message = PMA_message::error($message);
379 if ($GLOBALS['is_ajax_request']) {
380 PMA_ajaxResponse($message, false);
381 } else {
382 $message->display();
386 } // end PMA_RTN_handleEditor()
389 * This function will generate the values that are required to
390 * complete the editor form. It is especially necessary to handle
391 * the 'Add another parameter', 'Remove last parameter' and
392 * 'Change routine type' functionalities when JS is disabled.
394 * @return array Data necessary to create the routine editor.
396 function PMA_RTN_getDataFromRequest()
398 global $_REQUEST, $param_directions, $param_sqldataaccess;
400 $retval = array();
401 $indices = array('item_name',
402 'item_original_name',
403 'item_returnlength',
404 'item_returnopts_num',
405 'item_returnopts_text',
406 'item_definition',
407 'item_comment',
408 'item_definer');
409 foreach ($indices as $key => $index) {
410 $retval[$index] = isset($_REQUEST[$index]) ? $_REQUEST[$index] : '';
413 $retval['item_type'] = 'PROCEDURE';
414 $retval['item_type_toggle'] = 'FUNCTION';
415 if (isset($_REQUEST['item_type']) && $_REQUEST['item_type'] == 'FUNCTION') {
416 $retval['item_type'] = 'FUNCTION';
417 $retval['item_type_toggle'] = 'PROCEDURE';
419 $retval['item_original_type'] = 'PROCEDURE';
420 if (isset($_REQUEST['item_original_type'])
421 && $_REQUEST['item_original_type'] == 'FUNCTION'
423 $retval['item_original_type'] = 'FUNCTION';
425 $retval['item_num_params'] = 0;
426 $retval['item_param_dir'] = array();
427 $retval['item_param_name'] = array();
428 $retval['item_param_type'] = array();
429 $retval['item_param_length'] = array();
430 $retval['item_param_opts_num'] = array();
431 $retval['item_param_opts_text'] = array();
432 if ( isset($_REQUEST['item_param_name'])
433 && isset($_REQUEST['item_param_type'])
434 && isset($_REQUEST['item_param_length'])
435 && isset($_REQUEST['item_param_opts_num'])
436 && isset($_REQUEST['item_param_opts_text'])
437 && is_array($_REQUEST['item_param_name'])
438 && is_array($_REQUEST['item_param_type'])
439 && is_array($_REQUEST['item_param_length'])
440 && is_array($_REQUEST['item_param_opts_num'])
441 && is_array($_REQUEST['item_param_opts_text'])
443 if ($_REQUEST['item_type'] == 'PROCEDURE') {
444 $retval['item_param_dir'] = $_REQUEST['item_param_dir'];
445 foreach ($retval['item_param_dir'] as $key => $value) {
446 if (! in_array($value, $param_directions, true)) {
447 $retval['item_param_dir'][$key] = '';
451 $retval['item_param_name'] = $_REQUEST['item_param_name'];
452 $retval['item_param_type'] = $_REQUEST['item_param_type'];
453 foreach ($retval['item_param_type'] as $key => $value) {
454 if (! in_array($value, PMA_getSupportedDatatypes(), true)) {
455 $retval['item_param_type'][$key] = '';
458 $retval['item_param_length'] = $_REQUEST['item_param_length'];
459 $retval['item_param_opts_num'] = $_REQUEST['item_param_opts_num'];
460 $retval['item_param_opts_text'] = $_REQUEST['item_param_opts_text'];
461 $retval['item_num_params'] = max(
462 count($retval['item_param_name']),
463 count($retval['item_param_type']),
464 count($retval['item_param_length']),
465 count($retval['item_param_opts_num']),
466 count($retval['item_param_opts_text'])
469 $retval['item_returntype'] = '';
470 if (isset($_REQUEST['item_returntype'])
471 && in_array($_REQUEST['item_returntype'], PMA_getSupportedDatatypes())
473 $retval['item_returntype'] = $_REQUEST['item_returntype'];
476 $retval['item_isdeterministic'] = '';
477 if (isset($_REQUEST['item_isdeterministic'])
478 && strtolower($_REQUEST['item_isdeterministic']) == 'on'
480 $retval['item_isdeterministic'] = " checked='checked'";
482 $retval['item_securitytype_definer'] = '';
483 $retval['item_securitytype_invoker'] = '';
484 if (isset($_REQUEST['item_securitytype'])) {
485 if ($_REQUEST['item_securitytype'] === 'DEFINER') {
486 $retval['item_securitytype_definer'] = " selected='selected'";
487 } else if ($_REQUEST['item_securitytype'] === 'INVOKER') {
488 $retval['item_securitytype_invoker'] = " selected='selected'";
491 $retval['item_sqldataaccess'] = '';
492 if (isset($_REQUEST['item_sqldataaccess'])
493 && in_array($_REQUEST['item_sqldataaccess'], $param_sqldataaccess, true)
495 $retval['item_sqldataaccess'] = $_REQUEST['item_sqldataaccess'];
498 return $retval;
499 } // end function PMA_RTN_getDataFromRequest()
502 * This function will generate the values that are required to complete
503 * the "Edit routine" form given the name of a routine.
505 * @param string $name The name of the routine.
506 * @param string $type Type of routine (ROUTINE|PROCEDURE)
507 * @param bool $all Whether to return all data or just
508 * the info about parameters.
510 * @return array Data necessary to create the routine editor.
512 function PMA_RTN_getDataFromName($name, $type, $all = true)
514 global $param_directions, $param_sqldataaccess, $db;
516 $retval = array();
518 // Build and execute the query
519 $fields = "SPECIFIC_NAME, ROUTINE_TYPE, DTD_IDENTIFIER, "
520 . "ROUTINE_DEFINITION, IS_DETERMINISTIC, SQL_DATA_ACCESS, "
521 . "ROUTINE_COMMENT, SECURITY_TYPE";
522 $where = "ROUTINE_SCHEMA='" . PMA_sqlAddSlashes($db) . "' "
523 . "AND SPECIFIC_NAME='" . PMA_sqlAddSlashes($name) . "'"
524 . "AND ROUTINE_TYPE='" . PMA_sqlAddSlashes($type) . "'";
525 $query = "SELECT $fields FROM INFORMATION_SCHEMA.ROUTINES WHERE $where;";
527 $routine = PMA_DBI_fetch_single_row($query);
529 if (! $routine) {
530 return false;
533 // Get required data
534 $retval['item_name'] = $routine['SPECIFIC_NAME'];
535 $retval['item_type'] = $routine['ROUTINE_TYPE'];
536 $parsed_query = PMA_SQP_parse(
537 PMA_DBI_get_definition(
538 $db,
539 $routine['ROUTINE_TYPE'],
540 $routine['SPECIFIC_NAME']
543 $params = PMA_RTN_parseAllParameters($parsed_query, $routine['ROUTINE_TYPE']);
544 $retval['item_num_params'] = $params['num'];
545 $retval['item_param_dir'] = $params['dir'];
546 $retval['item_param_name'] = $params['name'];
547 $retval['item_param_type'] = $params['type'];
548 $retval['item_param_length'] = $params['length'];
549 $retval['item_param_opts_num'] = $params['opts'];
550 $retval['item_param_opts_text'] = $params['opts'];
552 // Get extra data
553 if ($all) {
554 if ($retval['item_type'] == 'FUNCTION') {
555 $retval['item_type_toggle'] = 'PROCEDURE';
556 } else {
557 $retval['item_type_toggle'] = 'FUNCTION';
559 $retval['item_returntype'] = '';
560 $retval['item_returnlength'] = '';
561 $retval['item_returnopts_num'] = '';
562 $retval['item_returnopts_text'] = '';
563 if (! empty($routine['DTD_IDENTIFIER'])) {
564 if (strlen($routine['DTD_IDENTIFIER']) > 63) {
565 // If the DTD_IDENTIFIER string from INFORMATION_SCHEMA is
566 // at least 64 characters, then it may actually have been
567 // chopped because that column is a varchar(64), so we will
568 // parse the output of SHOW CREATE query to get accurate
569 // information about the return variable.
570 $dtd = '';
571 $fetching = false;
572 for ($i=0; $i<$parsed_query['len']; $i++) {
573 if ($parsed_query[$i]['type'] == 'alpha_reservedWord'
574 && strtoupper($parsed_query[$i]['data']) == 'RETURNS'
576 $fetching = true;
577 } else if ($fetching == true && $parsed_query[$i]['type'] == 'alpha_reservedWord') {
578 // We will not be looking for options such as UNSIGNED
579 // or ZEROFILL because there is no way that a numeric
580 // field's DTD_IDENTIFIER can be longer than 64
581 // characters. We can safely assume that the return
582 // datatype is either ENUM or SET, so we only look
583 // for CHARSET.
584 $word = strtoupper($parsed_query[$i]['data']);
585 if ($word == 'CHARSET'
586 && ($parsed_query[$i+1]['type'] == 'alpha_charset'
587 || $parsed_query[$i+1]['type'] == 'alpha_identifier')
589 $dtd .= $word . ' ' . $parsed_query[$i+1]['data'];
591 break;
592 } else if ($fetching == true) {
593 $dtd .= $parsed_query[$i]['data'] . ' ';
596 $routine['DTD_IDENTIFIER'] = $dtd;
598 $returnparam = PMA_RTN_parseOneParameter($routine['DTD_IDENTIFIER']);
599 $retval['item_returntype'] = $returnparam[2];
600 $retval['item_returnlength'] = $returnparam[3];
601 $retval['item_returnopts_num'] = $returnparam[4];
602 $retval['item_returnopts_text'] = $returnparam[4];
604 $retval['item_definer'] = PMA_RTN_parseRoutineDefiner($parsed_query);
605 $retval['item_definition'] = $routine['ROUTINE_DEFINITION'];
606 $retval['item_isdeterministic'] = '';
607 if ($routine['IS_DETERMINISTIC'] == 'YES') {
608 $retval['item_isdeterministic'] = " checked='checked'";
610 $retval['item_securitytype_definer'] = '';
611 $retval['item_securitytype_invoker'] = '';
612 if ($routine['SECURITY_TYPE'] == 'DEFINER') {
613 $retval['item_securitytype_definer'] = " selected='selected'";
614 } else if ($routine['SECURITY_TYPE'] == 'INVOKER') {
615 $retval['item_securitytype_invoker'] = " selected='selected'";
617 $retval['item_sqldataaccess'] = $routine['SQL_DATA_ACCESS'];
618 $retval['item_comment'] = $routine['ROUTINE_COMMENT'];
621 return $retval;
622 } // PMA_RTN_getDataFromName()
625 * Creates one row for the parameter table used in the routine editor.
627 * @param array $routine Data for the routine returned by
628 * PMA_RTN_getDataFromRequest() or
629 * PMA_RTN_getDataFromName()
630 * @param mixed $index Either a numeric index of the row being processed
631 * or NULL to create a template row for AJAX request
632 * @param string $class Class used to hide the direction column, if the
633 * row is for a stored function.
635 * @return string HTML code of one row of parameter table for the editor.
637 function PMA_RTN_getParameterRow($routine = array(), $index = null, $class = '')
639 global $param_directions, $param_opts_num, $titles;
641 if ($index === null) {
642 // template row for AJAX request
643 $i = 0;
644 $index = '%s';
645 $drop_class = '';
646 $routine = array(
647 'item_param_dir' => array(0 => ''),
648 'item_param_name' => array(0 => ''),
649 'item_param_type' => array(0 => ''),
650 'item_param_length' => array(0 => ''),
651 'item_param_opts_num' => array(0 => ''),
652 'item_param_opts_text' => array(0 => '')
654 } else if (! empty($routine)) {
655 // regular row for routine editor
656 $drop_class = ' hide';
657 $i = $index;
658 } else {
659 // No input data. This shouldn't happen,
660 // but better be safe than sorry.
661 return '';
664 // Create the output
665 $retval = "";
666 $retval .= " <tr>\n";
667 $retval .= " <td class='routine_direction_cell$class'>\n";
668 $retval .= " <select name='item_param_dir[$index]'>\n";
669 foreach ($param_directions as $key => $value) {
670 $selected = "";
671 if (! empty($routine['item_param_dir'][$i])
672 && $routine['item_param_dir'][$i] == $value
674 $selected = " selected='selected'";
676 $retval .= " <option$selected>$value</option>\n";
678 $retval .= " </select>\n";
679 $retval .= " </td>\n";
680 $retval .= " <td><input name='item_param_name[$index]' type='text'\n";
681 $retval .= " value='{$routine['item_param_name'][$i]}' /></td>\n";
682 $retval .= " <td><select name='item_param_type[$index]'>";
683 $retval .= PMA_getSupportedDatatypes(true, $routine['item_param_type'][$i]) . "\n";
684 $retval .= " </select></td>\n";
685 $retval .= " <td><input name='item_param_length[$index]' type='text'\n";
686 $retval .= " value='{$routine['item_param_length'][$i]}' /></td>\n";
687 $retval .= " <td class='hide no_len'>---</td>\n";
688 $retval .= " <td class='routine_param_opts_text'>\n";
689 $retval .= PMA_generateCharsetDropdownBox(
690 PMA_CSDROPDOWN_CHARSET,
691 "item_param_opts_text[$index]",
692 null,
693 $routine['item_param_opts_text'][$i]
695 $retval .= " </td>\n";
696 $retval .= " <td class='hide no_opts'>---</td>\n";
697 $retval .= " <td class='routine_param_opts_num'>\n";
698 $retval .= " <select name='item_param_opts_num[$index]'>\n";
699 $retval .= " <option value=''></option>";
700 foreach ($param_opts_num as $key => $value) {
701 $selected = "";
702 if (! empty($routine['item_param_opts_num'][$i])
703 && $routine['item_param_opts_num'][$i] == $value
705 $selected = " selected='selected'";
707 $retval .= "<option$selected>$value</option>";
709 $retval .= "\n </select>\n";
710 $retval .= " </td>\n";
711 $retval .= " <td class='routine_param_remove$drop_class'>\n";
712 $retval .= " <a href='#' class='routine_param_remove_anchor'>\n";
713 $retval .= " {$titles['Drop']}\n";
714 $retval .= " </a>\n";
715 $retval .= " </td>\n";
716 $retval .= " </tr>\n";
718 return $retval;
719 } // end PMA_RTN_getParameterRow()
722 * Displays a form used to add/edit a routine
724 * @param string $mode If the editor will be used edit a routine
725 * or add a new one: 'edit' or 'add'.
726 * @param string $operation If the editor was previously invoked with
727 * JS turned off, this will hold the name of
728 * the current operation
729 * @param array $routine Data for the routine returned by
730 * PMA_RTN_getDataFromRequest() or
731 * PMA_RTN_getDataFromName()
733 * @return string HTML code for the editor.
735 function PMA_RTN_getEditorForm($mode, $operation, $routine)
737 global $db, $titles, $errors, $param_directions, $param_sqldataaccess, $param_opts_num;
739 // Escape special characters
740 $need_escape = array(
741 'item_original_name',
742 'item_name',
743 'item_returnlength',
744 'item_definition',
745 'item_definer',
746 'item_comment'
748 foreach ($need_escape as $key => $index) {
749 $routine[$index] = htmlentities($routine[$index], ENT_QUOTES);
751 for ($i=0; $i<$routine['item_num_params']; $i++) {
752 $routine['item_param_name'][$i] = htmlentities(
753 $routine['item_param_name'][$i],
754 ENT_QUOTES
756 $routine['item_param_length'][$i] = htmlentities(
757 $routine['item_param_length'][$i],
758 ENT_QUOTES
762 // Handle some logic first
763 if ($operation == 'change') {
764 if ($routine['item_type'] == 'PROCEDURE') {
765 $routine['item_type'] = 'FUNCTION';
766 $routine['item_type_toggle'] = 'PROCEDURE';
767 } else {
768 $routine['item_type'] = 'PROCEDURE';
769 $routine['item_type_toggle'] = 'FUNCTION';
771 } else if ($operation == 'add' || ($routine['item_num_params'] == 0 && $mode == 'add' && ! $errors)) {
772 $routine['item_param_dir'][] = '';
773 $routine['item_param_name'][] = '';
774 $routine['item_param_type'][] = '';
775 $routine['item_param_length'][] = '';
776 $routine['item_param_opts_num'][] = '';
777 $routine['item_param_opts_text'][] = '';
778 $routine['item_num_params']++;
779 } else if ($operation == 'remove') {
780 unset($routine['item_param_dir'][$routine['item_num_params']-1]);
781 unset($routine['item_param_name'][$routine['item_num_params']-1]);
782 unset($routine['item_param_type'][$routine['item_num_params']-1]);
783 unset($routine['item_param_length'][$routine['item_num_params']-1]);
784 unset($routine['item_param_opts_num'][$routine['item_num_params']-1]);
785 unset($routine['item_param_opts_text'][$routine['item_num_params']-1]);
786 $routine['item_num_params']--;
788 $disable_remove_parameter = '';
789 if (! $routine['item_num_params']) {
790 $disable_remove_parameter = " color: gray;' disabled='disabled";
792 $original_routine = '';
793 if ($mode == 'edit') {
794 $original_routine = "<input name='item_original_name' "
795 . "type='hidden' "
796 . "value='{$routine['item_original_name']}'/>\n"
797 . "<input name='item_original_type' "
798 . "type='hidden' "
799 . "value='{$routine['item_original_type']}'/>\n";
801 $isfunction_class = '';
802 $isprocedure_class = '';
803 $isfunction_select = '';
804 $isprocedure_select = '';
805 if ($routine['item_type'] == 'PROCEDURE') {
806 $isfunction_class = ' hide';
807 $isprocedure_select = " selected='selected'";
808 } else {
809 $isprocedure_class = ' hide';
810 $isfunction_select = " selected='selected'";
813 // Create the output
814 $retval = "";
815 $retval .= "<!-- START " . strtoupper($mode) . " ROUTINE FORM -->\n\n";
816 $retval .= "<form class='rte_form' action='db_routines.php' method='post'>\n";
817 $retval .= "<input name='{$mode}_item' type='hidden' value='1' />\n";
818 $retval .= $original_routine;
819 $retval .= PMA_generate_common_hidden_inputs($db) . "\n";
820 $retval .= "<fieldset>\n";
821 $retval .= "<legend>" . __('Details') . "</legend>\n";
822 $retval .= "<table class='rte_table' style='width: 100%'>\n";
823 $retval .= "<tr>\n";
824 $retval .= " <td style='width: 20%;'>" . __('Routine name') . "</td>\n";
825 $retval .= " <td><input type='text' name='item_name' maxlength='64'\n";
826 $retval .= " value='{$routine['item_name']}' /></td>\n";
827 $retval .= "</tr>\n";
828 $retval .= "<tr>\n";
829 $retval .= " <td>" . __('Type') . "</td>\n";
830 $retval .= " <td>\n";
831 if ($GLOBALS['is_ajax_request']) {
832 $retval .= " <select name='item_type'>\n";
833 $retval .= " <option value='PROCEDURE'$isprocedure_select>PROCEDURE</option>\n";
834 $retval .= " <option value='FUNCTION'$isfunction_select>FUNCTION</option>\n";
835 $retval .= " </select>\n";
836 } else {
837 $retval .= " <input name='item_type' type='hidden' value='{$routine['item_type']}' />\n";
838 $retval .= " <div style='width: 49%; float: left; text-align: center; font-weight: bold;'>\n";
839 $retval .= " {$routine['item_type']}\n";
840 $retval .= " </div>\n";
841 $retval .= " <input style='width: 49%;' type='submit' name='routine_changetype'\n";
842 $retval .= " value='".sprintf(__('Change to %s'), $routine['item_type_toggle'])."' />\n";
844 $retval .= " </td>\n";
845 $retval .= "</tr>\n";
846 $retval .= "<tr>\n";
847 $retval .= " <td>" . __('Parameters') . "</td>\n";
848 $retval .= " <td>\n";
849 // parameter handling start
850 $retval .= " <table class='routine_params_table'>\n";
851 $retval .= " <tr>\n";
852 $retval .= " <th class='routine_direction_cell$isprocedure_class'>" . __('Direction') . "</th>\n";
853 $retval .= " <th>" . __('Name') . "</th>\n";
854 $retval .= " <th>" . __('Type') . "</th>\n";
855 $retval .= " <th>" . __('Length/Values') . "</th>\n";
856 $retval .= " <th colspan='2'>" . __('Options') . "</th>\n";
857 $retval .= " <th class='routine_param_remove hide'>&nbsp;</th>\n";
858 $retval .= " </tr>";
859 for ($i=0; $i<$routine['item_num_params']; $i++) { // each parameter
860 $retval .= PMA_RTN_getParameterRow($routine, $i, $isprocedure_class);
862 $retval .= " </table>\n";
863 $retval .= " </td>\n";
864 $retval .= "</tr>\n";
865 $retval .= "<tr>\n";
866 $retval .= " <td>&nbsp;</td>\n";
867 $retval .= " <td>\n";
868 $retval .= " <input style='width: 49%;' type='submit' \n";
869 $retval .= " name='routine_addparameter'\n";
870 $retval .= " value='" . __('Add parameter') . "' />\n";
871 $retval .= " <input style='width: 49%;$disable_remove_parameter'\n";
872 $retval .= " type='submit' \n";
873 $retval .= " name='routine_removeparameter'\n";
874 $retval .= " value='" . __('Remove last parameter') . "' />\n";
875 $retval .= " </td>\n";
876 $retval .= "</tr>\n";
877 // parameter handling end
878 $retval .= "<tr class='routine_return_row$isfunction_class'>\n";
879 $retval .= " <td>" . __('Return type') . "</td>\n";
880 $retval .= " <td><select name='item_returntype'>\n";
881 $retval .= PMA_getSupportedDatatypes(true, $routine['item_returntype']) . "\n";
882 $retval .= " </select></td>\n";
883 $retval .= "</tr>\n";
884 $retval .= "<tr class='routine_return_row$isfunction_class'>\n";
885 $retval .= " <td>" . __('Return length/values') . "</td>\n";
886 $retval .= " <td><input type='text' name='item_returnlength'\n";
887 $retval .= " value='{$routine['item_returnlength']}' /></td>\n";
888 $retval .= " <td class='hide no_len'>---</td>\n";
889 $retval .= "</tr>\n";
890 $retval .= "<tr class='routine_return_row$isfunction_class'>\n";
891 $retval .= " <td>" . __('Return options') . "</td>\n";
892 $retval .= " <td><div>\n";
893 $retval .= PMA_generateCharsetDropdownBox(
894 PMA_CSDROPDOWN_CHARSET,
895 "item_returnopts_text",
896 null,
897 $routine['item_returnopts_text']
899 $retval .= "\n </div>\n";
900 $retval .= " <div><select name='item_returnopts_num'>\n";
901 $retval .= " <option value=''></option>";
902 foreach ($param_opts_num as $key => $value) {
903 $selected = "";
904 if (! empty($routine['item_returnopts_num'])
905 && $routine['item_returnopts_num'] == $value
907 $selected = " selected='selected'";
909 $retval .= "<option$selected>$value</option>";
911 $retval .= "\n </select></div>\n";
912 $retval .= " <div class='hide no_opts'>---</div>\n";
913 $retval .= "</td>\n";
914 $retval .= "</tr>\n";
915 $retval .= "<tr>\n";
916 $retval .= " <td>" . __('Definition') . "</td>\n";
917 $retval .= " <td><textarea name='item_definition' rows='15' cols='40'>";
918 $retval .= $routine['item_definition'];
919 $retval .= "</textarea></td>\n";
920 $retval .= "</tr>\n";
921 $retval .= "<tr>\n";
922 $retval .= " <td>" . __('Is deterministic') . "</td>\n";
923 $retval .= " <td><input type='checkbox' name='item_isdeterministic'{$routine['item_isdeterministic']} /></td>\n";
924 $retval .= "</tr>\n";
925 $retval .= "<tr>\n";
926 $retval .= " <td>" . __('Definer') . "</td>\n";
927 $retval .= " <td><input type='text' name='item_definer'\n";
928 $retval .= " value='{$routine['item_definer']}' /></td>\n";
929 $retval .= "</tr>\n";
930 $retval .= "<tr>\n";
931 $retval .= " <td>" . __('Security type') . "</td>\n";
932 $retval .= " <td><select name='item_securitytype'>\n";
933 $retval .= " <option value='DEFINER'{$routine['item_securitytype_definer']}>DEFINER</option>\n";
934 $retval .= " <option value='INVOKER'{$routine['item_securitytype_invoker']}>INVOKER</option>\n";
935 $retval .= " </select></td>\n";
936 $retval .= "</tr>\n";
937 $retval .= "<tr>\n";
938 $retval .= " <td>" . __('SQL data access') . "</td>\n";
939 $retval .= " <td><select name='item_sqldataaccess'>\n";
940 foreach ($param_sqldataaccess as $key => $value) {
941 $selected = "";
942 if ($routine['item_sqldataaccess'] == $value) {
943 $selected = " selected='selected'";
945 $retval .= " <option$selected>$value</option>\n";
947 $retval .= " </select></td>\n";
948 $retval .= "</tr>\n";
949 $retval .= "<tr>\n";
950 $retval .= " <td>" . __('Comment') . "</td>\n";
951 $retval .= " <td><input type='text' name='item_comment' maxlength='64'\n";
952 $retval .= " value='{$routine['item_comment']}' /></td>\n";
953 $retval .= "</tr>\n";
954 $retval .= "</table>\n";
955 $retval .= "</fieldset>\n";
956 if ($GLOBALS['is_ajax_request']) {
957 $retval .= "<input type='hidden' name='editor_process_{$mode}'\n";
958 $retval .= " value='true' />\n";
959 $retval .= "<input type='hidden' name='ajax_request' value='true' />\n";
960 } else {
961 $retval .= "<fieldset class='tblFooters'>\n";
962 $retval .= " <input type='submit' name='editor_process_{$mode}'\n";
963 $retval .= " value='" . __('Go') . "' />\n";
964 $retval .= "</fieldset>\n";
966 $retval .= "</form>\n\n";
967 $retval .= "<!-- END " . strtoupper($mode) . " ROUTINE FORM -->\n\n";
969 return $retval;
970 } // end PMA_RTN_getEditorForm()
973 * Composes the query necessary to create a routine from an HTTP request.
975 * @return string The CREATE [ROUTINE | PROCEDURE] query.
977 function PMA_RTN_getQueryFromRequest()
979 global $_REQUEST, $cfg, $errors, $param_sqldataaccess, $param_opts_num, $param_directions;
981 $_REQUEST['item_type'] = isset($_REQUEST['item_type']) ? $_REQUEST['item_type'] : '';
983 $query = 'CREATE ';
984 if (! empty($_REQUEST['item_definer'])) {
985 if (strpos($_REQUEST['item_definer'], '@') !== false) {
986 $arr = explode('@', $_REQUEST['item_definer']);
987 $query .= 'DEFINER=' . PMA_backquote($arr[0]);
988 $query .= '@' . PMA_backquote($arr[1]) . ' ';
989 } else {
990 $errors[] = __('The definer must be in the "username@hostname" format');
993 if ($_REQUEST['item_type'] == 'FUNCTION'
994 || $_REQUEST['item_type'] == 'PROCEDURE'
996 $query .= $_REQUEST['item_type'] . ' ';
997 } else {
998 $errors[] = sprintf(__('Invalid routine type: "%s"'), htmlspecialchars($_REQUEST['item_type']));
1000 if (! empty($_REQUEST['item_name'])) {
1001 $query .= PMA_backquote($_REQUEST['item_name']);
1002 } else {
1003 $errors[] = __('You must provide a routine name');
1005 $params = '';
1006 $warned_about_dir = false;
1007 $warned_about_name = false;
1008 $warned_about_length = false;
1009 if ( ! empty($_REQUEST['item_param_name'])
1010 && ! empty($_REQUEST['item_param_type'])
1011 && ! empty($_REQUEST['item_param_length'])
1012 && is_array($_REQUEST['item_param_name'])
1013 && is_array($_REQUEST['item_param_type'])
1014 && is_array($_REQUEST['item_param_length'])
1016 for ($i=0; $i<count($_REQUEST['item_param_name']); $i++) {
1017 if (! empty($_REQUEST['item_param_name'][$i]) && ! empty($_REQUEST['item_param_type'][$i])) {
1018 if ($_REQUEST['item_type'] == 'PROCEDURE'
1019 && ! empty($_REQUEST['item_param_dir'][$i])
1020 && in_array($_REQUEST['item_param_dir'][$i], $param_directions)
1022 $params .= $_REQUEST['item_param_dir'][$i] . " " . PMA_backquote($_REQUEST['item_param_name'][$i]) . " "
1023 . $_REQUEST['item_param_type'][$i];
1024 } else if ($_REQUEST['item_type'] == 'FUNCTION') {
1025 $params .= PMA_backquote($_REQUEST['item_param_name'][$i]) . " " . $_REQUEST['item_param_type'][$i];
1026 } else if (! $warned_about_dir) {
1027 $warned_about_dir = true;
1028 $errors[] = sprintf(
1029 __('Invalid direction "%s" given for parameter.'),
1030 htmlspecialchars($_REQUEST['item_param_dir'][$i])
1033 if ($_REQUEST['item_param_length'][$i] != ''
1034 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN)$@i',
1035 $_REQUEST['item_param_type'][$i])
1037 $params .= "(" . $_REQUEST['item_param_length'][$i] . ")";
1038 } else if ($_REQUEST['item_param_length'][$i] == '' && preg_match('@^(ENUM|SET|VARCHAR|VARBINARY)$@i', $_REQUEST['item_param_type'][$i])) {
1039 if (! $warned_about_length) {
1040 $warned_about_length = true;
1041 $errors[] = __('You must provide length/values for routine parameters of type ENUM, SET, VARCHAR and VARBINARY.');
1044 if (! empty($_REQUEST['item_param_opts_text'][$i])) {
1045 if (in_array($_REQUEST['item_param_type'][$i], $cfg['ColumnTypes']['STRING'])) {
1046 $params .= ' CHARSET ' . strtolower($_REQUEST['item_param_opts_text'][$i]);
1049 if (! empty($_REQUEST['item_param_opts_num'][$i])) {
1050 if (in_array($_REQUEST['item_param_type'][$i], $cfg['ColumnTypes']['NUMERIC'])) {
1051 $params .= ' ' . strtoupper($_REQUEST['item_param_opts_num'][$i]);
1054 if ($i != count($_REQUEST['item_param_name'])-1) {
1055 $params .= ", ";
1057 } else if (! $warned_about_name) {
1058 $warned_about_name = true;
1059 $errors[] = __('You must provide a name and a type for each routine parameter.');
1060 break;
1064 $query .= "(" . $params . ") ";
1065 if ($_REQUEST['item_type'] == 'FUNCTION') {
1066 if (! empty($_REQUEST['item_returntype']) && in_array($_REQUEST['item_returntype'], PMA_getSupportedDatatypes())) {
1067 $query .= "RETURNS {$_REQUEST['item_returntype']}";
1068 } else {
1069 $errors[] = __('You must provide a valid return type for the routine.');
1071 if (! empty($_REQUEST['item_returnlength'])
1072 && !preg_match('@^(DATE|DATETIME|TIME|TINYBLOB|TINYTEXT|BLOB|TEXT|MEDIUMBLOB|MEDIUMTEXT|LONGBLOB|LONGTEXT|SERIAL|BOOLEAN)$@i',
1073 $_REQUEST['item_returntype'])
1075 $query .= "(" . $_REQUEST['item_returnlength'] . ")";
1076 } else if (empty($_REQUEST['item_returnlength']) && preg_match('@^(ENUM|SET|VARCHAR|VARBINARY)$@i', $_REQUEST['item_returntype'])) {
1077 if (! $warned_about_length) {
1078 $warned_about_length = true;
1079 $errors[] = __('You must provide length/values for routine parameters of type ENUM, SET, VARCHAR and VARBINARY.');
1082 if (! empty($_REQUEST['item_returnopts_text'])) {
1083 if (in_array($_REQUEST['item_returntype'], $cfg['ColumnTypes']['STRING'])) {
1084 $query .= ' CHARSET ' . strtolower($_REQUEST['item_returnopts_text']);
1087 if (! empty($_REQUEST['item_returnopts_num'])) {
1088 if (in_array($_REQUEST['item_returntype'], $cfg['ColumnTypes']['NUMERIC'])) {
1089 $query .= ' ' . strtoupper($_REQUEST['item_returnopts_num']);
1092 $query .= ' ';
1094 if (! empty($_REQUEST['item_comment'])) {
1095 $query .= "COMMENT '" . PMA_sqlAddslashes($_REQUEST['item_comment']) . "' ";
1097 if (isset($_REQUEST['item_isdeterministic'])) {
1098 $query .= 'DETERMINISTIC ';
1099 } else {
1100 $query .= 'NOT DETERMINISTIC ';
1102 if (! empty($_REQUEST['item_sqldataaccess']) && in_array($_REQUEST['item_sqldataaccess'], $param_sqldataaccess)) {
1103 $query .= $_REQUEST['item_sqldataaccess'] . ' ';
1105 if (! empty($_REQUEST['item_securitytype'])) {
1106 if ($_REQUEST['item_securitytype'] == 'DEFINER' || $_REQUEST['item_securitytype'] == 'INVOKER') {
1107 $query .= 'SQL SECURITY ' . $_REQUEST['item_securitytype'] . ' ';
1110 if (! empty($_REQUEST['item_definition'])) {
1111 $query .= $_REQUEST['item_definition'];
1112 } else {
1113 $errors[] = __('You must provide a routine definition.');
1116 return $query;
1117 } // end PMA_RTN_getQueryFromRequest()
1120 * Handles requests for executing a routine
1122 function PMA_RTN_handleExecute()
1124 global $_GET, $_POST, $_REQUEST, $GLOBALS, $db, $cfg;
1127 * Handle all user requests other than the default of listing routines
1129 if (! empty($_REQUEST['execute_routine']) && ! empty($_REQUEST['item_name'])) {
1130 // Build the queries
1131 $routine = PMA_RTN_getDataFromName($_REQUEST['item_name'], $_REQUEST['item_type'], false);
1132 if ($routine !== false) {
1133 $queries = array();
1134 $end_query = array();
1135 $args = array();
1136 for ($i=0; $i<$routine['item_num_params']; $i++) {
1137 if (isset($_REQUEST['params'][$routine['item_param_name'][$i]])) {
1138 $value = $_REQUEST['params'][$routine['item_param_name'][$i]];
1139 if (is_array($value)) { // is SET type
1140 $value = implode(',', $value);
1142 $value = PMA_sqlAddSlashes($value);
1143 if (! empty($_REQUEST['funcs'][$routine['item_param_name'][$i]])
1144 && in_array($_REQUEST['funcs'][$routine['item_param_name'][$i]], $cfg['Functions'])
1146 $queries[] = "SET @p$i={$_REQUEST['funcs'][$routine['item_param_name'][$i]]}('$value');\n";
1147 } else {
1148 $queries[] = "SET @p$i='$value';\n";
1150 $args[] = "@p$i";
1151 } else {
1152 $args[] = "@p$i";
1154 if ($routine['item_type'] == 'PROCEDURE') {
1155 if ($routine['item_param_dir'][$i] == 'OUT'
1156 || $routine['item_param_dir'][$i] == 'INOUT'
1158 $end_query[] = "@p$i AS " . PMA_backquote($routine['item_param_name'][$i]);
1162 if ($routine['item_type'] == 'PROCEDURE') {
1163 $queries[] = "CALL " . PMA_backquote($routine['item_name'])
1164 . "(" . implode(', ', $args) . ");\n";
1165 if (count($end_query)) {
1166 $queries[] = "SELECT " . implode(', ', $end_query) . ";\n";
1168 } else {
1169 $queries[] = "SELECT " . PMA_backquote($routine['item_name'])
1170 . "(" . implode(', ', $args) . ") "
1171 . "AS " . PMA_backquote($routine['item_name']) . ";\n";
1173 // Execute the queries
1174 $affected = 0;
1175 $result = null;
1176 $outcome = true;
1177 foreach ($queries as $num => $query) {
1178 $resource = PMA_DBI_try_query($query);
1179 if ($resource === false) {
1180 $outcome = false;
1181 break;
1183 while (true) {
1184 if (! PMA_DBI_more_results()) {
1185 break;
1187 PMA_DBI_next_result();
1189 if (substr($query, 0, 6) == 'SELECT') {
1190 $result = $resource;
1191 } else if (substr($query, 0, 4) == 'CALL') {
1192 $affected = PMA_DBI_affected_rows() - PMA_DBI_num_rows($resource);
1195 // Generate output
1196 if ($outcome) {
1197 $message = __('Your SQL query has been executed successfully');
1198 if ($routine['item_type'] == 'PROCEDURE') {
1199 $message .= '<br />';
1200 $message .= sprintf(
1201 _ngettext(
1202 '%d row affected by the last statement inside the procedure',
1203 '%d rows affected by the last statement inside the procedure',
1204 $affected
1206 $affected
1209 $message = PMA_message::success($message);
1210 // Pass the SQL queries through the "pretty printer"
1211 $output = '<code class="sql" style="margin-bottom: 1em;">';
1212 $output .= PMA_SQP_formatHtml(PMA_SQP_parse(implode($queries)));
1213 $output .= '</code>';
1214 // Display results
1215 if ($result) {
1216 $output .= "<fieldset><legend>";
1217 $output .= sprintf(
1218 __('Execution results of routine %s'),
1219 PMA_backquote(htmlspecialchars($routine['item_name']))
1221 $output .= "</legend>";
1222 $output .= "<table><tr>";
1223 foreach (PMA_DBI_get_fields_meta($result) as $key => $field) {
1224 $output .= "<th>";
1225 $output .= htmlspecialchars($field->name);
1226 $output .= "</th>";
1228 $output .= "</tr>";
1229 // Stored routines can only ever return ONE ROW.
1230 $data = PMA_DBI_fetch_single_row($result);
1231 foreach ($data as $key => $value) {
1232 if ($value === null) {
1233 $value = '<i>NULL</i>';
1234 } else {
1235 $value = htmlspecialchars($value);
1237 $output .= "<td class='odd'>" . $value . "</td>";
1239 $output .= "</table></fieldset>";
1240 } else {
1241 $notice = __('MySQL returned an empty result set (i.e. zero rows).');
1242 $output .= PMA_message::notice($notice)->getDisplay();
1244 } else {
1245 $output = '';
1246 $message = PMA_message::error(sprintf(__('The following query has failed: "%s"'), $query) . '<br /><br />'
1247 . __('MySQL said: ') . PMA_DBI_getError(null));
1249 // Print/send output
1250 if ($GLOBALS['is_ajax_request']) {
1251 $extra_data = array('dialog' => false);
1252 PMA_ajaxResponse(
1253 $message->getDisplay() . $output,
1254 $message->isSuccess(),
1255 $extra_data
1257 } else {
1258 echo $message->getDisplay() . $output;
1259 if ($message->isError()) {
1260 // At least one query has failed, so shouldn't
1261 // execute any more queries, so we quit.
1262 exit;
1264 unset($_POST);
1265 // Now deliberately fall through to displaying the routines list
1267 } else {
1268 $message = __('Error in processing request') . ' : ';
1269 $message .= sprintf(
1270 PMA_RTE_getWord('not_found'),
1271 htmlspecialchars(PMA_backquote($_REQUEST['item_name'])),
1272 htmlspecialchars(PMA_backquote($db))
1274 $message = PMA_message::error($message);
1275 if ($GLOBALS['is_ajax_request']) {
1276 PMA_ajaxResponse($message, $message->isSuccess());
1277 } else {
1278 echo $message->getDisplay();
1279 unset($_POST);
1282 } else if (! empty($_GET['execute_dialog']) && ! empty($_GET['item_name'])) {
1284 * Display the execute form for a routine.
1286 $routine = PMA_RTN_getDataFromName($_GET['item_name'], $_GET['item_type'], true);
1287 if ($routine !== false) {
1288 $form = PMA_RTN_getExecuteForm($routine);
1289 if ($GLOBALS['is_ajax_request'] == true) {
1290 $extra_data = array();
1291 $extra_data['dialog'] = true;
1292 $extra_data['title'] = __("Execute routine") . " ";
1293 $extra_data['title'] .= PMA_backquote(
1294 htmlentities($_GET['item_name'], ENT_QUOTES)
1296 PMA_ajaxResponse($form, true, $extra_data);
1297 } else {
1298 echo "\n\n<h2>" . __("Execute routine") . "</h2>\n\n";
1299 echo $form;
1300 require './libraries/footer.inc.php';
1301 // exit;
1303 } else if (($GLOBALS['is_ajax_request'] == true)) {
1304 $message = __('Error in processing request') . ' : ';
1305 $message .= sprintf(
1306 PMA_RTE_getWord('not_found'),
1307 htmlspecialchars(PMA_backquote($_REQUEST['item_name'])),
1308 htmlspecialchars(PMA_backquote($db))
1310 $message = PMA_message::error($message);
1311 PMA_ajaxResponse($message, false);
1317 * Creates the HTML code that shows the routine execution dialog.
1319 * @param array $routine Data for the routine returned by
1320 * PMA_RTN_getDataFromName()
1322 * @return string HTML code for the routine execution dialog.
1324 function PMA_RTN_getExecuteForm($routine)
1326 global $db, $cfg;
1328 // Escape special characters
1329 $routine['item_name'] = htmlentities($routine['item_name'], ENT_QUOTES);
1330 for ($i=0; $i<$routine['item_num_params']; $i++) {
1331 $routine['item_param_name'][$i] = htmlentities(
1332 $routine['item_param_name'][$i],
1333 ENT_QUOTES
1337 // Create the output
1338 $retval = "";
1339 $retval .= "<!-- START ROUTINE EXECUTE FORM -->\n\n";
1340 $retval .= "<form action='db_routines.php' method='post' class='rte_form'>\n";
1341 $retval .= "<input type='hidden' name='item_name'\n";
1342 $retval .= " value='{$routine['item_name']}' />\n";
1343 $retval .= "<input type='hidden' name='item_type'\n";
1344 $retval .= " value='{$routine['item_type']}' />\n";
1345 $retval .= PMA_generate_common_hidden_inputs($db) . "\n";
1346 $retval .= "<fieldset>\n";
1347 if ($GLOBALS['is_ajax_request'] != true) {
1348 $retval .= "<legend>{$routine['item_name']}</legend>\n";
1349 $retval .= "<table class='rte_table'>\n";
1350 $retval .= "<caption class='tblHeaders'>\n";
1351 $retval .= __('Routine parameters');
1352 $retval .= "</caption>\n";
1353 } else {
1354 $retval .= "<legend>" . __('Routine parameters') . "</legend>\n";
1355 $retval .= "<table class='rte_table' style='width: 100%;'>\n";
1357 $retval .= "<tr>\n";
1358 $retval .= "<th>" . __('Name') . "</th>\n";
1359 $retval .= "<th>" . __('Type') . "</th>\n";
1360 if ($cfg['ShowFunctionFields']) {
1361 $retval .= "<th>" . __('Function') . "</th>\n";
1363 $retval .= "<th>" . __('Value') . "</th>\n";
1364 $retval .= "</tr>\n";
1365 // Get a list of data types that are not yet supported.
1366 $no_support_types = PMA_unsupportedDatatypes();
1367 for ($i=0; $i<$routine['item_num_params']; $i++) { // Each parameter
1368 if ($routine['item_type'] == 'PROCEDURE'
1369 && $routine['item_param_dir'][$i] == 'OUT'
1371 continue;
1373 $rowclass = ($i % 2 == 0) ? 'even' : 'odd';
1374 $retval .= "\n<tr class='$rowclass'>\n";
1375 $retval .= "<td>{$routine['item_param_name'][$i]}</td>\n";
1376 $retval .= "<td>{$routine['item_param_type'][$i]}</td>\n";
1377 if ($cfg['ShowFunctionFields']) {
1378 $retval .= "<td>\n";
1379 if (stristr($routine['item_param_type'][$i], 'enum')
1380 || stristr($routine['item_param_type'][$i], 'set')
1381 || in_array(strtolower($routine['item_param_type'][$i]), $no_support_types)
1383 $retval .= "--\n";
1384 } else {
1385 $field = array(
1386 'True_Type' => strtolower($routine['item_param_type'][$i]),
1387 'Type' => '',
1388 'Key' => '',
1389 'Field' => '',
1390 'Default' => '',
1391 'first_timestamp' => false
1393 $retval .= "<select name='funcs[{$routine['item_param_name'][$i]}]'>";
1394 $retval .= PMA_getFunctionsForField($field, false);
1395 $retval .= "</select>";
1397 $retval .= "</td>\n";
1399 // Append a class to date/time fields so that
1400 // jQuery can attach a datepicker to them
1401 $class = '';
1402 if ($routine['item_param_type'][$i] == 'DATETIME'
1403 || $routine['item_param_type'][$i] == 'TIMESTAMP'
1405 $class = 'datetimefield';
1406 } else if ($routine['item_param_type'][$i] == 'DATE') {
1407 $class = 'datefield';
1409 $retval .= "<td class='nowrap'>\n";
1410 if (in_array($routine['item_param_type'][$i], array('ENUM', 'SET'))) {
1411 $tokens = PMA_SQP_parse($routine['item_param_length'][$i]);
1412 if ($routine['item_param_type'][$i] == 'ENUM') {
1413 $input_type = 'radio';
1414 } else {
1415 $input_type = 'checkbox';
1417 for ($j=0; $j<$tokens['len']; $j++) {
1418 if ($tokens[$j]['type'] != 'punct_listsep') {
1419 $tokens[$j]['data'] = htmlentities(
1420 PMA_unquote($tokens[$j]['data']),
1421 ENT_QUOTES
1423 $retval .= "<input name='params[{$routine['item_param_name'][$i]}][]' "
1424 . "value='{$tokens[$j]['data']}' type='$input_type' />"
1425 . "{$tokens[$j]['data']}<br />\n";
1428 } else if (in_array(strtolower($routine['item_param_type'][$i]), $no_support_types)) {
1429 $retval .= "\n";
1430 } else {
1431 $retval .= "<input class='$class' type='text' name='params[{$routine['item_param_name'][$i]}]' />\n";
1433 $retval .= "</td>\n";
1434 $retval .= "</tr>\n";
1436 $retval .= "\n</table>\n";
1437 if ($GLOBALS['is_ajax_request'] != true) {
1438 $retval .= "</fieldset>\n\n";
1439 $retval .= "<fieldset class='tblFooters'>\n";
1440 $retval .= " <input type='submit' name='execute_routine'\n";
1441 $retval .= " value='" . __('Go') . "' />\n";
1442 $retval .= "</fieldset>\n";
1443 } else {
1444 $retval .= "<input type='hidden' name='execute_routine' value='true' />";
1445 $retval .= "<input type='hidden' name='ajax_request' value='true' />";
1447 $retval .= "</form>\n\n";
1448 $retval .= "<!-- END ROUTINE EXECUTE FORM -->\n\n";
1450 return $retval;
1451 } // end PMA_RTN_getExecuteForm()