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