Proyectos de Subversion Moodle

Rev

| 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
 * Configurable Reports
19
 * A Moodle block for creating Configurable Reports
20
 * @package blocks
21
 * @author: Juan leyva <http://www.twitter.com/jleyvadelgado>
22
 * @date: 2009
23
 */
24
 
25
function cr_print_js_function() {
26
?>
27
    <script type="text/javascript">
28
        function printDiv(id){
29
            var cdiv, tmpw;
30
 
31
            cdiv = document.getElementById(id);
32
            tmpw = window.open(" ","Print");
33
 
34
            tmpw.document.open();
35
            tmpw.document.write('<html><body>');
36
            tmpw.document.write(cdiv.innerHTML);
37
            tmpw.document.write('</'+'body></html>');
38
            tmpw.document.close();
39
            setTimeout(function() {
40
                tmpw.print();
41
                tmpw.close();
42
            }, 1000);
43
        }
44
    </script>
45
<?php
46
}
47
 
48
function cr_add_jsdatatables($cssid, \moodle_page $page) {
49
    global $OUTPUT;
50
    $data = array();
51
    $data['selector'] = $cssid;
52
 
53
    $page->requires->string_for_js('thousandssep', 'langconfig');
54
    $page->requires->strings_for_js(
55
        array(
56
            'datatables_sortascending',
57
            'datatables_sortdescending',
58
            'datatables_first',
59
            'datatables_last',
60
            'datatables_next',
61
            'datatables_previous',
62
            'datatables_emptytable',
63
            'datatables_info',
64
            'datatables_infoempty',
65
            'datatables_infofiltered',
66
            'datatables_lengthmenu',
67
            'datatables_loadingrecords',
68
            'datatables_processing',
69
            'datatables_search',
70
            'datatables_zerorecords',
71
            ),
72
        'block_configurable_reports');
73
 
74
    $page->requires->js_call_amd('block_configurable_reports/main', 'add_jsdatatables', array($data));
75
}
76
 
77
/**
78
 * @param $cssid
79
 * @param \moodle_page $page
80
 */
81
function cr_add_jsordering($cssid, \moodle_page $page = null) {
82
    global $OUTPUT;
83
 
84
    if(!empty($page)) {
85
        $data = array();
86
        $data['selector'] = $cssid;
87
        if (method_exists($OUTPUT, 'image_url')) {
88
            $data['background'] = $OUTPUT->image_url('normal', 'block_configurable_reports')->out();
89
            $data['backgroundasc'] = $OUTPUT->image_url('asc', 'block_configurable_reports')->out();
90
            $data['backgrounddesc'] = $OUTPUT->image_url('desc', 'block_configurable_reports')->out();
91
        }
92
        $page->requires->js_call_amd('block_configurable_reports/main', 'js_order', array($data));
93
    }
94
}
95
 
96
function urlencode_recursive($var) {
97
    if (is_object($var)) {
98
        $newvar = new \stdClass();
99
        $properties = get_object_vars($var);
100
        foreach ($properties as $property => $value) {
101
            $newvar->$property = urlencode_recursive($value);
102
        }
103
    } else if (is_array($var)) {
104
        $newvar = array();
105
        foreach ($var as $property => $value) {
106
            $newvar[$property] = urlencode_recursive($value);
107
        }
108
    } else if (is_string($var)) {
109
        $newvar = urlencode($var);
110
    } else {
111
        // Nulls, integers, etc.
112
        $newvar = $var;
113
    }
114
 
115
    return $newvar;
116
}
117
 
118
function urldecode_recursive($var) {
119
    if (is_object($var)) {
120
        $newvar = new \stdClass();
121
        $properties = get_object_vars($var);
122
        foreach ($properties as $property => $value) {
123
            $newvar->$property = urldecode_recursive($value);
124
        }
125
    } else if (is_array($var)) {
126
        $newvar = array();
127
        foreach ($var as $property => $value) {
128
            $newvar[$property] = urldecode_recursive($value);
129
        }
130
    } else if (is_string($var)) {
131
        $newvar = urldecode($var);
132
    } else {
133
        $newvar = $var;
134
    }
135
 
136
    return $newvar;
137
}
138
 
139
function cr_get_my_reports($courseid, $userid, $allcourses = true) {
140
    global $DB;
141
 
142
    $reports = [];
143
    if ($courseid == SITEID) {
144
        $context = \context_system::instance();
145
    } else {
146
        $context = \context_course::instance($courseid);
147
    }
148
 
149
    if (has_capability('block/configurable_reports:managereports', $context, $userid)) {
150
        if ($courseid == SITEID && $allcourses) {
151
            $reports = $DB->get_records('block_configurable_reports', null, 'name ASC');
152
        } else {
153
            $reports = $DB->get_records('block_configurable_reports', array('courseid' => $courseid), 'name ASC');
154
        }
155
    } else {
156
        $reports = $DB->get_records_select('block_configurable_reports', 'ownerid = ? AND courseid = ? ORDER BY name ASC', array($userid, $courseid));
157
    }
158
    return $reports;
159
}
160
 
161
function cr_serialize($var) {
162
    return serialize(urlencode_recursive($var));
163
}
164
 
165
function cr_unserialize($var) {
166
    // It's needed to convert the object to stdClass to avoid __PHP_Incomplete_Class error.
167
    $var = preg_replace('/O:6:"object"/', 'O:8:"stdClass"', $var);
168
    // To make SQL queries compatible with PostgreSQL it's needed to replace " to '.
169
    $var = preg_replace('/THEN\+%22(.+?)%22/', 'THEN+%27${1}%27', $var);
170
    $var = preg_replace('/%60/', '+++', $var);
171
 
172
    return urldecode_recursive(unserialize($var));
173
}
174
 
175
function cr_check_report_permissions($report, $userid, $context) {
176
    global $DB, $CFG;
177
 
178
    require_once($CFG->dirroot.'/blocks/configurable_reports/report.class.php');
179
    require_once($CFG->dirroot.'/blocks/configurable_reports/reports/'.$report->type.'/report.class.php');
180
 
181
    $classn = 'report_'.$report->type;
182
    $classi = new $classn($report->id);
183
    return $classi->check_permissions($userid, $context);
184
}
185
 
186
function cr_get_report_plugins($courseid) {
187
    $pluginoptions = array();
188
    $context = ($courseid == SITEID) ? \context_system::instance() : \context_course::instance($courseid);
189
    $plugins = get_list_of_plugins('blocks/configurable_reports/reports');
190
 
191
    if ($plugins) {
192
        foreach ($plugins as $p) {
193
            if ($p == 'sql' && !has_capability('block/configurable_reports:managesqlreports', $context)) {
194
                continue;
195
            }
196
            $pluginoptions[$p] = get_string('report_'.$p, 'block_configurable_reports');
197
        }
198
    }
199
    return $pluginoptions;
200
}
201
 
202
function cr_get_export_plugins() {
203
 
204
    $exportoptions = array();
205
    $plugins = get_list_of_plugins('blocks/configurable_reports/export');
206
 
207
    if ($plugins) {
208
        foreach ($plugins as $p) {
209
            $pluginoptions[$p] = get_string('export_'.$p, 'block_configurable_reports');
210
        }
211
    }
212
    return $pluginoptions;
213
}
214
 
215
function cr_print_table($table, $return = false) {
216
    global $COURSE;
217
 
218
    $output = '';
219
 
220
    if (isset($table->align)) {
221
        foreach ($table->align as $key => $aa) {
222
            if ($aa) {
223
                $align[$key] = ' text-align:'. fix_align_rtl($aa) .';';  // Fix for RTL languages.
224
            } else {
225
                $align[$key] = '';
226
            }
227
        }
228
    }
229
    if (isset($table->size)) {
230
        foreach ($table->size as $key => $ss) {
231
            if ($ss) {
232
                $size[$key] = ' width:'. $ss .';';
233
            } else {
234
                $size[$key] = '';
235
            }
236
        }
237
    }
238
    if (isset($table->wrap)) {
239
        foreach ($table->wrap as $key => $ww) {
240
            if ($ww) {
241
                $wrap[$key] = ' white-space:nowrap;';
242
            } else {
243
                $wrap[$key] = '';
244
            }
245
        }
246
    }
247
 
248
    if (empty($table->width)) {
249
        $table->width = '80%';
250
    }
251
 
252
    if (empty($table->tablealign)) {
253
        $table->tablealign = 'center';
254
    }
255
 
256
    if (!isset($table->cellpadding)) {
257
        $table->cellpadding = '5';
258
    }
259
 
260
    if (!isset($table->cellspacing)) {
261
        $table->cellspacing = '1';
262
    }
263
 
264
    if (empty($table->class)) {
265
        $table->class = 'generaltable';
266
    }
267
 
268
    $tableid = empty($table->id) ? '' : 'id="'.$table->id.'"';
269
    $output .= '<form action="send_emails.php" method="post" id="sendemail">';
270
    $output .= '<table width="'.$table->width.'" ';
271
    if (!empty($table->summary)) {
272
        $output .= " summary=\"$table->summary\"";
273
    }
274
    $output .= " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"$table->class boxalign$table->tablealign\" $tableid>\n";
275
 
276
    $countcols = 0;
277
    $isuserid = -1;
278
 
279
    if (!empty($table->head)) {
280
        $countcols = count($table->head);
281
        $output .= '<thead><tr>';
282
        $keys = array_keys($table->head);
283
        $lastkey = end($keys);
284
        foreach ($table->head as $key => $heading) {
285
            if ($heading == 'sendemail') {
286
                $isuserid = $key;
287
            }
288
            if (!isset($size[$key])) {
289
                $size[$key] = '';
290
            }
291
            if (!isset($align[$key])) {
292
                $align[$key] = '';
293
            }
294
            if ($key == $lastkey) {
295
                $extraclass = ' lastcol';
296
            } else {
297
                $extraclass = '';
298
            }
299
 
300
            $output .= '<th style="vertical-align:top;'. $align[$key].$size[$key] .';white-space:normal;" class="header c'.$key.$extraclass.'" scope="col">'. $heading .'</th>';
301
        }
302
        $output .= '</tr></thead>'."\n";
303
    }
304
 
305
    if (!empty($table->data)) {
306
        $oddeven = 1;
307
        $keys = array_keys($table->data);
308
        $lastrowkey = end($keys);
309
        foreach ($table->data as $key => $row) {
310
            $oddeven = $oddeven ? 0 : 1;
311
            if (!isset($table->rowclass[$key])) {
312
                $table->rowclass[$key] = '';
313
            }
314
            if ($key == $lastrowkey) {
315
                $table->rowclass[$key] .= ' lastrow';
316
            }
317
            $output .= '<tr class="r'.$oddeven.' '.$table->rowclass[$key].'">'."\n";
318
            if ($row == 'hr' and $countcols) {
319
                $output .= '<td colspan="'. $countcols .'"><div class="tabledivider"></div></td>';
320
            } else {  // It's a normal row of data.
321
                $keys2 = array_keys($row);
322
                $lastkey = end($keys2);
323
                foreach ($row as $key => $item) {
324
                    if (!isset($size[$key])) {
325
                        $size[$key] = '';
326
                    }
327
                    if (!isset($align[$key])) {
328
                        $align[$key] = '';
329
                    }
330
                    if (!isset($wrap[$key])) {
331
                        $wrap[$key] = '';
332
                    }
333
                    if ($key == $lastkey) {
334
                        $extraclass = ' lastcol';
335
                    } else {
336
                        $extraclass = '';
337
                    }
338
                    if ($key == $isuserid) {
339
                        $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'"><input name="userids[]" type="checkbox" value="'.$item.'"></td>';
340
                    } else {
341
                        $output .= '<td style="'. $align[$key].$size[$key].$wrap[$key] .'" class="cell c'.$key.$extraclass.'">'. $item .'</td>';
342
                    }
343
 
344
                }
345
            }
346
            $output .= '</tr>'."\n";
347
        }
348
    }
349
    $output .= '</table>'."\n";
350
    $output .= '<input type="hidden" name="courseid" value="'.$COURSE->id.'">';
351
    if ($isuserid != -1) {
352
        $output .= '<input type="submit" value="send emails">';
353
    }
354
    $output .= '</form>';
355
 
356
    if ($return) {
357
        return $output;
358
    }
359
 
360
    echo $output;
361
    return true;
362
}
363
 
364
function table_to_excel($filename, $table) {
365
    global $DB, $CFG;
366
 
367
    require_once($CFG->dirroot.'/lib/excellib.class.php');
368
 
369
    if (!empty($table->head)) {
370
        $countcols = count($table->head);
371
        $keys = array_keys($table->head);
372
        $lastkey = end($keys);
373
        foreach ($table->head as $key => $heading) {
374
                $matrix[0][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($heading))));
375
        }
376
    }
377
 
378
    if (!empty($table->data)) {
379
        foreach ($table->data as $rkey => $row) {
380
            foreach ($row as $key => $item) {
381
                $matrix[$rkey + 1][$key] = str_replace("\n", ' ', htmlspecialchars_decode(strip_tags(nl2br($item))));
382
            }
383
        }
384
    }
385
 
386
    $downloadfilename = clean_filename($filename);
387
    // Creating a workbook.
388
    $workbook = new MoodleExcelWorkbook("-");
389
    // Sending HTTP headers.
390
    $workbook->send($downloadfilename);
391
    // Adding the worksheet.
392
    $myxls =& $workbook->add_worksheet($filename);
393
 
394
    foreach ($matrix as $ri => $col) {
395
        foreach ($col as $ci => $cv) {
396
            $myxls->write_string($ri, $ci, $cv);
397
        }
398
    }
399
 
400
    $workbook->close();
401
    exit;
402
}
403
 
404
/**
405
 * Returns contexts in deprecated and current modes
406
 *
407
 * @param  int $context The context
408
 * @param  int $id      The context id
409
 * @param  int $flags   The flags to be used
410
 * @return stdClass     An object instance
411
 */
412
function cr_get_context($context, $id = null, $flags = null) {
413
 
414
    if ($context == CONTEXT_SYSTEM) {
415
        if (class_exists('context_system')) {
416
            return context_system::instance();
417
        } else {
418
            return get_context_instance(CONTEXT_SYSTEM);
419
        }
420
    } else if ($context == CONTEXT_COURSE) {
421
        if (class_exists('context_course')) {
422
            return context_course::instance($id, $flags);
423
        } else {
424
            return get_context_instance($context, $id, $flags);
425
        }
426
    } else if ($context == CONTEXT_COURSECAT) {
427
        if (class_exists('context_coursecat')) {
428
            return context_coursecat::instance($id, $flags);
429
        } else {
430
            return get_context_instance($context, $id, $flags);
431
        }
432
    } else if ($context == CONTEXT_BLOCK) {
433
        if (class_exists('context_block')) {
434
            return context_block::instance($id, $flags);
435
        } else {
436
            return get_context_instance($context, $id, $flags);
437
        }
438
    } else if ($context == CONTEXT_MODULE) {
439
        if (class_exists('context_module')) {
440
            return get_context_instance::instance($id, $flags);
441
        } else {
442
            return get_context_instance($context, $id, $flags);
443
        }
444
    } else if ($context == CONTEXT_USER) {
445
        if (class_exists('context_user')) {
446
            return context_user::instance($id, $flags);
447
        } else {
448
            return get_context_instance($context, $id, $flags);
449
        }
450
    }
451
 
452
    return get_context_instance($context, $id, $flags);
453
}
454
 
455
function cr_make_categories_list(&$list, &$parents, $requiredcapability = '', $excludeid = 0, $category = null, $path = '') {
456
    global $CFG, $DB;
457
 
458
    // For categories list use just this one function.
459
    if (empty($list)) {
460
        $list = array();
461
    }
462
 
463
    if (class_exists('core_course_category')) {
464
        $list += core_course_category::make_categories_list($requiredcapability, $excludeid);
465
    } else {
466
        require_once($CFG->libdir. '/coursecatlib.php');
467
        $list += coursecat::make_categories_list($requiredcapability, $excludeid);
468
    }
469
 
470
    // Building the list of all parents of all categories in the system is highly undesirable and hardly ever needed.
471
    // Usually user needs only parents for one particular category, in which case should be used:
472
    // coursecat::get($categoryid)->get_parents().
473
    if (empty($parents)) {
474
        $parents = array();
475
    }
476
    $all = $DB->get_records_sql('SELECT id, parent FROM {course_categories} ORDER BY sortorder');
477
    foreach ($all as $record) {
478
        if ($record->parent) {
479
            $parents[$record->id] = array_merge($parents[$record->parent], array($record->parent));
480
        } else {
481
            $parents[$record->id] = array();
482
        }
483
    }
484
}
485
 
486
function cr_import_xml($xml, $course) {
487
    global $CFG, $DB, $USER;
488
 
489
    require_once($CFG->dirroot.'/lib/xmlize.php');
490
    $data = xmlize($xml, 1, 'UTF-8');
491
 
492
    if (isset($data['report']['@']['version'])) {
493
        $newreport = new stdclass;
494
        foreach ($data['report']['#'] as $key => $val) {
495
            if ($key == 'components') {
496
                $val[0]['#'] = base64_decode(trim($val[0]['#']));
497
                // Fix url_encode " and ' when importing SQL queries.
498
                $tempcomponents = cr_unserialize($val[0]['#']);
499
                if (array_key_exists('customsql', $tempcomponents)) {
500
                    $tempcomponents['customsql']['config']->querysql = str_replace("\'", "'", $tempcomponents['customsql']['config']->querysql);
501
                    $tempcomponents['customsql']['config']->querysql = str_replace('\"', '"', $tempcomponents['customsql']['config']->querysql);
502
                }
503
                $val[0]['#'] = cr_serialize($tempcomponents);
504
            }
505
            $newreport->{$key} = trim($val[0]['#']);
506
        }
507
        $newreport->courseid = $course->id;
508
        $newreport->ownerid = $USER->id;
509
        $newreport->name .= " (" . userdate(time()) . ")";
510
 
511
        if (!$DB->insert_record('block_configurable_reports', $newreport)) {
512
            return false;
513
        }
514
        return true;
515
    }
516
    return false;
517
}
518
 
519
// For avoid warnings in versions minor than 2.7.
520
function cr_add_to_log($courseid, $module, $action, $url='', $info='', $cm=0, $user=0) {
521
    global $CFG;
522
 
523
    if ($CFG->version < 2014051200) {
524
        add_to_log($courseid, $module, $action, $url, $info, $cm, $user);
525
    }
526
}
527
 
528
function cr_logging_info() {
529
    global $DB, $CFG;
530
 
531
    static $uselegacyreader;
532
    static $useinternalreader;
533
    static $logtable;
534
 
535
    if (isset($uselegacyreader) && isset($useinternalreader) && isset($logtable)) {
536
        return array($uselegacyreader, $useinternalreader, $logtable);
537
    }
538
 
539
    $uselegacyreader = false; // Flag to determine if we should use the legacy reader.
540
    $useinternalreader = false; // Flag to determine if we should use the internal reader.
541
    $logtable = '';
542
 
543
    // Pre 2.7.
544
    if ($CFG->version < 2014051200) {
545
        $uselegacyreader = true;
546
        $logtable = 'log';
547
    } else {
548
 
549
        // Get list of readers.
550
        $logmanager = get_log_manager();
551
        $readers = $logmanager->get_readers();
552
 
553
        // Get preferred reader.
554
        if (!empty($readers)) {
555
            foreach ($readers as $readerpluginname => $reader) {
556
                // If legacy reader is preferred reader.
557
                if ($readerpluginname == 'logstore_legacy') {
558
                    $uselegacyreader = true;
559
                    $logtable = 'log';
560
                }
561
 
562
                // If sql_internal_table_reader is preferred reader.
563
                if ($reader instanceof \core\log\sql_internal_table_reader or $reader instanceof \core\log\sql_internal_reader) {
564
                    $useinternalreader = true;
565
                    $logtable = $reader->get_internal_log_table_name();
566
                }
567
            }
568
        }
569
    }
570
 
571
    return array($uselegacyreader, $useinternalreader, $logtable);
572
}