Proyectos de Subversion Moodle

Rev

| 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
                    );
99
                }
100
 
101
                // Mark cell if has failed tasks.
102
                $failed = $stats['failed'];
103
                if ($canruntasks && $failed > 0) {
104
                    $failed .= html_writer::div(
105
                        html_writer::link(
106
                            new moodle_url(
107
                                $adhocrunurl,
108
                                ['classname' => $classname, 'failedonly' => 1]
109
                            ),
110
                            get_string('runclassnamefailedonly', 'tool_task')
111
                        ),
112
                        'task-runnow'
113
                    );
114
                }
115
                $failedcell = new html_table_cell($failed);
116
                if ($failed > 0) {
117
                    $failedcell->attributes['class'] = 'table-danger';
118
                }
119
 
120
                // Prepares the next run time cell contents.
121
                $nextrun = '';
122
                if ($stats['stop']) {
123
                    $nextrun = get_string('never', 'admin');
124
                } else if ($stats['due'] > 0) {
125
                    $nextrun = get_string('asap', 'tool_task');
126
                } else if ($stats['nextruntime']) {
127
                    $nextrun = userdate($stats['nextruntime']);
128
                }
129
 
130
                $data[] = new html_table_row([
131
                    $classcell,
132
                    new html_table_cell($stats['running']),
133
                    new html_table_cell($duecontent),
134
                    new html_table_cell($stats['count'] - $stats['running'] - $stats['due']),
135
                    $failedcell,
136
                    new html_table_cell($nextrun),
137
                ]);
138
            }
139
        }
140
        $table->data = $data;
141
        return html_writer::table($table);
142
    }
143
 
144
    /**
145
     * This function will render a table with all the adhoc tasks for the class.
146
     *
147
     * @param string $classname
148
     * @param array $tasks - list of all adhoc tasks.
149
     * @param array|null $params
150
     * @return string HTML to output.
151
     */
152
    public function adhoc_tasks_class_table(string $classname, array $tasks, ?array $params = []): string {
153
        $adhocurl = '/admin/tool/task/adhoctasks.php';
154
        $adhocrunurl = '/admin/tool/task/run_adhoctasks.php';
155
        $showloglink = \core\task\logmanager::has_log_report();
156
        $failedonly = !empty($params['failedonly']);
157
        $canruntasks = \core\task\manager::is_runnable() && get_config('tool_task', 'enablerunnow');
158
 
159
        // Depending on the currently set parameters, set up toggle buttons.
160
        $failedorall = html_writer::link(
161
            new moodle_url(
162
                $adhocurl,
163
                array_merge($params, ['classname' => $classname, 'failedonly' => !$failedonly])
164
            ),
165
            get_string($failedonly ? 'showall' : 'showfailedonly', 'tool_task')
166
        );
167
 
168
        // Main tasks table.
169
        $table = $this->generate_adhoc_tasks_simple_table($tasks, $canruntasks);
170
 
171
        $table->caption = s($classname) . " "
172
            . get_string($failedonly ? 'adhoctasksfailed' : 'adhoctasks', 'tool_task');
173
        $table->head[3] .= " $failedorall"; // Spice up faildelay heading.
174
 
175
        if ($showloglink) {
176
            // Insert logs as the second col.
177
            array_splice($table->head, 1, 0, [get_string('logs')]);
178
            array_walk($table->data, function ($row, $idx) use ($classname) {
179
                $loglink = '';
180
                $faildelaycell = $row->cells[3];
181
                if ($faildelaycell->attributes['class'] == 'table-danger') {
182
                    // Failed task.
183
                    $loglink = $this->output->action_icon(
184
                        \core\task\logmanager::get_url_for_task_class($classname),
185
                        new pix_icon('e/file-text', get_string('viewlogs', 'tool_task', $classname)
186
                    ));
187
                }
188
 
189
                array_splice($row->cells, 1, 0, [new html_table_cell($loglink)]);
190
            });
191
        }
192
 
193
        return html_writer::table($table)
194
            . html_writer::div(
195
                html_writer::link(
196
                    new moodle_url(
197
                        $adhocrunurl,
198
                        array_merge($params, ['classname' => $classname])
199
                    ),
200
                    get_string('runclassname', 'tool_task')
201
                ),
202
                'task-runnow'
203
            )
204
            . html_writer::div(
205
                html_writer::link(
206
                    new moodle_url(
207
                        $adhocurl
208
                    ),
209
                    get_string('showsummary', 'tool_task')
210
                ),
211
                'task-show-summary'
212
            );
213
    }
214
 
215
    /**
216
     * This function will render a plain adhoc tasks table.
217
     *
218
     * @param array $tasks - list of adhoc tasks.
219
     * @return string HTML to output.
220
     */
221
    public function adhoc_tasks_simple_table(array $tasks): string {
222
        $table = $this->generate_adhoc_tasks_simple_table($tasks);
223
 
224
        return html_writer::table($table);
225
    }
226
 
227
    /**
228
     * This function will render a plain adhoc tasks table.
229
     *
230
     * @param array $tasks - list of adhoc tasks.
231
     * @param bool $wantruntasks add 'Run now' link
232
     * @return html_table
233
     */
234
    private function generate_adhoc_tasks_simple_table(array $tasks, bool $wantruntasks = false): html_table {
235
        $adhocrunurl = '/admin/tool/task/run_adhoctasks.php';
236
        $now = time();
237
        $failedstr = get_string('failed', 'tool_task');
238
 
239
        // Main tasks table.
240
        $table = new html_table();
241
        $table->caption = get_string('adhoctasks', 'tool_task');
242
        $table->head = [
243
            get_string('taskid', 'tool_task'),
244
            get_string('nextruntime', 'tool_task'),
245
            get_string('payload', 'tool_task'),
246
            $failedstr
247
        ];
248
 
249
        $table->attributes['class'] = 'generaltable';
250
        $table->colclasses = [];
251
 
252
        // For each task entry (row) show action buttons/logs link depending on the user permissions.
253
        $data = [];
254
        foreach ($tasks as $task) {
255
            $taskid = $task->get_id();
256
            $started = $task->get_timestarted();
257
 
258
            // Task id cell.
259
            $taskidcellcontent = html_writer::span($taskid, 'task-id');
260
            $taskidcell = new html_table_cell($taskidcellcontent);
261
            $taskidcell->header = true;
262
            $taskidcell->id = "task-$taskid";
263
 
264
            // Mark cell if task has failed.
265
            $faildelay = $task->get_fail_delay();
266
            $faildelaycell = new html_table_cell($faildelay ? $failedstr : '');
267
            if ($faildelay) {
268
                $faildelaycell->attributes['class'] = 'table-danger';
269
            }
270
 
271
            // Prepares the next run time cell contents.
272
            $nextrun = get_string('started', 'tool_task');
273
            if (!$started) {
274
                $nextruntime = $task->get_next_run_time();
275
                $due = $nextruntime < $now;
276
                if ($task->get_attempts_available() > 0) {
277
                    $nextrun = $due ? userdate($nextruntime) : get_string('asap', 'tool_task');
278
                } else {
279
                    $nextrun = get_string('never', 'admin');
280
                }
281
 
282
                if ($wantruntasks && ($faildelay || $due)) {
283
                    $nextrun .= ' '.html_writer::div(
284
                        html_writer::link(
285
                            new moodle_url(
286
                                $adhocrunurl,
287
                                ['id' => $taskid]
288
                            ),
289
                            get_string('runnow', 'tool_task')
290
                        ),
291
                        'task-runnow'
292
                    );
293
                }
294
            }
295
 
296
            $data[] = new html_table_row([
297
                $taskidcell,
298
                new html_table_cell($nextrun),
299
                new html_table_cell($task->get_custom_data_as_string()),
300
                $faildelaycell,
301
            ]);
302
        }
303
        $table->data = $data;
304
 
305
        return $table;
306
    }
307
 
308
    /**
309
     * Displays a notification on ad hoc task run request.
310
     *
311
     * @return string HTML notification block for task initiated message
312
     */
313
    public function adhoc_task_run(): string {
314
        return $this->output->notification(get_string('adhoctaskrun', 'tool_task'), 'info');
315
    }
316
 
317
    /**
318
     * This function will render one beautiful table with all the scheduled tasks.
319
     *
320
     * @param \core\task\scheduled_task[] $tasks - list of all scheduled tasks.
321
     * @param string $lastchanged (optional) the last task edited. Gets highlighted in teh table.
322
     * @return string HTML to output.
323
     */
324
    public function scheduled_tasks_table($tasks, $lastchanged = '') {
325
        global $CFG;
326
 
327
        $showloglink = \core\task\logmanager::has_log_report();
328
 
329
        $table = new html_table();
330
        $table->caption = get_string('scheduledtasks', 'tool_task');
331
        $table->head = [
332
            get_string('name'),
333
            get_string('component', 'tool_task'),
334
            get_string('edit'),
335
            get_string('logs'),
336
            get_string('lastruntime', 'tool_task'),
337
            get_string('nextruntime', 'tool_task'),
338
            get_string('taskscheduleminute', 'tool_task'),
339
            get_string('taskschedulehour', 'tool_task'),
340
            get_string('taskscheduleday', 'tool_task'),
341
            get_string('taskscheduledayofweek', 'tool_task'),
342
            get_string('taskschedulemonth', 'tool_task'),
343
            get_string('faildelay', 'tool_task'),
344
            get_string('default', 'tool_task'),
345
        ];
346
 
347
        $table->attributes['class'] = 'admintable generaltable';
348
        $table->colclasses = [];
349
 
350
        if (!$showloglink) {
351
            // Hide the log links.
352
            $table->colclasses['3'] = 'hidden';
353
        }
354
 
355
        $data = [];
356
        $yes = get_string('yes');
357
        $no = get_string('no');
358
        $canruntasks = \core\task\manager::is_runnable() && get_config('tool_task', 'enablerunnow');
359
        foreach ($tasks as $task) {
360
            $classname = get_class($task);
361
            $defaulttask = \core\task\manager::get_default_scheduled_task($classname, false);
362
 
363
            $customised = $task->is_customised() ? $no : $yes;
364
            if (empty($CFG->preventscheduledtaskchanges) && !$task->is_overridden()) {
365
                $configureurl = new moodle_url('/admin/tool/task/scheduledtasks.php',
366
                        ['action' => 'edit', 'task' => $classname]);
367
                $editlink = $this->output->action_icon($configureurl, new pix_icon('t/edit',
368
                        get_string('edittaskschedule', 'tool_task', $task->get_name())));
369
            } else {
370
                $editlink = $this->render(new pix_icon('t/locked',
371
                        get_string('scheduledtaskchangesdisabled', 'tool_task')));
372
            }
373
 
374
            $loglink = '';
375
            if ($showloglink) {
376
                $loglink = $this->output->action_icon(
377
                    \core\task\logmanager::get_url_for_task_class($classname),
378
                    new pix_icon('e/file-text', get_string('viewlogs', 'tool_task', $task->get_name())
379
                ));
380
            }
381
 
382
            $namecellcontent = $task->get_name() . "\n" .
383
                html_writer::span('\\' . $classname, 'task-class text-ltr');
384
            if ($task->is_overridden()) {
385
                // Let the user know the scheduled task is defined in config.
386
                $namecellcontent .= "\n" . html_writer::div(get_string('configoverride', 'admin'), 'alert-info');
387
            }
388
            $namecell = new html_table_cell($namecellcontent);
389
            $namecell->header = true;
390
            $namecell->id = scheduled_task::get_html_id($classname);
391
 
392
            $runnow = '';
393
            $canrunthistask = $canruntasks && $task->can_run();
394
            if ($canrunthistask) {
395
                $runnow = html_writer::div(html_writer::link(
396
                        new moodle_url('/admin/tool/task/schedule_task.php',
397
                            ['task' => $classname]),
398
                        get_string('runnow', 'tool_task')), 'task-runnow');
399
            }
400
 
401
            $faildelaycell = new html_table_cell($task->get_fail_delay());
402
            if ($task->get_fail_delay()) {
403
                $faildelaycell->text .= html_writer::div(
404
                    $this->output->single_button(
405
                        new moodle_url('/admin/tool/task/clear_fail_delay.php',
406
                                ['task' => $classname]),
407
                        get_string('clear')
408
                    ),
409
                    'task-runnow'
410
                );
411
                $faildelaycell->attributes['class'] = 'table-danger';
412
            }
413
 
414
            $row = new html_table_row([
415
                        $namecell,
416
                        new html_table_cell($this->component_name($task->get_component())),
417
                        new html_table_cell($editlink),
418
                        new html_table_cell($loglink),
419
                        new html_table_cell($this->last_run_time($task) . $runnow),
420
                        new html_table_cell($this->next_run_time($task)),
421
                        $this->time_cell($task->get_minute(), $defaulttask->get_minute()),
422
                        $this->time_cell($task->get_hour(), $defaulttask->get_hour()),
423
                        $this->time_cell($task->get_day(), $defaulttask->get_day()),
424
                        $this->time_cell($task->get_day_of_week(), $defaulttask->get_day_of_week()),
425
                        $this->time_cell($task->get_month(), $defaulttask->get_month()),
426
                        $faildelaycell,
427
                        new html_table_cell($customised)]);
428
 
429
            $classes = [];
430
            if (!$task->is_enabled()) {
431
                $classes[] = 'disabled';
432
            }
433
            if (get_class($task) == $lastchanged) {
434
                $classes[] = 'table-primary';
435
            }
436
            $row->attributes['class'] = implode(' ', $classes);
437
            $data[] = $row;
438
        }
439
        $table->data = $data;
440
        if ($lastchanged) {
441
            // IE does not support this, and the ancient version of Firefox we use for Behat
442
            // has the method, but then errors on 'centre'. So, just try to scroll, and if it fails, don't care.
443
            $this->page->requires->js_init_code(
444
                    'try{document.querySelector("tr.table-primary").scrollIntoView({block: "center"});}catch(e){}');
445
        }
446
        return html_writer::table($table);
447
    }
448
 
449
    /**
450
     * Nicely display the name of a component, with its disabled status and internal name.
451
     *
452
     * @param string $component component name, e.g. 'core' or 'mod_forum'.
453
     * @return string HTML.
454
     */
455
    public function component_name(string $component): string {
456
        list($type) = core_component::normalize_component($component);
457
        if ($type === 'core') {
458
            return get_string('corecomponent', 'tool_task');
459
        }
460
 
461
        $plugininfo = core_plugin_manager::instance()->get_plugin_info($component);
462
        if (!$plugininfo) {
463
            return $component;
464
        }
465
 
466
        $plugininfo->init_display_name();
467
 
468
        $componentname = $plugininfo->displayname;
469
        if ($plugininfo->is_enabled() === false) {
470
            $componentname .= ' ' . html_writer::span(
471
                            get_string('disabled', 'tool_task'), 'badge bg-secondary text-dark');
472
        }
473
        $componentname .= "\n" . html_writer::span($plugininfo->component, 'task-class text-ltr');
474
 
475
        return $componentname;
476
    }
477
 
478
    /**
479
     * Standard display of a tasks last run time.
480
     *
481
     * @param scheduled_task $task
482
     * @return string HTML.
483
     */
484
    public function last_run_time(scheduled_task $task): string {
485
        if ($task->get_last_run_time()) {
486
            return userdate($task->get_last_run_time());
487
        } else {
488
            return get_string('never');
489
        }
490
    }
491
 
492
    /**
493
     * Standard display of a tasks next run time.
494
     *
495
     * @param scheduled_task $task
496
     * @return string HTML.
497
     */
498
    public function next_run_time(scheduled_task $task): string {
499
        $nextrun = $task->get_next_run_time();
500
 
501
        if (!$task->is_component_enabled() && !$task->get_run_if_component_disabled()) {
502
            $nextrun = get_string('plugindisabled', 'tool_task');
503
        } else if ($task->get_disabled()) {
504
            $nextrun = get_string('taskdisabled', 'tool_task');
505
        } else if ($nextrun > time()) {
506
            $nextrun = userdate($nextrun);
507
        } else {
508
            $nextrun = get_string('asap', 'tool_task');
509
        }
510
 
511
        return $nextrun;
512
    }
513
 
514
    /**
515
     * Get a table cell to show one time, comparing it to the default.
516
     *
517
     * @param string $current the current setting.
518
     * @param string $default the default setting from the db/tasks.php file.
519
     * @return html_table_cell for use in the table.
520
     */
521
    protected function time_cell(string $current, string $default): html_table_cell {
522
        $cell = new html_table_cell($current);
523
        // Cron-style values must always be LTR.
524
        $cell->attributes['class'] = 'text-ltr';
525
 
526
        // If the current value is default, that is all we want to do.
527
        if ($default === '*') {
528
            if ($current === '*') {
529
                return $cell;
530
            }
531
        } else if ($default === 'R' ) {
532
            if (is_numeric($current)) {
533
                return $cell;
534
            }
535
        } else {
536
            if ($default === $current) {
537
                return $cell;
538
            }
539
        }
540
 
541
        // Otherwise, highlight and show the default.
542
        $cell->attributes['class'] .= ' table-warning';
543
        $cell->text .= ' ' . html_writer::span(
544
                get_string('defaultx', 'tool_task', $default), 'task-class');
545
        return $cell;
546
    }
547
 
548
    /**
549
     * Displays a warning on the page if cron is disabled.
550
     *
551
     * @return string HTML code for information about cron being disabled
552
     * @throws moodle_exception
553
     */
554
    public function cron_disabled(): string {
555
        return $this->output->notification(get_string('crondisabled', 'tool_task'), 'warning');
556
    }
557
 
558
    /**
559
     * Renders a link back to the scheduled tasks page (used from the 'run now' screen).
560
     *
561
     * @param string $taskclassname if specified, the list of tasks will scroll to show this task.
562
     * @return string HTML code
563
     */
564
    public function link_back($taskclassname = '') {
565
        $url = new moodle_url('/admin/tool/task/scheduledtasks.php');
566
        if ($taskclassname) {
567
            $url->param('lastchanged', $taskclassname);
568
        }
569
        return $this->render_from_template('tool_task/link_back', ['url' => $url]);
570
    }
571
}