Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
// This file is part of Moodle - http://moodle.org/
4
//
5
// Moodle is free software: you can redistribute it and/or modify
6
// it under the terms of the GNU General Public License as published by
7
// the Free Software Foundation, either version 3 of the License, or
8
// (at your option) any later version.
9
//
10
// Moodle is distributed in the hope that it will be useful,
11
// but WITHOUT ANY WARRANTY; without even the implied warranty of
12
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
// GNU General Public License for more details.
14
//
15
// You should have received a copy of the GNU General Public License
16
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17
 
18
/**
19
 * Output rendering for the plugin.
20
 *
21
 * @package     tool_task
22
 * @copyright   2014 Damyon Wiese
23
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
defined('MOODLE_INTERNAL') || die();
27
 
28
use core\task\scheduled_task;
29
 
30
 
31
/**
32
 * Implements the plugin renderer
33
 *
34
 * @copyright 2014 Damyon Wiese
35
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36
 */
37
class tool_task_renderer extends plugin_renderer_base {
38
 
39
    /**
40
     * This function will render a table with the summary of all adhoc tasks.
41
     *
42
     * @param array $summary
43
     * @return string HTML to output.
44
     */
45
    public function adhoc_tasks_summary_table(array $summary): string {
46
        $adhocurl = '/admin/tool/task/adhoctasks.php';
47
        $adhocrunurl = '/admin/tool/task/run_adhoctasks.php';
48
 
49
        // Main tasks table.
50
        $table = new html_table();
51
        $table->caption = get_string('adhoctasks', 'tool_task');
52
        $table->head = [
53
            get_string('component', 'tool_task') . ' / ' . get_string('classname', 'tool_task'),
54
            get_string('adhoctasksrunning', 'tool_task'),
55
            get_string('adhoctasksdue', 'tool_task'),
56
            get_string('adhoctasksfuture', 'tool_task'),
57
            get_string('adhoctasksfailed', 'tool_task'),
58
            get_string('nextruntime', 'tool_task'),
59
        ];
60
 
61
        $table->attributes['class'] = 'admintable generaltable';
62
        $table->colclasses = [];
63
 
64
        // For each task entry (row) show action buttons/logs link depending on the user permissions.
65
        $data = [];
66
        $canruntasks = \core\task\manager::is_runnable() && get_config('tool_task', 'enablerunnow');
67
        foreach ($summary as $component => $classes) {
68
            // Component cell.
69
            $componentcell = new html_table_cell($component);
70
            $componentcell->header = true;
71
            $componentcell->id = "tasks-$component";
72
            $componentcell->colspan = 6;
73
 
74
            $data[] = new html_table_row([$componentcell]);
75
 
76
            foreach ($classes as $classname => $stats) {
77
                // Task class cell.
78
                $classbits = explode('\\',  $classname);
79
                $classcontent = html_writer::link(
80
                    new moodle_url($adhocurl, ['classname' => $classname]),
81
                    end($classbits)
82
                );
83
                $classcell = new html_table_cell($classcontent);
84
                $classcell->header = true;
85
                $classcell->attributes['class'] = "task-class-summary text-ltr";
86
 
87
                $duecontent = $stats['due'];
88
                if ($canruntasks && ($stats['due'] > 0 || $stats['failed'] > 0)) {
89
                    $duecontent .= html_writer::div(
90
                        html_writer::link(
91
                            new moodle_url(
92
                                $adhocrunurl,
93
                                ['classname' => $classname]
94
                            ),
95
                            get_string('runclassname', 'tool_task')
96
                        ),
97
                        'task-runnow'
98
                    );
1441 ariadna 99
                    $duecontent .= html_writer::div(
100
                        html_writer::link(
101
                            new moodle_url(
102
                                $adhocrunurl,
103
                                ['classname' => $classname, 'dueonly' => 1]
104
                            ),
105
                            get_string('runclassnamedueonly', 'tool_task')
106
                        ),
107
                        'task-runnow'
108
                    );
1 efrain 109
                }
110
 
111
                // Mark cell if has failed tasks.
112
                $failed = $stats['failed'];
113
                if ($canruntasks && $failed > 0) {
114
                    $failed .= html_writer::div(
115
                        html_writer::link(
116
                            new moodle_url(
117
                                $adhocrunurl,
118
                                ['classname' => $classname, 'failedonly' => 1]
119
                            ),
120
                            get_string('runclassnamefailedonly', 'tool_task')
121
                        ),
122
                        'task-runnow'
123
                    );
124
                }
125
                $failedcell = new html_table_cell($failed);
126
                if ($failed > 0) {
127
                    $failedcell->attributes['class'] = 'table-danger';
128
                }
129
 
130
                // Prepares the next run time cell contents.
131
                $nextrun = '';
132
                if ($stats['stop']) {
133
                    $nextrun = get_string('never', 'admin');
134
                } else if ($stats['due'] > 0) {
135
                    $nextrun = get_string('asap', 'tool_task');
136
                } else if ($stats['nextruntime']) {
137
                    $nextrun = userdate($stats['nextruntime']);
138
                }
139
 
140
                $data[] = new html_table_row([
141
                    $classcell,
142
                    new html_table_cell($stats['running']),
143
                    new html_table_cell($duecontent),
144
                    new html_table_cell($stats['count'] - $stats['running'] - $stats['due']),
145
                    $failedcell,
146
                    new html_table_cell($nextrun),
147
                ]);
148
            }
149
        }
150
        $table->data = $data;
151
        return html_writer::table($table);
152
    }
153
 
154
    /**
155
     * This function will render a table with all the adhoc tasks for the class.
156
     *
157
     * @param string $classname
158
     * @param array $tasks - list of all adhoc tasks.
159
     * @param array|null $params
160
     * @return string HTML to output.
161
     */
162
    public function adhoc_tasks_class_table(string $classname, array $tasks, ?array $params = []): string {
163
        $adhocurl = '/admin/tool/task/adhoctasks.php';
164
        $adhocrunurl = '/admin/tool/task/run_adhoctasks.php';
165
        $showloglink = \core\task\logmanager::has_log_report();
166
        $failedonly = !empty($params['failedonly']);
167
        $canruntasks = \core\task\manager::is_runnable() && get_config('tool_task', 'enablerunnow');
168
 
169
        // Depending on the currently set parameters, set up toggle buttons.
170
        $failedorall = html_writer::link(
171
            new moodle_url(
172
                $adhocurl,
173
                array_merge($params, ['classname' => $classname, 'failedonly' => !$failedonly])
174
            ),
175
            get_string($failedonly ? 'showall' : 'showfailedonly', 'tool_task')
176
        );
177
 
178
        // Main tasks table.
179
        $table = $this->generate_adhoc_tasks_simple_table($tasks, $canruntasks);
180
 
181
        $table->caption = s($classname) . " "
182
            . get_string($failedonly ? 'adhoctasksfailed' : 'adhoctasks', 'tool_task');
183
        $table->head[3] .= " $failedorall"; // Spice up faildelay heading.
184
 
185
        if ($showloglink) {
186
            // Insert logs as the second col.
187
            array_splice($table->head, 1, 0, [get_string('logs')]);
188
            array_walk($table->data, function ($row, $idx) use ($classname) {
189
                $loglink = '';
190
                $faildelaycell = $row->cells[3];
191
                if ($faildelaycell->attributes['class'] == 'table-danger') {
192
                    // Failed task.
193
                    $loglink = $this->output->action_icon(
194
                        \core\task\logmanager::get_url_for_task_class($classname),
195
                        new pix_icon('e/file-text', get_string('viewlogs', 'tool_task', $classname)
196
                    ));
197
                }
198
 
199
                array_splice($row->cells, 1, 0, [new html_table_cell($loglink)]);
200
            });
201
        }
202
 
203
        return html_writer::table($table)
204
            . html_writer::div(
205
                html_writer::link(
206
                    new moodle_url(
207
                        $adhocrunurl,
208
                        array_merge($params, ['classname' => $classname])
209
                    ),
210
                    get_string('runclassname', 'tool_task')
211
                ),
212
                'task-runnow'
213
            )
214
            . html_writer::div(
215
                html_writer::link(
216
                    new moodle_url(
217
                        $adhocurl
218
                    ),
219
                    get_string('showsummary', 'tool_task')
220
                ),
221
                'task-show-summary'
222
            );
223
    }
224
 
225
    /**
226
     * This function will render a plain adhoc tasks table.
227
     *
228
     * @param array $tasks - list of adhoc tasks.
229
     * @return string HTML to output.
230
     */
231
    public function adhoc_tasks_simple_table(array $tasks): string {
232
        $table = $this->generate_adhoc_tasks_simple_table($tasks);
233
 
234
        return html_writer::table($table);
235
    }
236
 
237
    /**
238
     * This function will render a plain adhoc tasks table.
239
     *
240
     * @param array $tasks - list of adhoc tasks.
241
     * @param bool $wantruntasks add 'Run now' link
242
     * @return html_table
243
     */
244
    private function generate_adhoc_tasks_simple_table(array $tasks, bool $wantruntasks = false): html_table {
245
        $adhocrunurl = '/admin/tool/task/run_adhoctasks.php';
1441 ariadna 246
        $adhocdeleteurl = '/admin/tool/task/delete_adhoctasks.php';
1 efrain 247
        $now = time();
248
        $failedstr = get_string('failed', 'tool_task');
249
 
250
        // Main tasks table.
251
        $table = new html_table();
252
        $table->caption = get_string('adhoctasks', 'tool_task');
253
        $table->head = [
254
            get_string('taskid', 'tool_task'),
255
            get_string('nextruntime', 'tool_task'),
256
            get_string('payload', 'tool_task'),
1441 ariadna 257
            $failedstr,
258
            get_string('faildelay', 'tool_task'),
259
            get_string('actions','tool_task'),
1 efrain 260
        ];
261
 
262
        $table->attributes['class'] = 'generaltable';
263
        $table->colclasses = [];
264
 
265
        // For each task entry (row) show action buttons/logs link depending on the user permissions.
266
        $data = [];
267
        foreach ($tasks as $task) {
268
            $taskid = $task->get_id();
269
            $started = $task->get_timestarted();
270
 
271
            // Task id cell.
272
            $taskidcellcontent = html_writer::span($taskid, 'task-id');
273
            $taskidcell = new html_table_cell($taskidcellcontent);
274
            $taskidcell->header = true;
275
            $taskidcell->id = "task-$taskid";
276
 
277
            // Mark cell if task has failed.
278
            $faildelay = $task->get_fail_delay();
1441 ariadna 279
            $failedcell = new html_table_cell($faildelay ? $failedstr : '');
1 efrain 280
            if ($faildelay) {
1441 ariadna 281
                $failedcell->attributes['class'] = 'table-danger';
1 efrain 282
            }
283
 
284
            // Prepares the next run time cell contents.
285
            $nextrun = get_string('started', 'tool_task');
286
            if (!$started) {
287
                $nextruntime = $task->get_next_run_time();
288
                $due = $nextruntime < $now;
289
                if ($task->get_attempts_available() > 0) {
1441 ariadna 290
                    $nextrun = $due ? get_string('asap', 'tool_task') : userdate($nextruntime);
1 efrain 291
                } else {
292
                    $nextrun = get_string('never', 'admin');
293
                }
294
 
295
                if ($wantruntasks && ($faildelay || $due)) {
296
                    $nextrun .= ' '.html_writer::div(
297
                        html_writer::link(
298
                            new moodle_url(
299
                                $adhocrunurl,
300
                                ['id' => $taskid]
301
                            ),
302
                            get_string('runnow', 'tool_task')
303
                        ),
304
                        'task-runnow'
305
                    );
306
                }
307
            }
308
 
1441 ariadna 309
            // Create fail delay cell.
310
            $faildelaycellcontent = $faildelay;
311
            $faildelaycell = new html_table_cell($faildelaycellcontent);
312
 
313
            if ($faildelay) {
314
                $faildelaycell->attributes['class'] = 'table-danger';
315
            }
316
 
317
            // Add delete link with modal trigger.
318
            $deletelink = html_writer::link(
319
                new moodle_url($adhocdeleteurl, ['taskid' => $taskid, 'sesskey' => sesskey()]),
320
                get_string('delete'),
321
                [
322
                    'class' => 'btn btn-danger',
323
                    'role' => 'button',
324
                    'aria-label' => get_string('deleteadhoctask', 'tool_task', $taskid),
325
                    'data-confirmation' => 'modal',
326
                    'data-confirmation-type' => 'delete',
327
                    'data-confirmation-title-str' => '["deleteadhoctask", "tool_task", ' . $taskid . ']',
328
                    'data-confirmation-content-str' => '["confirmdeletetaskwithid", "tool_task", {"id":'.$taskid.'}]',
329
                    'data-confirmation-yes-button-str' => '["delete", "core"]',
330
                ]
331
            );
332
            $deletecell = new html_table_cell($deletelink);
333
 
1 efrain 334
            $data[] = new html_table_row([
335
                $taskidcell,
336
                new html_table_cell($nextrun),
337
                new html_table_cell($task->get_custom_data_as_string()),
1441 ariadna 338
                $failedcell,
1 efrain 339
                $faildelaycell,
1441 ariadna 340
                $deletecell,
1 efrain 341
            ]);
342
        }
343
        $table->data = $data;
344
 
345
        return $table;
346
    }
347
 
348
    /**
349
     * Displays a notification on ad hoc task run request.
350
     *
351
     * @return string HTML notification block for task initiated message
352
     */
353
    public function adhoc_task_run(): string {
354
        return $this->output->notification(get_string('adhoctaskrun', 'tool_task'), 'info');
355
    }
356
 
357
    /**
358
     * This function will render one beautiful table with all the scheduled tasks.
359
     *
360
     * @param \core\task\scheduled_task[] $tasks - list of all scheduled tasks.
361
     * @param string $lastchanged (optional) the last task edited. Gets highlighted in teh table.
362
     * @return string HTML to output.
363
     */
364
    public function scheduled_tasks_table($tasks, $lastchanged = '') {
365
        global $CFG;
366
 
367
        $showloglink = \core\task\logmanager::has_log_report();
368
 
369
        $table = new html_table();
370
        $table->caption = get_string('scheduledtasks', 'tool_task');
371
        $table->head = [
372
            get_string('name'),
373
            get_string('component', 'tool_task'),
374
            get_string('edit'),
375
            get_string('logs'),
376
            get_string('lastruntime', 'tool_task'),
377
            get_string('nextruntime', 'tool_task'),
378
            get_string('taskscheduleminute', 'tool_task'),
379
            get_string('taskschedulehour', 'tool_task'),
380
            get_string('taskscheduleday', 'tool_task'),
381
            get_string('taskscheduledayofweek', 'tool_task'),
382
            get_string('taskschedulemonth', 'tool_task'),
383
            get_string('faildelay', 'tool_task'),
384
            get_string('default', 'tool_task'),
385
        ];
386
 
387
        $table->attributes['class'] = 'admintable generaltable';
388
        $table->colclasses = [];
389
 
390
        if (!$showloglink) {
391
            // Hide the log links.
392
            $table->colclasses['3'] = 'hidden';
393
        }
394
 
395
        $data = [];
396
        $yes = get_string('yes');
397
        $no = get_string('no');
398
        $canruntasks = \core\task\manager::is_runnable() && get_config('tool_task', 'enablerunnow');
399
        foreach ($tasks as $task) {
400
            $classname = get_class($task);
401
            $defaulttask = \core\task\manager::get_default_scheduled_task($classname, false);
402
 
403
            $customised = $task->is_customised() ? $no : $yes;
404
            if (empty($CFG->preventscheduledtaskchanges) && !$task->is_overridden()) {
405
                $configureurl = new moodle_url('/admin/tool/task/scheduledtasks.php',
406
                        ['action' => 'edit', 'task' => $classname]);
407
                $editlink = $this->output->action_icon($configureurl, new pix_icon('t/edit',
408
                        get_string('edittaskschedule', 'tool_task', $task->get_name())));
409
            } else {
410
                $editlink = $this->render(new pix_icon('t/locked',
411
                        get_string('scheduledtaskchangesdisabled', 'tool_task')));
412
            }
413
 
414
            $loglink = '';
415
            if ($showloglink) {
416
                $loglink = $this->output->action_icon(
417
                    \core\task\logmanager::get_url_for_task_class($classname),
418
                    new pix_icon('e/file-text', get_string('viewlogs', 'tool_task', $task->get_name())
419
                ));
420
            }
421
 
422
            $namecellcontent = $task->get_name() . "\n" .
423
                html_writer::span('\\' . $classname, 'task-class text-ltr');
424
            if ($task->is_overridden()) {
425
                // Let the user know the scheduled task is defined in config.
426
                $namecellcontent .= "\n" . html_writer::div(get_string('configoverride', 'admin'), 'alert-info');
427
            }
428
            $namecell = new html_table_cell($namecellcontent);
429
            $namecell->header = true;
430
            $namecell->id = scheduled_task::get_html_id($classname);
431
 
432
            $runnow = '';
433
            $canrunthistask = $canruntasks && $task->can_run();
434
            if ($canrunthistask) {
435
                $runnow = html_writer::div(html_writer::link(
436
                        new moodle_url('/admin/tool/task/schedule_task.php',
437
                            ['task' => $classname]),
438
                        get_string('runnow', 'tool_task')), 'task-runnow');
439
            }
440
 
1441 ariadna 441
            if ($faildelay = $task->get_fail_delay()) {
442
                $faildelaycell = new html_table_cell(format_time($faildelay));
1 efrain 443
                $faildelaycell->text .= html_writer::div(
444
                    $this->output->single_button(
445
                        new moodle_url('/admin/tool/task/clear_fail_delay.php',
446
                                ['task' => $classname]),
447
                        get_string('clear')
448
                    ),
449
                    'task-runnow'
450
                );
451
                $faildelaycell->attributes['class'] = 'table-danger';
1441 ariadna 452
            } else {
453
                $faildelaycell = new html_table_cell(0);
1 efrain 454
            }
455
 
456
            $row = new html_table_row([
457
                        $namecell,
458
                        new html_table_cell($this->component_name($task->get_component())),
459
                        new html_table_cell($editlink),
460
                        new html_table_cell($loglink),
461
                        new html_table_cell($this->last_run_time($task) . $runnow),
462
                        new html_table_cell($this->next_run_time($task)),
463
                        $this->time_cell($task->get_minute(), $defaulttask->get_minute()),
464
                        $this->time_cell($task->get_hour(), $defaulttask->get_hour()),
465
                        $this->time_cell($task->get_day(), $defaulttask->get_day()),
466
                        $this->time_cell($task->get_day_of_week(), $defaulttask->get_day_of_week()),
467
                        $this->time_cell($task->get_month(), $defaulttask->get_month()),
468
                        $faildelaycell,
469
                        new html_table_cell($customised)]);
470
 
471
            $classes = [];
472
            if (!$task->is_enabled()) {
473
                $classes[] = 'disabled';
474
            }
475
            if (get_class($task) == $lastchanged) {
476
                $classes[] = 'table-primary';
477
            }
478
            $row->attributes['class'] = implode(' ', $classes);
479
            $data[] = $row;
480
        }
481
        $table->data = $data;
482
        if ($lastchanged) {
483
            // IE does not support this, and the ancient version of Firefox we use for Behat
484
            // has the method, but then errors on 'centre'. So, just try to scroll, and if it fails, don't care.
485
            $this->page->requires->js_init_code(
486
                    'try{document.querySelector("tr.table-primary").scrollIntoView({block: "center"});}catch(e){}');
487
        }
488
        return html_writer::table($table);
489
    }
490
 
491
    /**
492
     * Nicely display the name of a component, with its disabled status and internal name.
493
     *
494
     * @param string $component component name, e.g. 'core' or 'mod_forum'.
495
     * @return string HTML.
496
     */
497
    public function component_name(string $component): string {
498
        list($type) = core_component::normalize_component($component);
499
        if ($type === 'core') {
500
            return get_string('corecomponent', 'tool_task');
501
        }
502
 
503
        $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
504
        if (!$plugininfo) {
505
            return $component;
506
        }
507
 
508
        $plugininfo->init_display_name();
509
 
510
        $componentname = $plugininfo->displayname;
511
        if ($plugininfo->is_enabled() === false) {
512
            $componentname .= ' ' . html_writer::span(
513
                            get_string('disabled', 'tool_task'), 'badge bg-secondary text-dark');
514
        }
515
        $componentname .= "\n" . html_writer::span($plugininfo->component, 'task-class text-ltr');
516
 
517
        return $componentname;
518
    }
519
 
520
    /**
521
     * Standard display of a tasks last run time.
522
     *
523
     * @param scheduled_task $task
524
     * @return string HTML.
525
     */
526
    public function last_run_time(scheduled_task $task): string {
527
        if ($task->get_last_run_time()) {
528
            return userdate($task->get_last_run_time());
529
        } else {
530
            return get_string('never');
531
        }
532
    }
533
 
534
    /**
535
     * Standard display of a tasks next run time.
536
     *
537
     * @param scheduled_task $task
538
     * @return string HTML.
539
     */
540
    public function next_run_time(scheduled_task $task): string {
541
        $nextrun = $task->get_next_run_time();
542
 
543
        if (!$task->is_component_enabled() && !$task->get_run_if_component_disabled()) {
544
            $nextrun = get_string('plugindisabled', 'tool_task');
545
        } else if ($task->get_disabled()) {
546
            $nextrun = get_string('taskdisabled', 'tool_task');
547
        } else if ($nextrun > time()) {
548
            $nextrun = userdate($nextrun);
549
        } else {
550
            $nextrun = get_string('asap', 'tool_task');
551
        }
552
 
553
        return $nextrun;
554
    }
555
 
556
    /**
557
     * Get a table cell to show one time, comparing it to the default.
558
     *
559
     * @param string $current the current setting.
560
     * @param string $default the default setting from the db/tasks.php file.
561
     * @return html_table_cell for use in the table.
562
     */
563
    protected function time_cell(string $current, string $default): html_table_cell {
564
        $cell = new html_table_cell($current);
565
        // Cron-style values must always be LTR.
566
        $cell->attributes['class'] = 'text-ltr';
567
 
568
        // If the current value is default, that is all we want to do.
569
        if ($default === '*') {
570
            if ($current === '*') {
571
                return $cell;
572
            }
573
        } else if ($default === 'R' ) {
574
            if (is_numeric($current)) {
575
                return $cell;
576
            }
577
        } else {
578
            if ($default === $current) {
579
                return $cell;
580
            }
581
        }
582
 
583
        // Otherwise, highlight and show the default.
584
        $cell->attributes['class'] .= ' table-warning';
585
        $cell->text .= ' ' . html_writer::span(
586
                get_string('defaultx', 'tool_task', $default), 'task-class');
587
        return $cell;
588
    }
589
 
590
    /**
591
     * Displays a warning on the page if cron is disabled.
592
     *
593
     * @return string HTML code for information about cron being disabled
594
     * @throws moodle_exception
595
     */
596
    public function cron_disabled(): string {
597
        return $this->output->notification(get_string('crondisabled', 'tool_task'), 'warning');
598
    }
599
 
600
    /**
601
     * Renders a link back to the scheduled tasks page (used from the 'run now' screen).
602
     *
603
     * @param string $taskclassname if specified, the list of tasks will scroll to show this task.
604
     * @return string HTML code
605
     */
606
    public function link_back($taskclassname = '') {
607
        $url = new moodle_url('/admin/tool/task/scheduledtasks.php');
608
        if ($taskclassname) {
609
            $url->param('lastchanged', $taskclassname);
610
        }
611
        return $this->render_from_template('tool_task/link_back', ['url' => $url]);
612
    }
613
}