PageRenderTime 88ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/mod/data/lib.php

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