Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Events.php « Database « classes « libraries - github.com/phpmyadmin/phpmyadmin.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 1a2196d8f6bdbcc5135fcad9ed56d780cf01997a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
<?php

declare(strict_types=1);

namespace PhpMyAdmin\Database;

use PhpMyAdmin\DatabaseInterface;
use PhpMyAdmin\Html\Generator;
use PhpMyAdmin\Message;
use PhpMyAdmin\Query\Generator as QueryGenerator;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\Template;
use PhpMyAdmin\Util;

use function __;
use function array_column;
use function array_multisort;
use function count;
use function explode;
use function htmlspecialchars;
use function in_array;
use function intval;
use function mb_strtoupper;
use function sprintf;
use function str_contains;
use function strtoupper;
use function trim;

use const SORT_ASC;

/**
 * Functions for event management.
 */
class Events
{
    /** @var array<string, array<int, string>> */
    private $status = [
        'query' => ['ENABLE', 'DISABLE', 'DISABLE ON SLAVE'],
        'display' => ['ENABLED', 'DISABLED', 'SLAVESIDE_DISABLED'],
    ];

    /** @var array<int, string> */
    private $type = ['RECURRING', 'ONE TIME'];

    /** @var array<int, string> */
    private $interval = [
        'YEAR',
        'QUARTER',
        'MONTH',
        'DAY',
        'HOUR',
        'MINUTE',
        'WEEK',
        'SECOND',
        'YEAR_MONTH',
        'DAY_HOUR',
        'DAY_MINUTE',
        'DAY_SECOND',
        'HOUR_MINUTE',
        'HOUR_SECOND',
        'MINUTE_SECOND',
    ];

    /** @var DatabaseInterface */
    private $dbi;

    /** @var Template */
    private $template;

    /** @var ResponseRenderer */
    private $response;

    /**
     * @param DatabaseInterface $dbi      DatabaseInterface instance.
     * @param Template          $template Template instance.
     * @param ResponseRenderer  $response Response instance.
     */
    public function __construct(DatabaseInterface $dbi, Template $template, $response)
    {
        $this->dbi = $dbi;
        $this->template = $template;
        $this->response = $response;
    }

    /**
     * Handles editor requests for adding or editing an item
     */
    public function handleEditor(): void
    {
        $GLOBALS['errors'] = $GLOBALS['errors'] ?? null;
        $GLOBALS['message'] = $GLOBALS['message'] ?? null;

        if (! empty($_POST['editor_process_add']) || ! empty($_POST['editor_process_edit'])) {
            $sql_query = '';

            $item_query = $this->getQueryFromRequest();

            // set by getQueryFromRequest()
            if (! count($GLOBALS['errors'])) {
                // Execute the created query
                if (! empty($_POST['editor_process_edit'])) {
                    // Backup the old trigger, in case something goes wrong
                    $create_item = $this->dbi->getDefinition($GLOBALS['db'], 'EVENT', $_POST['item_original_name']);
                    $drop_item = 'DROP EVENT IF EXISTS '
                        . Util::backquote($_POST['item_original_name'])
                        . ";\n";
                    $result = $this->dbi->tryQuery($drop_item);
                    if (! $result) {
                        $GLOBALS['errors'][] = sprintf(
                            __('The following query has failed: "%s"'),
                            htmlspecialchars($drop_item)
                        )
                        . '<br>'
                        . __('MySQL said: ') . $this->dbi->getError();
                    } else {
                        $result = $this->dbi->tryQuery($item_query);
                        if (! $result) {
                            $GLOBALS['errors'][] = sprintf(
                                __('The following query has failed: "%s"'),
                                htmlspecialchars($item_query)
                            )
                            . '<br>'
                            . __('MySQL said: ') . $this->dbi->getError();
                            // We dropped the old item, but were unable to create
                            // the new one. Try to restore the backup query
                            $result = $this->dbi->tryQuery($create_item);
                            if (! $result) {
                                $GLOBALS['errors'] = $this->checkResult($create_item, $GLOBALS['errors']);
                            }
                        } else {
                            $GLOBALS['message'] = Message::success(
                                __('Event %1$s has been modified.')
                            );
                            $GLOBALS['message']->addParam(
                                Util::backquote($_POST['item_name'])
                            );
                            $sql_query = $drop_item . $item_query;
                        }
                    }
                } else {
                    // 'Add a new item' mode
                    $result = $this->dbi->tryQuery($item_query);
                    if (! $result) {
                        $GLOBALS['errors'][] = sprintf(
                            __('The following query has failed: "%s"'),
                            htmlspecialchars($item_query)
                        )
                        . '<br><br>'
                        . __('MySQL said: ') . $this->dbi->getError();
                    } else {
                        $GLOBALS['message'] = Message::success(
                            __('Event %1$s has been created.')
                        );
                        $GLOBALS['message']->addParam(
                            Util::backquote($_POST['item_name'])
                        );
                        $sql_query = $item_query;
                    }
                }
            }

            if (count($GLOBALS['errors'])) {
                $GLOBALS['message'] = Message::error(
                    '<b>'
                    . __(
                        'One or more errors have occurred while processing your request:'
                    )
                    . '</b>'
                );
                $GLOBALS['message']->addHtml('<ul>');
                foreach ($GLOBALS['errors'] as $string) {
                    $GLOBALS['message']->addHtml('<li>' . $string . '</li>');
                }

                $GLOBALS['message']->addHtml('</ul>');
            }

            $output = Generator::getMessage($GLOBALS['message'], $sql_query);

            if ($this->response->isAjax()) {
                if ($GLOBALS['message']->isSuccess()) {
                    $events = $this->getDetails($GLOBALS['db'], $_POST['item_name']);
                    $event = $events[0];
                    $this->response->addJSON(
                        'name',
                        htmlspecialchars(
                            mb_strtoupper($_POST['item_name'])
                        )
                    );
                    if (! empty($event)) {
                        $sqlDrop = sprintf(
                            'DROP EVENT IF EXISTS %s',
                            Util::backquote($event['name'])
                        );
                        $this->response->addJSON(
                            'new_row',
                            $this->template->render('database/events/row', [
                                'db' => $GLOBALS['db'],
                                'table' => $GLOBALS['table'],
                                'event' => $event,
                                'has_privilege' => Util::currentUserHasPrivilege('EVENT', $GLOBALS['db']),
                                'sql_drop' => $sqlDrop,
                                'row_class' => '',
                            ])
                        );
                    }

                    $this->response->addJSON('insert', ! empty($event));
                    $this->response->addJSON('message', $output);
                } else {
                    $this->response->setRequestStatus(false);
                    $this->response->addJSON('message', $GLOBALS['message']);
                }

                $this->response->addJSON('tableType', 'events');
                exit;
            }
        }

        /**
         * Display a form used to add/edit a trigger, if necessary
         */
        if (
            ! count($GLOBALS['errors'])
            && (! empty($_POST['editor_process_add'])
            || ! empty($_POST['editor_process_edit'])
            || (empty($_REQUEST['add_item'])
            && empty($_REQUEST['edit_item'])
            && empty($_POST['item_changetype'])))
        ) {
            return;
        }

        // FIXME: this must be simpler than that
        $operation = '';
        $title = '';
        $item = null;
        $mode = '';
        if (! empty($_POST['item_changetype'])) {
            $operation = 'change';
        }

        // Get the data for the form (if any)
        if (! empty($_REQUEST['add_item'])) {
            $title = __('Add event');
            $item = $this->getDataFromRequest();
            $mode = 'add';
        } elseif (! empty($_REQUEST['edit_item'])) {
            $title = __('Edit event');
            if (
                ! empty($_REQUEST['item_name'])
                && empty($_POST['editor_process_edit'])
                && empty($_POST['item_changetype'])
            ) {
                $item = $this->getDataFromName($_REQUEST['item_name']);
                if ($item !== null) {
                    $item['item_original_name'] = $item['item_name'];
                }
            } else {
                $item = $this->getDataFromRequest();
            }

            $mode = 'edit';
        }

        $this->sendEditor($mode, $item, $title, $GLOBALS['db'], $operation);
    }

    /**
     * This function will generate the values that are required to for the editor
     *
     * @return array    Data necessary to create the editor.
     */
    public function getDataFromRequest()
    {
        $retval = [];
        $indices = [
            'item_name',
            'item_original_name',
            'item_status',
            'item_execute_at',
            'item_interval_value',
            'item_interval_field',
            'item_starts',
            'item_ends',
            'item_definition',
            'item_preserve',
            'item_comment',
            'item_definer',
        ];
        foreach ($indices as $index) {
            $retval[$index] = $_POST[$index] ?? '';
        }

        $retval['item_type'] = 'ONE TIME';
        $retval['item_type_toggle'] = 'RECURRING';
        if (isset($_POST['item_type']) && $_POST['item_type'] === 'RECURRING') {
            $retval['item_type'] = 'RECURRING';
            $retval['item_type_toggle'] = 'ONE TIME';
        }

        return $retval;
    }

    /**
     * This function will generate the values that are required to complete
     * the "Edit event" form given the name of a event.
     *
     * @param string $name The name of the event.
     *
     * @return array|null Data necessary to create the editor.
     */
    public function getDataFromName($name): ?array
    {
        $retval = [];
        $columns = '`EVENT_NAME`, `STATUS`, `EVENT_TYPE`, `EXECUTE_AT`, '
                 . '`INTERVAL_VALUE`, `INTERVAL_FIELD`, `STARTS`, `ENDS`, '
                 . '`EVENT_DEFINITION`, `ON_COMPLETION`, `DEFINER`, `EVENT_COMMENT`';
        $where = 'EVENT_SCHEMA ' . Util::getCollateForIS() . '='
                 . "'" . $this->dbi->escapeString($GLOBALS['db']) . "' "
                 . "AND EVENT_NAME='" . $this->dbi->escapeString($name) . "'";
        $query = 'SELECT ' . $columns . ' FROM `INFORMATION_SCHEMA`.`EVENTS` WHERE ' . $where . ';';
        $item = $this->dbi->fetchSingleRow($query);
        if (! $item) {
            return null;
        }

        $retval['item_name'] = $item['EVENT_NAME'];
        $retval['item_status'] = $item['STATUS'];
        $retval['item_type'] = $item['EVENT_TYPE'];
        if ($retval['item_type'] === 'RECURRING') {
            $retval['item_type_toggle'] = 'ONE TIME';
        } else {
            $retval['item_type_toggle'] = 'RECURRING';
        }

        $retval['item_execute_at'] = $item['EXECUTE_AT'];
        $retval['item_interval_value'] = $item['INTERVAL_VALUE'];
        $retval['item_interval_field'] = $item['INTERVAL_FIELD'];
        $retval['item_starts'] = $item['STARTS'];
        $retval['item_ends'] = $item['ENDS'];
        $retval['item_preserve'] = '';
        if ($item['ON_COMPLETION'] === 'PRESERVE') {
            $retval['item_preserve'] = " checked='checked'";
        }

        $retval['item_definition'] = $item['EVENT_DEFINITION'];
        $retval['item_definer'] = $item['DEFINER'];
        $retval['item_comment'] = $item['EVENT_COMMENT'];

        return $retval;
    }

    /**
     * Displays a form used to add/edit an event
     *
     * @param string $mode      If the editor will be used to edit an event
     *                          or add a new one: 'edit' or 'add'.
     * @param string $operation If the editor was previously invoked with
     *                          JS turned off, this will hold the name of
     *                          the current operation
     * @param array  $item      Data for the event returned by
     *                          getDataFromRequest() or getDataFromName()
     *
     * @return string   HTML code for the editor.
     */
    public function getEditorForm($mode, $operation, array $item)
    {
        if ($operation === 'change') {
            if ($item['item_type'] === 'RECURRING') {
                $item['item_type'] = 'ONE TIME';
                $item['item_type_toggle'] = 'RECURRING';
            } else {
                $item['item_type'] = 'RECURRING';
                $item['item_type_toggle'] = 'ONE TIME';
            }
        }

        return $this->template->render('database/events/editor_form', [
            'db' => $GLOBALS['db'],
            'event' => $item,
            'mode' => $mode,
            'is_ajax' => $this->response->isAjax(),
            'status_display' => $this->status['display'],
            'event_type' => $this->type,
            'event_interval' => $this->interval,
        ]);
    }

    /**
     * Composes the query necessary to create an event from an HTTP request.
     *
     * @return string  The CREATE EVENT query.
     */
    public function getQueryFromRequest()
    {
        $GLOBALS['errors'] = $GLOBALS['errors'] ?? null;

        $query = 'CREATE ';
        if (! empty($_POST['item_definer'])) {
            if (str_contains($_POST['item_definer'], '@')) {
                $arr = explode('@', $_POST['item_definer']);
                $query .= 'DEFINER=' . Util::backquote($arr[0]);
                $query .= '@' . Util::backquote($arr[1]) . ' ';
            } else {
                $GLOBALS['errors'][] = __('The definer must be in the "username@hostname" format!');
            }
        }

        $query .= 'EVENT ';
        if (! empty($_POST['item_name'])) {
            $query .= Util::backquote($_POST['item_name']) . ' ';
        } else {
            $GLOBALS['errors'][] = __('You must provide an event name!');
        }

        $query .= 'ON SCHEDULE ';
        if (! empty($_POST['item_type']) && in_array($_POST['item_type'], $this->type)) {
            if ($_POST['item_type'] === 'RECURRING') {
                if (
                    ! empty($_POST['item_interval_value'])
                    && ! empty($_POST['item_interval_field'])
                    && in_array($_POST['item_interval_field'], $this->interval)
                ) {
                    $query .= 'EVERY ' . intval($_POST['item_interval_value']) . ' ';
                    $query .= $_POST['item_interval_field'] . ' ';
                } else {
                    $GLOBALS['errors'][] = __('You must provide a valid interval value for the event.');
                }

                if (! empty($_POST['item_starts'])) {
                    $query .= "STARTS '"
                        . $this->dbi->escapeString($_POST['item_starts'])
                        . "' ";
                }

                if (! empty($_POST['item_ends'])) {
                    $query .= "ENDS '"
                        . $this->dbi->escapeString($_POST['item_ends'])
                        . "' ";
                }
            } else {
                if (! empty($_POST['item_execute_at'])) {
                    $query .= "AT '"
                        . $this->dbi->escapeString($_POST['item_execute_at'])
                        . "' ";
                } else {
                    $GLOBALS['errors'][] = __('You must provide a valid execution time for the event.');
                }
            }
        } else {
            $GLOBALS['errors'][] = __('You must provide a valid type for the event.');
        }

        $query .= 'ON COMPLETION ';
        if (empty($_POST['item_preserve'])) {
            $query .= 'NOT ';
        }

        $query .= 'PRESERVE ';
        if (! empty($_POST['item_status'])) {
            foreach ($this->status['display'] as $key => $value) {
                if ($value == $_POST['item_status']) {
                    $query .= $this->status['query'][$key] . ' ';
                    break;
                }
            }
        }

        if (! empty($_POST['item_comment'])) {
            $query .= "COMMENT '" . $this->dbi->escapeString($_POST['item_comment']) . "' ";
        }

        $query .= 'DO ';
        if (! empty($_POST['item_definition'])) {
            $query .= $_POST['item_definition'];
        } else {
            $GLOBALS['errors'][] = __('You must provide an event definition.');
        }

        return $query;
    }

    public function getEventSchedulerStatus(): bool
    {
        $state = (string) $this->dbi->fetchValue('SHOW GLOBAL VARIABLES LIKE \'event_scheduler\'', 1);

        return strtoupper($state) === 'ON' || $state === '1';
    }

    /**
     * @param string|null $createStatement Query
     * @param array       $errors          Errors
     *
     * @return array
     */
    private function checkResult($createStatement, array $errors)
    {
        // OMG, this is really bad! We dropped the query,
        // failed to create a new one
        // and now even the backup query does not execute!
        // This should not happen, but we better handle
        // this just in case.
        $errors[] = __('Sorry, we failed to restore the dropped event.') . '<br>'
            . __('The backed up query was:')
            . '"' . htmlspecialchars((string) $createStatement) . '"<br>'
            . __('MySQL said: ') . $this->dbi->getError();

        return $errors;
    }

    /**
     * Send editor via ajax or by echoing.
     *
     * @param string     $mode      Editor mode 'add' or 'edit'
     * @param array|null $item      Data necessary to create the editor
     * @param string     $title     Title of the editor
     * @param string     $db        Database
     * @param string     $operation Operation 'change' or ''
     */
    private function sendEditor($mode, ?array $item, $title, $db, $operation): void
    {
        if ($item !== null) {
            $editor = $this->getEditorForm($mode, $operation, $item);
            if ($this->response->isAjax()) {
                $this->response->addJSON('message', $editor);
                $this->response->addJSON('title', $title);
            } else {
                echo "\n\n<h2>" . $title . "</h2>\n\n" . $editor;
                unset($_POST);
            }

            exit;
        }

        $message = __('Error in processing request:') . ' ';
        $message .= sprintf(
            __('No event with name %1$s found in database %2$s.'),
            htmlspecialchars(Util::backquote($_REQUEST['item_name'])),
            htmlspecialchars(Util::backquote($db))
        );
        $message = Message::error($message);
        if ($this->response->isAjax()) {
            $this->response->setRequestStatus(false);
            $this->response->addJSON('message', $message);
            exit;
        }

        echo $message->getDisplay();
    }

    public function export(): void
    {
        if (empty($_GET['export_item']) || empty($_GET['item_name'])) {
            return;
        }

        $itemName = $_GET['item_name'];
        $exportData = $this->dbi->getDefinition($GLOBALS['db'], 'EVENT', $itemName);

        if (! $exportData) {
            $exportData = false;
        }

        $itemName = htmlspecialchars(Util::backquote($itemName));
        if ($exportData !== false) {
            $exportData = htmlspecialchars(trim($exportData));
            $title = sprintf(__('Export of event %s'), $itemName);

            if ($this->response->isAjax()) {
                $this->response->addJSON('message', $exportData);
                $this->response->addJSON('title', $title);

                exit;
            }

            $output = '<div class="container">';
            $output .= '<h2>' . $title . '</h2>';
            $output .= '<div class="card"><div class="card-body">';
            $output .= '<textarea rows="15" class="form-control">' . $exportData . '</textarea>';
            $output .= '</div></div></div>';

            $this->response->addHTML($output);

            return;
        }

        $message = sprintf(
            __('Error in processing request: No event with name %1$s found in database %2$s.'),
            $itemName,
            htmlspecialchars(Util::backquote($GLOBALS['db']))
        );
        $message = Message::error($message);

        if ($this->response->isAjax()) {
            $this->response->setRequestStatus(false);
            $this->response->addJSON('message', $message);

            exit;
        }

        $this->response->addHTML($message->getDisplay());
    }

    /**
     * Returns details about the EVENTs for a specific database.
     *
     * @param string $db   db name
     * @param string $name event name
     *
     * @return array information about EVENTs
     */
    public function getDetails(string $db, string $name = ''): array
    {
        if (! $GLOBALS['cfg']['Server']['DisableIS']) {
            $query = QueryGenerator::getInformationSchemaEventsRequest(
                $this->dbi->escapeString($db),
                empty($name) ? null : $this->dbi->escapeString($name)
            );
        } else {
            $query = 'SHOW EVENTS FROM ' . Util::backquote($db);
            if ($name) {
                $query .= " WHERE `Name` = '"
                    . $this->dbi->escapeString($name) . "'";
            }
        }

        $result = [];
        $events = $this->dbi->fetchResult($query);

        foreach ($events as $event) {
            $result[] = [
                'name' => $event['Name'],
                'type' => $event['Type'],
                'status' => $event['Status'],
            ];
        }

        // Sort results by name
        $name = array_column($result, 'name');
        array_multisort($name, SORT_ASC, $result);

        return $result;
    }
}