PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 2ms

/calendar/lib.php

http://github.com/moodle/moodle
PHP | 3885 lines | 2371 code | 447 blank | 1067 comment | 673 complexity | 671e32887ce9663ec86541bb86c15376 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause

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

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