xref: /plugin/davcal/helper.php (revision 1bb22c2b6e155479aed3dc0255abebfbc91daa46)
1a1a3b679SAndreas Boehler<?php
2a1a3b679SAndreas Boehler/**
3cb71a62aSAndreas Boehler  * Helper Class for the DAVCal plugin
4a1a3b679SAndreas Boehler  * This helper does the actual work.
5a1a3b679SAndreas Boehler  *
6a1a3b679SAndreas Boehler  */
7a1a3b679SAndreas Boehler
8a1a3b679SAndreas Boehler// must be run within Dokuwiki
9a1a3b679SAndreas Boehlerif(!defined('DOKU_INC')) die();
10a1a3b679SAndreas Boehler
11a1a3b679SAndreas Boehlerclass helper_plugin_davcal extends DokuWiki_Plugin {
12a1a3b679SAndreas Boehler
13a1a3b679SAndreas Boehler  protected $sqlite = null;
14185e2535SAndreas Boehler  protected $cachedValues = array();
15a1a3b679SAndreas Boehler
16a1a3b679SAndreas Boehler  /**
17cb71a62aSAndreas Boehler    * Constructor to load the configuration and the SQLite plugin
18a1a3b679SAndreas Boehler    */
19a1a3b679SAndreas Boehler  public function helper_plugin_davcal() {
20a1a3b679SAndreas Boehler    $this->sqlite =& plugin_load('helper', 'sqlite');
2121d04f73SAndreas Boehler    global $conf;
2221d04f73SAndreas Boehler    if($conf['allowdebug'])
2321d04f73SAndreas Boehler        dbglog('---- DAVCAL helper.php init');
24a1a3b679SAndreas Boehler    if(!$this->sqlite)
25a1a3b679SAndreas Boehler    {
2621d04f73SAndreas Boehler        if($conf['allowdebug'])
2721d04f73SAndreas Boehler            dbglog('This plugin requires the sqlite plugin. Please install it.');
28a1a3b679SAndreas Boehler        msg('This plugin requires the sqlite plugin. Please install it.');
29a1a3b679SAndreas Boehler        return;
30a1a3b679SAndreas Boehler    }
31a1a3b679SAndreas Boehler
32a1a3b679SAndreas Boehler    if(!$this->sqlite->init('davcal', DOKU_PLUGIN.'davcal/db/'))
33a1a3b679SAndreas Boehler    {
3421d04f73SAndreas Boehler        if($conf['allowdebug'])
3521d04f73SAndreas Boehler            dbglog('Error initialising the SQLite DB for DAVCal');
36a1a3b679SAndreas Boehler        return;
37a1a3b679SAndreas Boehler    }
38a1a3b679SAndreas Boehler  }
39a1a3b679SAndreas Boehler
40cb71a62aSAndreas Boehler  /**
41185e2535SAndreas Boehler   * Retrieve meta data for a given page
42185e2535SAndreas Boehler   *
43185e2535SAndreas Boehler   * @param string $id optional The page ID
44185e2535SAndreas Boehler   * @return array The metadata
45185e2535SAndreas Boehler   */
46185e2535SAndreas Boehler  private function getMeta($id = null) {
47185e2535SAndreas Boehler    global $ID;
48185e2535SAndreas Boehler    global $INFO;
49185e2535SAndreas Boehler
50185e2535SAndreas Boehler    if ($id === null) $id = $ID;
51185e2535SAndreas Boehler
52185e2535SAndreas Boehler    if($ID === $id && $INFO['meta']) {
53185e2535SAndreas Boehler        $meta = $INFO['meta'];
54185e2535SAndreas Boehler    } else {
55185e2535SAndreas Boehler        $meta = p_get_metadata($id);
56185e2535SAndreas Boehler    }
57185e2535SAndreas Boehler
58185e2535SAndreas Boehler    return $meta;
59185e2535SAndreas Boehler  }
60185e2535SAndreas Boehler
61185e2535SAndreas Boehler  /**
62185e2535SAndreas Boehler   * Retrieve the meta data for a given page
63185e2535SAndreas Boehler   *
64185e2535SAndreas Boehler   * @param string $id optional The page ID
65185e2535SAndreas Boehler   * @return array with meta data
66185e2535SAndreas Boehler   */
67185e2535SAndreas Boehler  public function getCalendarMetaForPage($id = null)
68185e2535SAndreas Boehler  {
69185e2535SAndreas Boehler      if(is_null($id))
70185e2535SAndreas Boehler      {
71185e2535SAndreas Boehler          global $ID;
72185e2535SAndreas Boehler          $id = $ID;
73185e2535SAndreas Boehler      }
74185e2535SAndreas Boehler
75185e2535SAndreas Boehler      $meta = $this->getMeta($id);
76185e2535SAndreas Boehler      if(isset($meta['plugin_davcal']))
77185e2535SAndreas Boehler        return $meta['plugin_davcal'];
78185e2535SAndreas Boehler      else
79185e2535SAndreas Boehler        return array();
80185e2535SAndreas Boehler  }
81185e2535SAndreas Boehler
82185e2535SAndreas Boehler  /**
8380e1ddf7SAndreas Boehler   * Filter calendar pages and return only those where the current
8480e1ddf7SAndreas Boehler   * user has at least read permission.
8580e1ddf7SAndreas Boehler   *
8680e1ddf7SAndreas Boehler   * @param array $calendarPages Array with calendar pages to check
8780e1ddf7SAndreas Boehler   * @return array with filtered calendar pages
8880e1ddf7SAndreas Boehler   */
8980e1ddf7SAndreas Boehler  public function filterCalendarPagesByUserPermission($calendarPages)
9080e1ddf7SAndreas Boehler  {
9180e1ddf7SAndreas Boehler      $retList = array();
9280e1ddf7SAndreas Boehler      foreach($calendarPages as $page => $data)
9380e1ddf7SAndreas Boehler      {
940b805092SAndreas Boehler          // WebDAV Connections are always readable
950b805092SAndreas Boehler          if(strpos($page, 'webdav://') === 0)
960b805092SAndreas Boehler          {
970b805092SAndreas Boehler              $retList[$page] = $data;
980b805092SAndreas Boehler          }
990b805092SAndreas Boehler          elseif(auth_quickaclcheck($page) >= AUTH_READ)
10080e1ddf7SAndreas Boehler          {
10180e1ddf7SAndreas Boehler              $retList[$page] = $data;
10280e1ddf7SAndreas Boehler          }
10380e1ddf7SAndreas Boehler      }
10480e1ddf7SAndreas Boehler      return $retList;
10580e1ddf7SAndreas Boehler  }
10680e1ddf7SAndreas Boehler
10780e1ddf7SAndreas Boehler  /**
108185e2535SAndreas Boehler   * Get all calendar pages used by a given page
109185e2535SAndreas Boehler   * based on the stored metadata
110185e2535SAndreas Boehler   *
111185e2535SAndreas Boehler   * @param string $id optional The page id
112185e2535SAndreas Boehler   * @return mixed The pages as array or false
113185e2535SAndreas Boehler   */
114185e2535SAndreas Boehler  public function getCalendarPagesByMeta($id = null)
115185e2535SAndreas Boehler  {
116185e2535SAndreas Boehler      if(is_null($id))
117185e2535SAndreas Boehler      {
118185e2535SAndreas Boehler          global $ID;
119185e2535SAndreas Boehler          $id = $ID;
120185e2535SAndreas Boehler      }
121185e2535SAndreas Boehler
122185e2535SAndreas Boehler      $meta = $this->getCalendarMetaForPage($id);
1230b805092SAndreas Boehler
124185e2535SAndreas Boehler      if(isset($meta['id']))
125ed764890SAndreas Boehler      {
126ed764890SAndreas Boehler          // Filter the list of pages by permission
12780e1ddf7SAndreas Boehler          $pages = $this->filterCalendarPagesByUserPermission($meta['id']);
12880e1ddf7SAndreas Boehler          if(empty($pages))
129ed764890SAndreas Boehler            return false;
13080e1ddf7SAndreas Boehler          return $pages;
131ed764890SAndreas Boehler      }
132185e2535SAndreas Boehler      return false;
133185e2535SAndreas Boehler  }
134185e2535SAndreas Boehler
135185e2535SAndreas Boehler  /**
136185e2535SAndreas Boehler   * Get a list of calendar names/pages/ids/colors
137185e2535SAndreas Boehler   * for an array of page ids
138185e2535SAndreas Boehler   *
139185e2535SAndreas Boehler   * @param array $calendarPages The calendar pages to retrieve
140185e2535SAndreas Boehler   * @return array The list
141185e2535SAndreas Boehler   */
142185e2535SAndreas Boehler  public function getCalendarMapForIDs($calendarPages)
143185e2535SAndreas Boehler  {
144185e2535SAndreas Boehler      $data = array();
1454a2bf5eeSAndreas Boehler      foreach($calendarPages as $page => $color)
146185e2535SAndreas Boehler      {
1470b805092SAndreas Boehler            if(strpos($page, 'webdav://') === 0)
1480b805092SAndreas Boehler            {
1490b805092SAndreas Boehler                $wdc =& plugin_load('helper', 'webdavclient');
1500b805092SAndreas Boehler                if(is_null($wdc))
1510b805092SAndreas Boehler                    continue;
1520b805092SAndreas Boehler                $connectionId = str_replace('webdav://', '', $page);
1530b805092SAndreas Boehler                $settings = $wdc->getConnection($connectionId);
1542393a702SAndreas Boehler                if($settings === false)
1552393a702SAndreas Boehler                    continue;
1560b805092SAndreas Boehler                $name = $settings['displayname'];
157809cb0faSAndreas Boehler                $write = $settings['write'];
1580b805092SAndreas Boehler                $calid = $connectionId;
1590b805092SAndreas Boehler            }
1600b805092SAndreas Boehler            else
1610b805092SAndreas Boehler            {
162185e2535SAndreas Boehler                $calid = $this->getCalendarIdForPage($page);
163185e2535SAndreas Boehler                if($calid !== false)
164185e2535SAndreas Boehler                {
165185e2535SAndreas Boehler                    $settings = $this->getCalendarSettings($calid);
166185e2535SAndreas Boehler                    $name = $settings['displayname'];
1670b805092SAndreas Boehler                    //$color = $settings['calendarcolor'];
168ed764890SAndreas Boehler                    $write = (auth_quickaclcheck($page) > AUTH_READ);
1690b805092SAndreas Boehler                }
1700b805092SAndreas Boehler                else
1710b805092SAndreas Boehler                {
1720b805092SAndreas Boehler                    continue;
1730b805092SAndreas Boehler                }
1740b805092SAndreas Boehler            }
175185e2535SAndreas Boehler            $data[] = array('name' => $name, 'page' => $page, 'calid' => $calid,
176ed764890SAndreas Boehler                            'color' => $color, 'write' => $write);
177185e2535SAndreas Boehler      }
178185e2535SAndreas Boehler      return $data;
179185e2535SAndreas Boehler  }
180185e2535SAndreas Boehler
181185e2535SAndreas Boehler  /**
182185e2535SAndreas Boehler   * Get the saved calendar color for a given page.
183185e2535SAndreas Boehler   *
184185e2535SAndreas Boehler   * @param string $id optional The page ID
185185e2535SAndreas Boehler   * @return mixed The color on success, otherwise false
186185e2535SAndreas Boehler   */
187185e2535SAndreas Boehler  public function getCalendarColorForPage($id = null)
188185e2535SAndreas Boehler  {
189185e2535SAndreas Boehler      if(is_null($id))
190185e2535SAndreas Boehler      {
191185e2535SAndreas Boehler          global $ID;
192185e2535SAndreas Boehler          $id = $ID;
193185e2535SAndreas Boehler      }
194185e2535SAndreas Boehler
195185e2535SAndreas Boehler      $calid = $this->getCalendarIdForPage($id);
196185e2535SAndreas Boehler      if($calid === false)
197185e2535SAndreas Boehler        return false;
198185e2535SAndreas Boehler
199185e2535SAndreas Boehler      return $this->getCalendarColorForCalendar($calid);
200185e2535SAndreas Boehler  }
201185e2535SAndreas Boehler
202185e2535SAndreas Boehler  /**
203185e2535SAndreas Boehler   * Get the saved calendar color for a given calendar ID.
204185e2535SAndreas Boehler   *
205185e2535SAndreas Boehler   * @param string $id optional The calendar ID
206185e2535SAndreas Boehler   * @return mixed The color on success, otherwise false
207185e2535SAndreas Boehler   */
208185e2535SAndreas Boehler  public function getCalendarColorForCalendar($calid)
209185e2535SAndreas Boehler  {
210185e2535SAndreas Boehler      if(isset($this->cachedValues['calendarcolor'][$calid]))
211185e2535SAndreas Boehler        return $this->cachedValues['calendarcolor'][$calid];
212185e2535SAndreas Boehler
213185e2535SAndreas Boehler      $row = $this->getCalendarSettings($calid);
214185e2535SAndreas Boehler
215185e2535SAndreas Boehler      if(!isset($row['calendarcolor']))
216185e2535SAndreas Boehler        return false;
217185e2535SAndreas Boehler
218185e2535SAndreas Boehler      $color = $row['calendarcolor'];
219185e2535SAndreas Boehler      $this->cachedValues['calendarcolor'][$calid] = $color;
220185e2535SAndreas Boehler      return $color;
221185e2535SAndreas Boehler  }
222185e2535SAndreas Boehler
223185e2535SAndreas Boehler  /**
224e86c8dd3SAndreas Boehler   * Get the user's principal URL for iOS sync
225e86c8dd3SAndreas Boehler   * @param string $user the user name
226e86c8dd3SAndreas Boehler   * @return the URL to the principal sync
227e86c8dd3SAndreas Boehler   */
228e86c8dd3SAndreas Boehler  public function getPrincipalUrlForUser($user)
229e86c8dd3SAndreas Boehler  {
230e86c8dd3SAndreas Boehler      if(is_null($user))
231e86c8dd3SAndreas Boehler        return false;
232e86c8dd3SAndreas Boehler      $url = DOKU_URL.'lib/plugins/davcal/calendarserver.php/principals/'.$user;
233e86c8dd3SAndreas Boehler      return $url;
234e86c8dd3SAndreas Boehler  }
235e86c8dd3SAndreas Boehler
236e86c8dd3SAndreas Boehler  /**
237185e2535SAndreas Boehler   * Set the calendar color for a given page.
238185e2535SAndreas Boehler   *
239185e2535SAndreas Boehler   * @param string $color The color definition
240185e2535SAndreas Boehler   * @param string $id optional The page ID
241185e2535SAndreas Boehler   * @return boolean True on success, otherwise false
242185e2535SAndreas Boehler   */
243185e2535SAndreas Boehler  public function setCalendarColorForPage($color, $id = null)
244185e2535SAndreas Boehler  {
245185e2535SAndreas Boehler      if(is_null($id))
246185e2535SAndreas Boehler      {
247185e2535SAndreas Boehler          global $ID;
248185e2535SAndreas Boehler          $id = $ID;
249185e2535SAndreas Boehler      }
250185e2535SAndreas Boehler      $calid = $this->getCalendarIdForPage($id);
251185e2535SAndreas Boehler      if($calid === false)
252185e2535SAndreas Boehler        return false;
253185e2535SAndreas Boehler
25451f4febbSAndreas Boehler      $query = "UPDATE calendars SET calendarcolor = ? ".
25551f4febbSAndreas Boehler               " WHERE id = ?";
25651f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $color, $calid);
257185e2535SAndreas Boehler      if($res !== false)
258185e2535SAndreas Boehler      {
259185e2535SAndreas Boehler        $this->cachedValues['calendarcolor'][$calid] = $color;
260185e2535SAndreas Boehler        return true;
261185e2535SAndreas Boehler      }
262185e2535SAndreas Boehler      return false;
263185e2535SAndreas Boehler  }
264185e2535SAndreas Boehler
265185e2535SAndreas Boehler  /**
266cb71a62aSAndreas Boehler   * Set the calendar name and description for a given page with a given
267cb71a62aSAndreas Boehler   * page id.
268cb71a62aSAndreas Boehler   * If the calendar doesn't exist, the calendar is created!
269cb71a62aSAndreas Boehler   *
270cb71a62aSAndreas Boehler   * @param string  $name The name of the new calendar
271cb71a62aSAndreas Boehler   * @param string  $description The description of the new calendar
272cb71a62aSAndreas Boehler   * @param string  $id (optional) The ID of the page
273cb71a62aSAndreas Boehler   * @param string  $userid The userid of the creating user
274cb71a62aSAndreas Boehler   *
275cb71a62aSAndreas Boehler   * @return boolean True on success, otherwise false.
276cb71a62aSAndreas Boehler   */
277a1a3b679SAndreas Boehler  public function setCalendarNameForPage($name, $description, $id = null, $userid = null)
278a1a3b679SAndreas Boehler  {
279a1a3b679SAndreas Boehler      if(is_null($id))
280a1a3b679SAndreas Boehler      {
281a1a3b679SAndreas Boehler          global $ID;
282a1a3b679SAndreas Boehler          $id = $ID;
283a1a3b679SAndreas Boehler      }
284a1a3b679SAndreas Boehler      if(is_null($userid))
28534a47953SAndreas Boehler      {
28634a47953SAndreas Boehler        if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
28734a47953SAndreas Boehler        {
288a1a3b679SAndreas Boehler          $userid = $_SERVER['REMOTE_USER'];
28934a47953SAndreas Boehler        }
29034a47953SAndreas Boehler        else
29134a47953SAndreas Boehler        {
29234a47953SAndreas Boehler          $userid = uniqid('davcal-');
29334a47953SAndreas Boehler        }
29434a47953SAndreas Boehler      }
295a1a3b679SAndreas Boehler      $calid = $this->getCalendarIdForPage($id);
296a1a3b679SAndreas Boehler      if($calid === false)
297a1a3b679SAndreas Boehler        return $this->createCalendarForPage($name, $description, $id, $userid);
298a1a3b679SAndreas Boehler
29951f4febbSAndreas Boehler      $query = "UPDATE calendars SET displayname = ?, description = ? WHERE id = ?";
30051f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $name, $description, $calid);
301b269830cSAndreas Boehler      if($res !== false)
302b269830cSAndreas Boehler        return true;
303b269830cSAndreas Boehler      return false;
304a1a3b679SAndreas Boehler  }
305a1a3b679SAndreas Boehler
306cb71a62aSAndreas Boehler  /**
30765133ef9SAndreas Boehler   * Update a calendar's displayname
30865133ef9SAndreas Boehler   *
30965133ef9SAndreas Boehler   * @param int $calid The calendar's ID
31065133ef9SAndreas Boehler   * @param string $name The new calendar name
31165133ef9SAndreas Boehler   *
31265133ef9SAndreas Boehler   * @return boolean True on success, otherwise false
31365133ef9SAndreas Boehler   */
31465133ef9SAndreas Boehler  public function updateCalendarName($calid, $name)
31565133ef9SAndreas Boehler  {
31665133ef9SAndreas Boehler      $query = "UPDATE calendars SET displayname = ? WHERE id = ?";
31765133ef9SAndreas Boehler      $res = $this->sqlite->query($query, $calid, $name);
31865133ef9SAndreas Boehler      if($res !== false)
31965133ef9SAndreas Boehler      {
32065133ef9SAndreas Boehler        $this->updateSyncTokenLog($calid, '', 'modified');
32165133ef9SAndreas Boehler        return true;
32265133ef9SAndreas Boehler      }
32365133ef9SAndreas Boehler      return false;
32465133ef9SAndreas Boehler  }
32565133ef9SAndreas Boehler
32665133ef9SAndreas Boehler  /**
32765133ef9SAndreas Boehler   * Update the calendar description
32865133ef9SAndreas Boehler   *
32965133ef9SAndreas Boehler   * @param int $calid The calendar's ID
33065133ef9SAndreas Boehler   * @param string $description The new calendar's description
33165133ef9SAndreas Boehler   *
33265133ef9SAndreas Boehler   * @return boolean True on success, otherwise false
33365133ef9SAndreas Boehler   */
33465133ef9SAndreas Boehler  public function updateCalendarDescription($calid, $description)
33565133ef9SAndreas Boehler  {
33665133ef9SAndreas Boehler      $query = "UPDATE calendars SET description = ? WHERE id = ?";
33765133ef9SAndreas Boehler      $res = $this->sqlite->query($query, $calid, $description);
33865133ef9SAndreas Boehler      if($res !== false)
33965133ef9SAndreas Boehler      {
34065133ef9SAndreas Boehler        $this->updateSyncTokenLog($calid, '', 'modified');
34165133ef9SAndreas Boehler        return true;
34265133ef9SAndreas Boehler      }
34365133ef9SAndreas Boehler      return false;
34465133ef9SAndreas Boehler  }
34565133ef9SAndreas Boehler
34665133ef9SAndreas Boehler  /**
34765133ef9SAndreas Boehler   * Update a calendar's timezone information
34865133ef9SAndreas Boehler   *
34965133ef9SAndreas Boehler   * @param int $calid The calendar's ID
35065133ef9SAndreas Boehler   * @param string $timezone The new timezone to set
35165133ef9SAndreas Boehler   *
35265133ef9SAndreas Boehler   * @return boolean True on success, otherwise false
35365133ef9SAndreas Boehler   */
35465133ef9SAndreas Boehler  public function updateCalendarTimezone($calid, $timezone)
35565133ef9SAndreas Boehler  {
35665133ef9SAndreas Boehler      $query = "UPDATE calendars SET timezone = ? WHERE id = ?";
35765133ef9SAndreas Boehler      $res = $this->sqlite->query($query, $calid, $timezone);
35865133ef9SAndreas Boehler      if($res !== false)
35965133ef9SAndreas Boehler      {
36065133ef9SAndreas Boehler        $this->updateSyncTokenLog($calid, '', 'modified');
36165133ef9SAndreas Boehler        return true;
36265133ef9SAndreas Boehler      }
36365133ef9SAndreas Boehler      return false;
36465133ef9SAndreas Boehler  }
36565133ef9SAndreas Boehler
36665133ef9SAndreas Boehler  /**
367cb71a62aSAndreas Boehler   * Save the personal settings to the SQLite database 'calendarsettings'.
368cb71a62aSAndreas Boehler   *
369cb71a62aSAndreas Boehler   * @param array  $settings The settings array to store
370cb71a62aSAndreas Boehler   * @param string $userid (optional) The userid to store
371cb71a62aSAndreas Boehler   *
372cb71a62aSAndreas Boehler   * @param boolean True on success, otherwise false
373cb71a62aSAndreas Boehler   */
374a495d34cSAndreas Boehler  public function savePersonalSettings($settings, $userid = null)
375a495d34cSAndreas Boehler  {
376a495d34cSAndreas Boehler      if(is_null($userid))
37734a47953SAndreas Boehler      {
37834a47953SAndreas Boehler          if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
37934a47953SAndreas Boehler          {
380a495d34cSAndreas Boehler            $userid = $_SERVER['REMOTE_USER'];
38134a47953SAndreas Boehler          }
38234a47953SAndreas Boehler          else
38334a47953SAndreas Boehler          {
38434a47953SAndreas Boehler              return false;
38534a47953SAndreas Boehler          }
38634a47953SAndreas Boehler      }
387a495d34cSAndreas Boehler      $this->sqlite->query("BEGIN TRANSACTION");
388a495d34cSAndreas Boehler
38951f4febbSAndreas Boehler      $query = "DELETE FROM calendarsettings WHERE userid = ?";
39051f4febbSAndreas Boehler      $this->sqlite->query($query, $userid);
391bd883736SAndreas Boehler
392a495d34cSAndreas Boehler      foreach($settings as $key => $value)
393a495d34cSAndreas Boehler      {
39451f4febbSAndreas Boehler          $query = "INSERT INTO calendarsettings (userid, key, value) VALUES (?, ?, ?)";
39551f4febbSAndreas Boehler          $res = $this->sqlite->query($query, $userid, $key, $value);
396a495d34cSAndreas Boehler          if($res === false)
397a495d34cSAndreas Boehler              return false;
398a495d34cSAndreas Boehler      }
399a495d34cSAndreas Boehler      $this->sqlite->query("COMMIT TRANSACTION");
400185e2535SAndreas Boehler      $this->cachedValues['settings'][$userid] = $settings;
401a495d34cSAndreas Boehler      return true;
402a495d34cSAndreas Boehler  }
403a495d34cSAndreas Boehler
404cb71a62aSAndreas Boehler  /**
405cb71a62aSAndreas Boehler   * Retrieve the settings array for a given user id.
406cb71a62aSAndreas Boehler   * Some sane defaults are returned, currently:
407cb71a62aSAndreas Boehler   *
408cb71a62aSAndreas Boehler   *    timezone    => local
409cb71a62aSAndreas Boehler   *    weeknumbers => 0
410cb71a62aSAndreas Boehler   *    workweek    => 0
411cb71a62aSAndreas Boehler   *
412cb71a62aSAndreas Boehler   * @param string $userid (optional) The user id to retrieve
413cb71a62aSAndreas Boehler   *
414cb71a62aSAndreas Boehler   * @return array The settings array
415cb71a62aSAndreas Boehler   */
416a495d34cSAndreas Boehler  public function getPersonalSettings($userid = null)
417a495d34cSAndreas Boehler  {
418bd883736SAndreas Boehler      // Some sane default settings
419bd883736SAndreas Boehler      $settings = array(
420fb813b30SAndreas Boehler        'timezone' => $this->getConf('timezone'),
421fb813b30SAndreas Boehler        'weeknumbers' => $this->getConf('weeknumbers'),
422fb813b30SAndreas Boehler        'workweek' => $this->getConf('workweek'),
4231d5bdcd0SAndreas Boehler        'monday' => $this->getConf('monday'),
4241d5bdcd0SAndreas Boehler        'timeformat' => $this->getConf('timeformat')
425bd883736SAndreas Boehler      );
42634a47953SAndreas Boehler      if(is_null($userid))
42734a47953SAndreas Boehler      {
42834a47953SAndreas Boehler          if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
42934a47953SAndreas Boehler          {
43034a47953SAndreas Boehler            $userid = $_SERVER['REMOTE_USER'];
43134a47953SAndreas Boehler          }
43234a47953SAndreas Boehler          else
43334a47953SAndreas Boehler          {
43434a47953SAndreas Boehler            return $settings;
43534a47953SAndreas Boehler          }
43634a47953SAndreas Boehler      }
43734a47953SAndreas Boehler
43834a47953SAndreas Boehler      if(isset($this->cachedValues['settings'][$userid]))
43934a47953SAndreas Boehler        return $this->cachedValues['settings'][$userid];
44051f4febbSAndreas Boehler      $query = "SELECT key, value FROM calendarsettings WHERE userid = ?";
44151f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $userid);
442a495d34cSAndreas Boehler      $arr = $this->sqlite->res2arr($res);
443a495d34cSAndreas Boehler      foreach($arr as $row)
444a495d34cSAndreas Boehler      {
445a495d34cSAndreas Boehler          $settings[$row['key']] = $row['value'];
446a495d34cSAndreas Boehler      }
447185e2535SAndreas Boehler      $this->cachedValues['settings'][$userid] = $settings;
448a495d34cSAndreas Boehler      return $settings;
449a495d34cSAndreas Boehler  }
450a495d34cSAndreas Boehler
451cb71a62aSAndreas Boehler  /**
452cb71a62aSAndreas Boehler   * Retrieve the calendar ID based on a page ID from the SQLite table
453cb71a62aSAndreas Boehler   * 'pagetocalendarmapping'.
454cb71a62aSAndreas Boehler   *
455cb71a62aSAndreas Boehler   * @param string $id (optional) The page ID to retrieve the corresponding calendar
456cb71a62aSAndreas Boehler   *
457cb71a62aSAndreas Boehler   * @return mixed the ID on success, otherwise false
458cb71a62aSAndreas Boehler   */
459a1a3b679SAndreas Boehler  public function getCalendarIdForPage($id = null)
460a1a3b679SAndreas Boehler  {
461a1a3b679SAndreas Boehler      if(is_null($id))
462a1a3b679SAndreas Boehler      {
463a1a3b679SAndreas Boehler          global $ID;
464a1a3b679SAndreas Boehler          $id = $ID;
465a1a3b679SAndreas Boehler      }
466a1a3b679SAndreas Boehler
467185e2535SAndreas Boehler      if(isset($this->cachedValues['calid'][$id]))
468185e2535SAndreas Boehler        return $this->cachedValues['calid'][$id];
469185e2535SAndreas Boehler
47051f4febbSAndreas Boehler      $query = "SELECT calid FROM pagetocalendarmapping WHERE page = ?";
47151f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $id);
472a1a3b679SAndreas Boehler      $row = $this->sqlite->res2row($res);
473a1a3b679SAndreas Boehler      if(isset($row['calid']))
474185e2535SAndreas Boehler      {
475185e2535SAndreas Boehler        $calid = $row['calid'];
476185e2535SAndreas Boehler        $this->cachedValues['calid'] = $calid;
477185e2535SAndreas Boehler        return $calid;
478185e2535SAndreas Boehler      }
479a1a3b679SAndreas Boehler      return false;
480a1a3b679SAndreas Boehler  }
481a1a3b679SAndreas Boehler
482cb71a62aSAndreas Boehler  /**
483cb71a62aSAndreas Boehler   * Retrieve the complete calendar id to page mapping.
484cb71a62aSAndreas Boehler   * This is necessary to be able to retrieve a list of
485cb71a62aSAndreas Boehler   * calendars for a given user and check the access rights.
486cb71a62aSAndreas Boehler   *
487cb71a62aSAndreas Boehler   * @return array The mapping array
488cb71a62aSAndreas Boehler   */
489a1a3b679SAndreas Boehler  public function getCalendarIdToPageMapping()
490a1a3b679SAndreas Boehler  {
491a1a3b679SAndreas Boehler      $query = "SELECT calid, page FROM pagetocalendarmapping";
492a1a3b679SAndreas Boehler      $res = $this->sqlite->query($query);
493a1a3b679SAndreas Boehler      $arr = $this->sqlite->res2arr($res);
494a1a3b679SAndreas Boehler      return $arr;
495a1a3b679SAndreas Boehler  }
496a1a3b679SAndreas Boehler
497cb71a62aSAndreas Boehler  /**
498cb71a62aSAndreas Boehler   * Retrieve all calendar IDs a given user has access to.
499cb71a62aSAndreas Boehler   * The user is specified by the principalUri, so the
500cb71a62aSAndreas Boehler   * user name is actually split from the URI component.
501cb71a62aSAndreas Boehler   *
502cb71a62aSAndreas Boehler   * Access rights are checked against DokuWiki's ACL
503cb71a62aSAndreas Boehler   * and applied accordingly.
504cb71a62aSAndreas Boehler   *
505cb71a62aSAndreas Boehler   * @param string $principalUri The principal URI to work on
506cb71a62aSAndreas Boehler   *
507cb71a62aSAndreas Boehler   * @return array An associative array of calendar IDs
508cb71a62aSAndreas Boehler   */
509a1a3b679SAndreas Boehler  public function getCalendarIdsForUser($principalUri)
510a1a3b679SAndreas Boehler  {
51134a47953SAndreas Boehler      global $auth;
512a1a3b679SAndreas Boehler      $user = explode('/', $principalUri);
513a1a3b679SAndreas Boehler      $user = end($user);
514a1a3b679SAndreas Boehler      $mapping = $this->getCalendarIdToPageMapping();
515a1a3b679SAndreas Boehler      $calids = array();
51634a47953SAndreas Boehler      $ud = $auth->getUserData($user);
51734a47953SAndreas Boehler      $groups = $ud['grps'];
518a1a3b679SAndreas Boehler      foreach($mapping as $row)
519a1a3b679SAndreas Boehler      {
520a1a3b679SAndreas Boehler          $id = $row['calid'];
521a1a3b679SAndreas Boehler          $page = $row['page'];
52234a47953SAndreas Boehler          $acl = auth_aclcheck($page, $user, $groups);
523a1a3b679SAndreas Boehler          if($acl >= AUTH_READ)
524a1a3b679SAndreas Boehler          {
525a1a3b679SAndreas Boehler              $write = $acl > AUTH_READ;
526a1a3b679SAndreas Boehler              $calids[$id] = array('readonly' => !$write);
527a1a3b679SAndreas Boehler          }
528a1a3b679SAndreas Boehler      }
529a1a3b679SAndreas Boehler      return $calids;
530a1a3b679SAndreas Boehler  }
531a1a3b679SAndreas Boehler
532cb71a62aSAndreas Boehler  /**
533cb71a62aSAndreas Boehler   * Create a new calendar for a given page ID and set name and description
534cb71a62aSAndreas Boehler   * accordingly. Also update the pagetocalendarmapping table on success.
535cb71a62aSAndreas Boehler   *
536cb71a62aSAndreas Boehler   * @param string $name The calendar's name
537cb71a62aSAndreas Boehler   * @param string $description The calendar's description
538cb71a62aSAndreas Boehler   * @param string $id (optional) The page ID to work on
539cb71a62aSAndreas Boehler   * @param string $userid (optional) The user ID that created the calendar
540cb71a62aSAndreas Boehler   *
541cb71a62aSAndreas Boehler   * @return boolean True on success, otherwise false
542cb71a62aSAndreas Boehler   */
543a1a3b679SAndreas Boehler  public function createCalendarForPage($name, $description, $id = null, $userid = null)
544a1a3b679SAndreas Boehler  {
545a1a3b679SAndreas Boehler      if(is_null($id))
546a1a3b679SAndreas Boehler      {
547a1a3b679SAndreas Boehler          global $ID;
548a1a3b679SAndreas Boehler          $id = $ID;
549a1a3b679SAndreas Boehler      }
550a1a3b679SAndreas Boehler      if(is_null($userid))
55134a47953SAndreas Boehler      {
55234a47953SAndreas Boehler        if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
55334a47953SAndreas Boehler        {
554a1a3b679SAndreas Boehler          $userid = $_SERVER['REMOTE_USER'];
55534a47953SAndreas Boehler        }
55634a47953SAndreas Boehler        else
55734a47953SAndreas Boehler        {
55834a47953SAndreas Boehler          $userid = uniqid('davcal-');
55934a47953SAndreas Boehler        }
56034a47953SAndreas Boehler      }
561a1a3b679SAndreas Boehler      $values = array('principals/'.$userid,
562a1a3b679SAndreas Boehler                      $name,
563a1a3b679SAndreas Boehler                      str_replace(array('/', ' ', ':'), '_', $id),
564a1a3b679SAndreas Boehler                      $description,
565a1a3b679SAndreas Boehler                      'VEVENT,VTODO',
56655a741c0SAndreas Boehler                      0,
56755a741c0SAndreas Boehler                      1);
56851f4febbSAndreas Boehler      $query = "INSERT INTO calendars (principaluri, displayname, uri, description, components, transparent, synctoken) ".
56951f4febbSAndreas Boehler               "VALUES (?, ?, ?, ?, ?, ?, ?)";
57051f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $values[0], $values[1], $values[2], $values[3], $values[4], $values[5], $values[6]);
57155a741c0SAndreas Boehler      if($res === false)
57255a741c0SAndreas Boehler        return false;
573cb71a62aSAndreas Boehler
574cb71a62aSAndreas Boehler      // Get the new calendar ID
57551f4febbSAndreas Boehler      $query = "SELECT id FROM calendars WHERE principaluri = ? AND displayname = ? AND ".
57651f4febbSAndreas Boehler               "uri = ? AND description = ?";
57751f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $values[0], $values[1], $values[2], $values[3]);
578a1a3b679SAndreas Boehler      $row = $this->sqlite->res2row($res);
579cb71a62aSAndreas Boehler
580cb71a62aSAndreas Boehler      // Update the pagetocalendarmapping table with the new calendar ID
581a1a3b679SAndreas Boehler      if(isset($row['id']))
582a1a3b679SAndreas Boehler      {
58351f4febbSAndreas Boehler          $query = "INSERT INTO pagetocalendarmapping (page, calid) VALUES (?, ?)";
58451f4febbSAndreas Boehler          $res = $this->sqlite->query($query, $id, $row['id']);
58555a741c0SAndreas Boehler          return ($res !== false);
586a1a3b679SAndreas Boehler      }
587a1a3b679SAndreas Boehler
588a1a3b679SAndreas Boehler      return false;
589a1a3b679SAndreas Boehler  }
590a1a3b679SAndreas Boehler
591cb71a62aSAndreas Boehler  /**
59265133ef9SAndreas Boehler   * Add a new calendar entry to the given calendar. Calendar data is
59365133ef9SAndreas Boehler   * specified as ICS file, thus it needs to be parsed first.
59465133ef9SAndreas Boehler   *
59565133ef9SAndreas Boehler   * This is mainly needed for the sync support.
59665133ef9SAndreas Boehler   *
59765133ef9SAndreas Boehler   * @param int $calid The calendar's ID
59865133ef9SAndreas Boehler   * @param string $uri The new object URI
59965133ef9SAndreas Boehler   * @param string $ics The ICS file
60065133ef9SAndreas Boehler   *
60165133ef9SAndreas Boehler   * @return mixed The etag.
60265133ef9SAndreas Boehler   */
60365133ef9SAndreas Boehler  public function addCalendarEntryToCalendarByICS($calid, $uri, $ics)
60465133ef9SAndreas Boehler  {
60565133ef9SAndreas Boehler    $extraData = $this->getDenormalizedData($ics);
60665133ef9SAndreas Boehler
60765133ef9SAndreas Boehler    $query = "INSERT INTO calendarobjects (calendarid, uri, calendardata, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence, uid) VALUES (?,?,?,?,?,?,?,?,?,?)";
60865133ef9SAndreas Boehler    $res = $this->sqlite->query($query,
60965133ef9SAndreas Boehler            $calid,
61065133ef9SAndreas Boehler            $uri,
61165133ef9SAndreas Boehler            $ics,
61265133ef9SAndreas Boehler            time(),
61365133ef9SAndreas Boehler            $extraData['etag'],
61465133ef9SAndreas Boehler            $extraData['size'],
61565133ef9SAndreas Boehler            $extraData['componentType'],
61665133ef9SAndreas Boehler            $extraData['firstOccurence'],
61765133ef9SAndreas Boehler            $extraData['lastOccurence'],
61865133ef9SAndreas Boehler            $extraData['uid']);
61965133ef9SAndreas Boehler            // If successfully, update the sync token database
62065133ef9SAndreas Boehler    if($res !== false)
62165133ef9SAndreas Boehler    {
62265133ef9SAndreas Boehler        $this->updateSyncTokenLog($calid, $uri, 'added');
62365133ef9SAndreas Boehler    }
62465133ef9SAndreas Boehler    return $extraData['etag'];
62565133ef9SAndreas Boehler  }
62665133ef9SAndreas Boehler
62765133ef9SAndreas Boehler  /**
62865133ef9SAndreas Boehler   * Edit a calendar entry by providing a new ICS file. This is mainly
62965133ef9SAndreas Boehler   * needed for the sync support.
63065133ef9SAndreas Boehler   *
63165133ef9SAndreas Boehler   * @param int $calid The calendar's IS
63265133ef9SAndreas Boehler   * @param string $uri The object's URI to modify
63365133ef9SAndreas Boehler   * @param string $ics The new object's ICS file
63465133ef9SAndreas Boehler   */
63565133ef9SAndreas Boehler  public function editCalendarEntryToCalendarByICS($calid, $uri, $ics)
63665133ef9SAndreas Boehler  {
63765133ef9SAndreas Boehler      $extraData = $this->getDenormalizedData($ics);
63865133ef9SAndreas Boehler
63965133ef9SAndreas Boehler      $query = "UPDATE calendarobjects SET calendardata = ?, lastmodified = ?, etag = ?, size = ?, componenttype = ?, firstoccurence = ?, lastoccurence = ?, uid = ? WHERE calendarid = ? AND uri = ?";
64065133ef9SAndreas Boehler      $res = $this->sqlite->query($query,
64165133ef9SAndreas Boehler        $ics,
64265133ef9SAndreas Boehler        time(),
64365133ef9SAndreas Boehler        $extraData['etag'],
64465133ef9SAndreas Boehler        $extraData['size'],
64565133ef9SAndreas Boehler        $extraData['componentType'],
64665133ef9SAndreas Boehler        $extraData['firstOccurence'],
64765133ef9SAndreas Boehler        $extraData['lastOccurence'],
64865133ef9SAndreas Boehler        $extraData['uid'],
64965133ef9SAndreas Boehler        $calid,
65065133ef9SAndreas Boehler        $uri
65165133ef9SAndreas Boehler      );
65265133ef9SAndreas Boehler      if($res !== false)
65365133ef9SAndreas Boehler      {
65465133ef9SAndreas Boehler          $this->updateSyncTokenLog($calid, $uri, 'modified');
65565133ef9SAndreas Boehler      }
65665133ef9SAndreas Boehler      return $extraData['etag'];
65765133ef9SAndreas Boehler  }
65865133ef9SAndreas Boehler
65965133ef9SAndreas Boehler  /**
660cb71a62aSAndreas Boehler   * Add a new iCal entry for a given page, i.e. a given calendar.
661cb71a62aSAndreas Boehler   *
662cb71a62aSAndreas Boehler   * The parameter array needs to contain
663cb71a62aSAndreas Boehler   *   detectedtz       => The timezone as detected by the browser
66482a48dfbSAndreas Boehler   *   currenttz        => The timezone in use by the calendar
665cb71a62aSAndreas Boehler   *   eventfrom        => The event's start date
666cb71a62aSAndreas Boehler   *   eventfromtime    => The event's start time
667cb71a62aSAndreas Boehler   *   eventto          => The event's end date
668cb71a62aSAndreas Boehler   *   eventtotime      => The event's end time
669cb71a62aSAndreas Boehler   *   eventname        => The event's name
670cb71a62aSAndreas Boehler   *   eventdescription => The event's description
671cb71a62aSAndreas Boehler   *
672cb71a62aSAndreas Boehler   * @param string $id The page ID to work on
673cb71a62aSAndreas Boehler   * @param string $user The user who created the calendar
674cb71a62aSAndreas Boehler   * @param string $params A parameter array with values to create
675cb71a62aSAndreas Boehler   *
676cb71a62aSAndreas Boehler   * @return boolean True on success, otherwise false
677cb71a62aSAndreas Boehler   */
678a1a3b679SAndreas Boehler  public function addCalendarEntryToCalendarForPage($id, $user, $params)
679a1a3b679SAndreas Boehler  {
68082a48dfbSAndreas Boehler      if($params['currenttz'] !== '' && $params['currenttz'] !== 'local')
68182a48dfbSAndreas Boehler          $timezone = new \DateTimeZone($params['currenttz']);
68282a48dfbSAndreas Boehler      elseif($params['currenttz'] === 'local')
683a25c89eaSAndreas Boehler          $timezone = new \DateTimeZone($params['detectedtz']);
684bd883736SAndreas Boehler      else
685bd883736SAndreas Boehler          $timezone = new \DateTimeZone('UTC');
686cb71a62aSAndreas Boehler
687cb71a62aSAndreas Boehler      // Retrieve dates from settings
688b269830cSAndreas Boehler      $startDate = explode('-', $params['eventfrom']);
689b269830cSAndreas Boehler      $startTime = explode(':', $params['eventfromtime']);
690b269830cSAndreas Boehler      $endDate = explode('-', $params['eventto']);
691b269830cSAndreas Boehler      $endTime = explode(':', $params['eventtotime']);
692cb71a62aSAndreas Boehler
693cb71a62aSAndreas Boehler      // Load SabreDAV
6949bef4ad8SAndreas Boehler      require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
695a1a3b679SAndreas Boehler      $vcalendar = new \Sabre\VObject\Component\VCalendar();
696cb71a62aSAndreas Boehler
697cb71a62aSAndreas Boehler      // Add VCalendar, UID and Event Name
698a1a3b679SAndreas Boehler      $event = $vcalendar->add('VEVENT');
699b269830cSAndreas Boehler      $uuid = \Sabre\VObject\UUIDUtil::getUUID();
700b269830cSAndreas Boehler      $event->add('UID', $uuid);
701a1a3b679SAndreas Boehler      $event->summary = $params['eventname'];
702cb71a62aSAndreas Boehler
703cb71a62aSAndreas Boehler      // Add a description if requested
7040eebc909SAndreas Boehler      $description = $params['eventdescription'];
7050eebc909SAndreas Boehler      if($description !== '')
7060eebc909SAndreas Boehler        $event->add('DESCRIPTION', $description);
707cb71a62aSAndreas Boehler
7084ecb526cSAndreas Boehler      // Add attachments
7094ecb526cSAndreas Boehler      $attachments = $params['attachments'];
71082a48dfbSAndreas Boehler      if(!is_null($attachments))
7114ecb526cSAndreas Boehler        foreach($attachments as $attachment)
7124ecb526cSAndreas Boehler          $event->add('ATTACH', $attachment);
7134ecb526cSAndreas Boehler
714cb71a62aSAndreas Boehler      // Create a timestamp for last modified, created and dtstamp values in UTC
715b269830cSAndreas Boehler      $dtStamp = new \DateTime(null, new \DateTimeZone('UTC'));
716b269830cSAndreas Boehler      $event->add('DTSTAMP', $dtStamp);
717b269830cSAndreas Boehler      $event->add('CREATED', $dtStamp);
718b269830cSAndreas Boehler      $event->add('LAST-MODIFIED', $dtStamp);
719cb71a62aSAndreas Boehler
720cb71a62aSAndreas Boehler      // Adjust the start date, based on the given timezone information
721b269830cSAndreas Boehler      $dtStart = new \DateTime();
722a25c89eaSAndreas Boehler      $dtStart->setTimezone($timezone);
723b269830cSAndreas Boehler      $dtStart->setDate(intval($startDate[0]), intval($startDate[1]), intval($startDate[2]));
724cb71a62aSAndreas Boehler
725cb71a62aSAndreas Boehler      // Only add the time values if it's not an allday event
726b269830cSAndreas Boehler      if($params['allday'] != '1')
727b269830cSAndreas Boehler        $dtStart->setTime(intval($startTime[0]), intval($startTime[1]), 0);
728cb71a62aSAndreas Boehler
729cb71a62aSAndreas Boehler      // Adjust the end date, based on the given timezone information
730b269830cSAndreas Boehler      $dtEnd = new \DateTime();
731a25c89eaSAndreas Boehler      $dtEnd->setTimezone($timezone);
732b269830cSAndreas Boehler      $dtEnd->setDate(intval($endDate[0]), intval($endDate[1]), intval($endDate[2]));
733cb71a62aSAndreas Boehler
734cb71a62aSAndreas Boehler      // Only add the time values if it's not an allday event
735b269830cSAndreas Boehler      if($params['allday'] != '1')
736b269830cSAndreas Boehler        $dtEnd->setTime(intval($endTime[0]), intval($endTime[1]), 0);
737cb71a62aSAndreas Boehler
738b269830cSAndreas Boehler      // According to the VCal spec, we need to add a whole day here
739b269830cSAndreas Boehler      if($params['allday'] == '1')
740b269830cSAndreas Boehler          $dtEnd->add(new \DateInterval('P1D'));
741cb71a62aSAndreas Boehler
742cb71a62aSAndreas Boehler      // Really add Start and End events
743b269830cSAndreas Boehler      $dtStartEv = $event->add('DTSTART', $dtStart);
744b269830cSAndreas Boehler      $dtEndEv = $event->add('DTEND', $dtEnd);
745cb71a62aSAndreas Boehler
746cb71a62aSAndreas Boehler      // Adjust the DATE format for allday events
747b269830cSAndreas Boehler      if($params['allday'] == '1')
748b269830cSAndreas Boehler      {
749b269830cSAndreas Boehler          $dtStartEv['VALUE'] = 'DATE';
750b269830cSAndreas Boehler          $dtEndEv['VALUE'] = 'DATE';
751b269830cSAndreas Boehler      }
752cb71a62aSAndreas Boehler
753809cb0faSAndreas Boehler      $eventStr = $vcalendar->serialize();
754809cb0faSAndreas Boehler
755809cb0faSAndreas Boehler      if(strpos($id, 'webdav://') === 0)
756809cb0faSAndreas Boehler      {
757809cb0faSAndreas Boehler          $wdc =& plugin_load('helper', 'webdavclient');
758809cb0faSAndreas Boehler          if(is_null($wdc))
759809cb0faSAndreas Boehler            return false;
760809cb0faSAndreas Boehler          $connectionId = str_replace('webdav://', '', $id);
761809cb0faSAndreas Boehler          return $wdc->addCalendarEntry($connectionId, $eventStr);
762809cb0faSAndreas Boehler      }
763809cb0faSAndreas Boehler      else
764809cb0faSAndreas Boehler      {
765cb71a62aSAndreas Boehler          // Actually add the values to the database
766a1a3b679SAndreas Boehler          $calid = $this->getCalendarIdForPage($id);
767a1a3b679SAndreas Boehler          $uri = uniqid('dokuwiki-').'.ics';
768*1bb22c2bSAndreas Boehler          $now = new \DateTime();
769a1a3b679SAndreas Boehler
77051f4febbSAndreas Boehler          $query = "INSERT INTO calendarobjects (calendarid, uri, calendardata, lastmodified, componenttype, firstoccurence, lastoccurence, size, etag, uid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
77151f4febbSAndreas Boehler          $res = $this->sqlite->query($query, $calid, $uri, $eventStr, $now->getTimestamp(), 'VEVENT',
77251f4febbSAndreas Boehler                                      $event->DTSTART->getDateTime()->getTimeStamp(), $event->DTEND->getDateTime()->getTimeStamp(),
77351f4febbSAndreas Boehler                                      strlen($eventStr), md5($eventStr), $uuid);
774cb71a62aSAndreas Boehler
775cb71a62aSAndreas Boehler          // If successfully, update the sync token database
77655a741c0SAndreas Boehler          if($res !== false)
77755a741c0SAndreas Boehler          {
77855a741c0SAndreas Boehler              $this->updateSyncTokenLog($calid, $uri, 'added');
779a1a3b679SAndreas Boehler              return true;
780a1a3b679SAndreas Boehler          }
781809cb0faSAndreas Boehler      }
78255a741c0SAndreas Boehler      return false;
78355a741c0SAndreas Boehler  }
784a1a3b679SAndreas Boehler
785cb71a62aSAndreas Boehler  /**
786cb71a62aSAndreas Boehler   * Retrieve the calendar settings of a given calendar id
787cb71a62aSAndreas Boehler   *
788cb71a62aSAndreas Boehler   * @param string $calid The calendar ID
789cb71a62aSAndreas Boehler   *
790cb71a62aSAndreas Boehler   * @return array The calendar settings array
791cb71a62aSAndreas Boehler   */
792b269830cSAndreas Boehler  public function getCalendarSettings($calid)
793b269830cSAndreas Boehler  {
79465133ef9SAndreas Boehler      $query = "SELECT id, principaluri, calendarcolor, displayname, uri, description, components, transparent, synctoken FROM calendars WHERE id= ? ";
79551f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $calid);
796b269830cSAndreas Boehler      $row = $this->sqlite->res2row($res);
797b269830cSAndreas Boehler      return $row;
798b269830cSAndreas Boehler  }
799b269830cSAndreas Boehler
800cb71a62aSAndreas Boehler  /**
801cb71a62aSAndreas Boehler   * Retrieve all events that are within a given date range,
802cb71a62aSAndreas Boehler   * based on the timezone setting.
803cb71a62aSAndreas Boehler   *
804cb71a62aSAndreas Boehler   * There is also support for retrieving recurring events,
805cb71a62aSAndreas Boehler   * using Sabre's VObject Iterator. Recurring events are represented
806cb71a62aSAndreas Boehler   * as individual calendar entries with the same UID.
807cb71a62aSAndreas Boehler   *
808cb71a62aSAndreas Boehler   * @param string $id The page ID to work with
809cb71a62aSAndreas Boehler   * @param string $user The user ID to work with
810cb71a62aSAndreas Boehler   * @param string $startDate The start date as a string
811cb71a62aSAndreas Boehler   * @param string $endDate The end date as a string
8124a2bf5eeSAndreas Boehler   * @param string $color (optional) The calendar's color
813cb71a62aSAndreas Boehler   *
814cb71a62aSAndreas Boehler   * @return array An array containing the calendar entries.
815cb71a62aSAndreas Boehler   */
8164a2bf5eeSAndreas Boehler  public function getEventsWithinDateRange($id, $user, $startDate, $endDate, $timezone, $color = null)
817a1a3b679SAndreas Boehler  {
81882a48dfbSAndreas Boehler      if($timezone !== '' && $timezone !== 'local')
81982a48dfbSAndreas Boehler          $timezone = new \DateTimeZone($timezone);
820bd883736SAndreas Boehler      else
821bd883736SAndreas Boehler          $timezone = new \DateTimeZone('UTC');
822a1a3b679SAndreas Boehler      $data = array();
823cb71a62aSAndreas Boehler
824a469597cSAndreas Boehler      $query = "SELECT calendardata, componenttype, uid FROM calendarobjects WHERE calendarid = ?";
825a469597cSAndreas Boehler      $startTs = null;
826a469597cSAndreas Boehler      $endTs = null;
827a469597cSAndreas Boehler      if($startDate !== null)
828a469597cSAndreas Boehler      {
829a1a3b679SAndreas Boehler        $startTs = new \DateTime($startDate);
830a469597cSAndreas Boehler        $query .= " AND lastoccurence > ".$this->sqlite->quote_string($startTs->getTimestamp());
831a469597cSAndreas Boehler      }
832a469597cSAndreas Boehler      if($endDate !== null)
833a469597cSAndreas Boehler      {
834a1a3b679SAndreas Boehler        $endTs = new \DateTime($endDate);
835a469597cSAndreas Boehler        $query .= " AND firstoccurence < ".$this->sqlite->quote_string($endTs->getTimestamp());
836a469597cSAndreas Boehler      }
837cb71a62aSAndreas Boehler
8380b805092SAndreas Boehler      // Load SabreDAV
8390b805092SAndreas Boehler      require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
8400b805092SAndreas Boehler
8410b805092SAndreas Boehler      if(strpos($id, 'webdav://') === 0)
8420b805092SAndreas Boehler      {
8430b805092SAndreas Boehler          $wdc =& plugin_load('helper', 'webdavclient');
8440b805092SAndreas Boehler          if(is_null($wdc))
8450b805092SAndreas Boehler            return $data;
8460b805092SAndreas Boehler          $connectionId = str_replace('webdav://', '', $id);
8470b805092SAndreas Boehler          $arr = $wdc->getCalendarEntries($connectionId, $startDate, $endDate);
8480b805092SAndreas Boehler      }
8490b805092SAndreas Boehler      else
8500b805092SAndreas Boehler      {
8510b805092SAndreas Boehler          $calid = $this->getCalendarIdForPage($id);
8520b805092SAndreas Boehler          if(is_null($color))
8530b805092SAndreas Boehler            $color = $this->getCalendarColorForCalendar($calid);
8540b805092SAndreas Boehler
855cb71a62aSAndreas Boehler          // Retrieve matching calendar objects
856a469597cSAndreas Boehler          $res = $this->sqlite->query($query, $calid);
857a1a3b679SAndreas Boehler          $arr = $this->sqlite->res2arr($res);
8580b805092SAndreas Boehler      }
859cb71a62aSAndreas Boehler
860cb71a62aSAndreas Boehler      // Parse individual calendar entries
861a1a3b679SAndreas Boehler      foreach($arr as $row)
862a1a3b679SAndreas Boehler      {
863a1a3b679SAndreas Boehler          if(isset($row['calendardata']))
864a1a3b679SAndreas Boehler          {
865b269830cSAndreas Boehler              $entry = array();
866a1a3b679SAndreas Boehler              $vcal = \Sabre\VObject\Reader::read($row['calendardata']);
867ebc4eb57SAndreas Boehler              $recurrence = $vcal->VEVENT->RRULE;
868cb71a62aSAndreas Boehler              // If it is a recurring event, pass it through Sabre's EventIterator
869ebc4eb57SAndreas Boehler              if($recurrence != null)
870ebc4eb57SAndreas Boehler              {
871ebc4eb57SAndreas Boehler                  $rEvents = new \Sabre\VObject\Recur\EventIterator(array($vcal->VEVENT));
872ebc4eb57SAndreas Boehler                  $rEvents->rewind();
873e9b7d302SAndreas Boehler                  while($rEvents->valid())
874ebc4eb57SAndreas Boehler                  {
875ebc4eb57SAndreas Boehler                      $event = $rEvents->getEventObject();
876cb71a62aSAndreas Boehler                      // If we are after the given time range, exit
877a469597cSAndreas Boehler                      if(($endTs !== null) && ($rEvents->getDtStart()->getTimestamp() > $endTs->getTimestamp()))
878e9b7d302SAndreas Boehler                          break;
879cb71a62aSAndreas Boehler
880cb71a62aSAndreas Boehler                      // If we are before the given time range, continue
881a469597cSAndreas Boehler                      if(($startTs != null) && ($rEvents->getDtEnd()->getTimestamp() < $startTs->getTimestamp()))
882ebc4eb57SAndreas Boehler                      {
883ebc4eb57SAndreas Boehler                          $rEvents->next();
884ebc4eb57SAndreas Boehler                          continue;
885ebc4eb57SAndreas Boehler                      }
886cb71a62aSAndreas Boehler
887cb71a62aSAndreas Boehler                      // If we are within the given time range, parse the event
888185e2535SAndreas Boehler                      $data[] = $this->convertIcalDataToEntry($event, $id, $timezone, $row['uid'], $color, true);
889ebc4eb57SAndreas Boehler                      $rEvents->next();
890ebc4eb57SAndreas Boehler                  }
891ebc4eb57SAndreas Boehler              }
892ebc4eb57SAndreas Boehler              else
893185e2535SAndreas Boehler                $data[] = $this->convertIcalDataToEntry($vcal->VEVENT, $id, $timezone, $row['uid'], $color);
894ebc4eb57SAndreas Boehler          }
895ebc4eb57SAndreas Boehler      }
896ebc4eb57SAndreas Boehler      return $data;
897ebc4eb57SAndreas Boehler  }
898ebc4eb57SAndreas Boehler
899cb71a62aSAndreas Boehler  /**
900cb71a62aSAndreas Boehler   * Helper function that parses the iCal data of a VEVENT to a calendar entry.
901cb71a62aSAndreas Boehler   *
902cb71a62aSAndreas Boehler   * @param \Sabre\VObject\VEvent $event The event to parse
903cb71a62aSAndreas Boehler   * @param \DateTimeZone $timezone The timezone object
904cb71a62aSAndreas Boehler   * @param string $uid The entry's UID
9053c86dda8SAndreas Boehler   * @param boolean $recurring (optional) Set to true to define a recurring event
906cb71a62aSAndreas Boehler   *
907cb71a62aSAndreas Boehler   * @return array The parse calendar entry
908cb71a62aSAndreas Boehler   */
909185e2535SAndreas Boehler  private function convertIcalDataToEntry($event, $page, $timezone, $uid, $color, $recurring = false)
910ebc4eb57SAndreas Boehler  {
911ebc4eb57SAndreas Boehler      $entry = array();
912ebc4eb57SAndreas Boehler      $start = $event->DTSTART;
913cb71a62aSAndreas Boehler      // Parse only if the start date/time is present
914b269830cSAndreas Boehler      if($start !== null)
915b269830cSAndreas Boehler      {
916b269830cSAndreas Boehler        $dtStart = $start->getDateTime();
917b269830cSAndreas Boehler        $dtStart->setTimezone($timezone);
918bf0ad2b4SAndreas Boehler
919bf0ad2b4SAndreas Boehler        // moment.js doesn't like times be given even if
920bf0ad2b4SAndreas Boehler        // allDay is set to true
921bf0ad2b4SAndreas Boehler        // This should fix T23
922b269830cSAndreas Boehler        if($start['VALUE'] == 'DATE')
923bf0ad2b4SAndreas Boehler        {
924b269830cSAndreas Boehler          $entry['allDay'] = true;
925bf0ad2b4SAndreas Boehler          $entry['start'] = $dtStart->format("Y-m-d");
926bf0ad2b4SAndreas Boehler        }
927b269830cSAndreas Boehler        else
928bf0ad2b4SAndreas Boehler        {
929b269830cSAndreas Boehler          $entry['allDay'] = false;
930bf0ad2b4SAndreas Boehler          $entry['start'] = $dtStart->format(\DateTime::ATOM);
931bf0ad2b4SAndreas Boehler        }
932b269830cSAndreas Boehler      }
933ebc4eb57SAndreas Boehler      $end = $event->DTEND;
934bf0ad2b4SAndreas Boehler      // Parse only if the end date/time is present
935b269830cSAndreas Boehler      if($end !== null)
936b269830cSAndreas Boehler      {
937b269830cSAndreas Boehler        $dtEnd = $end->getDateTime();
938b269830cSAndreas Boehler        $dtEnd->setTimezone($timezone);
939bf0ad2b4SAndreas Boehler        if($end['VALUE'] == 'DATE')
940bf0ad2b4SAndreas Boehler          $entry['end'] = $dtEnd->format("Y-m-d");
941bf0ad2b4SAndreas Boehler        else
942b269830cSAndreas Boehler          $entry['end'] = $dtEnd->format(\DateTime::ATOM);
943b269830cSAndreas Boehler      }
944ebc4eb57SAndreas Boehler      $description = $event->DESCRIPTION;
9450eebc909SAndreas Boehler      if($description !== null)
9460eebc909SAndreas Boehler        $entry['description'] = (string)$description;
9470eebc909SAndreas Boehler      else
9480eebc909SAndreas Boehler        $entry['description'] = '';
9494ecb526cSAndreas Boehler      $attachments = $event->ATTACH;
9504ecb526cSAndreas Boehler      if($attachments !== null)
9514ecb526cSAndreas Boehler      {
9524ecb526cSAndreas Boehler        $entry['attachments'] = array();
9534ecb526cSAndreas Boehler        foreach($attachments as $attachment)
9544ecb526cSAndreas Boehler          $entry['attachments'][] = (string)$attachment;
9554ecb526cSAndreas Boehler      }
956ebc4eb57SAndreas Boehler      $entry['title'] = (string)$event->summary;
957ebc4eb57SAndreas Boehler      $entry['id'] = $uid;
958185e2535SAndreas Boehler      $entry['page'] = $page;
959185e2535SAndreas Boehler      $entry['color'] = $color;
9603c86dda8SAndreas Boehler      $entry['recurring'] = $recurring;
961185e2535SAndreas Boehler
962ebc4eb57SAndreas Boehler      return $entry;
963a1a3b679SAndreas Boehler  }
964a1a3b679SAndreas Boehler
965cb71a62aSAndreas Boehler  /**
966cb71a62aSAndreas Boehler   * Retrieve an event by its UID
967cb71a62aSAndreas Boehler   *
968cb71a62aSAndreas Boehler   * @param string $uid The event's UID
969cb71a62aSAndreas Boehler   *
970cb71a62aSAndreas Boehler   * @return mixed The table row with the given event
971cb71a62aSAndreas Boehler   */
972a1a3b679SAndreas Boehler  public function getEventWithUid($uid)
973a1a3b679SAndreas Boehler  {
97451f4febbSAndreas Boehler      $query = "SELECT calendardata, calendarid, componenttype, uri FROM calendarobjects WHERE uid = ?";
97551f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $uid);
976a1a3b679SAndreas Boehler      $row = $this->sqlite->res2row($res);
977a1a3b679SAndreas Boehler      return $row;
978a1a3b679SAndreas Boehler  }
979a1a3b679SAndreas Boehler
980cb71a62aSAndreas Boehler  /**
98165133ef9SAndreas Boehler   * Retrieve information of a calendar's object, not including the actual
98265133ef9SAndreas Boehler   * calendar data! This is mainly neede for the sync support.
98365133ef9SAndreas Boehler   *
98465133ef9SAndreas Boehler   * @param int $calid The calendar ID
98565133ef9SAndreas Boehler   *
98665133ef9SAndreas Boehler   * @return mixed The result
98765133ef9SAndreas Boehler   */
98865133ef9SAndreas Boehler  public function getCalendarObjects($calid)
98965133ef9SAndreas Boehler  {
99065133ef9SAndreas Boehler      $query = "SELECT id, uri, lastmodified, etag, calendarid, size, componenttype FROM calendarobjects WHERE calendarid = ?";
99165133ef9SAndreas Boehler      $res = $this->sqlite->query($query, $calid);
99265133ef9SAndreas Boehler      $arr = $this->sqlite->res2arr($res);
99365133ef9SAndreas Boehler      return $arr;
99465133ef9SAndreas Boehler  }
99565133ef9SAndreas Boehler
99665133ef9SAndreas Boehler  /**
99765133ef9SAndreas Boehler   * Retrieve a single calendar object by calendar ID and URI
99865133ef9SAndreas Boehler   *
99965133ef9SAndreas Boehler   * @param int $calid The calendar's ID
100065133ef9SAndreas Boehler   * @param string $uri The object's URI
100165133ef9SAndreas Boehler   *
100265133ef9SAndreas Boehler   * @return mixed The result
100365133ef9SAndreas Boehler   */
100465133ef9SAndreas Boehler  public function getCalendarObjectByUri($calid, $uri)
100565133ef9SAndreas Boehler  {
100665133ef9SAndreas Boehler      $query = "SELECT id, uri, lastmodified, etag, calendarid, size, calendardata, componenttype FROM calendarobjects WHERE calendarid = ? AND uri = ?";
100765133ef9SAndreas Boehler      $res = $this->sqlite->query($query, $calid, $uri);
100865133ef9SAndreas Boehler      $row = $this->sqlite->res2row($res);
100965133ef9SAndreas Boehler      return $row;
101065133ef9SAndreas Boehler  }
101165133ef9SAndreas Boehler
101265133ef9SAndreas Boehler  /**
101365133ef9SAndreas Boehler   * Retrieve several calendar objects by specifying an array of URIs.
101465133ef9SAndreas Boehler   * This is mainly neede for sync.
101565133ef9SAndreas Boehler   *
101665133ef9SAndreas Boehler   * @param int $calid The calendar's ID
101765133ef9SAndreas Boehler   * @param array $uris An array of URIs
101865133ef9SAndreas Boehler   *
101965133ef9SAndreas Boehler   * @return mixed The result
102065133ef9SAndreas Boehler   */
102165133ef9SAndreas Boehler  public function getMultipleCalendarObjectsByUri($calid, $uris)
102265133ef9SAndreas Boehler  {
102365133ef9SAndreas Boehler        $query = "SELECT id, uri, lastmodified, etag, calendarid, size, calendardata, componenttype FROM calendarobjects WHERE calendarid = ? AND uri IN (";
102465133ef9SAndreas Boehler        // Inserting a whole bunch of question marks
102565133ef9SAndreas Boehler        $query .= implode(',', array_fill(0, count($uris), '?'));
102665133ef9SAndreas Boehler        $query .= ')';
102765133ef9SAndreas Boehler        $vals = array_merge(array($calid), $uris);
102865133ef9SAndreas Boehler
102965133ef9SAndreas Boehler        $res = $this->sqlite->query($query, $vals);
103065133ef9SAndreas Boehler        $arr = $this->sqlite->res2arr($res);
103165133ef9SAndreas Boehler        return $arr;
103265133ef9SAndreas Boehler  }
103365133ef9SAndreas Boehler
103465133ef9SAndreas Boehler  /**
1035cb71a62aSAndreas Boehler   * Retrieve all calendar events for a given calendar ID
1036cb71a62aSAndreas Boehler   *
1037cb71a62aSAndreas Boehler   * @param string $calid The calendar's ID
1038cb71a62aSAndreas Boehler   *
1039cb71a62aSAndreas Boehler   * @return array An array containing all calendar data
1040cb71a62aSAndreas Boehler   */
1041f69bb449SAndreas Boehler  public function getAllCalendarEvents($calid)
1042f69bb449SAndreas Boehler  {
10437e0b8590SAndreas Boehler      $query = "SELECT calendardata, uid, componenttype, uri FROM calendarobjects WHERE calendarid = ?";
104451f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $calid);
1045f69bb449SAndreas Boehler      $arr = $this->sqlite->res2arr($res);
1046f69bb449SAndreas Boehler      return $arr;
1047f69bb449SAndreas Boehler  }
1048f69bb449SAndreas Boehler
1049cb71a62aSAndreas Boehler  /**
1050cb71a62aSAndreas Boehler   * Edit a calendar entry for a page, given by its parameters.
1051cb71a62aSAndreas Boehler   * The params array has the same format as @see addCalendarEntryForPage
1052cb71a62aSAndreas Boehler   *
1053cb71a62aSAndreas Boehler   * @param string $id The page's ID to work on
1054cb71a62aSAndreas Boehler   * @param string $user The user's ID to work on
1055cb71a62aSAndreas Boehler   * @param array $params The parameter array for the edited calendar event
1056cb71a62aSAndreas Boehler   *
1057cb71a62aSAndreas Boehler   * @return boolean True on success, otherwise false
1058cb71a62aSAndreas Boehler   */
1059a1a3b679SAndreas Boehler  public function editCalendarEntryForPage($id, $user, $params)
1060a1a3b679SAndreas Boehler  {
106182a48dfbSAndreas Boehler      if($params['currenttz'] !== '' && $params['currenttz'] !== 'local')
106282a48dfbSAndreas Boehler          $timezone = new \DateTimeZone($params['currenttz']);
106382a48dfbSAndreas Boehler      elseif($params['currenttz'] === 'local')
1064a25c89eaSAndreas Boehler          $timezone = new \DateTimeZone($params['detectedtz']);
1065bd883736SAndreas Boehler      else
1066bd883736SAndreas Boehler          $timezone = new \DateTimeZone('UTC');
1067cb71a62aSAndreas Boehler
1068cb71a62aSAndreas Boehler      // Parse dates
1069b269830cSAndreas Boehler      $startDate = explode('-', $params['eventfrom']);
1070b269830cSAndreas Boehler      $startTime = explode(':', $params['eventfromtime']);
1071b269830cSAndreas Boehler      $endDate = explode('-', $params['eventto']);
1072b269830cSAndreas Boehler      $endTime = explode(':', $params['eventtotime']);
1073cb71a62aSAndreas Boehler
1074cb71a62aSAndreas Boehler      // Retrieve the existing event based on the UID
107555a741c0SAndreas Boehler      $uid = $params['uid'];
1076809cb0faSAndreas Boehler
1077809cb0faSAndreas Boehler      if(strpos($id, 'webdav://') === 0)
1078809cb0faSAndreas Boehler      {
1079809cb0faSAndreas Boehler        $wdc =& plugin_load('helper', 'webdavclient');
1080809cb0faSAndreas Boehler        if(is_null($wdc))
1081809cb0faSAndreas Boehler          return false;
1082809cb0faSAndreas Boehler        $event = $wdc->getCalendarEntryByUid($uid);
1083809cb0faSAndreas Boehler      }
1084809cb0faSAndreas Boehler      else
1085809cb0faSAndreas Boehler      {
108655a741c0SAndreas Boehler        $event = $this->getEventWithUid($uid);
1087809cb0faSAndreas Boehler      }
1088cb71a62aSAndreas Boehler
1089cb71a62aSAndreas Boehler      // Load SabreDAV
10909bef4ad8SAndreas Boehler      require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
1091a1a3b679SAndreas Boehler      if(!isset($event['calendardata']))
1092a1a3b679SAndreas Boehler        return false;
109355a741c0SAndreas Boehler      $uri = $event['uri'];
109455a741c0SAndreas Boehler      $calid = $event['calendarid'];
1095cb71a62aSAndreas Boehler
1096cb71a62aSAndreas Boehler      // Parse the existing event
1097a1a3b679SAndreas Boehler      $vcal = \Sabre\VObject\Reader::read($event['calendardata']);
1098b269830cSAndreas Boehler      $vevent = $vcal->VEVENT;
1099cb71a62aSAndreas Boehler
1100cb71a62aSAndreas Boehler      // Set the new event values
1101b269830cSAndreas Boehler      $vevent->summary = $params['eventname'];
1102b269830cSAndreas Boehler      $dtStamp = new \DateTime(null, new \DateTimeZone('UTC'));
11030eebc909SAndreas Boehler      $description = $params['eventdescription'];
1104cb71a62aSAndreas Boehler
1105cb71a62aSAndreas Boehler      // Remove existing timestamps to overwrite them
11060eebc909SAndreas Boehler      $vevent->remove('DESCRIPTION');
1107b269830cSAndreas Boehler      $vevent->remove('DTSTAMP');
1108b269830cSAndreas Boehler      $vevent->remove('LAST-MODIFIED');
11094ecb526cSAndreas Boehler      $vevent->remove('ATTACH');
1110cb71a62aSAndreas Boehler
1111cb71a62aSAndreas Boehler      // Add new time stamps and description
1112b269830cSAndreas Boehler      $vevent->add('DTSTAMP', $dtStamp);
1113b269830cSAndreas Boehler      $vevent->add('LAST-MODIFIED', $dtStamp);
11140eebc909SAndreas Boehler      if($description !== '')
11150eebc909SAndreas Boehler        $vevent->add('DESCRIPTION', $description);
1116cb71a62aSAndreas Boehler
11174ecb526cSAndreas Boehler      // Add attachments
11184ecb526cSAndreas Boehler      $attachments = $params['attachments'];
111982a48dfbSAndreas Boehler      if(!is_null($attachments))
11204ecb526cSAndreas Boehler        foreach($attachments as $attachment)
11214ecb526cSAndreas Boehler          $vevent->add('ATTACH', $attachment);
11224ecb526cSAndreas Boehler
1123cb71a62aSAndreas Boehler      // Setup DTSTART
1124b269830cSAndreas Boehler      $dtStart = new \DateTime();
1125a25c89eaSAndreas Boehler      $dtStart->setTimezone($timezone);
1126b269830cSAndreas Boehler      $dtStart->setDate(intval($startDate[0]), intval($startDate[1]), intval($startDate[2]));
1127b269830cSAndreas Boehler      if($params['allday'] != '1')
1128b269830cSAndreas Boehler        $dtStart->setTime(intval($startTime[0]), intval($startTime[1]), 0);
1129cb71a62aSAndreas Boehler
11304ecb526cSAndreas Boehler      // Setup DTEND
1131b269830cSAndreas Boehler      $dtEnd = new \DateTime();
1132a25c89eaSAndreas Boehler      $dtEnd->setTimezone($timezone);
1133b269830cSAndreas Boehler      $dtEnd->setDate(intval($endDate[0]), intval($endDate[1]), intval($endDate[2]));
1134b269830cSAndreas Boehler      if($params['allday'] != '1')
1135b269830cSAndreas Boehler        $dtEnd->setTime(intval($endTime[0]), intval($endTime[1]), 0);
1136cb71a62aSAndreas Boehler
1137b269830cSAndreas Boehler      // According to the VCal spec, we need to add a whole day here
1138b269830cSAndreas Boehler      if($params['allday'] == '1')
1139b269830cSAndreas Boehler          $dtEnd->add(new \DateInterval('P1D'));
1140b269830cSAndreas Boehler      $vevent->remove('DTSTART');
1141b269830cSAndreas Boehler      $vevent->remove('DTEND');
1142b269830cSAndreas Boehler      $dtStartEv = $vevent->add('DTSTART', $dtStart);
1143b269830cSAndreas Boehler      $dtEndEv = $vevent->add('DTEND', $dtEnd);
1144cb71a62aSAndreas Boehler
1145cb71a62aSAndreas Boehler      // Remove the time for allday events
1146b269830cSAndreas Boehler      if($params['allday'] == '1')
1147b269830cSAndreas Boehler      {
1148b269830cSAndreas Boehler          $dtStartEv['VALUE'] = 'DATE';
1149b269830cSAndreas Boehler          $dtEndEv['VALUE'] = 'DATE';
1150b269830cSAndreas Boehler      }
1151a1a3b679SAndreas Boehler      $eventStr = $vcal->serialize();
1152809cb0faSAndreas Boehler      if(strpos($id, 'webdav://') === 0)
1153809cb0faSAndreas Boehler      {
1154809cb0faSAndreas Boehler          $connectionId = str_replace('webdav://', '', $id);
1155809cb0faSAndreas Boehler          return $wdc->editCalendarEntry($connectionId, $uid, $eventStr);
1156809cb0faSAndreas Boehler      }
1157809cb0faSAndreas Boehler      else
1158809cb0faSAndreas Boehler      {
1159809cb0faSAndreas Boehler          $now = new DateTime();
1160cb71a62aSAndreas Boehler          // Actually write to the database
116151f4febbSAndreas Boehler          $query = "UPDATE calendarobjects SET calendardata = ?, lastmodified = ?, ".
116251f4febbSAndreas Boehler                   "firstoccurence = ?, lastoccurence = ?, size = ?, etag = ? WHERE uid = ?";
116351f4febbSAndreas Boehler          $res = $this->sqlite->query($query, $eventStr, $now->getTimestamp(), $dtStart->getTimestamp(),
116451f4febbSAndreas Boehler                                      $dtEnd->getTimestamp(), strlen($eventStr), md5($eventStr), $uid);
116555a741c0SAndreas Boehler          if($res !== false)
116655a741c0SAndreas Boehler          {
116755a741c0SAndreas Boehler              $this->updateSyncTokenLog($calid, $uri, 'modified');
1168a1a3b679SAndreas Boehler              return true;
1169a1a3b679SAndreas Boehler          }
1170809cb0faSAndreas Boehler      }
117155a741c0SAndreas Boehler      return false;
117255a741c0SAndreas Boehler  }
1173a1a3b679SAndreas Boehler
1174cb71a62aSAndreas Boehler  /**
117565133ef9SAndreas Boehler   * Delete an event from a calendar by calendar ID and URI
117665133ef9SAndreas Boehler   *
117765133ef9SAndreas Boehler   * @param int $calid The calendar's ID
117865133ef9SAndreas Boehler   * @param string $uri The object's URI
117965133ef9SAndreas Boehler   *
118065133ef9SAndreas Boehler   * @return true
118165133ef9SAndreas Boehler   */
118265133ef9SAndreas Boehler  public function deleteCalendarEntryForCalendarByUri($calid, $uri)
118365133ef9SAndreas Boehler  {
118465133ef9SAndreas Boehler      $query = "DELETE FROM calendarobjects WHERE calendarid = ? AND uri = ?";
118565133ef9SAndreas Boehler      $res = $this->sqlite->query($query, $calid, $uri);
118665133ef9SAndreas Boehler      if($res !== false)
118765133ef9SAndreas Boehler      {
118865133ef9SAndreas Boehler          $this->updateSyncTokenLog($calid, $uri, 'deleted');
118965133ef9SAndreas Boehler      }
119065133ef9SAndreas Boehler      return true;
119165133ef9SAndreas Boehler  }
119265133ef9SAndreas Boehler
119365133ef9SAndreas Boehler  /**
1194cb71a62aSAndreas Boehler   * Delete a calendar entry for a given page. Actually, the event is removed
1195cb71a62aSAndreas Boehler   * based on the entry's UID, so that page ID is no used.
1196cb71a62aSAndreas Boehler   *
1197cb71a62aSAndreas Boehler   * @param string $id The page's ID (unused)
1198cb71a62aSAndreas Boehler   * @param array $params The parameter array to work with
1199cb71a62aSAndreas Boehler   *
1200cb71a62aSAndreas Boehler   * @return boolean True
1201cb71a62aSAndreas Boehler   */
1202a1a3b679SAndreas Boehler  public function deleteCalendarEntryForPage($id, $params)
1203a1a3b679SAndreas Boehler  {
1204a1a3b679SAndreas Boehler      $uid = $params['uid'];
1205809cb0faSAndreas Boehler      if(strpos($id, 'webdav://') === 0)
1206809cb0faSAndreas Boehler      {
1207809cb0faSAndreas Boehler        $wdc =& plugin_load('helper', 'webdavclient');
1208809cb0faSAndreas Boehler        if(is_null($wdc))
1209809cb0faSAndreas Boehler          return false;
1210809cb0faSAndreas Boehler        $connectionId = str_replace('webdav://', '', $id);
1211809cb0faSAndreas Boehler        $result = $wdc->deleteCalendarEntry($connectionId, $uid);
1212809cb0faSAndreas Boehler        return $result;
1213809cb0faSAndreas Boehler      }
121455a741c0SAndreas Boehler      $event = $this->getEventWithUid($uid);
12152c14b82bSAndreas Boehler      $calid = $event['calendarid'];
121655a741c0SAndreas Boehler      $uri = $event['uri'];
121751f4febbSAndreas Boehler      $query = "DELETE FROM calendarobjects WHERE uid = ?";
121851f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $uid);
121955a741c0SAndreas Boehler      if($res !== false)
122055a741c0SAndreas Boehler      {
122155a741c0SAndreas Boehler          $this->updateSyncTokenLog($calid, $uri, 'deleted');
122255a741c0SAndreas Boehler      }
1223a1a3b679SAndreas Boehler      return true;
1224a1a3b679SAndreas Boehler  }
1225a1a3b679SAndreas Boehler
1226cb71a62aSAndreas Boehler  /**
1227cb71a62aSAndreas Boehler   * Retrieve the current sync token for a calendar
1228cb71a62aSAndreas Boehler   *
1229cb71a62aSAndreas Boehler   * @param string $calid The calendar id
1230cb71a62aSAndreas Boehler   *
1231cb71a62aSAndreas Boehler   * @return mixed The synctoken or false
1232cb71a62aSAndreas Boehler   */
123355a741c0SAndreas Boehler  public function getSyncTokenForCalendar($calid)
123455a741c0SAndreas Boehler  {
1235b269830cSAndreas Boehler      $row = $this->getCalendarSettings($calid);
123655a741c0SAndreas Boehler      if(isset($row['synctoken']))
123755a741c0SAndreas Boehler          return $row['synctoken'];
123855a741c0SAndreas Boehler      return false;
123955a741c0SAndreas Boehler  }
124055a741c0SAndreas Boehler
1241cb71a62aSAndreas Boehler  /**
1242cb71a62aSAndreas Boehler   * Helper function to convert the operation name to
1243cb71a62aSAndreas Boehler   * an operation code as stored in the database
1244cb71a62aSAndreas Boehler   *
1245cb71a62aSAndreas Boehler   * @param string $operationName The operation name
1246cb71a62aSAndreas Boehler   *
1247cb71a62aSAndreas Boehler   * @return mixed The operation code or false
1248cb71a62aSAndreas Boehler   */
124955a741c0SAndreas Boehler  public function operationNameToOperation($operationName)
125055a741c0SAndreas Boehler  {
125155a741c0SAndreas Boehler      switch($operationName)
125255a741c0SAndreas Boehler      {
125355a741c0SAndreas Boehler          case 'added':
125455a741c0SAndreas Boehler              return 1;
125555a741c0SAndreas Boehler          break;
125655a741c0SAndreas Boehler          case 'modified':
125755a741c0SAndreas Boehler              return 2;
125855a741c0SAndreas Boehler          break;
125955a741c0SAndreas Boehler          case 'deleted':
126055a741c0SAndreas Boehler              return 3;
126155a741c0SAndreas Boehler          break;
126255a741c0SAndreas Boehler      }
126355a741c0SAndreas Boehler      return false;
126455a741c0SAndreas Boehler  }
126555a741c0SAndreas Boehler
1266cb71a62aSAndreas Boehler  /**
1267cb71a62aSAndreas Boehler   * Update the sync token log based on the calendar id and the
1268cb71a62aSAndreas Boehler   * operation that was performed.
1269cb71a62aSAndreas Boehler   *
1270cb71a62aSAndreas Boehler   * @param string $calid The calendar ID that was modified
1271cb71a62aSAndreas Boehler   * @param string $uri The calendar URI that was modified
1272cb71a62aSAndreas Boehler   * @param string $operation The operation that was performed
1273cb71a62aSAndreas Boehler   *
1274cb71a62aSAndreas Boehler   * @return boolean True on success, otherwise false
1275cb71a62aSAndreas Boehler   */
127655a741c0SAndreas Boehler  private function updateSyncTokenLog($calid, $uri, $operation)
127755a741c0SAndreas Boehler  {
127855a741c0SAndreas Boehler      $currentToken = $this->getSyncTokenForCalendar($calid);
127955a741c0SAndreas Boehler      $operationCode = $this->operationNameToOperation($operation);
128055a741c0SAndreas Boehler      if(($operationCode === false) || ($currentToken === false))
128155a741c0SAndreas Boehler          return false;
128255a741c0SAndreas Boehler      $values = array($uri,
128355a741c0SAndreas Boehler                      $currentToken,
128455a741c0SAndreas Boehler                      $calid,
128555a741c0SAndreas Boehler                      $operationCode
128655a741c0SAndreas Boehler      );
128751f4febbSAndreas Boehler      $query = "INSERT INTO calendarchanges (uri, synctoken, calendarid, operation) VALUES(?, ?, ?, ?)";
128851f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $uri, $currentToken, $calid, $operationCode);
128955a741c0SAndreas Boehler      if($res === false)
129055a741c0SAndreas Boehler        return false;
129155a741c0SAndreas Boehler      $currentToken++;
129251f4febbSAndreas Boehler      $query = "UPDATE calendars SET synctoken = ? WHERE id = ?";
129351f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $currentToken, $calid);
129455a741c0SAndreas Boehler      return ($res !== false);
129555a741c0SAndreas Boehler  }
129655a741c0SAndreas Boehler
1297cb71a62aSAndreas Boehler  /**
1298cb71a62aSAndreas Boehler   * Return the sync URL for a given Page, i.e. a calendar
1299cb71a62aSAndreas Boehler   *
1300cb71a62aSAndreas Boehler   * @param string $id The page's ID
1301cb71a62aSAndreas Boehler   * @param string $user (optional) The user's ID
1302cb71a62aSAndreas Boehler   *
1303cb71a62aSAndreas Boehler   * @return mixed The sync url or false
1304cb71a62aSAndreas Boehler   */
1305b269830cSAndreas Boehler  public function getSyncUrlForPage($id, $user = null)
1306b269830cSAndreas Boehler  {
130734a47953SAndreas Boehler      if(is_null($userid))
130834a47953SAndreas Boehler      {
130934a47953SAndreas Boehler        if(isset($_SERVER['REMOTE_USER']) && !is_null($_SERVER['REMOTE_USER']))
131034a47953SAndreas Boehler        {
131134a47953SAndreas Boehler          $userid = $_SERVER['REMOTE_USER'];
131234a47953SAndreas Boehler        }
131334a47953SAndreas Boehler        else
131434a47953SAndreas Boehler        {
131534a47953SAndreas Boehler          return false;
131634a47953SAndreas Boehler        }
131734a47953SAndreas Boehler      }
1318b269830cSAndreas Boehler
1319b269830cSAndreas Boehler      $calid = $this->getCalendarIdForPage($id);
1320b269830cSAndreas Boehler      if($calid === false)
1321b269830cSAndreas Boehler        return false;
1322b269830cSAndreas Boehler
1323b269830cSAndreas Boehler      $calsettings = $this->getCalendarSettings($calid);
1324b269830cSAndreas Boehler      if(!isset($calsettings['uri']))
1325b269830cSAndreas Boehler        return false;
1326b269830cSAndreas Boehler
1327b269830cSAndreas Boehler      $syncurl = DOKU_URL.'lib/plugins/davcal/calendarserver.php/calendars/'.$user.'/'.$calsettings['uri'];
1328b269830cSAndreas Boehler      return $syncurl;
1329b269830cSAndreas Boehler  }
1330b269830cSAndreas Boehler
1331cb71a62aSAndreas Boehler  /**
1332cb71a62aSAndreas Boehler   * Return the private calendar's URL for a given page
1333cb71a62aSAndreas Boehler   *
1334cb71a62aSAndreas Boehler   * @param string $id the page ID
1335cb71a62aSAndreas Boehler   *
1336cb71a62aSAndreas Boehler   * @return mixed The private URL or false
1337cb71a62aSAndreas Boehler   */
1338f69bb449SAndreas Boehler  public function getPrivateURLForPage($id)
1339f69bb449SAndreas Boehler  {
1340f69bb449SAndreas Boehler      $calid = $this->getCalendarIdForPage($id);
1341f69bb449SAndreas Boehler      if($calid === false)
1342f69bb449SAndreas Boehler        return false;
1343f69bb449SAndreas Boehler
1344f69bb449SAndreas Boehler      return $this->getPrivateURLForCalendar($calid);
1345f69bb449SAndreas Boehler  }
1346f69bb449SAndreas Boehler
1347cb71a62aSAndreas Boehler  /**
1348cb71a62aSAndreas Boehler   * Return the private calendar's URL for a given calendar ID
1349cb71a62aSAndreas Boehler   *
1350cb71a62aSAndreas Boehler   * @param string $calid The calendar's ID
1351cb71a62aSAndreas Boehler   *
1352cb71a62aSAndreas Boehler   * @return mixed The private URL or false
1353cb71a62aSAndreas Boehler   */
1354f69bb449SAndreas Boehler  public function getPrivateURLForCalendar($calid)
1355f69bb449SAndreas Boehler  {
1356185e2535SAndreas Boehler      if(isset($this->cachedValues['privateurl'][$calid]))
1357185e2535SAndreas Boehler        return $this->cachedValues['privateurl'][$calid];
135851f4febbSAndreas Boehler      $query = "SELECT url FROM calendartoprivateurlmapping WHERE calid = ?";
135951f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $calid);
1360f69bb449SAndreas Boehler      $row = $this->sqlite->res2row($res);
1361f69bb449SAndreas Boehler      if(!isset($row['url']))
1362f69bb449SAndreas Boehler      {
1363f69bb449SAndreas Boehler          $url = uniqid("dokuwiki-").".ics";
136451f4febbSAndreas Boehler          $query = "INSERT INTO calendartoprivateurlmapping (url, calid) VALUES(?, ?)";
136551f4febbSAndreas Boehler          $res = $this->sqlite->query($query, $url, $calid);
1366f69bb449SAndreas Boehler          if($res === false)
1367f69bb449SAndreas Boehler            return false;
1368f69bb449SAndreas Boehler      }
1369f69bb449SAndreas Boehler      else
1370f69bb449SAndreas Boehler      {
1371f69bb449SAndreas Boehler          $url = $row['url'];
1372f69bb449SAndreas Boehler      }
1373185e2535SAndreas Boehler
1374185e2535SAndreas Boehler      $url = DOKU_URL.'lib/plugins/davcal/ics.php/'.$url;
1375185e2535SAndreas Boehler      $this->cachedValues['privateurl'][$calid] = $url;
1376185e2535SAndreas Boehler      return $url;
1377f69bb449SAndreas Boehler  }
1378f69bb449SAndreas Boehler
1379cb71a62aSAndreas Boehler  /**
1380cb71a62aSAndreas Boehler   * Retrieve the calendar ID for a given private calendar URL
1381cb71a62aSAndreas Boehler   *
1382cb71a62aSAndreas Boehler   * @param string $url The private URL
1383cb71a62aSAndreas Boehler   *
1384cb71a62aSAndreas Boehler   * @return mixed The calendar ID or false
1385cb71a62aSAndreas Boehler   */
1386f69bb449SAndreas Boehler  public function getCalendarForPrivateURL($url)
1387f69bb449SAndreas Boehler  {
138851f4febbSAndreas Boehler      $query = "SELECT calid FROM calendartoprivateurlmapping WHERE url = ?";
138951f4febbSAndreas Boehler      $res = $this->sqlite->query($query, $url);
1390f69bb449SAndreas Boehler      $row = $this->sqlite->res2row($res);
1391f69bb449SAndreas Boehler      if(!isset($row['calid']))
1392f69bb449SAndreas Boehler        return false;
1393f69bb449SAndreas Boehler      return $row['calid'];
1394f69bb449SAndreas Boehler  }
1395f69bb449SAndreas Boehler
1396cb71a62aSAndreas Boehler  /**
1397cb71a62aSAndreas Boehler   * Return a given calendar as ICS feed, i.e. all events in one ICS file.
1398cb71a62aSAndreas Boehler   *
13997e0b8590SAndreas Boehler   * @param string $calid The calendar ID to retrieve
1400cb71a62aSAndreas Boehler   *
1401cb71a62aSAndreas Boehler   * @return mixed The calendar events as string or false
1402cb71a62aSAndreas Boehler   */
1403f69bb449SAndreas Boehler  public function getCalendarAsICSFeed($calid)
1404f69bb449SAndreas Boehler  {
1405f69bb449SAndreas Boehler      $calSettings = $this->getCalendarSettings($calid);
1406f69bb449SAndreas Boehler      if($calSettings === false)
1407f69bb449SAndreas Boehler        return false;
1408f69bb449SAndreas Boehler      $events = $this->getAllCalendarEvents($calid);
1409f69bb449SAndreas Boehler      if($events === false)
1410f69bb449SAndreas Boehler        return false;
1411f69bb449SAndreas Boehler
14127e0b8590SAndreas Boehler      // Load SabreDAV
14137e0b8590SAndreas Boehler      require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
14147e0b8590SAndreas Boehler      $out = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//DAVCal//DAVCal for DokuWiki//EN\r\nCALSCALE:GREGORIAN\r\nX-WR-CALNAME:";
14157e0b8590SAndreas Boehler      $out .= $calSettings['displayname']."\r\n";
1416f69bb449SAndreas Boehler      foreach($events as $event)
1417f69bb449SAndreas Boehler      {
14187e0b8590SAndreas Boehler          $vcal = \Sabre\VObject\Reader::read($event['calendardata']);
14197e0b8590SAndreas Boehler          $evt = $vcal->VEVENT;
14207e0b8590SAndreas Boehler          $out .= $evt->serialize();
1421f69bb449SAndreas Boehler      }
14227e0b8590SAndreas Boehler      $out .= "END:VCALENDAR\r\n";
1423f69bb449SAndreas Boehler      return $out;
1424f69bb449SAndreas Boehler  }
1425f69bb449SAndreas Boehler
14267c7c6b0bSAndreas Boehler  /**
14277c7c6b0bSAndreas Boehler   * Retrieve a configuration option for the plugin
14287c7c6b0bSAndreas Boehler   *
14297c7c6b0bSAndreas Boehler   * @param string $key The key to query
143021d04f73SAndreas Boehler   * @return mixed The option set, null if not found
14317c7c6b0bSAndreas Boehler   */
14327c7c6b0bSAndreas Boehler  public function getConfig($key)
14337c7c6b0bSAndreas Boehler  {
14347c7c6b0bSAndreas Boehler      return $this->getConf($key);
14357c7c6b0bSAndreas Boehler  }
14367c7c6b0bSAndreas Boehler
143765133ef9SAndreas Boehler  /**
143865133ef9SAndreas Boehler   * Parses some information from calendar objects, used for optimized
143965133ef9SAndreas Boehler   * calendar-queries. Taken nearly unmodified from Sabre's PDO backend
144065133ef9SAndreas Boehler   *
144165133ef9SAndreas Boehler   * Returns an array with the following keys:
144265133ef9SAndreas Boehler   *   * etag - An md5 checksum of the object without the quotes.
144365133ef9SAndreas Boehler   *   * size - Size of the object in bytes
144465133ef9SAndreas Boehler   *   * componentType - VEVENT, VTODO or VJOURNAL
144565133ef9SAndreas Boehler   *   * firstOccurence
144665133ef9SAndreas Boehler   *   * lastOccurence
144765133ef9SAndreas Boehler   *   * uid - value of the UID property
144865133ef9SAndreas Boehler   *
144965133ef9SAndreas Boehler   * @param string $calendarData
145065133ef9SAndreas Boehler   * @return array
145165133ef9SAndreas Boehler   */
145265133ef9SAndreas Boehler  protected function getDenormalizedData($calendarData)
145365133ef9SAndreas Boehler  {
145465133ef9SAndreas Boehler    require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
145565133ef9SAndreas Boehler
145665133ef9SAndreas Boehler    $vObject = \Sabre\VObject\Reader::read($calendarData);
145765133ef9SAndreas Boehler    $componentType = null;
145865133ef9SAndreas Boehler    $component = null;
145965133ef9SAndreas Boehler    $firstOccurence = null;
146065133ef9SAndreas Boehler    $lastOccurence = null;
146165133ef9SAndreas Boehler    $uid = null;
146265133ef9SAndreas Boehler    foreach ($vObject->getComponents() as $component)
146365133ef9SAndreas Boehler    {
146465133ef9SAndreas Boehler        if ($component->name !== 'VTIMEZONE')
146565133ef9SAndreas Boehler        {
146665133ef9SAndreas Boehler            $componentType = $component->name;
146765133ef9SAndreas Boehler            $uid = (string)$component->UID;
146865133ef9SAndreas Boehler            break;
146965133ef9SAndreas Boehler        }
147065133ef9SAndreas Boehler    }
147165133ef9SAndreas Boehler    if (!$componentType)
147265133ef9SAndreas Boehler    {
147365133ef9SAndreas Boehler        return false;
147465133ef9SAndreas Boehler    }
147565133ef9SAndreas Boehler    if ($componentType === 'VEVENT')
147665133ef9SAndreas Boehler    {
147765133ef9SAndreas Boehler        $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
147865133ef9SAndreas Boehler        // Finding the last occurence is a bit harder
147965133ef9SAndreas Boehler        if (!isset($component->RRULE))
148065133ef9SAndreas Boehler        {
148165133ef9SAndreas Boehler            if (isset($component->DTEND))
148265133ef9SAndreas Boehler            {
148365133ef9SAndreas Boehler                $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
148465133ef9SAndreas Boehler            }
148565133ef9SAndreas Boehler            elseif (isset($component->DURATION))
148665133ef9SAndreas Boehler            {
148765133ef9SAndreas Boehler                $endDate = clone $component->DTSTART->getDateTime();
148865133ef9SAndreas Boehler                $endDate->add(\Sabre\VObject\DateTimeParser::parse($component->DURATION->getValue()));
148965133ef9SAndreas Boehler                $lastOccurence = $endDate->getTimeStamp();
149065133ef9SAndreas Boehler            }
149165133ef9SAndreas Boehler            elseif (!$component->DTSTART->hasTime())
149265133ef9SAndreas Boehler            {
149365133ef9SAndreas Boehler                $endDate = clone $component->DTSTART->getDateTime();
149465133ef9SAndreas Boehler                $endDate->modify('+1 day');
149565133ef9SAndreas Boehler                $lastOccurence = $endDate->getTimeStamp();
149665133ef9SAndreas Boehler            }
149765133ef9SAndreas Boehler            else
149865133ef9SAndreas Boehler            {
149965133ef9SAndreas Boehler                $lastOccurence = $firstOccurence;
150065133ef9SAndreas Boehler            }
150165133ef9SAndreas Boehler        }
150265133ef9SAndreas Boehler        else
150365133ef9SAndreas Boehler        {
150465133ef9SAndreas Boehler            $it = new \Sabre\VObject\Recur\EventIterator($vObject, (string)$component->UID);
150565133ef9SAndreas Boehler            $maxDate = new \DateTime('2038-01-01');
150665133ef9SAndreas Boehler            if ($it->isInfinite())
150765133ef9SAndreas Boehler            {
150865133ef9SAndreas Boehler                $lastOccurence = $maxDate->getTimeStamp();
150965133ef9SAndreas Boehler            }
151065133ef9SAndreas Boehler            else
151165133ef9SAndreas Boehler            {
151265133ef9SAndreas Boehler                $end = $it->getDtEnd();
151365133ef9SAndreas Boehler                while ($it->valid() && $end < $maxDate)
151465133ef9SAndreas Boehler                {
151565133ef9SAndreas Boehler                    $end = $it->getDtEnd();
151665133ef9SAndreas Boehler                    $it->next();
151765133ef9SAndreas Boehler                }
151865133ef9SAndreas Boehler                $lastOccurence = $end->getTimeStamp();
151965133ef9SAndreas Boehler            }
152065133ef9SAndreas Boehler        }
152165133ef9SAndreas Boehler    }
152265133ef9SAndreas Boehler
152365133ef9SAndreas Boehler    return array(
152465133ef9SAndreas Boehler        'etag'           => md5($calendarData),
152565133ef9SAndreas Boehler        'size'           => strlen($calendarData),
152665133ef9SAndreas Boehler        'componentType'  => $componentType,
152765133ef9SAndreas Boehler        'firstOccurence' => $firstOccurence,
152865133ef9SAndreas Boehler        'lastOccurence'  => $lastOccurence,
152965133ef9SAndreas Boehler        'uid'            => $uid,
153065133ef9SAndreas Boehler    );
153165133ef9SAndreas Boehler
153265133ef9SAndreas Boehler  }
153365133ef9SAndreas Boehler
153465133ef9SAndreas Boehler  /**
153565133ef9SAndreas Boehler   * Query a calendar by ID and taking several filters into account.
153665133ef9SAndreas Boehler   * This is heavily based on Sabre's PDO backend.
153765133ef9SAndreas Boehler   *
153865133ef9SAndreas Boehler   * @param int $calendarId The calendar's ID
153965133ef9SAndreas Boehler   * @param array $filters The filter array to apply
154065133ef9SAndreas Boehler   *
154165133ef9SAndreas Boehler   * @return mixed The result
154265133ef9SAndreas Boehler   */
154365133ef9SAndreas Boehler  public function calendarQuery($calendarId, $filters)
154465133ef9SAndreas Boehler  {
154565133ef9SAndreas Boehler    $componentType = null;
154665133ef9SAndreas Boehler    $requirePostFilter = true;
154765133ef9SAndreas Boehler    $timeRange = null;
154865133ef9SAndreas Boehler
154965133ef9SAndreas Boehler    // if no filters were specified, we don't need to filter after a query
155065133ef9SAndreas Boehler    if (!$filters['prop-filters'] && !$filters['comp-filters'])
155165133ef9SAndreas Boehler    {
155265133ef9SAndreas Boehler        $requirePostFilter = false;
155365133ef9SAndreas Boehler    }
155465133ef9SAndreas Boehler
155565133ef9SAndreas Boehler    // Figuring out if there's a component filter
155665133ef9SAndreas Boehler    if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined'])
155765133ef9SAndreas Boehler    {
155865133ef9SAndreas Boehler        $componentType = $filters['comp-filters'][0]['name'];
155965133ef9SAndreas Boehler
156065133ef9SAndreas Boehler        // Checking if we need post-filters
156165133ef9SAndreas Boehler        if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters'])
156265133ef9SAndreas Boehler        {
156365133ef9SAndreas Boehler            $requirePostFilter = false;
156465133ef9SAndreas Boehler        }
156565133ef9SAndreas Boehler        // There was a time-range filter
156665133ef9SAndreas Boehler        if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range']))
156765133ef9SAndreas Boehler        {
156865133ef9SAndreas Boehler            $timeRange = $filters['comp-filters'][0]['time-range'];
156965133ef9SAndreas Boehler
157065133ef9SAndreas Boehler            // If start time OR the end time is not specified, we can do a
157165133ef9SAndreas Boehler            // 100% accurate mysql query.
157265133ef9SAndreas Boehler            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end']))
157365133ef9SAndreas Boehler            {
157465133ef9SAndreas Boehler                $requirePostFilter = false;
157565133ef9SAndreas Boehler            }
157665133ef9SAndreas Boehler        }
157765133ef9SAndreas Boehler
157865133ef9SAndreas Boehler    }
157965133ef9SAndreas Boehler
158065133ef9SAndreas Boehler    if ($requirePostFilter)
158165133ef9SAndreas Boehler    {
158265133ef9SAndreas Boehler        $query = "SELECT uri, calendardata FROM calendarobjects WHERE calendarid = ?";
158365133ef9SAndreas Boehler    }
158465133ef9SAndreas Boehler    else
158565133ef9SAndreas Boehler    {
158665133ef9SAndreas Boehler        $query = "SELECT uri FROM calendarobjects WHERE calendarid = ?";
158765133ef9SAndreas Boehler    }
158865133ef9SAndreas Boehler
158965133ef9SAndreas Boehler    $values = array(
159065133ef9SAndreas Boehler        $calendarId
159165133ef9SAndreas Boehler    );
159265133ef9SAndreas Boehler
159365133ef9SAndreas Boehler    if ($componentType)
159465133ef9SAndreas Boehler    {
159565133ef9SAndreas Boehler        $query .= " AND componenttype = ?";
159665133ef9SAndreas Boehler        $values[] = $componentType;
159765133ef9SAndreas Boehler    }
159865133ef9SAndreas Boehler
159965133ef9SAndreas Boehler    if ($timeRange && $timeRange['start'])
160065133ef9SAndreas Boehler    {
160165133ef9SAndreas Boehler        $query .= " AND lastoccurence > ?";
160265133ef9SAndreas Boehler        $values[] = $timeRange['start']->getTimeStamp();
160365133ef9SAndreas Boehler    }
160465133ef9SAndreas Boehler    if ($timeRange && $timeRange['end'])
160565133ef9SAndreas Boehler    {
160665133ef9SAndreas Boehler        $query .= " AND firstoccurence < ?";
160765133ef9SAndreas Boehler        $values[] = $timeRange['end']->getTimeStamp();
160865133ef9SAndreas Boehler    }
160965133ef9SAndreas Boehler
161065133ef9SAndreas Boehler    $res = $this->sqlite->query($query, $values);
161165133ef9SAndreas Boehler    $arr = $this->sqlite->res2arr($res);
161265133ef9SAndreas Boehler
161365133ef9SAndreas Boehler    $result = array();
161465133ef9SAndreas Boehler    foreach($arr as $row)
161565133ef9SAndreas Boehler    {
161665133ef9SAndreas Boehler        if ($requirePostFilter)
161765133ef9SAndreas Boehler        {
161865133ef9SAndreas Boehler            if (!$this->validateFilterForObject($row, $filters))
161965133ef9SAndreas Boehler            {
162065133ef9SAndreas Boehler                continue;
162165133ef9SAndreas Boehler            }
162265133ef9SAndreas Boehler        }
162365133ef9SAndreas Boehler        $result[] = $row['uri'];
162465133ef9SAndreas Boehler
162565133ef9SAndreas Boehler    }
162665133ef9SAndreas Boehler
162765133ef9SAndreas Boehler    return $result;
162865133ef9SAndreas Boehler  }
162965133ef9SAndreas Boehler
163065133ef9SAndreas Boehler  /**
163165133ef9SAndreas Boehler   * This method validates if a filter (as passed to calendarQuery) matches
163265133ef9SAndreas Boehler   * the given object. Taken from Sabre's PDO backend
163365133ef9SAndreas Boehler   *
163465133ef9SAndreas Boehler   * @param array $object
163565133ef9SAndreas Boehler   * @param array $filters
163665133ef9SAndreas Boehler   * @return bool
163765133ef9SAndreas Boehler   */
163865133ef9SAndreas Boehler  protected function validateFilterForObject($object, $filters)
163965133ef9SAndreas Boehler  {
164065133ef9SAndreas Boehler      require_once(DOKU_PLUGIN.'davcal/vendor/autoload.php');
164165133ef9SAndreas Boehler      // Unfortunately, setting the 'calendardata' here is optional. If
164265133ef9SAndreas Boehler      // it was excluded, we actually need another call to get this as
164365133ef9SAndreas Boehler      // well.
164465133ef9SAndreas Boehler      if (!isset($object['calendardata']))
164565133ef9SAndreas Boehler      {
164665133ef9SAndreas Boehler          $object = $this->getCalendarObjectByUri($object['calendarid'], $object['uri']);
164765133ef9SAndreas Boehler      }
164865133ef9SAndreas Boehler
164965133ef9SAndreas Boehler      $vObject = \Sabre\VObject\Reader::read($object['calendardata']);
165065133ef9SAndreas Boehler      $validator = new \Sabre\CalDAV\CalendarQueryValidator();
165165133ef9SAndreas Boehler
165265133ef9SAndreas Boehler      return $validator->validate($vObject, $filters);
165365133ef9SAndreas Boehler
165465133ef9SAndreas Boehler  }
165565133ef9SAndreas Boehler
165665133ef9SAndreas Boehler  /**
165765133ef9SAndreas Boehler   * Retrieve changes for a given calendar based on the given syncToken.
165865133ef9SAndreas Boehler   *
165965133ef9SAndreas Boehler   * @param int $calid The calendar's ID
166065133ef9SAndreas Boehler   * @param int $syncToken The supplied sync token
166165133ef9SAndreas Boehler   * @param int $syncLevel The sync level
166265133ef9SAndreas Boehler   * @param int $limit The limit of changes
166365133ef9SAndreas Boehler   *
166465133ef9SAndreas Boehler   * @return array The result
166565133ef9SAndreas Boehler   */
166665133ef9SAndreas Boehler  public function getChangesForCalendar($calid, $syncToken, $syncLevel, $limit = null)
166765133ef9SAndreas Boehler  {
166865133ef9SAndreas Boehler      // Current synctoken
166965133ef9SAndreas Boehler      $currentToken = $this->getSyncTokenForCalendar($calid);
167065133ef9SAndreas Boehler
167165133ef9SAndreas Boehler      if ($currentToken === false) return null;
167265133ef9SAndreas Boehler
167365133ef9SAndreas Boehler      $result = array(
167465133ef9SAndreas Boehler          'syncToken' => $currentToken,
167565133ef9SAndreas Boehler          'added'     => array(),
167665133ef9SAndreas Boehler          'modified'  => array(),
167765133ef9SAndreas Boehler          'deleted'   => array(),
167865133ef9SAndreas Boehler      );
167965133ef9SAndreas Boehler
168065133ef9SAndreas Boehler      if ($syncToken)
168165133ef9SAndreas Boehler      {
168265133ef9SAndreas Boehler
168365133ef9SAndreas Boehler          $query = "SELECT uri, operation FROM calendarchanges WHERE synctoken >= ? AND synctoken < ? AND calendarid = ? ORDER BY synctoken";
168465133ef9SAndreas Boehler          if ($limit > 0) $query .= " LIMIT " . (int)$limit;
168565133ef9SAndreas Boehler
168665133ef9SAndreas Boehler          // Fetching all changes
168765133ef9SAndreas Boehler          $res = $this->sqlite->query($query, $syncToken, $currentToken, $calid);
168865133ef9SAndreas Boehler          if($res === false)
168965133ef9SAndreas Boehler              return null;
169065133ef9SAndreas Boehler
169165133ef9SAndreas Boehler          $arr = $this->sqlite->res2arr($res);
169265133ef9SAndreas Boehler          $changes = array();
169365133ef9SAndreas Boehler
169465133ef9SAndreas Boehler          // This loop ensures that any duplicates are overwritten, only the
169565133ef9SAndreas Boehler          // last change on a node is relevant.
169665133ef9SAndreas Boehler          foreach($arr as $row)
169765133ef9SAndreas Boehler          {
169865133ef9SAndreas Boehler              $changes[$row['uri']] = $row['operation'];
169965133ef9SAndreas Boehler          }
170065133ef9SAndreas Boehler
170165133ef9SAndreas Boehler          foreach ($changes as $uri => $operation)
170265133ef9SAndreas Boehler          {
170365133ef9SAndreas Boehler              switch ($operation)
170465133ef9SAndreas Boehler              {
170565133ef9SAndreas Boehler                  case 1 :
170665133ef9SAndreas Boehler                      $result['added'][] = $uri;
170765133ef9SAndreas Boehler                      break;
170865133ef9SAndreas Boehler                  case 2 :
170965133ef9SAndreas Boehler                      $result['modified'][] = $uri;
171065133ef9SAndreas Boehler                      break;
171165133ef9SAndreas Boehler                  case 3 :
171265133ef9SAndreas Boehler                      $result['deleted'][] = $uri;
171365133ef9SAndreas Boehler                      break;
171465133ef9SAndreas Boehler              }
171565133ef9SAndreas Boehler
171665133ef9SAndreas Boehler          }
171765133ef9SAndreas Boehler      }
171865133ef9SAndreas Boehler      else
171965133ef9SAndreas Boehler      {
172065133ef9SAndreas Boehler          // No synctoken supplied, this is the initial sync.
172165133ef9SAndreas Boehler          $query = "SELECT uri FROM calendarobjects WHERE calendarid = ?";
172265133ef9SAndreas Boehler          $res = $this->sqlite->query($query);
172365133ef9SAndreas Boehler          $arr = $this->sqlite->res2arr($res);
172465133ef9SAndreas Boehler
172565133ef9SAndreas Boehler          $result['added'] = $arr;
172665133ef9SAndreas Boehler      }
172765133ef9SAndreas Boehler      return $result;
172865133ef9SAndreas Boehler  }
172965133ef9SAndreas Boehler
1730a1a3b679SAndreas Boehler}
1731