xref: /plugin/davcal/helper.php (revision a469597c69be3adc7e5b3a5f2dc9d43fd9e7ca0b)
1<?php
2/**
3  * Helper Class for the DAVCal plugin
4  * This helper does the actual work.
5  *
6  */
7
8// must be run within Dokuwiki
9if(!defined('DOKU_INC')) die();
10
11class helper_plugin_davcal extends DokuWiki_Plugin {
12
13  protected $sqlite = null;
14  protected $cachedValues = array();
15
16  /**
17    * Constructor to load the configuration and the SQLite plugin
18    */
19  public function helper_plugin_davcal() {
20    $this->sqlite =& plugin_load('helper', 'sqlite');
21    global $conf;
22    if($conf['allowdebug'])
23        dbglog('---- DAVCAL helper.php init');
24    if(!$this->sqlite)
25    {
26        if($conf['allowdebug'])
27            dbglog('This plugin requires the sqlite plugin. Please install it.');
28        msg('This plugin requires the sqlite plugin. Please install it.');
29        return;
30    }
31
32    if(!$this->sqlite->init('davcal', DOKU_PLUGIN.'davcal/db/'))
33    {
34        if($conf['allowdebug'])
35            dbglog('Error initialising the SQLite DB for DAVCal');
36        return;
37    }
38  }
39
40  /**
41   * Retrieve meta data for a given page
42   *
43   * @param string $id optional The page ID
44   * @return array The metadata
45   */
46  private function getMeta($id = null) {
47    global $ID;
48    global $INFO;
49
50    if ($id === null) $id = $ID;
51
52    if($ID === $id && $INFO['meta']) {
53        $meta = $INFO['meta'];
54    } else {
55        $meta = p_get_metadata($id);
56    }
57
58    return $meta;
59  }
60
61  /**
62   * Retrieve the meta data for a given page
63   *
64   * @param string $id optional The page ID
65   * @return array with meta data
66   */
67  public function getCalendarMetaForPage($id = null)
68  {
69      if(is_null($id))
70      {
71          global $ID;
72          $id = $ID;
73      }
74
75      $meta = $this->getMeta($id);
76      if(isset($meta['plugin_davcal']))
77        return $meta['plugin_davcal'];
78      else
79        return array();
80  }
81
82  /**
83   * Get all calendar pages used by a given page
84   * based on the stored metadata
85   *
86   * @param string $id optional The page id
87   * @return mixed The pages as array or false
88   */
89  public function getCalendarPagesByMeta($id = null)
90  {
91      if(is_null($id))
92      {
93          global $ID;
94          $id = $ID;
95      }
96
97      $meta = $this->getCalendarMetaForPage($id);
98      if(isset($meta['id']))
99          return array_keys($meta['id']);
100      return false;
101  }
102
103  /**
104   * Get a list of calendar names/pages/ids/colors
105   * for an array of page ids
106   *
107   * @param array $calendarPages The calendar pages to retrieve
108   * @return array The list
109   */
110  public function getCalendarMapForIDs($calendarPages)
111  {
112      $data = array();
113      foreach($calendarPages as $page)
114      {
115          $calid = $this->getCalendarIdForPage($page);
116          if($calid !== false)
117          {
118            $settings = $this->getCalendarSettings($calid);
119            $name = $settings['displayname'];
120            $color = $settings['calendarcolor'];
121            $data[] = array('name' => $name, 'page' => $page, 'calid' => $calid,
122                            'color' => $color);
123          }
124      }
125      return $data;
126  }
127
128  /**
129   * Get the saved calendar color for a given page.
130   *
131   * @param string $id optional The page ID
132   * @return mixed The color on success, otherwise false
133   */
134  public function getCalendarColorForPage($id = null)
135  {
136      if(is_null($id))
137      {
138          global $ID;
139          $id = $ID;
140      }
141
142      $calid = $this->getCalendarIdForPage($id);
143      if($calid === false)
144        return false;
145
146      return $this->getCalendarColorForCalendar($calid);
147  }
148
149  /**
150   * Get the saved calendar color for a given calendar ID.
151   *
152   * @param string $id optional The calendar ID
153   * @return mixed The color on success, otherwise false
154   */
155  public function getCalendarColorForCalendar($calid)
156  {
157      if(isset($this->cachedValues['calendarcolor'][$calid]))
158        return $this->cachedValues['calendarcolor'][$calid];
159
160      $row = $this->getCalendarSettings($calid);
161
162      if(!isset($row['calendarcolor']))
163        return false;
164
165      $color = $row['calendarcolor'];
166      $this->cachedValues['calendarcolor'][$calid] = $color;
167      return $color;
168  }
169
170  /**
171   * Get the user's principal URL for iOS sync
172   * @param string $user the user name
173   * @return the URL to the principal sync
174   */
175  public function getPrincipalUrlForUser($user)
176  {
177      if(is_null($user))
178        return false;
179      $url = DOKU_URL.'lib/plugins/davcal/calendarserver.php/principals/'.$user;
180      return $url;
181  }
182
183  /**
184   * Set the calendar color for a given page.
185   *
186   * @param string $color The color definition
187   * @param string $id optional The page ID
188   * @return boolean True on success, otherwise false
189   */
190  public function setCalendarColorForPage($color, $id = null)
191  {
192      if(is_null($id))
193      {
194          global $ID;
195          $id = $ID;
196      }
197      $calid = $this->getCalendarIdForPage($id);
198      if($calid === false)
199        return false;
200
201      $query = "UPDATE calendars SET calendarcolor = ? ".
202               " WHERE id = ?";
203      $res = $this->sqlite->query($query, $color, $calid);
204      if($res !== false)
205      {
206        $this->cachedValues['calendarcolor'][$calid] = $color;
207        return true;
208      }
209      return false;
210  }
211
212  /**
213   * Set the calendar name and description for a given page with a given
214   * page id.
215   * If the calendar doesn't exist, the calendar is created!
216   *
217   * @param string  $name The name of the new calendar
218   * @param string  $description The description of the new calendar
219   * @param string  $id (optional) The ID of the page
220   * @param string  $userid The userid of the creating user
221   *
222   * @return boolean True on success, otherwise false.
223   */
224  public function setCalendarNameForPage($name, $description, $id = null, $userid = null)
225  {
226      if(is_null($id))
227      {
228          global $ID;
229          $id = $ID;
230      }
231      if(is_null($userid))
232      {
233        if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
234        {
235          $userid = $_SERVER['REMOTE_USER'];
236        }
237        else
238        {
239          $userid = uniqid('davcal-');
240        }
241      }
242      $calid = $this->getCalendarIdForPage($id);
243      if($calid === false)
244        return $this->createCalendarForPage($name, $description, $id, $userid);
245
246      $query = "UPDATE calendars SET displayname = ?, description = ? WHERE id = ?";
247      $res = $this->sqlite->query($query, $name, $description, $calid);
248      if($res !== false)
249        return true;
250      return false;
251  }
252
253  /**
254   * Save the personal settings to the SQLite database 'calendarsettings'.
255   *
256   * @param array  $settings The settings array to store
257   * @param string $userid (optional) The userid to store
258   *
259   * @param boolean True on success, otherwise false
260   */
261  public function savePersonalSettings($settings, $userid = null)
262  {
263      if(is_null($userid))
264      {
265          if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
266          {
267            $userid = $_SERVER['REMOTE_USER'];
268          }
269          else
270          {
271              return false;
272          }
273      }
274      $this->sqlite->query("BEGIN TRANSACTION");
275
276      $query = "DELETE FROM calendarsettings WHERE userid = ?";
277      $this->sqlite->query($query, $userid);
278
279      foreach($settings as $key => $value)
280      {
281          $query = "INSERT INTO calendarsettings (userid, key, value) VALUES (?, ?, ?)";
282          $res = $this->sqlite->query($query, $userid, $key, $value);
283          if($res === false)
284              return false;
285      }
286      $this->sqlite->query("COMMIT TRANSACTION");
287      $this->cachedValues['settings'][$userid] = $settings;
288      return true;
289  }
290
291  /**
292   * Retrieve the settings array for a given user id.
293   * Some sane defaults are returned, currently:
294   *
295   *    timezone    => local
296   *    weeknumbers => 0
297   *    workweek    => 0
298   *
299   * @param string $userid (optional) The user id to retrieve
300   *
301   * @return array The settings array
302   */
303  public function getPersonalSettings($userid = null)
304  {
305      // Some sane default settings
306      $settings = array(
307        'timezone' => $this->getConf('timezone'),
308        'weeknumbers' => $this->getConf('weeknumbers'),
309        'workweek' => $this->getConf('workweek'),
310        'monday' => $this->getConf('monday'),
311        'timeformat' => $this->getConf('timeformat')
312      );
313      if(is_null($userid))
314      {
315          if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
316          {
317            $userid = $_SERVER['REMOTE_USER'];
318          }
319          else
320          {
321            return $settings;
322          }
323      }
324
325      if(isset($this->cachedValues['settings'][$userid]))
326        return $this->cachedValues['settings'][$userid];
327      $query = "SELECT key, value FROM calendarsettings WHERE userid = ?";
328      $res = $this->sqlite->query($query, $userid);
329      $arr = $this->sqlite->res2arr($res);
330      foreach($arr as $row)
331      {
332          $settings[$row['key']] = $row['value'];
333      }
334      $this->cachedValues['settings'][$userid] = $settings;
335      return $settings;
336  }
337
338  /**
339   * Retrieve the calendar ID based on a page ID from the SQLite table
340   * 'pagetocalendarmapping'.
341   *
342   * @param string $id (optional) The page ID to retrieve the corresponding calendar
343   *
344   * @return mixed the ID on success, otherwise false
345   */
346  public function getCalendarIdForPage($id = null)
347  {
348      if(is_null($id))
349      {
350          global $ID;
351          $id = $ID;
352      }
353
354      if(isset($this->cachedValues['calid'][$id]))
355        return $this->cachedValues['calid'][$id];
356
357      $query = "SELECT calid FROM pagetocalendarmapping WHERE page = ?";
358      $res = $this->sqlite->query($query, $id);
359      $row = $this->sqlite->res2row($res);
360      if(isset($row['calid']))
361      {
362        $calid = $row['calid'];
363        $this->cachedValues['calid'] = $calid;
364        return $calid;
365      }
366      return false;
367  }
368
369  /**
370   * Retrieve the complete calendar id to page mapping.
371   * This is necessary to be able to retrieve a list of
372   * calendars for a given user and check the access rights.
373   *
374   * @return array The mapping array
375   */
376  public function getCalendarIdToPageMapping()
377  {
378      $query = "SELECT calid, page FROM pagetocalendarmapping";
379      $res = $this->sqlite->query($query);
380      $arr = $this->sqlite->res2arr($res);
381      return $arr;
382  }
383
384  /**
385   * Retrieve all calendar IDs a given user has access to.
386   * The user is specified by the principalUri, so the
387   * user name is actually split from the URI component.
388   *
389   * Access rights are checked against DokuWiki's ACL
390   * and applied accordingly.
391   *
392   * @param string $principalUri The principal URI to work on
393   *
394   * @return array An associative array of calendar IDs
395   */
396  public function getCalendarIdsForUser($principalUri)
397  {
398      global $auth;
399      $user = explode('/', $principalUri);
400      $user = end($user);
401      $mapping = $this->getCalendarIdToPageMapping();
402      $calids = array();
403      $ud = $auth->getUserData($user);
404      $groups = $ud['grps'];
405      foreach($mapping as $row)
406      {
407          $id = $row['calid'];
408          $page = $row['page'];
409          $acl = auth_aclcheck($page, $user, $groups);
410          if($acl >= AUTH_READ)
411          {
412              $write = $acl > AUTH_READ;
413              $calids[$id] = array('readonly' => !$write);
414          }
415      }
416      return $calids;
417  }
418
419  /**
420   * Create a new calendar for a given page ID and set name and description
421   * accordingly. Also update the pagetocalendarmapping table on success.
422   *
423   * @param string $name The calendar's name
424   * @param string $description The calendar's description
425   * @param string $id (optional) The page ID to work on
426   * @param string $userid (optional) The user ID that created the calendar
427   *
428   * @return boolean True on success, otherwise false
429   */
430  public function createCalendarForPage($name, $description, $id = null, $userid = null)
431  {
432      if(is_null($id))
433      {
434          global $ID;
435          $id = $ID;
436      }
437      if(is_null($userid))
438      {
439        if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
440        {
441          $userid = $_SERVER['REMOTE_USER'];
442        }
443        else
444        {
445          $userid = uniqid('davcal-');
446        }
447      }
448      $values = array('principals/'.$userid,
449                      $name,
450                      str_replace(array('/', ' ', ':'), '_', $id),
451                      $description,
452                      'VEVENT,VTODO',
453                      0,
454                      1);
455      $query = "INSERT INTO calendars (principaluri, displayname, uri, description, components, transparent, synctoken) ".
456               "VALUES (?, ?, ?, ?, ?, ?, ?)";
457      $res = $this->sqlite->query($query, $values[0], $values[1], $values[2], $values[3], $values[4], $values[5], $values[6]);
458      if($res === false)
459        return false;
460
461      // Get the new calendar ID
462      $query = "SELECT id FROM calendars WHERE principaluri = ? AND displayname = ? AND ".
463               "uri = ? AND description = ?";
464      $res = $this->sqlite->query($query, $values[0], $values[1], $values[2], $values[3]);
465      $row = $this->sqlite->res2row($res);
466
467      // Update the pagetocalendarmapping table with the new calendar ID
468      if(isset($row['id']))
469      {
470          $query = "INSERT INTO pagetocalendarmapping (page, calid) VALUES (?, ?)";
471          $res = $this->sqlite->query($query, $id, $row['id']);
472          return ($res !== false);
473      }
474
475      return false;
476  }
477
478  /**
479   * Add a new iCal entry for a given page, i.e. a given calendar.
480   *
481   * The parameter array needs to contain
482   *   detectedtz       => The timezone as detected by the browser
483   *   currenttz        => The timezone in use by the calendar
484   *   eventfrom        => The event's start date
485   *   eventfromtime    => The event's start time
486   *   eventto          => The event's end date
487   *   eventtotime      => The event's end time
488   *   eventname        => The event's name
489   *   eventdescription => The event's description
490   *
491   * @param string $id The page ID to work on
492   * @param string $user The user who created the calendar
493   * @param string $params A parameter array with values to create
494   *
495   * @return boolean True on success, otherwise false
496   */
497  public function addCalendarEntryToCalendarForPage($id, $user, $params)
498  {
499      if($params['currenttz'] !== '' && $params['currenttz'] !== 'local')
500          $timezone = new \DateTimeZone($params['currenttz']);
501      elseif($params['currenttz'] === 'local')
502          $timezone = new \DateTimeZone($params['detectedtz']);
503      else
504          $timezone = new \DateTimeZone('UTC');
505
506      // Retrieve dates from settings
507      $startDate = explode('-', $params['eventfrom']);
508      $startTime = explode(':', $params['eventfromtime']);
509      $endDate = explode('-', $params['eventto']);
510      $endTime = explode(':', $params['eventtotime']);
511
512      // Load SabreDAV
513      require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
514      $vcalendar = new \Sabre\VObject\Component\VCalendar();
515
516      // Add VCalendar, UID and Event Name
517      $event = $vcalendar->add('VEVENT');
518      $uuid = \Sabre\VObject\UUIDUtil::getUUID();
519      $event->add('UID', $uuid);
520      $event->summary = $params['eventname'];
521
522      // Add a description if requested
523      $description = $params['eventdescription'];
524      if($description !== '')
525        $event->add('DESCRIPTION', $description);
526
527      // Add attachments
528      $attachments = $params['attachments'];
529      if(!is_null($attachments))
530        foreach($attachments as $attachment)
531          $event->add('ATTACH', $attachment);
532
533      // Create a timestamp for last modified, created and dtstamp values in UTC
534      $dtStamp = new \DateTime(null, new \DateTimeZone('UTC'));
535      $event->add('DTSTAMP', $dtStamp);
536      $event->add('CREATED', $dtStamp);
537      $event->add('LAST-MODIFIED', $dtStamp);
538
539      // Adjust the start date, based on the given timezone information
540      $dtStart = new \DateTime();
541      $dtStart->setTimezone($timezone);
542      $dtStart->setDate(intval($startDate[0]), intval($startDate[1]), intval($startDate[2]));
543
544      // Only add the time values if it's not an allday event
545      if($params['allday'] != '1')
546        $dtStart->setTime(intval($startTime[0]), intval($startTime[1]), 0);
547
548      // Adjust the end date, based on the given timezone information
549      $dtEnd = new \DateTime();
550      $dtEnd->setTimezone($timezone);
551      $dtEnd->setDate(intval($endDate[0]), intval($endDate[1]), intval($endDate[2]));
552
553      // Only add the time values if it's not an allday event
554      if($params['allday'] != '1')
555        $dtEnd->setTime(intval($endTime[0]), intval($endTime[1]), 0);
556
557      // According to the VCal spec, we need to add a whole day here
558      if($params['allday'] == '1')
559          $dtEnd->add(new \DateInterval('P1D'));
560
561      // Really add Start and End events
562      $dtStartEv = $event->add('DTSTART', $dtStart);
563      $dtEndEv = $event->add('DTEND', $dtEnd);
564
565      // Adjust the DATE format for allday events
566      if($params['allday'] == '1')
567      {
568          $dtStartEv['VALUE'] = 'DATE';
569          $dtEndEv['VALUE'] = 'DATE';
570      }
571
572      // Actually add the values to the database
573      $calid = $this->getCalendarIdForPage($id);
574      $uri = uniqid('dokuwiki-').'.ics';
575      $now = new DateTime();
576      $eventStr = $vcalendar->serialize();
577
578      $query = "INSERT INTO calendarobjects (calendarid, uri, calendardata, lastmodified, componenttype, firstoccurence, lastoccurence, size, etag, uid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
579      $res = $this->sqlite->query($query, $calid, $uri, $eventStr, $now->getTimestamp(), 'VEVENT',
580                                  $event->DTSTART->getDateTime()->getTimeStamp(), $event->DTEND->getDateTime()->getTimeStamp(),
581                                  strlen($eventStr), md5($eventStr), $uuid);
582
583      // If successfully, update the sync token database
584      if($res !== false)
585      {
586          $this->updateSyncTokenLog($calid, $uri, 'added');
587          return true;
588      }
589      return false;
590  }
591
592  /**
593   * Retrieve the calendar settings of a given calendar id
594   *
595   * @param string $calid The calendar ID
596   *
597   * @return array The calendar settings array
598   */
599  public function getCalendarSettings($calid)
600  {
601      $query = "SELECT principaluri, calendarcolor, displayname, uri, description, components, transparent, synctoken FROM calendars WHERE id= ? ";
602      $res = $this->sqlite->query($query, $calid);
603      $row = $this->sqlite->res2row($res);
604      return $row;
605  }
606
607  /**
608   * Retrieve all events that are within a given date range,
609   * based on the timezone setting.
610   *
611   * There is also support for retrieving recurring events,
612   * using Sabre's VObject Iterator. Recurring events are represented
613   * as individual calendar entries with the same UID.
614   *
615   * @param string $id The page ID to work with
616   * @param string $user The user ID to work with
617   * @param string $startDate The start date as a string
618   * @param string $endDate The end date as a string
619   *
620   * @return array An array containing the calendar entries.
621   */
622  public function getEventsWithinDateRange($id, $user, $startDate, $endDate, $timezone)
623  {
624      if($timezone !== '' && $timezone !== 'local')
625          $timezone = new \DateTimeZone($timezone);
626      else
627          $timezone = new \DateTimeZone('UTC');
628      $data = array();
629
630      // Load SabreDAV
631      require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
632      $calid = $this->getCalendarIdForPage($id);
633      $color = $this->getCalendarColorForCalendar($calid);
634      $query = "SELECT calendardata, componenttype, uid FROM calendarobjects WHERE calendarid = ?";
635      $startTs = null;
636      $endTs = null;
637      if($startDate !== null)
638      {
639        $startTs = new \DateTime($startDate);
640        $query .= " AND lastoccurence > ".$this->sqlite->quote_string($startTs->getTimestamp());
641      }
642      if($endDate !== null)
643      {
644        $endTs = new \DateTime($endDate);
645        $query .= " AND firstoccurence < ".$this->sqlite->quote_string($endTs->getTimestamp());
646      }
647
648      // Retrieve matching calendar objects
649      $res = $this->sqlite->query($query, $calid);
650      $arr = $this->sqlite->res2arr($res);
651
652      // Parse individual calendar entries
653      foreach($arr as $row)
654      {
655          if(isset($row['calendardata']))
656          {
657              $entry = array();
658              $vcal = \Sabre\VObject\Reader::read($row['calendardata']);
659              $recurrence = $vcal->VEVENT->RRULE;
660              // If it is a recurring event, pass it through Sabre's EventIterator
661              if($recurrence != null)
662              {
663                  $rEvents = new \Sabre\VObject\Recur\EventIterator(array($vcal->VEVENT));
664                  $rEvents->rewind();
665                  $done = false;
666                  while($rEvents->valid() && !$done)
667                  {
668                      $event = $rEvents->getEventObject();
669                      // If we are after the given time range, exit
670                      if(($endTs !== null) && ($rEvents->getDtStart()->getTimestamp() > $endTs->getTimestamp()))
671                      {
672                        $done = true;
673                        continue;
674                      }
675
676                      // If we are before the given time range, continue
677                      if(($startTs != null) && ($rEvents->getDtEnd()->getTimestamp() < $startTs->getTimestamp()))
678                      {
679                          $rEvents->next();
680                          continue;
681                      }
682
683                      // If we are within the given time range, parse the event
684                      $data[] = $this->convertIcalDataToEntry($event, $id, $timezone, $row['uid'], $color, true);
685                      $rEvents->next();
686                  }
687              }
688              else
689                $data[] = $this->convertIcalDataToEntry($vcal->VEVENT, $id, $timezone, $row['uid'], $color);
690          }
691      }
692      return $data;
693  }
694
695  /**
696   * Helper function that parses the iCal data of a VEVENT to a calendar entry.
697   *
698   * @param \Sabre\VObject\VEvent $event The event to parse
699   * @param \DateTimeZone $timezone The timezone object
700   * @param string $uid The entry's UID
701   * @param boolean $recurring (optional) Set to true to define a recurring event
702   *
703   * @return array The parse calendar entry
704   */
705  private function convertIcalDataToEntry($event, $page, $timezone, $uid, $color, $recurring = false)
706  {
707      $entry = array();
708      $start = $event->DTSTART;
709      // Parse only if the start date/time is present
710      if($start !== null)
711      {
712        $dtStart = $start->getDateTime();
713        $dtStart->setTimezone($timezone);
714
715        // moment.js doesn't like times be given even if
716        // allDay is set to true
717        // This should fix T23
718        if($start['VALUE'] == 'DATE')
719        {
720          $entry['allDay'] = true;
721          $entry['start'] = $dtStart->format("Y-m-d");
722        }
723        else
724        {
725          $entry['allDay'] = false;
726          $entry['start'] = $dtStart->format(\DateTime::ATOM);
727        }
728      }
729      $end = $event->DTEND;
730      // Parse only if the end date/time is present
731      if($end !== null)
732      {
733        $dtEnd = $end->getDateTime();
734        $dtEnd->setTimezone($timezone);
735        if($end['VALUE'] == 'DATE')
736          $entry['end'] = $dtEnd->format("Y-m-d");
737        else
738          $entry['end'] = $dtEnd->format(\DateTime::ATOM);
739      }
740      $description = $event->DESCRIPTION;
741      if($description !== null)
742        $entry['description'] = (string)$description;
743      else
744        $entry['description'] = '';
745      $attachments = $event->ATTACH;
746      if($attachments !== null)
747      {
748        $entry['attachments'] = array();
749        foreach($attachments as $attachment)
750          $entry['attachments'][] = (string)$attachment;
751      }
752      $entry['title'] = (string)$event->summary;
753      $entry['id'] = $uid;
754      $entry['page'] = $page;
755      $entry['color'] = $color;
756      $entry['recurring'] = $recurring;
757
758      return $entry;
759  }
760
761  /**
762   * Retrieve an event by its UID
763   *
764   * @param string $uid The event's UID
765   *
766   * @return mixed The table row with the given event
767   */
768  public function getEventWithUid($uid)
769  {
770      $query = "SELECT calendardata, calendarid, componenttype, uri FROM calendarobjects WHERE uid = ?";
771      $res = $this->sqlite->query($query, $uid);
772      $row = $this->sqlite->res2row($res);
773      return $row;
774  }
775
776  /**
777   * Retrieve all calendar events for a given calendar ID
778   *
779   * @param string $calid The calendar's ID
780   *
781   * @return array An array containing all calendar data
782   */
783  public function getAllCalendarEvents($calid)
784  {
785      $query = "SELECT calendardata, uid, componenttype, uri FROM calendarobjects WHERE calendarid = ?".
786      $res = $this->sqlite->query($query, $calid);
787      $arr = $this->sqlite->res2arr($res);
788      return $arr;
789  }
790
791  /**
792   * Edit a calendar entry for a page, given by its parameters.
793   * The params array has the same format as @see addCalendarEntryForPage
794   *
795   * @param string $id The page's ID to work on
796   * @param string $user The user's ID to work on
797   * @param array $params The parameter array for the edited calendar event
798   *
799   * @return boolean True on success, otherwise false
800   */
801  public function editCalendarEntryForPage($id, $user, $params)
802  {
803      if($params['currenttz'] !== '' && $params['currenttz'] !== 'local')
804          $timezone = new \DateTimeZone($params['currenttz']);
805      elseif($params['currenttz'] === 'local')
806          $timezone = new \DateTimeZone($params['detectedtz']);
807      else
808          $timezone = new \DateTimeZone('UTC');
809
810      // Parse dates
811      $startDate = explode('-', $params['eventfrom']);
812      $startTime = explode(':', $params['eventfromtime']);
813      $endDate = explode('-', $params['eventto']);
814      $endTime = explode(':', $params['eventtotime']);
815
816      // Retrieve the existing event based on the UID
817      $uid = $params['uid'];
818      $event = $this->getEventWithUid($uid);
819
820      // Load SabreDAV
821      require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
822      if(!isset($event['calendardata']))
823        return false;
824      $uri = $event['uri'];
825      $calid = $event['calendarid'];
826
827      // Parse the existing event
828      $vcal = \Sabre\VObject\Reader::read($event['calendardata']);
829      $vevent = $vcal->VEVENT;
830
831      // Set the new event values
832      $vevent->summary = $params['eventname'];
833      $dtStamp = new \DateTime(null, new \DateTimeZone('UTC'));
834      $description = $params['eventdescription'];
835
836      // Remove existing timestamps to overwrite them
837      $vevent->remove('DESCRIPTION');
838      $vevent->remove('DTSTAMP');
839      $vevent->remove('LAST-MODIFIED');
840      $vevent->remove('ATTACH');
841
842      // Add new time stamps and description
843      $vevent->add('DTSTAMP', $dtStamp);
844      $vevent->add('LAST-MODIFIED', $dtStamp);
845      if($description !== '')
846        $vevent->add('DESCRIPTION', $description);
847
848      // Add attachments
849      $attachments = $params['attachments'];
850      if(!is_null($attachments))
851        foreach($attachments as $attachment)
852          $vevent->add('ATTACH', $attachment);
853
854      // Setup DTSTART
855      $dtStart = new \DateTime();
856      $dtStart->setTimezone($timezone);
857      $dtStart->setDate(intval($startDate[0]), intval($startDate[1]), intval($startDate[2]));
858      if($params['allday'] != '1')
859        $dtStart->setTime(intval($startTime[0]), intval($startTime[1]), 0);
860
861      // Setup DTEND
862      $dtEnd = new \DateTime();
863      $dtEnd->setTimezone($timezone);
864      $dtEnd->setDate(intval($endDate[0]), intval($endDate[1]), intval($endDate[2]));
865      if($params['allday'] != '1')
866        $dtEnd->setTime(intval($endTime[0]), intval($endTime[1]), 0);
867
868      // According to the VCal spec, we need to add a whole day here
869      if($params['allday'] == '1')
870          $dtEnd->add(new \DateInterval('P1D'));
871      $vevent->remove('DTSTART');
872      $vevent->remove('DTEND');
873      $dtStartEv = $vevent->add('DTSTART', $dtStart);
874      $dtEndEv = $vevent->add('DTEND', $dtEnd);
875
876      // Remove the time for allday events
877      if($params['allday'] == '1')
878      {
879          $dtStartEv['VALUE'] = 'DATE';
880          $dtEndEv['VALUE'] = 'DATE';
881      }
882      $now = new DateTime();
883      $eventStr = $vcal->serialize();
884      // Actually write to the database
885      $query = "UPDATE calendarobjects SET calendardata = ?, lastmodified = ?, ".
886               "firstoccurence = ?, lastoccurence = ?, size = ?, etag = ? WHERE uid = ?";
887      $res = $this->sqlite->query($query, $eventStr, $now->getTimestamp(), $dtStart->getTimestamp(),
888                                  $dtEnd->getTimestamp(), strlen($eventStr), md5($eventStr), $uid);
889      if($res !== false)
890      {
891          $this->updateSyncTokenLog($calid, $uri, 'modified');
892          return true;
893      }
894      return false;
895  }
896
897  /**
898   * Delete a calendar entry for a given page. Actually, the event is removed
899   * based on the entry's UID, so that page ID is no used.
900   *
901   * @param string $id The page's ID (unused)
902   * @param array $params The parameter array to work with
903   *
904   * @return boolean True
905   */
906  public function deleteCalendarEntryForPage($id, $params)
907  {
908      $uid = $params['uid'];
909      $event = $this->getEventWithUid($uid);
910      $calid = $event['calendarid'];
911      $uri = $event['uri'];
912      $query = "DELETE FROM calendarobjects WHERE uid = ?";
913      $res = $this->sqlite->query($query, $uid);
914      if($res !== false)
915      {
916          $this->updateSyncTokenLog($calid, $uri, 'deleted');
917      }
918      return true;
919  }
920
921  /**
922   * Retrieve the current sync token for a calendar
923   *
924   * @param string $calid The calendar id
925   *
926   * @return mixed The synctoken or false
927   */
928  public function getSyncTokenForCalendar($calid)
929  {
930      $row = $this->getCalendarSettings($calid);
931      if(isset($row['synctoken']))
932          return $row['synctoken'];
933      return false;
934  }
935
936  /**
937   * Helper function to convert the operation name to
938   * an operation code as stored in the database
939   *
940   * @param string $operationName The operation name
941   *
942   * @return mixed The operation code or false
943   */
944  public function operationNameToOperation($operationName)
945  {
946      switch($operationName)
947      {
948          case 'added':
949              return 1;
950          break;
951          case 'modified':
952              return 2;
953          break;
954          case 'deleted':
955              return 3;
956          break;
957      }
958      return false;
959  }
960
961  /**
962   * Update the sync token log based on the calendar id and the
963   * operation that was performed.
964   *
965   * @param string $calid The calendar ID that was modified
966   * @param string $uri The calendar URI that was modified
967   * @param string $operation The operation that was performed
968   *
969   * @return boolean True on success, otherwise false
970   */
971  private function updateSyncTokenLog($calid, $uri, $operation)
972  {
973      $currentToken = $this->getSyncTokenForCalendar($calid);
974      $operationCode = $this->operationNameToOperation($operation);
975      if(($operationCode === false) || ($currentToken === false))
976          return false;
977      $values = array($uri,
978                      $currentToken,
979                      $calid,
980                      $operationCode
981      );
982      $query = "INSERT INTO calendarchanges (uri, synctoken, calendarid, operation) VALUES(?, ?, ?, ?)";
983      $res = $this->sqlite->query($query, $uri, $currentToken, $calid, $operationCode);
984      if($res === false)
985        return false;
986      $currentToken++;
987      $query = "UPDATE calendars SET synctoken = ? WHERE id = ?";
988      $res = $this->sqlite->query($query, $currentToken, $calid);
989      return ($res !== false);
990  }
991
992  /**
993   * Return the sync URL for a given Page, i.e. a calendar
994   *
995   * @param string $id The page's ID
996   * @param string $user (optional) The user's ID
997   *
998   * @return mixed The sync url or false
999   */
1000  public function getSyncUrlForPage($id, $user = null)
1001  {
1002      if(is_null($userid))
1003      {
1004        if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
1005        {
1006          $userid = $_SERVER['REMOTE_USER'];
1007        }
1008        else
1009        {
1010          return false;
1011        }
1012      }
1013
1014      $calid = $this->getCalendarIdForPage($id);
1015      if($calid === false)
1016        return false;
1017
1018      $calsettings = $this->getCalendarSettings($calid);
1019      if(!isset($calsettings['uri']))
1020        return false;
1021
1022      $syncurl = DOKU_URL.'lib/plugins/davcal/calendarserver.php/calendars/'.$user.'/'.$calsettings['uri'];
1023      return $syncurl;
1024  }
1025
1026  /**
1027   * Return the private calendar's URL for a given page
1028   *
1029   * @param string $id the page ID
1030   *
1031   * @return mixed The private URL or false
1032   */
1033  public function getPrivateURLForPage($id)
1034  {
1035      $calid = $this->getCalendarIdForPage($id);
1036      if($calid === false)
1037        return false;
1038
1039      return $this->getPrivateURLForCalendar($calid);
1040  }
1041
1042  /**
1043   * Return the private calendar's URL for a given calendar ID
1044   *
1045   * @param string $calid The calendar's ID
1046   *
1047   * @return mixed The private URL or false
1048   */
1049  public function getPrivateURLForCalendar($calid)
1050  {
1051      if(isset($this->cachedValues['privateurl'][$calid]))
1052        return $this->cachedValues['privateurl'][$calid];
1053      $query = "SELECT url FROM calendartoprivateurlmapping WHERE calid = ?";
1054      $res = $this->sqlite->query($query, $calid);
1055      $row = $this->sqlite->res2row($res);
1056      if(!isset($row['url']))
1057      {
1058          $url = uniqid("dokuwiki-").".ics";
1059          $query = "INSERT INTO calendartoprivateurlmapping (url, calid) VALUES(?, ?)";
1060          $res = $this->sqlite->query($query, $url, $calid);
1061          if($res === false)
1062            return false;
1063      }
1064      else
1065      {
1066          $url = $row['url'];
1067      }
1068
1069      $url = DOKU_URL.'lib/plugins/davcal/ics.php/'.$url;
1070      $this->cachedValues['privateurl'][$calid] = $url;
1071      return $url;
1072  }
1073
1074  /**
1075   * Retrieve the calendar ID for a given private calendar URL
1076   *
1077   * @param string $url The private URL
1078   *
1079   * @return mixed The calendar ID or false
1080   */
1081  public function getCalendarForPrivateURL($url)
1082  {
1083      $query = "SELECT calid FROM calendartoprivateurlmapping WHERE url = ?";
1084      $res = $this->sqlite->query($query, $url);
1085      $row = $this->sqlite->res2row($res);
1086      if(!isset($row['calid']))
1087        return false;
1088      return $row['calid'];
1089  }
1090
1091  /**
1092   * Return a given calendar as ICS feed, i.e. all events in one ICS file.
1093   *
1094   * @param string $caldi The calendar ID to retrieve
1095   *
1096   * @return mixed The calendar events as string or false
1097   */
1098  public function getCalendarAsICSFeed($calid)
1099  {
1100      $calSettings = $this->getCalendarSettings($calid);
1101      if($calSettings === false)
1102        return false;
1103      $events = $this->getAllCalendarEvents($calid);
1104      if($events === false)
1105        return false;
1106
1107      $out = "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//DAVCal//DAVCal for DokuWiki//EN\nCALSCALE:GREGORIAN\nX-WR-CALNAME:";
1108      $out .= $calSettings['displayname']."\n";
1109      foreach($events as $event)
1110      {
1111          $out .= rtrim($event['calendardata']);
1112          $out .= "\n";
1113      }
1114      $out .= "END:VCALENDAR\n";
1115      return $out;
1116  }
1117
1118  /**
1119   * Retrieve a configuration option for the plugin
1120   *
1121   * @param string $key The key to query
1122   * @return mixed The option set, null if not found
1123   */
1124  public function getConfig($key)
1125  {
1126      return $this->getConf($key);
1127  }
1128
1129}
1130