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