forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locallib.php
1497 lines (1350 loc) · 55.9 KB
/
locallib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package mod_data
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/data/lib.php');
require_once($CFG->libdir . '/portfolio/caller.php');
require_once($CFG->libdir . '/filelib.php');
/**
* The class to handle entry exports of a database module
*/
class data_portfolio_caller extends portfolio_module_caller_base {
/** @var int the single record to export */
protected $recordid;
/** @var object the record from the data table */
private $data;
/**#@+ @var array the fields used and their fieldtypes */
private $fields;
private $fieldtypes;
/** @var object the records to export */
private $records;
/** @var int how many records are 'mine' */
private $minecount;
/**
* the required callback arguments for a single-record export
*
* @return array
*/
public static function expected_callbackargs() {
return array(
'id' => true,
'recordid' => false,
);
}
/**
* @param array $callbackargs the arguments passed through
*/
public function __construct($callbackargs) {
parent::__construct($callbackargs);
// set up the list of fields to export
$this->selectedfields = array();
foreach ($callbackargs as $key => $value) {
if (strpos($key, 'field_') === 0) {
$this->selectedfields[] = substr($key, 6);
}
}
}
/**
* load up the data needed for the export
*
* @global object $DB
*/
public function load_data() {
global $DB, $USER;
if (!$this->cm = get_coursemodule_from_id('data', $this->id)) {
throw new portfolio_caller_exception('invalidid', 'data');
}
if (!$this->data = $DB->get_record('data', array('id' => $this->cm->instance))) {
throw new portfolio_caller_exception('invalidid', 'data');
}
$fieldrecords = $DB->get_records('data_fields', array('dataid' => $this->cm->instance), 'id');
// populate objets for this databases fields
$this->fields = array();
foreach ($fieldrecords as $fieldrecord) {
$tmp = data_get_field($fieldrecord, $this->data);
$this->fields[] = $tmp;
$this->fieldtypes[] = $tmp->type;
}
$this->records = array();
if ($this->recordid) {
$tmp = $DB->get_record('data_records', array('id' => $this->recordid));
$tmp->content = $DB->get_records('data_content', array('recordid' => $this->recordid));
$this->records[] = $tmp;
} else {
$where = array('dataid' => $this->data->id);
if (!has_capability('mod/data:exportallentries', context_module::instance($this->cm->id))) {
$where['userid'] = $USER->id; // get them all in case, we'll unset ones that aren't ours later if necessary
}
$tmp = $DB->get_records('data_records', $where);
foreach ($tmp as $t) {
$t->content = $DB->get_records('data_content', array('recordid' => $t->id));
$this->records[] = $t;
}
$this->minecount = $DB->count_records('data_records', array('dataid' => $this->data->id, 'userid' => $USER->id));
}
if ($this->recordid) {
list($formats, $files) = self::formats($this->fields, $this->records[0]);
$this->set_file_and_format_data($files);
}
}
/**
* How long we think the export will take
* Single entry is probably not too long.
* But we check for filesizes
* Else base it on the number of records
*
* @return one of PORTFOLIO_TIME_XX constants
*/
public function expected_time() {
if ($this->recordid) {
return $this->expected_time_file();
} else {
return portfolio_expected_time_db(count($this->records));
}
}
/**
* Calculate the shal1 of this export
* Dependent on the export format.
* @return string
*/
public function get_sha1() {
// in the case that we're exporting a subclass of 'file' and we have a singlefile,
// then we're not exporting any metadata, just the file by itself by mimetype.
if ($this->exporter->get('format') instanceof portfolio_format_file && $this->singlefile) {
return $this->get_sha1_file();
}
// otherwise we're exporting some sort of multipart content so use the data
$str = '';
foreach ($this->records as $record) {
foreach ($record as $data) {
if (is_array($data) || is_object($data)) {
$keys = array_keys($data);
$testkey = array_pop($keys);
if (is_array($data[$testkey]) || is_object($data[$testkey])) {
foreach ($data as $d) {
$str .= implode(',', (array)$d);
}
} else {
$str .= implode(',', (array)$data);
}
} else {
$str .= $data;
}
}
}
return sha1($str . ',' . $this->exporter->get('formatclass'));
}
/**
* Prepare the package for export
*
* @return stored_file object
*/
public function prepare_package() {
global $DB;
$leapwriter = null;
$content = '';
$filename = '';
$uid = $this->exporter->get('user')->id;
$users = array(); //cache
$onlymine = $this->get_export_config('mineonly');
if ($this->exporter->get('formatclass') == PORTFOLIO_FORMAT_LEAP2A) {
$leapwriter = $this->exporter->get('format')->leap2a_writer();
$ids = array();
}
if ($this->exporter->get('format') instanceof portfolio_format_file && $this->singlefile) {
return $this->get('exporter')->copy_existing_file($this->singlefile);
}
foreach ($this->records as $key => $record) {
if ($onlymine && $record->userid != $uid) {
unset($this->records[$key]); // sha1
continue;
}
list($tmpcontent, $files) = $this->exportentry($record);
$content .= $tmpcontent;
if ($leapwriter) {
$entry = new portfolio_format_leap2a_entry('dataentry' . $record->id, $this->data->name, 'resource', $tmpcontent);
$entry->published = $record->timecreated;
$entry->updated = $record->timemodified;
if ($record->userid != $uid) {
if (!array_key_exists($record->userid, $users)) {
$users[$record->userid] = $DB->get_record('user', array('id' => $record->userid), 'id,firstname,lastname');
}
$entry->author = $users[$record->userid];
}
$ids[] = $entry->id;
$leapwriter->link_files($entry, $files, 'dataentry' . $record->id . 'file');
$leapwriter->add_entry($entry);
}
}
if ($leapwriter) {
if (count($this->records) > 1) { // make a selection element to tie them all together
$selection = new portfolio_format_leap2a_entry('datadb' . $this->data->id,
get_string('entries', 'data') . ': ' . $this->data->name, 'selection');
$leapwriter->add_entry($selection);
$leapwriter->make_selection($selection, $ids, 'Grouping');
}
$filename = $this->exporter->get('format')->manifest_name();
$content = $leapwriter->to_xml();
} else {
if (count($this->records) == 1) {
$filename = clean_filename($this->cm->name . '-entry.html');
} else {
$filename = clean_filename($this->cm->name . '-full.html');
}
}
return $this->exporter->write_new_file(
$content,
$filename,
($this->exporter->get('format') instanceof PORTFOLIO_FORMAT_RICH) // if we have associate files, this is a 'manifest'
);
}
/**
* Verify the user can still export this entry
*
* @return bool
*/
public function check_permissions() {
if ($this->recordid) {
if (data_isowner($this->recordid)) {
return has_capability('mod/data:exportownentry', context_module::instance($this->cm->id));
}
return has_capability('mod/data:exportentry', context_module::instance($this->cm->id));
}
if ($this->has_export_config() && !$this->get_export_config('mineonly')) {
return has_capability('mod/data:exportallentries', context_module::instance($this->cm->id));
}
return has_capability('mod/data:exportownentry', context_module::instance($this->cm->id));
}
/**
* @return string
*/
public static function display_name() {
return get_string('modulename', 'data');
}
/**
* @global object
* @return bool|void
*/
public function __wakeup() {
global $CFG;
if (empty($CFG)) {
return true; // too early yet
}
foreach ($this->fieldtypes as $key => $field) {
require_once($CFG->dirroot . '/mod/data/field/' . $field .'/field.class.php');
$this->fields[$key] = unserialize(serialize($this->fields[$key]));
}
}
/**
* Prepare a single entry for export, replacing all the content etc
*
* @param stdclass $record the entry to export
*
* @return array with key 0 = the html content, key 1 = array of attachments
*/
private function exportentry($record) {
// Replacing tags
$patterns = array();
$replacement = array();
$files = array();
// Then we generate strings to replace for normal tags
$format = $this->get('exporter')->get('format');
foreach ($this->fields as $field) {
$patterns[]='[['.$field->field->name.']]';
if (is_callable(array($field, 'get_file'))) {
if (!$file = $field->get_file($record->id)) {
$replacement[] = '';
continue; // probably left empty
}
$replacement[] = $format->file_output($file);
$this->get('exporter')->copy_existing_file($file);
$files[] = $file;
} else {
$replacement[] = $field->display_browse_field($record->id, 'singletemplate');
}
}
// Replacing special tags (##Edit##, ##Delete##, ##More##)
$patterns[]='##edit##';
$patterns[]='##delete##';
$patterns[]='##export##';
$patterns[]='##more##';
$patterns[]='##moreurl##';
$patterns[]='##user##';
$patterns[]='##approve##';
$patterns[]='##disapprove##';
$patterns[]='##comments##';
$patterns[] = '##timeadded##';
$patterns[] = '##timemodified##';
$replacement[] = '';
$replacement[] = '';
$replacement[] = '';
$replacement[] = '';
$replacement[] = '';
$replacement[] = '';
$replacement[] = '';
$replacement[] = '';
$replacement[] = '';
$replacement[] = userdate($record->timecreated);
$replacement[] = userdate($record->timemodified);
// actual replacement of the tags
return array(str_ireplace($patterns, $replacement, $this->data->singletemplate), $files);
}
/**
* Given the fields being exported, and the single record,
* work out which export format(s) we can use
*
* @param array $fields array of field objects
* @param object $record The data record object
*
* @uses PORTFOLIO_FORMAT_PLAINHTML
* @uses PORTFOLIO_FORMAT_RICHHTML
*
* @return array of PORTFOLIO_XX constants
*/
public static function formats($fields, $record) {
$formats = array(PORTFOLIO_FORMAT_PLAINHTML);
$includedfiles = array();
foreach ($fields as $singlefield) {
if (is_callable(array($singlefield, 'get_file'))) {
if ($file = $singlefield->get_file($record->id)) {
$includedfiles[] = $file;
}
}
}
if (count($includedfiles) == 1 && count($fields) == 1) {
$formats = array(portfolio_format_from_mimetype($includedfiles[0]->get_mimetype()));
} else if (count($includedfiles) > 0) {
$formats = array(PORTFOLIO_FORMAT_RICHHTML);
}
return array($formats, $includedfiles);
}
public static function has_files($data) {
global $DB;
$fieldrecords = $DB->get_records('data_fields', array('dataid' => $data->id), 'id');
// populate objets for this databases fields
foreach ($fieldrecords as $fieldrecord) {
$field = data_get_field($fieldrecord, $data);
if (is_callable(array($field, 'get_file'))) {
return true;
}
}
return false;
}
/**
* base supported formats before we know anything about the export
*/
public static function base_supported_formats() {
return array(PORTFOLIO_FORMAT_RICHHTML, PORTFOLIO_FORMAT_PLAINHTML, PORTFOLIO_FORMAT_LEAP2A);
}
public function has_export_config() {
// if we're exporting more than just a single entry,
// and we have the capability to export all entries,
// then ask whether we want just our own, or all of them
return (empty($this->recordid) // multi-entry export
&& $this->minecount > 0 // some of them are mine
&& $this->minecount != count($this->records) // not all of them are mine
&& has_capability('mod/data:exportallentries', context_module::instance($this->cm->id))); // they actually have a choice in the matter
}
public function export_config_form(&$mform, $instance) {
if (!$this->has_export_config()) {
return;
}
$mform->addElement('selectyesno', 'mineonly', get_string('exportownentries', 'data', (object)array('mine' => $this->minecount, 'all' => count($this->records))));
$mform->setDefault('mineonly', 1);
}
public function get_allowed_export_config() {
return array('mineonly');
}
}
/**
* Class representing the virtual node with all itemids in the file browser
*
* @category files
* @copyright 2012 David Mudrak <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class data_file_info_container extends file_info {
/** @var file_browser */
protected $browser;
/** @var stdClass */
protected $course;
/** @var stdClass */
protected $cm;
/** @var string */
protected $component;
/** @var stdClass */
protected $context;
/** @var array */
protected $areas;
/** @var string */
protected $filearea;
/**
* Constructor (in case you did not realize it ;-)
*
* @param file_browser $browser
* @param stdClass $course
* @param stdClass $cm
* @param stdClass $context
* @param array $areas
* @param string $filearea
*/
public function __construct($browser, $course, $cm, $context, $areas, $filearea) {
parent::__construct($browser, $context);
$this->browser = $browser;
$this->course = $course;
$this->cm = $cm;
$this->component = 'mod_data';
$this->context = $context;
$this->areas = $areas;
$this->filearea = $filearea;
}
/**
* @return array with keys contextid, filearea, itemid, filepath and filename
*/
public function get_params() {
return array(
'contextid' => $this->context->id,
'component' => $this->component,
'filearea' => $this->filearea,
'itemid' => null,
'filepath' => null,
'filename' => null,
);
}
/**
* Can new files or directories be added via the file browser
*
* @return bool
*/
public function is_writable() {
return false;
}
/**
* Should this node be considered as a folder in the file browser
*
* @return bool
*/
public function is_directory() {
return true;
}
/**
* Returns localised visible name of this node
*
* @return string
*/
public function get_visible_name() {
return $this->areas[$this->filearea];
}
/**
* Returns list of children nodes
*
* @return array of file_info instances
*/
public function get_children() {
return $this->get_filtered_children('*', false, true);
}
/**
* Help function to return files matching extensions or their count
*
* @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg')
* @param bool|int $countonly if false returns the children, if an int returns just the
* count of children but stops counting when $countonly number of children is reached
* @param bool $returnemptyfolders if true returns items that don't have matching files inside
* @return array|int array of file_info instances or the count
*/
private function get_filtered_children($extensions = '*', $countonly = false, $returnemptyfolders = false) {
global $DB;
$params = array('contextid' => $this->context->id,
'component' => $this->component,
'filearea' => $this->filearea);
$sql = 'SELECT DISTINCT itemid
FROM {files}
WHERE contextid = :contextid
AND component = :component
AND filearea = :filearea';
if (!$returnemptyfolders) {
$sql .= ' AND filename <> :emptyfilename';
$params['emptyfilename'] = '.';
}
list($sql2, $params2) = $this->build_search_files_sql($extensions);
$sql .= ' '.$sql2;
$params = array_merge($params, $params2);
if ($countonly === false) {
$sql .= ' ORDER BY itemid DESC';
}
$rs = $DB->get_recordset_sql($sql, $params);
$children = array();
foreach ($rs as $record) {
if ($child = $this->browser->get_file_info($this->context, 'mod_data', $this->filearea, $record->itemid)) {
$children[] = $child;
}
if ($countonly !== false && count($children) >= $countonly) {
break;
}
}
$rs->close();
if ($countonly !== false) {
return count($children);
}
return $children;
}
/**
* Returns list of children which are either files matching the specified extensions
* or folders that contain at least one such file.
*
* @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg')
* @return array of file_info instances
*/
public function get_non_empty_children($extensions = '*') {
return $this->get_filtered_children($extensions, false);
}
/**
* Returns the number of children which are either files matching the specified extensions
* or folders containing at least one such file.
*
* @param string|array $extensions, for example '*' or array('.gif','.jpg')
* @param int $limit stop counting after at least $limit non-empty children are found
* @return int
*/
public function count_non_empty_children($extensions = '*', $limit = 1) {
return $this->get_filtered_children($extensions, $limit);
}
/**
* Returns parent file_info instance
*
* @return file_info or null for root
*/
public function get_parent() {
return $this->browser->get_file_info($this->context);
}
}
/**
* This creates new calendar events given as timeavailablefrom and timeclose by $data.
*
* @param stdClass $data
* @return void
*/
function data_set_events($data) {
global $DB, $CFG;
require_once($CFG->dirroot.'/calendar/lib.php');
// Get CMID if not sent as part of $data.
if (!isset($data->coursemodule)) {
$cm = get_coursemodule_from_instance('data', $data->id, $data->course);
$data->coursemodule = $cm->id;
}
// Data start calendar events.
$event = new stdClass();
$event->eventtype = DATA_EVENT_TYPE_OPEN;
// The DATA_EVENT_TYPE_OPEN event should only be an action event if no close time was specified.
$event->type = empty($data->timeavailableto) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
if ($event->id = $DB->get_field('event', 'id',
array('modulename' => 'data', 'instance' => $data->id, 'eventtype' => $event->eventtype))) {
if ($data->timeavailablefrom > 0) {
// Calendar event exists so update it.
$event->name = get_string('calendarstart', 'data', $data->name);
$event->description = format_module_intro('data', $data, $data->coursemodule, false);
$event->format = FORMAT_HTML;
$event->timestart = $data->timeavailablefrom;
$event->timesort = $data->timeavailablefrom;
$event->visible = instance_is_visible('data', $data);
$event->timeduration = 0;
$calendarevent = calendar_event::load($event->id);
$calendarevent->update($event, false);
} else {
// Calendar event is on longer needed.
$calendarevent = calendar_event::load($event->id);
$calendarevent->delete();
}
} else {
// Event doesn't exist so create one.
if (isset($data->timeavailablefrom) && $data->timeavailablefrom > 0) {
$event->name = get_string('calendarstart', 'data', $data->name);
$event->description = format_module_intro('data', $data, $data->coursemodule, false);
$event->format = FORMAT_HTML;
$event->courseid = $data->course;
$event->groupid = 0;
$event->userid = 0;
$event->modulename = 'data';
$event->instance = $data->id;
$event->timestart = $data->timeavailablefrom;
$event->timesort = $data->timeavailablefrom;
$event->visible = instance_is_visible('data', $data);
$event->timeduration = 0;
calendar_event::create($event, false);
}
}
// Data end calendar events.
$event = new stdClass();
$event->type = CALENDAR_EVENT_TYPE_ACTION;
$event->eventtype = DATA_EVENT_TYPE_CLOSE;
if ($event->id = $DB->get_field('event', 'id',
array('modulename' => 'data', 'instance' => $data->id, 'eventtype' => $event->eventtype))) {
if ($data->timeavailableto > 0) {
// Calendar event exists so update it.
$event->name = get_string('calendarend', 'data', $data->name);
$event->description = format_module_intro('data', $data, $data->coursemodule, false);
$event->format = FORMAT_HTML;
$event->timestart = $data->timeavailableto;
$event->timesort = $data->timeavailableto;
$event->visible = instance_is_visible('data', $data);
$event->timeduration = 0;
$calendarevent = calendar_event::load($event->id);
$calendarevent->update($event, false);
} else {
// Calendar event is on longer needed.
$calendarevent = calendar_event::load($event->id);
$calendarevent->delete();
}
} else {
// Event doesn't exist so create one.
if (isset($data->timeavailableto) && $data->timeavailableto > 0) {
$event->name = get_string('calendarend', 'data', $data->name);
$event->description = format_module_intro('data', $data, $data->coursemodule, false);
$event->format = FORMAT_HTML;
$event->courseid = $data->course;
$event->groupid = 0;
$event->userid = 0;
$event->modulename = 'data';
$event->instance = $data->id;
$event->timestart = $data->timeavailableto;
$event->timesort = $data->timeavailableto;
$event->visible = instance_is_visible('data', $data);
$event->timeduration = 0;
calendar_event::create($event, false);
}
}
}
/**
* Check if a database is available for the current user.
*
* @param stdClass $data database record
* @param boolean $canmanageentries optional, if the user can manage entries
* @param stdClass $context Module context, required if $canmanageentries is not set
* @return array status (available or not and possible warnings)
* @since Moodle 3.3
*/
function data_get_time_availability_status($data, $canmanageentries = null, $context = null) {
$open = true;
$closed = false;
$warnings = array();
if ($canmanageentries === null) {
$canmanageentries = has_capability('mod/data:manageentries', $context);
}
if (!$canmanageentries) {
$timenow = time();
if (!empty($data->timeavailablefrom) and $data->timeavailablefrom > $timenow) {
$open = false;
}
if (!empty($data->timeavailableto) and $timenow > $data->timeavailableto) {
$closed = true;
}
if (!$open or $closed) {
if (!$open) {
$warnings['notopenyet'] = userdate($data->timeavailablefrom);
}
if ($closed) {
$warnings['expired'] = userdate($data->timeavailableto);
}
return array(false, $warnings);
}
}
// Database is available.
return array(true, $warnings);
}
/**
* Requires a database to be available for the current user.
*
* @param stdClass $data database record
* @param boolean $canmanageentries optional, if the user can manage entries
* @param stdClass $context Module context, required if $canmanageentries is not set
* @throws moodle_exception
* @since Moodle 3.3
*/
function data_require_time_available($data, $canmanageentries = null, $context = null) {
list($available, $warnings) = data_get_time_availability_status($data, $canmanageentries, $context);
if (!$available) {
$reason = current(array_keys($warnings));
throw new moodle_exception($reason, 'data', '', $warnings[$reason]);
}
}
/**
* Return the number of entries left to add to complete the activity.
*
* @param stdClass $data database object
* @param int $numentries the number of entries the current user has created
* @param bool $canmanageentries whether the user can manage entries (teachers, managers)
* @return int the number of entries left, 0 if no entries left or if is not required
* @since Moodle 3.3
*/
function data_get_entries_left_to_add($data, $numentries, $canmanageentries) {
if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !$canmanageentries) {
return $data->requiredentries - $numentries;
}
return 0;
}
/**
* Return the number of entires left to add to view other users entries..
*
* @param stdClass $data database object
* @param int $numentries the number of entries the current user has created
* @param bool $canmanageentries whether the user can manage entries (teachers, managers)
* @return int the number of entries left, 0 if no entries left or if is not required
* @since Moodle 3.3
*/
function data_get_entries_left_to_view($data, $numentries, $canmanageentries) {
if ($data->requiredentriestoview > 0 && $numentries < $data->requiredentriestoview && !$canmanageentries) {
return $data->requiredentriestoview - $numentries;
}
return 0;
}
/**
* Returns data records tagged with a specified tag.
*
* This is a callback used by the tag area mod_data/data_records to search for data records
* tagged with a specific tag.
*
* @param core_tag_tag $tag
* @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
* are displayed on the page and the per-page limit may be bigger
* @param int $fromctx context id where the link was displayed, may be used by callbacks
* to display items in the same context first
* @param int $ctx context id where to search for records
* @param bool $rec search in subcontexts as well
* @param int $page 0-based number of page being displayed
* @return \core_tag\output\tagindex
*/
function mod_data_get_tagged_records($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = true, $page = 0) {
global $DB, $OUTPUT, $USER;
$perpage = $exclusivemode ? 20 : 5;
// Build the SQL query.
$ctxselect = context_helper::get_preload_record_columns_sql('ctx');
$query = "SELECT dr.id, dr.dataid, dr.approved, d.timeviewfrom, d.timeviewto, dr.groupid, d.approval, dr.userid,
d.requiredentriestoview, cm.id AS cmid, c.id AS courseid, c.shortname, c.fullname, $ctxselect
FROM {data_records} dr
JOIN {data} d
ON d.id = dr.dataid
JOIN {modules} m
ON m.name = 'data'
JOIN {course_modules} cm
ON cm.module = m.id AND cm.instance = d.id
JOIN {tag_instance} tt
ON dr.id = tt.itemid
JOIN {course} c
ON cm.course = c.id
JOIN {context} ctx
ON ctx.instanceid = cm.id AND ctx.contextlevel = :coursemodulecontextlevel
WHERE tt.itemtype = :itemtype
AND tt.tagid = :tagid
AND tt.component = :component
AND cm.deletioninprogress = 0
AND dr.id %ITEMFILTER%
AND c.id %COURSEFILTER%";
$params = array(
'itemtype' => 'data_records',
'tagid' => $tag->id,
'component' => 'mod_data',
'coursemodulecontextlevel' => CONTEXT_MODULE
);
if ($ctx) {
$context = $ctx ? context::instance_by_id($ctx) : context_system::instance();
$query .= $rec ? ' AND (ctx.id = :contextid OR ctx.path LIKE :path)' : ' AND ctx.id = :contextid';
$params['contextid'] = $context->id;
$params['path'] = $context->path . '/%';
}
$query .= " ORDER BY ";
if ($fromctx) {
// In order-clause specify that modules from inside "fromctx" context should be returned first.
$fromcontext = context::instance_by_id($fromctx);
$query .= ' (CASE WHEN ctx.id = :fromcontextid OR ctx.path LIKE :frompath THEN 0 ELSE 1 END),';
$params['fromcontextid'] = $fromcontext->id;
$params['frompath'] = $fromcontext->path . '/%';
}
$query .= ' c.sortorder, cm.id, dr.id';
$totalpages = $page + 1;
// Use core_tag_index_builder to build and filter the list of items.
$builder = new core_tag_index_builder('mod_data', 'data_records', $query, $params, $page * $perpage, $perpage + 1);
$now = time();
$entrycount = [];
$activitygroupmode = [];
$usergroups = [];
$titlefields = [];
while ($item = $builder->has_item_that_needs_access_check()) {
context_helper::preload_from_record($item);
$modinfo = get_fast_modinfo($item->courseid);
$cm = $modinfo->get_cm($item->cmid);
$context = \context_module::instance($cm->id);
$courseid = $item->courseid;
if (!$builder->can_access_course($courseid)) {
$builder->set_accessible($item, false);
continue;
}
if (!$cm->uservisible) {
$builder->set_accessible($item, false);
continue;
}
if (!has_capability('mod/data:viewentry', $context)) {
$builder->set_accessible($item, false);
continue;
}
if ($USER->id != $item->userid && (($item->timeviewfrom && $now < $item->timeviewfrom)
|| ($item->timeviewto && $now > $item->timeviewto))) {
$builder->set_accessible($item, false);
continue;
}
if ($USER->id != $item->userid && $item->approval && !$item->approved) {
$builder->set_accessible($item, false);
continue;
}
if ($item->requiredentriestoview) {
if (!isset($entrycount[$item->dataid])) {
$entrycount[$item->dataid] = $DB->count_records('data_records', array('dataid' => $item->dataid));
}
$sufficiententries = $item->requiredentriestoview > $entrycount[$item->dataid];
$builder->set_accessible($item, $sufficiententries);
}
if (!isset($activitygroupmode[$cm->id])) {
$activitygroupmode[$cm->id] = groups_get_activity_groupmode($cm);
}
if (!isset($usergroups[$item->groupid])) {
$usergroups[$item->groupid] = groups_is_member($item->groupid, $USER->id);
}
if ($activitygroupmode[$cm->id] == SEPARATEGROUPS && !$usergroups[$item->groupid]) {
$builder->set_accessible($item, false);
continue;
}
$builder->set_accessible($item, true);
}
$items = $builder->get_items();
if (count($items) > $perpage) {
$totalpages = $page + 2; // We don't need exact page count, just indicate that the next page exists.
array_pop($items);
}
// Build the display contents.
if ($items) {
$tagfeed = new core_tag\output\tagfeed();
foreach ($items as $item) {
context_helper::preload_from_record($item);
$modinfo = get_fast_modinfo($item->courseid);
$cm = $modinfo->get_cm($item->cmid);
$pageurl = new moodle_url('/mod/data/view.php', array(
'rid' => $item->id,
'd' => $item->dataid
));
if (!isset($titlefields[$item->dataid])) {
$titlefields[$item->dataid] = data_get_tag_title_field($item->dataid);
}
$pagename = data_get_tag_title_for_entry($titlefields[$item->dataid], $item);
$pagename = html_writer::link($pageurl, $pagename);
$courseurl = course_get_url($item->courseid, $cm->sectionnum);
$cmname = html_writer::link($cm->url, $cm->get_formatted_name());
$coursename = format_string($item->fullname, true, array('context' => context_course::instance($item->courseid)));
$coursename = html_writer::link($courseurl, $coursename);
$icon = html_writer::link($pageurl, html_writer::empty_tag('img', array('src' => $cm->get_icon_url())));
$tagfeed->add($icon, $pagename, $cmname . '<br>' . $coursename);
}
$content = $OUTPUT->render_from_template('core_tag/tagfeed', $tagfeed->export_for_template($OUTPUT));
return new core_tag\output\tagindex($tag, 'mod_data', 'data_records', $content, $exclusivemode,
$fromctx, $ctx, $rec, $page, $totalpages);
}
}
/**
* Get the title of a field to show when displaying tag results.
*
* @param int $dataid The id of the data field
* @return stdClass The field data from the 'data_fields' table as well as it's priority
*/
function data_get_tag_title_field($dataid) {
global $DB, $CFG;
$validfieldtypes = array('text', 'textarea', 'menu', 'radiobutton', 'checkbox', 'multimenu', 'url');
$fields = $DB->get_records('data_fields', ['dataid' => $dataid]);
$template = $DB->get_field('data', 'addtemplate', ['id' => $dataid]);
$filteredfields = [];
foreach ($fields as $field) {
if (!in_array($field->type, $validfieldtypes)) {
continue;
}
$field->addtemplateposition = strpos($template, '[['.$field->name.']]');
if ($field->addtemplateposition === false) {
continue;
}
require_once($CFG->dirroot . '/mod/data/field/' . $field->type . '/field.class.php');
$classname = 'data_field_' . $field->type;
$field->priority = $classname::get_priority();
$filteredfields[] = $field;
}
$sort = function($record1, $record2) {
// If a content's fieldtype is compulsory in the database than it would have priority than any other non-compulsory content.
if (($record1->required && $record2->required) || (!$record1->required && !$record2->required)) {
if ($record1->priority === $record2->priority) {
return $record1->id < $record2->id ? 1 : -1;
}
return $record1->priority < $record2->priority ? -1 : 1;
} else if ($record1->required && !$record2->required) {
return 1;
} else {
return -1;
}
};
usort($filteredfields, $sort);
return array_shift($filteredfields);
}
/**
* Get the title of an entry to show when displaying tag results.