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
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * This file contains functions used by the log reports
19
 *
20
 * This files lists the functions that are used during the log report generation.
21
 *
22
 * @package    report_log
23
 * @copyright  1999 onwards Martin Dougiamas (http://dougiamas.com)
24
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25
 */
26
 
27
defined('MOODLE_INTERNAL') || die;
28
 
29
if (!defined('REPORT_LOG_MAX_DISPLAY')) {
30
    define('REPORT_LOG_MAX_DISPLAY', 150); // days
31
}
32
 
33
require_once(__DIR__.'/lib.php');
34
 
35
/**
36
 * This function is used to generate and display the log activity graph
37
 *
38
 * @global stdClass $CFG
39
 * @param  stdClass $course course instance
40
 * @param  int|stdClass    $user id/object of the user whose logs are needed
41
 * @param  string $typeormode type of logs graph needed (usercourse.png/userday.png) or the mode (today, all).
42
 * @param  int $date timestamp in GMT (seconds since epoch)
43
 * @param  string $logreader Log reader.
1441 ariadna 44
 * @param  int $sitecoursefilter use a course filter in site context.
1 efrain 45
 * @return void
46
 */
1441 ariadna 47
function report_log_print_graph($course, $user, $typeormode, $date=0, $logreader='', $sitecoursefilter = 0) {
1 efrain 48
    global $CFG, $OUTPUT;
49
 
50
    if (!is_object($user)) {
51
        $user = core_user::get_user($user);
52
    }
53
 
54
    $logmanager = get_log_manager();
55
    $readers = $logmanager->get_readers();
56
 
57
    if (empty($logreader)) {
58
        $reader = reset($readers);
59
    } else {
60
        $reader = $readers[$logreader];
61
    }
62
    // If reader is not a sql_internal_table_reader and not legacy store then don't show graph.
63
    if (!($reader instanceof \core\log\sql_internal_table_reader)) {
64
        return array();
65
    }
66
    $coursecontext = context_course::instance($course->id);
67
 
68
    $a = new stdClass();
69
    $a->coursename = format_string($course->shortname, true, array('context' => $coursecontext));
70
    $a->username = fullname($user, true);
71
 
72
    if ($typeormode == 'today' || $typeormode == 'userday.png') {
1441 ariadna 73
        $logs = report_log_usertoday_data($course, $user, $date, $logreader, $sitecoursefilter);
1 efrain 74
        $title = get_string("hitsoncoursetoday", "", $a);
75
    } else if ($typeormode == 'all' || $typeormode == 'usercourse.png') {
1441 ariadna 76
        $logs = report_log_userall_data($course, $user, $logreader, $sitecoursefilter);
1 efrain 77
        $title = get_string("hitsoncourse", "", $a);
78
    }
79
 
80
    if (!empty($CFG->preferlinegraphs)) {
81
        $chart = new \core\chart_line();
82
    } else {
83
        $chart = new \core\chart_bar();
84
    }
85
 
86
    $series = new \core\chart_series(get_string("hits"), $logs['series']);
87
    $chart->add_series($series);
88
    $chart->set_title($title);
89
    $chart->set_labels($logs['labels']);
90
    $yaxis = $chart->get_yaxis(0, true);
91
    $yaxis->set_label(get_string("hits"));
92
    $yaxis->set_stepsize(max(1, round(max($logs['series']) / 10)));
93
 
94
    echo $OUTPUT->render($chart);
95
}
96
 
97
/**
98
 * Select all log records for a given course and user
99
 *
100
 * @param int $userid The id of the user as found in the 'user' table.
101
 * @param int $courseid The id of the course as found in the 'course' table.
102
 * @param string $coursestart unix timestamp representing course start date and time.
103
 * @param string $logreader log reader to use.
104
 * @return array
105
 */
106
function report_log_usercourse($userid, $courseid, $coursestart, $logreader = '') {
107
    global $DB;
108
 
109
    $logmanager = get_log_manager();
110
    $readers = $logmanager->get_readers();
111
    if (empty($logreader)) {
112
        $reader = reset($readers);
113
    } else {
114
        $reader = $readers[$logreader];
115
    }
116
 
117
    // If reader is not a sql_internal_table_reader and not legacy store then return.
118
    if (!($reader instanceof \core\log\sql_internal_table_reader)) {
119
        return array();
120
    }
121
 
122
    $coursestart = (int)$coursestart; // Note: unfortunately pg complains if you use name parameter or column alias in GROUP BY.
123
    $logtable = $reader->get_internal_log_table_name();
124
    $timefield = 'timecreated';
125
    $coursefield = 'courseid';
126
    $nonanonymous = 'AND anonymous = 0';
127
 
128
    $params = array();
129
    $courseselect = '';
130
    if ($courseid) {
131
        $courseselect = "AND $coursefield = :courseid";
132
        $params['courseid'] = $courseid;
133
    }
134
    $params['userid'] = $userid;
135
    return $DB->get_records_sql("SELECT FLOOR(($timefield - $coursestart)/" . DAYSECS . ") AS day, COUNT(*) AS num
136
                                   FROM {" . $logtable . "}
137
                                  WHERE userid = :userid
138
                                        AND $timefield > $coursestart $courseselect $nonanonymous
139
                               GROUP BY FLOOR(($timefield - $coursestart)/" . DAYSECS .")", $params);
140
}
141
 
142
/**
143
 * Select all log records for a given course, user, and day
144
 *
145
 * @param int $userid The id of the user as found in the 'user' table.
146
 * @param int $courseid The id of the course as found in the 'course' table.
147
 * @param string $daystart unix timestamp of the start of the day for which the logs needs to be retrived
148
 * @param string $logreader log reader to use.
149
 * @return array
150
 */
151
function report_log_userday($userid, $courseid, $daystart, $logreader = '') {
152
    global $DB;
153
    $logmanager = get_log_manager();
154
    $readers = $logmanager->get_readers();
155
    if (empty($logreader)) {
156
        $reader = reset($readers);
157
    } else {
158
        $reader = $readers[$logreader];
159
    }
160
 
161
    // If reader is not a sql_internal_table_reader and not legacy store then return.
162
    if (!($reader instanceof \core\log\sql_internal_table_reader)) {
163
        return array();
164
    }
165
 
166
    $daystart = (int)$daystart; // Note: unfortunately pg complains if you use name parameter or column alias in GROUP BY.
167
 
168
    $logtable = $reader->get_internal_log_table_name();
169
    $timefield = 'timecreated';
170
    $coursefield = 'courseid';
171
    $nonanonymous = 'AND anonymous = 0';
172
    $params = array('userid' => $userid);
173
 
174
    $courseselect = '';
175
    if ($courseid) {
176
        $courseselect = "AND $coursefield = :courseid";
177
        $params['courseid'] = $courseid;
178
    }
179
    return $DB->get_records_sql("SELECT FLOOR(($timefield - $daystart)/" . HOURSECS . ") AS hour, COUNT(*) AS num
180
                                   FROM {" . $logtable . "}
181
                                  WHERE userid = :userid
182
                                        AND $timefield > $daystart $courseselect $nonanonymous
183
                               GROUP BY FLOOR(($timefield - $daystart)/" . HOURSECS . ") ", $params);
184
}
185
 
186
/**
187
 * This function is used to generate and display Mnet selector form
188
 *
189
 * @global stdClass $USER
190
 * @global stdClass $CFG
191
 * @global stdClass $SITE
192
 * @global moodle_database $DB
193
 * @global core_renderer $OUTPUT
194
 * @global stdClass $SESSION
195
 * @uses CONTEXT_SYSTEM
196
 * @uses COURSE_MAX_COURSES_PER_DROPDOWN
197
 * @uses CONTEXT_COURSE
198
 * @uses SEPARATEGROUPS
199
 * @param  int      $hostid host id
200
 * @param  stdClass $course course instance
201
 * @param  int      $selecteduser id of the selected user
202
 * @param  string   $selecteddate Date selected
203
 * @param  string   $modname course_module->id
204
 * @param  string   $modid number or 'site_errors'
205
 * @param  string   $modaction an action as recorded in the logs
206
 * @param  int      $selectedgroup Group to display
207
 * @param  int      $showcourses whether to show courses if we're over our limit.
208
 * @param  int      $showusers whether to show users if we're over our limit.
209
 * @param  string   $logformat Format of the logs (downloadascsv, showashtml, downloadasods, downloadasexcel)
210
 * @return void
211
 */
212
function report_log_print_mnet_selector_form($hostid, $course, $selecteduser=0, $selecteddate='today',
213
                                 $modname="", $modid=0, $modaction='', $selectedgroup=-1, $showcourses=0, $showusers=0, $logformat='showashtml') {
214
 
215
    global $USER, $CFG, $SITE, $DB, $OUTPUT, $SESSION;
216
    require_once $CFG->dirroot.'/mnet/peer.php';
217
 
218
    $mnet_peer = new mnet_peer();
219
    $mnet_peer->set_id($hostid);
220
 
221
    $sql = "SELECT DISTINCT course, hostid, coursename FROM {mnet_log}";
222
    $courses = $DB->get_records_sql($sql);
223
    $remotecoursecount = count($courses);
224
 
225
    // first check to see if we can override showcourses and showusers
226
    $numcourses = $remotecoursecount + $DB->count_records('course');
227
    if ($numcourses < COURSE_MAX_COURSES_PER_DROPDOWN && !$showcourses) {
228
        $showcourses = 1;
229
    }
230
 
231
    $sitecontext = context_system::instance();
232
 
233
    // Context for remote data is always SITE
234
    // Groups for remote data are always OFF
235
    if ($hostid == $CFG->mnet_localhost_id) {
236
        $context = context_course::instance($course->id);
237
 
238
        /// Setup for group handling.
239
        if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
240
            $selectedgroup = -1;
241
            $showgroups = false;
242
        } else if ($course->groupmode) {
243
            $showgroups = true;
244
        } else {
245
            $selectedgroup = 0;
246
            $showgroups = false;
247
        }
248
 
249
        if ($selectedgroup === -1) {
250
            if (isset($SESSION->currentgroup[$course->id])) {
251
                $selectedgroup =  $SESSION->currentgroup[$course->id];
252
            } else {
253
                $selectedgroup = groups_get_all_groups($course->id, $USER->id);
254
                if (is_array($selectedgroup)) {
255
                    $selectedgroup = array_shift(array_keys($selectedgroup));
256
                    $SESSION->currentgroup[$course->id] = $selectedgroup;
257
                } else {
258
                    $selectedgroup = 0;
259
                }
260
            }
261
        }
262
 
263
    } else {
264
        $context = $sitecontext;
265
    }
266
 
267
    // Get all the possible users
268
    $users = array();
269
 
270
    // Define limitfrom and limitnum for queries below
271
    // If $showusers is enabled... don't apply limitfrom and limitnum
272
    $limitfrom = empty($showusers) ? 0 : '';
273
    $limitnum  = empty($showusers) ? COURSE_MAX_USERS_PER_DROPDOWN + 1 : '';
274
 
275
    // If looking at a different host, we're interested in all our site users
276
    if ($hostid == $CFG->mnet_localhost_id && $course->id != SITEID) {
277
        $userfieldsapi = \core_user\fields::for_name();
278
        $courseusers = get_enrolled_users($context, '', $selectedgroup, 'u.id, ' .
279
                $userfieldsapi->get_sql('u', false, '', '', false)->selects,
280
                null, $limitfrom, $limitnum);
281
    } else {
282
        // this may be a lot of users :-(
283
        $userfieldsapi = \core_user\fields::for_name();
284
        $courseusers = $DB->get_records('user', array('deleted' => 0), 'lastaccess DESC', 'id, ' .
285
                $userfieldsapi->get_sql('', false, '', '', false)->selects,
286
                $limitfrom, $limitnum);
287
    }
288
 
289
    if (count($courseusers) < COURSE_MAX_USERS_PER_DROPDOWN && !$showusers) {
290
        $showusers = 1;
291
    }
292
 
293
    if ($showusers) {
294
        if ($courseusers) {
295
            foreach ($courseusers as $courseuser) {
296
                $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', $context));
297
            }
298
        }
299
        $users[$CFG->siteguest] = get_string('guestuser');
300
    }
301
 
302
    // Get all the hosts that have log records
303
    $sql = "select distinct
304
                h.id,
305
                h.name
306
            from
307
                {mnet_host} h,
308
                {mnet_log} l
309
            where
310
                h.id = l.hostid
311
            order by
312
                h.name";
313
 
314
    if ($hosts = $DB->get_records_sql($sql)) {
315
        foreach($hosts as $host) {
316
            $hostarray[$host->id] = $host->name;
317
        }
318
    }
319
 
320
    $hostarray[$CFG->mnet_localhost_id] = $SITE->fullname;
321
    asort($hostarray);
322
 
323
    $dropdown = array();
324
 
325
    foreach($hostarray as $hostid => $name) {
326
        $courses = array();
327
        $sites = array();
328
        if ($CFG->mnet_localhost_id == $hostid) {
329
            if (has_capability('report/log:view', $sitecontext) && $showcourses) {
330
                if ($ccc = $DB->get_records("course", null, "fullname","id,shortname,fullname,category")) {
331
                    foreach ($ccc as $cc) {
332
                        if ($cc->id == SITEID) {
333
                            $sites["$hostid/$cc->id"]   = format_string($cc->fullname).' ('.get_string('site').')';
334
                        } else {
335
                            $courses["$hostid/$cc->id"] = format_string(get_course_display_name_for_list($cc));
336
                        }
337
                    }
338
                }
339
            }
340
        } else {
341
            if (has_capability('report/log:view', $sitecontext) && $showcourses) {
342
                $sql = "SELECT DISTINCT course, coursename FROM {mnet_log} where hostid = ?";
343
                if ($ccc = $DB->get_records_sql($sql, array($hostid))) {
344
                    foreach ($ccc as $cc) {
345
                        if (1 == $cc->course) { // TODO: this might be wrong - site course may have another id
346
                            $sites["$hostid/$cc->course"]   = $cc->coursename.' ('.get_string('site').')';
347
                        } else {
348
                            $courses["$hostid/$cc->course"] = $cc->coursename;
349
                        }
350
                    }
351
                }
352
            }
353
        }
354
 
355
        asort($courses);
356
        $dropdown[] = array($name=>($sites + $courses));
357
    }
358
 
359
 
360
    $activities = array();
361
    $selectedactivity = "";
362
 
363
    $modinfo = get_fast_modinfo($course);
364
    if (!empty($modinfo->cms)) {
365
        $section = 0;
366
        $thissection = array();
367
        foreach ($modinfo->cms as $cm) {
368
            // Exclude activities that aren't visible or have no view link (e.g. label). Account for folder being displayed inline.
369
            if (!$cm->uservisible || (!$cm->has_view() && strcmp($cm->modname, 'folder') !== 0)) {
370
                continue;
371
            }
372
            if ($cm->sectionnum > 0 and $section <> $cm->sectionnum) {
373
                $activities[] = $thissection;
374
                $thissection = array();
375
            }
376
            $section = $cm->sectionnum;
377
            $modname = strip_tags($cm->get_formatted_name());
378
            if (core_text::strlen($modname) > 55) {
379
                $modname = core_text::substr($modname, 0, 50)."...";
380
            }
381
            if (!$cm->visible) {
382
                $modname = "(".$modname.")";
383
            }
384
            $key = get_section_name($course, $cm->sectionnum);
385
            if (!isset($thissection[$key])) {
386
                $thissection[$key] = array();
387
            }
388
            $thissection[$key][$cm->id] = $modname;
389
 
390
            if ($cm->id == $modid) {
391
                $selectedactivity = "$cm->id";
392
            }
393
        }
394
        if (!empty($thissection)) {
395
            $activities[] = $thissection;
396
        }
397
    }
398
 
399
    if (has_capability('report/log:view', $sitecontext) && !$course->category) {
400
        $activities["site_errors"] = get_string("siteerrors");
401
        if ($modid === "site_errors") {
402
            $selectedactivity = "site_errors";
403
        }
404
    }
405
 
406
    $strftimedate = get_string("strftimedate");
407
    $strftimedaydate = get_string("strftimedaydate");
408
 
409
    asort($users);
410
 
411
    // Prepare the list of action options.
412
    $actions = array(
413
        'view' => get_string('view'),
414
        'add' => get_string('add'),
415
        'update' => get_string('update'),
416
        'delete' => get_string('delete'),
417
        '-view' => get_string('allchanges')
418
    );
419
 
420
    // Get all the possible dates
421
    // Note that we are keeping track of real (GMT) time and user time
422
    // User time is only used in displays - all calcs and passing is GMT
423
 
424
    $timenow = time(); // GMT
425
 
426
    // What day is it now for the user, and when is midnight that day (in GMT).
427
    $timemidnight = $today = usergetmidnight($timenow);
428
 
429
    // Put today up the top of the list
430
    $dates = array(
431
        "0" => get_string('alldays'),
432
        "$timemidnight" => get_string("today").", ".userdate($timenow, $strftimedate)
433
    );
434
 
435
    if (!$course->startdate or ($course->startdate > $timenow)) {
436
        $course->startdate = $course->timecreated;
437
    }
438
 
439
    $numdates = 1;
440
    while ($timemidnight > $course->startdate and $numdates < 365) {
441
        $timemidnight = $timemidnight - 86400;
442
        $timenow = $timenow - 86400;
443
        $dates["$timemidnight"] = userdate($timenow, $strftimedaydate);
444
        $numdates++;
445
    }
446
 
447
    if ($selecteddate === "today") {
448
        $selecteddate = $today;
449
    }
450
 
451
    echo "<form class=\"logselectform\" action=\"$CFG->wwwroot/report/log/index.php\" method=\"get\">\n";
452
    echo "<div>\n";//invisible fieldset here breaks wrapping
453
    echo "<input type=\"hidden\" name=\"chooselog\" value=\"1\" />\n";
454
    echo "<input type=\"hidden\" name=\"showusers\" value=\"$showusers\" />\n";
455
    echo "<input type=\"hidden\" name=\"showcourses\" value=\"$showcourses\" />\n";
456
    if (has_capability('report/log:view', $sitecontext) && $showcourses) {
457
        $cid = empty($course->id)? '1' : $course->id;
458
        echo html_writer::label(get_string('selectacoursesite'), 'menuhost_course', false, array('class' => 'accesshide'));
459
        echo html_writer::select($dropdown, "host_course", $hostid.'/'.$cid);
460
    } else {
461
        $courses = array();
462
        $courses[$course->id] = get_course_display_name_for_list($course) . ((empty($course->category)) ? ' ('.get_string('site').') ' : '');
463
        echo html_writer::label(get_string('selectacourse'), 'menuid', false, array('class' => 'accesshide'));
464
        echo html_writer::select($courses,"id",$course->id, false);
465
        if (has_capability('report/log:view', $sitecontext)) {
466
            $a = new stdClass();
467
            $a->url = "$CFG->wwwroot/report/log/index.php?chooselog=0&group=$selectedgroup&user=$selecteduser"
468
                ."&id=$course->id&date=$selecteddate&modid=$selectedactivity&showcourses=1&showusers=$showusers";
469
            print_string('logtoomanycourses','moodle',$a);
470
        }
471
    }
472
 
473
    if ($showgroups) {
474
        if ($cgroups = groups_get_all_groups($course->id)) {
475
            foreach ($cgroups as $cgroup) {
476
                $groups[$cgroup->id] = $cgroup->name;
477
            }
478
        }
479
        else {
480
            $groups = array();
481
        }
482
        echo html_writer::label(get_string('selectagroup'), 'menugroup', false, array('class' => 'accesshide'));
483
        echo html_writer::select($groups, "group", $selectedgroup, get_string("allgroups"));
484
    }
485
 
486
    if ($showusers) {
487
        echo html_writer::label(get_string('participantslist'), 'menuuser', false, array('class' => 'accesshide'));
488
        echo html_writer::select($users, "user", $selecteduser, get_string("allparticipants"));
489
    }
490
    else {
491
        $users = array();
492
        if (!empty($selecteduser)) {
493
            $user = $DB->get_record('user', array('id'=>$selecteduser));
494
            $users[$selecteduser] = fullname($user);
495
        }
496
        else {
497
            $users[0] = get_string('allparticipants');
498
        }
499
        echo html_writer::label(get_string('participantslist'), 'menuuser', false, array('class' => 'accesshide'));
500
        echo html_writer::select($users, "user", $selecteduser, false);
501
        $a = new stdClass();
502
        $a->url = "$CFG->wwwroot/report/log/index.php?chooselog=0&group=$selectedgroup&user=$selecteduser"
503
            ."&id=$course->id&date=$selecteddate&modid=$selectedactivity&showusers=1&showcourses=$showcourses";
504
        print_string('logtoomanyusers','moodle',$a);
505
    }
506
 
507
    echo html_writer::label(get_string('date'), 'menudate', false, array('class' => 'accesshide'));
508
    echo html_writer::select($dates, "date", $selecteddate, false);
509
    echo html_writer::label(get_string('showreports'), 'menumodid', false, array('class' => 'accesshide'));
510
    echo html_writer::select($activities, "modid", $selectedactivity, get_string("allactivities"));
511
    echo html_writer::label(get_string('actions'), 'menumodaction', false, array('class' => 'accesshide'));
512
    echo html_writer::select($actions, 'modaction', $modaction, get_string("allactions"));
513
 
514
    $logformats = array('showashtml' => get_string('displayonpage'),
515
                        'downloadascsv' => get_string('downloadtext'),
516
                        'downloadasods' => get_string('downloadods'),
517
                        'downloadasexcel' => get_string('downloadexcel'));
518
    echo html_writer::label(get_string('logsformat', 'report_log'), 'menulogformat', false, array('class' => 'accesshide'));
519
    echo html_writer::select($logformats, 'logformat', $logformat, false);
520
    echo '<input type="submit" value="'.get_string('gettheselogs').'" />';
521
    echo '</div>';
522
    echo '</form>';
523
}
524
 
525
/**
526
 * Fetch logs since the start of the courses and structure in series and labels to be sent to Chart API.
527
 *
528
 * @param stdClass $course the course object
529
 * @param stdClass $user user object
530
 * @param string $logreader the log reader where the logs are.
1441 ariadna 531
 * @param int $sitecoursefilter use a course filter in site context.
1 efrain 532
 * @return array structured array to be sent to chart API, split in two indexes (series and labels).
533
 */
1441 ariadna 534
function report_log_userall_data($course, $user, $logreader, $sitecoursefilter = 0) {
1 efrain 535
    global $CFG;
536
    $site = get_site();
537
    $timenow = time();
538
    $logs = [];
539
    if ($course->id == $site->id) {
1441 ariadna 540
        $courseselect = $sitecoursefilter;
1 efrain 541
    } else {
542
        $courseselect = $course->id;
543
    }
544
 
545
    $maxseconds = REPORT_LOG_MAX_DISPLAY * 3600 * 24;  // Seconds.
546
    if ($timenow - $course->startdate > $maxseconds) {
547
        $course->startdate = $timenow - $maxseconds;
548
    }
549
 
550
    if (!empty($CFG->loglifetime)) {
551
        $maxseconds = $CFG->loglifetime * 3600 * 24;  // Seconds.
552
        if ($timenow - $course->startdate > $maxseconds) {
553
            $course->startdate = $timenow - $maxseconds;
554
        }
555
    }
556
 
557
    $timestart = $coursestart = usergetmidnight($course->startdate);
558
 
559
    $i = 0;
560
    $logs['series'][$i] = 0;
561
    $logs['labels'][$i] = 0;
562
    while ($timestart < $timenow) {
563
        $timefinish = $timestart + 86400;
564
        $logs['labels'][$i] = userdate($timestart, "%a %d %b");
565
        $logs['series'][$i] = 0;
566
        $i++;
567
        $timestart = $timefinish;
568
    }
569
    $rawlogs = report_log_usercourse($user->id, $courseselect, $coursestart, $logreader);
570
 
571
    foreach ($rawlogs as $rawlog) {
572
        if (isset($logs['labels'][$rawlog->day])) {
573
            $logs['series'][$rawlog->day] = $rawlog->num;
574
        }
575
    }
576
 
577
    return $logs;
578
}
579
 
580
/**
581
 * Fetch logs of the current day and structure in series and labels to be sent to Chart API.
582
 *
583
 * @param stdClass $course the course object
584
 * @param stdClass $user user object
585
 * @param int $date A time of a day (in GMT).
586
 * @param string $logreader the log reader where the logs are.
1441 ariadna 587
 * @param int $sitecoursefilter use a course filter in site context.
1 efrain 588
 * @return array $logs structured array to be sent to chart API, split in two indexes (series and labels).
589
 */
1441 ariadna 590
function report_log_usertoday_data($course, $user, $date, $logreader, $sitecoursefilter = 0) {
1 efrain 591
    $site = get_site();
592
    $logs = [];
593
 
594
    if ($course->id == $site->id) {
1441 ariadna 595
        $courseselect = $sitecoursefilter;
1 efrain 596
    } else {
597
        $courseselect = $course->id;
598
    }
599
 
600
    if ($date) {
601
        $daystart = usergetmidnight($date);
602
    } else {
603
        $daystart = usergetmidnight(time());
604
    }
605
 
606
    for ($i = 0; $i <= 23; $i++) {
607
        $hour = $daystart + $i * 3600;
608
        $logs['series'][$i] = 0;
609
        $logs['labels'][$i] = userdate($hour, "%H:00");
610
    }
611
 
612
    $rawlogs = report_log_userday($user->id, $courseselect, $daystart, $logreader);
613
 
614
    foreach ($rawlogs as $rawlog) {
615
        if (isset($logs['labels'][$rawlog->hour])) {
616
            $logs['series'][$rawlog->hour] = $rawlog->num;
617
        }
618
    }
619
 
620
    return $logs;
621
}