├── src ├── includes │ ├── README │ ├── Translation.php │ ├── XMLDocument.php │ ├── XMLElement.php │ └── AWLUtilities.php ├── CalDAVObject.php ├── CalDAVCalendar.php ├── CalDAVException.php ├── CalDAVFilter.php ├── SimpleCalDAVClient.php └── CalDAVClient.php ├── TODO ├── composer.json ├── config └── listCalendars.php ├── .gitignore ├── README.md ├── example code └── example.php ├── COPYING └── LICENSE /src/includes/README: -------------------------------------------------------------------------------- 1 | These libraries are borrowed from Andrew’s Web Libraries: 2 | https://github.com/andrews-web-libraries/awl 3 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | Known Bugs: 2 | - getTODOs: Time range filter doesn't work properly 3 | 4 | ToDo: 5 | - fix bugs 6 | - write some PHPUnit tests -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "thecsea/simple-caldav-client", 3 | "type": "library", 4 | "keywords": ["caldav","client", "simple"], 5 | "description": "A simple and complete php caldav client", 6 | "homepage": "http://www.thecsea.it", 7 | "minimum-stability": "stable", 8 | "license": "GPL-2.0", 9 | "authors": [ 10 | { 11 | "name": "claudio cardinale", 12 | "email": "cardi@thecsea.it", 13 | "homepage": "http://thecsea.it" 14 | } 15 | ], 16 | "require": { 17 | "php": ">=5.3.0", 18 | "ext-curl": "*", 19 | "ext-xml": "*" 20 | }, 21 | "autoload": { 22 | "psr-4": { 23 | "it\\thecsea\\simple_caldav_client\\": "src/" 24 | } 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /src/CalDAVObject.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * This class represents a calendar resource on the CalDAV-Server (event, todo, etc.) 8 | * 9 | * href: The link to the resource in the calendar 10 | * data: The iCalendar-Data. The "heart" of the resource. 11 | * etag: The entity tag is a unique identifier, not only of a resource 12 | * like the unique ID, but of serveral versions of the same resource. This means that a resource with one unique 13 | * ID can have many different entity tags, depending on the content of the resource. One version of a resource, 14 | * i. e. one special description in combination with one special starting time, created at one specific time, 15 | * etc., has exactly on unique entity tag. 16 | * The assignment of an entity tag ensures, that you know what you are changing/deleting. It ensures, that no one 17 | * changed the resource between your viewing of the resource and your change/delete-request. Assigning an entity tag 18 | * provides you of accidently destroying the work of others. 19 | * 20 | * @package simpleCalDAV 21 | * 22 | */ 23 | 24 | namespace it\thecsea\simple_caldav_client; 25 | 26 | class CalDAVObject { 27 | private $href; 28 | private $data; 29 | private $etag; 30 | 31 | public function __construct ($href, $data, $etag) { 32 | $this->href = $href; 33 | $this->data = $data; 34 | $this->etag = $etag; 35 | } 36 | 37 | 38 | // Getter 39 | 40 | public function getHref () { 41 | return $this->href; 42 | } 43 | 44 | public function getData () { 45 | return $this->data; 46 | } 47 | 48 | public function getEtag () { 49 | return $this->etag; 50 | } 51 | } 52 | 53 | ?> -------------------------------------------------------------------------------- /config/listCalendars.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * Open this file in a webbrowser to view a list of all accessible calendars 8 | * on the server and the information related to those calendars. It can be used 9 | * to determine the calendar-id, needed for SimpleCalDAV. 10 | * 11 | * @package simpleCalDAV 12 | */ 13 | 14 | require_once('../vendor/autoload.php'); 15 | 16 | use it\thecsea\simple_caldav_client\SimpleCalDAVClient; 17 | 18 | if($_POST == null) { 19 | echo ' 20 |
21 |

This formular can be used to view a list of all accessible calendars on the server and the information related to those calendars. It can be used to determine the calendar-id, needed for SimpleCalDAV.

22 |

Calendar-URL:

23 |

Username:

24 |

Password:

25 | 26 |
'; 27 | } 28 | 29 | else { 30 | $client = new SimpleCalDAVClient(); 31 | 32 | try { 33 | $client->connect($_POST['url'], $_POST['user'], $_POST['pass']); 34 | 35 | $calendars = $client->findCalendars(); 36 | 37 | echo' 38 | '; 39 | 40 | $i = 0; 41 | foreach($calendars as $cal) { 42 | $i++; 43 | 44 | echo ' 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | '; 53 | } 54 | 55 | echo ' 56 |
Calendar #'.$i.'
URL: '.$cal->getURL().'
Display Name: '.$cal->getDisplayName().'
Calendar ID: '.$cal->getCalendarID().'
CTAG: '.$cal->getCTag().'
RBG-Color: '.$cal->getRBGcolor().'
Order: '.$cal->getOrder().'
'; 57 | } 58 | 59 | catch (Exception $e) { 60 | echo $e->__toString(); 61 | } 62 | } 63 | 64 | ?> -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io 2 | 3 | ### Linux ### 4 | *~ 5 | 6 | # KDE directory preferences 7 | .directory 8 | 9 | # Linux trash folder which might appear on any partition or disk 10 | .Trash-* 11 | 12 | 13 | 14 | 15 | ### OSX ### 16 | .DS_Store 17 | .AppleDouble 18 | .LSOverride 19 | 20 | # Icon must end with two \r 21 | Icon 22 | 23 | 24 | # Thumbnails 25 | ._* 26 | 27 | # Files that might appear in the root of a volume 28 | .DocumentRevisions-V100 29 | .fseventsd 30 | .Spotlight-V100 31 | .TemporaryItems 32 | .Trashes 33 | .VolumeIcon.icns 34 | 35 | # Directories potentially created on remote AFP share 36 | .AppleDB 37 | .AppleDesktop 38 | Network Trash Folder 39 | Temporary Items 40 | .apdisk 41 | 42 | 43 | 44 | ### Windows ### 45 | # Windows image file caches 46 | Thumbs.db 47 | ehthumbs.db 48 | 49 | # Folder config file 50 | Desktop.ini 51 | 52 | # Recycle Bin used on file shares 53 | $RECYCLE.BIN/ 54 | 55 | 56 | ### PhpStorm ### 57 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm 58 | 59 | *.iml 60 | 61 | ## Directory-based project format: 62 | .idea/ 63 | # if you remove the above rule, at least ignore the following: 64 | 65 | # Company-specific stuff: 66 | # .idea/workspace.xml 67 | # .idea/tasks.xml 68 | # .idea/dictionaries 69 | 70 | # Sensitive or high-churn files: 71 | # .idea/dataSources.ids 72 | # .idea/dataSources.xml 73 | # .idea/sqlDataSources.xml 74 | # .idea/dynamic.xml 75 | # .idea/uiDesigner.xml 76 | 77 | # Gradle: 78 | # .idea/gradle.xml 79 | # .idea/libraries 80 | 81 | # Mongo Explorer plugin: 82 | # .idea/mongoSettings.xml 83 | 84 | ## File-based project format: 85 | *.ipr 86 | *.iws 87 | 88 | ## Plugin-specific files: 89 | 90 | # IntelliJ 91 | /out/ 92 | 93 | # mpeltonen/sbt-idea plugin 94 | .idea_modules/ 95 | 96 | # JIRA plugin 97 | atlassian-ide-plugin.xml 98 | 99 | # Crashlytics plugin (for Android Studio and IntelliJ) 100 | com_crashlytics_export_strings.xml 101 | crashlytics.properties 102 | crashlytics-build.properties 103 | 104 | 105 | 106 | ### Composer ### 107 | composer.phar 108 | composer.lock 109 | /vendor 110 | 111 | 112 | ### tests ### 113 | coverage.xml 114 | coverage.txt 115 | coverage.clover 116 | 117 | ### gulp ### 118 | node_modules/ 119 | npm-debug.log 120 | public/css 121 | 122 | ### laravel ide helper ### 123 | .phpstorm.meta.php 124 | _ide_helper.php 125 | 126 | 127 | ### DEPLOYING ### 128 | .git_utility 129 | 130 | 131 | ### laravel environment ### 132 | .env -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # simpleCalDAV 2 | 3 | Build status: [![Latest Stable Version](https://poser.pugx.org/thecsea/simple-caldav-client/v/stable)](https://packagist.org/packages/thecsea/simple-caldav-client) [![Total Downloads](https://poser.pugx.org/thecsea/simple-caldav-client/downloads)](https://packagist.org/packages/thecsea/simple-caldav-client) [![Latest Unstable Version](https://poser.pugx.org/thecsea/simple-caldav-client/v/unstable)](https://packagist.org/packages/thecsea/simple-caldav-client) [![License](https://poser.pugx.org/thecsea/simple-caldav-client/license)](https://packagist.org/packages/thecsea/simple-caldav-client) 4 | 5 | This library is just a porting for packagist of [https://github.com/wvrzel/simpleCalDAV](https://github.com/wvrzel/simpleCalDAV) 6 | 7 | # Examples of use 8 | * [https://github.com/dsd-meetme/backend](https://github.com/dsd-meetme/backend) 9 | 10 | simpleCalDAV 11 | 12 | Copyright 2014 Michael Palm 13 | 14 | Table of content 15 | 16 | 1. About 17 | 1. Requirements 18 | 1. Installation 19 | 1. How to get started 20 | 1. Example Code 21 | 22 | ------------------------ 23 | 24 | 1) About 25 | 26 | simpleCalDAV is a php library that allows you to connect to a calDAV-server to get event-, todo- and free/busy-calendar resources from the server, to change them, to delete them, to create new ones, etc. 27 | simpleCalDAV was made and tested for connections to the CalDAV-server Baikal 0.2.7. But it should work with any other CalDAV-server too. 28 | 29 | It contains the following functions: 30 | - connect() 31 | - findCalendars() 32 | - setCalendar() 33 | - create() 34 | - change() 35 | - delete() 36 | - getEvents() 37 | - getTODOs() 38 | - getCustomReport() 39 | 40 | All of those functions are really easy to use, self-explanatory and are deliverd with a big innitial comment, which explains all needed arguments and the return values. 41 | 42 | This library is heavily based on AgenDAV simple-caldav-client-v2.php by Jorge López Pérez which again is heavily based on DAViCal caldav-client-v2.php by Andrew McMillan . 43 | Actually, I hardly added any features. The main point of my work is to make everything straight forward and easy to use. You can use simpleCalDAV whithout a deeper understanding of the calDAV-protocol. 44 | 45 | 46 | 2) Requirements 47 | 48 | Requirements of this library are 49 | - The php extension cURL ( http://www.php.net/manual/en/book.curl.php ) 50 | 51 | 52 | 3) Installation 53 | 54 | Just navigate into a directory on your server and execute 55 | git clone https://github.com/wvrzel/simpleCalDAV.git 56 | 57 | Assure yourself that cURL is installed. 58 | 59 | Import SimpleCalDAVClient.php in your code and you are ready to go ;-) 60 | 61 | 62 | 4) How to get started 63 | 64 | Read the comments in SimpleCalDAVClient.php and the example code. 65 | 66 | 67 | 5) Example Code 68 | 69 | Example code is provided under "/example code/". 70 | -------------------------------------------------------------------------------- /src/CalDAVCalendar.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * This class represents an accsessible calendar on the server. 8 | * 9 | * I think the functions 10 | * - getURL() 11 | * - getDisplayName() 12 | * - getCalendarID() 13 | * - getRGBAcolor() 14 | * - getRBGcolor() 15 | * are pretty self-explanatory. 16 | * 17 | * 18 | * getCTag() returns the ctag of the calendar. 19 | * The ctag is an hash-value used to check, if the client is up to date. The ctag changes everytime 20 | * someone changes something in the calendar. So, to check if anything happend since your last visit: 21 | * just compare the ctags. 22 | * 23 | * getOrder() returns the order of the calendar in the list of calendars 24 | * 25 | * 26 | * @package simpleCalDAV 27 | * 28 | */ 29 | 30 | namespace it\thecsea\simple_caldav_client; 31 | 32 | class CalDAVCalendar { 33 | private $url; 34 | private $displayname; 35 | private $ctag; 36 | private $calendar_id; 37 | private $rgba_color; 38 | private $rbg_color; 39 | private $order; 40 | 41 | function __construct ( $url, $displayname = null, $ctag = null, $calendar_id = null, $rbg_color = null, $order = null ) { 42 | $this->url = $url; 43 | $this->displayname = $displayname; 44 | $this->ctag = $ctag; 45 | $this->calendar_id = $calendar_id; 46 | $this->rbg_color = $rbg_color; 47 | $this->order = $order; 48 | } 49 | 50 | function __toString () { 51 | return( '(URL: '.$this->url.' Ctag: '.$this->ctag.' Displayname: '.$this->displayname .')'. "\n" ); 52 | } 53 | 54 | // Getters 55 | 56 | function getURL () { 57 | return $this->url; 58 | } 59 | 60 | function getDisplayName () { 61 | return $this->displayname; 62 | } 63 | 64 | function getCTag () { 65 | return $this->ctag; 66 | } 67 | 68 | function getCalendarID () { 69 | return $this->calendar_id; 70 | } 71 | 72 | function getRBGcolor () { 73 | return $this->rbg_color; 74 | } 75 | 76 | function getOrder () { 77 | return $this->order; 78 | } 79 | 80 | 81 | // Setters 82 | 83 | function setURL ( $url ) { 84 | $this->url = $url; 85 | } 86 | 87 | function setDisplayName ( $displayname ) { 88 | $this->displayname = $displayname; 89 | } 90 | 91 | function setCtag ( $ctag ) { 92 | $this->ctag = $ctag; 93 | } 94 | 95 | function setCalendarID ( $calendar_id ) { 96 | $this->calendar_id = $calendar_id; 97 | } 98 | 99 | function setRBGcolor ( $rbg_color ) { 100 | $this->rbg_color = $rbg_color; 101 | } 102 | 103 | function setOrder ( $order ) { 104 | $this->order = $order; 105 | } 106 | } 107 | 108 | ?> -------------------------------------------------------------------------------- /src/CalDAVException.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * This class is an extension to the Exception-class, to store and report additional data in the case 8 | * of a problem. 9 | * For debugging purposes, just sorround all of your SimpleCalDAVClient-Code with try { ... } catch (Exception $e) { echo $e->__toString(); } 10 | * 11 | * @package simpleCalDAV 12 | * 13 | */ 14 | 15 | namespace it\thecsea\simple_caldav_client; 16 | 17 | class CalDAVException extends \Exception { 18 | private $requestHeader; 19 | private $requestBody; 20 | private $responseHeader; 21 | private $responseBody; 22 | 23 | public function __construct($message, $client, $code = 0, Exception $previous = null) { 24 | parent::__construct($message, $code, $previous); 25 | 26 | $this->requestHeader = $client->GetHttpRequest(); 27 | $this->requestBody = $client->GetBody(); 28 | $this->responseHeader = $client->GetResponseHeaders(); 29 | $this->responseBody = $client->GetResponseBody(); 30 | } 31 | 32 | public function __toString() { 33 | $string = ''; 34 | $dom = new \DOMDocument(); 35 | $dom->preserveWhiteSpace = FALSE; 36 | $dom->formatOutput = TRUE; 37 | 38 | $string .= '
';
39 |         $string .= 'Exception: '.$this->getMessage().'



'; 40 | $string .= 'If you think there is a bug in SimpleCalDAV, please report the following information on github or send it at palm.michael@gmx.de.


'; 41 | $string .= '
For debugging purposes:
'; 42 | $string .= '
last request:

'; 43 | 44 | $string .= $this->requestHeader; 45 | 46 | if(!empty($this->requestBody)) { 47 | 48 | if(!preg_match( '#^Content-type:.*?text/calendar.*?$#', $this->requestHeader, $matches)) { 49 | $dom->loadXML($this->requestBody); 50 | $string .= htmlentities($dom->saveXml()); 51 | } 52 | 53 | else $string .= htmlentities($this->requestBody).'

'; 54 | } 55 | 56 | $string .= '
last response:

'; 57 | 58 | $string .= $this->responseHeader; 59 | 60 | if(!empty($this->responseBody)) { 61 | if(!preg_match( '#^Content-type:.*?text/calendar.*?$#', $this->responseHeader, $matches)) { 62 | $dom->loadXML($this->responseBody); 63 | $string .= htmlentities($dom->saveXml()); 64 | } 65 | 66 | else $string .= htmlentities($this->responseBody); 67 | } 68 | 69 | $string .= '

'; 70 | 71 | $string .= 'Trace:

'.$this->getTraceAsString(); 72 | 73 | $string .= '
'; 74 | 75 | return $string; 76 | } 77 | 78 | public function getRequestHeader() { 79 | return $this->requestHeader; 80 | } 81 | 82 | public function getrequestBody() { 83 | return $this->requestBody; 84 | } 85 | 86 | public function getResponseHeader() { 87 | return $this->responseHeader; 88 | } 89 | 90 | public function getresponseBody() { 91 | return $this->responseBody; 92 | } 93 | } 94 | 95 | ?> 96 | -------------------------------------------------------------------------------- /src/includes/Translation.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright Catalyst IT Ltd 8 | * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later 9 | */ 10 | 11 | if ( !function_exists('i18n') ) { 12 | /** 13 | * Mark a string as being internationalized. This is a semaphore method; it 14 | * does nothing but it allows us to easily identify strings that require 15 | * translation. Generally this is used to mark strings that will be stored 16 | * in the database (like descriptions of permissions). 17 | * 18 | * AWL uses GNU gettext for internationalization (i18n) and localization (l10n) of 19 | * text presented to the user. Gettext needs to know about all places involving strings, 20 | * that must be translated. Mark any place, where localization at runtime shall take place 21 | * by using the function translate(). 22 | * 23 | * In the help I have used 'xlate' rather than 'translate' and 'x18n' rather than 'i18n' 24 | * so that the tools skip this particular file for translation :-) 25 | * 26 | * E.g. instead of: 27 | * print 'TEST to be displayed in different languages'; 28 | * use: 29 | * print xlate('TEST to be displayed in different languages'); 30 | * and you are all set for pure literals. The translation teams will receive that literal 31 | * string as a job to translate and will translate it (when the message is clear enough). 32 | * At runtime the message is then localized when printed. 33 | * The input string can contain a hint to assist translators: 34 | * print xlate('TT '); 35 | * The hint portion of the string will not be printed. 36 | * 37 | * But consider this case: 38 | * $message_to_be_localized = 'TEST to be displayed in different languages'; 39 | * print xlate($message_to_be_localized); 40 | * 41 | * The translate() function is called in the right place for runtime handling, but there 42 | * is no message at gettext preprocessing time to be given to the translation teams, 43 | * just a variable name. Translation of the variable name would break the code! So all 44 | * places potentially feeding this variable have to be marked to be given to translation 45 | * teams, but not translated at runtime! 46 | * 47 | * This method resolves all such cases. Simply mark the candidates: 48 | * $message_to_be_localized = x18n('TEST to be displayed in different languages'); 49 | * print xlate($message_to_be_localized); 50 | * 51 | * @param string the value 52 | * @return string the same value 53 | */ 54 | function i18n($value) { 55 | return $value; /* Just pass the value through */ 56 | } 57 | } 58 | 59 | 60 | if ( !function_exists('translate') ) { 61 | /** 62 | * Convert a string in English to whatever this user's locale is 63 | */ 64 | if ( function_exists('gettext') ) { 65 | function translate( $en ) { 66 | if ( ! isset($en) || $en == '' ) return $en; 67 | $xl = gettext($en); 68 | dbg_error_log('I18N','Translated =%s= into =%s=', $en, $xl ); 69 | return $xl; 70 | } 71 | } 72 | else { 73 | function translate( $en ) { 74 | return $en; 75 | } 76 | } 77 | } 78 | 79 | 80 | if ( !function_exists('init_gettext') ) { 81 | /** 82 | * Initialise our use of Gettext 83 | */ 84 | function init_gettext( $domain, $location ) { 85 | if ( !function_exists('bindtextdomain') ) return; 86 | bindtextdomain( $domain, $location ); 87 | $codeset = bind_textdomain_codeset( $domain, 'UTF-8' ); 88 | textdomain( $domain ); 89 | dbg_error_log('I18N','Bound domain =%s= to location =%s= using character set =%s=', $domain, $location, $codeset ); 90 | } 91 | } 92 | 93 | 94 | if ( !function_exists('awl_set_locale') ) { 95 | /** 96 | * Set the translation to the user's locale. At this stage all we do is 97 | * call the gettext function. 98 | */ 99 | function awl_set_locale( $locale ) { 100 | global $c; 101 | 102 | if ( !is_array($locale) && ! preg_match('/^[a-z]{2}(_[A-Z]{2})?\./', $locale ) ) { 103 | $locale = array( $locale, $locale.'.UTF-8'); 104 | } 105 | if ( !function_exists('setlocale') ) { 106 | dbg_log_array('WARN','No "setlocale()" function? PHP gettext support missing?' ); 107 | return; 108 | } 109 | if ( $newlocale = setlocale( LC_ALL, $locale) ) { 110 | dbg_error_log('I18N','Set locale to =%s=', $newlocale ); 111 | $c->current_locale = $newlocale; 112 | } 113 | else { 114 | dbg_log_array('I18N','Unsupported locale: ', $locale, false ); 115 | } 116 | } 117 | } 118 | 119 | -------------------------------------------------------------------------------- /example code/example.php: -------------------------------------------------------------------------------- 1 | connect('http://yourServer/baikal/cal.php/calendars/yourUser/yourCalendar', 'username', 'password'); 120 | /* With proxy 121 | $client->connect('http://yourServer/baikal/cal.php/calendars/yourUser/yourCalendar', 'username', 'password', ['proxy_host'=>'http://myproxyip:myproxyport']); 122 | */ 123 | 124 | 125 | $arrayOfCalendars = $client->findCalendars(); // Returns an array of all accessible calendars on the server. 126 | 127 | $client->setCalendar($arrayOfCalendars["myCalendarID"]); // Here: Use the calendar ID of your choice. If you don't know which calendar ID to use, try config/listCalendars.php 128 | 129 | 130 | 131 | 132 | 133 | /* 134 | * You can create calendar objects (e.g. events, todos,...) on the server with create(). 135 | * Just pass a string with the iCalendar-data which should be saved on the server. 136 | * The function returns a CalDAVObject (see CalDAVObject.php) with the stored information about the new object on the server 137 | */ 138 | 139 | $firstNewEventOnServer = $client->create($firstNewEvent); // Creates $firstNewEvent on the server and a CalDAVObject representing the event. 140 | $secondNewEventOnServer = $client->create($secondNewEvent); // Creates $firstNewEvent on the server and a CalDAVObject representing the event. 141 | 142 | 143 | 144 | 145 | 146 | /* 147 | * You can getEvents with getEvents() 148 | */ 149 | $client->getEvents('20140418T103000Z', '20140419T200000Z'); // Returns array($firstNewEventOnServer, $secondNewEventOnServer); 150 | 151 | /* 152 | * An CalDAVObject $o has three attributes 153 | * $o->getHref(): Link to the object on the server 154 | * $o->getData(): The iCalendar-data describing the object 155 | * $o->getEtag(): see CalDAVObject.php 156 | * 157 | * $o->getHref() and $o->getEtag() can be used to change or to delete the object. 158 | * $o->getData() can be processed further on, e.g. printed 159 | */ 160 | 161 | $firstNewEventOnServer = $client->change($firstNewEventOnServer->getHref(),$changedFirstEvent, $firstNewEventOnServer->getEtag()); 162 | // Change the first event on the server from $firstNewEvent to $changedFirstEvent 163 | // and overwrite $firstNewEventOnServer with the new representation of the changed event on the server. 164 | 165 | $events = $client->getEvents('20140418T103000Z', '20140419T200000Z'); // Returns array($secondNewEventOnServer); 166 | 167 | echo $events[0]->getData(); // Prints $secondNewEvent. See CalDAVObject.php 168 | 169 | $client->delete($secondNewEventOnServer->getHref(), $secondNewEventOnServer->getEtag()); // Deletes the second new event from the server. 170 | 171 | $client->getEvents('20140418T103000Z', '20140419T200000Z'); // Returns an empty array 172 | 173 | 174 | 175 | 176 | 177 | /* 178 | * You can create custom queries to the server via CalDAVFilter. See CalDAVFilter.php 179 | */ 180 | 181 | $filter = new CalDAVFilter("VEVENT"); 182 | $filter->mustInclude("SUMMARY"); // Should include a SUMMARY 183 | $filter->mustInclude("PRIORITY", TRUE); // Should not include a PRIORITY 184 | $filter->mustIncludeMatchSubstr("DESCRIPTION", "ExampleDescription2", TRUE); // "ExampleDescription1" should not be a substring of the DESCRIPTION 185 | $filter->mustOverlapWithTimerange(NULL, "20140420T100000Z"); 186 | $events = $client->getCustomReport($filter->toXML()); // Returns array($changedFirstEvent) 187 | 188 | $client->delete($events[0]->getHref(), $events[0]->getEtag()); // Deletes the changed first event from the server. 189 | } 190 | 191 | catch (Exception $e) { 192 | echo $e->__toString(); 193 | } 194 | 195 | ?> -------------------------------------------------------------------------------- /src/CalDAVFilter.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * This class represents a filter, which can be used to get a custom report of 8 | * calendar resources (events, todos, etc.) from the CalDAV-Server 9 | * 10 | * resourceType: The type of resource you want to get. Has to be either 11 | * "VEVENT", "VTODO", "VJOURNAL", "VFREEBUSY" or "VALARM". 12 | * You have to decide. 13 | * 14 | * mustInclude(), 15 | * mustIncludeMatchSubstr(), 16 | * mustOverlapWithTimerange(): Use these functions for further filter-options 17 | * 18 | * toXML(): Transforms the filter to xml-code for the server. Used to pass as 19 | * argument for SimpleCalDAVClient->getCustomReport() 20 | * 21 | * @package simpleCalDAV 22 | * 23 | */ 24 | 25 | namespace it\thecsea\simple_caldav_client; 26 | 27 | class CalDAVFilter { 28 | private $resourceType; 29 | private $mustIncludes = array(); 30 | 31 | /* 32 | * @param $type The type of resource you want to get. Has to be either 33 | * "VEVENT", "VTODO", "VJOURNAL", "VFREEBUSY" or "VALARM". 34 | * You have to decide. 35 | */ 36 | public function __construct ( $type ) { 37 | $this->resourceType = $type; 38 | } 39 | 40 | /** 41 | * function mustInclude() 42 | * Specifies that a certin property has to be included. The content of the 43 | * property is irrelevant. 44 | * 45 | * Only call this function and mustIncludeMatchSubstr() once per property! 46 | * 47 | * Examples: 48 | * mustInclude("SUMMARY"); specifies that all returned resources have to 49 | * have the SUMMARY-property. 50 | * mustInclude("LOCATION "); specifies that all returned resources have to 51 | * have the LOCATION-property. 52 | * 53 | * Arguments: 54 | * @param string $field The name of the property. For a full list of valid 55 | * property names see http://www.rfcreader.com/#rfc5545_line3622 56 | * Note that the server might not support all of them. 57 | * @param bool $inverse Makes the effect inverse: The resource must NOT include 58 | * the property $field 59 | */ 60 | public function mustInclude ( $field, $inverse = FALSE ) { 61 | $this->mustIncludes[] = array("mustInclude", $field, $inverse); 62 | } 63 | 64 | /** 65 | * function mustIncludeMatchSubstr() 66 | * Specifies that a certin property has to be included and that its value 67 | * has to match a given substring. 68 | * 69 | * Only call this function and mustInclude() once per property! 70 | * 71 | * Examples: 72 | * mustIncludeMatchSubstr("SUMMARY", "a part of the summary"); would return 73 | * a resource with "SUMMARY:This is a part of the summary" included, but no 74 | * resource with "SUMMARY:This is a part of the". 75 | * 76 | * Arguments: 77 | * @param string $field The name of the property. For a full list of valid 78 | * property names see http://www.rfcreader.com/#rfc5545_line3622 79 | * Note that the server might not support all of them. 80 | * @param string $substring Substring to match against the value of the property. 81 | * @param bool $inverse Makes the effect inverse: The property value must NOT 82 | * include the $substring 83 | */ 84 | public function mustIncludeMatchSubstr ( $field, $substring, $inverse = FALSE ) { 85 | $this->mustIncludes[] = array("mustIncludeMatchSubstr", $field, $substring, $inverse); 86 | } 87 | 88 | /** 89 | * function mustOverlapWithTimerange() 90 | * Specifies that the resource has to overlap with a given timerange. 91 | * @see http://www.rfcreader.com/#rfc4791_line3944 92 | * 93 | * Only call this function once per CalDAVFilter-object! 94 | * 95 | * Arguments: 96 | * @param string $start The starting point of the time interval. Must be in the format yyyymmddThhmmssZ and should be in 97 | * GMT. If omitted the value is set to -infinity. 98 | * @param string $end The end point of the time interval. Must be in the format yyyymmddThhmmssZ and should be in 99 | * GMT. If omitted the value is set to +infinity. 100 | */ 101 | public function mustOverlapWithTimerange ( $start = NULL, $end = NULL) { 102 | // Are $start and $end in the correct format? 103 | if ( ( isset($start) and ! preg_match( '#^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ$#', $start, $matches ) ) 104 | or ( isset($end) and ! preg_match( '#^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ$#', $end, $matches ) ) ) 105 | { 106 | trigger_error('$start or $end are in the wrong format. They must have the format yyyymmddThhmmssZ and should be in GMT', E_USER_ERROR); 107 | } 108 | 109 | $this->mustIncludes[] = array("mustOverlapWithTimerange", $start, $end); 110 | } 111 | 112 | /** 113 | * Transforms the filter to xml-code for the server. Used to pass as 114 | * argument for SimpleCalDAVClient->getCustomReport() 115 | * 116 | * @return string 117 | * 118 | * Example: 119 | * $simpleCalDAVClient->getCustomReport($filter->toXML()); 120 | * 121 | * @see SimpleCalDAVClient.php 122 | */ 123 | public function toXML () { 124 | $xml = ''; 125 | 126 | foreach($this->mustIncludes as $filter) { 127 | switch($filter[0]) { 128 | case "mustInclude": 129 | $xml .= ''; 138 | break; 139 | 140 | case "mustOverlapWithTimerange": 141 | if($this->resourceType == "VTODO") $xml .= ''; 142 | $xml .= 'resourceType == "VTODO") $xml .= ''; 147 | break; 148 | } 149 | } 150 | 151 | $xml .= ''; 152 | 153 | return $xml; 154 | } 155 | } 156 | 157 | ?> -------------------------------------------------------------------------------- /src/includes/XMLDocument.php: -------------------------------------------------------------------------------- 1 | 8 | * @copyright Morphoss Ltd - http://www.morphoss.com/ 9 | * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LGPL version 3 or later 10 | * 11 | */ 12 | 13 | namespace it\thecsea\simple_caldav_client\includes; 14 | 15 | 16 | /** 17 | * A class for XML Documents which will contain namespaced XML elements 18 | * 19 | * @package awl 20 | */ 21 | #[\AllowDynamicProperties] 22 | class XMLDocument { 23 | 24 | /**#@+ 25 | * @access private 26 | */ 27 | /** 28 | * holds the namespaces which this document has been configured for. 29 | * @var namespaces 30 | */ 31 | private $namespaces; 32 | 33 | /** 34 | * holds the prefixes which are shorthand for the namespaces. 35 | * @var prefixes 36 | */ 37 | private $prefixes; 38 | 39 | /** 40 | * Holds the root document for the tree 41 | * @var root 42 | */ 43 | private $root; 44 | 45 | /** 46 | * Simple XMLDocument constructor 47 | * 48 | * @param array $namespaces An array of 'namespace' => 'prefix' pairs, where the prefix is used as a short form for the namespace. 49 | */ 50 | function __construct( $namespaces = null ) { 51 | $this->namespaces = array(); 52 | $this->prefixes = array(); 53 | if ( $namespaces != null ) { 54 | foreach( $namespaces AS $ns => $prefix ) { 55 | $this->namespaces[$ns] = $prefix; 56 | $this->prefixes[$prefix] = $prefix; 57 | } 58 | } 59 | $this->next_prefix = 0; 60 | } 61 | 62 | /** 63 | * Add a new namespace to the document, optionally specifying it's short prefix 64 | * 65 | * @param string $namespace The full namespace name to be added 66 | * @param string $prefix An optional short form for the namespace. 67 | */ 68 | function AddNamespace( $namespace, $prefix = null ) { 69 | if ( !isset($this->namespaces[$namespace]) ) { 70 | if ( isset($prefix) && ($prefix == "" || isset($this->prefixes[$prefix])) ) $prefix = null; 71 | if ( $prefix == null ) { 72 | // Try and build a prefix based on the first alphabetic character of the last element of the namespace 73 | if ( preg_match('/^(.*):([^:]+)$/', $namespace, $matches) ) { 74 | $alpha = preg_replace( '/[^a-z]/i', '', $matches[2] ); 75 | $prefix = strtoupper(substr($alpha,0,1)); 76 | } 77 | else { 78 | $prefix = 'X'; 79 | } 80 | $i = ""; 81 | if ( isset($this->prefixes[$prefix]) ) { 82 | for ( $i=1; $i<10 && isset($this->prefixes["$prefix$i"]); $i++ ) { 83 | } 84 | } 85 | if ( isset($this->prefixes["$prefix$i"]) ) { 86 | dbg_error_log("ERROR", "Cannot find a free prefix for this namespace"); 87 | exit; 88 | } 89 | $prefix = "$prefix$i"; 90 | dbg_error_log("XMLDocument", "auto-assigning prefix of '%s' for ns of '%s'", $prefix, $namespace ); 91 | } 92 | else if ( $prefix == "" || isset($this->prefixes[$prefix]) ) { 93 | dbg_error_log("ERROR", "Cannot assign the same prefix to two different namespaces"); 94 | exit; 95 | } 96 | 97 | $this->prefixes[$prefix] = $prefix; 98 | $this->namespaces[$namespace] = $prefix; 99 | } 100 | else { 101 | if ( isset($this->namespaces[$namespace]) && $this->namespaces[$namespace] != $prefix ) { 102 | dbg_error_log("ERROR", "Cannot use the same namespace with two different prefixes"); 103 | exit; 104 | } 105 | $this->prefixes[$prefix] = $prefix; 106 | $this->namespaces[$namespace] = $prefix; 107 | } 108 | } 109 | 110 | /** 111 | * Return the default namespace for this document 112 | */ 113 | function DefaultNamespace() { 114 | foreach( $this->namespaces AS $k => $v ) { 115 | if ( $v == '' ) { 116 | return $k; 117 | } 118 | } 119 | return ''; 120 | } 121 | 122 | /** 123 | * Return a tag with namespace stripped and replaced with a short form, and the ns added to the document. 124 | * 125 | */ 126 | function GetXmlNsArray() { 127 | 128 | $ns = array(); 129 | foreach( $this->namespaces AS $n => $p ) { 130 | if ( $p == "" ) $ns["xmlns"] = $n; else $ns["xmlns:$p"] = $n; 131 | } 132 | 133 | return $ns; 134 | } 135 | 136 | 137 | /** 138 | * Return a tag with namespace stripped and replaced with a short form, and the ns added to the document. 139 | * 140 | * @param string $in_tag The tag we want a namespace prefix on. 141 | * @param string $namespace The namespace we want it in (which will be parsed from $in_tag if not present 142 | * @param string $prefix The prefix we would like to use. Leave it out and one will be assigned. 143 | * 144 | * @return string The tag with a namespace prefix consistent with previous tags in this namespace. 145 | */ 146 | function Tag( $in_tag, $namespace=null, $prefix=null ) { 147 | 148 | if ( $namespace == null ) { 149 | // Attempt to split out from namespace:tag 150 | if ( preg_match('/^(.*):([^:]+)$/', $in_tag, $matches) ) { 151 | $namespace = $matches[1]; 152 | $tag = $matches[2]; 153 | } 154 | else { 155 | // There is nothing we can do here 156 | return $in_tag; 157 | } 158 | } 159 | else { 160 | $tag = $in_tag; 161 | } 162 | 163 | if ( !isset($this->namespaces[$namespace]) ) { 164 | $this->AddNamespace( $namespace, $prefix ); 165 | } 166 | $prefix = $this->namespaces[$namespace]; 167 | 168 | return $prefix . ($prefix == "" ? "" : ":") . $tag; 169 | } 170 | 171 | static public $ns_dav = 'DAV:'; 172 | static public $ns_caldav = 'urn:ietf:params:xml:ns:caldav'; 173 | static public $ns_carddav = 'urn:ietf:params:xml:ns:carddav'; 174 | static public $ns_calendarserver = 'http://calendarserver.org/ns/'; 175 | 176 | /** 177 | * Special helper for namespaced tags. 178 | * 179 | * @param object $element The tag are adding a new namespaced element to 180 | * @param string $tag the tag name, possibly prefixed with the namespace 181 | * @param mixed $content The content of the tag 182 | * @param array $attributes An array of key/value pairs of attributes. 183 | * @param string $namespace The namespace for the tag 184 | * 185 | */ 186 | function NSElement( &$element, $in_tag, $content=false, $attributes=false, $namespace=null ) { 187 | if ( $namespace == null && preg_match('/^(.*):([^:]+)$/', $in_tag, $matches) ) { 188 | $namespace = $matches[1]; 189 | if ( preg_match('{^[A-Z][A-Z0-9]*$}', $namespace ) ) { 190 | throw new Exception("Dodgy looking namespace from '".$in_tag."'!"); 191 | } 192 | $tag = $matches[2]; 193 | } 194 | else { 195 | $tag = $in_tag; 196 | if ( isset($namespace) ) { 197 | $tag = str_replace($namespace.':', '', $tag); 198 | } 199 | } 200 | 201 | if ( isset($namespace) && !isset($this->namespaces[$namespace]) ) $this->AddNamespace( $namespace ); 202 | return $element->NewElement( $tag, $content, $attributes, $namespace ); 203 | } 204 | 205 | 206 | /** 207 | * Special helper for tags in the DAV: namespace. 208 | * 209 | * @param object $element The tag are adding a new namespaced element to 210 | * @param string $tag the tag name 211 | * @param mixed $content The content of the tag 212 | * @param array $attributes An array of key/value pairs of attributes. 213 | */ 214 | function DAVElement( &$element, $tag, $content=false, $attributes=false ) { 215 | if ( !isset($this->namespaces[self::$ns_dav]) ) $this->AddNamespace( self::$ns_dav, '' ); 216 | return $this->NSElement( $element, $tag, $content, $attributes, self::$ns_dav ); 217 | } 218 | 219 | /** 220 | * Special helper for tags in the urn:ietf:params:xml:ns:caldav namespace. 221 | * 222 | * @param object $element The tag are adding a new namespaced element to 223 | * @param string $tag the tag name 224 | * @param mixed $content The content of the tag 225 | * @param array $attributes An array of key/value pairs of attributes. 226 | */ 227 | function CalDAVElement( &$element, $tag, $content=false, $attributes=false ) { 228 | if ( !isset($this->namespaces[self::$ns_caldav]) ) $this->AddNamespace( self::$ns_caldav, 'C' ); 229 | return $this->NSElement( $element, $tag, $content, $attributes, self::$ns_caldav ); 230 | } 231 | 232 | 233 | /** 234 | * Special helper for tags in the urn:ietf:params:xml:ns:carddav namespace. 235 | * 236 | * @param object $element The tag are adding a new namespaced element to 237 | * @param string $tag the tag name 238 | * @param mixed $content The content of the tag 239 | * @param array $attributes An array of key/value pairs of attributes. 240 | */ 241 | function CardDAVElement( &$element, $tag, $content=false, $attributes=false ) { 242 | if ( !isset($this->namespaces[self::$ns_carddav]) ) $this->AddNamespace( self::$ns_carddav, 'VC' ); 243 | return $this->NSElement( $element, $tag, $content, $attributes, self::$ns_carddav ); 244 | } 245 | 246 | 247 | /** 248 | * Special helper for tags in the urn:ietf:params:xml:ns:caldav namespace. 249 | * 250 | * @param object $element The tag are adding a new namespaced element to 251 | * @param string $tag the tag name 252 | * @param mixed $content The content of the tag 253 | * @param array $attributes An array of key/value pairs of attributes. 254 | */ 255 | function CalendarserverElement( &$element, $tag, $content=false, $attributes=false ) { 256 | if ( !isset($this->namespaces[self::$ns_calendarserver]) ) $this->AddNamespace( self::$ns_calendarserver, 'A' ); 257 | return $this->NSElement( $element, $tag, $content, $attributes, self::$ns_calendarserver ); 258 | } 259 | 260 | 261 | /** 262 | * @param string $in_tag The tag name of the new element, possibly namespaced 263 | * @param mixed $content Either a string of content, or an array of sub-elements 264 | * @param array $attributes An array of attribute name/value pairs 265 | * @param array $xmlns An XML namespace specifier 266 | */ 267 | function NewXMLElement( $in_tag, $content=false, $attributes=false, $xmlns=null ) { 268 | if ( $xmlns == null && preg_match('/^(.*):([^:]+)$/', $in_tag, $matches) ) { 269 | $xmlns = $matches[1]; 270 | $tagname = $matches[2]; 271 | } 272 | else { 273 | $tagname = $in_tag; 274 | } 275 | 276 | if ( isset($xmlns) && !isset($this->namespaces[$xmlns]) ) $this->AddNamespace( $xmlns ); 277 | return new XMLElement($tagname, $content, $attributes, $xmlns ); 278 | } 279 | 280 | /** 281 | * Render the document tree into (nicely formatted) XML 282 | * 283 | * @param mixed $root A root XMLElement or a tagname to create one with the remaining parameters. 284 | * @param mixed $content Either a string of content, or an array of sub-elements 285 | * @param array $attributes An array of attribute name/value pairs 286 | * @param array $xmlns An XML namespace specifier 287 | * 288 | * @return A rendered namespaced XML document. 289 | */ 290 | function Render( $root, $content=false, $attributes=false, $xmlns=null ) { 291 | if ( is_object($root) ) { 292 | /** They handed us a pre-existing object. We'll just use it... */ 293 | $this->root = $root; 294 | } 295 | else { 296 | /** We got a tag name, so we need to create the root element */ 297 | $this->root = $this->NewXMLElement( $root, $content, $attributes, $xmlns ); 298 | } 299 | 300 | /** 301 | * Add our namespace attributes here. 302 | */ 303 | foreach( $this->namespaces AS $n => $p ) { 304 | $this->root->SetAttribute( 'xmlns'.($p == '' ? '' : ':') . $p, $n); 305 | } 306 | 307 | /** And render... */ 308 | return $this->root->Render(0,''); 309 | } 310 | 311 | /** 312 | * Return a DAV::href XML element, or an array of them 313 | * @param mixed $url The URL (or array of URLs) to be wrapped in DAV::href tags 314 | * 315 | * @return XMLElement The newly created XMLElement object. 316 | */ 317 | function href($url) { 318 | if ( is_array($url) ) { 319 | $set = array(); 320 | foreach( $url AS $href ) { 321 | $set[] = $this->href( $href ); 322 | } 323 | return $set; 324 | } 325 | if ( preg_match('[@+ ]',$url) ) { 326 | trace_bug('URL "%s" was not encoded before call to XMLDocument::href()', $url ); 327 | $url = str_replace( '%2F', '/', rawurlencode($url)); 328 | } 329 | return $this->NewXMLElement('href', $url, false, 'DAV:'); 330 | } 331 | 332 | } 333 | 334 | 335 | -------------------------------------------------------------------------------- /src/includes/XMLElement.php: -------------------------------------------------------------------------------- 1 | 8 | * @copyright Catalyst .Net Ltd, Morphoss Ltd 9 | * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LGPL version 3 or later 10 | */ 11 | 12 | namespace it\thecsea\simple_caldav_client\includes; 13 | 14 | require_once(__DIR__.'/AWLUtilities.php'); 15 | 16 | /** 17 | * A class for XML elements which may have attributes, or contain 18 | * other XML sub-elements 19 | * 20 | * @package awl 21 | */ 22 | class XMLElement { 23 | protected $tagname; 24 | protected $xmlns; 25 | protected $attributes; 26 | protected $content; 27 | protected $_parent; 28 | 29 | /** 30 | * Constructor - nothing fancy as yet. 31 | * 32 | * @param string $tagname The tag name of the new element 33 | * @param mixed $content Either a string of content, or an array of sub-elements 34 | * @param array $attributes An array of attribute name/value pairs 35 | * @param string $xmlns An XML namespace specifier 36 | */ 37 | function __construct( $tagname, $content=false, $attributes=false, $xmlns=null ) { 38 | $this->tagname=$tagname; 39 | if ( gettype($content) == "object" ) { 40 | // Subtree to be parented here 41 | $this->content = array(&$content); 42 | } 43 | else { 44 | // Array or text 45 | $this->content = $content; 46 | } 47 | $this->attributes = $attributes; 48 | if ( isset($xmlns) ) { 49 | $this->xmlns = $xmlns; 50 | } 51 | else { 52 | if ( preg_match( '{^(.*):([^:]*)$}', $tagname, $matches) ) { 53 | $prefix = $matches[1]; 54 | $tag = $matches[2]; 55 | if ( isset($this->attributes['xmlns:'.$prefix]) ) { 56 | $this->xmlns = $this->attributes['xmlns:'.$prefix]; 57 | } 58 | } 59 | else if ( isset($this->attributes['xmlns']) ) { 60 | $this->xmlns = $this->attributes['xmlns']; 61 | } 62 | } 63 | } 64 | 65 | 66 | /** 67 | * Count the number of elements 68 | * @return int The number of elements 69 | */ 70 | function CountElements( ) { 71 | if ( $this->content === false ) return 0; 72 | if ( is_array($this->content) ) return count($this->content); 73 | if ( $this->content == '' ) return 0; 74 | return 1; 75 | } 76 | 77 | /** 78 | * Set an element attribute to a value 79 | * 80 | * @param string The attribute name 81 | * @param string The attribute value 82 | */ 83 | function SetAttribute($k,$v) { 84 | if ( gettype($this->attributes) != "array" ) $this->attributes = array(); 85 | $this->attributes[$k] = $v; 86 | if ( strtolower($k) == 'xmlns' ) { 87 | $this->xmlns = $v; 88 | } 89 | } 90 | 91 | /** 92 | * Set the whole content to a value 93 | * 94 | * @param mixed The element content, which may be text, or an array of sub-elements 95 | */ 96 | function SetContent($v) { 97 | $this->content = $v; 98 | } 99 | 100 | /** 101 | * Accessor for the tag name 102 | * 103 | * @return string The tag name of the element 104 | */ 105 | function GetTag() { 106 | return $this->tagname; 107 | } 108 | 109 | /** 110 | * Accessor for the full-namespaced tag name 111 | * 112 | * @return string The tag name of the element, prefixed by the namespace 113 | */ 114 | function GetNSTag() { 115 | return (empty($this->xmlns) ? '' : $this->xmlns . ':') . $this->tagname; 116 | } 117 | 118 | /** 119 | * Accessor for a single attribute 120 | * @param string $attr The name of the attribute. 121 | * @return string The value of that attribute of the element 122 | */ 123 | function GetAttribute( $attr ) { 124 | if ( $attr == 'xmlns' ) return $this->xmlns; 125 | if ( isset($this->attributes[$attr]) ) return $this->attributes[$attr]; 126 | return null; 127 | } 128 | 129 | /** 130 | * Accessor for the attributes 131 | * 132 | * @return array The attributes of this element 133 | */ 134 | function GetAttributes() { 135 | return $this->attributes; 136 | } 137 | 138 | /** 139 | * Accessor for the content 140 | * 141 | * @return array The content of this element 142 | */ 143 | function GetContent() { 144 | return $this->content; 145 | } 146 | 147 | /** 148 | * Return an array of elements matching the specified tag, or all elements if no tag is supplied. 149 | * Unlike GetContent() this will always return an array. 150 | * 151 | * @return array The XMLElements within the tree which match this tag 152 | */ 153 | function GetElements( $tag=null, $recursive=false ) { 154 | $elements = array(); 155 | if ( gettype($this->content) == "array" ) { 156 | foreach( $this->content AS $k => $v ) { 157 | if ( empty($tag) || $v->GetNSTag() == $tag ) { 158 | $elements[] = $v; 159 | } 160 | if ( $recursive ) { 161 | $elements = $elements + $v->GetElements($tag,true); 162 | } 163 | } 164 | } 165 | else if ( empty($tag) || (isset($v->content->tagname) && $v->content->GetNSTag() == $tag) ) { 166 | $elements[] = $this->content; 167 | } 168 | return $elements; 169 | } 170 | 171 | 172 | /** 173 | * Return an array of elements matching the specified path 174 | * 175 | * @return array The XMLElements within the tree which match this tag 176 | */ 177 | function GetPath( $path ) { 178 | $elements = array(); 179 | // printf( "Querying within '%s' for path '%s'\n", $this->tagname, $path ); 180 | if ( !preg_match( '#(/)?([^/]+)(/?.*)$#', $path, $matches ) ) return $elements; 181 | // printf( "Matches: %s -- %s -- %s\n", $matches[1], $matches[2], $matches[3] ); 182 | if ( $matches[2] == '*' || $matches[2] == $this->GetNSTag()) { 183 | if ( $matches[3] == '' ) { 184 | /** 185 | * That is the full path 186 | */ 187 | $elements[] = $this; 188 | } 189 | else if ( gettype($this->content) == "array" ) { 190 | /** 191 | * There is more to the path, so we recurse into that sub-part 192 | */ 193 | foreach( $this->content AS $k => $v ) { 194 | $elements = array_merge( $elements, $v->GetPath($matches[3]) ); 195 | } 196 | } 197 | } 198 | 199 | if ( $matches[1] != '/' && gettype($this->content) == "array" ) { 200 | /** 201 | * If our input $path was not rooted, we recurse further 202 | */ 203 | foreach( $this->content AS $k => $v ) { 204 | $elements = array_merge( $elements, $v->GetPath($path) ); 205 | } 206 | } 207 | // printf( "Found %d within '%s' for path '%s'\n", count($elements), $this->tagname, $path ); 208 | return $elements; 209 | } 210 | 211 | 212 | /** 213 | * Add a sub-element 214 | * 215 | * @param object An XMLElement to be appended to the array of sub-elements 216 | */ 217 | function AddSubTag(&$v) { 218 | if ( gettype($this->content) != "array" ) $this->content = array(); 219 | $this->content[] =& $v; 220 | return count($this->content); 221 | } 222 | 223 | /** 224 | * Add a new sub-element 225 | * 226 | * @param string The tag name of the new element 227 | * @param mixed Either a string of content, or an array of sub-elements 228 | * @param array An array of attribute name/value pairs 229 | * 230 | * @return objectref A reference to the new XMLElement 231 | */ 232 | function &NewElement( $tagname, $content=false, $attributes=false, $xmlns=null ) { 233 | if ( gettype($this->content) != "array" ) $this->content = array(); 234 | $element = new XMLElement($tagname,$content,$attributes,$xmlns); 235 | $this->content[] =& $element; 236 | return $element; 237 | } 238 | 239 | 240 | /** 241 | * Render just the internal content 242 | * 243 | * @return string The content of this element, as a string without this element wrapping it. 244 | */ 245 | function RenderContent($indent=0, $nslist=null, $force_xmlns=false ) { 246 | $r = ""; 247 | if ( is_array($this->content) ) { 248 | /** 249 | * Render the sub-elements with a deeper indent level 250 | */ 251 | $r .= "\n"; 252 | foreach( $this->content AS $k => $v ) { 253 | if ( is_object($v) ) { 254 | $r .= $v->Render($indent+1, "", $nslist, $force_xmlns); 255 | } 256 | } 257 | $r .= substr(" ",0,$indent); 258 | } 259 | else { 260 | /** 261 | * Render the content, with special characters escaped 262 | * 263 | */ 264 | if(strpos($this->content, 'content, ']]>')===strlen($this->content)-3) 265 | $r .= '', ']]]]>', substr($this->content, 9, -3)) . ']]>'; 266 | else if ( defined('ENT_XML1') && defined('ENT_DISALLOWED') ) 267 | // Newer PHP versions allow specifying ENT_XML1, but default to ENT_HTML401. Go figure. #PHPWTF 268 | $r .= htmlspecialchars($this->content, ENT_NOQUOTES | ENT_XML1 | ENT_DISALLOWED ); 269 | // Need to work out exactly how to do this in PHP. 270 | // else if ( preg_match('{^[\t\n\r\x0020-\xD7FF\xE000-\xFFFD\x10000-\x10FFFF]+$}u', utf8ToUnicode($this->content)) ) 271 | // $r .= 'content . ']]>'; 272 | else 273 | // Older PHP versions default to ENT_XML1. 274 | $r .= htmlspecialchars($this->content, ENT_NOQUOTES ); 275 | } 276 | return $r; 277 | } 278 | 279 | 280 | /** 281 | * Render the document tree into (nicely formatted) XML 282 | * 283 | * @param int The indenting level for the pretty formatting of the element 284 | */ 285 | function Render($indent=0, $xmldef="", $nslist=null, $force_xmlns=false) { 286 | $r = ( $xmldef == "" ? "" : $xmldef."\n"); 287 | 288 | $attr = ""; 289 | $tagname = $this->tagname; 290 | $xmlns_done = false; 291 | if ( gettype($this->attributes) == "array" ) { 292 | /** 293 | * Render the element attribute values 294 | */ 295 | foreach( $this->attributes AS $k => $v ) { 296 | if ( preg_match('#^xmlns(:?(.+))?$#', $k, $matches ) ) { 297 | // if ( $force_xmlns ) printf( "1: %s: %s\n", $this->tagname, $this->xmlns ); 298 | if ( !isset($nslist) ) $nslist = array(); 299 | $prefix = (isset($matches[2]) ? $matches[2] : ''); 300 | if ( isset($nslist[$v]) && $nslist[$v] == $prefix ) continue; // No need to include in list as it's in a wrapping element 301 | $nslist[$v] = $prefix; 302 | if ( !isset($this->xmlns) ) $this->xmlns = $v; 303 | $xmlns_done = true; 304 | } 305 | $attr .= sprintf( ' %s="%s"', $k, htmlspecialchars($v) ); 306 | } 307 | } 308 | if ( isset($this->xmlns) && isset($nslist[$this->xmlns]) && $nslist[$this->xmlns] != '' ) { 309 | // if ( $force_xmlns ) printf( "2: %s: %s\n", $this->tagname, $this->xmlns ); 310 | $tagname = $nslist[$this->xmlns] . ':' . $tagname; 311 | if ( $force_xmlns ) $attr .= sprintf( ' xmlns="%s"', $this->xmlns); 312 | } 313 | else if ( isset($this->xmlns) && !isset($nslist[$this->xmlns]) && gettype($this->attributes) == 'array' && !isset($this->attributes[$this->xmlns]) ) { 314 | // if ( $force_xmlns ) printf( "3: %s: %s\n", $this->tagname, $this->xmlns ); 315 | $attr .= sprintf( ' xmlns="%s"', $this->xmlns); 316 | } 317 | else if ( $force_xmlns && isset($this->xmlns) && ! $xmlns_done ) { 318 | // printf( "4: %s: %s\n", $this->tagname, $this->xmlns ); 319 | $attr .= sprintf( ' xmlns="%s"', $this->xmlns); 320 | } 321 | 322 | $r .= substr(" ",0,$indent) . '<' . $tagname . $attr; 323 | 324 | if ( (is_array($this->content) && count($this->content) > 0) || (!is_array($this->content) && strlen($this->content) > 0) ) { 325 | $r .= ">"; 326 | $r .= $this->RenderContent($indent,$nslist,$force_xmlns); 327 | $r .= '\n"; 328 | } 329 | else { 330 | $r .= "/>\n"; 331 | } 332 | return $r; 333 | } 334 | 335 | 336 | function __tostring() { 337 | return $this->Render(); 338 | } 339 | } 340 | 341 | 342 | /** 343 | * Rebuild an XML tree in our own style from the parsed XML tags using 344 | * a tail-recursive approach. 345 | * 346 | * @param array $xmltags An array of XML tags we get from using the PHP XML parser 347 | * @param intref &$start_from A pointer to our current integer offset into $xmltags 348 | * @return mixed Either a single XMLElement, or an array of XMLElement objects. 349 | */ 350 | function BuildXMLTree( $xmltags, &$start_from ) { 351 | $content = array(); 352 | 353 | if ( !isset($start_from) ) $start_from = 0; 354 | 355 | for( $i=0; $i < 50000 && isset($xmltags[$start_from]); $i++) { 356 | $tagdata = $xmltags[$start_from++]; 357 | if ( !isset($tagdata) || !isset($tagdata['tag']) || !isset($tagdata['type']) ) break; 358 | if ( $tagdata['type'] == "close" ) break; 359 | $xmlns = null; 360 | $tag = $tagdata['tag']; 361 | if ( preg_match( '{^(.*):([^:]*)$}', $tag, $matches) ) { 362 | $xmlns = $matches[1]; 363 | $tag = $matches[2]; 364 | } 365 | $attributes = ( isset($tagdata['attributes']) ? $tagdata['attributes'] : false ); 366 | if ( $tagdata['type'] == "open" ) { 367 | $subtree = BuildXMLTree( $xmltags, $start_from ); 368 | $content[] = new XMLElement($tag, $subtree, $attributes, $xmlns ); 369 | } 370 | else if ( $tagdata['type'] == "complete" ) { 371 | $value = ( isset($tagdata['value']) ? $tagdata['value'] : false ); 372 | $content[] = new XMLElement($tag, $value, $attributes, $xmlns ); 373 | } 374 | } 375 | 376 | /** 377 | * If there is only one element, return it directly, otherwise return the 378 | * array of them 379 | */ 380 | if ( count($content) == 1 ) { 381 | return $content[0]; 382 | } 383 | return $content; 384 | } 385 | 386 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /src/SimpleCalDAVClient.php: -------------------------------------------------------------------------------- 1 | 7 | * 8 | * simpleCalDAV is a php library that allows you to connect to a calDAV-server to get event-, todo- 9 | * and free/busy-calendar resources from the server, to change them, to delete them, to create new ones, etc. 10 | * simpleCalDAV was made and tested for connections to the CalDAV-server Baikal 0.2.7. But it should work 11 | * with any other CalDAV-server too. 12 | * 13 | * It contains the following functions: 14 | * - connect() 15 | * - findCalendars() 16 | * - setCalendar() 17 | * - create() 18 | * - change() 19 | * - delete() 20 | * - getEvents() 21 | * - getTODOs() 22 | * - getCustomReport() 23 | * 24 | * All of those functions - except the last one - are realy easy to use, self-explanatory and are 25 | * deliverd with a big innitial comment, which explains all needed arguments and the return values. 26 | * 27 | * This library is heavily based on AgenDAV caldav-client-v2.php by Jorge L�pez P�rez which 28 | * again is heavily based on DAViCal caldav-client-v2.php by Andrew McMillan . 29 | * Actually, I hardly added any features. The main point of my work is to make everything straight 30 | * forward and easy to use. You can use simpleCalDAV whithout a deeper understanding of the 31 | * calDAV-protocol. 32 | * 33 | * Requirements of this library are 34 | * - The php extension cURL ( http://www.php.net/manual/en/book.curl.php ) 35 | * - From Andrew�s Web Libraries: ( https://github.com/andrews-web-libraries/awl ) 36 | * - XMLDocument.php 37 | * - XMLElement.php 38 | * - AWLUtilities.php 39 | * 40 | * @package simpleCalDAV 41 | */ 42 | 43 | namespace it\thecsea\simple_caldav_client; 44 | 45 | 46 | class SimpleCalDAVClient { 47 | private $client; 48 | private $url; 49 | 50 | /** 51 | * function connect() 52 | * Connects to a CalDAV-Server. 53 | * 54 | * Arguments: 55 | * @param string $url URL to the CalDAV-server. E.g. http://exam.pl/baikal/cal.php/username/calendername/ 56 | * @param string $user Username to login with 57 | * @param string $pass Password to login with 58 | * @param array $options 59 | * 60 | * Debugging: 61 | * @throws CalDAVException For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); } 62 | */ 63 | function connect ( $url, $user, $pass, $options=[] ) 64 | { 65 | 66 | // Connect to CalDAV-Server and log in 67 | $client = new CalDAVClient($url, $user, $pass, $options); 68 | 69 | // Valid CalDAV-Server? Or is it just a WebDAV-Server? 70 | if( ! $client->isValidCalDAVServer() ) 71 | { 72 | 73 | if( $client->GetHttpResultCode() == '401' ) // unauthorisized 74 | { 75 | throw new CalDAVException('Login failed', $client); 76 | } 77 | 78 | elseif( $client->GetHttpResultCode() == '' ) // can't reach server 79 | { 80 | throw new CalDAVException('Can\'t reach server', $client); 81 | } 82 | 83 | else throw new CalDAVException('Could\'n find a CalDAV-collection under the url', $client); 84 | } 85 | 86 | // Check for errors 87 | if( $client->GetHttpResultCode() != '200' ) { 88 | if( $client->GetHttpResultCode() == '401' ) // unauthorisized 89 | { 90 | throw new CalDAVException('Login failed', $client); 91 | } 92 | 93 | elseif( $client->GetHttpResultCode() == '' ) // can't reach server 94 | { 95 | throw new CalDAVException('Can\'t reach server', $client); 96 | } 97 | 98 | else // Unknown status 99 | { 100 | throw new CalDAVException('Recieved unknown HTTP status while checking the connection after establishing it', $client); 101 | } 102 | } 103 | 104 | $this->client = $client; 105 | } 106 | 107 | /** 108 | * function findCalendars() 109 | * 110 | * Requests a list of all accessible calendars on the server 111 | * 112 | * Return value: 113 | * @return CalDAVCalendar[] an array of CalDAVCalendar-Objects (see CalDAVCalendar.php), representing all calendars accessible by the current principal (user). 114 | * 115 | * Debugging: 116 | * @throws CalDAVException 117 | * For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); exit(-1); } 118 | */ 119 | function findCalendars() 120 | { 121 | if(!isset($this->client)) throw new \Exception('No connection. Try connect().'); 122 | 123 | return $this->client->FindCalendars(true); 124 | } 125 | 126 | /** 127 | * function setCalendar() 128 | * 129 | * Sets the actual calendar to work with 130 | * @param CalDAVCalendar $calendar 131 | * 132 | * Debugging: 133 | * @throws CalDAVException 134 | * For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); exit(-1); } 135 | */ 136 | function setCalendar ( CalDAVCalendar $calendar ) 137 | { 138 | if(!isset($this->client)) throw new \Exception('No connection. Try connect().'); 139 | 140 | $this->client->SetCalendar($this->client->first_url_part.$calendar->getURL()); 141 | 142 | // Is there a '/' at the end of the calendar_url? 143 | if ( ! preg_match( '#^.*?/$#', $this->client->calendar_url, $matches ) ) { $this->url = $this->client->calendar_url.'/'; } 144 | else { $this->url = $this->client->calendar_url; } 145 | } 146 | 147 | /** 148 | * function create() 149 | * Creates a new calendar resource on the CalDAV-Server (event, todo, etc.). 150 | * 151 | * Arguments: 152 | * @param string $cal iCalendar-data of the resource you want to create. 153 | * Notice: The iCalendar-data contains the unique ID which specifies where the event is being saved. 154 | * 155 | * Return value: 156 | * @return CalDAVObject An CalDAVObject-representation (see CalDAVObject.php) of your created resource 157 | * 158 | * Debugging: 159 | * @throws CalDAVException 160 | * For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); exit(-1); } 161 | */ 162 | function create ( $cal ) 163 | { 164 | // Connection and calendar set? 165 | if(!isset($this->client)) throw new \Exception('No connection. Try connect().'); 166 | if(!isset($this->client->calendar_url)) throw new \Exception('No calendar selected. Try findCalendars() and setCalendar().'); 167 | 168 | // Parse $cal for UID 169 | if (! preg_match( '#^UID:(.*?)\r?\n?$#m', $cal, $matches ) ) { throw new \Exception('Can\'t find UID in $cal'); } 170 | else { $uid = $matches[1]; } 171 | 172 | // Does $this->url.$uid.'.ics' already exist? 173 | $result = $this->client->GetEntryByHref( $this->url.$uid.'.ics' ); 174 | if ( $this->client->GetHttpResultCode() == '200' ) { throw new CalDAVException($this->url.$uid.'.ics already exists. UID not unique?', $this->client); } 175 | else if ( $this->client->GetHttpResultCode() == '404' ); 176 | else throw new CalDAVException('Recieved unknown HTTP status', $this->client); 177 | 178 | // Put it! 179 | $newEtag = $this->client->DoPUTRequest( $this->url.$uid.'.ics', $cal ); 180 | 181 | // PUT-request successfull? 182 | if ( $this->client->GetHttpResultCode() != '201' ) 183 | { 184 | if ( $this->client->GetHttpResultCode() == '204' ) // $url.$uid.'.ics' already existed on server 185 | { 186 | throw new CalDAVException( $this->url.$uid.'.ics already existed. Entry has been overwritten.', $this->client); 187 | } 188 | 189 | else // Unknown status 190 | { 191 | throw new CalDAVException('Recieved unknown HTTP status', $this->client); 192 | } 193 | } 194 | 195 | return new CalDAVObject($this->url.$uid.'.ics', $cal, $newEtag); 196 | } 197 | 198 | /** 199 | * function change() 200 | * Changes a calendar resource (event, todo, etc.) on the CalDAV-Server. 201 | * 202 | * Arguments: 203 | * @param string $href See CalDAVObject.php 204 | * @param string $new_data The new iCalendar-data that should be used to overwrite the old one. 205 | * @param string $etag See CalDAVObject.php 206 | * 207 | * Return value: 208 | * @return CalDAVObject An CalDAVObject-representation (see CalDAVObject.php) of your changed resource 209 | * 210 | * Debugging: 211 | * @throws CalDAVException 212 | * For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); exit(-1); } 213 | */ 214 | function change ( $href, $new_data, $etag ) 215 | { 216 | // Connection and calendar set? 217 | if(!isset($this->client)) throw new \Exception('No connection. Try connect().'); 218 | if(!isset($this->client->calendar_url)) throw new \Exception('No calendar selected. Try findCalendars() and setCalendar().'); 219 | 220 | // Does $href exist? 221 | $result = $this->client->GetEntryByHref($href); 222 | if ( $this->client->GetHttpResultCode() == '200' ); 223 | else if ( $this->client->GetHttpResultCode() == '404' ) throw new CalDAVException('Can\'t find '.$href.' on the server', $this->client); 224 | else throw new CalDAVException('Recieved unknown HTTP status', $this->client); 225 | 226 | // $etag correct? 227 | if($result[0]['etag'] != $etag) { throw new CalDAVException('Wrong entity tag. The entity seems to have changed.', $this->client); } 228 | 229 | // Put it! 230 | $newEtag = $this->client->DoPUTRequest( $href, $new_data, $etag ); 231 | 232 | // PUT-request successfull? 233 | if ( $this->client->GetHttpResultCode() != '204' && $this->client->GetHttpResultCode() != '200' ) 234 | { 235 | throw new CalDAVException('Recieved unknown HTTP status', $this->client); 236 | } 237 | 238 | return new CalDAVObject($href, $new_data, $newEtag); 239 | } 240 | 241 | /** 242 | * function delete() 243 | * Delets an event or a TODO from the CalDAV-Server. 244 | * 245 | * Arguments: 246 | * @param string $href See CalDAVObject.php 247 | * @param string|null $etag See CalDAVObject.php 248 | * 249 | * Debugging: 250 | * @throws CalDAVException 251 | * For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); exit(-1); } 252 | */ 253 | function delete ( $href, $etag = null ) 254 | { 255 | // Connection and calendar set? 256 | if(!isset($this->client)) throw new \Exception('No connection. Try connect().'); 257 | if(!isset($this->client->calendar_url)) throw new \Exception('No calendar selected. Try findCalendars() and setCalendar().'); 258 | 259 | // Does $href exist? 260 | $result = $this->client->GetEntryByHref($href); 261 | if(count($result) == 0) throw new CalDAVException('Can\'t find '.$href.'on server', $this->client); 262 | 263 | if(isset($etag) and !empty($etag)) { 264 | // $etag correct? 265 | if($result[0]['etag'] != $etag) { throw new CalDAVException('Wrong entity tag. The entity seems to have changed.', $this->client); } 266 | } 267 | 268 | // Do the deletion 269 | if(isset($etag) and !empty($etag)) { 270 | $this->client->DoDELETERequest($href, $etag); 271 | } else { 272 | $this->client->DoDELETERequest($href); 273 | } 274 | 275 | // Deletion successfull? 276 | if ( $this->client->GetHttpResultCode() != '200' and $this->client->GetHttpResultCode() != '204' ) 277 | { 278 | throw new CalDAVException('Recieved unknown HTTP status', $this->client); 279 | } 280 | } 281 | 282 | /** 283 | * function getEvents() 284 | * Gets a all events from the CalDAV-Server which lie in a defined time interval. 285 | * 286 | * Arguments: 287 | * @param string|null $start The starting point of the time interval. Must be in the format yyyymmddThhmmssZ and should be in 288 | * GMT. If omitted the value is set to -infinity. 289 | * @param string|null $end The end point of the time interval. Must be in the format yyyymmddThhmmssZ and should be in 290 | * GMT. If omitted the value is set to +infinity. 291 | * 292 | * Return value: 293 | * @return CalDAVObject[] an array of CalDAVObjects (See CalDAVObject.php), representing the found events. 294 | * 295 | * Debugging: 296 | * @throws CalDAVException 297 | * For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); exit(-1); } 298 | */ 299 | function getEvents ( $start = null, $end = null ) 300 | { 301 | // Connection and calendar set? 302 | if(!isset($this->client)) throw new \Exception('No connection. Try connect().'); 303 | if(!isset($this->client->calendar_url)) throw new \Exception('No calendar selected. Try findCalendars() and setCalendar().'); 304 | 305 | // Are $start and $end in the correct format? 306 | if ( ( isset($start) and ! preg_match( '#^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ$#', $start, $matches ) ) 307 | or ( isset($end) and ! preg_match( '#^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ$#', $end, $matches ) ) ) 308 | { trigger_error('$start or $end are in the wrong format. They must have the format yyyymmddThhmmssZ and should be in GMT', E_USER_ERROR); } 309 | 310 | // Get it! 311 | $results = $this->client->GetEvents( $start, $end ); 312 | 313 | // GET-request successfull? 314 | if ( $this->client->GetHttpResultCode() != '207' ) 315 | { 316 | throw new CalDAVException('Recieved unknown HTTP status', $this->client); 317 | } 318 | 319 | // Reformat 320 | $report = array(); 321 | foreach($results as $event) $report[] = new CalDAVObject($this->url.$event['href'], $event['data'], $event['etag']); 322 | 323 | return $report; 324 | } 325 | 326 | /** 327 | * function getEventByGuid( $guid ) 328 | * Gets an events from the CalDAV-Server with specified UID. 329 | * 330 | * Arguments: 331 | * @param string $guid UID of the iCal requested. 332 | * 333 | * Return value: 334 | * @return array an array of arrays containing ['href'], ['etag'] and the iCal in ['data'] for the found event. 335 | * 336 | */ 337 | function getEventByGuid ( $guid ) 338 | { 339 | // Connection and calendar set? 340 | if(!isset($this->client)) throw new CalDAVException('No connection. Try connect().', $this->client); 341 | if(!isset($this->client->calendar_url)) throw new CalDAVException('No calendar selected. Try findCalendars() and setCalendar().', $this->client); 342 | 343 | // Get it! 344 | $data = $this->client->GetEntryByUid($guid); 345 | foreach ($data as &$element) { 346 | $element['href'] = $this->client->calendar_url . $element['href']; 347 | unset($element); 348 | } 349 | return $data; 350 | 351 | } 352 | 353 | /** 354 | * function getTODOs() 355 | * Gets a all TODOs from the CalDAV-Server which lie in a defined time interval and match the 356 | * given criteria. 357 | * 358 | * Arguments: 359 | * @param string $start The starting point of the time interval. Must be in the format yyyymmddThhmmssZ and should be in 360 | * GMT. If omitted the value is set to -infinity. 361 | * @param string $end The end point of the time interval. Must be in the format yyyymmddThhmmssZ and should be in 362 | * GMT. If omitted the value is set to +infinity. 363 | * @param bool|null $completed Filter for completed tasks (true) or for uncompleted tasks (false). If omitted, the function will return both. 364 | * @param bool|null $cancelled Filter for cancelled tasks (true) or for uncancelled tasks (false). If omitted, the function will return both. 365 | * 366 | * Return value: 367 | * @return CalDAVObject[] an array of CalDAVObjects (See CalDAVObject.php), representing the found TODOs. 368 | * 369 | * Debugging: 370 | * @throws CalDAVException 371 | * For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); exit(-1); } 372 | */ 373 | function getTODOs ( $start = null, $end = null, $completed = null, $cancelled = null ) 374 | { 375 | // Connection and calendar set? 376 | if(!isset($this->client)) throw new \Exception('No connection. Try connect().'); 377 | if(!isset($this->client->calendar_url)) throw new \Exception('No calendar selected. Try findCalendars() and setCalendar().'); 378 | 379 | // Are $start and $end in the correct format? 380 | if ( ( isset($start) and ! preg_match( '#^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ$#', $start, $matches ) ) 381 | or ( isset($end) and ! preg_match( '#^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ$#', $end, $matches ) ) ) 382 | { 383 | trigger_error('$start or $end are in the wrong format. They must have the format yyyymmddThhmmssZ and should be in GMT', E_USER_ERROR); 384 | } 385 | 386 | // Get it! 387 | $results = $this->client->GetTodos( $start, $end, $completed, $cancelled ); 388 | 389 | // GET-request successfull? 390 | if ( $this->client->GetHttpResultCode() != '207' ) 391 | { 392 | throw new CalDAVException('Recieved unknown HTTP status', $this->client); 393 | } 394 | 395 | // Reformat 396 | $report = array(); 397 | foreach($results as $event) $report[] = new CalDAVObject($this->url.$event['href'], $event['data'], $event['etag']); 398 | 399 | return $report; 400 | } 401 | 402 | /** 403 | * function getCustomReport() 404 | * Sends a custom request to the server 405 | * (Sends a REPORT-request with a custom -tag) 406 | * 407 | * You can either write the filterXML yourself or build an CalDAVFilter-object (see CalDAVFilter.php). 408 | * 409 | * See http://www.rfcreader.com/#rfc4791_line1524 for more information about how to write filters on your own. 410 | * 411 | * Arguments: 412 | * @param string $filterXML The stuff, you want to send encapsulated in the -tag. 413 | * 414 | * Return value: 415 | * @return CalDAVObject[] an array of CalDAVObjects (See CalDAVObject.php), representing the found calendar resources. 416 | * 417 | * Debugging: 418 | * @throws CalDAVException 419 | * For debugging purposes, just sorround everything with try { ... } catch (Exception $e) { echo $e->__toString(); exit(-1); } 420 | */ 421 | function getCustomReport ( $filterXML ) 422 | { 423 | // Connection and calendar set? 424 | if(!isset($this->client)) throw new \Exception('No connection. Try connect().'); 425 | if(!isset($this->client->calendar_url)) throw new \Exception('No calendar selected. Try findCalendars() and setCalendar().'); 426 | 427 | // Get report! 428 | $this->client->SetDepth('1'); 429 | 430 | // Get it! 431 | $results = $this->client->DoCalendarQuery(''.$filterXML.''); 432 | 433 | // GET-request successfull? 434 | if ( $this->client->GetHttpResultCode() != '207' ) 435 | { 436 | throw new CalDAVException('Recieved unknown HTTP status', $this->client); 437 | } 438 | 439 | // Reformat 440 | $report = array(); 441 | foreach($results as $event) $report[] = new CalDAVObject($this->url.$event['href'], $event['data'], $event['etag']); 442 | 443 | return $report; 444 | } 445 | } 446 | 447 | ?> 448 | -------------------------------------------------------------------------------- /src/includes/AWLUtilities.php: -------------------------------------------------------------------------------- 1 | 9 | * @copyright Catalyst IT Ltd, Morphoss Ltd 10 | * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU LGPL version 3 or later 11 | */ 12 | 13 | if ( !function_exists('dbg_error_log') ) { 14 | /** 15 | * Writes a debug message into the error log using printf syntax. If the first 16 | * parameter is "ERROR" then the message will _always_ be logged. 17 | * Otherwise, the first parameter is a "component" name, and will only be logged 18 | * if $c->dbg["component"] is set to some non-null value. 19 | * 20 | * If you want to see every log message then $c->dbg["ALL"] can be set, to 21 | * override the debugging status of the individual components. 22 | * 23 | * @var string $component The component to identify itself, or "ERROR", or "LOG:component" 24 | * @var string $format A format string for the log message 25 | * @var [string $parameter ...] Parameters for the format string. 26 | */ 27 | function dbg_error_log() { 28 | global $c; 29 | $args = func_get_args(); 30 | $type = "DBG"; 31 | $component = array_shift($args); 32 | if ( substr( $component, 0, 3) == "LOG" ) { 33 | // Special escape case for stuff that always gets logged. 34 | $type = 'LOG'; 35 | $component = substr($component,4); 36 | } 37 | else if ( $component == "ERROR" ) { 38 | $type = "***"; 39 | } 40 | else if ( isset($c->dbg["ALL"]) ) { 41 | $type = "ALL"; 42 | } 43 | else if ( !isset($c->dbg[strtolower($component)]) ) return; 44 | 45 | $argc = func_num_args(); 46 | if ( 2 <= $argc ) { 47 | $format = array_shift($args); 48 | } 49 | else { 50 | $format = "%s"; 51 | } 52 | @error_log( $c->sysabbr.": $type: $component:". vsprintf( $format, $args ) ); 53 | } 54 | } 55 | 56 | 57 | if ( !function_exists('fatal') ) { 58 | function fatal() { 59 | global $c; 60 | $args = func_get_args(); 61 | $argc = func_num_args(); 62 | if ( 2 <= $argc ) { 63 | $format = array_shift($args); 64 | } 65 | else { 66 | $format = "%s"; 67 | } 68 | @error_log( $c->sysabbr.": FATAL: $component:". vsprintf( $format, $args ) ); 69 | 70 | @error_log( "================= Stack Trace ===================" ); 71 | 72 | $trace = array_reverse(debug_backtrace()); 73 | array_pop($trace); 74 | foreach( $trace AS $k => $v ) { 75 | @error_log( sprintf(" ===> %s[%d] calls %s%s%s()", 76 | $v['file'], 77 | $v['line'], 78 | (isset($v['class'])?$v['class']:''), 79 | (isset($v['type'])?$v['type']:''), 80 | (isset($v['function'])?$v['function']:'') 81 | )); 82 | } 83 | echo "Fatal Error"; 84 | exit(); 85 | } 86 | } 87 | 88 | 89 | if ( !function_exists('trace_bug') ) { 90 | /** 91 | * Not as sever as a fatal() call, but we want to log and trace it 92 | */ 93 | function trace_bug() { 94 | global $c; 95 | $args = func_get_args(); 96 | $argc = func_num_args(); 97 | if ( 2 <= $argc ) { 98 | $format = array_shift($args); 99 | } 100 | else { 101 | $format = "%s"; 102 | } 103 | @error_log( $c->sysabbr.": BUG: $component:". vsprintf( $format, $args ) ); 104 | 105 | @error_log( "================= Stack Trace ===================" ); 106 | 107 | $trace = array_reverse(debug_backtrace()); 108 | array_pop($trace); 109 | foreach( $trace AS $k => $v ) { 110 | @error_log( sprintf(" ===> %s[%d] calls %s%s%s()", 111 | $v['file'], 112 | $v['line'], 113 | (isset($v['class'])?$v['class']:''), 114 | (isset($v['type'])?$v['type']:''), 115 | (isset($v['function'])?$v['function']:'') 116 | )); 117 | } 118 | } 119 | } 120 | 121 | 122 | if ( !function_exists('apache_request_headers') ) { 123 | /** 124 | * Compatibility so we can use the apache function name and still work with CGI 125 | * @package awl 126 | */ 127 | eval(' 128 | function apache_request_headers() { 129 | foreach($_SERVER as $key=>$value) { 130 | if (substr($key,0,5)=="HTTP_") { 131 | $key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5))))); 132 | $out[$key]=$value; 133 | } 134 | } 135 | return $out; 136 | } 137 | '); 138 | } 139 | 140 | 141 | 142 | if ( !function_exists('dbg_log_array') ) { 143 | /** 144 | * Function to dump an array to the error log, possibly recursively 145 | * 146 | * @var string $component Which component should this log message identify itself from 147 | * @var string $name What name should this array dump identify itself as 148 | * @var array $arr The array to be dumped. 149 | * @var boolean $recursive Should the dump recurse into arrays/objects in the array 150 | */ 151 | function dbg_log_array( $component, $name, $arr, $recursive = false ) { 152 | if ( !isset($arr) || (gettype($arr) != 'array' && gettype($arr) != 'object') ) { 153 | dbg_error_log( $component, "%s: array is not set, or is not an array!", $name); 154 | return; 155 | } 156 | foreach ($arr as $key => $value) { 157 | dbg_error_log( $component, "%s: >>%s<< = >>%s<<", $name, $key, 158 | (gettype($value) == 'array' || gettype($value) == 'object' ? gettype($value) : $value) ); 159 | if ( $recursive && (gettype($value) == 'array' || (gettype($value) == 'object' && "$key" != 'self' && "$key" != 'parent') ) ) { 160 | dbg_log_array( $component, "$name"."[$key]", $value, $recursive ); 161 | } 162 | } 163 | } 164 | } 165 | 166 | 167 | 168 | if ( !function_exists("session_simple_md5") ) { 169 | /** 170 | * Make a plain MD5 hash of a string, identifying the type of hash it is 171 | * 172 | * @param string $instr The string to be salted and MD5'd 173 | * @return string The *MD5* and the MD5 of the string 174 | */ 175 | function session_simple_md5( $instr ) { 176 | global $c; 177 | if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making plain MD5: instr=$instr, md5($instr)=".md5($instr) ); 178 | return ( '*MD5*'. md5($instr) ); 179 | } 180 | } 181 | 182 | 183 | 184 | if ( !function_exists("session_salted_md5") ) { 185 | /** 186 | * Make a salted MD5 string, given a string and (possibly) a salt. 187 | * 188 | * If no salt is supplied we will generate a random one. 189 | * 190 | * @param string $instr The string to be salted and MD5'd 191 | * @param string $salt Some salt to sprinkle into the string to be MD5'd so we don't get the same PW always hashing to the same value. 192 | * @return string The salt, a * and the MD5 of the salted string, as in SALT*SALTEDHASH 193 | */ 194 | function session_salted_md5( $instr, $salt = "" ) { 195 | if ( $salt == "" ) $salt = substr( md5(rand(100000,999999)), 2, 8); 196 | global $c; 197 | if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making salted MD5: salt=$salt, instr=$instr, md5($salt$instr)=".md5($salt . $instr) ); 198 | return ( sprintf("*%s*%s", $salt, md5($salt . $instr) ) ); 199 | } 200 | } 201 | 202 | 203 | 204 | if ( !function_exists("session_salted_sha1") ) { 205 | /** 206 | * Make a salted SHA1 string, given a string and (possibly) a salt. PHP5 only (although it 207 | * could be made to work on PHP4 (@see http://www.openldap.org/faq/data/cache/347.html). The 208 | * algorithm used here is compatible with OpenLDAP so passwords generated through this function 209 | * should be able to be migrated to OpenLDAP by using the part following the second '*', i.e. 210 | * the '{SSHA}....' part. 211 | * 212 | * If no salt is supplied we will generate a random one. 213 | * 214 | * @param string $instr The string to be salted and SHA1'd 215 | * @param string $salt Some salt to sprinkle into the string to be SHA1'd so we don't get the same PW always hashing to the same value. 216 | * @return string A *, the salt, a * and the SHA1 of the salted string, as in *SALT*SALTEDHASH 217 | */ 218 | function session_salted_sha1( $instr, $salt = "" ) { 219 | if ( $salt == "" ) $salt = substr( str_replace('*','',base64_encode(sha1(rand(100000,9999999),true))), 2, 9); 220 | global $c; 221 | if ( isset($c->dbg['password']) ) dbg_error_log( "Login", "Making salted SHA1: salt=$salt, instr=$instr, encoded($instr$salt)=".base64_encode(sha1($instr . $salt, true).$salt) ); 222 | return ( sprintf("*%s*{SSHA}%s", $salt, base64_encode(sha1($instr.$salt, true) . $salt ) ) ); 223 | } 224 | } 225 | 226 | 227 | if ( !function_exists("session_validate_password") ) { 228 | 229 | /** 230 | * Checks what a user entered against the actual password on their account. 231 | * @param string $they_sent What the user entered. 232 | * @param string $we_have What we have in the database as their password. Which may (or may not) be a salted MD5. 233 | * @return boolean Whether or not the users attempt matches what is already on file. 234 | */ 235 | function session_validate_password( $they_sent, $we_have ) { 236 | global $c; 237 | if ( preg_match('/^\*\*.+$/', $we_have ) ) { 238 | // The "forced" style of "**plaintext" to allow easier admin setting 239 | return ( "**$they_sent" == $we_have ); 240 | } 241 | 242 | if ( isset($c->wp_includes) && substring($we_have,0,1) == '$' ) { 243 | // Include Wordpress password handling, if it's in the path. 244 | @require_once($c->wp_includes .'/class-phpass.php'); 245 | 246 | if ( class_exists('PasswordHash') ) { 247 | $wp_hasher = new PasswordHash(8, true); 248 | return $wp_hasher->CheckPassword($password, $hash); 249 | } 250 | } 251 | 252 | if ( preg_match('/^\*(.+)\*{[A-Z]+}.+$/', $we_have, $regs ) ) { 253 | if ( function_exists("session_salted_sha1") ) { 254 | // A nicely salted sha1sum like "**{SSHA}" 255 | $salt = $regs[1]; 256 | $sha1_sent = session_salted_sha1( $they_sent, $salt ) ; 257 | return ( $sha1_sent == $we_have ); 258 | } 259 | else { 260 | dbg_error_log( "ERROR", "Password is salted SHA-1 but you are using PHP4!" ); 261 | echo << 263 | 264 | Salted SHA1 Password format not supported with PHP4 265 | 266 | 267 |

Salted SHA1 Password format not supported with PHP4

268 |

At some point you have used PHP5 to set the password for this user and now you are 269 | using PHP4. You will need to assign a new password to this user using PHP4, or ensure 270 | you use PHP5 everywhere (recommended).

271 |

AWL has now switched to using salted SHA-1 passwords by preference in a format 272 | compatible with OpenLDAP.

273 | 274 | 275 | EOERRMSG; 276 | exit; 277 | } 278 | } 279 | 280 | if ( preg_match('/^\*MD5\*.+$/', $we_have, $regs ) ) { 281 | // A crappy unsalted md5sum like "*MD5*" 282 | $md5_sent = session_simple_md5( $they_sent ) ; 283 | return ( $md5_sent == $we_have ); 284 | } 285 | else if ( preg_match('/^\*(.+)\*.+$/', $we_have, $regs ) ) { 286 | // A nicely salted md5sum like "**" 287 | $salt = $regs[1]; 288 | $md5_sent = session_salted_md5( $they_sent, $salt ) ; 289 | return ( $md5_sent == $we_have ); 290 | } 291 | 292 | // Anything else is bad 293 | return false; 294 | 295 | } 296 | } 297 | 298 | 299 | 300 | if ( !function_exists("replace_uri_params") ) { 301 | /** 302 | * Given a URL (presumably the current one) and a parameter, replace the value of parameter, 303 | * extending the URL as necessary if the parameter is not already there. 304 | * @param string $uri The URI we will be replacing parameters in. 305 | * @param array $replacements An array of replacement pairs array( "replace_this" => "with this" ) 306 | * @return string The URI with the replacements done. 307 | */ 308 | function replace_uri_params( $uri, $replacements ) { 309 | $replaced = $uri; 310 | foreach( $replacements AS $param => $new_value ) { 311 | $rxp = preg_replace( '/([\[\]])/', '\\\\$1', $param ); // Some parameters may be arrays. 312 | $regex = "/([&?])($rxp)=([^&]+)/"; 313 | dbg_error_log("core", "Looking for [%s] to replace with [%s] regex is %s and searching [%s]", $param, $new_value, $regex, $replaced ); 314 | if ( preg_match( $regex, $replaced ) ) 315 | $replaced = preg_replace( $regex, "\$1$param=$new_value", $replaced); 316 | else 317 | $replaced .= "&$param=$new_value"; 318 | } 319 | if ( ! preg_match( '/\?/', $replaced ) ) { 320 | $replaced = preg_replace("/&(.+)$/", "?\$1", $replaced); 321 | } 322 | $replaced = str_replace("&", "--AmPeRsAnD--", $replaced); 323 | $replaced = str_replace("&", "&", $replaced); 324 | $replaced = str_replace("--AmPeRsAnD--", "&", $replaced); 325 | dbg_error_log("core", "URI <<$uri>> morphed to <<$replaced>>"); 326 | return $replaced; 327 | } 328 | } 329 | 330 | 331 | if ( !function_exists("uuid") ) { 332 | /** 333 | * Generates a Universally Unique IDentifier, version 4. 334 | * 335 | * RFC 4122 (http://www.ietf.org/rfc/rfc4122.txt) defines a special type of Globally 336 | * Unique IDentifiers (GUID), as well as several methods for producing them. One 337 | * such method, described in section 4.4, is based on truly random or pseudo-random 338 | * number generators, and is therefore implementable in a language like PHP. 339 | * 340 | * We choose to produce pseudo-random numbers with the Mersenne Twister, and to always 341 | * limit single generated numbers to 16 bits (ie. the decimal value 65535). That is 342 | * because, even on 32-bit systems, PHP's RAND_MAX will often be the maximum *signed* 343 | * value, with only the equivalent of 31 significant bits. Producing two 16-bit random 344 | * numbers to make up a 32-bit one is less efficient, but guarantees that all 32 bits 345 | * are random. 346 | * 347 | * The algorithm for version 4 UUIDs (ie. those based on random number generators) 348 | * states that all 128 bits separated into the various fields (32 bits, 16 bits, 16 bits, 349 | * 8 bits and 8 bits, 48 bits) should be random, except : (a) the version number should 350 | * be the last 4 bits in the 3rd field, and (b) bits 6 and 7 of the 4th field should 351 | * be 01. We try to conform to that definition as efficiently as possible, generating 352 | * smaller values where possible, and minimizing the number of base conversions. 353 | * 354 | * @copyright Copyright (c) CFD Labs, 2006. This function may be used freely for 355 | * any purpose ; it is distributed without any form of warranty whatsoever. 356 | * @author David Holmes 357 | * 358 | * @return string A UUID, made up of 32 hex digits and 4 hyphens. 359 | */ 360 | 361 | function uuid() { 362 | 363 | // The field names refer to RFC 4122 section 4.1.2 364 | 365 | return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x', 366 | mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low" 367 | mt_rand(0, 65535), // 16 bits for "time_mid" 368 | mt_rand(0, 4095), // 12 bits before the 0100 of (version) 4 for "time_hi_and_version" 369 | bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)), 370 | // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res" 371 | // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d) 372 | // 8 bits for "clk_seq_low" 373 | mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node" 374 | ); 375 | } 376 | } 377 | 378 | if ( !function_exists("translate") ) { 379 | require(__DIR__."/Translation.php"); 380 | } 381 | 382 | if ( !function_exists("clone") && version_compare(phpversion(), '5.0') < 0) { 383 | /** 384 | * PHP5 screws with the assignment operator changing so that $a = $b means that 385 | * $a becomes a reference to $b. There is a clone() that we can use in PHP5, so 386 | * we have to emulate that for PHP4. Bleargh. 387 | */ 388 | eval( 'function clone($object) { return $object; }' ); 389 | } 390 | 391 | if ( !function_exists("quoted_printable_encode") ) { 392 | /** 393 | * Process a string to fit the requirements of RFC2045 section 6.7. Note that 394 | * this works, but replaces more characters than the minimum set. For readability 395 | * the spaces aren't encoded as =20 though. 396 | */ 397 | function quoted_printable_encode($string) { 398 | return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=",str_replace("%20"," ",rawurlencode($string)))); 399 | } 400 | } 401 | 402 | 403 | if ( !function_exists("check_by_regex") ) { 404 | /** 405 | * Verify a value is OK by testing a regex against it. If it is an array apply it to 406 | * each element in the array recursively. If it is an object we don't mess 407 | * with it. 408 | */ 409 | function check_by_regex( $val, $regex ) { 410 | if ( is_null($val) ) return null; 411 | switch( $regex ) { 412 | case 'int': $regex = '#^\d+$#'; break; 413 | } 414 | if ( is_array($val) ) { 415 | foreach( $val AS $k => $v ) { 416 | $val[$k] = check_by_regex($v,$regex); 417 | } 418 | } 419 | else if ( ! is_object($val) ) { 420 | if ( preg_match( $regex, $val, $matches) ) { 421 | $val = $matches[0]; 422 | } 423 | else { 424 | $val = ''; 425 | } 426 | } 427 | return $val; 428 | } 429 | } 430 | 431 | 432 | if ( !function_exists("param_to_global") ) { 433 | /** 434 | * Convert a parameter to a global. We first look in _POST and then in _GET, 435 | * and if they passed in a bunch of valid characters, we will make sure the 436 | * incoming is cleaned to only match that set. 437 | * 438 | * @param string $varname The name of the global variable to put the answer in 439 | * @param string $match_regex The part of the parameter matching this regex will be returned 440 | * @param string $alias1 An alias for the name that we should look for first. 441 | * @param " ... More aliases, in the order which they should be examined. $varname will be appended to the end. 442 | */ 443 | function param_to_global( ) { 444 | $args = func_get_args(); 445 | 446 | $varname = array_shift($args); 447 | $GLOBALS[$varname] = null; 448 | 449 | $match_regex = null; 450 | $argc = func_num_args(); 451 | if ( $argc > 1 ) { 452 | $match_regex = array_shift($args); 453 | } 454 | 455 | $args[] = $varname; 456 | foreach( $args AS $k => $name ) { 457 | if ( isset($_POST[$name]) ) { 458 | $result = $_POST[$name]; 459 | break; 460 | } 461 | else if ( isset($_GET[$name]) ) { 462 | $result = $_GET[$name]; 463 | break; 464 | } 465 | } 466 | if ( !isset($result) ) return null; 467 | 468 | if ( isset($match_regex) ) { 469 | $result = check_by_regex( $result, $match_regex ); 470 | } 471 | 472 | $GLOBALS[$varname] = $result; 473 | return $result; 474 | } 475 | } 476 | 477 | 478 | if ( !function_exists("get_fields") ) { 479 | /** 480 | * @var array $_AWL_field_cache is a cache of the field names for a table 481 | */ 482 | $_AWL_field_cache = array(); 483 | 484 | /** 485 | * Get the names of the fields for a particular table 486 | * @param string $tablename The name of the table. 487 | * @return array of string The public fields in the table. 488 | */ 489 | function get_fields( $tablename ) { 490 | global $_AWL_field_cache; 491 | 492 | if ( !isset($_AWL_field_cache[$tablename]) ) { 493 | dbg_error_log( "core", ":get_fields: Loading fields for table '$tablename'" ); 494 | $qry = new AwlQuery(); 495 | $db = $qry->GetConnection(); 496 | $qry->SetSQL($db->GetFields($tablename)); 497 | $qry->Exec("core"); 498 | $fields = array(); 499 | while( $row = $qry->Fetch() ) { 500 | $fields[$row->fieldname] = $row->typename . ($row->precision >= 0 ? sprintf('(%d)',$row->precision) : ''); 501 | } 502 | $_AWL_field_cache[$tablename] = $fields; 503 | } 504 | return $_AWL_field_cache[$tablename]; 505 | } 506 | } 507 | 508 | 509 | if ( !function_exists("force_utf8") ) { 510 | function define_byte_mappings() { 511 | global $byte_map, $nibble_good_chars; 512 | 513 | # Needed for using Grant McLean's byte mappings code 514 | $ascii_char = '[\x00-\x7F]'; 515 | $cont_byte = '[\x80-\xBF]'; 516 | 517 | $utf8_2 = '[\xC0-\xDF]' . $cont_byte; 518 | $utf8_3 = '[\xE0-\xEF]' . $cont_byte . '{2}'; 519 | $utf8_4 = '[\xF0-\xF7]' . $cont_byte . '{3}'; 520 | $utf8_5 = '[\xF8-\xFB]' . $cont_byte . '{4}'; 521 | 522 | $nibble_good_chars = "/^($ascii_char+|$utf8_2|$utf8_3|$utf8_4|$utf8_5)(.*)$/s"; 523 | 524 | # From http://unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT 525 | $byte_map = array( 526 | "\x80" => "\xE2\x82\xAC", # EURO SIGN 527 | "\x82" => "\xE2\x80\x9A", # SINGLE LOW-9 QUOTATION MARK 528 | "\x83" => "\xC6\x92", # LATIN SMALL LETTER F WITH HOOK 529 | "\x84" => "\xE2\x80\x9E", # DOUBLE LOW-9 QUOTATION MARK 530 | "\x85" => "\xE2\x80\xA6", # HORIZONTAL ELLIPSIS 531 | "\x86" => "\xE2\x80\xA0", # DAGGER 532 | "\x87" => "\xE2\x80\xA1", # DOUBLE DAGGER 533 | "\x88" => "\xCB\x86", # MODIFIER LETTER CIRCUMFLEX ACCENT 534 | "\x89" => "\xE2\x80\xB0", # PER MILLE SIGN 535 | "\x8A" => "\xC5\xA0", # LATIN CAPITAL LETTER S WITH CARON 536 | "\x8B" => "\xE2\x80\xB9", # SINGLE LEFT-POINTING ANGLE QUOTATION MARK 537 | "\x8C" => "\xC5\x92", # LATIN CAPITAL LIGATURE OE 538 | "\x8E" => "\xC5\xBD", # LATIN CAPITAL LETTER Z WITH CARON 539 | "\x91" => "\xE2\x80\x98", # LEFT SINGLE QUOTATION MARK 540 | "\x92" => "\xE2\x80\x99", # RIGHT SINGLE QUOTATION MARK 541 | "\x93" => "\xE2\x80\x9C", # LEFT DOUBLE QUOTATION MARK 542 | "\x94" => "\xE2\x80\x9D", # RIGHT DOUBLE QUOTATION MARK 543 | "\x95" => "\xE2\x80\xA2", # BULLET 544 | "\x96" => "\xE2\x80\x93", # EN DASH 545 | "\x97" => "\xE2\x80\x94", # EM DASH 546 | "\x98" => "\xCB\x9C", # SMALL TILDE 547 | "\x99" => "\xE2\x84\xA2", # TRADE MARK SIGN 548 | "\x9A" => "\xC5\xA1", # LATIN SMALL LETTER S WITH CARON 549 | "\x9B" => "\xE2\x80\xBA", # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 550 | "\x9C" => "\xC5\x93", # LATIN SMALL LIGATURE OE 551 | "\x9E" => "\xC5\xBE", # LATIN SMALL LETTER Z WITH CARON 552 | "\x9F" => "\xC5\xB8", # LATIN CAPITAL LETTER Y WITH DIAERESIS 553 | ); 554 | 555 | for( $i=160; $i < 256; $i++ ) { 556 | $ch = chr($i); 557 | $byte_map[$ch] = iconv('ISO-8859-1', 'UTF-8', $ch); 558 | } 559 | } 560 | define_byte_mappings(); 561 | 562 | function force_utf8( $input ) { 563 | global $byte_map, $nibble_good_chars; 564 | 565 | $output = ''; 566 | $char = ''; 567 | $rest = ''; 568 | while( $input != '' ) { 569 | if ( preg_match( $nibble_good_chars, $input, $matches ) ) { 570 | $output .= $matches[1]; 571 | $rest = $matches[2]; 572 | } 573 | else { 574 | preg_match( '/^(.)(.*)$/s', $input, $matches ); 575 | $char = $matches[1]; 576 | $rest = $matches[2]; 577 | if ( isset($byte_map[$char]) ) { 578 | $output .= $byte_map[$char]; 579 | } 580 | else { 581 | # Must be valid UTF8 already 582 | $output .= $char; 583 | } 584 | } 585 | $input = $rest; 586 | } 587 | return $output; 588 | } 589 | 590 | } 591 | 592 | 593 | /** 594 | * Try and extract something like "Pacific/Auckland" or "America/Indiana/Indianapolis" if possible. 595 | */ 596 | function olson_from_tzstring( $tzstring ) { 597 | global $c; 598 | 599 | if ( function_exists('timezone_identifiers_list') && in_array($tzstring,timezone_identifiers_list()) ) return $tzstring; 600 | if ( preg_match( '{((Antarctica|America|Africa|Atlantic|Asia|Australia|Indian|Europe|Pacific)/(([^/]+)/)?[^/]+)$}', $tzstring, $matches ) ) { 601 | // dbg_error_log( 'INFO', 'Found timezone "%s" from string "%s"', $matches[1], $tzstring ); 602 | return $matches[1]; 603 | } 604 | switch( $tzstring ) { 605 | case 'New Zealand Standard Time': case 'New Zealand Daylight Time': 606 | return 'Pacific/Auckland'; 607 | break; 608 | case 'Central Standard Time': case 'Central Daylight Time': case 'US/Central': 609 | return 'America/Chicago'; 610 | break; 611 | case 'Eastern Standard Time': case 'Eastern Daylight Time': case 'US/Eastern': 612 | case '(UTC-05:00) Eastern Time (US & Canada)': 613 | return 'America/New_York'; 614 | break; 615 | case 'Pacific Standard Time': case 'Pacific Daylight Time': case 'US/Pacific': 616 | return 'America/Los_Angeles'; 617 | break; 618 | case 'Mountain Standard Time': case 'Mountain Daylight Time': case 'US/Mountain': case 'Mountain Time': 619 | return 'America/Denver'; 620 | // The US 'Mountain Time' can in fact be America/(Denver|Boise|Phoenix|Shiprock) which 621 | // all vary to some extent due to differing DST rules. 622 | break; 623 | case '(GMT-07.00) Arizona': 624 | return 'America/Phoenix'; 625 | break; 626 | default: 627 | if ( isset($c->timezone_translations) && is_array($c->timezone_translations) 628 | && !empty($c->timezone_translations[$tzstring]) ) 629 | return $c->timezone_translations[$tzstring]; 630 | } 631 | return null; 632 | } 633 | 634 | if ( !function_exists("deprecated") ) { 635 | function deprecated( $method ) { 636 | global $c; 637 | if ( isset($c->dbg['ALL']) || isset($c->dbg['deprecated']) ) { 638 | $stack = debug_backtrace(); 639 | array_shift($stack); 640 | if ( preg_match( '{/inc/iCalendar.php$}', $stack[0]['file'] ) && $stack[0]['line'] > __LINE__ ) return; 641 | @error_log( sprintf( $c->sysabbr.':DEPRECATED: Call to deprecated method "%s"', $method)); 642 | foreach( $stack AS $k => $v ) { 643 | @error_log( sprintf( $c->sysabbr.': ==> called from line %4d of %s', $v['line'], $v['file'])); 644 | } 645 | } 646 | } 647 | } 648 | 649 | 650 | if ( !function_exists("gzdecode") ) { 651 | function gzdecode( $instring ) { 652 | global $c; 653 | if ( !isset($c->use_pipe_gunzip) || $c->use_pipe_gunzip ) { 654 | $descriptorspec = array( 655 | 0 => array("pipe", "r"), // stdin is a pipe that the child will read from 656 | 1 => array("pipe", "w"), // stdout is a pipe that the child will write to 657 | 2 => array("file", "/dev/null", "a") // stderr is discarded 658 | ); 659 | $process = proc_open('gunzip',$descriptorspec, $pipes); 660 | if ( is_resource($process) ) { 661 | fwrite($pipes[0],$instring); 662 | fclose($pipes[0]); 663 | 664 | $outstring = stream_get_contents($pipes[1]); 665 | fclose($pipes[1]); 666 | 667 | proc_close($process); 668 | return $outstring; 669 | } 670 | return ''; 671 | } 672 | else { 673 | $g=tempnam('./','gz'); 674 | file_put_contents($g,$instring); 675 | ob_start(); 676 | readgzfile($g); 677 | $d=ob_get_clean(); 678 | unlink($g); 679 | return $d; 680 | } 681 | } 682 | } 683 | 684 | /** 685 | * Return the AWL version 686 | */ 687 | function awl_version() { 688 | global $c; 689 | $c->awl_library_version = 0.54; 690 | return $c->awl_library_version; 691 | } -------------------------------------------------------------------------------- /src/CalDAVClient.php: -------------------------------------------------------------------------------- 1 | 4 | * 5 | * This file is heavily based on AgenDAV caldav-client-v2.php by 6 | * Jorge López Pérez which is again heavily based 7 | * on DAViCal caldav-client-v2.php by Andrew McMillan 8 | * 9 | * 10 | * @package simpleCalDAV 11 | */ 12 | 13 | namespace it\thecsea\simple_caldav_client; 14 | 15 | use it\thecsea\simple_caldav_client\includes\XMLDocument; 16 | use it\thecsea\simple_caldav_client\includes\XMLElement; 17 | 18 | class CalDAVClient { 19 | /** 20 | * Server, username, password, calendar 21 | * 22 | * @var string 23 | */ 24 | protected $base_url, $user, $pass, $entry, $protocol, $server, $port; 25 | 26 | /** 27 | * The principal-URL we're using 28 | */ 29 | protected $principal_url; 30 | 31 | /** 32 | * The calendar-URL we're using 33 | */ 34 | public $calendar_url; 35 | 36 | /** 37 | * The calendar-home-set we're using 38 | */ 39 | protected $calendar_home_set; 40 | 41 | /** 42 | * The calendar_urls we have discovered 43 | */ 44 | protected $calendar_urls; 45 | 46 | /** 47 | * The useragent which is send to the caldav server 48 | * 49 | * @var string 50 | */ 51 | public $user_agent = 'simpleCalDAVclient'; 52 | 53 | protected $headers = array(); 54 | protected $body = ""; 55 | protected $requestMethod = "GET"; 56 | protected $httpRequest = ""; // for debugging http headers sent 57 | protected $xmlRequest = ""; // for debugging xml sent 58 | protected $httpResponse = ""; // http headers received 59 | protected $xmlResponse = ""; // xml received 60 | protected $httpResultCode = ""; 61 | private $httpResponseHeaders = ''; 62 | private $httpResponseBody = ''; 63 | 64 | protected $parser; // our XML parser object 65 | protected $request_url = ""; 66 | protected $xmlnodes = array(); 67 | protected $xmltags = array(); 68 | 69 | // Requests timeout 70 | private $timeout; 71 | 72 | // cURL handle 73 | private $ch; 74 | 75 | // Full URL 76 | private $full_url; 77 | 78 | // First part of the full url 79 | public $first_url_part; 80 | 81 | /** 82 | * Constructor 83 | * 84 | * @param string $base_url 85 | * @param string $user 86 | * @param string $pass 87 | * @param array $options 88 | * 89 | * Valid options are: 90 | * 91 | * $options['auth'] : Auth type. Can be any of values for 92 | * CURLOPT_HTTPAUTH (from 93 | * http://www.php.net/manual/es/function.curl-setopt.php). Default: 94 | * basic or digest 95 | * 96 | * $options['timeout'] : Timeout in seconds 97 | */ 98 | 99 | // TODO: proxy options, interface used, 100 | function __construct( $base_url, $user, $pass, $options = array()) { 101 | $this->user = $user; 102 | $this->pass = $pass; 103 | $this->headers = array(); 104 | 105 | if ( preg_match( '#^((https?)://([a-z0-9.-]+)(:([0-9]+))?)(/.*)$#', $base_url, $matches ) ) { 106 | $this->server = $matches[3]; 107 | $this->base_url = $matches[6]; 108 | if ( $matches[2] == 'https' ) { 109 | $this->protocol = 'ssl'; 110 | $this->port = 443; 111 | } 112 | else { 113 | $this->protocol = 'tcp'; 114 | $this->port = 80; 115 | } 116 | if ( $matches[4] != '' ) { 117 | $this->port = intval($matches[5]); 118 | } 119 | } else { 120 | trigger_error("Invalid URL: '".$base_url."'", E_USER_ERROR); 121 | } 122 | 123 | $this->timeout = isset($options['timeout']) ? 124 | $options['timeout'] : 10; 125 | $this->ch = curl_init(); 126 | curl_setopt_array($this->ch, array( 127 | CURLOPT_CONNECTTIMEOUT => $this->timeout, 128 | CURLOPT_FAILONERROR => FALSE, 129 | CURLOPT_MAXREDIRS => 2, 130 | CURLOPT_FORBID_REUSE => FALSE, 131 | CURLOPT_RETURNTRANSFER => TRUE, 132 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 133 | CURLOPT_HTTPAUTH => 134 | isset($options['auth']) ? $options['auth'] : 135 | (CURLAUTH_BASIC | CURLAUTH_DIGEST), 136 | CURLOPT_USERAGENT => 'cURL based CalDAV client', 137 | CURLINFO_HEADER_OUT => TRUE, 138 | CURLOPT_HEADER => TRUE, 139 | CURLOPT_SSL_VERIFYPEER => FALSE 140 | )); 141 | 142 | // Define Proxy 143 | if(isset($options['proxy_host'])) { 144 | curl_setopt($this->ch, CURLOPT_PROXY, $options['proxy_host']); 145 | } 146 | 147 | $this->full_url = $base_url; 148 | $this->first_url_part = $matches[1]; 149 | } 150 | 151 | /** 152 | * Check with OPTIONS if calendar-access is enabled 153 | * 154 | * Can be used to check authentication against server 155 | * 156 | * @return bool 157 | */ 158 | function isValidCalDAVServer() { 159 | // Clean headers 160 | $this->headers = array(); 161 | $dav_options = $this->DoOptionsRequestAndGetDAVHeader(); 162 | return isset($dav_options['calendar-access']); 163 | } 164 | 165 | /** 166 | * Issues an OPTIONS request 167 | * 168 | * @param string $url The URL to make the request to 169 | * 170 | * @return array DAV options 171 | */ 172 | function DoOptionsRequestAndGetDAVHeader( $url = null ) { 173 | $this->requestMethod = "OPTIONS"; 174 | $this->body = ""; 175 | $headers = $this->DoRequest($url); 176 | 177 | $result = array(); 178 | 179 | $headers = preg_split('/\r?\n/', $headers); 180 | 181 | // DAV header(s) 182 | $dav_header = preg_grep('/^DAV:/i', $headers); // /i for case insensitive as some servers (example Nextcloud) do not send uppercase headers 183 | if (is_array($dav_header)) { 184 | $dav_header = array_values($dav_header); 185 | $dav_header = preg_replace('/^DAV: /i', '', $dav_header); // /i for case insensitive 186 | $dav_options = array(); 187 | 188 | foreach ($dav_header as $d) { 189 | $dav_options = array_merge($dav_options, 190 | array_flip(preg_split('/[, ]+/', $d))); 191 | } 192 | 193 | $result = $dav_options; 194 | 195 | } 196 | 197 | return $result; 198 | } 199 | 200 | 201 | /** 202 | * Adds an If-Match or If-None-Match header 203 | * 204 | * @param bool $match to Match or Not to Match, that is the question! 205 | * @param string $etag The etag to match / not match against. 206 | */ 207 | function SetMatch( $match, $etag = '*' ) { 208 | $this->headers['match'] = sprintf( "%s-Match: \"%s\"", ($match ? "If" : "If-None"), $etag); 209 | } 210 | 211 | /** 212 | * Add a Depth: header. Valid values are 0, 1 or infinity 213 | * 214 | * @param string $depth The depth, default to infinity 215 | */ 216 | function SetDepth( $depth = '0' ) { 217 | $this->headers['depth'] = 'Depth: '. ($depth == '1' ? "1" : ($depth == 'infinity' ? $depth : "0") ); 218 | } 219 | 220 | /** 221 | * @param string|null $user_agent 222 | */ 223 | function SetUserAgent( $user_agent = null ) { 224 | $this->user_agent = $user_agent; 225 | curl_setopt($this->ch, CURLOPT_USERAGENT, $user_agent); 226 | } 227 | 228 | /** 229 | * Add a Content-type: header. 230 | * 231 | * @param string $type The content type 232 | */ 233 | function SetContentType( $type ) { 234 | $this->headers['content-type'] = "Content-type: $type"; 235 | } 236 | 237 | /** 238 | * Set the calendar_url we will be using for a while. 239 | * 240 | * @param string $url The calendar_url 241 | */ 242 | function SetCalendar( $url ) { 243 | $this->calendar_url = $url; 244 | } 245 | 246 | /** 247 | * Split response into httpResponse and xmlResponse 248 | * 249 | * @param string $response Response from server 250 | */ 251 | function ParseResponse( $response ) { 252 | $pos = strpos($response, 'httpResponse = trim($response); 255 | } 256 | else { 257 | $this->httpResponse = trim(substr($response, 0, $pos)); 258 | $this->xmlResponse = trim(substr($response, $pos)); 259 | $this->xmlResponse = preg_replace('{>[^>]*$}s', '>',$this->xmlResponse ); 260 | $parser = xml_parser_create_ns('UTF-8'); 261 | xml_parser_set_option ( $parser, XML_OPTION_SKIP_WHITE, 1 ); 262 | xml_parser_set_option ( $parser, XML_OPTION_CASE_FOLDING, 0 ); 263 | 264 | if ( xml_parse_into_struct( $parser, $this->xmlResponse, $this->xmlnodes, $this->xmltags ) === 0 ) { 265 | //printf( "XML parsing error: %s - %s\n", xml_get_error_code($parser), xml_error_string(xml_get_error_code($parser)) ); 266 | // debug_print_backtrace(); 267 | // echo "\nNodes array............................................................\n"; print_r( $this->xmlnodes ); 268 | // echo "\nTags array............................................................\n"; print_r( $this->xmltags ); 269 | //printf( "\nXML Reponse:\n%s\n", $this->xmlResponse ); 270 | log_message('ERROR', 'XML parsing error: ' 271 | . xml_get_error_code($parser) . ', ' 272 | . xml_error_string(xml_get_error_code($parser))); 273 | } 274 | 275 | xml_parser_free($parser); 276 | } 277 | } 278 | 279 | /** 280 | * Parse response headers 281 | * 282 | * @param string $headers 283 | */ 284 | function ParseResponseHeaders($headers) { 285 | $lines = preg_split('/[\r\n]+/', $headers); 286 | $this->httpResultCode = preg_replace('/^[\S]+ (\d+).+$/', '\1', 287 | $lines[0]); 288 | } 289 | 290 | /** 291 | * Output http request headers 292 | * 293 | * @return string HTTP headers 294 | */ 295 | function GetHttpRequest() { 296 | return $this->httpRequest; 297 | } 298 | /** 299 | * Output http response headers 300 | * 301 | * @return string HTTP headers 302 | */ 303 | function GetResponseHeaders() { 304 | return $this->httpResponseHeaders; 305 | } 306 | /** 307 | * Output http response body 308 | * 309 | * @return string HTTP body 310 | */ 311 | function GetResponseBody() { 312 | return $this->httpResponseBody; 313 | } 314 | /** 315 | * Output request body 316 | * 317 | * @return string raw xml 318 | */ 319 | function GetBody() { 320 | return $this->body; 321 | } 322 | /** 323 | * Output xml response 324 | * 325 | * @return string raw xml 326 | */ 327 | function GetXmlResponse() { 328 | return $this->xmlResponse; 329 | } 330 | /** 331 | * Output HTTP status code 332 | * 333 | * @return string HTTP status code 334 | */ 335 | function GetHttpResultCode() { 336 | return $this->httpResultCode; 337 | } 338 | 339 | /** 340 | * Send a request to the server 341 | * 342 | * @param string $url The URL to make the request to 343 | * 344 | * @return bool|string The content of the response from the server 345 | */ 346 | function DoRequest( $url = null ) { 347 | if (is_null($url)) { 348 | $url = $this->full_url; 349 | } 350 | 351 | $this->request_url = $url; 352 | 353 | curl_setopt($this->ch, CURLOPT_URL, $url); 354 | 355 | // Request method 356 | curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->requestMethod); 357 | 358 | // Empty body. If not used, cURL will spend ~5s on this request 359 | if ($this->requestMethod == 'HEAD' || empty($this->body) ) { 360 | curl_setopt($this->ch, CURLOPT_NOBODY, TRUE); 361 | } else { 362 | curl_setopt($this->ch, CURLOPT_NOBODY, FALSE); 363 | } 364 | 365 | // Headers 366 | if (!isset($this->headers['content-type'])) $this->headers['content-type'] = "Content-type: text/plain"; 367 | 368 | // Remove cURL generated 'Expect: 100-continue' 369 | $this->headers['disable_expect'] = 'Expect:'; 370 | curl_setopt($this->ch, CURLOPT_HTTPHEADER, 371 | array_values($this->headers)); 372 | 373 | curl_setopt($this->ch, CURLOPT_USERPWD, $this->user . ':' . 374 | $this->pass); 375 | 376 | // Request body 377 | curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->body); 378 | 379 | // Save Request 380 | curl_setopt($this->ch, CURLINFO_HEADER_OUT, TRUE); 381 | curl_setopt($this->ch, CURLOPT_HTTP09_ALLOWED, true); 382 | 383 | $response = curl_exec($this->ch); 384 | 385 | if (FALSE === $response) { 386 | // TODO better error handling 387 | log_message('ERROR', 'Error requesting ' . $url . ': ' 388 | . curl_error($this->ch)); 389 | return false; 390 | } 391 | 392 | $info = curl_getinfo($this->ch); 393 | 394 | // Save request 395 | $this->httpRequest = $info['request_header']; 396 | 397 | // Get headers (idea from SabreDAV WebDAV client) 398 | $this->httpResponseHeaders = substr($response, 0, $info['header_size']); 399 | $this->httpResponseBody = substr($response, $info['header_size']); 400 | 401 | // Get only last headers (needed when using unspecific HTTP auth 402 | // method or request got redirected) 403 | $this->httpResponseHeaders = preg_replace('/^.+\r\n\r\n(.+)/sU', '$1', 404 | $this->httpResponseHeaders); 405 | 406 | // Parse response 407 | $this->ParseResponseHeaders($this->httpResponseHeaders); 408 | $this->ParseResponse($this->httpResponseBody); 409 | 410 | //TODO debug 411 | 412 | /* 413 | log_message('INTERNALS', 'REQh: ' . var_export($info['request_header'], TRUE)); 414 | log_message('INTERNALS', 'REQb: ' . var_export($this->body, TRUE)); 415 | log_message('INTERNALS', 'RPLh: ' . var_export($this->httpResponseHeaders, TRUE)); 416 | log_message('INTERNALS', 'RPLb: ' . var_export($this->httpResponseBody, TRUE)); 417 | */ 418 | 419 | return $response; 420 | } 421 | 422 | /** 423 | * Send an OPTIONS request to the server 424 | * 425 | * @param string $url The URL to make the request to 426 | * 427 | * @return array The allowed options 428 | */ 429 | function DoOptionsRequest( $url = null ) { 430 | $this->requestMethod = "OPTIONS"; 431 | $this->body = ""; 432 | $headers = $this->DoRequest($url); 433 | $options_header = preg_replace( '/^.*Allow: ([a-z, ]+)\r?\n.*/is', '$1', $headers ); 434 | $options = array_flip( preg_split( '/[, ]+/', $options_header )); 435 | return $options; 436 | } 437 | 438 | 439 | 440 | /** 441 | * Send an XML request to the server (e.g. PROPFIND, REPORT, MKCALENDAR) 442 | * 443 | * @param string $request_method The method (PROPFIND, REPORT, etc) to use with the request 444 | * @param string $xml The XML to send along with the request 445 | * @param string $url The URL to make the request to 446 | * 447 | * @return array An array of the allowed methods 448 | */ 449 | function DoXMLRequest( $request_method, $xml, $url = null ) { 450 | $this->body = $xml; 451 | $this->requestMethod = $request_method; 452 | $this->SetContentType("text/xml"); 453 | return $this->DoRequest($url); 454 | } 455 | 456 | 457 | 458 | /** 459 | * Get a single item from the server. 460 | * 461 | * @param string $url The URL to GET 462 | */ 463 | function DoGETRequest( $url ) { 464 | $this->body = ""; 465 | $this->requestMethod = "GET"; 466 | return $this->DoRequest( $url ); 467 | } 468 | 469 | 470 | /** 471 | * Get the HEAD of a single item from the server. 472 | * 473 | * @param string $url The URL to HEAD 474 | */ 475 | function DoHEADRequest( $url ) { 476 | $this->body = ""; 477 | $this->requestMethod = "HEAD"; 478 | return $this->DoRequest( $url ); 479 | } 480 | 481 | 482 | /** 483 | * PUT a text/icalendar resource, returning the etag 484 | * 485 | * @param string $url The URL to make the request to 486 | * @param string $icalendar The iCalendar resource to send to the server 487 | * @param string $etag The etag of an existing resource to be overwritten, or '*' for a new resource. 488 | * 489 | * @return string The content of the response from the server 490 | */ 491 | function DoPUTRequest( $url, $icalendar, $etag = null ) { 492 | $this->body = $icalendar; 493 | 494 | $this->requestMethod = "PUT"; 495 | if ( $etag != null ) { 496 | $this->SetMatch( ($etag != '*'), $etag ); 497 | } 498 | $this->SetContentType('text/calendar; encoding="utf-8"'); 499 | $this->DoRequest($url); 500 | 501 | $etag = null; 502 | if ( preg_match( '{^ETag:\s+"([^"]*)"\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 503 | else if ( preg_match( '{^ETag:\s+([^\s]*)\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 504 | if ( !isset($etag) || $etag == '' ) { 505 | // Try with HEAD 506 | $save_request = $this->httpRequest; 507 | $save_response_headers = $this->httpResponseHeaders; 508 | $save_http_result = $this->httpResultCode; 509 | $this->DoHEADRequest( $url ); 510 | if ( preg_match( '{^Etag:\s+"([^"]*)"\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 511 | else if ( preg_match( '{^ETag:\s+([^\s]*)\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 512 | /* 513 | if ( !isset($etag) || $etag == '' ) { 514 | printf( "Still No etag in:\n%s\n", $this->httpResponseHeaders ); 515 | } 516 | */ 517 | $this->httpRequest = $save_request; 518 | $this->httpResponseHeaders = $save_response_headers; 519 | $this->httpResultCode = $save_http_result; 520 | } 521 | return $etag; 522 | } 523 | 524 | 525 | /** 526 | * DELETE a text/icalendar resource 527 | * 528 | * @param string $url The URL to make the request to 529 | * @param string $etag The etag of an existing resource to be deleted, or '*' for any resource at that URL. 530 | * 531 | * @return int The HTTP Result Code for the DELETE 532 | */ 533 | function DoDELETERequest( $url, $etag = null ) { 534 | $this->body = ""; 535 | 536 | $this->requestMethod = "DELETE"; 537 | if ( $etag != null ) { 538 | $this->SetMatch( true, $etag ); 539 | } 540 | $this->DoRequest($url); 541 | return $this->httpResultCode; 542 | } 543 | 544 | 545 | /** 546 | * Get a single item from the server. 547 | * 548 | * @param string $url The URL to PROPFIND on 549 | * @param raw|string 550 | */ 551 | function DoPROPFINDRequest( $url, $props, $depth = 0 ) { 552 | $this->SetDepth($depth); 553 | $xml = new XMLDocument( array( 'DAV:' => '', 'urn:ietf:params:xml:ns:caldav' => 'C' ) ); 554 | $prop = new XMLElement('prop'); 555 | foreach( $props AS $v ) { 556 | $xml->NSElement($prop,$v); 557 | } 558 | 559 | $this->body = $xml->Render('propfind',$prop ); 560 | 561 | $this->requestMethod = 'PROPFIND'; 562 | $this->SetContentType('text/xml'); 563 | $this->DoRequest($url); 564 | return $this->GetXmlResponse(); 565 | } 566 | 567 | 568 | /** 569 | * Get/Set the Principal URL 570 | * 571 | * @param $url string|null The Principal URL to set 572 | * @return string 573 | */ 574 | function PrincipalURL( $url = null ) { 575 | if ( isset($url) ) { 576 | $this->principal_url = $url; 577 | } 578 | return $this->principal_url; 579 | } 580 | 581 | 582 | /** 583 | * Get/Set the calendar-home-set URL 584 | * 585 | * @param $urls array|null of string The calendar-home-set URLs to set 586 | * @return array|array[] 587 | */ 588 | function CalendarHomeSet( $urls = null ) { 589 | if ( isset($urls) ) { 590 | if ( ! is_array($urls) ) $urls = array($urls); 591 | $this->calendar_home_set = $urls; 592 | } 593 | return $this->calendar_home_set; 594 | } 595 | 596 | 597 | /** 598 | * Get/Set the calendar-home-set URL 599 | * 600 | * @param $urls array of string The calendar URLs to set 601 | * @return array|array[] 602 | */ 603 | function CalendarUrls( $urls = null ) { 604 | if ( isset($urls) ) { 605 | if ( ! is_array($urls) ) $urls = array($urls); 606 | $this->calendar_urls = $urls; 607 | } 608 | return $this->calendar_urls; 609 | } 610 | 611 | 612 | /** 613 | * Return the first occurrence of an href inside the named tag. 614 | * 615 | * @param string $tagname The tag name to find the href inside of 616 | * @return string|null 617 | */ 618 | function HrefValueInside( $tagname ) { 619 | if (!isset($this->xmltags[$tagname])) { 620 | return null; 621 | } 622 | 623 | foreach( $this->xmltags[$tagname] AS $k => $v ) { 624 | $j = $v + 1; 625 | if ( $this->xmlnodes[$j]['tag'] == 'DAV::href' ) { 626 | return rawurldecode($this->xmlnodes[$j]['value']); 627 | } 628 | } 629 | return null; 630 | } 631 | 632 | 633 | /** 634 | * Return the href containing this property. Except only if it's inside a status != 200 635 | * 636 | * @param string $tagname The tag name of the property to find the href for 637 | * @param int $i Which instance of the tag should we use 638 | */ 639 | function HrefForProp( $tagname, $i = 0 ) { 640 | if ( isset($this->xmltags[$tagname]) && isset($this->xmltags[$tagname][$i]) ) { 641 | $j = $this->xmltags[$tagname][$i]; 642 | while( $j-- > 0 && $this->xmlnodes[$j]['tag'] != 'DAV::href' ) { 643 | // printf( "Node[$j]: %s\n", $this->xmlnodes[$j]['tag']); 644 | if ( $this->xmlnodes[$j]['tag'] == 'DAV::status' && $this->xmlnodes[$j]['value'] != 'HTTP/1.1 200 OK' ) return null; 645 | } 646 | // printf( "Node[$j]: %s\n", $this->xmlnodes[$j]['tag']); 647 | if ( $j > 0 && isset($this->xmlnodes[$j]['value']) ) { 648 | // printf( "Value[$j]: %s\n", $this->xmlnodes[$j]['value']); 649 | return rawurldecode($this->xmlnodes[$j]['value']); 650 | } 651 | } 652 | else { 653 | // printf( "xmltags[$tagname] or xmltags[$tagname][$i] is not set\n"); 654 | } 655 | return null; 656 | } 657 | 658 | 659 | /** 660 | * Return the href which has a resourcetype of the specified type 661 | * 662 | * @param string $tagname The tag name of the resourcetype to find the href for 663 | * @param int $i Which instance of the tag should we use 664 | */ 665 | function HrefForResourcetype( $tagname, $i = 0 ) { 666 | if ( isset($this->xmltags[$tagname]) && isset($this->xmltags[$tagname][$i]) ) { 667 | $j = $this->xmltags[$tagname][$i]; 668 | while( $j-- > 0 && $this->xmlnodes[$j]['tag'] != 'DAV::resourcetype' ); 669 | if ( $j > 0 ) { 670 | while( $j-- > 0 && $this->xmlnodes[$j]['tag'] != 'DAV::href' ); 671 | if ( $j > 0 && isset($this->xmlnodes[$j]['value']) ) { 672 | return rawurldecode($this->xmlnodes[$j]['value']); 673 | } 674 | } 675 | } 676 | return null; 677 | } 678 | 679 | 680 | /** 681 | * Return the ... of a propstat where the status is OK 682 | * 683 | * @param string $nodenum The node number in the xmlnodes which is the href 684 | */ 685 | function GetOKProps( $nodenum ) { 686 | $props = null; 687 | $level = $this->xmlnodes[$nodenum]['level']; 688 | $status = ''; 689 | while ( $this->xmlnodes[++$nodenum]['level'] >= $level ) { 690 | if ( $this->xmlnodes[$nodenum]['tag'] == 'DAV::propstat' ) { 691 | if ( $this->xmlnodes[$nodenum]['type'] == 'open' ) { 692 | $props = array(); 693 | $status = ''; 694 | } 695 | else { 696 | if ( $status == 'HTTP/1.1 200 OK' ) break; 697 | } 698 | } 699 | elseif ( !isset($this->xmlnodes[$nodenum]) || !is_array($this->xmlnodes[$nodenum]) ) { 700 | break; 701 | } 702 | elseif ( $this->xmlnodes[$nodenum]['tag'] == 'DAV::status' ) { 703 | $status = $this->xmlnodes[$nodenum]['value']; 704 | } 705 | else { 706 | $props[] = $this->xmlnodes[$nodenum]; 707 | } 708 | } 709 | return $props; 710 | } 711 | 712 | 713 | /** 714 | * Attack the given URL in an attempt to find a principal URL 715 | * 716 | * @param string $url The URL to find the principal-URL from 717 | */ 718 | function FindPrincipal( $url = null ) { 719 | $xml = $this->DoPROPFINDRequest( $url, array('resourcetype', 'current-user-principal', 'owner', 'principal-URL', 720 | 'urn:ietf:params:xml:ns:caldav:calendar-home-set'), 1); 721 | 722 | $principal_url = $this->HrefForProp('DAV::principal'); 723 | 724 | if ( !isset($principal_url) ) { 725 | foreach( array('DAV::current-user-principal', 'DAV::principal-URL', 'DAV::owner') AS $href ) { 726 | if ( !isset($principal_url) ) { 727 | $principal_url = $this->HrefValueInside($href); 728 | } 729 | } 730 | } 731 | 732 | return $this->PrincipalURL($principal_url); 733 | } 734 | 735 | 736 | /** 737 | * @param bool $recursed 738 | * @return array|array[] 739 | */ 740 | function FindCalendarHome( $recursed=false ) { 741 | if ( !isset($this->principal_url) ) { 742 | $this->FindPrincipal(); 743 | } 744 | if ( $recursed ) { 745 | $this->DoPROPFINDRequest( $this->first_url_part.$this->principal_url, array('urn:ietf:params:xml:ns:caldav:calendar-home-set'), 0); 746 | } 747 | 748 | $calendar_home = array(); 749 | if (isset($this->xmltags['urn:ietf:params:xml:ns:caldav:calendar-home-set'])) { 750 | foreach( $this->xmltags['urn:ietf:params:xml:ns:caldav:calendar-home-set'] AS $k => $v ) { 751 | if ( $this->xmlnodes[$v]['type'] != 'open' ) continue; 752 | while( $this->xmlnodes[++$v]['type'] != 'close' && $this->xmlnodes[$v]['tag'] != 'urn:ietf:params:xml:ns:caldav:calendar-home-set' ) { 753 | // printf( "Tag: '%s' = '%s'\n", $this->xmlnodes[$v]['tag'], $this->xmlnodes[$v]['value']); 754 | if ( $this->xmlnodes[$v]['tag'] == 'DAV::href' && isset($this->xmlnodes[$v]['value']) ) 755 | $calendar_home[] = rawurldecode($this->xmlnodes[$v]['value']); 756 | } 757 | } 758 | } 759 | 760 | if ( !$recursed && count($calendar_home) < 1 ) { 761 | $calendar_home = $this->FindCalendarHome(true); 762 | } 763 | 764 | return $this->CalendarHomeSet($calendar_home); 765 | } 766 | 767 | /** 768 | * Find own calendars 769 | * 770 | * @param bool $recursed 771 | * @return array 772 | */ 773 | function FindCalendars( $recursed=false ) { 774 | if ( !isset($this->calendar_home_set[0]) ) { 775 | $this->FindCalendarHome($recursed); 776 | } 777 | $properties = array( 778 | 'resourcetype', 779 | 'displayname', 780 | 'http://calendarserver.org/ns/:getctag', 781 | 'http://apple.com/ns/ical/:calendar-color', 782 | 'http://apple.com/ns/ical/:calendar-order', 783 | ); 784 | @$this->DoPROPFINDRequest( $this->first_url_part.$this->calendar_home_set[0], $properties, 1); 785 | 786 | return $this->parse_calendar_info(); 787 | } 788 | 789 | /** 790 | * Do a PROPFIND on a calendar and retrieve its information 791 | * 792 | * @param string $url 793 | * @return array 794 | */ 795 | function GetCalendarDetailsByURL($url) { 796 | $properties = array( 797 | 'resourcetype', 798 | 'displayname', 799 | 'http://calendarserver.org/ns/:getctag', 800 | 'http://apple.com/ns/ical/:calendar-color', 801 | 'http://apple.com/ns/ical/:calendar-order', 802 | ); 803 | $this->DoPROPFINDRequest($url, $properties, 0); 804 | 805 | return $this->parse_calendar_info(); 806 | } 807 | 808 | /** 809 | * Find the calendars, from the calendar_home_set 810 | * 811 | * @param string|null $url 812 | * @return CalDAVCalendar 813 | */ 814 | function GetCalendarDetails( $url = null ) { 815 | if ( isset($url) ) $this->SetCalendar($url); 816 | 817 | $calendar_properties = array( 'resourcetype', 'displayname', 'http://calendarserver.org/ns/:getctag', 'urn:ietf:params:xml:ns:caldav:calendar-timezone', 'supported-report-set' ); 818 | $this->DoPROPFINDRequest( $this->calendar_url, $calendar_properties, 0); 819 | 820 | $hnode = $this->xmltags['DAV::href'][0]; 821 | $href = rawurldecode($this->xmlnodes[$hnode]['value']); 822 | 823 | $calendar = new CalDAVCalendar($href); 824 | $ok_props = $this->GetOKProps($hnode); 825 | foreach( $ok_props AS $k => $v ) { 826 | $name = preg_replace( '{^.*:}', '', $v['tag'] ); 827 | if ( isset($v['value'] ) ) { 828 | $calendar->{$name} = $v['value']; 829 | } 830 | /* else { 831 | printf( "Calendar property '%s' has no text content\n", $v['tag'] ); 832 | }*/ 833 | } 834 | 835 | return $calendar; 836 | } 837 | 838 | 839 | /** 840 | * Get all etags for a calendar 841 | * 842 | * @param string|null $url 843 | * @return array 844 | */ 845 | function GetCollectionETags( $url = null ) { 846 | if ( isset($url) ) $this->SetCalendar($url); 847 | 848 | $this->DoPROPFINDRequest( $this->calendar_url, array('getetag'), 1); 849 | 850 | $etags = array(); 851 | if ( isset($this->xmltags['DAV::getetag']) ) { 852 | foreach( $this->xmltags['DAV::getetag'] AS $k => $v ) { 853 | $href = $this->HrefForProp('DAV::getetag', $k); 854 | if ( isset($href) && isset($this->xmlnodes[$v]['value']) ) $etags[$href] = $this->xmlnodes[$v]['value']; 855 | } 856 | } 857 | 858 | return $etags; 859 | } 860 | 861 | 862 | /** 863 | * Get a bunch of events for a calendar with a calendar-multiget report 864 | * 865 | * @param array $event_hrefs 866 | * @param string|null $url 867 | * @return array 868 | */ 869 | function CalendarMultiget( $event_hrefs, $url = null ) { 870 | 871 | if ( isset($url) ) $this->SetCalendar($url); 872 | 873 | $hrefs = ''; 874 | foreach( $event_hrefs AS $k => $href ) { 875 | $href = str_replace( rawurlencode('/'),'/',rawurlencode($href)); 876 | $hrefs .= ''.$href.''; 877 | } 878 | $this->body = << 880 | 881 | 882 | $hrefs 883 | 884 | EOXML; 885 | 886 | $this->requestMethod = "REPORT"; 887 | $this->SetContentType("text/xml"); 888 | $response = $this->DoRequest( $this->calendar_url ); 889 | 890 | $report = array(); 891 | foreach( $this->xmlnodes as $k => $v ) { 892 | switch( $v['tag'] ) { 893 | case 'DAV::response': 894 | if ( $v['type'] == 'open' ) { 895 | $response = array(); 896 | } 897 | elseif ( $v['type'] == 'close' ) { 898 | $report[] = $response; 899 | } 900 | break; 901 | case 'DAV::href': 902 | $response['href'] = basename( rawurldecode($v['value']) ); 903 | break; 904 | case 'DAV::getetag': 905 | $response['etag'] = preg_replace('/^"?([^"]+)"?/', '$1', $v['value']); 906 | break; 907 | case 'urn:ietf:params:xml:ns:caldav:calendar-data': 908 | $response['data'] = $v['value']; 909 | break; 910 | } 911 | } 912 | 913 | return $report; 914 | } 915 | 916 | 917 | /** 918 | * Given XML for a calendar query, return an array of the events (/todos) in the 919 | * response. Each event in the array will have a 'href', 'etag' and '$response_type' 920 | * part, where the 'href' is relative to the calendar and the '$response_type' contains the 921 | * definition of the calendar data in iCalendar format. 922 | * 923 | * @param string $filter XML fragment which is the element of a calendar-query 924 | * @param string $url The URL of the calendar, or null to use the 'current' calendar_url 925 | * 926 | * @return array An array of the relative URLs, etags, and events from the server. Each element of the array will 927 | * be an array with 'href', 'etag' and 'data' elements, corresponding to the URL, the server-supplied 928 | * etag (which only varies when the data changes) and the calendar data in iCalendar format. 929 | */ 930 | function DoCalendarQuery( $filter, $url = null ) { 931 | 932 | if ( isset($url) ) $this->SetCalendar($url); 933 | 934 | $this->body = << 936 | 937 | 938 | 939 | 940 | $filter 941 | 942 | EOXML; 943 | 944 | $this->requestMethod = "REPORT"; 945 | $this->SetContentType("text/xml"); 946 | $this->DoRequest( $this->calendar_url ); 947 | 948 | $report = array(); 949 | foreach( $this->xmlnodes as $k => $v ) { 950 | switch( $v['tag'] ) { 951 | case 'DAV::response': 952 | if ( $v['type'] == 'open' ) { 953 | $response = array(); 954 | } 955 | elseif ( $v['type'] == 'close' ) { 956 | $report[] = $response; 957 | } 958 | break; 959 | case 'DAV::href': 960 | $response['href'] = basename( rawurldecode($v['value']) ); 961 | break; 962 | case 'DAV::getetag': 963 | $response['etag'] = preg_replace('/^"?([^"]+)"?/', '$1', $v['value']); 964 | break; 965 | case 'urn:ietf:params:xml:ns:caldav:calendar-data': 966 | $response['data'] = $v['value']; 967 | break; 968 | } 969 | } 970 | return $report; 971 | } 972 | 973 | 974 | /** 975 | * Get the events in a range from $start to $finish. The dates should be in the 976 | * format yyyymmddThhmmssZ and should be in GMT. The events are returned as an 977 | * array of event arrays. Each event array will have a 'href', 'etag' and 'event' 978 | * part, where the 'href' is relative to the calendar and the event contains the 979 | * definition of the event in iCalendar format. 980 | * 981 | * @param string $start The start time for the period 982 | * @param string $finish The finish time for the period 983 | * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default null. 984 | * 985 | * @return array An array of the relative URLs, etags, and events, returned from DoCalendarQuery() @see DoCalendarQuery() 986 | */ 987 | function GetEvents( $start = null, $finish = null, $relative_url = null ) { 988 | $this->SetDepth('1'); 989 | $filter = ""; 990 | if ( isset($start) && isset($finish) ) 991 | $range = ""; 992 | elseif ( isset($start) && ! isset($finish) ) 993 | $range = ""; 994 | elseif ( ! isset($start) && isset($finish) ) 995 | $range = ""; 996 | else 997 | $range = ''; 998 | 999 | $filter = << 1001 | 1002 | 1003 | $range 1004 | 1005 | 1006 |
1007 | EOFILTER; 1008 | 1009 | return $this->DoCalendarQuery($filter, $relative_url); 1010 | } 1011 | 1012 | 1013 | /** 1014 | * Get the todo's in a range from $start to $finish. The dates should be in the 1015 | * format yyyymmddThhmmssZ and should be in GMT. The events are returned as an 1016 | * array of event arrays. Each event array will have a 'href', 'etag' and 'event' 1017 | * part, where the 'href' is relative to the calendar and the event contains the 1018 | * definition of the event in iCalendar format. 1019 | * 1020 | * @param string $start The start time for the period 1021 | * @param string $finish The finish time for the period 1022 | * @param boolean $completed Whether to include completed tasks 1023 | * @param boolean $cancelled Whether to include cancelled tasks 1024 | * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''. 1025 | * 1026 | * @return array An array of the relative URLs, etags, and events, returned from DoCalendarQuery() @see DoCalendarQuery() 1027 | */ 1028 | function GetTodos( $start = null, $finish = null, $completed = null, $cancelled = null, $relative_url = "" ) { 1029 | $this->SetDepth('1'); 1030 | 1031 | if ( isset($start) && isset($finish) ) 1032 | $range = ""; 1033 | elseif ( isset($start) && ! isset($finish) ) 1034 | $range = ""; 1035 | elseif ( ! isset($start) && isset($finish) ) 1036 | $range = ""; 1037 | else 1038 | $range = ''; 1039 | 1040 | 1041 | // Warning! May contain traces of double negatives... 1042 | if(isset($completed) && $completed == true) 1043 | $completed_filter = 'COMPLETED'; 1044 | else if(isset($completed) && $completed == false) 1045 | $completed_filter = 'COMPLETED'; 1046 | else 1047 | $completed_filter = ''; 1048 | 1049 | if(isset($cancelled) && $cancelled == true) 1050 | $cancelled_filter = 'CANCELLED'; 1051 | else if(isset($cancelled) && $cancelled == false) 1052 | $cancelled_filter = 'CANCELLED'; 1053 | else 1054 | $cancelled_filter = ''; 1055 | 1056 | $filter = << 1058 | 1059 | 1060 | $completed_filter 1061 | $cancelled_filter 1062 | $range 1063 | 1064 | 1065 |
1066 | EOFILTER; 1067 | 1068 | return $this->DoCalendarQuery($filter); 1069 | } 1070 | 1071 | 1072 | /** 1073 | * Get the calendar entry by UID 1074 | * 1075 | * @param string $uid 1076 | * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''. 1077 | * 1078 | * @return array An array of the relative URL, etag, and calendar data returned from DoCalendarQuery() @see DoCalendarQuery() 1079 | */ 1080 | function GetEntryByUid( $uid, $relative_url = null ) { 1081 | $this->SetDepth('1'); 1082 | $filter = ""; 1083 | if ( $uid ) { 1084 | $filter = << 1086 | 1087 | 1088 | 1089 | $uid 1090 | 1091 | 1092 | 1093 | 1094 | EOFILTER; 1095 | } 1096 | 1097 | return $this->DoCalendarQuery($filter, $relative_url); 1098 | } 1099 | 1100 | 1101 | /** 1102 | * Get the calendar entry by HREF 1103 | * 1104 | * @param string $href The href from a call to GetEvents or GetTodos etc. 1105 | * 1106 | * @return string The iCalendar of the calendar entry 1107 | */ 1108 | function GetEntryByHref( $href ) { 1109 | //$href = str_replace( rawurlencode('/'),'/',rawurlencode($href)); 1110 | $response = $this->DoGETRequest( $href ); 1111 | 1112 | $report = array(); 1113 | 1114 | if ( $this->GetHttpResultCode() == '404' ) { return $report; } 1115 | 1116 | $etag = null; 1117 | if ( preg_match( '{^ETag:\s+"([^"]*)"\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 1118 | else if ( preg_match( '{^ETag:\s+([^\s]*)\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 1119 | if ( !isset($etag) || $etag == '' ) { 1120 | // Try with HEAD 1121 | $save_request = $this->httpRequest; 1122 | $save_response_headers = $this->httpResponseHeaders; 1123 | $save_http_result = $this->httpResultCode; 1124 | $this->DoHEADRequest( $href ); 1125 | if ( preg_match( '{^Etag:\s+"([^"]*)"\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 1126 | else if ( preg_match( '{^ETag:\s+([^\s]*)\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 1127 | 1128 | /* 1129 | if ( !isset($etag) || $etag == '' ) { 1130 | printf( "Still No etag in:\n%s\n", $this->httpResponseHeaders ); 1131 | } 1132 | */ 1133 | $this->httpRequest = $save_request; 1134 | $this->httpResponseHeaders = $save_response_headers; 1135 | $this->httpResultCode = $save_http_result; 1136 | } 1137 | 1138 | $report = array(array('etag'=>$etag)); 1139 | 1140 | return $report; 1141 | } 1142 | 1143 | /** 1144 | * Get calendar info after a PROPFIND 1145 | */ 1146 | function parse_calendar_info() { 1147 | $calendars = array(); 1148 | if ( isset($this->xmltags['urn:ietf:params:xml:ns:caldav:calendar']) ) { 1149 | $calendar_urls = array(); 1150 | foreach( $this->xmltags['urn:ietf:params:xml:ns:caldav:calendar'] AS $k => $v ) { 1151 | $calendar_urls[$this->HrefForProp('urn:ietf:params:xml:ns:caldav:calendar', $k)] = 1; 1152 | } 1153 | 1154 | foreach( $this->xmltags['DAV::href'] AS $i => $hnode ) { 1155 | $href = rawurldecode($this->xmlnodes[$hnode]['value']); 1156 | 1157 | if ( !isset($calendar_urls[$href]) ) continue; 1158 | 1159 | // printf("Seems '%s' is a calendar.\n", $href ); 1160 | 1161 | 1162 | $calendar = new CalDAVCalendar($href); 1163 | 1164 | /* 1165 | * Transform href into calendar 1166 | * /xxxxx/yyyyy/caldav.php/principal/resource/ 1167 | * t-3 t-2 1168 | */ 1169 | $pieces = preg_split('/\//', $href); 1170 | $total = count($pieces); 1171 | $calendar_id = $pieces[$total-2]; 1172 | $calendar->setCalendarID($calendar_id); 1173 | 1174 | $ok_props = $this->GetOKProps($hnode); 1175 | foreach( $ok_props AS $v ) { 1176 | switch( $v['tag'] ) { 1177 | case 'http://calendarserver.org/ns/:getctag': 1178 | $calendar->setCtag((isset($v['value']) ? 1179 | $v['value'] : '-')); 1180 | break; 1181 | case 'DAV::displayname': 1182 | $calendar->setDisplayName((isset($v['value']) ? 1183 | $v['value'] : '-')); 1184 | break; 1185 | case 'http://apple.com/ns/ical/:calendar-color': 1186 | $calendar->setRBGcolor((isset($v['value']) ? 1187 | $this->_rgba2rgb($v['value']) : '-')); 1188 | break; 1189 | case 'http://apple.com/ns/ical/:calendar-order': 1190 | $calendar->setOrder((isset($v['value']) ? 1191 | $v['value'] : '-')); 1192 | break; 1193 | } 1194 | } 1195 | $calendars[$calendar->getCalendarID()] = $calendar; 1196 | } 1197 | } 1198 | 1199 | return $calendars; 1200 | } 1201 | /** 1202 | * Issues a PROPPATCH on a resource 1203 | * 1204 | * @param string XML request 1205 | * @param string URL 1206 | * @return TRUE on success, FALSE otherwise 1207 | */ 1208 | function DoPROPPATCH($xml_text, $url) { 1209 | $this->DoXMLRequest('PROPPATCH', $xml_text, $url); 1210 | 1211 | $errmsg = ''; 1212 | 1213 | if ($this->httpResultCode == '207') { 1214 | $errmsg = $this->httpResultCode; 1215 | // Find propstat tag(s) 1216 | if (isset($this->xmltags['DAV::propstat'])) { 1217 | foreach ($this->xmltags['DAV::propstat'] as $i => $node) { 1218 | if ($this->xmlnodes[$node]['type'] == 'close') { 1219 | continue; 1220 | } 1221 | // propstat @ $i: open 1222 | // propstat @ $i + 1: close 1223 | // Search for prop and status 1224 | $level = $this->xmlnodes[$node]['level']; 1225 | $level++; 1226 | 1227 | while ($this->xmlnodes[++$node]['level'] >= $level) { 1228 | if ($this->xmlnodes[$node]['tag'] == 'DAV::status' 1229 | && $this->xmlnodes[$node]['value'] != 1230 | 'HTTP/1.1 200 OK') { 1231 | return $this->xmlnodes[$node]['value']; 1232 | } 1233 | } 1234 | } 1235 | } 1236 | } else if ($this->httpResultCode != 200) { 1237 | return 'Unknown HTTP code'; 1238 | } 1239 | 1240 | return TRUE; 1241 | } 1242 | 1243 | /** 1244 | * Queries server using a principal-property search 1245 | * 1246 | * @param string XML request 1247 | * @param string URL 1248 | * @return FALSE on error, array with results otherwise 1249 | */ 1250 | function principal_property_search($xml_text, $url) { 1251 | $result = array(); 1252 | $this->DoXMLRequest('REPORT', $xml_text, $url); 1253 | 1254 | if ($this->httpResultCode == '207') { 1255 | $errmsg = $this->httpResultCode; 1256 | // Find response tag(s) 1257 | if (isset($this->xmltags['DAV::response'])) { 1258 | foreach ($this->xmltags['DAV::response'] as $i => $node) { 1259 | if ($this->xmlnodes[$node]['type'] == 'close') { 1260 | continue; 1261 | } 1262 | 1263 | $result[$i]['href'] = 1264 | $this->HrefForProp('DAV::response', $i+1); 1265 | 1266 | $level = $this->xmlnodes[$node]['level']; 1267 | $level++; 1268 | 1269 | $ok_props = $this->GetOKProps($node); 1270 | 1271 | foreach ($ok_props as $v) { 1272 | switch($v['tag']) { 1273 | case 'DAV::displayname': 1274 | $result[$i]['displayname'] = 1275 | isset($v['value']) ? $v['value'] : ''; 1276 | break; 1277 | case 'DAV::email': 1278 | $result[$i]['email'] = 1279 | isset($v['value']) ? $v['value'] : ''; 1280 | break; 1281 | } 1282 | } 1283 | 1284 | } 1285 | } 1286 | } else if ($this->httpResultCode != 200) { 1287 | return 'Unknown HTTP code'; 1288 | } 1289 | 1290 | return $result; 1291 | } 1292 | 1293 | /** 1294 | * Converts a RGBA hexadecimal string (#rrggbbXX) to RGB 1295 | */ 1296 | private function _rgba2rgb($s) { 1297 | if (strlen($s) == '9') { 1298 | return substr($s, 0, 7); 1299 | } else { 1300 | // Unknown string 1301 | return $s; 1302 | } 1303 | } 1304 | 1305 | public function printLastMessages() { 1306 | $string = ''; 1307 | $dom = new DOMDocument(); 1308 | $dom->preserveWhiteSpace = FALSE; 1309 | $dom->formatOutput = TRUE; 1310 | 1311 | $string .= '
';
1312 |         $string .= 'last request:

'; 1313 | 1314 | $string .= $this->httpRequest; 1315 | 1316 | if(!empty($this->body)) { 1317 | $dom->loadXML($this->body); 1318 | $string .= htmlentities($dom->saveXml()); 1319 | } 1320 | 1321 | $string .= '
last response:

'; 1322 | 1323 | $string .= $this->httpResponse; 1324 | 1325 | if(!empty($this->xmlResponse)) { 1326 | $dom->loadXML($this->xmlResponse); 1327 | $string .= htmlentities($dom->saveXml()); 1328 | } 1329 | 1330 | $string .= '
'; 1331 | 1332 | echo $string; 1333 | } 1334 | } 1335 | 1336 | /** 1337 | * Error handeling functions 1338 | */ 1339 | 1340 | $debug = TRUE; 1341 | 1342 | function log_message ($type, $message) { 1343 | global $debug; 1344 | if ($debug) { 1345 | echo '['.$type.'] '.$message.'\n'; 1346 | } 1347 | } 1348 | --------------------------------------------------------------------------------