PageRenderTime 67ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

/calendar/lib.php

https://bitbucket.org/moodle/moodle
PHP | 3981 lines | 2414 code | 467 blank | 1100 comment | 684 complexity | a04859ea934bd6cf87ea651a2331e675 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  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. * Calendar extension
  18. *
  19. * @package core_calendar
  20. * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
  21. * Avgoustos Tsinakos
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. if (!defined('MOODLE_INTERNAL')) {
  25. die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
  26. }
  27. /**
  28. * These are read by the administration component to provide default values
  29. */
  30. /**
  31. * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
  32. */
  33. define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
  34. /**
  35. * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
  36. */
  37. define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
  38. /**
  39. * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
  40. */
  41. define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
  42. // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
  43. // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
  44. /**
  45. * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
  46. */
  47. define('CALENDAR_DEFAULT_WEEKEND', 65);
  48. /**
  49. * CALENDAR_URL - path to calendar's folder
  50. */
  51. define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
  52. /**
  53. * CALENDAR_TF_24 - Calendar time in 24 hours format
  54. */
  55. define('CALENDAR_TF_24', '%H:%M');
  56. /**
  57. * CALENDAR_TF_12 - Calendar time in 12 hours format
  58. */
  59. define('CALENDAR_TF_12', '%I:%M %p');
  60. /**
  61. * CALENDAR_EVENT_GLOBAL - Site calendar event types
  62. * @deprecated since 3.8
  63. */
  64. define('CALENDAR_EVENT_GLOBAL', 1);
  65. /**
  66. * CALENDAR_EVENT_SITE - Site calendar event types
  67. */
  68. define('CALENDAR_EVENT_SITE', 1);
  69. /**
  70. * CALENDAR_EVENT_COURSE - Course calendar event types
  71. */
  72. define('CALENDAR_EVENT_COURSE', 2);
  73. /**
  74. * CALENDAR_EVENT_GROUP - group calendar event types
  75. */
  76. define('CALENDAR_EVENT_GROUP', 4);
  77. /**
  78. * CALENDAR_EVENT_USER - user calendar event types
  79. */
  80. define('CALENDAR_EVENT_USER', 8);
  81. /**
  82. * CALENDAR_EVENT_COURSECAT - Course category calendar event types
  83. */
  84. define('CALENDAR_EVENT_COURSECAT', 16);
  85. /**
  86. * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
  87. */
  88. define('CALENDAR_IMPORT_FROM_FILE', 0);
  89. /**
  90. * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
  91. */
  92. define('CALENDAR_IMPORT_FROM_URL', 1);
  93. /**
  94. * CALENDAR_IMPORT_EVENT_UPDATED_SKIPPED - imported event was skipped
  95. */
  96. define('CALENDAR_IMPORT_EVENT_SKIPPED', -1);
  97. /**
  98. * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
  99. */
  100. define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
  101. /**
  102. * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
  103. */
  104. define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
  105. /**
  106. * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
  107. */
  108. define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
  109. /**
  110. * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
  111. */
  112. define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
  113. /**
  114. * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
  115. */
  116. define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
  117. /**
  118. * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
  119. */
  120. define('CALENDAR_EVENT_TYPE_STANDARD', 0);
  121. /**
  122. * CALENDAR_EVENT_TYPE_ACTION - Action events.
  123. */
  124. define('CALENDAR_EVENT_TYPE_ACTION', 1);
  125. /**
  126. * Manage calendar events.
  127. *
  128. * This class provides the required functionality in order to manage calendar events.
  129. * It was introduced as part of Moodle 2.0 and was created in order to provide a
  130. * better framework for dealing with calendar events in particular regard to file
  131. * handling through the new file API.
  132. *
  133. * @package core_calendar
  134. * @category calendar
  135. * @copyright 2009 Sam Hemelryk
  136. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  137. *
  138. * @property int $id The id within the event table
  139. * @property string $name The name of the event
  140. * @property string $description The description of the event
  141. * @property int $format The format of the description FORMAT_?
  142. * @property int $courseid The course the event is associated with (0 if none)
  143. * @property int $groupid The group the event is associated with (0 if none)
  144. * @property int $userid The user the event is associated with (0 if none)
  145. * @property int $repeatid If this is a repeated event this will be set to the
  146. * id of the original
  147. * @property string $component If created by a plugin/component (other than module), the full frankenstyle name of a component
  148. * @property string $modulename If added by a module this will be the module name
  149. * @property int $instance If added by a module this will be the module instance
  150. * @property string $eventtype The event type
  151. * @property int $timestart The start time as a timestamp
  152. * @property int $timeduration The duration of the event in seconds
  153. * @property int $timeusermidnight User midnight for the event
  154. * @property int $visible 1 if the event is visible
  155. * @property int $uuid ?
  156. * @property int $sequence ?
  157. * @property int $timemodified The time last modified as a timestamp
  158. */
  159. class calendar_event {
  160. /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
  161. protected $properties = null;
  162. /** @var string The converted event discription with file paths resolved.
  163. * This gets populated when someone requests description for the first time */
  164. protected $_description = null;
  165. /** @var array The options to use with this description editor */
  166. protected $editoroptions = array(
  167. 'subdirs' => false,
  168. 'forcehttps' => false,
  169. 'maxfiles' => -1,
  170. 'maxbytes' => null,
  171. 'trusttext' => false);
  172. /** @var object The context to use with the description editor */
  173. protected $editorcontext = null;
  174. /**
  175. * Instantiates a new event and optionally populates its properties with the data provided.
  176. *
  177. * @param \stdClass $data Optional. An object containing the properties to for
  178. * an event
  179. */
  180. public function __construct($data = null) {
  181. global $CFG, $USER;
  182. // First convert to object if it is not already (should either be object or assoc array).
  183. if (!is_object($data)) {
  184. $data = (object) $data;
  185. }
  186. $this->editoroptions['maxbytes'] = $CFG->maxbytes;
  187. $data->eventrepeats = 0;
  188. if (empty($data->id)) {
  189. $data->id = null;
  190. }
  191. if (!empty($data->subscriptionid)) {
  192. $data->subscription = calendar_get_subscription($data->subscriptionid);
  193. }
  194. // Default to a user event.
  195. if (empty($data->eventtype)) {
  196. $data->eventtype = 'user';
  197. }
  198. // Default to the current user.
  199. if (empty($data->userid)) {
  200. $data->userid = $USER->id;
  201. }
  202. if (!empty($data->timeduration) && is_array($data->timeduration)) {
  203. $data->timeduration = make_timestamp(
  204. $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
  205. $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
  206. }
  207. if (!empty($data->description) && is_array($data->description)) {
  208. $data->format = $data->description['format'];
  209. $data->description = $data->description['text'];
  210. } else if (empty($data->description)) {
  211. $data->description = '';
  212. $data->format = editors_get_preferred_format();
  213. }
  214. // Ensure form is defaulted correctly.
  215. if (empty($data->format)) {
  216. $data->format = editors_get_preferred_format();
  217. }
  218. if (empty($data->component)) {
  219. $data->component = null;
  220. }
  221. $this->properties = $data;
  222. }
  223. /**
  224. * Magic set method.
  225. *
  226. * Attempts to call a set_$key method if one exists otherwise falls back
  227. * to simply set the property.
  228. *
  229. * @param string $key property name
  230. * @param mixed $value value of the property
  231. */
  232. public function __set($key, $value) {
  233. if (method_exists($this, 'set_'.$key)) {
  234. $this->{'set_'.$key}($value);
  235. }
  236. $this->properties->{$key} = $value;
  237. }
  238. /**
  239. * Magic get method.
  240. *
  241. * Attempts to call a get_$key method to return the property and ralls over
  242. * to return the raw property.
  243. *
  244. * @param string $key property name
  245. * @return mixed property value
  246. * @throws \coding_exception
  247. */
  248. public function __get($key) {
  249. if (method_exists($this, 'get_'.$key)) {
  250. return $this->{'get_'.$key}();
  251. }
  252. if (!property_exists($this->properties, $key)) {
  253. throw new \coding_exception('Undefined property requested');
  254. }
  255. return $this->properties->{$key};
  256. }
  257. /**
  258. * Magic isset method.
  259. *
  260. * PHP needs an isset magic method if you use the get magic method and
  261. * still want empty calls to work.
  262. *
  263. * @param string $key $key property name
  264. * @return bool|mixed property value, false if property is not exist
  265. */
  266. public function __isset($key) {
  267. return !empty($this->properties->{$key});
  268. }
  269. /**
  270. * Calculate the context value needed for an event.
  271. *
  272. * Event's type can be determine by the available value store in $data
  273. * It is important to check for the existence of course/courseid to determine
  274. * the course event.
  275. * Default value is set to CONTEXT_USER
  276. *
  277. * @return \stdClass The context object.
  278. */
  279. protected function calculate_context() {
  280. global $USER, $DB;
  281. $context = null;
  282. if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
  283. $context = \context_coursecat::instance($this->properties->categoryid);
  284. } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
  285. $context = \context_course::instance($this->properties->courseid);
  286. } else if (isset($this->properties->course) && $this->properties->course > 0) {
  287. $context = \context_course::instance($this->properties->course);
  288. } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
  289. $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
  290. $context = \context_course::instance($group->courseid);
  291. } else if (isset($this->properties->userid) && $this->properties->userid > 0
  292. && $this->properties->userid == $USER->id) {
  293. $context = \context_user::instance($this->properties->userid);
  294. } else if (isset($this->properties->userid) && $this->properties->userid > 0
  295. && $this->properties->userid != $USER->id &&
  296. !empty($this->properties->modulename) &&
  297. isset($this->properties->instance) && $this->properties->instance > 0) {
  298. $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
  299. false, MUST_EXIST);
  300. $context = \context_course::instance($cm->course);
  301. } else {
  302. $context = \context_user::instance($this->properties->userid);
  303. }
  304. return $context;
  305. }
  306. /**
  307. * Returns the context for this event. The context is calculated
  308. * the first time is is requested and then stored in a member
  309. * variable to be returned each subsequent time.
  310. *
  311. * This is a magical getter function that will be called when
  312. * ever the context property is accessed, e.g. $event->context.
  313. *
  314. * @return context
  315. */
  316. protected function get_context() {
  317. if (!isset($this->properties->context)) {
  318. $this->properties->context = $this->calculate_context();
  319. }
  320. return $this->properties->context;
  321. }
  322. /**
  323. * Returns an array of editoroptions for this event.
  324. *
  325. * @return array event editor options
  326. */
  327. protected function get_editoroptions() {
  328. return $this->editoroptions;
  329. }
  330. /**
  331. * Returns an event description: Called by __get
  332. * Please use $blah = $event->description;
  333. *
  334. * @return string event description
  335. */
  336. protected function get_description() {
  337. global $CFG;
  338. require_once($CFG->libdir . '/filelib.php');
  339. if ($this->_description === null) {
  340. // Check if we have already resolved the context for this event.
  341. if ($this->editorcontext === null) {
  342. // Switch on the event type to decide upon the appropriate context to use for this event.
  343. $this->editorcontext = $this->get_context();
  344. if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
  345. return clean_text($this->properties->description, $this->properties->format);
  346. }
  347. }
  348. // Work out the item id for the editor, if this is a repeated event
  349. // then the files will be associated with the original.
  350. if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
  351. $itemid = $this->properties->repeatid;
  352. } else {
  353. $itemid = $this->properties->id;
  354. }
  355. // Convert file paths in the description so that things display correctly.
  356. $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
  357. $this->editorcontext->id, 'calendar', 'event_description', $itemid);
  358. // Clean the text so no nasties get through.
  359. $this->_description = clean_text($this->_description, $this->properties->format);
  360. }
  361. // Finally return the description.
  362. return $this->_description;
  363. }
  364. /**
  365. * Return the number of repeat events there are in this events series.
  366. *
  367. * @return int number of event repeated
  368. */
  369. public function count_repeats() {
  370. global $DB;
  371. if (!empty($this->properties->repeatid)) {
  372. $this->properties->eventrepeats = $DB->count_records('event',
  373. array('repeatid' => $this->properties->repeatid));
  374. // We don't want to count ourselves.
  375. $this->properties->eventrepeats--;
  376. }
  377. return $this->properties->eventrepeats;
  378. }
  379. /**
  380. * Update or create an event within the database
  381. *
  382. * Pass in a object containing the event properties and this function will
  383. * insert it into the database and deal with any associated files
  384. *
  385. * Capability checking should be performed if the user is directly manipulating the event
  386. * and no other capability has been tested. However if the event is not being manipulated
  387. * directly by the user and another capability has been checked for them to do this then
  388. * capabilites should not be checked.
  389. *
  390. * For example if a user is editing an event in the calendar the check should be true,
  391. * but if you are updating an event in an activities settings are changed then the calendar
  392. * capabilites should not be checked.
  393. *
  394. * @see self::create()
  395. * @see self::update()
  396. *
  397. * @param \stdClass $data object of event
  398. * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
  399. * @return bool event updated
  400. */
  401. public function update($data, $checkcapability=true) {
  402. global $DB, $USER;
  403. foreach ($data as $key => $value) {
  404. $this->properties->$key = $value;
  405. }
  406. $this->properties->timemodified = time();
  407. $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
  408. // Prepare event data.
  409. $eventargs = array(
  410. 'context' => $this->get_context(),
  411. 'objectid' => $this->properties->id,
  412. 'other' => array(
  413. 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
  414. 'timestart' => $this->properties->timestart,
  415. 'name' => $this->properties->name
  416. )
  417. );
  418. if (empty($this->properties->id) || $this->properties->id < 1) {
  419. if ($checkcapability) {
  420. if (!calendar_add_event_allowed($this->properties)) {
  421. print_error('nopermissiontoupdatecalendar');
  422. }
  423. }
  424. if ($usingeditor) {
  425. switch ($this->properties->eventtype) {
  426. case 'user':
  427. $this->properties->courseid = 0;
  428. $this->properties->course = 0;
  429. $this->properties->groupid = 0;
  430. $this->properties->userid = $USER->id;
  431. break;
  432. case 'site':
  433. $this->properties->courseid = SITEID;
  434. $this->properties->course = SITEID;
  435. $this->properties->groupid = 0;
  436. $this->properties->userid = $USER->id;
  437. break;
  438. case 'course':
  439. $this->properties->groupid = 0;
  440. $this->properties->userid = $USER->id;
  441. break;
  442. case 'category':
  443. $this->properties->groupid = 0;
  444. $this->properties->category = 0;
  445. $this->properties->userid = $USER->id;
  446. break;
  447. case 'group':
  448. $this->properties->userid = $USER->id;
  449. break;
  450. default:
  451. // We should NEVER get here, but just incase we do lets fail gracefully.
  452. $usingeditor = false;
  453. break;
  454. }
  455. // If we are actually using the editor, we recalculate the context because some default values
  456. // were set when calculate_context() was called from the constructor.
  457. if ($usingeditor) {
  458. $this->properties->context = $this->calculate_context();
  459. $this->editorcontext = $this->get_context();
  460. }
  461. $editor = $this->properties->description;
  462. $this->properties->format = $this->properties->description['format'];
  463. $this->properties->description = $this->properties->description['text'];
  464. }
  465. // Insert the event into the database.
  466. $this->properties->id = $DB->insert_record('event', $this->properties);
  467. if ($usingeditor) {
  468. $this->properties->description = file_save_draft_area_files(
  469. $editor['itemid'],
  470. $this->editorcontext->id,
  471. 'calendar',
  472. 'event_description',
  473. $this->properties->id,
  474. $this->editoroptions,
  475. $editor['text'],
  476. $this->editoroptions['forcehttps']);
  477. $DB->set_field('event', 'description', $this->properties->description,
  478. array('id' => $this->properties->id));
  479. }
  480. // Log the event entry.
  481. $eventargs['objectid'] = $this->properties->id;
  482. $eventargs['context'] = $this->get_context();
  483. $event = \core\event\calendar_event_created::create($eventargs);
  484. $event->trigger();
  485. $repeatedids = array();
  486. if (!empty($this->properties->repeat)) {
  487. $this->properties->repeatid = $this->properties->id;
  488. $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
  489. $eventcopy = clone($this->properties);
  490. unset($eventcopy->id);
  491. $timestart = new \DateTime('@' . $eventcopy->timestart);
  492. $timestart->setTimezone(\core_date::get_user_timezone_object());
  493. for ($i = 1; $i < $eventcopy->repeats; $i++) {
  494. $timestart->add(new \DateInterval('P7D'));
  495. $eventcopy->timestart = $timestart->getTimestamp();
  496. // Get the event id for the log record.
  497. $eventcopyid = $DB->insert_record('event', $eventcopy);
  498. // If the context has been set delete all associated files.
  499. if ($usingeditor) {
  500. $fs = get_file_storage();
  501. $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
  502. $this->properties->id);
  503. foreach ($files as $file) {
  504. $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
  505. }
  506. }
  507. $repeatedids[] = $eventcopyid;
  508. // Trigger an event.
  509. $eventargs['objectid'] = $eventcopyid;
  510. $eventargs['other']['timestart'] = $eventcopy->timestart;
  511. $event = \core\event\calendar_event_created::create($eventargs);
  512. $event->trigger();
  513. }
  514. }
  515. return true;
  516. } else {
  517. if ($checkcapability) {
  518. if (!calendar_edit_event_allowed($this->properties)) {
  519. print_error('nopermissiontoupdatecalendar');
  520. }
  521. }
  522. if ($usingeditor) {
  523. if ($this->editorcontext !== null) {
  524. $this->properties->description = file_save_draft_area_files(
  525. $this->properties->description['itemid'],
  526. $this->editorcontext->id,
  527. 'calendar',
  528. 'event_description',
  529. $this->properties->id,
  530. $this->editoroptions,
  531. $this->properties->description['text'],
  532. $this->editoroptions['forcehttps']);
  533. } else {
  534. $this->properties->format = $this->properties->description['format'];
  535. $this->properties->description = $this->properties->description['text'];
  536. }
  537. }
  538. $event = $DB->get_record('event', array('id' => $this->properties->id));
  539. $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
  540. if ($updaterepeated) {
  541. $sqlset = 'name = ?,
  542. description = ?,
  543. timeduration = ?,
  544. timemodified = ?,
  545. groupid = ?,
  546. courseid = ?';
  547. // Note: Group and course id may not be set. If not, keep their current values.
  548. $params = [
  549. $this->properties->name,
  550. $this->properties->description,
  551. $this->properties->timeduration,
  552. time(),
  553. isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
  554. isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
  555. ];
  556. // Note: Only update start date, if it was changed by the user.
  557. if ($this->properties->timestart != $event->timestart) {
  558. $timestartoffset = $this->properties->timestart - $event->timestart;
  559. $sqlset .= ', timestart = timestart + ?';
  560. $params[] = $timestartoffset;
  561. }
  562. // Note: Only update location, if it was changed by the user.
  563. $updatelocation = (!empty($this->properties->location) && $this->properties->location !== $event->location);
  564. if ($updatelocation) {
  565. $sqlset .= ', location = ?';
  566. $params[] = $this->properties->location;
  567. }
  568. // Update all.
  569. $sql = "UPDATE {event}
  570. SET $sqlset
  571. WHERE repeatid = ?";
  572. $params[] = $event->repeatid;
  573. $DB->execute($sql, $params);
  574. // Trigger an update event for each of the calendar event.
  575. $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
  576. foreach ($events as $calendarevent) {
  577. $eventargs['objectid'] = $calendarevent->id;
  578. $eventargs['other']['timestart'] = $calendarevent->timestart;
  579. $event = \core\event\calendar_event_updated::create($eventargs);
  580. $event->add_record_snapshot('event', $calendarevent);
  581. $event->trigger();
  582. }
  583. } else {
  584. $DB->update_record('event', $this->properties);
  585. $event = self::load($this->properties->id);
  586. $this->properties = $event->properties();
  587. // Trigger an update event.
  588. $event = \core\event\calendar_event_updated::create($eventargs);
  589. $event->add_record_snapshot('event', $this->properties);
  590. $event->trigger();
  591. }
  592. return true;
  593. }
  594. }
  595. /**
  596. * Deletes an event and if selected an repeated events in the same series
  597. *
  598. * This function deletes an event, any associated events if $deleterepeated=true,
  599. * and cleans up any files associated with the events.
  600. *
  601. * @see self::delete()
  602. *
  603. * @param bool $deleterepeated delete event repeatedly
  604. * @return bool succession of deleting event
  605. */
  606. public function delete($deleterepeated = false) {
  607. global $DB;
  608. // If $this->properties->id is not set then something is wrong.
  609. if (empty($this->properties->id)) {
  610. debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
  611. return false;
  612. }
  613. $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
  614. // Delete the event.
  615. $DB->delete_records('event', array('id' => $this->properties->id));
  616. // Trigger an event for the delete action.
  617. $eventargs = array(
  618. 'context' => $this->get_context(),
  619. 'objectid' => $this->properties->id,
  620. 'other' => array(
  621. 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
  622. 'timestart' => $this->properties->timestart,
  623. 'name' => $this->properties->name
  624. ));
  625. $event = \core\event\calendar_event_deleted::create($eventargs);
  626. $event->add_record_snapshot('event', $calevent);
  627. $event->trigger();
  628. // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
  629. if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
  630. $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
  631. array($this->properties->id), IGNORE_MULTIPLE);
  632. if (!empty($newparent)) {
  633. $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
  634. array($newparent, $this->properties->id));
  635. // Get all records where the repeatid is the same as the event being removed.
  636. $events = $DB->get_records('event', array('repeatid' => $newparent));
  637. // For each of the returned events trigger an update event.
  638. foreach ($events as $calendarevent) {
  639. // Trigger an event for the update.
  640. $eventargs['objectid'] = $calendarevent->id;
  641. $eventargs['other']['timestart'] = $calendarevent->timestart;
  642. $event = \core\event\calendar_event_updated::create($eventargs);
  643. $event->add_record_snapshot('event', $calendarevent);
  644. $event->trigger();
  645. }
  646. }
  647. }
  648. // If the editor context hasn't already been set then set it now.
  649. if ($this->editorcontext === null) {
  650. $this->editorcontext = $this->get_context();
  651. }
  652. // If the context has been set delete all associated files.
  653. if ($this->editorcontext !== null) {
  654. $fs = get_file_storage();
  655. $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
  656. foreach ($files as $file) {
  657. $file->delete();
  658. }
  659. }
  660. // If we need to delete repeated events then we will fetch them all and delete one by one.
  661. if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
  662. // Get all records where the repeatid is the same as the event being removed.
  663. $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
  664. // For each of the returned events populate an event object and call delete.
  665. // make sure the arg passed is false as we are already deleting all repeats.
  666. foreach ($events as $event) {
  667. $event = new calendar_event($event);
  668. $event->delete(false);
  669. }
  670. }
  671. return true;
  672. }
  673. /**
  674. * Fetch all event properties.
  675. *
  676. * This function returns all of the events properties as an object and optionally
  677. * can prepare an editor for the description field at the same time. This is
  678. * designed to work when the properties are going to be used to set the default
  679. * values of a moodle forms form.
  680. *
  681. * @param bool $prepareeditor If set to true a editor is prepared for use with
  682. * the mforms editor element. (for description)
  683. * @return \stdClass Object containing event properties
  684. */
  685. public function properties($prepareeditor = false) {
  686. global $DB;
  687. // First take a copy of the properties. We don't want to actually change the
  688. // properties or we'd forever be converting back and forwards between an
  689. // editor formatted description and not.
  690. $properties = clone($this->properties);
  691. // Clean the description here.
  692. $properties->description = clean_text($properties->description, $properties->format);
  693. // If set to true we need to prepare the properties for use with an editor
  694. // and prepare the file area.
  695. if ($prepareeditor) {
  696. // We may or may not have a property id. If we do then we need to work
  697. // out the context so we can copy the existing files to the draft area.
  698. if (!empty($properties->id)) {
  699. if ($properties->eventtype === 'site') {
  700. // Site context.
  701. $this->editorcontext = $this->get_context();
  702. } else if ($properties->eventtype === 'user') {
  703. // User context.
  704. $this->editorcontext = $this->get_context();
  705. } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
  706. // First check the course is valid.
  707. $course = $DB->get_record('course', array('id' => $properties->courseid));
  708. if (!$course) {
  709. print_error('invalidcourse');
  710. }
  711. // Course context.
  712. $this->editorcontext = $this->get_context();
  713. // We have a course and are within the course context so we had
  714. // better use the courses max bytes value.
  715. $this->editoroptions['maxbytes'] = $course->maxbytes;
  716. } else if ($properties->eventtype === 'category') {
  717. // First check the course is valid.
  718. \core_course_category::get($properties->categoryid, MUST_EXIST, true);
  719. // Course context.
  720. $this->editorcontext = $this->get_context();
  721. } else {
  722. // If we get here we have a custom event type as used by some
  723. // modules. In this case the event will have been added by
  724. // code and we won't need the editor.
  725. $this->editoroptions['maxbytes'] = 0;
  726. $this->editoroptions['maxfiles'] = 0;
  727. }
  728. if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
  729. $contextid = false;
  730. } else {
  731. // Get the context id that is what we really want.
  732. $contextid = $this->editorcontext->id;
  733. }
  734. } else {
  735. // If we get here then this is a new event in which case we don't need a
  736. // context as there is no existing files to copy to the draft area.
  737. $contextid = null;
  738. }
  739. // If the contextid === false we don't support files so no preparing
  740. // a draft area.
  741. if ($contextid !== false) {
  742. // Just encase it has already been submitted.
  743. $draftiddescription = file_get_submitted_draft_itemid('description');
  744. // Prepare the draft area, this copies existing files to the draft area as well.
  745. $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
  746. 'event_description', $properties->id, $this->editoroptions, $properties->description);
  747. } else {
  748. $draftiddescription = 0;
  749. }
  750. // Structure the description field as the editor requires.
  751. $properties->description = array('text' => $properties->description, 'format' => $properties->format,
  752. 'itemid' => $draftiddescription);
  753. }
  754. // Finally return the properties.
  755. return $properties;
  756. }
  757. /**
  758. * Toggles the visibility of an event
  759. *
  760. * @param null|bool $force If it is left null the events visibility is flipped,
  761. * If it is false the event is made hidden, if it is true it
  762. * is made visible.
  763. * @return bool if event is successfully updated, toggle will be visible
  764. */
  765. public function toggle_visibility($force = null) {
  766. global $DB;
  767. // Set visible to the default if it is not already set.
  768. if (empty($this->properties->visible)) {
  769. $this->properties->visible = 1;
  770. }
  771. if ($force === true || ($force !== false && $this->properties->visible == 0)) {
  772. // Make this event visible.
  773. $this->properties->visible = 1;
  774. } else {
  775. // Make this event hidden.
  776. $this->properties->visible = 0;
  777. }
  778. // Update the database to reflect this change.
  779. $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
  780. $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
  781. // Prepare event data.
  782. $eventargs = array(
  783. 'context' => $this->get_context(),
  784. 'objectid' => $this->properties->id,
  785. 'other' => array(
  786. 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
  787. 'timestart' => $this->properties->timestart,
  788. 'name' => $this->properties->name
  789. )
  790. );
  791. $event = \core\event\calendar_event_updated::create($eventargs);
  792. $event->add_record_snapshot('event', $calendarevent);
  793. $event->trigger();
  794. return $success;
  795. }
  796. /**
  797. * Returns an event object when provided with an event id.
  798. *
  799. * This function makes use of MUST_EXIST, if the event id passed in is invalid
  800. * it will result in an exception being thrown.
  801. *
  802. * @param int|object $param event object or event id
  803. * @return calendar_event
  804. */
  805. public static function load($param) {
  806. global $DB;
  807. if (is_object($param)) {
  808. $event = new calendar_event($param);
  809. } else {
  810. $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
  811. $event = new calendar_event($event);
  812. }
  813. return $event;
  814. }
  815. /**
  816. * Creates a new event and returns an event object.
  817. *
  818. * Capability checking should be performed if the user is directly creating the event
  819. * and no other capability has been tested. However if the event is not being created
  820. * directly by the user and another capability has been checked for them to do this then
  821. * capabilites should not be checked.
  822. *
  823. * For example if a user is creating an event in the calendar the check should be true,
  824. * but if you are creating an event in an activity when it is created then the calendar
  825. * capabilites should not be checked.
  826. *
  827. * @param \stdClass|array $properties An object containing event properties
  828. * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
  829. * @throws \coding_exception
  830. *
  831. * @return calendar_event|bool The event object or false if it failed
  832. */
  833. public static function create($properties, $checkcapability = true) {
  834. if (is_array($properties)) {
  835. $properties = (object)$properties;
  836. }
  837. if (!is_object($properties)) {
  838. throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
  839. }
  840. $event = new calendar_event($properties);
  841. if ($event->update($properties, $checkcapability)) {
  842. return $event;
  843. } else {
  844. return false;
  845. }
  846. }
  847. /**
  848. * Format the event name using the external API.
  849. *
  850. * This function should we used when text formatting is required in external functions.
  851. *
  852. * @return string Formatted name.
  853. */
  854. public function format_external_name() {
  855. if ($this->editorcontext === null) {
  856. // Switch on the event type to decide upon the appropriate context to use for this event.
  857. $this->editorcontext = $this->get_context();
  858. }
  859. return external_format_string($this->properties->name, $this->editorcontext->id);
  860. }
  861. /**
  862. * Format the text using the external API.
  863. *
  864. * This function should we used when text formatting is required in external functions.
  865. *
  866. * @return array an array containing the text formatted and the text format
  867. */
  868. public function format_external_text() {
  869. if ($this->editorcontext === null) {
  870. // Switch on the event type to decide upon the appropriate context to use for this event.
  871. $this->editorcontext = $this->get_context();
  872. if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
  873. // We don't have a context here, do a normal format_text.
  874. return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
  875. }
  876. }
  877. // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
  878. if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
  879. $itemid = $this->properties->repeatid;
  880. } else {
  881. $itemid = $this->properties->id;
  882. }
  883. return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
  884. 'calendar', 'event_description', $itemid);
  885. }
  886. }
  887. /**
  888. * Calendar information class
  889. *
  890. * This class is used simply to organise the information pertaining to a calendar
  891. * and is used primarily to make information easily available.
  892. *
  893. * @package core_calendar
  894. * @category calendar
  895. * @copyright 2010 Sam Hemelryk
  896. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  897. */
  898. class calendar_information {
  899. /**
  900. * @var int The timestamp
  901. *
  902. * Rather than setting the day, month and year we will set a timestamp which will be able
  903. * to be used by multiple calendars.
  904. */
  905. public $time;
  906. /** @var int A course id */
  907. public $courseid = null;
  908. /** @var array An array of categories */
  909. public $categories = array();
  910. /** @var int The current category */
  911. public $categoryid = null;
  912. /** @var array An array of courses */
  913. public $courses = array();
  914. /** @var array An array of groups */
  915. public $groups = array();
  916. /** @var array An array of users */
  917. public $users = array();
  918. /** @var context The anticipated context that the calendar is viewed in */
  919. public $context = null;
  920. /** @var string The calendar's view mode. */
  921. protected $viewmode;
  922. /**
  923. * Creates a new instance
  924. *
  925. * @param int $day the number of the day
  926. * @param int $month the number of the month
  927. * @param int $year the number of the year
  928. * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
  929. * and $calyear to support multiple calendars
  930. */
  931. public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
  932. // If a day, month and year were passed then convert it to a timestamp. If these were passed
  933. // then we can assume the day, month and year are passed as Gregorian, as no where in core
  934. // should we be passing these values rather than the time. This is done for BC.
  935. if (!empty($day) || !empty($month) || !empty($year)) {
  936. $date = usergetdate(time());
  937. if (empty($day)) {
  938. $day = $date['mday'];
  939. }
  940. if (empty($month)) {
  941. $month = $date['mon'];
  942. }
  943. if (empty($year)) {
  944. $year = $date['year'];
  945. }
  946. if (checkdate($month, $day, $year)) {
  947. $time = make_timestamp($year, $month, $day);
  948. } else {
  949. $time = time();
  950. }
  951. }
  952. $this->set_time($time);
  953. }
  954. /**
  955. * Creates and set up a instance.
  956. *
  957. * @param int $time the unixtimestamp representing the date we want to view.
  958. * @param int $courseid The ID of the course the user wishes to view.
  959. * @param int $categoryid The ID of the category the user wishes to view
  960. * If a courseid is specified, this value is ignored.
  961. * @return calendar_information
  962. */
  963. public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
  964. $calendar = new static(0, 0, 0, $time);
  965. if ($courseid != SITEID && !empty($courseid)) {
  966. // Course ID must be valid and existing.
  967. $course = get_course($courseid);
  968. $calendar->context = context_course::instance($course->id);
  969. if (!$course->visible && !is_role_switched($course->id)) {
  970. require_capability('moodle/course:viewhiddencourses', $calendar->context);
  971. }
  972. $courses = [$course->id => $course];
  973. $category = (\core_course_category::get($course->category, MUST_EXIST, true))->get_db_record();
  974. } else if (!empty($categoryid)) {
  975. $course = get_site();
  976. $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
  977. // Filter available courses to those within this category or it's children.
  978. $ids = [$categoryid];
  979. $category = \core_course_category::get($categoryid);
  980. $ids = array_merge($ids, array_keys($category->get_children()));
  981. $courses = array_filter($courses, function($course) use ($ids) {
  982. return array_search($course->category, $ids) !== false;
  983. });
  984. $category = $category->get_db_record();
  985. $calendar->context = context_coursecat::instance($categoryid);
  986. } else {
  987. $course = get_site();
  988. $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
  989. $category = null;
  990. $calendar->context = context_system::instance();
  991. }
  992. $calendar->set_sources($course, $courses, $category);
  993. return $calendar;
  994. }
  995. /**
  996. * Set the time period of this instance.
  997. *
  998. * @param int $time the unixtimestamp representing the date we want to view.
  999. * @return $this
  1000. */
  1001. public function set_time($time = null) {
  1002. if (empty($time)) {
  1003. $this->time = time();
  1004. } else {
  1005. $this->time = $time;
  1006. }
  1007. return $this;
  1008. }
  1009. /**
  1010. * Initialize calendar information
  1011. *
  1012. * @deprecated 3.4
  1013. * @param stdClass $course object
  1014. * @param array $coursestoload An array of courses [$course->id => $course]
  1015. * @param bool $ignorefilters options to use filter
  1016. */
  1017. public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
  1018. debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
  1019. DEBUG_DEVELOPER);
  1020. $this->set_sources($course, $coursestoload);
  1021. }
  1022. /**
  1023. * Set the sources for events within the calendar.
  1024. *
  1025. * If no category is provided, then the category path for the current
  1026. * course will be used.
  1027. *
  1028. * @param stdClass $course The current course being viewed.
  1029. * @param stdClass[] $courses The list of all courses currently accessible.
  1030. * @param stdClass $category The current category to show.
  1031. */
  1032. public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
  1033. global $USER;
  1034. // A cousre must always be specified.
  1035. $this->course = $course;
  1036. $this->courseid = $course->id;
  1037. list($courseids, $group, $user) = calendar_set_filters($courses);
  1038. $this->courses = $courseids;
  1039. $this->groups = $group;
  1040. $this->users = $user;
  1041. // Do not show category events by default.
  1042. $this->categoryid = null;
  1043. $this->categories = null;
  1044. // Determine the correct category information to show.
  1045. // When called with a course, the category of that course is usually included too.
  1046. // When a category was specifically requested, it should be requested with the site id.
  1047. if (SITEID !== $this->courseid) {
  1048. // A specific course was requested.
  1049. // Fetch the category that this course is in, along with all parents.
  1050. // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
  1051. $category = \core_course_category::get($course->category, MUST_EXIST, true);
  1052. $this->categoryid = $category->id;
  1053. $this->categories = $category->get_parents();
  1054. $this->categories[] = $category->id;
  1055. } else if (null !== $category && $category->id > 0) {
  1056. // A specific category was requested.
  1057. // Fetch all parents of this category, along with all children too.
  1058. $category = \core_course_category::get($category->id);
  1059. $this->categoryid = $category->id;
  1060. // Build the category list.
  1061. // This includes the current category.
  1062. $this->categories = $category->get_parents();
  1063. $this->categories[] = $category->id;
  1064. $this->categories = array_merge($this->categories, $category->get_all_children_ids());
  1065. } else if (SITEID === $this->courseid) {
  1066. // The site was requested.
  1067. // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
  1068. // Grab the list of categories that this user has courses in.
  1069. $coursecategories = array_flip(array_map(function($course) {
  1070. return $course->category;
  1071. }, $courses));
  1072. $calcatcache = cache::make('core', 'calendar_categories');
  1073. $this->categories = $calcatcache->get('site');
  1074. if ($this->categories === false) {
  1075. // Use the category id as the key in the following array. That way we do not have to remove duplicates.
  1076. $categories = [];
  1077. foreach (\core_course_category::get_all() as $category) {
  1078. if (isset($coursecategories[$category->id]) ||

Large files files are truncated, but you can click here to view the full file