~ubuntu-branches/ubuntu/trusty/moodle/trusty-proposed

« back to all changes in this revision

Viewing changes to .pc/0020-MDL-35558-mod_data-Show-only-own-entries-while-there.patch/mod/data/lib.php

  • Committer: Package Import Robot
  • Author(s): Tomasz Muras
  • Date: 2012-11-15 21:50:13 UTC
  • mfrom: (1.1.9)
  • Revision ID: package-import@ubuntu.com-20121115215013-hmzkwz3v5hvm2a0a
Tags: 2.2.6.dfsg-1
New upstream version: 2.2.6 (Build: 20121112)

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
 * @package   mod-data
20
 
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
21
 
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 
 */
23
 
 
24
 
// Some constants
25
 
define ('DATA_MAX_ENTRIES', 50);
26
 
define ('DATA_PERPAGE_SINGLE', 1);
27
 
 
28
 
define ('DATA_FIRSTNAME', -1);
29
 
define ('DATA_LASTNAME', -2);
30
 
define ('DATA_APPROVED', -3);
31
 
define ('DATA_TIMEADDED', 0);
32
 
define ('DATA_TIMEMODIFIED', -4);
33
 
 
34
 
define ('DATA_CAP_EXPORT', 'mod/data:viewalluserpresets');
35
 
 
36
 
define('DATA_PRESET_COMPONENT', 'mod_data');
37
 
define('DATA_PRESET_FILEAREA', 'site_presets');
38
 
define('DATA_PRESET_CONTEXT', SYSCONTEXTID);
39
 
 
40
 
// Users having assigned the default role "Non-editing teacher" can export database records
41
 
// Using the mod/data capability "viewalluserpresets" existing in Moodle 1.9.x.
42
 
// In Moodle >= 2, new roles may be introduced and used instead.
43
 
 
44
 
/**
45
 
 * @package   mod-data
46
 
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
47
 
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48
 
 */
49
 
class data_field_base {     // Base class for Database Field Types (see field/*/field.class.php)
50
 
 
51
 
    /** @var string Subclasses must override the type with their name */
52
 
    var $type = 'unknown';
53
 
    /** @var object The database object that this field belongs to */
54
 
    var $data = NULL;
55
 
    /** @var object The field object itself, if we know it */
56
 
    var $field = NULL;
57
 
    /** @var int Width of the icon for this fieldtype */
58
 
    var $iconwidth = 16;
59
 
    /** @var int Width of the icon for this fieldtype */
60
 
    var $iconheight = 16;
61
 
    /** @var object course module or cmifno */
62
 
    var $cm;
63
 
    /** @var object activity context */
64
 
    var $context;
65
 
 
66
 
    /**
67
 
     * Constructor function
68
 
     *
69
 
     * @global object
70
 
     * @uses CONTEXT_MODULE
71
 
     * @param int $field
72
 
     * @param int $data
73
 
     * @param int $cm
74
 
     */
75
 
    function __construct($field=0, $data=0, $cm=0) {   // Field or data or both, each can be id or object
76
 
        global $DB;
77
 
 
78
 
        if (empty($field) && empty($data)) {
79
 
            print_error('missingfield', 'data');
80
 
        }
81
 
 
82
 
        if (!empty($field)) {
83
 
            if (is_object($field)) {
84
 
                $this->field = $field;  // Programmer knows what they are doing, we hope
85
 
            } else if (!$this->field = $DB->get_record('data_fields', array('id'=>$field))) {
86
 
                print_error('invalidfieldid', 'data');
87
 
            }
88
 
            if (empty($data)) {
89
 
                if (!$this->data = $DB->get_record('data', array('id'=>$this->field->dataid))) {
90
 
                    print_error('invalidid', 'data');
91
 
                }
92
 
            }
93
 
        }
94
 
 
95
 
        if (empty($this->data)) {         // We need to define this properly
96
 
            if (!empty($data)) {
97
 
                if (is_object($data)) {
98
 
                    $this->data = $data;  // Programmer knows what they are doing, we hope
99
 
                } else if (!$this->data = $DB->get_record('data', array('id'=>$data))) {
100
 
                    print_error('invalidid', 'data');
101
 
                }
102
 
            } else {                      // No way to define it!
103
 
                print_error('missingdata', 'data');
104
 
            }
105
 
        }
106
 
 
107
 
        if ($cm) {
108
 
            $this->cm = $cm;
109
 
        } else {
110
 
            $this->cm = get_coursemodule_from_instance('data', $this->data->id);
111
 
        }
112
 
 
113
 
        if (empty($this->field)) {         // We need to define some default values
114
 
            $this->define_default_field();
115
 
        }
116
 
 
117
 
        $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
118
 
    }
119
 
 
120
 
 
121
 
    /**
122
 
     * This field just sets up a default field object
123
 
     *
124
 
     * @return bool
125
 
     */
126
 
    function define_default_field() {
127
 
        global $OUTPUT;
128
 
        if (empty($this->data->id)) {
129
 
            echo $OUTPUT->notification('Programmer error: dataid not defined in field class');
130
 
        }
131
 
        $this->field = new stdClass();
132
 
        $this->field->id = 0;
133
 
        $this->field->dataid = $this->data->id;
134
 
        $this->field->type   = $this->type;
135
 
        $this->field->param1 = '';
136
 
        $this->field->param2 = '';
137
 
        $this->field->param3 = '';
138
 
        $this->field->name = '';
139
 
        $this->field->description = '';
140
 
 
141
 
        return true;
142
 
    }
143
 
 
144
 
    /**
145
 
     * Set up the field object according to data in an object.  Now is the time to clean it!
146
 
     *
147
 
     * @return bool
148
 
     */
149
 
    function define_field($data) {
150
 
        $this->field->type        = $this->type;
151
 
        $this->field->dataid      = $this->data->id;
152
 
 
153
 
        $this->field->name        = trim($data->name);
154
 
        $this->field->description = trim($data->description);
155
 
 
156
 
        if (isset($data->param1)) {
157
 
            $this->field->param1 = trim($data->param1);
158
 
        }
159
 
        if (isset($data->param2)) {
160
 
            $this->field->param2 = trim($data->param2);
161
 
        }
162
 
        if (isset($data->param3)) {
163
 
            $this->field->param3 = trim($data->param3);
164
 
        }
165
 
        if (isset($data->param4)) {
166
 
            $this->field->param4 = trim($data->param4);
167
 
        }
168
 
        if (isset($data->param5)) {
169
 
            $this->field->param5 = trim($data->param5);
170
 
        }
171
 
 
172
 
        return true;
173
 
    }
174
 
 
175
 
    /**
176
 
     * Insert a new field in the database
177
 
     * We assume the field object is already defined as $this->field
178
 
     *
179
 
     * @global object
180
 
     * @return bool
181
 
     */
182
 
    function insert_field() {
183
 
        global $DB, $OUTPUT;
184
 
 
185
 
        if (empty($this->field)) {
186
 
            echo $OUTPUT->notification('Programmer error: Field has not been defined yet!  See define_field()');
187
 
            return false;
188
 
        }
189
 
 
190
 
        $this->field->id = $DB->insert_record('data_fields',$this->field);
191
 
        return true;
192
 
    }
193
 
 
194
 
 
195
 
    /**
196
 
     * Update a field in the database
197
 
     *
198
 
     * @global object
199
 
     * @return bool
200
 
     */
201
 
    function update_field() {
202
 
        global $DB;
203
 
 
204
 
        $DB->update_record('data_fields', $this->field);
205
 
        return true;
206
 
    }
207
 
 
208
 
    /**
209
 
     * Delete a field completely
210
 
     *
211
 
     * @global object
212
 
     * @return bool
213
 
     */
214
 
    function delete_field() {
215
 
        global $DB;
216
 
 
217
 
        if (!empty($this->field->id)) {
218
 
            $this->delete_content();
219
 
            $DB->delete_records('data_fields', array('id'=>$this->field->id));
220
 
        }
221
 
        return true;
222
 
    }
223
 
 
224
 
    /**
225
 
     * Print the relevant form element in the ADD template for this field
226
 
     *
227
 
     * @global object
228
 
     * @param int $recordid
229
 
     * @return string
230
 
     */
231
 
    function display_add_field($recordid=0){
232
 
        global $DB;
233
 
 
234
 
        if ($recordid){
235
 
            $content = $DB->get_field('data_content', 'content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid));
236
 
        } else {
237
 
            $content = '';
238
 
        }
239
 
 
240
 
        // beware get_field returns false for new, empty records MDL-18567
241
 
        if ($content===false) {
242
 
            $content='';
243
 
        }
244
 
 
245
 
        $str = '<div title="'.s($this->field->description).'">';
246
 
        $str .= '<input style="width:300px;" type="text" name="field_'.$this->field->id.'" id="field_'.$this->field->id.'" value="'.s($content).'" />';
247
 
        $str .= '</div>';
248
 
 
249
 
        return $str;
250
 
    }
251
 
 
252
 
    /**
253
 
     * Print the relevant form element to define the attributes for this field
254
 
     * viewable by teachers only.
255
 
     *
256
 
     * @global object
257
 
     * @global object
258
 
     * @return void Output is echo'd
259
 
     */
260
 
    function display_edit_field() {
261
 
        global $CFG, $DB, $OUTPUT;
262
 
 
263
 
        if (empty($this->field)) {   // No field has been defined yet, try and make one
264
 
            $this->define_default_field();
265
 
        }
266
 
        echo $OUTPUT->box_start('generalbox boxaligncenter boxwidthwide');
267
 
 
268
 
        echo '<form id="editfield" action="'.$CFG->wwwroot.'/mod/data/field.php" method="post">'."\n";
269
 
        echo '<input type="hidden" name="d" value="'.$this->data->id.'" />'."\n";
270
 
        if (empty($this->field->id)) {
271
 
            echo '<input type="hidden" name="mode" value="add" />'."\n";
272
 
            $savebutton = get_string('add');
273
 
        } else {
274
 
            echo '<input type="hidden" name="fid" value="'.$this->field->id.'" />'."\n";
275
 
            echo '<input type="hidden" name="mode" value="update" />'."\n";
276
 
            $savebutton = get_string('savechanges');
277
 
        }
278
 
        echo '<input type="hidden" name="type" value="'.$this->type.'" />'."\n";
279
 
        echo '<input name="sesskey" value="'.sesskey().'" type="hidden" />'."\n";
280
 
 
281
 
        echo $OUTPUT->heading($this->name());
282
 
 
283
 
        require_once($CFG->dirroot.'/mod/data/field/'.$this->type.'/mod.html');
284
 
 
285
 
        echo '<div class="mdl-align">';
286
 
        echo '<input type="submit" value="'.$savebutton.'" />'."\n";
287
 
        echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />'."\n";
288
 
        echo '</div>';
289
 
 
290
 
        echo '</form>';
291
 
 
292
 
        echo $OUTPUT->box_end();
293
 
    }
294
 
 
295
 
    /**
296
 
     * Display the content of the field in browse mode
297
 
     *
298
 
     * @global object
299
 
     * @param int $recordid
300
 
     * @param object $template
301
 
     * @return bool|string
302
 
     */
303
 
    function display_browse_field($recordid, $template) {
304
 
        global $DB;
305
 
 
306
 
        if ($content = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
307
 
            if (isset($content->content)) {
308
 
                $options = new stdClass();
309
 
                if ($this->field->param1 == '1') {  // We are autolinking this field, so disable linking within us
310
 
                    //$content->content = '<span class="nolink">'.$content->content.'</span>';
311
 
                    //$content->content1 = FORMAT_HTML;
312
 
                    $options->filter=false;
313
 
                }
314
 
                $options->para = false;
315
 
                $str = format_text($content->content, $content->content1, $options);
316
 
            } else {
317
 
                $str = '';
318
 
            }
319
 
            return $str;
320
 
        }
321
 
        return false;
322
 
    }
323
 
 
324
 
    /**
325
 
     * Update the content of one data field in the data_content table
326
 
     * @global object
327
 
     * @param int $recordid
328
 
     * @param mixed $value
329
 
     * @param string $name
330
 
     * @return bool
331
 
     */
332
 
    function update_content($recordid, $value, $name=''){
333
 
        global $DB;
334
 
 
335
 
        $content = new stdClass();
336
 
        $content->fieldid = $this->field->id;
337
 
        $content->recordid = $recordid;
338
 
        $content->content = clean_param($value, PARAM_NOTAGS);
339
 
 
340
 
        if ($oldcontent = $DB->get_record('data_content', array('fieldid'=>$this->field->id, 'recordid'=>$recordid))) {
341
 
            $content->id = $oldcontent->id;
342
 
            return $DB->update_record('data_content', $content);
343
 
        } else {
344
 
            return $DB->insert_record('data_content', $content);
345
 
        }
346
 
    }
347
 
 
348
 
    /**
349
 
     * Delete all content associated with the field
350
 
     *
351
 
     * @global object
352
 
     * @param int $recordid
353
 
     * @return bool
354
 
     */
355
 
    function delete_content($recordid=0) {
356
 
        global $DB;
357
 
 
358
 
        if ($recordid) {
359
 
            $conditions = array('fieldid'=>$this->field->id, 'recordid'=>$recordid);
360
 
        } else {
361
 
            $conditions = array('fieldid'=>$this->field->id);
362
 
        }
363
 
 
364
 
        $rs = $DB->get_recordset('data_content', $conditions);
365
 
        if ($rs->valid()) {
366
 
            $fs = get_file_storage();
367
 
            foreach ($rs as $content) {
368
 
                $fs->delete_area_files($this->context->id, 'mod_data', 'content', $content->id);
369
 
            }
370
 
        }
371
 
        $rs->close();
372
 
 
373
 
        return $DB->delete_records('data_content', $conditions);
374
 
    }
375
 
 
376
 
    /**
377
 
     * Check if a field from an add form is empty
378
 
     *
379
 
     * @param mixed $value
380
 
     * @param mixed $name
381
 
     * @return bool
382
 
     */
383
 
    function notemptyfield($value, $name) {
384
 
        return !empty($value);
385
 
    }
386
 
 
387
 
    /**
388
 
     * Just in case a field needs to print something before the whole form
389
 
     */
390
 
    function print_before_form() {
391
 
    }
392
 
 
393
 
    /**
394
 
     * Just in case a field needs to print something after the whole form
395
 
     */
396
 
    function print_after_form() {
397
 
    }
398
 
 
399
 
 
400
 
    /**
401
 
     * Returns the sortable field for the content. By default, it's just content
402
 
     * but for some plugins, it could be content 1 - content4
403
 
     *
404
 
     * @return string
405
 
     */
406
 
    function get_sort_field() {
407
 
        return 'content';
408
 
    }
409
 
 
410
 
    /**
411
 
     * Returns the SQL needed to refer to the column.  Some fields may need to CAST() etc.
412
 
     *
413
 
     * @param string $fieldname
414
 
     * @return string $fieldname
415
 
     */
416
 
    function get_sort_sql($fieldname) {
417
 
        return $fieldname;
418
 
    }
419
 
 
420
 
    /**
421
 
     * Returns the name/type of the field
422
 
     *
423
 
     * @return string
424
 
     */
425
 
    function name() {
426
 
        return get_string('name'.$this->type, 'data');
427
 
    }
428
 
 
429
 
    /**
430
 
     * Prints the respective type icon
431
 
     *
432
 
     * @global object
433
 
     * @return string
434
 
     */
435
 
    function image() {
436
 
        global $OUTPUT;
437
 
 
438
 
        $params = array('d'=>$this->data->id, 'fid'=>$this->field->id, 'mode'=>'display', 'sesskey'=>sesskey());
439
 
        $link = new moodle_url('/mod/data/field.php', $params);
440
 
        $str = '<a href="'.$link->out().'">';
441
 
        $str .= '<img src="'.$OUTPUT->pix_url('field/'.$this->type, 'data') . '" ';
442
 
        $str .= 'height="'.$this->iconheight.'" width="'.$this->iconwidth.'" alt="'.$this->type.'" title="'.$this->type.'" /></a>';
443
 
        return $str;
444
 
    }
445
 
 
446
 
    /**
447
 
     * Per default, it is assumed that fields support text exporting.
448
 
     * Override this (return false) on fields not supporting text exporting.
449
 
     *
450
 
     * @return bool true
451
 
     */
452
 
    function text_export_supported() {
453
 
        return true;
454
 
    }
455
 
 
456
 
    /**
457
 
     * Per default, return the record's text value only from the "content" field.
458
 
     * Override this in fields class if necesarry.
459
 
     *
460
 
     * @param string $record
461
 
     * @return string
462
 
     */
463
 
    function export_text_value($record) {
464
 
        if ($this->text_export_supported()) {
465
 
            return $record->content;
466
 
        }
467
 
    }
468
 
 
469
 
    /**
470
 
     * @param string $relativepath
471
 
     * @return bool false
472
 
     */
473
 
    function file_ok($relativepath) {
474
 
        return false;
475
 
    }
476
 
}
477
 
 
478
 
 
479
 
/**
480
 
 * Given a template and a dataid, generate a default case template
481
 
 *
482
 
 * @global object
483
 
 * @param object $data
484
 
 * @param string template [addtemplate, singletemplate, listtempalte, rsstemplate]
485
 
 * @param int $recordid
486
 
 * @param bool $form
487
 
 * @param bool $update
488
 
 * @return bool|string
489
 
 */
490
 
function data_generate_default_template(&$data, $template, $recordid=0, $form=false, $update=true) {
491
 
    global $DB;
492
 
 
493
 
    if (!$data && !$template) {
494
 
        return false;
495
 
    }
496
 
    if ($template == 'csstemplate' or $template == 'jstemplate' ) {
497
 
        return '';
498
 
    }
499
 
 
500
 
    // get all the fields for that database
501
 
    if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'id')) {
502
 
 
503
 
        $table = new html_table();
504
 
        $table->attributes['class'] = 'mod-data-default-template';
505
 
        $table->colclasses = array('template-field', 'template-token');
506
 
        $table->data = array();
507
 
        foreach ($fields as $field) {
508
 
            if ($form) {   // Print forms instead of data
509
 
                $fieldobj = data_get_field($field, $data);
510
 
                $token = $fieldobj->display_add_field($recordid);
511
 
            } else {           // Just print the tag
512
 
                $token = '[['.$field->name.']]';
513
 
            }
514
 
            $table->data[] = array(
515
 
                $field->name.': ',
516
 
                $token
517
 
            );
518
 
        }
519
 
        if ($template == 'listtemplate') {
520
 
            $cell = new html_table_cell('##edit##  ##more##  ##delete##  ##approve##  ##export##');
521
 
            $cell->colspan = 2;
522
 
            $cell->attributes['class'] = 'controls';
523
 
            $table->data[] = new html_table_row(array($cell));
524
 
        } else if ($template == 'singletemplate') {
525
 
            $cell = new html_table_cell('##edit##  ##delete##  ##approve##  ##export##');
526
 
            $cell->colspan = 2;
527
 
            $cell->attributes['class'] = 'controls';
528
 
            $table->data[] = new html_table_row(array($cell));
529
 
        } else if ($template == 'asearchtemplate') {
530
 
            $row = new html_table_row(array(get_string('authorfirstname', 'data').': ', '##firstname##'));
531
 
            $row->attributes['class'] = 'searchcontrols';
532
 
            $table->data[] = $row;
533
 
            $row = new html_table_row(array(get_string('authorlastname', 'data').': ', '##lastname##'));
534
 
            $row->attributes['class'] = 'searchcontrols';
535
 
            $table->data[] = $row;
536
 
        }
537
 
 
538
 
        $str  = html_writer::start_tag('div', array('class' => 'defaulttemplate'));
539
 
        $str .= html_writer::table($table);
540
 
        $str .= html_writer::end_tag('div');
541
 
        if ($template == 'listtemplate'){
542
 
            $str .= html_writer::empty_tag('hr');
543
 
        }
544
 
 
545
 
        if ($update) {
546
 
            $newdata = new stdClass();
547
 
            $newdata->id = $data->id;
548
 
            $newdata->{$template} = $str;
549
 
            $DB->update_record('data', $newdata);
550
 
            $data->{$template} = $str;
551
 
        }
552
 
 
553
 
        return $str;
554
 
    }
555
 
}
556
 
 
557
 
 
558
 
/**
559
 
 * Search for a field name and replaces it with another one in all the
560
 
 * form templates. Set $newfieldname as '' if you want to delete the
561
 
 * field from the form.
562
 
 *
563
 
 * @global object
564
 
 * @param object $data
565
 
 * @param string $searchfieldname
566
 
 * @param string $newfieldname
567
 
 * @return bool
568
 
 */
569
 
function data_replace_field_in_templates($data, $searchfieldname, $newfieldname) {
570
 
    global $DB;
571
 
 
572
 
    if (!empty($newfieldname)) {
573
 
        $prestring = '[[';
574
 
        $poststring = ']]';
575
 
        $idpart = '#id';
576
 
 
577
 
    } else {
578
 
        $prestring = '';
579
 
        $poststring = '';
580
 
        $idpart = '';
581
 
    }
582
 
 
583
 
    $newdata = new stdClass();
584
 
    $newdata->id = $data->id;
585
 
    $newdata->singletemplate = str_ireplace('[['.$searchfieldname.']]',
586
 
            $prestring.$newfieldname.$poststring, $data->singletemplate);
587
 
 
588
 
    $newdata->listtemplate = str_ireplace('[['.$searchfieldname.']]',
589
 
            $prestring.$newfieldname.$poststring, $data->listtemplate);
590
 
 
591
 
    $newdata->addtemplate = str_ireplace('[['.$searchfieldname.']]',
592
 
            $prestring.$newfieldname.$poststring, $data->addtemplate);
593
 
 
594
 
    $newdata->addtemplate = str_ireplace('[['.$searchfieldname.'#id]]',
595
 
            $prestring.$newfieldname.$idpart.$poststring, $data->addtemplate);
596
 
 
597
 
    $newdata->rsstemplate = str_ireplace('[['.$searchfieldname.']]',
598
 
            $prestring.$newfieldname.$poststring, $data->rsstemplate);
599
 
 
600
 
    return $DB->update_record('data', $newdata);
601
 
}
602
 
 
603
 
 
604
 
/**
605
 
 * Appends a new field at the end of the form template.
606
 
 *
607
 
 * @global object
608
 
 * @param object $data
609
 
 * @param string $newfieldname
610
 
 */
611
 
function data_append_new_field_to_templates($data, $newfieldname) {
612
 
    global $DB;
613
 
 
614
 
    $newdata = new stdClass();
615
 
    $newdata->id = $data->id;
616
 
    $change = false;
617
 
 
618
 
    if (!empty($data->singletemplate)) {
619
 
        $newdata->singletemplate = $data->singletemplate.' [[' . $newfieldname .']]';
620
 
        $change = true;
621
 
    }
622
 
    if (!empty($data->addtemplate)) {
623
 
        $newdata->addtemplate = $data->addtemplate.' [[' . $newfieldname . ']]';
624
 
        $change = true;
625
 
    }
626
 
    if (!empty($data->rsstemplate)) {
627
 
        $newdata->rsstemplate = $data->singletemplate.' [[' . $newfieldname . ']]';
628
 
        $change = true;
629
 
    }
630
 
    if ($change) {
631
 
        $DB->update_record('data', $newdata);
632
 
    }
633
 
}
634
 
 
635
 
 
636
 
/**
637
 
 * given a field name
638
 
 * this function creates an instance of the particular subfield class
639
 
 *
640
 
 * @global object
641
 
 * @param string $name
642
 
 * @param object $data
643
 
 * @return object|bool
644
 
 */
645
 
function data_get_field_from_name($name, $data){
646
 
    global $DB;
647
 
 
648
 
    $field = $DB->get_record('data_fields', array('name'=>$name, 'dataid'=>$data->id));
649
 
 
650
 
    if ($field) {
651
 
        return data_get_field($field, $data);
652
 
    } else {
653
 
        return false;
654
 
    }
655
 
}
656
 
 
657
 
/**
658
 
 * given a field id
659
 
 * this function creates an instance of the particular subfield class
660
 
 *
661
 
 * @global object
662
 
 * @param int $fieldid
663
 
 * @param object $data
664
 
 * @return bool|object
665
 
 */
666
 
function data_get_field_from_id($fieldid, $data){
667
 
    global $DB;
668
 
 
669
 
    $field = $DB->get_record('data_fields', array('id'=>$fieldid, 'dataid'=>$data->id));
670
 
 
671
 
    if ($field) {
672
 
        return data_get_field($field, $data);
673
 
    } else {
674
 
        return false;
675
 
    }
676
 
}
677
 
 
678
 
/**
679
 
 * given a field id
680
 
 * this function creates an instance of the particular subfield class
681
 
 *
682
 
 * @global object
683
 
 * @param string $type
684
 
 * @param object $data
685
 
 * @return object
686
 
 */
687
 
function data_get_field_new($type, $data) {
688
 
    global $CFG;
689
 
 
690
 
    require_once($CFG->dirroot.'/mod/data/field/'.$type.'/field.class.php');
691
 
    $newfield = 'data_field_'.$type;
692
 
    $newfield = new $newfield(0, $data);
693
 
    return $newfield;
694
 
}
695
 
 
696
 
/**
697
 
 * returns a subclass field object given a record of the field, used to
698
 
 * invoke plugin methods
699
 
 * input: $param $field - record from db
700
 
 *
701
 
 * @global object
702
 
 * @param object $field
703
 
 * @param object $data
704
 
 * @param object $cm
705
 
 * @return object
706
 
 */
707
 
function data_get_field($field, $data, $cm=null) {
708
 
    global $CFG;
709
 
 
710
 
    if ($field) {
711
 
        require_once('field/'.$field->type.'/field.class.php');
712
 
        $newfield = 'data_field_'.$field->type;
713
 
        $newfield = new $newfield($field, $data, $cm);
714
 
        return $newfield;
715
 
    }
716
 
}
717
 
 
718
 
 
719
 
/**
720
 
 * Given record object (or id), returns true if the record belongs to the current user
721
 
 *
722
 
 * @global object
723
 
 * @global object
724
 
 * @param mixed $record record object or id
725
 
 * @return bool
726
 
 */
727
 
function data_isowner($record) {
728
 
    global $USER, $DB;
729
 
 
730
 
    if (!isloggedin()) { // perf shortcut
731
 
        return false;
732
 
    }
733
 
 
734
 
    if (!is_object($record)) {
735
 
        if (!$record = $DB->get_record('data_records', array('id'=>$record))) {
736
 
            return false;
737
 
        }
738
 
    }
739
 
 
740
 
    return ($record->userid == $USER->id);
741
 
}
742
 
 
743
 
/**
744
 
 * has a user reached the max number of entries?
745
 
 *
746
 
 * @param object $data
747
 
 * @return bool
748
 
 */
749
 
function data_atmaxentries($data){
750
 
    if (!$data->maxentries){
751
 
        return false;
752
 
 
753
 
    } else {
754
 
        return (data_numentries($data) >= $data->maxentries);
755
 
    }
756
 
}
757
 
 
758
 
/**
759
 
 * returns the number of entries already made by this user
760
 
 *
761
 
 * @global object
762
 
 * @global object
763
 
 * @param object $data
764
 
 * @return int
765
 
 */
766
 
function data_numentries($data){
767
 
    global $USER, $DB;
768
 
    $sql = 'SELECT COUNT(*) FROM {data_records} WHERE dataid=? AND userid=?';
769
 
    return $DB->count_records_sql($sql, array($data->id, $USER->id));
770
 
}
771
 
 
772
 
/**
773
 
 * function that takes in a dataid and adds a record
774
 
 * this is used everytime an add template is submitted
775
 
 *
776
 
 * @global object
777
 
 * @global object
778
 
 * @param object $data
779
 
 * @param int $groupid
780
 
 * @return bool
781
 
 */
782
 
function data_add_record($data, $groupid=0){
783
 
    global $USER, $DB;
784
 
 
785
 
    $cm = get_coursemodule_from_instance('data', $data->id);
786
 
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
787
 
 
788
 
    $record = new stdClass();
789
 
    $record->userid = $USER->id;
790
 
    $record->dataid = $data->id;
791
 
    $record->groupid = $groupid;
792
 
    $record->timecreated = $record->timemodified = time();
793
 
    if (has_capability('mod/data:approve', $context)) {
794
 
        $record->approved = 1;
795
 
    } else {
796
 
        $record->approved = 0;
797
 
    }
798
 
    return $DB->insert_record('data_records', $record);
799
 
}
800
 
 
801
 
/**
802
 
 * check the multple existence any tag in a template
803
 
 *
804
 
 * check to see if there are 2 or more of the same tag being used.
805
 
 *
806
 
 * @global object
807
 
 * @param int $dataid,
808
 
 * @param string $template
809
 
 * @return bool
810
 
 */
811
 
function data_tags_check($dataid, $template) {
812
 
    global $DB, $OUTPUT;
813
 
 
814
 
    // first get all the possible tags
815
 
    $fields = $DB->get_records('data_fields', array('dataid'=>$dataid));
816
 
    // then we generate strings to replace
817
 
    $tagsok = true; // let's be optimistic
818
 
    foreach ($fields as $field){
819
 
        $pattern="/\[\[".$field->name."\]\]/i";
820
 
        if (preg_match_all($pattern, $template, $dummy)>1){
821
 
            $tagsok = false;
822
 
            echo $OUTPUT->notification('[['.$field->name.']] - '.get_string('multipletags','data'));
823
 
        }
824
 
    }
825
 
    // else return true
826
 
    return $tagsok;
827
 
}
828
 
 
829
 
/**
830
 
 * Adds an instance of a data
831
 
 *
832
 
 * @global object
833
 
 * @param object $data
834
 
 * @return $int
835
 
 */
836
 
function data_add_instance($data) {
837
 
    global $DB;
838
 
 
839
 
    if (empty($data->assessed)) {
840
 
        $data->assessed = 0;
841
 
    }
842
 
 
843
 
    $data->timemodified = time();
844
 
 
845
 
    $data->id = $DB->insert_record('data', $data);
846
 
 
847
 
    data_grade_item_update($data);
848
 
 
849
 
    return $data->id;
850
 
}
851
 
 
852
 
/**
853
 
 * updates an instance of a data
854
 
 *
855
 
 * @global object
856
 
 * @param object $data
857
 
 * @return bool
858
 
 */
859
 
function data_update_instance($data) {
860
 
    global $DB, $OUTPUT;
861
 
 
862
 
    $data->timemodified = time();
863
 
    $data->id           = $data->instance;
864
 
 
865
 
    if (empty($data->assessed)) {
866
 
        $data->assessed = 0;
867
 
    }
868
 
 
869
 
    if (empty($data->ratingtime) or empty($data->assessed)) {
870
 
        $data->assesstimestart  = 0;
871
 
        $data->assesstimefinish = 0;
872
 
    }
873
 
 
874
 
    if (empty($data->notification)) {
875
 
        $data->notification = 0;
876
 
    }
877
 
 
878
 
    $DB->update_record('data', $data);
879
 
 
880
 
    data_grade_item_update($data);
881
 
 
882
 
    return true;
883
 
 
884
 
}
885
 
 
886
 
/**
887
 
 * deletes an instance of a data
888
 
 *
889
 
 * @global object
890
 
 * @param int $id
891
 
 * @return bool
892
 
 */
893
 
function data_delete_instance($id) {    // takes the dataid
894
 
    global $DB, $CFG;
895
 
 
896
 
    if (!$data = $DB->get_record('data', array('id'=>$id))) {
897
 
        return false;
898
 
    }
899
 
 
900
 
    $cm = get_coursemodule_from_instance('data', $data->id);
901
 
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
902
 
 
903
 
/// Delete all the associated information
904
 
 
905
 
    // files
906
 
    $fs = get_file_storage();
907
 
    $fs->delete_area_files($context->id, 'mod_data');
908
 
 
909
 
    // get all the records in this data
910
 
    $sql = "SELECT r.id
911
 
              FROM {data_records} r
912
 
             WHERE r.dataid = ?";
913
 
 
914
 
    $DB->delete_records_select('data_content', "recordid IN ($sql)", array($id));
915
 
 
916
 
    // delete all the records and fields
917
 
    $DB->delete_records('data_records', array('dataid'=>$id));
918
 
    $DB->delete_records('data_fields', array('dataid'=>$id));
919
 
 
920
 
    // Delete the instance itself
921
 
    $result = $DB->delete_records('data', array('id'=>$id));
922
 
 
923
 
    // cleanup gradebook
924
 
    data_grade_item_delete($data);
925
 
 
926
 
    return $result;
927
 
}
928
 
 
929
 
/**
930
 
 * returns a summary of data activity of this user
931
 
 *
932
 
 * @global object
933
 
 * @param object $course
934
 
 * @param object $user
935
 
 * @param object $mod
936
 
 * @param object $data
937
 
 * @return object|null
938
 
 */
939
 
function data_user_outline($course, $user, $mod, $data) {
940
 
    global $DB, $CFG;
941
 
    require_once("$CFG->libdir/gradelib.php");
942
 
 
943
 
    $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
944
 
    if (empty($grades->items[0]->grades)) {
945
 
        $grade = false;
946
 
    } else {
947
 
        $grade = reset($grades->items[0]->grades);
948
 
    }
949
 
 
950
 
 
951
 
    if ($countrecords = $DB->count_records('data_records', array('dataid'=>$data->id, 'userid'=>$user->id))) {
952
 
        $result = new stdClass();
953
 
        $result->info = get_string('numrecords', 'data', $countrecords);
954
 
        $lastrecord   = $DB->get_record_sql('SELECT id,timemodified FROM {data_records}
955
 
                                              WHERE dataid = ? AND userid = ?
956
 
                                           ORDER BY timemodified DESC', array($data->id, $user->id), true);
957
 
        $result->time = $lastrecord->timemodified;
958
 
        if ($grade) {
959
 
            $result->info .= ', ' . get_string('grade') . ': ' . $grade->str_long_grade;
960
 
        }
961
 
        return $result;
962
 
    } else if ($grade) {
963
 
        $result = new stdClass();
964
 
        $result->info = get_string('grade') . ': ' . $grade->str_long_grade;
965
 
 
966
 
        //datesubmitted == time created. dategraded == time modified or time overridden
967
 
        //if grade was last modified by the user themselves use date graded. Otherwise use date submitted
968
 
        //TODO: move this copied & pasted code somewhere in the grades API. See MDL-26704
969
 
        if ($grade->usermodified == $user->id || empty($grade->datesubmitted)) {
970
 
            $result->time = $grade->dategraded;
971
 
        } else {
972
 
            $result->time = $grade->datesubmitted;
973
 
        }
974
 
 
975
 
        return $result;
976
 
    }
977
 
    return NULL;
978
 
}
979
 
 
980
 
/**
981
 
 * Prints all the records uploaded by this user
982
 
 *
983
 
 * @global object
984
 
 * @param object $course
985
 
 * @param object $user
986
 
 * @param object $mod
987
 
 * @param object $data
988
 
 */
989
 
function data_user_complete($course, $user, $mod, $data) {
990
 
    global $DB, $CFG, $OUTPUT;
991
 
    require_once("$CFG->libdir/gradelib.php");
992
 
 
993
 
    $grades = grade_get_grades($course->id, 'mod', 'data', $data->id, $user->id);
994
 
    if (!empty($grades->items[0]->grades)) {
995
 
        $grade = reset($grades->items[0]->grades);
996
 
        echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
997
 
        if ($grade->str_feedback) {
998
 
            echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
999
 
        }
1000
 
    }
1001
 
 
1002
 
    if ($records = $DB->get_records('data_records', array('dataid'=>$data->id,'userid'=>$user->id), 'timemodified DESC')) {
1003
 
        data_print_template('singletemplate', $records, $data);
1004
 
    }
1005
 
}
1006
 
 
1007
 
/**
1008
 
 * Return grade for given user or all users.
1009
 
 *
1010
 
 * @global object
1011
 
 * @param object $data
1012
 
 * @param int $userid optional user id, 0 means all users
1013
 
 * @return array array of grades, false if none
1014
 
 */
1015
 
function data_get_user_grades($data, $userid=0) {
1016
 
    global $CFG;
1017
 
 
1018
 
    require_once($CFG->dirroot.'/rating/lib.php');
1019
 
 
1020
 
    $ratingoptions = new stdClass;
1021
 
    $ratingoptions->component = 'mod_data';
1022
 
    $ratingoptions->ratingarea = 'entry';
1023
 
    $ratingoptions->modulename = 'data';
1024
 
    $ratingoptions->moduleid   = $data->id;
1025
 
 
1026
 
    $ratingoptions->userid = $userid;
1027
 
    $ratingoptions->aggregationmethod = $data->assessed;
1028
 
    $ratingoptions->scaleid = $data->scale;
1029
 
    $ratingoptions->itemtable = 'data_records';
1030
 
    $ratingoptions->itemtableusercolumn = 'userid';
1031
 
 
1032
 
    $rm = new rating_manager();
1033
 
    return $rm->get_user_grades($ratingoptions);
1034
 
}
1035
 
 
1036
 
/**
1037
 
 * Update activity grades
1038
 
 *
1039
 
 * @global object
1040
 
 * @global object
1041
 
 * @param object $data
1042
 
 * @param int $userid specific user only, 0 means all
1043
 
 * @param bool $nullifnone
1044
 
 */
1045
 
function data_update_grades($data, $userid=0, $nullifnone=true) {
1046
 
    global $CFG, $DB;
1047
 
    require_once($CFG->libdir.'/gradelib.php');
1048
 
 
1049
 
    if (!$data->assessed) {
1050
 
        data_grade_item_update($data);
1051
 
 
1052
 
    } else if ($grades = data_get_user_grades($data, $userid)) {
1053
 
        data_grade_item_update($data, $grades);
1054
 
 
1055
 
    } else if ($userid and $nullifnone) {
1056
 
        $grade = new stdClass();
1057
 
        $grade->userid   = $userid;
1058
 
        $grade->rawgrade = NULL;
1059
 
        data_grade_item_update($data, $grade);
1060
 
 
1061
 
    } else {
1062
 
        data_grade_item_update($data);
1063
 
    }
1064
 
}
1065
 
 
1066
 
/**
1067
 
 * Update all grades in gradebook.
1068
 
 *
1069
 
 * @global object
1070
 
 */
1071
 
function data_upgrade_grades() {
1072
 
    global $DB;
1073
 
 
1074
 
    $sql = "SELECT COUNT('x')
1075
 
              FROM {data} d, {course_modules} cm, {modules} m
1076
 
             WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
1077
 
    $count = $DB->count_records_sql($sql);
1078
 
 
1079
 
    $sql = "SELECT d.*, cm.idnumber AS cmidnumber, d.course AS courseid
1080
 
              FROM {data} d, {course_modules} cm, {modules} m
1081
 
             WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id";
1082
 
    $rs = $DB->get_recordset_sql($sql);
1083
 
    if ($rs->valid()) {
1084
 
        // too much debug output
1085
 
        $pbar = new progress_bar('dataupgradegrades', 500, true);
1086
 
        $i=0;
1087
 
        foreach ($rs as $data) {
1088
 
            $i++;
1089
 
            upgrade_set_timeout(60*5); // set up timeout, may also abort execution
1090
 
            data_update_grades($data, 0, false);
1091
 
            $pbar->update($i, $count, "Updating Database grades ($i/$count).");
1092
 
        }
1093
 
    }
1094
 
    $rs->close();
1095
 
}
1096
 
 
1097
 
/**
1098
 
 * Update/create grade item for given data
1099
 
 *
1100
 
 * @global object
1101
 
 * @param object $data object with extra cmidnumber
1102
 
 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
1103
 
 * @return object grade_item
1104
 
 */
1105
 
function data_grade_item_update($data, $grades=NULL) {
1106
 
    global $CFG;
1107
 
    require_once($CFG->libdir.'/gradelib.php');
1108
 
 
1109
 
    $params = array('itemname'=>$data->name, 'idnumber'=>$data->cmidnumber);
1110
 
 
1111
 
    if (!$data->assessed or $data->scale == 0) {
1112
 
        $params['gradetype'] = GRADE_TYPE_NONE;
1113
 
 
1114
 
    } else if ($data->scale > 0) {
1115
 
        $params['gradetype'] = GRADE_TYPE_VALUE;
1116
 
        $params['grademax']  = $data->scale;
1117
 
        $params['grademin']  = 0;
1118
 
 
1119
 
    } else if ($data->scale < 0) {
1120
 
        $params['gradetype'] = GRADE_TYPE_SCALE;
1121
 
        $params['scaleid']   = -$data->scale;
1122
 
    }
1123
 
 
1124
 
    if ($grades  === 'reset') {
1125
 
        $params['reset'] = true;
1126
 
        $grades = NULL;
1127
 
    }
1128
 
 
1129
 
    return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, $grades, $params);
1130
 
}
1131
 
 
1132
 
/**
1133
 
 * Delete grade item for given data
1134
 
 *
1135
 
 * @global object
1136
 
 * @param object $data object
1137
 
 * @return object grade_item
1138
 
 */
1139
 
function data_grade_item_delete($data) {
1140
 
    global $CFG;
1141
 
    require_once($CFG->libdir.'/gradelib.php');
1142
 
 
1143
 
    return grade_update('mod/data', $data->course, 'mod', 'data', $data->id, 0, NULL, array('deleted'=>1));
1144
 
}
1145
 
 
1146
 
/**
1147
 
 * returns a list of participants of this database
1148
 
 *
1149
 
 * Returns the users with data in one data
1150
 
 * (users with records in data_records, data_comments and ratings)
1151
 
 *
1152
 
 * @todo: deprecated - to be deleted in 2.2
1153
 
 *
1154
 
 * @param int $dataid
1155
 
 * @return array
1156
 
 */
1157
 
function data_get_participants($dataid) {
1158
 
    global $DB;
1159
 
 
1160
 
    $params = array('dataid' => $dataid);
1161
 
 
1162
 
    $sql = "SELECT DISTINCT u.id, u.id
1163
 
              FROM {user} u,
1164
 
                   {data_records} r
1165
 
             WHERE r.dataid = :dataid AND
1166
 
                   u.id = r.userid";
1167
 
    $records = $DB->get_records_sql($sql, $params);
1168
 
 
1169
 
    $sql = "SELECT DISTINCT u.id, u.id
1170
 
              FROM {user} u,
1171
 
                   {data_records} r,
1172
 
                   {comments} c
1173
 
             WHERE r.dataid = ? AND
1174
 
                   u.id = r.userid AND
1175
 
                   r.id = c.itemid AND
1176
 
                   c.commentarea = 'database_entry'";
1177
 
    $comments = $DB->get_records_sql($sql, $params);
1178
 
 
1179
 
    $sql = "SELECT DISTINCT u.id, u.id
1180
 
              FROM {user} u,
1181
 
                   {data_records} r,
1182
 
                   {ratings} a
1183
 
             WHERE r.dataid = ? AND
1184
 
                   u.id = r.userid AND
1185
 
                   r.id = a.itemid AND
1186
 
                   a.component = 'mod_data' AND
1187
 
                   a.ratingarea = 'entry'";
1188
 
    $ratings = $DB->get_records_sql($sql, $params);
1189
 
 
1190
 
    $participants = array();
1191
 
 
1192
 
    if ($records) {
1193
 
        foreach ($records as $record) {
1194
 
            $participants[$record->id] = $record;
1195
 
        }
1196
 
    }
1197
 
    if ($comments) {
1198
 
        foreach ($comments as $comment) {
1199
 
            $participants[$comment->id] = $comment;
1200
 
        }
1201
 
    }
1202
 
    if ($ratings) {
1203
 
        foreach ($ratings as $rating) {
1204
 
            $participants[$rating->id] = $rating;
1205
 
        }
1206
 
    }
1207
 
 
1208
 
    return $participants;
1209
 
}
1210
 
 
1211
 
// junk functions
1212
 
/**
1213
 
 * takes a list of records, the current data, a search string,
1214
 
 * and mode to display prints the translated template
1215
 
 *
1216
 
 * @global object
1217
 
 * @global object
1218
 
 * @param string $template
1219
 
 * @param array $records
1220
 
 * @param object $data
1221
 
 * @param string $search
1222
 
 * @param int $page
1223
 
 * @param bool $return
1224
 
 * @return mixed
1225
 
 */
1226
 
function data_print_template($template, $records, $data, $search='', $page=0, $return=false) {
1227
 
    global $CFG, $DB, $OUTPUT;
1228
 
    $cm = get_coursemodule_from_instance('data', $data->id);
1229
 
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1230
 
 
1231
 
    static $fields = NULL;
1232
 
    static $isteacher;
1233
 
    static $dataid = NULL;
1234
 
 
1235
 
    if (empty($dataid)) {
1236
 
        $dataid = $data->id;
1237
 
    } else if ($dataid != $data->id) {
1238
 
        $fields = NULL;
1239
 
    }
1240
 
 
1241
 
    if (empty($fields)) {
1242
 
        $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1243
 
        foreach ($fieldrecords as $fieldrecord) {
1244
 
            $fields[]= data_get_field($fieldrecord, $data);
1245
 
        }
1246
 
        $isteacher = has_capability('mod/data:managetemplates', $context);
1247
 
    }
1248
 
 
1249
 
    if (empty($records)) {
1250
 
        return;
1251
 
    }
1252
 
 
1253
 
    // Check whether this activity is read-only at present
1254
 
    $readonly = data_in_readonly_period($data);
1255
 
 
1256
 
    foreach ($records as $record) {   // Might be just one for the single template
1257
 
 
1258
 
    // Replacing tags
1259
 
        $patterns = array();
1260
 
        $replacement = array();
1261
 
 
1262
 
    // Then we generate strings to replace for normal tags
1263
 
        foreach ($fields as $field) {
1264
 
            $patterns[]='[['.$field->field->name.']]';
1265
 
            $replacement[] = highlight($search, $field->display_browse_field($record->id, $template));
1266
 
        }
1267
 
 
1268
 
    // Replacing special tags (##Edit##, ##Delete##, ##More##)
1269
 
        $patterns[]='##edit##';
1270
 
        $patterns[]='##delete##';
1271
 
        if (has_capability('mod/data:manageentries', $context) || (!$readonly && data_isowner($record->id))) {
1272
 
            $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/edit.php?d='
1273
 
                             .$data->id.'&amp;rid='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('t/edit') . '" class="iconsmall" alt="'.get_string('edit').'" title="'.get_string('edit').'" /></a>';
1274
 
            $replacement[] = '<a href="'.$CFG->wwwroot.'/mod/data/view.php?d='
1275
 
                             .$data->id.'&amp;delete='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('t/delete') . '" class="iconsmall" alt="'.get_string('delete').'" title="'.get_string('delete').'" /></a>';
1276
 
        } else {
1277
 
            $replacement[] = '';
1278
 
            $replacement[] = '';
1279
 
        }
1280
 
 
1281
 
        $moreurl = $CFG->wwwroot . '/mod/data/view.php?d=' . $data->id . '&amp;rid=' . $record->id;
1282
 
        if ($search) {
1283
 
            $moreurl .= '&amp;filter=1';
1284
 
        }
1285
 
        $patterns[]='##more##';
1286
 
        $replacement[] = '<a href="' . $moreurl . '"><img src="' . $OUTPUT->pix_url('i/search') . '" class="iconsmall" alt="' . get_string('more', 'data') . '" title="' . get_string('more', 'data') . '" /></a>';
1287
 
 
1288
 
        $patterns[]='##moreurl##';
1289
 
        $replacement[] = $moreurl;
1290
 
 
1291
 
        $patterns[]='##user##';
1292
 
        $replacement[] = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$record->userid.
1293
 
                               '&amp;course='.$data->course.'">'.fullname($record).'</a>';
1294
 
 
1295
 
        $patterns[]='##export##';
1296
 
 
1297
 
        if (!empty($CFG->enableportfolios) && ($template == 'singletemplate' || $template == 'listtemplate')
1298
 
            && ((has_capability('mod/data:exportentry', $context)
1299
 
                || (data_isowner($record->id) && has_capability('mod/data:exportownentry', $context))))) {
1300
 
            require_once($CFG->libdir . '/portfoliolib.php');
1301
 
            $button = new portfolio_add_button();
1302
 
            $button->set_callback_options('data_portfolio_caller', array('id' => $cm->id, 'recordid' => $record->id), '/mod/data/locallib.php');
1303
 
            list($formats, $files) = data_portfolio_caller::formats($fields, $record);
1304
 
            $button->set_formats($formats);
1305
 
            $replacement[] = $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1306
 
        } else {
1307
 
            $replacement[] = '';
1308
 
        }
1309
 
 
1310
 
        $patterns[] = '##timeadded##';
1311
 
        $replacement[] = userdate($record->timecreated);
1312
 
 
1313
 
        $patterns[] = '##timemodified##';
1314
 
        $replacement [] = userdate($record->timemodified);
1315
 
 
1316
 
        $patterns[]='##approve##';
1317
 
        if (has_capability('mod/data:approve', $context) && ($data->approval) && (!$record->approved)){
1318
 
            $replacement[] = '<span class="approve"><a href="'.$CFG->wwwroot.'/mod/data/view.php?d='.$data->id.'&amp;approve='.$record->id.'&amp;sesskey='.sesskey().'"><img src="'.$OUTPUT->pix_url('i/approve') . '" class="iconsmall" alt="'.get_string('approve').'" /></a></span>';
1319
 
        } else {
1320
 
            $replacement[] = '';
1321
 
        }
1322
 
 
1323
 
        $patterns[]='##comments##';
1324
 
        if (($template == 'listtemplate') && ($data->comments)) {
1325
 
 
1326
 
            if (!empty($CFG->usecomments)) {
1327
 
                require_once($CFG->dirroot  . '/comment/lib.php');
1328
 
                list($context, $course, $cm) = get_context_info_array($context->id);
1329
 
                $cmt = new stdClass();
1330
 
                $cmt->context = $context;
1331
 
                $cmt->course  = $course;
1332
 
                $cmt->cm      = $cm;
1333
 
                $cmt->area    = 'database_entry';
1334
 
                $cmt->itemid  = $record->id;
1335
 
                $cmt->showcount = true;
1336
 
                $cmt->component = 'mod_data';
1337
 
                $comment = new comment($cmt);
1338
 
                $replacement[] = $comment->output(true);
1339
 
            }
1340
 
        } else {
1341
 
            $replacement[] = '';
1342
 
        }
1343
 
 
1344
 
        // actual replacement of the tags
1345
 
        $newtext = str_ireplace($patterns, $replacement, $data->{$template});
1346
 
 
1347
 
        // no more html formatting and filtering - see MDL-6635
1348
 
        if ($return) {
1349
 
            return $newtext;
1350
 
        } else {
1351
 
            echo $newtext;
1352
 
 
1353
 
            // hack alert - return is always false in singletemplate anyway ;-)
1354
 
            /**********************************
1355
 
             *    Printing Ratings Form       *
1356
 
             *********************************/
1357
 
            if ($template == 'singletemplate') {    //prints ratings options
1358
 
                data_print_ratings($data, $record);
1359
 
            }
1360
 
 
1361
 
            /**********************************
1362
 
             *    Printing Comments Form       *
1363
 
             *********************************/
1364
 
            if (($template == 'singletemplate') && ($data->comments)) {
1365
 
                if (!empty($CFG->usecomments)) {
1366
 
                    require_once($CFG->dirroot . '/comment/lib.php');
1367
 
                    list($context, $course, $cm) = get_context_info_array($context->id);
1368
 
                    $cmt = new stdClass();
1369
 
                    $cmt->context = $context;
1370
 
                    $cmt->course  = $course;
1371
 
                    $cmt->cm      = $cm;
1372
 
                    $cmt->area    = 'database_entry';
1373
 
                    $cmt->itemid  = $record->id;
1374
 
                    $cmt->showcount = true;
1375
 
                    $cmt->component = 'mod_data';
1376
 
                    $comment = new comment($cmt);
1377
 
                    $comment->output(false);
1378
 
                }
1379
 
            }
1380
 
        }
1381
 
    }
1382
 
}
1383
 
 
1384
 
/**
1385
 
 * Return rating related permissions
1386
 
 *
1387
 
 * @param string $contextid the context id
1388
 
 * @param string $component the component to get rating permissions for
1389
 
 * @param string $ratingarea the rating area to get permissions for
1390
 
 * @return array an associative array of the user's rating permissions
1391
 
 */
1392
 
function data_rating_permissions($contextid, $component, $ratingarea) {
1393
 
    $context = get_context_instance_by_id($contextid, MUST_EXIST);
1394
 
    if ($component != 'mod_data' || $ratingarea != 'entry') {
1395
 
        return null;
1396
 
    }
1397
 
    return array(
1398
 
        'view'    => has_capability('mod/data:viewrating',$context),
1399
 
        'viewany' => has_capability('mod/data:viewanyrating',$context),
1400
 
        'viewall' => has_capability('mod/data:viewallratings',$context),
1401
 
        'rate'    => has_capability('mod/data:rate',$context)
1402
 
    );
1403
 
}
1404
 
 
1405
 
/**
1406
 
 * Validates a submitted rating
1407
 
 * @param array $params submitted data
1408
 
 *            context => object the context in which the rated items exists [required]
1409
 
 *            itemid => int the ID of the object being rated
1410
 
 *            scaleid => int the scale from which the user can select a rating. Used for bounds checking. [required]
1411
 
 *            rating => int the submitted rating
1412
 
 *            rateduserid => int the id of the user whose items have been rated. NOT the user who submitted the ratings. 0 to update all. [required]
1413
 
 *            aggregation => int the aggregation method to apply when calculating grades ie RATING_AGGREGATE_AVERAGE [required]
1414
 
 * @return boolean true if the rating is valid. Will throw rating_exception if not
1415
 
 */
1416
 
function data_rating_validate($params) {
1417
 
    global $DB, $USER;
1418
 
 
1419
 
    // Check the component is mod_data
1420
 
    if ($params['component'] != 'mod_data') {
1421
 
        throw new rating_exception('invalidcomponent');
1422
 
    }
1423
 
 
1424
 
    // Check the ratingarea is entry (the only rating area in data module)
1425
 
    if ($params['ratingarea'] != 'entry') {
1426
 
        throw new rating_exception('invalidratingarea');
1427
 
    }
1428
 
 
1429
 
    // Check the rateduserid is not the current user .. you can't rate your own entries
1430
 
    if ($params['rateduserid'] == $USER->id) {
1431
 
        throw new rating_exception('nopermissiontorate');
1432
 
    }
1433
 
 
1434
 
    $datasql = "SELECT d.id as dataid, d.scale, d.course, r.userid as userid, d.approval, r.approved, r.timecreated, d.assesstimestart, d.assesstimefinish, r.groupid
1435
 
                  FROM {data_records} r
1436
 
                  JOIN {data} d ON r.dataid = d.id
1437
 
                 WHERE r.id = :itemid";
1438
 
    $dataparams = array('itemid'=>$params['itemid']);
1439
 
    if (!$info = $DB->get_record_sql($datasql, $dataparams)) {
1440
 
        //item doesn't exist
1441
 
        throw new rating_exception('invaliditemid');
1442
 
    }
1443
 
 
1444
 
    if ($info->scale != $params['scaleid']) {
1445
 
        //the scale being submitted doesnt match the one in the database
1446
 
        throw new rating_exception('invalidscaleid');
1447
 
    }
1448
 
 
1449
 
    //check that the submitted rating is valid for the scale
1450
 
 
1451
 
    // lower limit
1452
 
    if ($params['rating'] < 0  && $params['rating'] != RATING_UNSET_RATING) {
1453
 
        throw new rating_exception('invalidnum');
1454
 
    }
1455
 
 
1456
 
    // upper limit
1457
 
    if ($info->scale < 0) {
1458
 
        //its a custom scale
1459
 
        $scalerecord = $DB->get_record('scale', array('id' => -$info->scale));
1460
 
        if ($scalerecord) {
1461
 
            $scalearray = explode(',', $scalerecord->scale);
1462
 
            if ($params['rating'] > count($scalearray)) {
1463
 
                throw new rating_exception('invalidnum');
1464
 
            }
1465
 
        } else {
1466
 
            throw new rating_exception('invalidscaleid');
1467
 
        }
1468
 
    } else if ($params['rating'] > $info->scale) {
1469
 
        //if its numeric and submitted rating is above maximum
1470
 
        throw new rating_exception('invalidnum');
1471
 
    }
1472
 
 
1473
 
    if ($info->approval && !$info->approved) {
1474
 
        //database requires approval but this item isnt approved
1475
 
        throw new rating_exception('nopermissiontorate');
1476
 
    }
1477
 
 
1478
 
    // check the item we're rating was created in the assessable time window
1479
 
    if (!empty($info->assesstimestart) && !empty($info->assesstimefinish)) {
1480
 
        if ($info->timecreated < $info->assesstimestart || $info->timecreated > $info->assesstimefinish) {
1481
 
            throw new rating_exception('notavailable');
1482
 
        }
1483
 
    }
1484
 
 
1485
 
    $course = $DB->get_record('course', array('id'=>$info->course), '*', MUST_EXIST);
1486
 
    $cm = get_coursemodule_from_instance('data', $info->dataid, $course->id, false, MUST_EXIST);
1487
 
    $context = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
1488
 
 
1489
 
    // if the supplied context doesnt match the item's context
1490
 
    if ($context->id != $params['context']->id) {
1491
 
        throw new rating_exception('invalidcontext');
1492
 
    }
1493
 
 
1494
 
    // Make sure groups allow this user to see the item they're rating
1495
 
    $groupid = $info->groupid;
1496
 
    if ($groupid > 0 and $groupmode = groups_get_activity_groupmode($cm, $course)) {   // Groups are being used
1497
 
        if (!groups_group_exists($groupid)) { // Can't find group
1498
 
            throw new rating_exception('cannotfindgroup');//something is wrong
1499
 
        }
1500
 
 
1501
 
        if (!groups_is_member($groupid) and !has_capability('moodle/site:accessallgroups', $context)) {
1502
 
            // do not allow rating of posts from other groups when in SEPARATEGROUPS or VISIBLEGROUPS
1503
 
            throw new rating_exception('notmemberofgroup');
1504
 
        }
1505
 
    }
1506
 
 
1507
 
    return true;
1508
 
}
1509
 
 
1510
 
 
1511
 
/**
1512
 
 * function that takes in the current data, number of items per page,
1513
 
 * a search string and prints a preference box in view.php
1514
 
 *
1515
 
 * This preference box prints a searchable advanced search template if
1516
 
 *     a) A template is defined
1517
 
 *  b) The advanced search checkbox is checked.
1518
 
 *
1519
 
 * @global object
1520
 
 * @global object
1521
 
 * @param object $data
1522
 
 * @param int $perpage
1523
 
 * @param string $search
1524
 
 * @param string $sort
1525
 
 * @param string $order
1526
 
 * @param array $search_array
1527
 
 * @param int $advanced
1528
 
 * @param string $mode
1529
 
 * @return void
1530
 
 */
1531
 
function data_print_preference_form($data, $perpage, $search, $sort='', $order='ASC', $search_array = '', $advanced = 0, $mode= ''){
1532
 
    global $CFG, $DB, $PAGE, $OUTPUT;
1533
 
 
1534
 
    $cm = get_coursemodule_from_instance('data', $data->id);
1535
 
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1536
 
    echo '<br /><div class="datapreferences">';
1537
 
    echo '<form id="options" action="view.php" method="get">';
1538
 
    echo '<div>';
1539
 
    echo '<input type="hidden" name="d" value="'.$data->id.'" />';
1540
 
    if ($mode =='asearch') {
1541
 
        $advanced = 1;
1542
 
        echo '<input type="hidden" name="mode" value="list" />';
1543
 
    }
1544
 
    echo '<label for="pref_perpage">'.get_string('pagesize','data').'</label> ';
1545
 
    $pagesizes = array(2=>2,3=>3,4=>4,5=>5,6=>6,7=>7,8=>8,9=>9,10=>10,15=>15,
1546
 
                       20=>20,30=>30,40=>40,50=>50,100=>100,200=>200,300=>300,400=>400,500=>500,1000=>1000);
1547
 
    echo html_writer::select($pagesizes, 'perpage', $perpage, false, array('id'=>'pref_perpage'));
1548
 
    echo '<div id="reg_search" style="display: ';
1549
 
    if ($advanced) {
1550
 
        echo 'none';
1551
 
    }
1552
 
    else {
1553
 
        echo 'inline';
1554
 
    }
1555
 
    echo ';" >&nbsp;&nbsp;&nbsp;<label for="pref_search">'.get_string('search').'</label> <input type="text" size="16" name="search" id= "pref_search" value="'.s($search).'" /></div>';
1556
 
    echo '&nbsp;&nbsp;&nbsp;<label for="pref_sortby">'.get_string('sortby').'</label> ';
1557
 
    // foreach field, print the option
1558
 
    echo '<select name="sort" id="pref_sortby">';
1559
 
    if ($fields = $DB->get_records('data_fields', array('dataid'=>$data->id), 'name')) {
1560
 
        echo '<optgroup label="'.get_string('fields', 'data').'">';
1561
 
        foreach ($fields as $field) {
1562
 
            if ($field->id == $sort) {
1563
 
                echo '<option value="'.$field->id.'" selected="selected">'.$field->name.'</option>';
1564
 
            } else {
1565
 
                echo '<option value="'.$field->id.'">'.$field->name.'</option>';
1566
 
            }
1567
 
        }
1568
 
        echo '</optgroup>';
1569
 
    }
1570
 
    $options = array();
1571
 
    $options[DATA_TIMEADDED]    = get_string('timeadded', 'data');
1572
 
    $options[DATA_TIMEMODIFIED] = get_string('timemodified', 'data');
1573
 
    $options[DATA_FIRSTNAME]    = get_string('authorfirstname', 'data');
1574
 
    $options[DATA_LASTNAME]     = get_string('authorlastname', 'data');
1575
 
    if ($data->approval and has_capability('mod/data:approve', $context)) {
1576
 
        $options[DATA_APPROVED] = get_string('approved', 'data');
1577
 
    }
1578
 
    echo '<optgroup label="'.get_string('other', 'data').'">';
1579
 
    foreach ($options as $key => $name) {
1580
 
        if ($key == $sort) {
1581
 
            echo '<option value="'.$key.'" selected="selected">'.$name.'</option>';
1582
 
        } else {
1583
 
            echo '<option value="'.$key.'">'.$name.'</option>';
1584
 
        }
1585
 
    }
1586
 
    echo '</optgroup>';
1587
 
    echo '</select>';
1588
 
    echo '<label for="pref_order" class="accesshide">'.get_string('order').'</label>';
1589
 
    echo '<select id="pref_order" name="order">';
1590
 
    if ($order == 'ASC') {
1591
 
        echo '<option value="ASC" selected="selected">'.get_string('ascending','data').'</option>';
1592
 
    } else {
1593
 
        echo '<option value="ASC">'.get_string('ascending','data').'</option>';
1594
 
    }
1595
 
    if ($order == 'DESC') {
1596
 
        echo '<option value="DESC" selected="selected">'.get_string('descending','data').'</option>';
1597
 
    } else {
1598
 
        echo '<option value="DESC">'.get_string('descending','data').'</option>';
1599
 
    }
1600
 
    echo '</select>';
1601
 
 
1602
 
    if ($advanced) {
1603
 
        $checked = ' checked="checked" ';
1604
 
    }
1605
 
    else {
1606
 
        $checked = '';
1607
 
    }
1608
 
    $PAGE->requires->js('/mod/data/data.js');
1609
 
    echo '&nbsp;<input type="hidden" name="advanced" value="0" />';
1610
 
    echo '&nbsp;<input type="hidden" name="filter" value="1" />';
1611
 
    echo '&nbsp;<input type="checkbox" id="advancedcheckbox" name="advanced" value="1" '.$checked.' onchange="showHideAdvSearch(this.checked);" /><label for="advancedcheckbox">'.get_string('advancedsearch', 'data').'</label>';
1612
 
    echo '&nbsp;<input type="submit" value="'.get_string('savesettings','data').'" />';
1613
 
 
1614
 
    echo '<br />';
1615
 
    echo '<div class="dataadvancedsearch" id="data_adv_form" style="display: ';
1616
 
 
1617
 
    if ($advanced) {
1618
 
        echo 'inline';
1619
 
    }
1620
 
    else {
1621
 
        echo 'none';
1622
 
    }
1623
 
    echo ';margin-left:auto;margin-right:auto;" >';
1624
 
    echo '<table class="boxaligncenter">';
1625
 
 
1626
 
    // print ASC or DESC
1627
 
    echo '<tr><td colspan="2">&nbsp;</td></tr>';
1628
 
    $i = 0;
1629
 
 
1630
 
    // Determine if we are printing all fields for advanced search, or the template for advanced search
1631
 
    // If a template is not defined, use the deafault template and display all fields.
1632
 
    if(empty($data->asearchtemplate)) {
1633
 
        data_generate_default_template($data, 'asearchtemplate');
1634
 
    }
1635
 
 
1636
 
    static $fields = NULL;
1637
 
    static $isteacher;
1638
 
    static $dataid = NULL;
1639
 
 
1640
 
    if (empty($dataid)) {
1641
 
        $dataid = $data->id;
1642
 
    } else if ($dataid != $data->id) {
1643
 
        $fields = NULL;
1644
 
    }
1645
 
 
1646
 
    if (empty($fields)) {
1647
 
        $fieldrecords = $DB->get_records('data_fields', array('dataid'=>$data->id));
1648
 
        foreach ($fieldrecords as $fieldrecord) {
1649
 
            $fields[]= data_get_field($fieldrecord, $data);
1650
 
        }
1651
 
 
1652
 
        $isteacher = has_capability('mod/data:managetemplates', $context);
1653
 
    }
1654
 
 
1655
 
    // Replacing tags
1656
 
    $patterns = array();
1657
 
    $replacement = array();
1658
 
 
1659
 
    // Then we generate strings to replace for normal tags
1660
 
    foreach ($fields as $field) {
1661
 
        $fieldname = $field->field->name;
1662
 
        $fieldname = preg_quote($fieldname, '/');
1663
 
        $patterns[] = "/\[\[$fieldname\]\]/i";
1664
 
        $searchfield = data_get_field_from_id($field->field->id, $data);
1665
 
        if (!empty($search_array[$field->field->id]->data)) {
1666
 
            $replacement[] = $searchfield->display_search_field($search_array[$field->field->id]->data);
1667
 
        } else {
1668
 
            $replacement[] = $searchfield->display_search_field();
1669
 
        }
1670
 
    }
1671
 
    $fn = !empty($search_array[DATA_FIRSTNAME]->data) ? $search_array[DATA_FIRSTNAME]->data : '';
1672
 
    $ln = !empty($search_array[DATA_LASTNAME]->data) ? $search_array[DATA_LASTNAME]->data : '';
1673
 
    $patterns[]    = '/##firstname##/';
1674
 
    $replacement[] = '<input type="text" size="16" name="u_fn" value="'.$fn.'" />';
1675
 
    $patterns[]    = '/##lastname##/';
1676
 
    $replacement[] = '<input type="text" size="16" name="u_ln" value="'.$ln.'" />';
1677
 
 
1678
 
    // actual replacement of the tags
1679
 
    $newtext = preg_replace($patterns, $replacement, $data->asearchtemplate);
1680
 
 
1681
 
    $options = new stdClass();
1682
 
    $options->para=false;
1683
 
    $options->noclean=true;
1684
 
    echo '<tr><td>';
1685
 
    echo format_text($newtext, FORMAT_HTML, $options);
1686
 
    echo '</td></tr>';
1687
 
 
1688
 
    echo '<tr><td colspan="4" style="text-align: center;"><br/><input type="submit" value="'.get_string('savesettings','data').'" /><input type="submit" name="resetadv" value="'.get_string('resetsettings','data').'" /></td></tr>';
1689
 
    echo '</table>';
1690
 
    echo '</div>';
1691
 
    echo '</div>';
1692
 
    echo '</form>';
1693
 
    echo '</div>';
1694
 
}
1695
 
 
1696
 
/**
1697
 
 * @global object
1698
 
 * @global object
1699
 
 * @param object $data
1700
 
 * @param object $record
1701
 
 * @return void Output echo'd
1702
 
 */
1703
 
function data_print_ratings($data, $record) {
1704
 
    global $OUTPUT;
1705
 
    if (!empty($record->rating)){
1706
 
        echo $OUTPUT->render($record->rating);
1707
 
    }
1708
 
}
1709
 
 
1710
 
/**
1711
 
 * For Participantion Reports
1712
 
 *
1713
 
 * @return array
1714
 
 */
1715
 
function data_get_view_actions() {
1716
 
    return array('view');
1717
 
}
1718
 
 
1719
 
/**
1720
 
 * @return array
1721
 
 */
1722
 
function data_get_post_actions() {
1723
 
    return array('add','update','record delete');
1724
 
}
1725
 
 
1726
 
/**
1727
 
 * @param string $name
1728
 
 * @param int $dataid
1729
 
 * @param int $fieldid
1730
 
 * @return bool
1731
 
 */
1732
 
function data_fieldname_exists($name, $dataid, $fieldid = 0) {
1733
 
    global $DB;
1734
 
 
1735
 
    if (!is_numeric($name)) {
1736
 
        $like = $DB->sql_like('df.name', ':name', false);
1737
 
    } else {
1738
 
        $like = "df.name = :name";
1739
 
    }
1740
 
    $params = array('name'=>$name);
1741
 
    if ($fieldid) {
1742
 
        $params['dataid']   = $dataid;
1743
 
        $params['fieldid1'] = $fieldid;
1744
 
        $params['fieldid2'] = $fieldid;
1745
 
        return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1746
 
                                        WHERE $like AND df.dataid = :dataid
1747
 
                                              AND ((df.id < :fieldid1) OR (df.id > :fieldid2))", $params);
1748
 
    } else {
1749
 
        $params['dataid']   = $dataid;
1750
 
        return $DB->record_exists_sql("SELECT * FROM {data_fields} df
1751
 
                                        WHERE $like AND df.dataid = :dataid", $params);
1752
 
    }
1753
 
}
1754
 
 
1755
 
/**
1756
 
 * @param array $fieldinput
1757
 
 */
1758
 
function data_convert_arrays_to_strings(&$fieldinput) {
1759
 
    foreach ($fieldinput as $key => $val) {
1760
 
        if (is_array($val)) {
1761
 
            $str = '';
1762
 
            foreach ($val as $inner) {
1763
 
                $str .= $inner . ',';
1764
 
            }
1765
 
            $str = substr($str, 0, -1);
1766
 
 
1767
 
            $fieldinput->$key = $str;
1768
 
        }
1769
 
    }
1770
 
}
1771
 
 
1772
 
 
1773
 
/**
1774
 
 * Converts a database (module instance) to use the Roles System
1775
 
 *
1776
 
 * @global object
1777
 
 * @global object
1778
 
 * @uses CONTEXT_MODULE
1779
 
 * @uses CAP_PREVENT
1780
 
 * @uses CAP_ALLOW
1781
 
 * @param object $data a data object with the same attributes as a record
1782
 
 *                     from the data database table
1783
 
 * @param int $datamodid the id of the data module, from the modules table
1784
 
 * @param array $teacherroles array of roles that have archetype teacher
1785
 
 * @param array $studentroles array of roles that have archetype student
1786
 
 * @param array $guestroles array of roles that have archetype guest
1787
 
 * @param int $cmid the course_module id for this data instance
1788
 
 * @return boolean data module was converted or not
1789
 
 */
1790
 
function data_convert_to_roles($data, $teacherroles=array(), $studentroles=array(), $cmid=NULL) {
1791
 
    global $CFG, $DB, $OUTPUT;
1792
 
 
1793
 
    if (!isset($data->participants) && !isset($data->assesspublic)
1794
 
            && !isset($data->groupmode)) {
1795
 
        // We assume that this database has already been converted to use the
1796
 
        // Roles System. above fields get dropped the data module has been
1797
 
        // upgraded to use Roles.
1798
 
        return false;
1799
 
    }
1800
 
 
1801
 
    if (empty($cmid)) {
1802
 
        // We were not given the course_module id. Try to find it.
1803
 
        if (!$cm = get_coursemodule_from_instance('data', $data->id)) {
1804
 
            echo $OUTPUT->notification('Could not get the course module for the data');
1805
 
            return false;
1806
 
        } else {
1807
 
            $cmid = $cm->id;
1808
 
        }
1809
 
    }
1810
 
    $context = get_context_instance(CONTEXT_MODULE, $cmid);
1811
 
 
1812
 
 
1813
 
    // $data->participants:
1814
 
    // 1 - Only teachers can add entries
1815
 
    // 3 - Teachers and students can add entries
1816
 
    switch ($data->participants) {
1817
 
        case 1:
1818
 
            foreach ($studentroles as $studentrole) {
1819
 
                assign_capability('mod/data:writeentry', CAP_PREVENT, $studentrole->id, $context->id);
1820
 
            }
1821
 
            foreach ($teacherroles as $teacherrole) {
1822
 
                assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1823
 
            }
1824
 
            break;
1825
 
        case 3:
1826
 
            foreach ($studentroles as $studentrole) {
1827
 
                assign_capability('mod/data:writeentry', CAP_ALLOW, $studentrole->id, $context->id);
1828
 
            }
1829
 
            foreach ($teacherroles as $teacherrole) {
1830
 
                assign_capability('mod/data:writeentry', CAP_ALLOW, $teacherrole->id, $context->id);
1831
 
            }
1832
 
            break;
1833
 
    }
1834
 
 
1835
 
    // $data->assessed:
1836
 
    // 2 - Only teachers can rate posts
1837
 
    // 1 - Everyone can rate posts
1838
 
    // 0 - No one can rate posts
1839
 
    switch ($data->assessed) {
1840
 
        case 0:
1841
 
            foreach ($studentroles as $studentrole) {
1842
 
                assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1843
 
            }
1844
 
            foreach ($teacherroles as $teacherrole) {
1845
 
                assign_capability('mod/data:rate', CAP_PREVENT, $teacherrole->id, $context->id);
1846
 
            }
1847
 
            break;
1848
 
        case 1:
1849
 
            foreach ($studentroles as $studentrole) {
1850
 
                assign_capability('mod/data:rate', CAP_ALLOW, $studentrole->id, $context->id);
1851
 
            }
1852
 
            foreach ($teacherroles as $teacherrole) {
1853
 
                assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1854
 
            }
1855
 
            break;
1856
 
        case 2:
1857
 
            foreach ($studentroles as $studentrole) {
1858
 
                assign_capability('mod/data:rate', CAP_PREVENT, $studentrole->id, $context->id);
1859
 
            }
1860
 
            foreach ($teacherroles as $teacherrole) {
1861
 
                assign_capability('mod/data:rate', CAP_ALLOW, $teacherrole->id, $context->id);
1862
 
            }
1863
 
            break;
1864
 
    }
1865
 
 
1866
 
    // $data->assesspublic:
1867
 
    // 0 - Students can only see their own ratings
1868
 
    // 1 - Students can see everyone's ratings
1869
 
    switch ($data->assesspublic) {
1870
 
        case 0:
1871
 
            foreach ($studentroles as $studentrole) {
1872
 
                assign_capability('mod/data:viewrating', CAP_PREVENT, $studentrole->id, $context->id);
1873
 
            }
1874
 
            foreach ($teacherroles as $teacherrole) {
1875
 
                assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1876
 
            }
1877
 
            break;
1878
 
        case 1:
1879
 
            foreach ($studentroles as $studentrole) {
1880
 
                assign_capability('mod/data:viewrating', CAP_ALLOW, $studentrole->id, $context->id);
1881
 
            }
1882
 
            foreach ($teacherroles as $teacherrole) {
1883
 
                assign_capability('mod/data:viewrating', CAP_ALLOW, $teacherrole->id, $context->id);
1884
 
            }
1885
 
            break;
1886
 
    }
1887
 
 
1888
 
    if (empty($cm)) {
1889
 
        $cm = $DB->get_record('course_modules', array('id'=>$cmid));
1890
 
    }
1891
 
 
1892
 
    switch ($cm->groupmode) {
1893
 
        case NOGROUPS:
1894
 
            break;
1895
 
        case SEPARATEGROUPS:
1896
 
            foreach ($studentroles as $studentrole) {
1897
 
                assign_capability('moodle/site:accessallgroups', CAP_PREVENT, $studentrole->id, $context->id);
1898
 
            }
1899
 
            foreach ($teacherroles as $teacherrole) {
1900
 
                assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1901
 
            }
1902
 
            break;
1903
 
        case VISIBLEGROUPS:
1904
 
            foreach ($studentroles as $studentrole) {
1905
 
                assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $studentrole->id, $context->id);
1906
 
            }
1907
 
            foreach ($teacherroles as $teacherrole) {
1908
 
                assign_capability('moodle/site:accessallgroups', CAP_ALLOW, $teacherrole->id, $context->id);
1909
 
            }
1910
 
            break;
1911
 
    }
1912
 
    return true;
1913
 
}
1914
 
 
1915
 
/**
1916
 
 * Returns the best name to show for a preset
1917
 
 *
1918
 
 * @param string $shortname
1919
 
 * @param  string $path
1920
 
 * @return string
1921
 
 */
1922
 
function data_preset_name($shortname, $path) {
1923
 
 
1924
 
    // We are looking inside the preset itself as a first choice, but also in normal data directory
1925
 
    $string = get_string('modulename', 'datapreset_'.$shortname);
1926
 
 
1927
 
    if (substr($string, 0, 1) == '[') {
1928
 
        return $shortname;
1929
 
    } else {
1930
 
        return $string;
1931
 
    }
1932
 
}
1933
 
 
1934
 
/**
1935
 
 * Returns an array of all the available presets.
1936
 
 *
1937
 
 * @return array
1938
 
 */
1939
 
function data_get_available_presets($context) {
1940
 
    global $CFG, $USER;
1941
 
 
1942
 
    $presets = array();
1943
 
 
1944
 
    // First load the ratings sub plugins that exist within the modules preset dir
1945
 
    if ($dirs = get_list_of_plugins('mod/data/preset')) {
1946
 
        foreach ($dirs as $dir) {
1947
 
            $fulldir = $CFG->dirroot.'/mod/data/preset/'.$dir;
1948
 
            if (is_directory_a_preset($fulldir)) {
1949
 
                $preset = new stdClass();
1950
 
                $preset->path = $fulldir;
1951
 
                $preset->userid = 0;
1952
 
                $preset->shortname = $dir;
1953
 
                $preset->name = data_preset_name($dir, $fulldir);
1954
 
                if (file_exists($fulldir.'/screenshot.jpg')) {
1955
 
                    $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.jpg';
1956
 
                } else if (file_exists($fulldir.'/screenshot.png')) {
1957
 
                    $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.png';
1958
 
                } else if (file_exists($fulldir.'/screenshot.gif')) {
1959
 
                    $preset->screenshot = $CFG->wwwroot.'/mod/data/preset/'.$dir.'/screenshot.gif';
1960
 
                }
1961
 
                $presets[] = $preset;
1962
 
            }
1963
 
        }
1964
 
    }
1965
 
    // Now add to that the site presets that people have saved
1966
 
    $presets = data_get_available_site_presets($context, $presets);
1967
 
    return $presets;
1968
 
}
1969
 
 
1970
 
/**
1971
 
 * Gets an array of all of the presets that users have saved to the site.
1972
 
 *
1973
 
 * @param stdClass $context The context that we are looking from.
1974
 
 * @param array $presets
1975
 
 * @return array An array of presets
1976
 
 */
1977
 
function data_get_available_site_presets($context, array $presets=array()) {
1978
 
    global $USER;
1979
 
 
1980
 
    $fs = get_file_storage();
1981
 
    $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
1982
 
    $canviewall = has_capability('mod/data:viewalluserpresets', $context);
1983
 
    if (empty($files)) {
1984
 
        return $presets;
1985
 
    }
1986
 
    foreach ($files as $file) {
1987
 
        if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory() || (!$canviewall && $file->get_userid() != $USER->id)) {
1988
 
            continue;
1989
 
        }
1990
 
        $preset = new stdClass;
1991
 
        $preset->path = $file->get_filepath();
1992
 
        $preset->name = trim($preset->path, '/');
1993
 
        $preset->shortname = $preset->name;
1994
 
        $preset->userid = $file->get_userid();
1995
 
        $preset->id = $file->get_id();
1996
 
        $preset->storedfile = $file;
1997
 
        $presets[] = $preset;
1998
 
    }
1999
 
    return $presets;
2000
 
}
2001
 
 
2002
 
/**
2003
 
 * Deletes a saved preset.
2004
 
 *
2005
 
 * @param string $name
2006
 
 * @return bool
2007
 
 */
2008
 
function data_delete_site_preset($name) {
2009
 
    $fs = get_file_storage();
2010
 
 
2011
 
    $files = $fs->get_directory_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/');
2012
 
    if (!empty($files)) {
2013
 
        foreach ($files as $file) {
2014
 
            $file->delete();
2015
 
        }
2016
 
    }
2017
 
 
2018
 
    $dir = $fs->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, '/'.$name.'/', '.');
2019
 
    if (!empty($dir)) {
2020
 
        $dir->delete();
2021
 
    }
2022
 
    return true;
2023
 
}
2024
 
 
2025
 
/**
2026
 
 * Prints the heads for a page
2027
 
 *
2028
 
 * @param stdClass $course
2029
 
 * @param stdClass $cm
2030
 
 * @param stdClass $data
2031
 
 * @param string $currenttab
2032
 
 */
2033
 
function data_print_header($course, $cm, $data, $currenttab='') {
2034
 
 
2035
 
    global $CFG, $displaynoticegood, $displaynoticebad, $OUTPUT, $PAGE;
2036
 
 
2037
 
    $PAGE->set_title($data->name);
2038
 
    echo $OUTPUT->header();
2039
 
    echo $OUTPUT->heading(format_string($data->name));
2040
 
 
2041
 
// Groups needed for Add entry tab
2042
 
    $currentgroup = groups_get_activity_group($cm);
2043
 
    $groupmode = groups_get_activity_groupmode($cm);
2044
 
 
2045
 
    // Print the tabs
2046
 
 
2047
 
    if ($currenttab) {
2048
 
        include('tabs.php');
2049
 
    }
2050
 
 
2051
 
    // Print any notices
2052
 
 
2053
 
    if (!empty($displaynoticegood)) {
2054
 
        echo $OUTPUT->notification($displaynoticegood, 'notifysuccess');    // good (usually green)
2055
 
    } else if (!empty($displaynoticebad)) {
2056
 
        echo $OUTPUT->notification($displaynoticebad);                     // bad (usuually red)
2057
 
    }
2058
 
}
2059
 
 
2060
 
/**
2061
 
 * Can user add more entries?
2062
 
 *
2063
 
 * @param object $data
2064
 
 * @param mixed $currentgroup
2065
 
 * @param int $groupmode
2066
 
 * @param stdClass $context
2067
 
 * @return bool
2068
 
 */
2069
 
function data_user_can_add_entry($data, $currentgroup, $groupmode, $context = null) {
2070
 
    global $USER;
2071
 
 
2072
 
    if (empty($context)) {
2073
 
        $cm = get_coursemodule_from_instance('data', $data->id, 0, false, MUST_EXIST);
2074
 
        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2075
 
    }
2076
 
 
2077
 
    if (has_capability('mod/data:manageentries', $context)) {
2078
 
        // no entry limits apply if user can manage
2079
 
 
2080
 
    } else if (!has_capability('mod/data:writeentry', $context)) {
2081
 
        return false;
2082
 
 
2083
 
    } else if (data_atmaxentries($data)) {
2084
 
        return false;
2085
 
    } else if (data_in_readonly_period($data)) {
2086
 
        // Check whether we're in a read-only period
2087
 
        return false;
2088
 
    }
2089
 
 
2090
 
    if (!$groupmode or has_capability('moodle/site:accessallgroups', $context)) {
2091
 
        return true;
2092
 
    }
2093
 
 
2094
 
    if ($currentgroup) {
2095
 
        return groups_is_member($currentgroup);
2096
 
    } else {
2097
 
        //else it might be group 0 in visible mode
2098
 
        if ($groupmode == VISIBLEGROUPS){
2099
 
            return true;
2100
 
        } else {
2101
 
            return false;
2102
 
        }
2103
 
    }
2104
 
}
2105
 
 
2106
 
/**
2107
 
 * Check whether the specified database activity is currently in a read-only period
2108
 
 *
2109
 
 * @param object $data
2110
 
 * @return bool returns true if the time fields in $data indicate a read-only period; false otherwise
2111
 
 */
2112
 
function data_in_readonly_period($data) {
2113
 
    $now = time();
2114
 
    if (!$data->timeviewfrom && !$data->timeviewto) {
2115
 
        return false;
2116
 
    } else if (($data->timeviewfrom && $now < $data->timeviewfrom) || ($data->timeviewto && $now > $data->timeviewto)) {
2117
 
        return false;
2118
 
    }
2119
 
    return true;
2120
 
}
2121
 
 
2122
 
/**
2123
 
 * @return bool
2124
 
 */
2125
 
function is_directory_a_preset($directory) {
2126
 
    $directory = rtrim($directory, '/\\') . '/';
2127
 
    $status = file_exists($directory.'singletemplate.html') &&
2128
 
              file_exists($directory.'listtemplate.html') &&
2129
 
              file_exists($directory.'listtemplateheader.html') &&
2130
 
              file_exists($directory.'listtemplatefooter.html') &&
2131
 
              file_exists($directory.'addtemplate.html') &&
2132
 
              file_exists($directory.'rsstemplate.html') &&
2133
 
              file_exists($directory.'rsstitletemplate.html') &&
2134
 
              file_exists($directory.'csstemplate.css') &&
2135
 
              file_exists($directory.'jstemplate.js') &&
2136
 
              file_exists($directory.'preset.xml');
2137
 
 
2138
 
    return $status;
2139
 
}
2140
 
 
2141
 
/**
2142
 
 * Abstract class used for data preset importers
2143
 
 */
2144
 
abstract class data_preset_importer {
2145
 
 
2146
 
    protected $course;
2147
 
    protected $cm;
2148
 
    protected $module;
2149
 
    protected $directory;
2150
 
 
2151
 
    /**
2152
 
     * Constructor
2153
 
     *
2154
 
     * @param stdClass $course
2155
 
     * @param stdClass $cm
2156
 
     * @param stdClass $module
2157
 
     * @param string $directory
2158
 
     */
2159
 
    public function __construct($course, $cm, $module, $directory) {
2160
 
        $this->course = $course;
2161
 
        $this->cm = $cm;
2162
 
        $this->module = $module;
2163
 
        $this->directory = $directory;
2164
 
    }
2165
 
 
2166
 
    /**
2167
 
     * Returns the name of the directory the preset is located in
2168
 
     * @return string
2169
 
     */
2170
 
    public function get_directory() {
2171
 
        return basename($this->directory);
2172
 
    }
2173
 
 
2174
 
    /**
2175
 
     * Retreive the contents of a file. That file may either be in a conventional directory of the Moodle file storage
2176
 
     * @param file_storage $filestorage. should be null if using a conventional directory
2177
 
     * @param stored_file $fileobj the directory to look in. null if using a conventional directory
2178
 
     * @param string $dir the directory to look in. null if using the Moodle file storage
2179
 
     * @param string $filename the name of the file we want
2180
 
     * @return string the contents of the file
2181
 
     */
2182
 
    public function data_preset_get_file_contents(&$filestorage, &$fileobj, $dir, $filename) {
2183
 
        if(empty($filestorage) || empty($fileobj)) {
2184
 
            if (substr($dir, -1)!='/') {
2185
 
                $dir .= '/';
2186
 
            }
2187
 
            return file_get_contents($dir.$filename);
2188
 
        } else {
2189
 
            $file = $filestorage->get_file(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA, 0, $fileobj->get_filepath(), $filename);
2190
 
            return $file->get_content();
2191
 
        }
2192
 
 
2193
 
    }
2194
 
    /**
2195
 
     * Gets the preset settings
2196
 
     * @global moodle_database $DB
2197
 
     * @return stdClass
2198
 
     */
2199
 
    public function get_preset_settings() {
2200
 
        global $DB;
2201
 
 
2202
 
        $fs = $fileobj = null;
2203
 
        if (!is_directory_a_preset($this->directory)) {
2204
 
            //maybe the user requested a preset stored in the Moodle file storage
2205
 
 
2206
 
            $fs = get_file_storage();
2207
 
            $files = $fs->get_area_files(DATA_PRESET_CONTEXT, DATA_PRESET_COMPONENT, DATA_PRESET_FILEAREA);
2208
 
 
2209
 
            //preset name to find will be the final element of the directory
2210
 
            $presettofind = end(explode('/',$this->directory));
2211
 
 
2212
 
            //now go through the available files available and see if we can find it
2213
 
            foreach ($files as $file) {
2214
 
                if (($file->is_directory() && $file->get_filepath()=='/') || !$file->is_directory()) {
2215
 
                    continue;
2216
 
                }
2217
 
                $presetname = trim($file->get_filepath(), '/');
2218
 
                if ($presetname==$presettofind) {
2219
 
                    $this->directory = $presetname;
2220
 
                    $fileobj = $file;
2221
 
                }
2222
 
            }
2223
 
 
2224
 
            if (empty($fileobj)) {
2225
 
                print_error('invalidpreset', 'data', '', $this->directory);
2226
 
            }
2227
 
        }
2228
 
 
2229
 
        $allowed_settings = array(
2230
 
            'intro',
2231
 
            'comments',
2232
 
            'requiredentries',
2233
 
            'requiredentriestoview',
2234
 
            'maxentries',
2235
 
            'rssarticles',
2236
 
            'approval',
2237
 
            'defaultsortdir',
2238
 
            'defaultsort');
2239
 
 
2240
 
        $result = new stdClass;
2241
 
        $result->settings = new stdClass;
2242
 
        $result->importfields = array();
2243
 
        $result->currentfields = $DB->get_records('data_fields', array('dataid'=>$this->module->id));
2244
 
        if (!$result->currentfields) {
2245
 
            $result->currentfields = array();
2246
 
        }
2247
 
 
2248
 
 
2249
 
        /* Grab XML */
2250
 
        $presetxml = $this->data_preset_get_file_contents($fs, $fileobj, $this->directory,'preset.xml');
2251
 
        $parsedxml = xmlize($presetxml, 0);
2252
 
 
2253
 
        /* First, do settings. Put in user friendly array. */
2254
 
        $settingsarray = $parsedxml['preset']['#']['settings'][0]['#'];
2255
 
        $result->settings = new StdClass();
2256
 
        foreach ($settingsarray as $setting => $value) {
2257
 
            if (!is_array($value) || !in_array($setting, $allowed_settings)) {
2258
 
                // unsupported setting
2259
 
                continue;
2260
 
            }
2261
 
            $result->settings->$setting = $value[0]['#'];
2262
 
        }
2263
 
 
2264
 
        /* Now work out fields to user friendly array */
2265
 
        $fieldsarray = $parsedxml['preset']['#']['field'];
2266
 
        foreach ($fieldsarray as $field) {
2267
 
            if (!is_array($field)) {
2268
 
                continue;
2269
 
            }
2270
 
            $f = new StdClass();
2271
 
            foreach ($field['#'] as $param => $value) {
2272
 
                if (!is_array($value)) {
2273
 
                    continue;
2274
 
                }
2275
 
                $f->$param = $value[0]['#'];
2276
 
            }
2277
 
            $f->dataid = $this->module->id;
2278
 
            $f->type = clean_param($f->type, PARAM_ALPHA);
2279
 
            $result->importfields[] = $f;
2280
 
        }
2281
 
        /* Now add the HTML templates to the settings array so we can update d */
2282
 
        $result->settings->singletemplate     = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"singletemplate.html");
2283
 
        $result->settings->listtemplate       = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplate.html");
2284
 
        $result->settings->listtemplateheader = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplateheader.html");
2285
 
        $result->settings->listtemplatefooter = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"listtemplatefooter.html");
2286
 
        $result->settings->addtemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"addtemplate.html");
2287
 
        $result->settings->rsstemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstemplate.html");
2288
 
        $result->settings->rsstitletemplate   = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"rsstitletemplate.html");
2289
 
        $result->settings->csstemplate        = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"csstemplate.css");
2290
 
        $result->settings->jstemplate         = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"jstemplate.js");
2291
 
 
2292
 
        //optional
2293
 
        if (file_exists($this->directory."/asearchtemplate.html")) {
2294
 
            $result->settings->asearchtemplate = $this->data_preset_get_file_contents($fs, $fileobj,$this->directory,"asearchtemplate.html");
2295
 
        } else {
2296
 
            $result->settings->asearchtemplate = NULL;
2297
 
        }
2298
 
        $result->settings->instance = $this->module->id;
2299
 
 
2300
 
        return $result;
2301
 
    }
2302
 
 
2303
 
    /**
2304
 
     * Import the preset into the given database module
2305
 
     * @return bool
2306
 
     */
2307
 
    function import($overwritesettings) {
2308
 
        global $DB, $CFG;
2309
 
 
2310
 
        $params = $this->get_preset_settings();
2311
 
        $settings = $params->settings;
2312
 
        $newfields = $params->importfields;
2313
 
        $currentfields = $params->currentfields;
2314
 
        $preservedfields = array();
2315
 
 
2316
 
        /* Maps fields and makes new ones */
2317
 
        if (!empty($newfields)) {
2318
 
            /* We require an injective mapping, and need to know what to protect */
2319
 
            foreach ($newfields as $nid => $newfield) {
2320
 
                $cid = optional_param("field_$nid", -1, PARAM_INT);
2321
 
                if ($cid == -1) {
2322
 
                    continue;
2323
 
                }
2324
 
                if (array_key_exists($cid, $preservedfields)){
2325
 
                    print_error('notinjectivemap', 'data');
2326
 
                }
2327
 
                else $preservedfields[$cid] = true;
2328
 
            }
2329
 
 
2330
 
            foreach ($newfields as $nid => $newfield) {
2331
 
                $cid = optional_param("field_$nid", -1, PARAM_INT);
2332
 
 
2333
 
                /* A mapping. Just need to change field params. Data kept. */
2334
 
                if ($cid != -1 and isset($currentfields[$cid])) {
2335
 
                    $fieldobject = data_get_field_from_id($currentfields[$cid]->id, $this->module);
2336
 
                    foreach ($newfield as $param => $value) {
2337
 
                        if ($param != "id") {
2338
 
                            $fieldobject->field->$param = $value;
2339
 
                        }
2340
 
                    }
2341
 
                    unset($fieldobject->field->similarfield);
2342
 
                    $fieldobject->update_field();
2343
 
                    unset($fieldobject);
2344
 
                } else {
2345
 
                    /* Make a new field */
2346
 
                    include_once("field/$newfield->type/field.class.php");
2347
 
 
2348
 
                    if (!isset($newfield->description)) {
2349
 
                        $newfield->description = '';
2350
 
                    }
2351
 
                    $classname = 'data_field_'.$newfield->type;
2352
 
                    $fieldclass = new $classname($newfield, $this->module);
2353
 
                    $fieldclass->insert_field();
2354
 
                    unset($fieldclass);
2355
 
                }
2356
 
            }
2357
 
        }
2358
 
 
2359
 
        /* Get rid of all old unused data */
2360
 
        if (!empty($preservedfields)) {
2361
 
            foreach ($currentfields as $cid => $currentfield) {
2362
 
                if (!array_key_exists($cid, $preservedfields)) {
2363
 
                    /* Data not used anymore so wipe! */
2364
 
                    print "Deleting field $currentfield->name<br />";
2365
 
 
2366
 
                    $id = $currentfield->id;
2367
 
                    //Why delete existing data records and related comments/ratings??
2368
 
                    $DB->delete_records('data_content', array('fieldid'=>$id));
2369
 
                    $DB->delete_records('data_fields', array('id'=>$id));
2370
 
                }
2371
 
            }
2372
 
        }
2373
 
 
2374
 
        // handle special settings here
2375
 
        if (!empty($settings->defaultsort)) {
2376
 
            if (is_numeric($settings->defaultsort)) {
2377
 
                // old broken value
2378
 
                $settings->defaultsort = 0;
2379
 
            } else {
2380
 
                $settings->defaultsort = (int)$DB->get_field('data_fields', 'id', array('dataid'=>$this->module->id, 'name'=>$settings->defaultsort));
2381
 
            }
2382
 
        } else {
2383
 
            $settings->defaultsort = 0;
2384
 
        }
2385
 
 
2386
 
        // do we want to overwrite all current database settings?
2387
 
        if ($overwritesettings) {
2388
 
            // all supported settings
2389
 
            $overwrite = array_keys((array)$settings);
2390
 
        } else {
2391
 
            // only templates and sorting
2392
 
            $overwrite = array('singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter',
2393
 
                               'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate',
2394
 
                               'asearchtemplate', 'defaultsortdir', 'defaultsort');
2395
 
        }
2396
 
 
2397
 
        // now overwrite current data settings
2398
 
        foreach ($this->module as $prop=>$unused) {
2399
 
            if (in_array($prop, $overwrite)) {
2400
 
                $this->module->$prop = $settings->$prop;
2401
 
            }
2402
 
        }
2403
 
 
2404
 
        data_update_instance($this->module);
2405
 
 
2406
 
        return $this->cleanup();
2407
 
    }
2408
 
 
2409
 
    /**
2410
 
     * Any clean up routines should go here
2411
 
     * @return bool
2412
 
     */
2413
 
    public function cleanup() {
2414
 
        return true;
2415
 
    }
2416
 
}
2417
 
 
2418
 
/**
2419
 
 * Data preset importer for uploaded presets
2420
 
 */
2421
 
class data_preset_upload_importer extends data_preset_importer {
2422
 
    public function __construct($course, $cm, $module, $filepath) {
2423
 
        global $USER;
2424
 
        if (is_file($filepath)) {
2425
 
            $fp = get_file_packer();
2426
 
            if ($fp->extract_to_pathname($filepath, $filepath.'_extracted')) {
2427
 
                fulldelete($filepath);
2428
 
            }
2429
 
            $filepath .= '_extracted';
2430
 
        }
2431
 
        parent::__construct($course, $cm, $module, $filepath);
2432
 
    }
2433
 
    public function cleanup() {
2434
 
        return fulldelete($this->directory);
2435
 
    }
2436
 
}
2437
 
 
2438
 
/**
2439
 
 * Data preset importer for existing presets
2440
 
 */
2441
 
class data_preset_existing_importer extends data_preset_importer {
2442
 
    protected $userid;
2443
 
    public function __construct($course, $cm, $module, $fullname) {
2444
 
        global $USER;
2445
 
        list($userid, $shortname) = explode('/', $fullname, 2);
2446
 
        $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2447
 
        if ($userid && ($userid != $USER->id) && !has_capability('mod/data:manageuserpresets', $context) && !has_capability('mod/data:viewalluserpresets', $context)) {
2448
 
           throw new coding_exception('Invalid preset provided');
2449
 
        }
2450
 
 
2451
 
        $this->userid = $userid;
2452
 
        $filepath = data_preset_path($course, $userid, $shortname);
2453
 
        parent::__construct($course, $cm, $module, $filepath);
2454
 
    }
2455
 
    public function get_userid() {
2456
 
        return $this->userid;
2457
 
    }
2458
 
}
2459
 
 
2460
 
/**
2461
 
 * @global object
2462
 
 * @global object
2463
 
 * @param object $course
2464
 
 * @param int $userid
2465
 
 * @param string $shortname
2466
 
 * @return string
2467
 
 */
2468
 
function data_preset_path($course, $userid, $shortname) {
2469
 
    global $USER, $CFG;
2470
 
 
2471
 
    $context = get_context_instance(CONTEXT_COURSE, $course->id);
2472
 
 
2473
 
    $userid = (int)$userid;
2474
 
 
2475
 
    $path = null;
2476
 
    if ($userid > 0 && ($userid == $USER->id || has_capability('mod/data:viewalluserpresets', $context))) {
2477
 
        $path = $CFG->dataroot.'/data/preset/'.$userid.'/'.$shortname;
2478
 
    } else if ($userid == 0) {
2479
 
        $path = $CFG->dirroot.'/mod/data/preset/'.$shortname;
2480
 
    } else if ($userid < 0) {
2481
 
        $path = $CFG->tempdir.'/data/'.-$userid.'/'.$shortname;
2482
 
    }
2483
 
 
2484
 
    return $path;
2485
 
}
2486
 
 
2487
 
/**
2488
 
 * Implementation of the function for printing the form elements that control
2489
 
 * whether the course reset functionality affects the data.
2490
 
 *
2491
 
 * @param $mform form passed by reference
2492
 
 */
2493
 
function data_reset_course_form_definition(&$mform) {
2494
 
    $mform->addElement('header', 'dataheader', get_string('modulenameplural', 'data'));
2495
 
    $mform->addElement('checkbox', 'reset_data', get_string('deleteallentries','data'));
2496
 
 
2497
 
    $mform->addElement('checkbox', 'reset_data_notenrolled', get_string('deletenotenrolled', 'data'));
2498
 
    $mform->disabledIf('reset_data_notenrolled', 'reset_data', 'checked');
2499
 
 
2500
 
    $mform->addElement('checkbox', 'reset_data_ratings', get_string('deleteallratings'));
2501
 
    $mform->disabledIf('reset_data_ratings', 'reset_data', 'checked');
2502
 
 
2503
 
    $mform->addElement('checkbox', 'reset_data_comments', get_string('deleteallcomments'));
2504
 
    $mform->disabledIf('reset_data_comments', 'reset_data', 'checked');
2505
 
}
2506
 
 
2507
 
/**
2508
 
 * Course reset form defaults.
2509
 
 * @return array
2510
 
 */
2511
 
function data_reset_course_form_defaults($course) {
2512
 
    return array('reset_data'=>0, 'reset_data_ratings'=>1, 'reset_data_comments'=>1, 'reset_data_notenrolled'=>0);
2513
 
}
2514
 
 
2515
 
/**
2516
 
 * Removes all grades from gradebook
2517
 
 *
2518
 
 * @global object
2519
 
 * @global object
2520
 
 * @param int $courseid
2521
 
 * @param string $type optional type
2522
 
 */
2523
 
function data_reset_gradebook($courseid, $type='') {
2524
 
    global $CFG, $DB;
2525
 
 
2526
 
    $sql = "SELECT d.*, cm.idnumber as cmidnumber, d.course as courseid
2527
 
              FROM {data} d, {course_modules} cm, {modules} m
2528
 
             WHERE m.name='data' AND m.id=cm.module AND cm.instance=d.id AND d.course=?";
2529
 
 
2530
 
    if ($datas = $DB->get_records_sql($sql, array($courseid))) {
2531
 
        foreach ($datas as $data) {
2532
 
            data_grade_item_update($data, 'reset');
2533
 
        }
2534
 
    }
2535
 
}
2536
 
 
2537
 
/**
2538
 
 * Actual implementation of the reset course functionality, delete all the
2539
 
 * data responses for course $data->courseid.
2540
 
 *
2541
 
 * @global object
2542
 
 * @global object
2543
 
 * @param object $data the data submitted from the reset course.
2544
 
 * @return array status array
2545
 
 */
2546
 
function data_reset_userdata($data) {
2547
 
    global $CFG, $DB;
2548
 
    require_once($CFG->libdir.'/filelib.php');
2549
 
    require_once($CFG->dirroot.'/rating/lib.php');
2550
 
 
2551
 
    $componentstr = get_string('modulenameplural', 'data');
2552
 
    $status = array();
2553
 
 
2554
 
    $allrecordssql = "SELECT r.id
2555
 
                        FROM {data_records} r
2556
 
                             INNER JOIN {data} d ON r.dataid = d.id
2557
 
                       WHERE d.course = ?";
2558
 
 
2559
 
    $alldatassql = "SELECT d.id
2560
 
                      FROM {data} d
2561
 
                     WHERE d.course=?";
2562
 
 
2563
 
    $rm = new rating_manager();
2564
 
    $ratingdeloptions = new stdClass;
2565
 
    $ratingdeloptions->component = 'mod_data';
2566
 
    $ratingdeloptions->ratingarea = 'entry';
2567
 
 
2568
 
    // delete entries if requested
2569
 
    if (!empty($data->reset_data)) {
2570
 
        $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2571
 
        $DB->delete_records_select('data_content', "recordid IN ($allrecordssql)", array($data->courseid));
2572
 
        $DB->delete_records_select('data_records', "dataid IN ($alldatassql)", array($data->courseid));
2573
 
 
2574
 
        if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2575
 
            foreach ($datas as $dataid=>$unused) {
2576
 
                fulldelete("$CFG->dataroot/$data->courseid/moddata/data/$dataid");
2577
 
 
2578
 
                if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2579
 
                    continue;
2580
 
                }
2581
 
                $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2582
 
 
2583
 
                $ratingdeloptions->contextid = $datacontext->id;
2584
 
                $rm->delete_ratings($ratingdeloptions);
2585
 
            }
2586
 
        }
2587
 
 
2588
 
        if (empty($data->reset_gradebook_grades)) {
2589
 
            // remove all grades from gradebook
2590
 
            data_reset_gradebook($data->courseid);
2591
 
        }
2592
 
        $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallentries', 'data'), 'error'=>false);
2593
 
    }
2594
 
 
2595
 
    // remove entries by users not enrolled into course
2596
 
    if (!empty($data->reset_data_notenrolled)) {
2597
 
        $recordssql = "SELECT r.id, r.userid, r.dataid, u.id AS userexists, u.deleted AS userdeleted
2598
 
                         FROM {data_records} r
2599
 
                              JOIN {data} d ON r.dataid = d.id
2600
 
                              LEFT JOIN {user} u ON r.userid = u.id
2601
 
                        WHERE d.course = ? AND r.userid > 0";
2602
 
 
2603
 
        $course_context = get_context_instance(CONTEXT_COURSE, $data->courseid);
2604
 
        $notenrolled = array();
2605
 
        $fields = array();
2606
 
        $rs = $DB->get_recordset_sql($recordssql, array($data->courseid));
2607
 
        foreach ($rs as $record) {
2608
 
            if (array_key_exists($record->userid, $notenrolled) or !$record->userexists or $record->userdeleted
2609
 
              or !is_enrolled($course_context, $record->userid)) {
2610
 
                //delete ratings
2611
 
                if (!$cm = get_coursemodule_from_instance('data', $record->dataid)) {
2612
 
                    continue;
2613
 
                }
2614
 
                $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2615
 
                $ratingdeloptions->contextid = $datacontext->id;
2616
 
                $ratingdeloptions->itemid = $record->id;
2617
 
                $rm->delete_ratings($ratingdeloptions);
2618
 
 
2619
 
                $DB->delete_records('comments', array('itemid'=>$record->id, 'commentarea'=>'database_entry'));
2620
 
                $DB->delete_records('data_content', array('recordid'=>$record->id));
2621
 
                $DB->delete_records('data_records', array('id'=>$record->id));
2622
 
                // HACK: this is ugly - the recordid should be before the fieldid!
2623
 
                if (!array_key_exists($record->dataid, $fields)) {
2624
 
                    if ($fs = $DB->get_records('data_fields', array('dataid'=>$record->dataid))) {
2625
 
                        $fields[$record->dataid] = array_keys($fs);
2626
 
                    } else {
2627
 
                        $fields[$record->dataid] = array();
2628
 
                    }
2629
 
                }
2630
 
                foreach($fields[$record->dataid] as $fieldid) {
2631
 
                    fulldelete("$CFG->dataroot/$data->courseid/moddata/data/$record->dataid/$fieldid/$record->id");
2632
 
                }
2633
 
                $notenrolled[$record->userid] = true;
2634
 
            }
2635
 
        }
2636
 
        $rs->close();
2637
 
        $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotenrolled', 'data'), 'error'=>false);
2638
 
    }
2639
 
 
2640
 
    // remove all ratings
2641
 
    if (!empty($data->reset_data_ratings)) {
2642
 
        if ($datas = $DB->get_records_sql($alldatassql, array($data->courseid))) {
2643
 
            foreach ($datas as $dataid=>$unused) {
2644
 
                if (!$cm = get_coursemodule_from_instance('data', $dataid)) {
2645
 
                    continue;
2646
 
                }
2647
 
                $datacontext = get_context_instance(CONTEXT_MODULE, $cm->id);
2648
 
 
2649
 
                $ratingdeloptions->contextid = $datacontext->id;
2650
 
                $rm->delete_ratings($ratingdeloptions);
2651
 
            }
2652
 
        }
2653
 
 
2654
 
        if (empty($data->reset_gradebook_grades)) {
2655
 
            // remove all grades from gradebook
2656
 
            data_reset_gradebook($data->courseid);
2657
 
        }
2658
 
 
2659
 
        $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallratings'), 'error'=>false);
2660
 
    }
2661
 
 
2662
 
    // remove all comments
2663
 
    if (!empty($data->reset_data_comments)) {
2664
 
        $DB->delete_records_select('comments', "itemid IN ($allrecordssql) AND commentarea='database_entry'", array($data->courseid));
2665
 
        $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallcomments'), 'error'=>false);
2666
 
    }
2667
 
 
2668
 
    // updating dates - shift may be negative too
2669
 
    if ($data->timeshift) {
2670
 
        shift_course_mod_dates('data', array('timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto'), $data->timeshift, $data->courseid);
2671
 
        $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
2672
 
    }
2673
 
 
2674
 
    return $status;
2675
 
}
2676
 
 
2677
 
/**
2678
 
 * Returns all other caps used in module
2679
 
 *
2680
 
 * @return array
2681
 
 */
2682
 
function data_get_extra_capabilities() {
2683
 
    return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames', 'moodle/rating:view', 'moodle/rating:viewany', 'moodle/rating:viewall', 'moodle/rating:rate', 'moodle/comment:view', 'moodle/comment:post', 'moodle/comment:delete');
2684
 
}
2685
 
 
2686
 
/**
2687
 
 * @param string $feature FEATURE_xx constant for requested feature
2688
 
 * @return mixed True if module supports feature, null if doesn't know
2689
 
 */
2690
 
function data_supports($feature) {
2691
 
    switch($feature) {
2692
 
        case FEATURE_GROUPS:                  return true;
2693
 
        case FEATURE_GROUPINGS:               return true;
2694
 
        case FEATURE_GROUPMEMBERSONLY:        return true;
2695
 
        case FEATURE_MOD_INTRO:               return true;
2696
 
        case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
2697
 
        case FEATURE_GRADE_HAS_GRADE:         return true;
2698
 
        case FEATURE_GRADE_OUTCOMES:          return true;
2699
 
        case FEATURE_RATE:                    return true;
2700
 
        case FEATURE_BACKUP_MOODLE2:          return true;
2701
 
        case FEATURE_SHOW_DESCRIPTION:        return true;
2702
 
 
2703
 
        default: return null;
2704
 
    }
2705
 
}
2706
 
/**
2707
 
 * @global object
2708
 
 * @param array $export
2709
 
 * @param string $delimiter_name
2710
 
 * @param object $database
2711
 
 * @param int $count
2712
 
 * @param bool $return
2713
 
 * @return string|void
2714
 
 */
2715
 
function data_export_csv($export, $delimiter_name, $dataname, $count, $return=false) {
2716
 
    global $CFG;
2717
 
    require_once($CFG->libdir . '/csvlib.class.php');
2718
 
    $delimiter = csv_import_reader::get_delimiter($delimiter_name);
2719
 
    $filename = clean_filename("{$dataname}-{$count}_record");
2720
 
    if ($count > 1) {
2721
 
        $filename .= 's';
2722
 
    }
2723
 
    $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2724
 
    $filename .= clean_filename("-{$delimiter_name}_separated");
2725
 
    $filename .= '.csv';
2726
 
    if (empty($return)) {
2727
 
        header("Content-Type: application/download\n");
2728
 
        header("Content-Disposition: attachment; filename=$filename");
2729
 
        header('Expires: 0');
2730
 
        header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
2731
 
        header('Pragma: public');
2732
 
    }
2733
 
    $encdelim = '&#' . ord($delimiter) . ';';
2734
 
    $returnstr = '';
2735
 
    foreach($export as $row) {
2736
 
        foreach($row as $key => $column) {
2737
 
            $row[$key] = str_replace($delimiter, $encdelim, $column);
2738
 
        }
2739
 
        $returnstr .= implode($delimiter, $row) . "\n";
2740
 
    }
2741
 
    if (empty($return)) {
2742
 
        echo $returnstr;
2743
 
        return;
2744
 
    }
2745
 
    return $returnstr;
2746
 
}
2747
 
 
2748
 
/**
2749
 
 * @global object
2750
 
 * @param array $export
2751
 
 * @param string $dataname
2752
 
 * @param int $count
2753
 
 * @return string
2754
 
 */
2755
 
function data_export_xls($export, $dataname, $count) {
2756
 
    global $CFG;
2757
 
    require_once("$CFG->libdir/excellib.class.php");
2758
 
    $filename = clean_filename("{$dataname}-{$count}_record");
2759
 
    if ($count > 1) {
2760
 
        $filename .= 's';
2761
 
    }
2762
 
    $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2763
 
    $filename .= '.xls';
2764
 
 
2765
 
    $filearg = '-';
2766
 
    $workbook = new MoodleExcelWorkbook($filearg);
2767
 
    $workbook->send($filename);
2768
 
    $worksheet = array();
2769
 
    $worksheet[0] =& $workbook->add_worksheet('');
2770
 
    $rowno = 0;
2771
 
    foreach ($export as $row) {
2772
 
        $colno = 0;
2773
 
        foreach($row as $col) {
2774
 
            $worksheet[0]->write($rowno, $colno, $col);
2775
 
            $colno++;
2776
 
        }
2777
 
        $rowno++;
2778
 
    }
2779
 
    $workbook->close();
2780
 
    return $filename;
2781
 
}
2782
 
 
2783
 
/**
2784
 
 * @global object
2785
 
 * @param array $export
2786
 
 * @param string $dataname
2787
 
 * @param int $count
2788
 
 * @param string
2789
 
 */
2790
 
function data_export_ods($export, $dataname, $count) {
2791
 
    global $CFG;
2792
 
    require_once("$CFG->libdir/odslib.class.php");
2793
 
    $filename = clean_filename("{$dataname}-{$count}_record");
2794
 
    if ($count > 1) {
2795
 
        $filename .= 's';
2796
 
    }
2797
 
    $filename .= clean_filename('-' . gmdate("Ymd_Hi"));
2798
 
    $filename .= '.ods';
2799
 
    $filearg = '-';
2800
 
    $workbook = new MoodleODSWorkbook($filearg);
2801
 
    $workbook->send($filename);
2802
 
    $worksheet = array();
2803
 
    $worksheet[0] =& $workbook->add_worksheet('');
2804
 
    $rowno = 0;
2805
 
    foreach ($export as $row) {
2806
 
        $colno = 0;
2807
 
        foreach($row as $col) {
2808
 
            $worksheet[0]->write($rowno, $colno, $col);
2809
 
            $colno++;
2810
 
        }
2811
 
        $rowno++;
2812
 
    }
2813
 
    $workbook->close();
2814
 
    return $filename;
2815
 
}
2816
 
 
2817
 
/**
2818
 
 * @global object
2819
 
 * @param int $dataid
2820
 
 * @param array $fields
2821
 
 * @param array $selectedfields
2822
 
 * @param int $currentgroup group ID of the current group. This is used for
2823
 
 * exporting data while maintaining group divisions.
2824
 
 * @return array
2825
 
 */
2826
 
function data_get_exportdata($dataid, $fields, $selectedfields, $currentgroup=0) {
2827
 
    global $DB;
2828
 
 
2829
 
    $exportdata = array();
2830
 
 
2831
 
    // populate the header in first row of export
2832
 
    foreach($fields as $key => $field) {
2833
 
        if (!in_array($field->field->id, $selectedfields)) {
2834
 
            // ignore values we aren't exporting
2835
 
            unset($fields[$key]);
2836
 
        } else {
2837
 
            $exportdata[0][] = $field->field->name;
2838
 
        }
2839
 
    }
2840
 
 
2841
 
    $datarecords = $DB->get_records('data_records', array('dataid'=>$dataid));
2842
 
    ksort($datarecords);
2843
 
    $line = 1;
2844
 
    foreach($datarecords as $record) {
2845
 
        // get content indexed by fieldid
2846
 
        if ($currentgroup) {
2847
 
            $select = 'SELECT c.fieldid, c.content, c.content1, c.content2, c.content3, c.content4 FROM {data_content} c, {data_records} r WHERE c.recordid = ? AND r.id = c.recordid AND r.groupid = ?';
2848
 
            $where = array($record->id, $currentgroup);
2849
 
        } else {
2850
 
            $select = 'SELECT fieldid, content, content1, content2, content3, content4 FROM {data_content} WHERE recordid = ?';
2851
 
            $where = array($record->id);
2852
 
        }
2853
 
 
2854
 
        if( $content = $DB->get_records_sql($select, $where) ) {
2855
 
            foreach($fields as $field) {
2856
 
                $contents = '';
2857
 
                if(isset($content[$field->field->id])) {
2858
 
                    $contents = $field->export_text_value($content[$field->field->id]);
2859
 
                }
2860
 
                $exportdata[$line][] = $contents;
2861
 
            }
2862
 
        }
2863
 
        $line++;
2864
 
    }
2865
 
    $line--;
2866
 
    return $exportdata;
2867
 
}
2868
 
 
2869
 
/**
2870
 
 * Lists all browsable file areas
2871
 
 *
2872
 
 * @param object $course
2873
 
 * @param object $cm
2874
 
 * @param object $context
2875
 
 * @return array
2876
 
 */
2877
 
function data_get_file_areas($course, $cm, $context) {
2878
 
    $areas = array();
2879
 
    return $areas;
2880
 
}
2881
 
 
2882
 
/**
2883
 
 * File browsing support for data module.
2884
 
 *
2885
 
 * @param file_browser $browser
2886
 
 * @param array $areas
2887
 
 * @param stdClass $course
2888
 
 * @param cm_info $cm
2889
 
 * @param context $context
2890
 
 * @param string $filearea
2891
 
 * @param int $itemid
2892
 
 * @param string $filepath
2893
 
 * @param string $filename
2894
 
 * @return file_info_stored file_info_stored instance or null if not found
2895
 
 */
2896
 
function mod_data_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
2897
 
    global $CFG, $DB;
2898
 
 
2899
 
    if ($context->contextlevel != CONTEXT_MODULE) {
2900
 
        return null;
2901
 
    }
2902
 
 
2903
 
    if ($filearea === 'content') {
2904
 
        if (!$content = $DB->get_record('data_content', array('id'=>$itemid))) {
2905
 
            return null;
2906
 
        }
2907
 
 
2908
 
        if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
2909
 
            return null;
2910
 
        }
2911
 
 
2912
 
        if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
2913
 
            return null;
2914
 
        }
2915
 
 
2916
 
        if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
2917
 
            return null;
2918
 
        }
2919
 
 
2920
 
        //check if approved
2921
 
        if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
2922
 
            return null;
2923
 
        }
2924
 
 
2925
 
        // group access
2926
 
        if ($record->groupid) {
2927
 
            $groupmode = groups_get_activity_groupmode($cm, $course);
2928
 
            if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
2929
 
                if (!groups_is_member($record->groupid)) {
2930
 
                    return null;
2931
 
                }
2932
 
            }
2933
 
        }
2934
 
 
2935
 
        $fieldobj = data_get_field($field, $data, $cm);
2936
 
 
2937
 
        $filepath = is_null($filepath) ? '/' : $filepath;
2938
 
        $filename = is_null($filename) ? '.' : $filename;
2939
 
        if (!$fieldobj->file_ok($filepath.$filename)) {
2940
 
            return null;
2941
 
        }
2942
 
 
2943
 
        $fs = get_file_storage();
2944
 
        if (!($storedfile = $fs->get_file($context->id, 'mod_data', $filearea, $itemid, $filepath, $filename))) {
2945
 
            return null;
2946
 
        }
2947
 
        $urlbase = $CFG->wwwroot.'/pluginfile.php';
2948
 
        return new file_info_stored($browser, $context, $storedfile, $urlbase, $filearea, $itemid, true, true, false);
2949
 
    }
2950
 
 
2951
 
    return null;
2952
 
}
2953
 
 
2954
 
/**
2955
 
 * Serves the data attachments. Implements needed access control ;-)
2956
 
 *
2957
 
 * @param object $course
2958
 
 * @param object $cm
2959
 
 * @param object $context
2960
 
 * @param string $filearea
2961
 
 * @param array $args
2962
 
 * @param bool $forcedownload
2963
 
 * @return bool false if file not found, does not return if found - justsend the file
2964
 
 */
2965
 
function data_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2966
 
    global $CFG, $DB;
2967
 
 
2968
 
    if ($context->contextlevel != CONTEXT_MODULE) {
2969
 
        return false;
2970
 
    }
2971
 
 
2972
 
    require_course_login($course, true, $cm);
2973
 
 
2974
 
    if ($filearea === 'content') {
2975
 
        $contentid = (int)array_shift($args);
2976
 
 
2977
 
        if (!$content = $DB->get_record('data_content', array('id'=>$contentid))) {
2978
 
            return false;
2979
 
        }
2980
 
 
2981
 
        if (!$field = $DB->get_record('data_fields', array('id'=>$content->fieldid))) {
2982
 
            return false;
2983
 
        }
2984
 
 
2985
 
        if (!$record = $DB->get_record('data_records', array('id'=>$content->recordid))) {
2986
 
            return false;
2987
 
        }
2988
 
 
2989
 
        if (!$data = $DB->get_record('data', array('id'=>$field->dataid))) {
2990
 
            return false;
2991
 
        }
2992
 
 
2993
 
        if ($data->id != $cm->instance) {
2994
 
            // hacker attempt - context does not match the contentid
2995
 
            return false;
2996
 
        }
2997
 
 
2998
 
        //check if approved
2999
 
        if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3000
 
            return false;
3001
 
        }
3002
 
 
3003
 
        // group access
3004
 
        if ($record->groupid) {
3005
 
            $groupmode = groups_get_activity_groupmode($cm, $course);
3006
 
            if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3007
 
                if (!groups_is_member($record->groupid)) {
3008
 
                    return false;
3009
 
                }
3010
 
            }
3011
 
        }
3012
 
 
3013
 
        $fieldobj = data_get_field($field, $data, $cm);
3014
 
 
3015
 
        $relativepath = implode('/', $args);
3016
 
        $fullpath = "/$context->id/mod_data/content/$content->id/$relativepath";
3017
 
 
3018
 
        if (!$fieldobj->file_ok($relativepath)) {
3019
 
            return false;
3020
 
        }
3021
 
 
3022
 
        $fs = get_file_storage();
3023
 
        if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
3024
 
            return false;
3025
 
        }
3026
 
 
3027
 
        // finally send the file
3028
 
        send_stored_file($file, 0, 0, true); // download MUST be forced - security!
3029
 
    }
3030
 
 
3031
 
    return false;
3032
 
}
3033
 
 
3034
 
 
3035
 
function data_extend_navigation($navigation, $course, $module, $cm) {
3036
 
    global $CFG, $OUTPUT, $USER, $DB;
3037
 
 
3038
 
    $rid = optional_param('rid', 0, PARAM_INT);
3039
 
 
3040
 
    $data = $DB->get_record('data', array('id'=>$cm->instance));
3041
 
    $currentgroup = groups_get_activity_group($cm);
3042
 
    $groupmode = groups_get_activity_groupmode($cm);
3043
 
 
3044
 
     $numentries = data_numentries($data);
3045
 
    /// Check the number of entries required against the number of entries already made (doesn't apply to teachers)
3046
 
    if ($data->requiredentries > 0 && $numentries < $data->requiredentries && !has_capability('mod/data:manageentries', get_context_instance(CONTEXT_MODULE, $cm->id))) {
3047
 
        $data->entriesleft = $data->requiredentries - $numentries;
3048
 
        $entriesnode = $navigation->add(get_string('entrieslefttoadd', 'data', $data));
3049
 
        $entriesnode->add_class('note');
3050
 
    }
3051
 
 
3052
 
    $navigation->add(get_string('list', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance)));
3053
 
    if (!empty($rid)) {
3054
 
        $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'rid'=>$rid)));
3055
 
    } else {
3056
 
        $navigation->add(get_string('single', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'single')));
3057
 
    }
3058
 
    $navigation->add(get_string('search', 'data'), new moodle_url('/mod/data/view.php', array('d'=>$cm->instance, 'mode'=>'asearch')));
3059
 
}
3060
 
 
3061
 
/**
3062
 
 * Adds module specific settings to the settings block
3063
 
 *
3064
 
 * @param settings_navigation $settings The settings navigation object
3065
 
 * @param navigation_node $datanode The node to add module settings to
3066
 
 */
3067
 
function data_extend_settings_navigation(settings_navigation $settings, navigation_node $datanode) {
3068
 
    global $PAGE, $DB, $CFG, $USER;
3069
 
 
3070
 
    $data = $DB->get_record('data', array("id" => $PAGE->cm->instance));
3071
 
 
3072
 
    $currentgroup = groups_get_activity_group($PAGE->cm);
3073
 
    $groupmode = groups_get_activity_groupmode($PAGE->cm);
3074
 
 
3075
 
    if (data_user_can_add_entry($data, $currentgroup, $groupmode, $PAGE->cm->context)) { // took out participation list here!
3076
 
        if (empty($editentry)) { //TODO: undefined
3077
 
            $addstring = get_string('add', 'data');
3078
 
        } else {
3079
 
            $addstring = get_string('editentry', 'data');
3080
 
        }
3081
 
        $datanode->add($addstring, new moodle_url('/mod/data/edit.php', array('d'=>$PAGE->cm->instance)));
3082
 
    }
3083
 
 
3084
 
    if (has_capability(DATA_CAP_EXPORT, $PAGE->cm->context)) {
3085
 
        // The capability required to Export database records is centrally defined in 'lib.php'
3086
 
        // and should be weaker than those required to edit Templates, Fields and Presets.
3087
 
        $datanode->add(get_string('exportentries', 'data'), new moodle_url('/mod/data/export.php', array('d'=>$data->id)));
3088
 
    }
3089
 
    if (has_capability('mod/data:manageentries', $PAGE->cm->context)) {
3090
 
        $datanode->add(get_string('importentries', 'data'), new moodle_url('/mod/data/import.php', array('d'=>$data->id)));
3091
 
    }
3092
 
 
3093
 
    if (has_capability('mod/data:managetemplates', $PAGE->cm->context)) {
3094
 
        $currenttab = '';
3095
 
        if ($currenttab == 'list') {
3096
 
            $defaultemplate = 'listtemplate';
3097
 
        } else if ($currenttab == 'add') {
3098
 
            $defaultemplate = 'addtemplate';
3099
 
        } else if ($currenttab == 'asearch') {
3100
 
            $defaultemplate = 'asearchtemplate';
3101
 
        } else {
3102
 
            $defaultemplate = 'singletemplate';
3103
 
        }
3104
 
 
3105
 
        $templates = $datanode->add(get_string('templates', 'data'));
3106
 
 
3107
 
        $templatelist = array ('listtemplate', 'singletemplate', 'asearchtemplate', 'addtemplate', 'rsstemplate', 'csstemplate', 'jstemplate');
3108
 
        foreach ($templatelist as $template) {
3109
 
            $templates->add(get_string($template, 'data'), new moodle_url('/mod/data/templates.php', array('d'=>$data->id,'mode'=>$template)));
3110
 
        }
3111
 
 
3112
 
        $datanode->add(get_string('fields', 'data'), new moodle_url('/mod/data/field.php', array('d'=>$data->id)));
3113
 
        $datanode->add(get_string('presets', 'data'), new moodle_url('/mod/data/preset.php', array('d'=>$data->id)));
3114
 
    }
3115
 
 
3116
 
    if (!empty($CFG->enablerssfeeds) && !empty($CFG->data_enablerssfeeds) && $data->rssarticles > 0) {
3117
 
        require_once("$CFG->libdir/rsslib.php");
3118
 
 
3119
 
        $string = get_string('rsstype','forum');
3120
 
 
3121
 
        $url = new moodle_url(rss_get_url($PAGE->cm->context->id, $USER->id, 'mod_data', $data->id));
3122
 
        $datanode->add($string, $url, settings_navigation::TYPE_SETTING, null, null, new pix_icon('i/rss', ''));
3123
 
    }
3124
 
}
3125
 
 
3126
 
/**
3127
 
 * Save the database configuration as a preset.
3128
 
 *
3129
 
 * @param stdClass $course The course the database module belongs to.
3130
 
 * @param stdClass $cm The course module record
3131
 
 * @param stdClass $data The database record
3132
 
 * @param string $path
3133
 
 * @return bool
3134
 
 */
3135
 
function data_presets_save($course, $cm, $data, $path) {
3136
 
    global $USER;
3137
 
    $fs = get_file_storage();
3138
 
    $filerecord = new stdClass;
3139
 
    $filerecord->contextid = DATA_PRESET_CONTEXT;
3140
 
    $filerecord->component = DATA_PRESET_COMPONENT;
3141
 
    $filerecord->filearea = DATA_PRESET_FILEAREA;
3142
 
    $filerecord->itemid = 0;
3143
 
    $filerecord->filepath = '/'.$path.'/';
3144
 
    $filerecord->userid = $USER->id;
3145
 
 
3146
 
    $filerecord->filename = 'preset.xml';
3147
 
    $fs->create_file_from_string($filerecord, data_presets_generate_xml($course, $cm, $data));
3148
 
 
3149
 
    $filerecord->filename = 'singletemplate.html';
3150
 
    $fs->create_file_from_string($filerecord, $data->singletemplate);
3151
 
 
3152
 
    $filerecord->filename = 'listtemplateheader.html';
3153
 
    $fs->create_file_from_string($filerecord, $data->listtemplateheader);
3154
 
 
3155
 
    $filerecord->filename = 'listtemplate.html';
3156
 
    $fs->create_file_from_string($filerecord, $data->listtemplate);
3157
 
 
3158
 
    $filerecord->filename = 'listtemplatefooter.html';
3159
 
    $fs->create_file_from_string($filerecord, $data->listtemplatefooter);
3160
 
 
3161
 
    $filerecord->filename = 'addtemplate.html';
3162
 
    $fs->create_file_from_string($filerecord, $data->addtemplate);
3163
 
 
3164
 
    $filerecord->filename = 'rsstemplate.html';
3165
 
    $fs->create_file_from_string($filerecord, $data->rsstemplate);
3166
 
 
3167
 
    $filerecord->filename = 'rsstitletemplate.html';
3168
 
    $fs->create_file_from_string($filerecord, $data->rsstitletemplate);
3169
 
 
3170
 
    $filerecord->filename = 'csstemplate.css';
3171
 
    $fs->create_file_from_string($filerecord, $data->csstemplate);
3172
 
 
3173
 
    $filerecord->filename = 'jstemplate.js';
3174
 
    $fs->create_file_from_string($filerecord, $data->jstemplate);
3175
 
 
3176
 
    $filerecord->filename = 'asearchtemplate.html';
3177
 
    $fs->create_file_from_string($filerecord, $data->asearchtemplate);
3178
 
 
3179
 
    return true;
3180
 
}
3181
 
 
3182
 
/**
3183
 
 * Generates the XML for the database module provided
3184
 
 *
3185
 
 * @global moodle_database $DB
3186
 
 * @param stdClass $course The course the database module belongs to.
3187
 
 * @param stdClass $cm The course module record
3188
 
 * @param stdClass $data The database record
3189
 
 * @return string The XML for the preset
3190
 
 */
3191
 
function data_presets_generate_xml($course, $cm, $data) {
3192
 
    global $DB;
3193
 
 
3194
 
    // Assemble "preset.xml":
3195
 
    $presetxmldata = "<preset>\n\n";
3196
 
 
3197
 
    // Raw settings are not preprocessed during saving of presets
3198
 
    $raw_settings = array(
3199
 
        'intro',
3200
 
        'comments',
3201
 
        'requiredentries',
3202
 
        'requiredentriestoview',
3203
 
        'maxentries',
3204
 
        'rssarticles',
3205
 
        'approval',
3206
 
        'defaultsortdir'
3207
 
    );
3208
 
 
3209
 
    $presetxmldata .= "<settings>\n";
3210
 
    // First, settings that do not require any conversion
3211
 
    foreach ($raw_settings as $setting) {
3212
 
        $presetxmldata .= "<$setting>" . htmlspecialchars($data->$setting) . "</$setting>\n";
3213
 
    }
3214
 
 
3215
 
    // Now specific settings
3216
 
    if ($data->defaultsort > 0 && $sortfield = data_get_field_from_id($data->defaultsort, $data)) {
3217
 
        $presetxmldata .= '<defaultsort>' . htmlspecialchars($sortfield->field->name) . "</defaultsort>\n";
3218
 
    } else {
3219
 
        $presetxmldata .= "<defaultsort>0</defaultsort>\n";
3220
 
    }
3221
 
    $presetxmldata .= "</settings>\n\n";
3222
 
    // Now for the fields. Grab all that are non-empty
3223
 
    $fields = $DB->get_records('data_fields', array('dataid'=>$data->id));
3224
 
    ksort($fields);
3225
 
    if (!empty($fields)) {
3226
 
        foreach ($fields as $field) {
3227
 
            $presetxmldata .= "<field>\n";
3228
 
            foreach ($field as $key => $value) {
3229
 
                if ($value != '' && $key != 'id' && $key != 'dataid') {
3230
 
                    $presetxmldata .= "<$key>" . htmlspecialchars($value) . "</$key>\n";
3231
 
                }
3232
 
            }
3233
 
            $presetxmldata .= "</field>\n\n";
3234
 
        }
3235
 
    }
3236
 
    $presetxmldata .= '</preset>';
3237
 
    return $presetxmldata;
3238
 
}
3239
 
 
3240
 
function data_presets_export($course, $cm, $data, $tostorage=false) {
3241
 
    global $CFG, $DB;
3242
 
 
3243
 
    $presetname = clean_filename($data->name) . '-preset-' . gmdate("Ymd_Hi");
3244
 
    $exportsubdir = "mod_data/presetexport/$presetname";
3245
 
    make_temp_directory($exportsubdir);
3246
 
    $exportdir = "$CFG->tempdir/$exportsubdir";
3247
 
 
3248
 
    // Assemble "preset.xml":
3249
 
    $presetxmldata = data_presets_generate_xml($course, $cm, $data);
3250
 
 
3251
 
    // After opening a file in write mode, close it asap
3252
 
    $presetxmlfile = fopen($exportdir . '/preset.xml', 'w');
3253
 
    fwrite($presetxmlfile, $presetxmldata);
3254
 
    fclose($presetxmlfile);
3255
 
 
3256
 
    // Now write the template files
3257
 
    $singletemplate = fopen($exportdir . '/singletemplate.html', 'w');
3258
 
    fwrite($singletemplate, $data->singletemplate);
3259
 
    fclose($singletemplate);
3260
 
 
3261
 
    $listtemplateheader = fopen($exportdir . '/listtemplateheader.html', 'w');
3262
 
    fwrite($listtemplateheader, $data->listtemplateheader);
3263
 
    fclose($listtemplateheader);
3264
 
 
3265
 
    $listtemplate = fopen($exportdir . '/listtemplate.html', 'w');
3266
 
    fwrite($listtemplate, $data->listtemplate);
3267
 
    fclose($listtemplate);
3268
 
 
3269
 
    $listtemplatefooter = fopen($exportdir . '/listtemplatefooter.html', 'w');
3270
 
    fwrite($listtemplatefooter, $data->listtemplatefooter);
3271
 
    fclose($listtemplatefooter);
3272
 
 
3273
 
    $addtemplate = fopen($exportdir . '/addtemplate.html', 'w');
3274
 
    fwrite($addtemplate, $data->addtemplate);
3275
 
    fclose($addtemplate);
3276
 
 
3277
 
    $rsstemplate = fopen($exportdir . '/rsstemplate.html', 'w');
3278
 
    fwrite($rsstemplate, $data->rsstemplate);
3279
 
    fclose($rsstemplate);
3280
 
 
3281
 
    $rsstitletemplate = fopen($exportdir . '/rsstitletemplate.html', 'w');
3282
 
    fwrite($rsstitletemplate, $data->rsstitletemplate);
3283
 
    fclose($rsstitletemplate);
3284
 
 
3285
 
    $csstemplate = fopen($exportdir . '/csstemplate.css', 'w');
3286
 
    fwrite($csstemplate, $data->csstemplate);
3287
 
    fclose($csstemplate);
3288
 
 
3289
 
    $jstemplate = fopen($exportdir . '/jstemplate.js', 'w');
3290
 
    fwrite($jstemplate, $data->jstemplate);
3291
 
    fclose($jstemplate);
3292
 
 
3293
 
    $asearchtemplate = fopen($exportdir . '/asearchtemplate.html', 'w');
3294
 
    fwrite($asearchtemplate, $data->asearchtemplate);
3295
 
    fclose($asearchtemplate);
3296
 
 
3297
 
    // Check if all files have been generated
3298
 
    if (! is_directory_a_preset($exportdir)) {
3299
 
        print_error('generateerror', 'data');
3300
 
    }
3301
 
 
3302
 
    $filenames = array(
3303
 
        'preset.xml',
3304
 
        'singletemplate.html',
3305
 
        'listtemplateheader.html',
3306
 
        'listtemplate.html',
3307
 
        'listtemplatefooter.html',
3308
 
        'addtemplate.html',
3309
 
        'rsstemplate.html',
3310
 
        'rsstitletemplate.html',
3311
 
        'csstemplate.css',
3312
 
        'jstemplate.js',
3313
 
        'asearchtemplate.html'
3314
 
    );
3315
 
 
3316
 
    $filelist = array();
3317
 
    foreach ($filenames as $filename) {
3318
 
        $filelist[$filename] = $exportdir . '/' . $filename;
3319
 
    }
3320
 
 
3321
 
    $exportfile = $exportdir.'.zip';
3322
 
    file_exists($exportfile) && unlink($exportfile);
3323
 
 
3324
 
    $fp = get_file_packer('application/zip');
3325
 
    $fp->archive_to_pathname($filelist, $exportfile);
3326
 
 
3327
 
    foreach ($filelist as $file) {
3328
 
        unlink($file);
3329
 
    }
3330
 
    rmdir($exportdir);
3331
 
 
3332
 
    // Return the full path to the exported preset file:
3333
 
    return $exportfile;
3334
 
}
3335
 
 
3336
 
/**
3337
 
 * Running addtional permission check on plugin, for example, plugins
3338
 
 * may have switch to turn on/off comments option, this callback will
3339
 
 * affect UI display, not like pluginname_comment_validate only throw
3340
 
 * exceptions.
3341
 
 * Capability check has been done in comment->check_permissions(), we
3342
 
 * don't need to do it again here.
3343
 
 *
3344
 
 * @param stdClass $comment_param {
3345
 
 *              context  => context the context object
3346
 
 *              courseid => int course id
3347
 
 *              cm       => stdClass course module object
3348
 
 *              commentarea => string comment area
3349
 
 *              itemid      => int itemid
3350
 
 * }
3351
 
 * @return array
3352
 
 */
3353
 
function data_comment_permissions($comment_param) {
3354
 
    global $CFG, $DB;
3355
 
    if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3356
 
        throw new comment_exception('invalidcommentitemid');
3357
 
    }
3358
 
    if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3359
 
        throw new comment_exception('invalidid', 'data');
3360
 
    }
3361
 
    if ($data->comments) {
3362
 
        return array('post'=>true, 'view'=>true);
3363
 
    } else {
3364
 
        return array('post'=>false, 'view'=>false);
3365
 
    }
3366
 
}
3367
 
 
3368
 
/**
3369
 
 * Validate comment parameter before perform other comments actions
3370
 
 *
3371
 
 * @param stdClass $comment_param {
3372
 
 *              context  => context the context object
3373
 
 *              courseid => int course id
3374
 
 *              cm       => stdClass course module object
3375
 
 *              commentarea => string comment area
3376
 
 *              itemid      => int itemid
3377
 
 * }
3378
 
 * @return boolean
3379
 
 */
3380
 
function data_comment_validate($comment_param) {
3381
 
    global $DB;
3382
 
    // validate comment area
3383
 
    if ($comment_param->commentarea != 'database_entry') {
3384
 
        throw new comment_exception('invalidcommentarea');
3385
 
    }
3386
 
    // validate itemid
3387
 
    if (!$record = $DB->get_record('data_records', array('id'=>$comment_param->itemid))) {
3388
 
        throw new comment_exception('invalidcommentitemid');
3389
 
    }
3390
 
    if (!$data = $DB->get_record('data', array('id'=>$record->dataid))) {
3391
 
        throw new comment_exception('invalidid', 'data');
3392
 
    }
3393
 
    if (!$course = $DB->get_record('course', array('id'=>$data->course))) {
3394
 
        throw new comment_exception('coursemisconf');
3395
 
    }
3396
 
    if (!$cm = get_coursemodule_from_instance('data', $data->id, $course->id)) {
3397
 
        throw new comment_exception('invalidcoursemodule');
3398
 
    }
3399
 
    if (!$data->comments) {
3400
 
        throw new comment_exception('commentsoff', 'data');
3401
 
    }
3402
 
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3403
 
 
3404
 
    //check if approved
3405
 
    if ($data->approval and !$record->approved and !data_isowner($record) and !has_capability('mod/data:approve', $context)) {
3406
 
        throw new comment_exception('notapproved', 'data');
3407
 
    }
3408
 
 
3409
 
    // group access
3410
 
    if ($record->groupid) {
3411
 
        $groupmode = groups_get_activity_groupmode($cm, $course);
3412
 
        if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
3413
 
            if (!groups_is_member($record->groupid)) {
3414
 
                throw new comment_exception('notmemberofgroup');
3415
 
            }
3416
 
        }
3417
 
    }
3418
 
    // validate context id
3419
 
    if ($context->id != $comment_param->context->id) {
3420
 
        throw new comment_exception('invalidcontext');
3421
 
    }
3422
 
    // validation for comment deletion
3423
 
    if (!empty($comment_param->commentid)) {
3424
 
        if ($comment = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
3425
 
            if ($comment->commentarea != 'database_entry') {
3426
 
                throw new comment_exception('invalidcommentarea');
3427
 
            }
3428
 
            if ($comment->contextid != $comment_param->context->id) {
3429
 
                throw new comment_exception('invalidcontext');
3430
 
            }
3431
 
            if ($comment->itemid != $comment_param->itemid) {
3432
 
                throw new comment_exception('invalidcommentitemid');
3433
 
            }
3434
 
        } else {
3435
 
            throw new comment_exception('invalidcommentid');
3436
 
        }
3437
 
    }
3438
 
    return true;
3439
 
}
3440
 
 
3441
 
/**
3442
 
 * Return a list of page types
3443
 
 * @param string $pagetype current page type
3444
 
 * @param stdClass $parentcontext Block's parent context
3445
 
 * @param stdClass $currentcontext Current context of block
3446
 
 */
3447
 
function data_page_type_list($pagetype, $parentcontext, $currentcontext) {
3448
 
    $module_pagetype = array('mod-data-*'=>get_string('page-mod-data-x', 'data'));
3449
 
    return $module_pagetype;
3450
 
}
3451
 
 
3452
 
/**
3453
 
 * Checks to see if the user has permission to delete the preset.
3454
 
 * @param stdClass $context  Context object.
3455
 
 * @param stdClass $preset  The preset object that we are checking for deletion.
3456
 
 * @return bool  Returns true if the user can delete, otherwise false.
3457
 
 */
3458
 
function data_user_can_delete_preset($context, $preset) {
3459
 
    global $USER;
3460
 
 
3461
 
    if (has_capability('mod/data:manageuserpresets', $context)) {
3462
 
        return true;
3463
 
    } else {
3464
 
        $candelete = false;
3465
 
        if ($preset->userid == $USER->id) {
3466
 
            $candelete = true;
3467
 
        }
3468
 
        return $candelete;
3469
 
    }
3470
 
}
3471
 
 
3472
 
/**
3473
 
 * Get all of the record ids from a database activity.
3474
 
 *
3475
 
 * @param int    $dataid      The dataid of the database module.
3476
 
 * @param object $selectdata  Contains an additional sql statement for the
3477
 
 *                            where clause for group and approval fields.
3478
 
 * @param array  $params      Parameters that coincide with the sql statement.
3479
 
 * @return array $idarray     An array of record ids
3480
 
 */
3481
 
function data_get_all_recordids($dataid, $selectdata = '', $params = null) {
3482
 
    global $DB;
3483
 
    $initsql = 'SELECT r.id
3484
 
                  FROM {data_records} r
3485
 
                 WHERE r.dataid = :dataid';
3486
 
    if ($selectdata != '') {
3487
 
        $initsql .= $selectdata;
3488
 
        $params = array_merge(array('dataid' => $dataid), $params);
3489
 
    } else {
3490
 
        $params = array('dataid' => $dataid);
3491
 
    }
3492
 
    $initsql .= ' GROUP BY r.id';
3493
 
    $initrecord = $DB->get_recordset_sql($initsql, $params);
3494
 
    $idarray = array();
3495
 
    foreach ($initrecord as $data) {
3496
 
        $idarray[] = $data->id;
3497
 
    }
3498
 
    // Close the record set and free up resources.
3499
 
    $initrecord->close();
3500
 
    return $idarray;
3501
 
}
3502
 
 
3503
 
/**
3504
 
 * Get the ids of all the records that match that advanced search criteria
3505
 
 * This goes and loops through each criterion one at a time until it either
3506
 
 * runs out of records or returns a subset of records.
3507
 
 *
3508
 
 * @param array $recordids    An array of record ids.
3509
 
 * @param array $searcharray  Contains information for the advanced search criteria
3510
 
 * @param int $dataid         The data id of the database.
3511
 
 * @return array $recordids   An array of record ids.
3512
 
 */
3513
 
function data_get_advance_search_ids($recordids, $searcharray, $dataid) {
3514
 
    $searchcriteria = array_keys($searcharray);
3515
 
    // Loop through and reduce the IDs one search criteria at a time.
3516
 
    foreach ($searchcriteria as $key) {
3517
 
        $recordids = data_get_recordids($key, $searcharray, $dataid, $recordids);
3518
 
        // If we don't have anymore IDs then stop.
3519
 
        if (!$recordids) {
3520
 
            break;
3521
 
        }
3522
 
    }
3523
 
    return $recordids;
3524
 
}
3525
 
 
3526
 
/**
3527
 
 * Gets the record IDs given the search criteria
3528
 
 *
3529
 
 * @param string $alias       Record alias.
3530
 
 * @param array $searcharray  Criteria for the search.
3531
 
 * @param int $dataid         Data ID for the database
3532
 
 * @param array $recordids    An array of record IDs.
3533
 
 * @return array $nestarray   An arry of record IDs
3534
 
 */
3535
 
function data_get_recordids($alias, $searcharray, $dataid, $recordids) {
3536
 
    global $DB;
3537
 
 
3538
 
    $nestsearch = $searcharray[$alias];
3539
 
    // searching for content outside of mdl_data_content
3540
 
    if ($alias < 0) {
3541
 
        $alias = '';
3542
 
    }
3543
 
    list($insql, $params) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3544
 
    $nestselect = 'SELECT c' . $alias . '.recordid
3545
 
                     FROM {data_content} c' . $alias . ',
3546
 
                          {data_fields} f,
3547
 
                          {data_records} r,
3548
 
                          {user} u ';
3549
 
    $nestwhere = 'WHERE u.id = r.userid
3550
 
                    AND f.id = c' . $alias . '.fieldid
3551
 
                    AND r.id = c' . $alias . '.recordid
3552
 
                    AND r.dataid = :dataid
3553
 
                    AND c' . $alias .'.recordid ' . $insql . '
3554
 
                    AND ';
3555
 
 
3556
 
    $params['dataid'] = $dataid;
3557
 
    if (count($nestsearch->params) != 0) {
3558
 
        $params = array_merge($params, $nestsearch->params);
3559
 
        $nestsql = $nestselect . $nestwhere . $nestsearch->sql;
3560
 
    } else {
3561
 
        $thing = $DB->sql_like($nestsearch->field, ':search1', false);
3562
 
        $nestsql = $nestselect . $nestwhere . $thing . ' GROUP BY c' . $alias . '.recordid';
3563
 
        $params['search1'] = "%$nestsearch->data%";
3564
 
    }
3565
 
    $nestrecords = $DB->get_recordset_sql($nestsql, $params);
3566
 
    $nestarray = array();
3567
 
    foreach ($nestrecords as $data) {
3568
 
        $nestarray[] = $data->recordid;
3569
 
    }
3570
 
    // Close the record set and free up resources.
3571
 
    $nestrecords->close();
3572
 
    return $nestarray;
3573
 
}
3574
 
 
3575
 
/**
3576
 
 * Returns an array with an sql string for advanced searches and the parameters that go with them.
3577
 
 *
3578
 
 * @param int $sort            DATA_*
3579
 
 * @param stdClass $data       Data module object
3580
 
 * @param array $recordids     An array of record IDs.
3581
 
 * @param string $selectdata   Information for the select part of the sql statement.
3582
 
 * @param string $sortorder    Additional sort parameters
3583
 
 * @return array sqlselect     sqlselect['sql] has the sql string, sqlselect['params'] contains an array of parameters.
3584
 
 */
3585
 
function data_get_advanced_search_sql($sort, $data, $recordids, $selectdata, $sortorder) {
3586
 
    global $DB;
3587
 
    if ($sort == 0) {
3588
 
        $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname
3589
 
                        FROM {data_content} c,
3590
 
                             {data_records} r,
3591
 
                             {user} u ';
3592
 
        $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname ';
3593
 
    } else {
3594
 
        // Sorting through 'Other' criteria
3595
 
        if ($sort <= 0) {
3596
 
            switch ($sort) {
3597
 
                case DATA_LASTNAME:
3598
 
                    $sortcontentfull = "u.lastname";
3599
 
                    break;
3600
 
                case DATA_FIRSTNAME:
3601
 
                    $sortcontentfull = "u.firstname";
3602
 
                    break;
3603
 
                case DATA_APPROVED:
3604
 
                    $sortcontentfull = "r.approved";
3605
 
                    break;
3606
 
                case DATA_TIMEMODIFIED:
3607
 
                    $sortcontentfull = "r.timemodified";
3608
 
                    break;
3609
 
                case DATA_TIMEADDED:
3610
 
                default:
3611
 
                    $sortcontentfull = "r.timecreated";
3612
 
            }
3613
 
        } else {
3614
 
            $sortfield = data_get_field_from_id($sort, $data);
3615
 
            $sortcontent = $DB->sql_compare_text('c.' . $sortfield->get_sort_field());
3616
 
            $sortcontentfull = $sortfield->get_sort_sql($sortcontent);
3617
 
        }
3618
 
 
3619
 
        $nestselectsql = 'SELECT r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' . $sortcontentfull . '
3620
 
                              AS sortorder
3621
 
                            FROM {data_content} c,
3622
 
                                 {data_records} r,
3623
 
                                 {user} u ';
3624
 
        $groupsql = ' GROUP BY r.id, r.approved, r.timecreated, r.timemodified, r.userid, u.firstname, u.lastname, ' .$sortcontentfull;
3625
 
    }
3626
 
    $nestfromsql = 'WHERE c.recordid = r.id
3627
 
                      AND r.dataid = :dataid
3628
 
                      AND r.userid = u.id';
3629
 
 
3630
 
    // Find the field we are sorting on
3631
 
    if ($sort > 0 or data_get_field_from_id($sort, $data)) {
3632
 
        $nestfromsql .= ' AND c.fieldid = :sort';
3633
 
    }
3634
 
 
3635
 
    // If there are no record IDs then return an sql statment that will return no rows.
3636
 
    if (count($recordids) != 0) {
3637
 
        list($insql, $inparam) = $DB->get_in_or_equal($recordids, SQL_PARAMS_NAMED);
3638
 
    } else {
3639
 
        list($insql, $inparam) = $DB->get_in_or_equal(array('-1'), SQL_PARAMS_NAMED);
3640
 
    }
3641
 
    $nestfromsql .= ' AND c.recordid ' . $insql . $selectdata . $groupsql;
3642
 
    $sqlselect['sql'] = "$nestselectsql $nestfromsql $sortorder";
3643
 
    $sqlselect['params'] = $inparam;
3644
 
    return $sqlselect;
3645
 
}