PageRenderTime 40ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/mod/data/lib.php

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