├── SimpleCalDAVClient.php ├── include ├── README ├── Translation.php ├── XMLDocument.php ├── XMLElement.php └── AWLUtilities.php ├── TODO ├── .gitattributes ├── CalDAVObject.php ├── config └── listCalendars.php ├── README ├── CalDAVCalendar.php ├── CalDAVException.php ├── .gitignore ├── example code └── example.php ├── CalDAVFilter.php ├── COPYING └── CalDAVClient.php /SimpleCalDAVClient.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/derweili/simpleCalDAV/master/SimpleCalDAVClient.php -------------------------------------------------------------------------------- /include/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 -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /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 | class CalDAVObject { 25 | private $href; 26 | private $data; 27 | private $etag; 28 | 29 | public function __construct ($href, $data, $etag) { 30 | $this->href = $href; 31 | $this->data = $data; 32 | $this->etag = $etag; 33 | } 34 | 35 | 36 | // Getter 37 | 38 | public function getHref () { 39 | return $this->href; 40 | } 41 | 42 | public function getData () { 43 | return $this->data; 44 | } 45 | 46 | public function getEtag () { 47 | return $this->etag; 48 | } 49 | } 50 | 51 | ?> -------------------------------------------------------------------------------- /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('../SimpleCalDAVClient.php'); 15 | 16 | if($_POST == null) { 17 | echo ' 18 |
19 |

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.

20 |

Calendar-URL:

21 |

Username:

22 |

Password:

23 | 24 |
'; 25 | } 26 | 27 | else { 28 | $client = new SimpleCalDAVClient(); 29 | 30 | try { 31 | $client->connect($_POST['url'], $_POST['user'], $_POST['pass']); 32 | 33 | $calendars = $client->findCalendars(); 34 | 35 | echo' 36 | '; 37 | 38 | $i = 0; 39 | foreach($calendars as $cal) { 40 | $i++; 41 | 42 | echo ' 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | '; 51 | } 52 | 53 | echo ' 54 |
Calendar #'.$i.'
URL: '.$cal->getURL().'
Display Name: '.$cal->getDisplayName().'
Calendar ID: '.$cal->getCalendarID().'
CTAG: '.$cal->getCTag().'
RBG-Color: '.$cal->getRBGcolor().'
Order: '.$cal->getOrder().'
'; 55 | } 56 | 57 | catch (Exception $e) { 58 | echo $e->__toString(); 59 | } 60 | } 61 | 62 | ?> -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | simpleCalDAV 2 | 3 | Copyright 2014 Michael Palm 4 | 5 | Table of content 6 | 1. About 7 | 2. Requirements 8 | 3. Installation 9 | 4. How to get started 10 | 5. Example Code 11 | 12 | ------------------------ 13 | 14 | 1. About 15 | 16 | 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. 17 | 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. 18 | 19 | It contains the following functions: 20 | - connect() 21 | - findCalendars() 22 | - setCalendar() 23 | - create() 24 | - change() 25 | - delete() 26 | - getEvents() 27 | - getTODOs() 28 | - getCustomReport() 29 | 30 | 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. 31 | 32 | This library is heavily based on AgenDAV caldav-client-v2.php by Jorge López Pérez which again is heavily based on DAViCal caldav-client-v2.php by Andrew McMillan . 33 | 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. 34 | 35 | 36 | 2. Requirements 37 | 38 | Requirements of this library are 39 | - The php extension cURL ( http://www.php.net/manual/en/book.curl.php ) 40 | 41 | 42 | 3. Installation 43 | 44 | Just navigate into a directory on your server and execute 45 | git clone https://github.com/wvrzel/simpleCalDAV.git 46 | 47 | Assure yourself that cURL is installed. 48 | 49 | Import SimpleCalDAVClient.php in your code and you are ready to go ;-) 50 | 51 | 52 | 4. How to get started 53 | 54 | Read the comments in SimpleCalDAVClient.php and the example code. 55 | 56 | 57 | 5. Example Code 58 | 59 | Example code is provided under "/example code/". 60 | -------------------------------------------------------------------------------- /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 | class CalDAVCalendar { 31 | private $url; 32 | private $displayname; 33 | private $ctag; 34 | private $calendar_id; 35 | private $rgba_color; 36 | private $rbg_color; 37 | private $order; 38 | 39 | function __construct ( $url, $displayname = null, $ctag = null, $calendar_id = null, $rbg_color = null, $order = null ) { 40 | $this->url = $url; 41 | $this->displayname = $displayname; 42 | $this->ctag = $ctag; 43 | $this->calendar_id = $calendar_id; 44 | $this->rbg_color = $rbg_color; 45 | $this->order = $order; 46 | } 47 | 48 | function __toString () { 49 | return( '(URL: '.$this->url.' Ctag: '.$this->ctag.' Displayname: '.$this->displayname .')'. "\n" ); 50 | } 51 | 52 | // Getters 53 | 54 | function getURL () { 55 | return $this->url; 56 | } 57 | 58 | function getDisplayName () { 59 | return $this->displayname; 60 | } 61 | 62 | function getCTag () { 63 | return $this->ctag; 64 | } 65 | 66 | function getCalendarID () { 67 | return $this->calendar_id; 68 | } 69 | 70 | function getRBGcolor () { 71 | return $this->rbg_color; 72 | } 73 | 74 | function getOrder () { 75 | return $this->order; 76 | } 77 | 78 | 79 | // Setters 80 | 81 | function setURL ( $url ) { 82 | $this->url = $url; 83 | } 84 | 85 | function setDisplayName ( $displayname ) { 86 | $this->displayname = $displayname; 87 | } 88 | 89 | function setCtag ( $ctag ) { 90 | $this->ctag = $ctag; 91 | } 92 | 93 | function setCalendarID ( $calendar_id ) { 94 | $this->calendar_id = $calendar_id; 95 | } 96 | 97 | function setRBGcolor ( $rbg_color ) { 98 | $this->rbg_color = $rbg_color; 99 | } 100 | 101 | function setOrder ( $order ) { 102 | $this->order = $order; 103 | } 104 | } 105 | 106 | ?> -------------------------------------------------------------------------------- /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 | class CalDAVException extends Exception { 16 | private $requestHeader; 17 | private $requestBody; 18 | private $responseHeader; 19 | private $responseBody; 20 | 21 | public function __construct($message, $client, $code = 0, Exception $previous = null) { 22 | parent::__construct($message, $code, $previous); 23 | 24 | $this->requestHeader = $client->GetHttpRequest(); 25 | $this->requestBody = $client->GetBody(); 26 | $this->responseHeader = $client->GetResponseHeaders(); 27 | $this->responseBody = $client->GetResponseBody(); 28 | } 29 | 30 | public function __toString() { 31 | $string = ''; 32 | $dom = new DOMDocument(); 33 | $dom->preserveWhiteSpace = FALSE; 34 | $dom->formatOutput = TRUE; 35 | 36 | $string .= '
';
37 | 		$string .= 'Exception: '.$this->getMessage().'



'; 38 | $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.


'; 39 | $string .= '
For debugging purposes:
'; 40 | $string .= '
last request:

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

'; 52 | } 53 | 54 | $string .= '
last response:

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

'; 68 | 69 | $string .= 'Trace:

'.$this->getTraceAsString(); 70 | 71 | $string .= '
'; 72 | 73 | return $string; 74 | } 75 | 76 | public function getRequestHeader() { 77 | return $this->requestHeader; 78 | } 79 | 80 | public function getrequestBody() { 81 | return $this->requestBody; 82 | } 83 | 84 | public function getResponseHeader() { 85 | return $this->responseHeader; 86 | } 87 | 88 | public function getresponseBody() { 89 | return $this->responseBody; 90 | } 91 | } 92 | 93 | ?> -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################# 2 | ## Eclipse 3 | ################# 4 | 5 | *.pydevproject 6 | .project 7 | .metadata 8 | bin/ 9 | tmp/ 10 | *.tmp 11 | *.bak 12 | *.swp 13 | *~.nib 14 | local.properties 15 | .classpath 16 | .settings/ 17 | .loadpath 18 | 19 | # External tool builders 20 | .externalToolBuilders/ 21 | 22 | # Locally stored "Eclipse launch configurations" 23 | *.launch 24 | 25 | # CDT-specific 26 | .cproject 27 | 28 | # PDT-specific 29 | .buildpath 30 | 31 | 32 | ################# 33 | ## Visual Studio 34 | ################# 35 | 36 | ## Ignore Visual Studio temporary files, build results, and 37 | ## files generated by popular Visual Studio add-ons. 38 | 39 | # User-specific files 40 | *.suo 41 | *.user 42 | *.sln.docstates 43 | 44 | # Build results 45 | 46 | [Dd]ebug/ 47 | [Rr]elease/ 48 | x64/ 49 | build/ 50 | [Bb]in/ 51 | [Oo]bj/ 52 | 53 | # MSTest test Results 54 | [Tt]est[Rr]esult*/ 55 | [Bb]uild[Ll]og.* 56 | 57 | *_i.c 58 | *_p.c 59 | *.ilk 60 | *.meta 61 | *.obj 62 | *.pch 63 | *.pdb 64 | *.pgc 65 | *.pgd 66 | *.rsp 67 | *.sbr 68 | *.tlb 69 | *.tli 70 | *.tlh 71 | *.tmp 72 | *.tmp_proj 73 | *.log 74 | *.vspscc 75 | *.vssscc 76 | .builds 77 | *.pidb 78 | *.log 79 | *.scc 80 | 81 | # Visual C++ cache files 82 | ipch/ 83 | *.aps 84 | *.ncb 85 | *.opensdf 86 | *.sdf 87 | *.cachefile 88 | 89 | # Visual Studio profiler 90 | *.psess 91 | *.vsp 92 | *.vspx 93 | 94 | # Guidance Automation Toolkit 95 | *.gpState 96 | 97 | # ReSharper is a .NET coding add-in 98 | _ReSharper*/ 99 | *.[Rr]e[Ss]harper 100 | 101 | # TeamCity is a build add-in 102 | _TeamCity* 103 | 104 | # DotCover is a Code Coverage Tool 105 | *.dotCover 106 | 107 | # NCrunch 108 | *.ncrunch* 109 | .*crunch*.local.xml 110 | 111 | # Installshield output folder 112 | [Ee]xpress/ 113 | 114 | # DocProject is a documentation generator add-in 115 | DocProject/buildhelp/ 116 | DocProject/Help/*.HxT 117 | DocProject/Help/*.HxC 118 | DocProject/Help/*.hhc 119 | DocProject/Help/*.hhk 120 | DocProject/Help/*.hhp 121 | DocProject/Help/Html2 122 | DocProject/Help/html 123 | 124 | # Click-Once directory 125 | publish/ 126 | 127 | # Publish Web Output 128 | *.Publish.xml 129 | *.pubxml 130 | 131 | # NuGet Packages Directory 132 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 133 | #packages/ 134 | 135 | # Windows Azure Build Output 136 | csx 137 | *.build.csdef 138 | 139 | # Windows Store app package directory 140 | AppPackages/ 141 | 142 | # Others 143 | sql/ 144 | *.Cache 145 | ClientBin/ 146 | [Ss]tyle[Cc]op.* 147 | ~$* 148 | *~ 149 | *.dbmdl 150 | *.[Pp]ublish.xml 151 | *.pfx 152 | *.publishsettings 153 | 154 | # RIA/Silverlight projects 155 | Generated_Code/ 156 | 157 | # Backup & report files from converting an old project file to a newer 158 | # Visual Studio version. Backup files are not needed, because we have git ;-) 159 | _UpgradeReport_Files/ 160 | Backup*/ 161 | UpgradeLog*.XML 162 | UpgradeLog*.htm 163 | 164 | # SQL Server files 165 | App_Data/*.mdf 166 | App_Data/*.ldf 167 | 168 | ############# 169 | ## Windows detritus 170 | ############# 171 | 172 | # Windows image file caches 173 | Thumbs.db 174 | ehthumbs.db 175 | 176 | # Folder config file 177 | Desktop.ini 178 | 179 | # Recycle Bin used on file shares 180 | $RECYCLE.BIN/ 181 | 182 | # Mac crap 183 | .DS_Store 184 | 185 | 186 | ############# 187 | ## Python 188 | ############# 189 | 190 | *.py[co] 191 | 192 | # Packages 193 | *.egg 194 | *.egg-info 195 | dist/ 196 | build/ 197 | eggs/ 198 | parts/ 199 | var/ 200 | sdist/ 201 | develop-eggs/ 202 | .installed.cfg 203 | 204 | # Installer logs 205 | pip-log.txt 206 | 207 | # Unit test / coverage reports 208 | .coverage 209 | .tox 210 | 211 | #Translations 212 | *.mo 213 | 214 | #Mr Developer 215 | .mr.developer.cfg 216 | /AWLUtilities.php 217 | /index.php 218 | /Translation.php 219 | /XMLDocument.php 220 | /XMLElement.php 221 | -------------------------------------------------------------------------------- /include/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'); 118 | 119 | $arrayOfCalendars = $client->findCalendars(); // Returns an array of all accessible calendars on the server. 120 | 121 | $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 122 | 123 | 124 | 125 | 126 | 127 | /* 128 | * You can create calendar objects (e.g. events, todos,...) on the server with create(). 129 | * Just pass a string with the iCalendar-data which should be saved on the server. 130 | * The function returns a CalDAVObject (see CalDAVObject.php) with the stored information about the new object on the server 131 | */ 132 | 133 | $firstNewEventOnServer = $client->create($firstNewEvent); // Creates $firstNewEvent on the server and a CalDAVObject representing the event. 134 | $secondNewEventOnServer = $client->create($secondNewEvent); // Creates $firstNewEvent on the server and a CalDAVObject representing the event. 135 | 136 | 137 | 138 | 139 | 140 | /* 141 | * You can getEvents with getEvents() 142 | */ 143 | $client->getEvents('20140418T103000Z', '20140419T200000Z'); // Returns array($firstNewEventOnServer, $secondNewEventOnServer); 144 | 145 | /* 146 | * An CalDAVObject $o has three attributes 147 | * $o->getHref(): Link to the object on the server 148 | * $o->getData(): The iCalendar-data describing the object 149 | * $o->getEtag(): see CalDAVObject.php 150 | * 151 | * $o->getHref() and $o->getEtag() can be used to change or to delete the object. 152 | * $o->getData() can be processed further on, e.g. printed 153 | */ 154 | 155 | $firstNewEventOnServer = $client->change($firstNewEventOnServer->getHref(),$changedFirstEvent, $firstNewEventOnServer->getEtag()); 156 | // Change the first event on the server from $firstNewEvent to $changedFirstEvent 157 | // and overwrite $firstNewEventOnServer with the new representation of the changed event on the server. 158 | 159 | $events = $client->getEvents('20140418T103000Z', '20140419T200000Z'); // Returns array($secondNewEventOnServer); 160 | 161 | echo $events[0]->getData(); // Prints $secondNewEvent. See CalDAVObject.php 162 | 163 | $client->delete($secondNewEventOnServer->getHref(), $secondNewEventOnServer->getEtag()); // Deletes the second new event from the server. 164 | 165 | $client->getEvents('20140418T103000Z', '20140419T200000Z'); // Returns an empty array 166 | 167 | 168 | 169 | 170 | 171 | /* 172 | * You can create custom queries to the server via CalDAVFilter. See CalDAVFilter.php 173 | */ 174 | 175 | $filter = new CalDAVFilter("VEVENT"); 176 | $filter->mustInclude("SUMMARY"); // Should include a SUMMARY 177 | $filter->mustInclude("PRIORITY", TRUE); // Should not include a PRIORITY 178 | $filter->mustIncludeMatchSubstr("DESCRIPTION", "ExampleDescription2", TRUE); // "ExampleDescription1" should not be a substring of the DESCRIPTION 179 | $filter->mustOverlapWithTimerange(NULL, "20140420T100000Z"); 180 | $events = $client->getCustomReport($filter->toXML()); // Returns array($changedFirstEvent) 181 | 182 | $client->delete($events[0]->getHref(), $events[0]->getEtag()); // Deletes the changed first event from the server. 183 | } 184 | 185 | catch (Exception $e) { 186 | echo $e->__toString(); 187 | } 188 | 189 | ?> -------------------------------------------------------------------------------- /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 | class CalDAVFilter { 26 | private $resourceType; 27 | private $mustIncludes = array(); 28 | 29 | /* 30 | * @param $type The type of resource you want to get. Has to be either 31 | * "VEVENT", "VTODO", "VJOURNAL", "VFREEBUSY" or "VALARM". 32 | * You have to decide. 33 | */ 34 | public function __construct ( $type ) { 35 | $this->resourceType = $type; 36 | } 37 | 38 | /** 39 | * function mustInclude() 40 | * Specifies that a certin property has to be included. The content of the 41 | * property is irrelevant. 42 | * 43 | * Only call this function and mustIncludeMatchSubstr() once per property! 44 | * 45 | * Examples: 46 | * mustInclude("SUMMARY"); specifies that all returned resources have to 47 | * have the SUMMARY-property. 48 | * mustInclude("LOCATION "); specifies that all returned resources have to 49 | * have the LOCATION-property. 50 | * 51 | * Arguments: 52 | * @param $field The name of the property. For a full list of valid 53 | * property names see http://www.rfcreader.com/#rfc5545_line3622 54 | * Note that the server might not support all of them. 55 | * @param $inverse Makes the effect inverse: The resource must NOT include 56 | * the property $field 57 | */ 58 | public function mustInclude ( $field, $inverse = FALSE ) { 59 | $this->mustIncludes[] = array("mustInclude", $field, $inverse); 60 | } 61 | 62 | /** 63 | * function mustIncludeMatchSubstr() 64 | * Specifies that a certin property has to be included and that its value 65 | * has to match a given substring. 66 | * 67 | * Only call this function and mustInclude() once per property! 68 | * 69 | * Examples: 70 | * mustIncludeMatchSubstr("SUMMARY", "a part of the summary"); would return 71 | * a resource with "SUMMARY:This is a part of the summary" included, but no 72 | * resource with "SUMMARY:This is a part of the". 73 | * 74 | * Arguments: 75 | * @param $field The name of the property. For a full list of valid 76 | * property names see http://www.rfcreader.com/#rfc5545_line3622 77 | * Note that the server might not support all of them. 78 | * @param $substring Substring to match against the value of the property. 79 | * @param $inverse Makes the effect inverse: The property value must NOT 80 | * include the $substring 81 | */ 82 | public function mustIncludeMatchSubstr ( $field, $substring, $inverse = FALSE ) { 83 | $this->mustIncludes[] = array("mustIncludeMatchSubstr", $field, $substring, $inverse); 84 | } 85 | 86 | /** 87 | * function mustOverlapWithTimerange() 88 | * Specifies that the resource has to overlap with a given timerange. 89 | * @see http://www.rfcreader.com/#rfc4791_line3944 90 | * 91 | * Only call this function once per CalDAVFilter-object! 92 | * 93 | * Arguments: 94 | * @param $start The starting point of the time interval. Must be in the format yyyymmddThhmmssZ and should be in 95 | * GMT. If omitted the value is set to -infinity. 96 | * @param $end The end 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 | */ 99 | public function mustOverlapWithTimerange ( $start = NULL, $end = NULL) { 100 | // Are $start and $end in the correct format? 101 | if ( ( isset($start) and ! preg_match( '#^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ$#', $start, $matches ) ) 102 | or ( isset($end) and ! preg_match( '#^\d\d\d\d\d\d\d\dT\d\d\d\d\d\dZ$#', $end, $matches ) ) ) 103 | { trigger_error('$start or $end are in the wrong format. They must have the format yyyymmddThhmmssZ and should be in GMT', E_USER_ERROR); } 104 | 105 | $this->mustIncludes[] = array("mustOverlapWithTimerange", $start, $end); 106 | } 107 | 108 | /** 109 | * Transforms the filter to xml-code for the server. Used to pass as 110 | * argument for SimpleCalDAVClient->getCustomReport() 111 | * 112 | * Example: 113 | * $simpleCalDAVClient->getCustomReport($filter->toXML()); 114 | * 115 | * @see SimpleCalDAVClient.php 116 | */ 117 | public function toXML () { 118 | $xml = ''; 119 | 120 | foreach($this->mustIncludes as $filter) { 121 | switch($filter[0]) { 122 | case "mustInclude": 123 | $xml .= ''; 132 | break; 133 | 134 | case "mustOverlapWithTimerange": 135 | if($this->resourceType == "VTODO") $xml .= ''; 136 | $xml .= 'resourceType == "VTODO") $xml .= ''; 141 | break; 142 | } 143 | } 144 | 145 | $xml .= ''; 146 | 147 | return $xml; 148 | } 149 | } 150 | 151 | ?> -------------------------------------------------------------------------------- /include/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 | require_once("XMLElement.php"); 14 | 15 | /** 16 | * A class for XML Documents which will contain namespaced XML elements 17 | * 18 | * @package awl 19 | */ 20 | class XMLDocument { 21 | 22 | /**#@+ 23 | * @access private 24 | */ 25 | /** 26 | * holds the namespaces which this document has been configured for. 27 | * @var namespaces 28 | */ 29 | private $namespaces; 30 | 31 | /** 32 | * holds the prefixes which are shorthand for the namespaces. 33 | * @var prefixes 34 | */ 35 | private $prefixes; 36 | 37 | /** 38 | * Holds the root document for the tree 39 | * @var root 40 | */ 41 | private $root; 42 | 43 | /** 44 | * Simple XMLDocument constructor 45 | * 46 | * @param array $namespaces An array of 'namespace' => 'prefix' pairs, where the prefix is used as a short form for the namespace. 47 | */ 48 | function __construct( $namespaces = null ) { 49 | $this->namespaces = array(); 50 | $this->prefixes = array(); 51 | if ( $namespaces != null ) { 52 | foreach( $namespaces AS $ns => $prefix ) { 53 | $this->namespaces[$ns] = $prefix; 54 | $this->prefixes[$prefix] = $prefix; 55 | } 56 | } 57 | $this->next_prefix = 0; 58 | } 59 | 60 | /** 61 | * Add a new namespace to the document, optionally specifying it's short prefix 62 | * 63 | * @param string $namespace The full namespace name to be added 64 | * @param string $prefix An optional short form for the namespace. 65 | */ 66 | function AddNamespace( $namespace, $prefix = null ) { 67 | if ( !isset($this->namespaces[$namespace]) ) { 68 | if ( isset($prefix) && ($prefix == "" || isset($this->prefixes[$prefix])) ) $prefix = null; 69 | if ( $prefix == null ) { 70 | // Try and build a prefix based on the first alphabetic character of the last element of the namespace 71 | if ( preg_match('/^(.*):([^:]+)$/', $namespace, $matches) ) { 72 | $alpha = preg_replace( '/[^a-z]/i', '', $matches[2] ); 73 | $prefix = strtoupper(substr($alpha,0,1)); 74 | } 75 | else { 76 | $prefix = 'X'; 77 | } 78 | $i = ""; 79 | if ( isset($this->prefixes[$prefix]) ) { 80 | for ( $i=1; $i<10 && isset($this->prefixes["$prefix$i"]); $i++ ) { 81 | } 82 | } 83 | if ( isset($this->prefixes["$prefix$i"]) ) { 84 | dbg_error_log("ERROR", "Cannot find a free prefix for this namespace"); 85 | exit; 86 | } 87 | $prefix = "$prefix$i"; 88 | dbg_error_log("XMLDocument", "auto-assigning prefix of '%s' for ns of '%s'", $prefix, $namespace ); 89 | } 90 | else if ( $prefix == "" || isset($this->prefixes[$prefix]) ) { 91 | dbg_error_log("ERROR", "Cannot assign the same prefix to two different namespaces"); 92 | exit; 93 | } 94 | 95 | $this->prefixes[$prefix] = $prefix; 96 | $this->namespaces[$namespace] = $prefix; 97 | } 98 | else { 99 | if ( isset($this->namespaces[$namespace]) && $this->namespaces[$namespace] != $prefix ) { 100 | dbg_error_log("ERROR", "Cannot use the same namespace with two different prefixes"); 101 | exit; 102 | } 103 | $this->prefixes[$prefix] = $prefix; 104 | $this->namespaces[$namespace] = $prefix; 105 | } 106 | } 107 | 108 | /** 109 | * Return the default namespace for this document 110 | */ 111 | function DefaultNamespace() { 112 | foreach( $this->namespaces AS $k => $v ) { 113 | if ( $v == '' ) { 114 | return $k; 115 | } 116 | } 117 | return ''; 118 | } 119 | 120 | /** 121 | * Return a tag with namespace stripped and replaced with a short form, and the ns added to the document. 122 | * 123 | */ 124 | function GetXmlNsArray() { 125 | 126 | $ns = array(); 127 | foreach( $this->namespaces AS $n => $p ) { 128 | if ( $p == "" ) $ns["xmlns"] = $n; else $ns["xmlns:$p"] = $n; 129 | } 130 | 131 | return $ns; 132 | } 133 | 134 | 135 | /** 136 | * Return a tag with namespace stripped and replaced with a short form, and the ns added to the document. 137 | * 138 | * @param string $in_tag The tag we want a namespace prefix on. 139 | * @param string $namespace The namespace we want it in (which will be parsed from $in_tag if not present 140 | * @param string $prefix The prefix we would like to use. Leave it out and one will be assigned. 141 | * 142 | * @return string The tag with a namespace prefix consistent with previous tags in this namespace. 143 | */ 144 | function Tag( $in_tag, $namespace=null, $prefix=null ) { 145 | 146 | if ( $namespace == null ) { 147 | // Attempt to split out from namespace:tag 148 | if ( preg_match('/^(.*):([^:]+)$/', $in_tag, $matches) ) { 149 | $namespace = $matches[1]; 150 | $tag = $matches[2]; 151 | } 152 | else { 153 | // There is nothing we can do here 154 | return $in_tag; 155 | } 156 | } 157 | else { 158 | $tag = $in_tag; 159 | } 160 | 161 | if ( !isset($this->namespaces[$namespace]) ) { 162 | $this->AddNamespace( $namespace, $prefix ); 163 | } 164 | $prefix = $this->namespaces[$namespace]; 165 | 166 | return $prefix . ($prefix == "" ? "" : ":") . $tag; 167 | } 168 | 169 | static public $ns_dav = 'DAV:'; 170 | static public $ns_caldav = 'urn:ietf:params:xml:ns:caldav'; 171 | static public $ns_carddav = 'urn:ietf:params:xml:ns:carddav'; 172 | static public $ns_calendarserver = 'http://calendarserver.org/ns/'; 173 | 174 | /** 175 | * Special helper for namespaced tags. 176 | * 177 | * @param object $element The tag are adding a new namespaced element to 178 | * @param string $tag the tag name, possibly prefixed with the namespace 179 | * @param mixed $content The content of the tag 180 | * @param array $attributes An array of key/value pairs of attributes. 181 | * @param string $namespace The namespace for the tag 182 | * 183 | */ 184 | function NSElement( &$element, $in_tag, $content=false, $attributes=false, $namespace=null ) { 185 | if ( $namespace == null && preg_match('/^(.*):([^:]+)$/', $in_tag, $matches) ) { 186 | $namespace = $matches[1]; 187 | if ( preg_match('{^[A-Z][A-Z0-9]*$}', $namespace ) ) { 188 | throw new Exception("Dodgy looking namespace from '".$in_tag."'!"); 189 | } 190 | $tag = $matches[2]; 191 | } 192 | else { 193 | $tag = $in_tag; 194 | if ( isset($namespace) ) { 195 | $tag = str_replace($namespace.':', '', $tag); 196 | } 197 | } 198 | 199 | if ( isset($namespace) && !isset($this->namespaces[$namespace]) ) $this->AddNamespace( $namespace ); 200 | return $element->NewElement( $tag, $content, $attributes, $namespace ); 201 | } 202 | 203 | 204 | /** 205 | * Special helper for tags in the DAV: namespace. 206 | * 207 | * @param object $element The tag are adding a new namespaced element to 208 | * @param string $tag the tag name 209 | * @param mixed $content The content of the tag 210 | * @param array $attributes An array of key/value pairs of attributes. 211 | */ 212 | function DAVElement( &$element, $tag, $content=false, $attributes=false ) { 213 | if ( !isset($this->namespaces[self::$ns_dav]) ) $this->AddNamespace( self::$ns_dav, '' ); 214 | return $this->NSElement( $element, $tag, $content, $attributes, self::$ns_dav ); 215 | } 216 | 217 | /** 218 | * Special helper for tags in the urn:ietf:params:xml:ns:caldav namespace. 219 | * 220 | * @param object $element The tag are adding a new namespaced element to 221 | * @param string $tag the tag name 222 | * @param mixed $content The content of the tag 223 | * @param array $attributes An array of key/value pairs of attributes. 224 | */ 225 | function CalDAVElement( &$element, $tag, $content=false, $attributes=false ) { 226 | if ( !isset($this->namespaces[self::$ns_caldav]) ) $this->AddNamespace( self::$ns_caldav, 'C' ); 227 | return $this->NSElement( $element, $tag, $content, $attributes, self::$ns_caldav ); 228 | } 229 | 230 | 231 | /** 232 | * Special helper for tags in the urn:ietf:params:xml:ns:carddav namespace. 233 | * 234 | * @param object $element The tag are adding a new namespaced element to 235 | * @param string $tag the tag name 236 | * @param mixed $content The content of the tag 237 | * @param array $attributes An array of key/value pairs of attributes. 238 | */ 239 | function CardDAVElement( &$element, $tag, $content=false, $attributes=false ) { 240 | if ( !isset($this->namespaces[self::$ns_carddav]) ) $this->AddNamespace( self::$ns_carddav, 'VC' ); 241 | return $this->NSElement( $element, $tag, $content, $attributes, self::$ns_carddav ); 242 | } 243 | 244 | 245 | /** 246 | * Special helper for tags in the urn:ietf:params:xml:ns:caldav namespace. 247 | * 248 | * @param object $element The tag are adding a new namespaced element to 249 | * @param string $tag the tag name 250 | * @param mixed $content The content of the tag 251 | * @param array $attributes An array of key/value pairs of attributes. 252 | */ 253 | function CalendarserverElement( &$element, $tag, $content=false, $attributes=false ) { 254 | if ( !isset($this->namespaces[self::$ns_calendarserver]) ) $this->AddNamespace( self::$ns_calendarserver, 'A' ); 255 | return $this->NSElement( $element, $tag, $content, $attributes, self::$ns_calendarserver ); 256 | } 257 | 258 | 259 | /** 260 | * @param string $in_tag The tag name of the new element, possibly namespaced 261 | * @param mixed $content Either a string of content, or an array of sub-elements 262 | * @param array $attributes An array of attribute name/value pairs 263 | * @param array $xmlns An XML namespace specifier 264 | */ 265 | function NewXMLElement( $in_tag, $content=false, $attributes=false, $xmlns=null ) { 266 | if ( $xmlns == null && preg_match('/^(.*):([^:]+)$/', $in_tag, $matches) ) { 267 | $xmlns = $matches[1]; 268 | $tagname = $matches[2]; 269 | } 270 | else { 271 | $tagname = $in_tag; 272 | } 273 | 274 | if ( isset($xmlns) && !isset($this->namespaces[$xmlns]) ) $this->AddNamespace( $xmlns ); 275 | return new XMLElement($tagname, $content, $attributes, $xmlns ); 276 | } 277 | 278 | /** 279 | * Render the document tree into (nicely formatted) XML 280 | * 281 | * @param mixed $root A root XMLElement or a tagname to create one with the remaining parameters. 282 | * @param mixed $content Either a string of content, or an array of sub-elements 283 | * @param array $attributes An array of attribute name/value pairs 284 | * @param array $xmlns An XML namespace specifier 285 | * 286 | * @return A rendered namespaced XML document. 287 | */ 288 | function Render( $root, $content=false, $attributes=false, $xmlns=null ) { 289 | if ( is_object($root) ) { 290 | /** They handed us a pre-existing object. We'll just use it... */ 291 | $this->root = $root; 292 | } 293 | else { 294 | /** We got a tag name, so we need to create the root element */ 295 | $this->root = $this->NewXMLElement( $root, $content, $attributes, $xmlns ); 296 | } 297 | 298 | /** 299 | * Add our namespace attributes here. 300 | */ 301 | foreach( $this->namespaces AS $n => $p ) { 302 | $this->root->SetAttribute( 'xmlns'.($p == '' ? '' : ':') . $p, $n); 303 | } 304 | 305 | /** And render... */ 306 | return $this->root->Render(0,''); 307 | } 308 | 309 | /** 310 | * Return a DAV::href XML element, or an array of them 311 | * @param mixed $url The URL (or array of URLs) to be wrapped in DAV::href tags 312 | * 313 | * @return XMLElement The newly created XMLElement object. 314 | */ 315 | function href($url) { 316 | if ( is_array($url) ) { 317 | $set = array(); 318 | foreach( $url AS $href ) { 319 | $set[] = $this->href( $href ); 320 | } 321 | return $set; 322 | } 323 | if ( preg_match('[@+ ]',$url) ) { 324 | trace_bug('URL "%s" was not encoded before call to XMLDocument::href()', $url ); 325 | $url = str_replace( '%2F', '/', rawurlencode($url)); 326 | } 327 | return $this->NewXMLElement('href', $url, false, 'DAV:'); 328 | } 329 | 330 | } 331 | 332 | 333 | -------------------------------------------------------------------------------- /include/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 | require_once('AWLUtilities.php'); 13 | 14 | /** 15 | * A class for XML elements which may have attributes, or contain 16 | * other XML sub-elements 17 | * 18 | * @package awl 19 | */ 20 | class XMLElement { 21 | protected $tagname; 22 | protected $xmlns; 23 | protected $attributes; 24 | protected $content; 25 | protected $_parent; 26 | 27 | /** 28 | * Constructor - nothing fancy as yet. 29 | * 30 | * @param string $tagname The tag name of the new element 31 | * @param mixed $content Either a string of content, or an array of sub-elements 32 | * @param array $attributes An array of attribute name/value pairs 33 | * @param string $xmlns An XML namespace specifier 34 | */ 35 | function __construct( $tagname, $content=false, $attributes=false, $xmlns=null ) { 36 | $this->tagname=$tagname; 37 | if ( gettype($content) == "object" ) { 38 | // Subtree to be parented here 39 | $this->content = array(&$content); 40 | } 41 | else { 42 | // Array or text 43 | $this->content = $content; 44 | } 45 | $this->attributes = $attributes; 46 | if ( isset($xmlns) ) { 47 | $this->xmlns = $xmlns; 48 | } 49 | else { 50 | if ( preg_match( '{^(.*):([^:]*)$}', $tagname, $matches) ) { 51 | $prefix = $matches[1]; 52 | $tag = $matches[2]; 53 | if ( isset($this->attributes['xmlns:'.$prefix]) ) { 54 | $this->xmlns = $this->attributes['xmlns:'.$prefix]; 55 | } 56 | } 57 | else if ( isset($this->attributes['xmlns']) ) { 58 | $this->xmlns = $this->attributes['xmlns']; 59 | } 60 | } 61 | } 62 | 63 | 64 | /** 65 | * Count the number of elements 66 | * @return int The number of elements 67 | */ 68 | function CountElements( ) { 69 | if ( $this->content === false ) return 0; 70 | if ( is_array($this->content) ) return count($this->content); 71 | if ( $this->content == '' ) return 0; 72 | return 1; 73 | } 74 | 75 | /** 76 | * Set an element attribute to a value 77 | * 78 | * @param string The attribute name 79 | * @param string The attribute value 80 | */ 81 | function SetAttribute($k,$v) { 82 | if ( gettype($this->attributes) != "array" ) $this->attributes = array(); 83 | $this->attributes[$k] = $v; 84 | if ( strtolower($k) == 'xmlns' ) { 85 | $this->xmlns = $v; 86 | } 87 | } 88 | 89 | /** 90 | * Set the whole content to a value 91 | * 92 | * @param mixed The element content, which may be text, or an array of sub-elements 93 | */ 94 | function SetContent($v) { 95 | $this->content = $v; 96 | } 97 | 98 | /** 99 | * Accessor for the tag name 100 | * 101 | * @return string The tag name of the element 102 | */ 103 | function GetTag() { 104 | return $this->tagname; 105 | } 106 | 107 | /** 108 | * Accessor for the full-namespaced tag name 109 | * 110 | * @return string The tag name of the element, prefixed by the namespace 111 | */ 112 | function GetNSTag() { 113 | return (empty($this->xmlns) ? '' : $this->xmlns . ':') . $this->tagname; 114 | } 115 | 116 | /** 117 | * Accessor for a single attribute 118 | * @param string $attr The name of the attribute. 119 | * @return string The value of that attribute of the element 120 | */ 121 | function GetAttribute( $attr ) { 122 | if ( $attr == 'xmlns' ) return $this->xmlns; 123 | if ( isset($this->attributes[$attr]) ) return $this->attributes[$attr]; 124 | return null; 125 | } 126 | 127 | /** 128 | * Accessor for the attributes 129 | * 130 | * @return array The attributes of this element 131 | */ 132 | function GetAttributes() { 133 | return $this->attributes; 134 | } 135 | 136 | /** 137 | * Accessor for the content 138 | * 139 | * @return array The content of this element 140 | */ 141 | function GetContent() { 142 | return $this->content; 143 | } 144 | 145 | /** 146 | * Return an array of elements matching the specified tag, or all elements if no tag is supplied. 147 | * Unlike GetContent() this will always return an array. 148 | * 149 | * @return array The XMLElements within the tree which match this tag 150 | */ 151 | function GetElements( $tag=null, $recursive=false ) { 152 | $elements = array(); 153 | if ( gettype($this->content) == "array" ) { 154 | foreach( $this->content AS $k => $v ) { 155 | if ( empty($tag) || $v->GetNSTag() == $tag ) { 156 | $elements[] = $v; 157 | } 158 | if ( $recursive ) { 159 | $elements = $elements + $v->GetElements($tag,true); 160 | } 161 | } 162 | } 163 | else if ( empty($tag) || (isset($v->content->tagname) && $v->content->GetNSTag() == $tag) ) { 164 | $elements[] = $this->content; 165 | } 166 | return $elements; 167 | } 168 | 169 | 170 | /** 171 | * Return an array of elements matching the specified path 172 | * 173 | * @return array The XMLElements within the tree which match this tag 174 | */ 175 | function GetPath( $path ) { 176 | $elements = array(); 177 | // printf( "Querying within '%s' for path '%s'\n", $this->tagname, $path ); 178 | if ( !preg_match( '#(/)?([^/]+)(/?.*)$#', $path, $matches ) ) return $elements; 179 | // printf( "Matches: %s -- %s -- %s\n", $matches[1], $matches[2], $matches[3] ); 180 | if ( $matches[2] == '*' || $matches[2] == $this->GetNSTag()) { 181 | if ( $matches[3] == '' ) { 182 | /** 183 | * That is the full path 184 | */ 185 | $elements[] = $this; 186 | } 187 | else if ( gettype($this->content) == "array" ) { 188 | /** 189 | * There is more to the path, so we recurse into that sub-part 190 | */ 191 | foreach( $this->content AS $k => $v ) { 192 | $elements = array_merge( $elements, $v->GetPath($matches[3]) ); 193 | } 194 | } 195 | } 196 | 197 | if ( $matches[1] != '/' && gettype($this->content) == "array" ) { 198 | /** 199 | * If our input $path was not rooted, we recurse further 200 | */ 201 | foreach( $this->content AS $k => $v ) { 202 | $elements = array_merge( $elements, $v->GetPath($path) ); 203 | } 204 | } 205 | // printf( "Found %d within '%s' for path '%s'\n", count($elements), $this->tagname, $path ); 206 | return $elements; 207 | } 208 | 209 | 210 | /** 211 | * Add a sub-element 212 | * 213 | * @param object An XMLElement to be appended to the array of sub-elements 214 | */ 215 | function AddSubTag(&$v) { 216 | if ( gettype($this->content) != "array" ) $this->content = array(); 217 | $this->content[] =& $v; 218 | return count($this->content); 219 | } 220 | 221 | /** 222 | * Add a new sub-element 223 | * 224 | * @param string The tag name of the new element 225 | * @param mixed Either a string of content, or an array of sub-elements 226 | * @param array An array of attribute name/value pairs 227 | * 228 | * @return objectref A reference to the new XMLElement 229 | */ 230 | function &NewElement( $tagname, $content=false, $attributes=false, $xmlns=null ) { 231 | if ( gettype($this->content) != "array" ) $this->content = array(); 232 | $element = new XMLElement($tagname,$content,$attributes,$xmlns); 233 | $this->content[] =& $element; 234 | return $element; 235 | } 236 | 237 | 238 | /** 239 | * Render just the internal content 240 | * 241 | * @return string The content of this element, as a string without this element wrapping it. 242 | */ 243 | function RenderContent($indent=0, $nslist=null, $force_xmlns=false ) { 244 | $r = ""; 245 | if ( is_array($this->content) ) { 246 | /** 247 | * Render the sub-elements with a deeper indent level 248 | */ 249 | $r .= "\n"; 250 | foreach( $this->content AS $k => $v ) { 251 | if ( is_object($v) ) { 252 | $r .= $v->Render($indent+1, "", $nslist, $force_xmlns); 253 | } 254 | } 255 | $r .= substr(" ",0,$indent); 256 | } 257 | else { 258 | /** 259 | * Render the content, with special characters escaped 260 | * 261 | */ 262 | if(strpos($this->content, 'content, ']]>')===strlen($this->content)-3) 263 | $r .= '', ']]]]>', substr($this->content, 9, -3)) . ']]>'; 264 | else if ( defined('ENT_XML1') && defined('ENT_DISALLOWED') ) 265 | // Newer PHP versions allow specifying ENT_XML1, but default to ENT_HTML401. Go figure. #PHPWTF 266 | $r .= htmlspecialchars($this->content, ENT_NOQUOTES | ENT_XML1 | ENT_DISALLOWED ); 267 | // Need to work out exactly how to do this in PHP. 268 | // else if ( preg_match('{^[\t\n\r\x0020-\xD7FF\xE000-\xFFFD\x10000-\x10FFFF]+$}u', utf8ToUnicode($this->content)) ) 269 | // $r .= 'content . ']]>'; 270 | else 271 | // Older PHP versions default to ENT_XML1. 272 | $r .= htmlspecialchars($this->content, ENT_NOQUOTES ); 273 | } 274 | return $r; 275 | } 276 | 277 | 278 | /** 279 | * Render the document tree into (nicely formatted) XML 280 | * 281 | * @param int The indenting level for the pretty formatting of the element 282 | */ 283 | function Render($indent=0, $xmldef="", $nslist=null, $force_xmlns=false) { 284 | $r = ( $xmldef == "" ? "" : $xmldef."\n"); 285 | 286 | $attr = ""; 287 | $tagname = $this->tagname; 288 | $xmlns_done = false; 289 | if ( gettype($this->attributes) == "array" ) { 290 | /** 291 | * Render the element attribute values 292 | */ 293 | foreach( $this->attributes AS $k => $v ) { 294 | if ( preg_match('#^xmlns(:?(.+))?$#', $k, $matches ) ) { 295 | // if ( $force_xmlns ) printf( "1: %s: %s\n", $this->tagname, $this->xmlns ); 296 | if ( !isset($nslist) ) $nslist = array(); 297 | $prefix = (isset($matches[2]) ? $matches[2] : ''); 298 | if ( isset($nslist[$v]) && $nslist[$v] == $prefix ) continue; // No need to include in list as it's in a wrapping element 299 | $nslist[$v] = $prefix; 300 | if ( !isset($this->xmlns) ) $this->xmlns = $v; 301 | $xmlns_done = true; 302 | } 303 | $attr .= sprintf( ' %s="%s"', $k, htmlspecialchars($v) ); 304 | } 305 | } 306 | if ( isset($this->xmlns) && isset($nslist[$this->xmlns]) && $nslist[$this->xmlns] != '' ) { 307 | // if ( $force_xmlns ) printf( "2: %s: %s\n", $this->tagname, $this->xmlns ); 308 | $tagname = $nslist[$this->xmlns] . ':' . $tagname; 309 | if ( $force_xmlns ) $attr .= sprintf( ' xmlns="%s"', $this->xmlns); 310 | } 311 | else if ( isset($this->xmlns) && !isset($nslist[$this->xmlns]) && gettype($this->attributes) == 'array' && !isset($this->attributes[$this->xmlns]) ) { 312 | // if ( $force_xmlns ) printf( "3: %s: %s\n", $this->tagname, $this->xmlns ); 313 | $attr .= sprintf( ' xmlns="%s"', $this->xmlns); 314 | } 315 | else if ( $force_xmlns && isset($this->xmlns) && ! $xmlns_done ) { 316 | // printf( "4: %s: %s\n", $this->tagname, $this->xmlns ); 317 | $attr .= sprintf( ' xmlns="%s"', $this->xmlns); 318 | } 319 | 320 | $r .= substr(" ",0,$indent) . '<' . $tagname . $attr; 321 | 322 | if ( (is_array($this->content) && count($this->content) > 0) || (!is_array($this->content) && strlen($this->content) > 0) ) { 323 | $r .= ">"; 324 | $r .= $this->RenderContent($indent,$nslist,$force_xmlns); 325 | $r .= '\n"; 326 | } 327 | else { 328 | $r .= "/>\n"; 329 | } 330 | return $r; 331 | } 332 | 333 | 334 | function __tostring() { 335 | return $this->Render(); 336 | } 337 | } 338 | 339 | 340 | /** 341 | * Rebuild an XML tree in our own style from the parsed XML tags using 342 | * a tail-recursive approach. 343 | * 344 | * @param array $xmltags An array of XML tags we get from using the PHP XML parser 345 | * @param intref &$start_from A pointer to our current integer offset into $xmltags 346 | * @return mixed Either a single XMLElement, or an array of XMLElement objects. 347 | */ 348 | function BuildXMLTree( $xmltags, &$start_from ) { 349 | $content = array(); 350 | 351 | if ( !isset($start_from) ) $start_from = 0; 352 | 353 | for( $i=0; $i < 50000 && isset($xmltags[$start_from]); $i++) { 354 | $tagdata = $xmltags[$start_from++]; 355 | if ( !isset($tagdata) || !isset($tagdata['tag']) || !isset($tagdata['type']) ) break; 356 | if ( $tagdata['type'] == "close" ) break; 357 | $xmlns = null; 358 | $tag = $tagdata['tag']; 359 | if ( preg_match( '{^(.*):([^:]*)$}', $tag, $matches) ) { 360 | $xmlns = $matches[1]; 361 | $tag = $matches[2]; 362 | } 363 | $attributes = ( isset($tagdata['attributes']) ? $tagdata['attributes'] : false ); 364 | if ( $tagdata['type'] == "open" ) { 365 | $subtree = BuildXMLTree( $xmltags, $start_from ); 366 | $content[] = new XMLElement($tag, $subtree, $attributes, $xmlns ); 367 | } 368 | else if ( $tagdata['type'] == "complete" ) { 369 | $value = ( isset($tagdata['value']) ? $tagdata['value'] : false ); 370 | $content[] = new XMLElement($tag, $value, $attributes, $xmlns ); 371 | } 372 | } 373 | 374 | /** 375 | * If there is only one element, return it directly, otherwise return the 376 | * array of them 377 | */ 378 | if ( count($content) == 1 ) { 379 | return $content[0]; 380 | } 381 | return $content; 382 | } 383 | 384 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /include/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("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 | } -------------------------------------------------------------------------------- /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 | require_once('CalDAVCalendar.php'); 14 | require_once('include/XMLDocument.php'); 15 | 16 | 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 | 62 | protected $parser; // our XML parser object 63 | 64 | // Requests timeout 65 | private $timeout; 66 | 67 | // cURL handle 68 | private $ch; 69 | 70 | // Full URL 71 | private $full_url; 72 | 73 | // First part of the full url 74 | public $first_url_part; 75 | 76 | /** 77 | * Constructor 78 | * 79 | * Valid options are: 80 | * 81 | * $options['auth'] : Auth type. Can be any of values for 82 | * CURLOPT_HTTPAUTH (from 83 | * http://www.php.net/manual/es/function.curl-setopt.php). Default: 84 | * basic or digest 85 | * 86 | * $options['timeout'] : Timeout in seconds 87 | */ 88 | 89 | // TODO: proxy options, interface used, 90 | function __construct( $base_url, $user, $pass, $options = array()) { 91 | $this->user = $user; 92 | $this->pass = $pass; 93 | $this->headers = array(); 94 | 95 | if ( preg_match( '#^((https?)://([a-z0-9.-]+)(:([0-9]+))?)(/.*)$#', $base_url, $matches ) ) { 96 | $this->server = $matches[3]; 97 | $this->base_url = $matches[6]; 98 | if ( $matches[2] == 'https' ) { 99 | $this->protocol = 'ssl'; 100 | $this->port = 443; 101 | } 102 | else { 103 | $this->protocol = 'tcp'; 104 | $this->port = 80; 105 | } 106 | if ( $matches[4] != '' ) { 107 | $this->port = intval($matches[5]); 108 | } 109 | } else { 110 | trigger_error("Invalid URL: '".$base_url."'", E_USER_ERROR); 111 | } 112 | 113 | $this->timeout = isset($options['timeout']) ? 114 | $options['timeout'] : 10; 115 | $this->ch = curl_init(); 116 | curl_setopt_array($this->ch, array( 117 | CURLOPT_CONNECTTIMEOUT => $this->timeout, 118 | CURLOPT_FAILONERROR => FALSE, 119 | CURLOPT_MAXREDIRS => 2, 120 | CURLOPT_FORBID_REUSE => FALSE, 121 | CURLOPT_RETURNTRANSFER => TRUE, 122 | CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 123 | CURLOPT_HTTPAUTH => 124 | isset($options['auth']) ? $options['auth'] : 125 | (CURLAUTH_BASIC | CURLAUTH_DIGEST), 126 | CURLOPT_USERAGENT => 'cURL based CalDAV client', 127 | CURLINFO_HEADER_OUT => TRUE, 128 | CURLOPT_HEADER => TRUE, 129 | CURLOPT_SSL_VERIFYPEER => FALSE 130 | )); 131 | 132 | $this->full_url = $base_url; 133 | $this->first_url_part = $matches[1]; 134 | } 135 | 136 | /** 137 | * Check with OPTIONS if calendar-access is enabled 138 | * 139 | * Can be used to check authentication against server 140 | * 141 | */ 142 | function isValidCalDAVServer() { 143 | // Clean headers 144 | $this->headers = array(); 145 | $dav_options = $this->DoOptionsRequestAndGetDAVHeader(); 146 | $valid_caldav_server = isset($dav_options['calendar-access']); 147 | 148 | return $valid_caldav_server; 149 | } 150 | 151 | /** 152 | * Issues an OPTIONS request 153 | * 154 | * @param string $url The URL to make the request to 155 | * 156 | * @return array DAV options 157 | */ 158 | function DoOptionsRequestAndGetDAVHeader( $url = null ) { 159 | $this->requestMethod = "OPTIONS"; 160 | $this->body = ""; 161 | $headers = $this->DoRequest($url); 162 | 163 | $result = array(); 164 | 165 | $headers = preg_split('/\r?\n/', $headers); 166 | 167 | // DAV header(s) 168 | $dav_header = preg_grep('/^DAV:/', $headers); 169 | if (is_array($dav_header)) { 170 | $dav_header = array_values($dav_header); 171 | $dav_header = preg_replace('/^DAV: /', '', $dav_header); 172 | 173 | $dav_options = array(); 174 | 175 | foreach ($dav_header as $d) { 176 | $dav_options = array_merge($dav_options, 177 | array_flip(preg_split('/[, ]+/', $d))); 178 | } 179 | 180 | $result = $dav_options; 181 | 182 | } 183 | 184 | return $result; 185 | } 186 | 187 | 188 | /** 189 | * Adds an If-Match or If-None-Match header 190 | * 191 | * @param bool $match to Match or Not to Match, that is the question! 192 | * @param string $etag The etag to match / not match against. 193 | */ 194 | function SetMatch( $match, $etag = '*' ) { 195 | $this->headers['match'] = sprintf( "%s-Match: \"%s\"", ($match ? "If" : "If-None"), $etag); 196 | } 197 | 198 | /** 199 | * Add a Depth: header. Valid values are 0, 1 or infinity 200 | * 201 | * @param int $depth The depth, default to infinity 202 | */ 203 | function SetDepth( $depth = '0' ) { 204 | $this->headers['depth'] = 'Depth: '. ($depth == '1' ? "1" : ($depth == 'infinity' ? $depth : "0") ); 205 | } 206 | 207 | /** 208 | * Add a Depth: header. Valid values are 1 or infinity 209 | * 210 | * @param int $depth The depth, default to infinity 211 | */ 212 | function SetUserAgent( $user_agent = null ) { 213 | $this->user_agent = $user_agent; 214 | curl_setopt($this->ch, CURLOPT_USERAGENT, $user_agent); 215 | } 216 | 217 | /** 218 | * Add a Content-type: header. 219 | * 220 | * @param string $type The content type 221 | */ 222 | function SetContentType( $type ) { 223 | $this->headers['content-type'] = "Content-type: $type"; 224 | } 225 | 226 | /** 227 | * Set the calendar_url we will be using for a while. 228 | * 229 | * @param string $url The calendar_url 230 | */ 231 | function SetCalendar( $url ) { 232 | $this->calendar_url = $url; 233 | } 234 | 235 | /** 236 | * Split response into httpResponse and xmlResponse 237 | * 238 | * @param string Response from server 239 | */ 240 | function ParseResponse( $response ) { 241 | $pos = strpos($response, 'httpResponse = trim($response); 244 | } 245 | else { 246 | $this->httpResponse = trim(substr($response, 0, $pos)); 247 | $this->xmlResponse = trim(substr($response, $pos)); 248 | $this->xmlResponse = preg_replace('{>[^>]*$}s', '>',$this->xmlResponse ); 249 | $parser = xml_parser_create_ns('UTF-8'); 250 | //xml_parser_set_option ( $parser, XML_OPTION_SKIP_WHITE, 1 ); 251 | xml_parser_set_option ( $parser, XML_OPTION_CASE_FOLDING, 0 ); 252 | 253 | if ( xml_parse_into_struct( $parser, $this->xmlResponse, $this->xmlnodes, $this->xmltags ) === 0 ) { 254 | //printf( "XML parsing error: %s - %s\n", xml_get_error_code($parser), xml_error_string(xml_get_error_code($parser)) ); 255 | // debug_print_backtrace(); 256 | // echo "\nNodes array............................................................\n"; print_r( $this->xmlnodes ); 257 | // echo "\nTags array............................................................\n"; print_r( $this->xmltags ); 258 | //printf( "\nXML Reponse:\n%s\n", $this->xmlResponse ); 259 | log_message('ERROR', 'XML parsing error: ' 260 | . xml_get_error_code($parser) . ', ' 261 | . xml_error_string(xml_get_error_code($parser))); 262 | } 263 | 264 | xml_parser_free($parser); 265 | } 266 | } 267 | 268 | /** 269 | * Parse response headers 270 | */ 271 | function ParseResponseHeaders($headers) { 272 | $lines = preg_split('/[\r\n]+/', $headers); 273 | $this->httpResultCode = preg_replace('/^[\S]+ (\d+).+$/', '\1', 274 | $lines[0]); 275 | } 276 | 277 | /** 278 | * Output http request headers 279 | * 280 | * @return HTTP headers 281 | */ 282 | function GetHttpRequest() { 283 | return $this->httpRequest; 284 | } 285 | /** 286 | * Output http response headers 287 | * 288 | * @return HTTP headers 289 | */ 290 | function GetResponseHeaders() { 291 | return $this->httpResponseHeaders; 292 | } 293 | /** 294 | * Output http response body 295 | * 296 | * @return HTTP body 297 | */ 298 | function GetResponseBody() { 299 | return $this->httpResponseBody; 300 | } 301 | /** 302 | * Output request body 303 | * 304 | * @return raw xml 305 | */ 306 | function GetBody() { 307 | return $this->body; 308 | } 309 | /** 310 | * Output xml response 311 | * 312 | * @return raw xml 313 | */ 314 | function GetXmlResponse() { 315 | return $this->xmlResponse; 316 | } 317 | /** 318 | * Output HTTP status code 319 | * 320 | * @return string HTTP status code 321 | */ 322 | function GetHttpResultCode() { 323 | return $this->httpResultCode; 324 | } 325 | 326 | /** 327 | * Send a request to the server 328 | * 329 | * @param string $url The URL to make the request to 330 | * 331 | * @return string The content of the response from the server 332 | */ 333 | function DoRequest( $url = null ) { 334 | if (is_null($url)) { 335 | $url = $this->full_url; 336 | } 337 | 338 | $this->request_url = $url; 339 | 340 | curl_setopt($this->ch, CURLOPT_URL, $url); 341 | 342 | // Request method 343 | curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->requestMethod); 344 | 345 | // Empty body. If not used, cURL will spend ~5s on this request 346 | if ($this->requestMethod == 'HEAD' || empty($this->body) ) { 347 | curl_setopt($this->ch, CURLOPT_NOBODY, TRUE); 348 | } else { 349 | curl_setopt($this->ch, CURLOPT_NOBODY, FALSE); 350 | } 351 | 352 | // Headers 353 | if (!isset($this->headers['content-type'])) $this->headers['content-type'] = "Content-type: text/plain"; 354 | 355 | // Remove cURL generated 'Expect: 100-continue' 356 | $this->headers['disable_expect'] = 'Expect:'; 357 | curl_setopt($this->ch, CURLOPT_HTTPHEADER, 358 | array_values($this->headers)); 359 | 360 | curl_setopt($this->ch, CURLOPT_USERPWD, $this->user . ':' . 361 | $this->pass); 362 | 363 | // Request body 364 | curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->body); 365 | 366 | // Save Request 367 | curl_setopt($this->ch, CURLINFO_HEADER_OUT, TRUE); 368 | 369 | $response = curl_exec($this->ch); 370 | 371 | if (FALSE === $response) { 372 | // TODO better error handling 373 | log_message('ERROR', 'Error requesting ' . $url . ': ' 374 | . curl_error($this->ch)); 375 | return false; 376 | } 377 | 378 | $info = curl_getinfo($this->ch); 379 | 380 | // Save request 381 | $this->httpRequest = $info['request_header']; 382 | 383 | // Get headers (idea from SabreDAV WebDAV client) 384 | $this->httpResponseHeaders = substr($response, 0, $info['header_size']); 385 | $this->httpResponseBody = substr($response, $info['header_size']); 386 | 387 | // Get only last headers (needed when using unspecific HTTP auth 388 | // method or request got redirected) 389 | $this->httpResponseHeaders = preg_replace('/^.+\r\n\r\n(.+)/sU', '$1', 390 | $this->httpResponseHeaders); 391 | 392 | // Parse response 393 | $this->ParseResponseHeaders($this->httpResponseHeaders); 394 | $this->ParseResponse($this->httpResponseBody); 395 | 396 | //TODO debug 397 | 398 | /* 399 | log_message('INTERNALS', 'REQh: ' . var_export($info['request_header'], TRUE)); 400 | log_message('INTERNALS', 'REQb: ' . var_export($this->body, TRUE)); 401 | log_message('INTERNALS', 'RPLh: ' . var_export($this->httpResponseHeaders, TRUE)); 402 | log_message('INTERNALS', 'RPLb: ' . var_export($this->httpResponseBody, TRUE)); 403 | */ 404 | 405 | return $response; 406 | } 407 | 408 | /** 409 | * Send an OPTIONS request to the server 410 | * 411 | * @param string $url The URL to make the request to 412 | * 413 | * @return array The allowed options 414 | */ 415 | function DoOptionsRequest( $url = null ) { 416 | $this->requestMethod = "OPTIONS"; 417 | $this->body = ""; 418 | $headers = $this->DoRequest($url); 419 | $options_header = preg_replace( '/^.*Allow: ([a-z, ]+)\r?\n.*/is', '$1', $headers ); 420 | $options = array_flip( preg_split( '/[, ]+/', $options_header )); 421 | return $options; 422 | } 423 | 424 | 425 | 426 | /** 427 | * Send an XML request to the server (e.g. PROPFIND, REPORT, MKCALENDAR) 428 | * 429 | * @param string $method The method (PROPFIND, REPORT, etc) to use with the request 430 | * @param string $xml The XML to send along with the request 431 | * @param string $url The URL to make the request to 432 | * 433 | * @return array An array of the allowed methods 434 | */ 435 | function DoXMLRequest( $request_method, $xml, $url = null ) { 436 | $this->body = $xml; 437 | $this->requestMethod = $request_method; 438 | $this->SetContentType("text/xml"); 439 | return $this->DoRequest($url); 440 | } 441 | 442 | 443 | 444 | /** 445 | * Get a single item from the server. 446 | * 447 | * @param string $url The URL to GET 448 | */ 449 | function DoGETRequest( $url ) { 450 | $this->body = ""; 451 | $this->requestMethod = "GET"; 452 | return $this->DoRequest( $url ); 453 | } 454 | 455 | 456 | /** 457 | * Get the HEAD of a single item from the server. 458 | * 459 | * @param string $url The URL to HEAD 460 | */ 461 | function DoHEADRequest( $url ) { 462 | $this->body = ""; 463 | $this->requestMethod = "HEAD"; 464 | return $this->DoRequest( $url ); 465 | } 466 | 467 | 468 | /** 469 | * PUT a text/icalendar resource, returning the etag 470 | * 471 | * @param string $url The URL to make the request to 472 | * @param string $icalendar The iCalendar resource to send to the server 473 | * @param string $etag The etag of an existing resource to be overwritten, or '*' for a new resource. 474 | * 475 | * @return string The content of the response from the server 476 | */ 477 | function DoPUTRequest( $url, $icalendar, $etag = null ) { 478 | $this->body = $icalendar; 479 | 480 | $this->requestMethod = "PUT"; 481 | if ( $etag != null ) { 482 | $this->SetMatch( ($etag != '*'), $etag ); 483 | } 484 | $this->SetContentType('text/calendar; encoding="utf-8"'); 485 | $this->DoRequest($url); 486 | 487 | $etag = null; 488 | if ( preg_match( '{^ETag:\s+"([^"]*)"\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 489 | else if ( preg_match( '{^ETag:\s+([^\s]*)\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 490 | if ( !isset($etag) || $etag == '' ) { 491 | // Try with HEAD 492 | $save_request = $this->httpRequest; 493 | $save_response_headers = $this->httpResponseHeaders; 494 | $save_http_result = $this->httpResultCode; 495 | $this->DoHEADRequest( $url ); 496 | if ( preg_match( '{^Etag:\s+"([^"]*)"\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 497 | else if ( preg_match( '{^ETag:\s+([^\s]*)\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 498 | /* 499 | if ( !isset($etag) || $etag == '' ) { 500 | printf( "Still No etag in:\n%s\n", $this->httpResponseHeaders ); 501 | } 502 | */ 503 | $this->httpRequest = $save_request; 504 | $this->httpResponseHeaders = $save_response_headers; 505 | $this->httpResultCode = $save_http_result; 506 | } 507 | return $etag; 508 | } 509 | 510 | 511 | /** 512 | * DELETE a text/icalendar resource 513 | * 514 | * @param string $url The URL to make the request to 515 | * @param string $etag The etag of an existing resource to be deleted, or '*' for any resource at that URL. 516 | * 517 | * @return int The HTTP Result Code for the DELETE 518 | */ 519 | function DoDELETERequest( $url, $etag = null ) { 520 | $this->body = ""; 521 | 522 | $this->requestMethod = "DELETE"; 523 | if ( $etag != null ) { 524 | $this->SetMatch( true, $etag ); 525 | } 526 | $this->DoRequest($url); 527 | return $this->httpResultCode; 528 | } 529 | 530 | 531 | /** 532 | * Get a single item from the server. 533 | * 534 | * @param string $url The URL to PROPFIND on 535 | */ 536 | function DoPROPFINDRequest( $url, $props, $depth = 0 ) { 537 | $this->SetDepth($depth); 538 | $xml = new XMLDocument( array( 'DAV:' => '', 'urn:ietf:params:xml:ns:caldav' => 'C' ) ); 539 | $prop = new XMLElement('prop'); 540 | foreach( $props AS $v ) { 541 | $xml->NSElement($prop,$v); 542 | } 543 | 544 | $this->body = $xml->Render('propfind',$prop ); 545 | 546 | $this->requestMethod = 'PROPFIND'; 547 | $this->SetContentType('text/xml'); 548 | $this->DoRequest($url); 549 | return $this->GetXmlResponse(); 550 | } 551 | 552 | 553 | /** 554 | * Get/Set the Principal URL 555 | * 556 | * @param $url string The Principal URL to set 557 | */ 558 | function PrincipalURL( $url = null ) { 559 | if ( isset($url) ) { 560 | $this->principal_url = $url; 561 | } 562 | return $this->principal_url; 563 | } 564 | 565 | 566 | /** 567 | * Get/Set the calendar-home-set URL 568 | * 569 | * @param $url array of string The calendar-home-set URLs to set 570 | */ 571 | function CalendarHomeSet( $urls = null ) { 572 | if ( isset($urls) ) { 573 | if ( ! is_array($urls) ) $urls = array($urls); 574 | $this->calendar_home_set = $urls; 575 | } 576 | return $this->calendar_home_set; 577 | } 578 | 579 | 580 | /** 581 | * Get/Set the calendar-home-set URL 582 | * 583 | * @param $urls array of string The calendar URLs to set 584 | */ 585 | function CalendarUrls( $urls = null ) { 586 | if ( isset($urls) ) { 587 | if ( ! is_array($urls) ) $urls = array($urls); 588 | $this->calendar_urls = $urls; 589 | } 590 | return $this->calendar_urls; 591 | } 592 | 593 | 594 | /** 595 | * Return the first occurrence of an href inside the named tag. 596 | * 597 | * @param string $tagname The tag name to find the href inside of 598 | */ 599 | function HrefValueInside( $tagname ) { 600 | foreach( $this->xmltags[$tagname] AS $k => $v ) { 601 | $j = $v + 1; 602 | if ( $this->xmlnodes[$j]['tag'] == 'DAV::href' ) { 603 | return rawurldecode($this->xmlnodes[$j]['value']); 604 | } 605 | } 606 | return null; 607 | } 608 | 609 | 610 | /** 611 | * Return the href containing this property. Except only if it's inside a status != 200 612 | * 613 | * @param string $tagname The tag name of the property to find the href for 614 | * @param integer $which Which instance of the tag should we use 615 | */ 616 | function HrefForProp( $tagname, $i = 0 ) { 617 | if ( isset($this->xmltags[$tagname]) && isset($this->xmltags[$tagname][$i]) ) { 618 | $j = $this->xmltags[$tagname][$i]; 619 | while( $j-- > 0 && $this->xmlnodes[$j]['tag'] != 'DAV::href' ) { 620 | // printf( "Node[$j]: %s\n", $this->xmlnodes[$j]['tag']); 621 | if ( $this->xmlnodes[$j]['tag'] == 'DAV::status' && $this->xmlnodes[$j]['value'] != 'HTTP/1.1 200 OK' ) return null; 622 | } 623 | // printf( "Node[$j]: %s\n", $this->xmlnodes[$j]['tag']); 624 | if ( $j > 0 && isset($this->xmlnodes[$j]['value']) ) { 625 | // printf( "Value[$j]: %s\n", $this->xmlnodes[$j]['value']); 626 | return rawurldecode($this->xmlnodes[$j]['value']); 627 | } 628 | } 629 | else { 630 | // printf( "xmltags[$tagname] or xmltags[$tagname][$i] is not set\n"); 631 | } 632 | return null; 633 | } 634 | 635 | 636 | /** 637 | * Return the href which has a resourcetype of the specified type 638 | * 639 | * @param string $tagname The tag name of the resourcetype to find the href for 640 | * @param integer $which Which instance of the tag should we use 641 | */ 642 | function HrefForResourcetype( $tagname, $i = 0 ) { 643 | if ( isset($this->xmltags[$tagname]) && isset($this->xmltags[$tagname][$i]) ) { 644 | $j = $this->xmltags[$tagname][$i]; 645 | while( $j-- > 0 && $this->xmlnodes[$j]['tag'] != 'DAV::resourcetype' ); 646 | if ( $j > 0 ) { 647 | while( $j-- > 0 && $this->xmlnodes[$j]['tag'] != 'DAV::href' ); 648 | if ( $j > 0 && isset($this->xmlnodes[$j]['value']) ) { 649 | return rawurldecode($this->xmlnodes[$j]['value']); 650 | } 651 | } 652 | } 653 | return null; 654 | } 655 | 656 | 657 | /** 658 | * Return the ... of a propstat where the status is OK 659 | * 660 | * @param string $nodenum The node number in the xmlnodes which is the href 661 | */ 662 | function GetOKProps( $nodenum ) { 663 | $props = null; 664 | $level = $this->xmlnodes[$nodenum]['level']; 665 | $status = ''; 666 | while ( $this->xmlnodes[++$nodenum]['level'] >= $level ) { 667 | if ( $this->xmlnodes[$nodenum]['tag'] == 'DAV::propstat' ) { 668 | if ( $this->xmlnodes[$nodenum]['type'] == 'open' ) { 669 | $props = array(); 670 | $status = ''; 671 | } 672 | else { 673 | if ( $status == 'HTTP/1.1 200 OK' ) break; 674 | } 675 | } 676 | elseif ( !isset($this->xmlnodes[$nodenum]) || !is_array($this->xmlnodes[$nodenum]) ) { 677 | break; 678 | } 679 | elseif ( $this->xmlnodes[$nodenum]['tag'] == 'DAV::status' ) { 680 | $status = $this->xmlnodes[$nodenum]['value']; 681 | } 682 | else { 683 | $props[] = $this->xmlnodes[$nodenum]; 684 | } 685 | } 686 | return $props; 687 | } 688 | 689 | 690 | /** 691 | * Attack the given URL in an attempt to find a principal URL 692 | * 693 | * @param string $url The URL to find the principal-URL from 694 | */ 695 | function FindPrincipal( $url = null ) { 696 | $xml = $this->DoPROPFINDRequest( $url, array('resourcetype', 'current-user-principal', 'owner', 'principal-URL', 697 | 'urn:ietf:params:xml:ns:caldav:calendar-home-set'), 1); 698 | 699 | $principal_url = $this->HrefForProp('DAV::principal'); 700 | 701 | if ( !isset($principal_url) ) { 702 | foreach( array('DAV::current-user-principal', 'DAV::principal-URL', 'DAV::owner') AS $href ) { 703 | if ( !isset($principal_url) ) { 704 | $principal_url = $this->HrefValueInside($href); 705 | } 706 | } 707 | } 708 | 709 | return $this->PrincipalURL($principal_url); 710 | } 711 | 712 | 713 | /** 714 | * Attack the given URL in an attempt to find the calendar-home-url of the current principal 715 | * 716 | * @param string $url The URL to find the calendar-home-set from 717 | */ 718 | function FindCalendarHome( $recursed=false ) { 719 | if ( !isset($this->principal_url) ) { 720 | $this->FindPrincipal(); 721 | } 722 | if ( $recursed ) { 723 | $this->DoPROPFINDRequest( $this->first_url_part.$this->principal_url, array('urn:ietf:params:xml:ns:caldav:calendar-home-set'), 0); 724 | } 725 | 726 | $calendar_home = array(); 727 | foreach( $this->xmltags['urn:ietf:params:xml:ns:caldav:calendar-home-set'] AS $k => $v ) { 728 | if ( $this->xmlnodes[$v]['type'] != 'open' ) continue; 729 | while( $this->xmlnodes[++$v]['type'] != 'close' && $this->xmlnodes[$v]['tag'] != 'urn:ietf:params:xml:ns:caldav:calendar-home-set' ) { 730 | // printf( "Tag: '%s' = '%s'\n", $this->xmlnodes[$v]['tag'], $this->xmlnodes[$v]['value']); 731 | if ( $this->xmlnodes[$v]['tag'] == 'DAV::href' && isset($this->xmlnodes[$v]['value']) ) 732 | $calendar_home[] = rawurldecode($this->xmlnodes[$v]['value']); 733 | } 734 | } 735 | 736 | if ( !$recursed && count($calendar_home) < 1 ) { 737 | $calendar_home = $this->FindCalendarHome(true); 738 | } 739 | 740 | return $this->CalendarHomeSet($calendar_home); 741 | } 742 | 743 | /* 744 | * Find own calendars 745 | */ 746 | function FindCalendars( $recursed=false ) { 747 | if ( !isset($this->calendar_home_set[0]) ) { 748 | $this->FindCalendarHome($recursed); 749 | } 750 | $properties = 751 | array( 752 | 'resourcetype', 753 | 'displayname', 754 | 'http://calendarserver.org/ns/:getctag', 755 | 'http://apple.com/ns/ical/:calendar-color', 756 | 'http://apple.com/ns/ical/:calendar-order', 757 | ); 758 | $this->DoPROPFINDRequest( $this->first_url_part.$this->calendar_home_set[0], $properties, 1); 759 | 760 | return $this->parse_calendar_info(); 761 | } 762 | 763 | /** 764 | * Do a PROPFIND on a calendar and retrieve its information 765 | */ 766 | function GetCalendarDetailsByURL($url) { 767 | $properties = 768 | array( 769 | 'resourcetype', 770 | 'displayname', 771 | 'http://calendarserver.org/ns/:getctag', 772 | 'http://apple.com/ns/ical/:calendar-color', 773 | 'http://apple.com/ns/ical/:calendar-order', 774 | ); 775 | $this->DoPROPFINDRequest($url, $properties, 0); 776 | 777 | return $this->parse_calendar_info(); 778 | } 779 | 780 | /** 781 | * Find the calendars, from the calendar_home_set 782 | */ 783 | function GetCalendarDetails( $url = null ) { 784 | if ( isset($url) ) $this->SetCalendar($url); 785 | 786 | $calendar_properties = array( 'resourcetype', 'displayname', 'http://calendarserver.org/ns/:getctag', 'urn:ietf:params:xml:ns:caldav:calendar-timezone', 'supported-report-set' ); 787 | $this->DoPROPFINDRequest( $this->calendar_url, $calendar_properties, 0); 788 | 789 | $hnode = $this->xmltags['DAV::href'][0]; 790 | $href = rawurldecode($this->xmlnodes[$hnode]['value']); 791 | 792 | $calendar = new CalDAVCalendar($href); 793 | $ok_props = $this->GetOKProps($hnode); 794 | foreach( $ok_props AS $k => $v ) { 795 | $name = preg_replace( '{^.*:}', '', $v['tag'] ); 796 | if ( isset($v['value'] ) ) { 797 | $calendar->{$name} = $v['value']; 798 | } 799 | /* else { 800 | printf( "Calendar property '%s' has no text content\n", $v['tag'] ); 801 | }*/ 802 | } 803 | 804 | return $calendar; 805 | } 806 | 807 | 808 | /** 809 | * Get all etags for a calendar 810 | */ 811 | function GetCollectionETags( $url = null ) { 812 | if ( isset($url) ) $this->SetCalendar($url); 813 | 814 | $this->DoPROPFINDRequest( $this->calendar_url, array('getetag'), 1); 815 | 816 | $etags = array(); 817 | if ( isset($this->xmltags['DAV::getetag']) ) { 818 | foreach( $this->xmltags['DAV::getetag'] AS $k => $v ) { 819 | $href = $this->HrefForProp('DAV::getetag', $k); 820 | if ( isset($href) && isset($this->xmlnodes[$v]['value']) ) $etags[$href] = $this->xmlnodes[$v]['value']; 821 | } 822 | } 823 | 824 | return $etags; 825 | } 826 | 827 | 828 | /** 829 | * Get a bunch of events for a calendar with a calendar-multiget report 830 | */ 831 | function CalendarMultiget( $event_hrefs, $url = null ) { 832 | 833 | if ( isset($url) ) $this->SetCalendar($url); 834 | 835 | $hrefs = ''; 836 | foreach( $event_hrefs AS $k => $href ) { 837 | $href = str_replace( rawurlencode('/'),'/',rawurlencode($href)); 838 | $hrefs .= ''.$href.''; 839 | } 840 | $this->body = << 842 | 843 | 844 | $hrefs 845 | 846 | EOXML; 847 | 848 | $this->requestMethod = "REPORT"; 849 | $this->SetContentType("text/xml"); 850 | $response = $this->DoRequest( $this->calendar_url ); 851 | 852 | $report = array(); 853 | foreach( $this->xmlnodes as $k => $v ) { 854 | switch( $v['tag'] ) { 855 | case 'DAV::response': 856 | if ( $v['type'] == 'open' ) { 857 | $response = array(); 858 | } 859 | elseif ( $v['type'] == 'close' ) { 860 | $report[] = $response; 861 | } 862 | break; 863 | case 'DAV::href': 864 | $response['href'] = basename( rawurldecode($v['value']) ); 865 | break; 866 | case 'DAV::getetag': 867 | $response['etag'] = preg_replace('/^"?([^"]+)"?/', '$1', $v['value']); 868 | break; 869 | case 'urn:ietf:params:xml:ns:caldav:calendar-data': 870 | $response['data'] = $v['value']; 871 | break; 872 | } 873 | } 874 | 875 | return $report; 876 | } 877 | 878 | 879 | /** 880 | * Given XML for a calendar query, return an array of the events (/todos) in the 881 | * response. Each event in the array will have a 'href', 'etag' and '$response_type' 882 | * part, where the 'href' is relative to the calendar and the '$response_type' contains the 883 | * definition of the calendar data in iCalendar format. 884 | * 885 | * @param string $filter XML fragment which is the element of a calendar-query 886 | * @param string $url The URL of the calendar, or null to use the 'current' calendar_url 887 | * 888 | * @return array An array of the relative URLs, etags, and events from the server. Each element of the array will 889 | * be an array with 'href', 'etag' and 'data' elements, corresponding to the URL, the server-supplied 890 | * etag (which only varies when the data changes) and the calendar data in iCalendar format. 891 | */ 892 | function DoCalendarQuery( $filter, $url = null ) { 893 | 894 | if ( isset($url) ) $this->SetCalendar($url); 895 | 896 | $this->body = << 898 | 899 | 900 | 901 | 902 | $filter 903 | 904 | EOXML; 905 | 906 | $this->requestMethod = "REPORT"; 907 | $this->SetContentType("text/xml"); 908 | $this->DoRequest( $this->calendar_url ); 909 | 910 | $report = array(); 911 | foreach( $this->xmlnodes as $k => $v ) { 912 | switch( $v['tag'] ) { 913 | case 'DAV::response': 914 | if ( $v['type'] == 'open' ) { 915 | $response = array(); 916 | } 917 | elseif ( $v['type'] == 'close' ) { 918 | $report[] = $response; 919 | } 920 | break; 921 | case 'DAV::href': 922 | $response['href'] = basename( rawurldecode($v['value']) ); 923 | break; 924 | case 'DAV::getetag': 925 | $response['etag'] = preg_replace('/^"?([^"]+)"?/', '$1', $v['value']); 926 | break; 927 | case 'urn:ietf:params:xml:ns:caldav:calendar-data': 928 | $response['data'] = $v['value']; 929 | break; 930 | } 931 | } 932 | return $report; 933 | } 934 | 935 | 936 | /** 937 | * Get the events in a range from $start to $finish. The dates should be in the 938 | * format yyyymmddThhmmssZ and should be in GMT. The events are returned as an 939 | * array of event arrays. Each event array will have a 'href', 'etag' and 'event' 940 | * part, where the 'href' is relative to the calendar and the event contains the 941 | * definition of the event in iCalendar format. 942 | * 943 | * @param timestamp $start The start time for the period 944 | * @param timestamp $finish The finish time for the period 945 | * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default null. 946 | * 947 | * @return array An array of the relative URLs, etags, and events, returned from DoCalendarQuery() @see DoCalendarQuery() 948 | */ 949 | function GetEvents( $start = null, $finish = null, $relative_url = null ) { 950 | $this->SetDepth('1'); 951 | $filter = ""; 952 | if ( isset($start) && isset($finish) ) 953 | $range = ""; 954 | elseif ( isset($start) && ! isset($finish) ) 955 | $range = ""; 956 | elseif ( ! isset($start) && isset($finish) ) 957 | $range = ""; 958 | else 959 | $range = ''; 960 | 961 | $filter = << 963 | 964 | 965 | $range 966 | 967 | 968 | 969 | EOFILTER; 970 | 971 | return $this->DoCalendarQuery($filter, $relative_url); 972 | } 973 | 974 | 975 | /** 976 | * Get the todo's in a range from $start to $finish. The dates should be in the 977 | * format yyyymmddThhmmssZ and should be in GMT. The events are returned as an 978 | * array of event arrays. Each event array will have a 'href', 'etag' and 'event' 979 | * part, where the 'href' is relative to the calendar and the event contains the 980 | * definition of the event in iCalendar format. 981 | * 982 | * @param timestamp $start The start time for the period 983 | * @param timestamp $finish The finish time for the period 984 | * @param boolean $completed Whether to include completed tasks 985 | * @param boolean $cancelled Whether to include cancelled tasks 986 | * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''. 987 | * 988 | * @return array An array of the relative URLs, etags, and events, returned from DoCalendarQuery() @see DoCalendarQuery() 989 | */ 990 | function GetTodos( $start = null, $finish = null, $completed = null, $cancelled = null, $relative_url = "" ) { 991 | $this->SetDepth('1'); 992 | 993 | if ( isset($start) && isset($finish) ) 994 | $range = ""; 995 | elseif ( isset($start) && ! isset($finish) ) 996 | $range = ""; 997 | elseif ( ! isset($start) && isset($finish) ) 998 | $range = ""; 999 | else 1000 | $range = ''; 1001 | 1002 | 1003 | // Warning! May contain traces of double negatives... 1004 | if(isset($completed) && $completed == true) 1005 | $completed_filter = 'COMPLETED'; 1006 | else if(isset($completed) && $completed == false) 1007 | $completed_filter = 'COMPLETED'; 1008 | else 1009 | $completed_filter = ''; 1010 | 1011 | if(isset($cancelled) && $cancelled == true) 1012 | $cancelled_filter = 'CANCELLED'; 1013 | else if(isset($cancelled) && $cancelled == false) 1014 | $cancelled_filter = 'CANCELLED'; 1015 | else 1016 | $cancelled_filter = ''; 1017 | 1018 | $filter = << 1020 | 1021 | 1022 | $completed_filter 1023 | $cancelled_filter 1024 | $range 1025 | 1026 | 1027 | 1028 | EOFILTER; 1029 | 1030 | return $this->DoCalendarQuery($filter); 1031 | } 1032 | 1033 | 1034 | /** 1035 | * Get the calendar entry by UID 1036 | * 1037 | * @param uid 1038 | * @param string $relative_url The URL relative to the base_url specified when the calendar was opened. Default ''. 1039 | * 1040 | * @return array An array of the relative URL, etag, and calendar data returned from DoCalendarQuery() @see DoCalendarQuery() 1041 | */ 1042 | function GetEntryByUid( $uid, $relative_url = null ) { 1043 | $this->SetDepth('1'); 1044 | $filter = ""; 1045 | if ( $uid ) { 1046 | $filter = << 1048 | 1049 | 1050 | 1051 | $uid 1052 | 1053 | 1054 | 1055 | 1056 | EOFILTER; 1057 | } 1058 | 1059 | return $this->DoCalendarQuery($filter, $relative_url); 1060 | } 1061 | 1062 | 1063 | /** 1064 | * Get the calendar entry by HREF 1065 | * 1066 | * @param string $href The href from a call to GetEvents or GetTodos etc. 1067 | * 1068 | * @return string The iCalendar of the calendar entry 1069 | */ 1070 | function GetEntryByHref( $href ) { 1071 | //$href = str_replace( rawurlencode('/'),'/',rawurlencode($href)); 1072 | $response = $this->DoGETRequest( $href ); 1073 | 1074 | $report = array(); 1075 | 1076 | if ( $this->GetHttpResultCode() == '404' ) { return $report; } 1077 | 1078 | $etag = null; 1079 | if ( preg_match( '{^ETag:\s+"([^"]*)"\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 1080 | else if ( preg_match( '{^ETag:\s+([^\s]*)\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 1081 | if ( !isset($etag) || $etag == '' ) { 1082 | // Try with HEAD 1083 | $save_request = $this->httpRequest; 1084 | $save_response_headers = $this->httpResponseHeaders; 1085 | $save_http_result = $this->httpResultCode; 1086 | $this->DoHEADRequest( $href ); 1087 | if ( preg_match( '{^Etag:\s+"([^"]*)"\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 1088 | else if ( preg_match( '{^ETag:\s+([^\s]*)\s*$}im', $this->httpResponseHeaders, $matches ) ) $etag = $matches[1]; 1089 | 1090 | /* 1091 | if ( !isset($etag) || $etag == '' ) { 1092 | printf( "Still No etag in:\n%s\n", $this->httpResponseHeaders ); 1093 | } 1094 | */ 1095 | $this->httpRequest = $save_request; 1096 | $this->httpResponseHeaders = $save_response_headers; 1097 | $this->httpResultCode = $save_http_result; 1098 | } 1099 | 1100 | $report = array(array('etag'=>$etag)); 1101 | 1102 | return $report; 1103 | } 1104 | 1105 | /** 1106 | * Get calendar info after a PROPFIND 1107 | */ 1108 | function parse_calendar_info() { 1109 | $calendars = array(); 1110 | if ( isset($this->xmltags['urn:ietf:params:xml:ns:caldav:calendar']) ) { 1111 | $calendar_urls = array(); 1112 | foreach( $this->xmltags['urn:ietf:params:xml:ns:caldav:calendar'] AS $k => $v ) { 1113 | $calendar_urls[$this->HrefForProp('urn:ietf:params:xml:ns:caldav:calendar', $k)] = 1; 1114 | } 1115 | 1116 | foreach( $this->xmltags['DAV::href'] AS $i => $hnode ) { 1117 | $href = rawurldecode($this->xmlnodes[$hnode]['value']); 1118 | 1119 | if ( !isset($calendar_urls[$href]) ) continue; 1120 | 1121 | // printf("Seems '%s' is a calendar.\n", $href ); 1122 | 1123 | 1124 | $calendar = new CalDAVCalendar($href); 1125 | 1126 | /* 1127 | * Transform href into calendar 1128 | * /xxxxx/yyyyy/caldav.php/principal/resource/ 1129 | * t-3 t-2 1130 | */ 1131 | $pieces = preg_split('/\//', $href); 1132 | $total = count($pieces); 1133 | $calendar_id = $pieces[$total-2]; 1134 | $calendar->setCalendarID($calendar_id); 1135 | 1136 | $ok_props = $this->GetOKProps($hnode); 1137 | foreach( $ok_props AS $v ) { 1138 | switch( $v['tag'] ) { 1139 | case 'http://calendarserver.org/ns/:getctag': 1140 | $calendar->setCtag((isset($v['value']) ? 1141 | $v['value'] : '-')); 1142 | break; 1143 | case 'DAV::displayname': 1144 | $calendar->setDisplayName((isset($v['value']) ? 1145 | $v['value'] : '-')); 1146 | break; 1147 | case 'http://apple.com/ns/ical/:calendar-color': 1148 | $calendar->setRBGcolor((isset($v['value']) ? 1149 | $this->_rgba2rgb($v['value']) : '-')); 1150 | break; 1151 | case 'http://apple.com/ns/ical/:calendar-order': 1152 | $calendar->setOrder((isset($v['value']) ? 1153 | $v['value'] : '-')); 1154 | break; 1155 | } 1156 | } 1157 | $calendars[$calendar->getCalendarID()] = $calendar; 1158 | } 1159 | } 1160 | 1161 | return $calendars; 1162 | } 1163 | /** 1164 | * Issues a PROPPATCH on a resource 1165 | * 1166 | * @param string XML request 1167 | * @param string URL 1168 | * @return TRUE on success, FALSE otherwise 1169 | */ 1170 | function DoPROPPATCH($xml_text, $url) { 1171 | $this->DoXMLRequest('PROPPATCH', $xml_text, $url); 1172 | 1173 | $errmsg = ''; 1174 | 1175 | if ($this->httpResultCode == '207') { 1176 | $errmsg = $this->httpResultCode; 1177 | // Find propstat tag(s) 1178 | if (isset($this->xmltags['DAV::propstat'])) { 1179 | foreach ($this->xmltags['DAV::propstat'] as $i => $node) { 1180 | if ($this->xmlnodes[$node]['type'] == 'close') { 1181 | continue; 1182 | } 1183 | // propstat @ $i: open 1184 | // propstat @ $i + 1: close 1185 | // Search for prop and status 1186 | $level = $this->xmlnodes[$node]['level']; 1187 | $level++; 1188 | 1189 | while ($this->xmlnodes[++$node]['level'] >= $level) { 1190 | if ($this->xmlnodes[$node]['tag'] == 'DAV::status' 1191 | && $this->xmlnodes[$node]['value'] != 1192 | 'HTTP/1.1 200 OK') { 1193 | return $this->xmlnodes[$node]['value']; 1194 | } 1195 | } 1196 | } 1197 | } 1198 | } else if ($this->httpResultCode != 200) { 1199 | return 'Unknown HTTP code'; 1200 | } 1201 | 1202 | return TRUE; 1203 | } 1204 | 1205 | /** 1206 | * Queries server using a principal-property search 1207 | * 1208 | * @param string XML request 1209 | * @param string URL 1210 | * @return FALSE on error, array with results otherwise 1211 | */ 1212 | function principal_property_search($xml_text, $url) { 1213 | $result = array(); 1214 | $this->DoXMLRequest('REPORT', $xml_text, $url); 1215 | 1216 | if ($this->httpResultCode == '207') { 1217 | $errmsg = $this->httpResultCode; 1218 | // Find response tag(s) 1219 | if (isset($this->xmltags['DAV::response'])) { 1220 | foreach ($this->xmltags['DAV::response'] as $i => $node) { 1221 | if ($this->xmlnodes[$node]['type'] == 'close') { 1222 | continue; 1223 | } 1224 | 1225 | $result[$i]['href'] = 1226 | $this->HrefForProp('DAV::response', $i+1); 1227 | 1228 | $level = $this->xmlnodes[$node]['level']; 1229 | $level++; 1230 | 1231 | $ok_props = $this->GetOKProps($node); 1232 | 1233 | foreach ($ok_props as $v) { 1234 | switch($v['tag']) { 1235 | case 'DAV::displayname': 1236 | $result[$i]['displayname'] = 1237 | isset($v['value']) ? $v['value'] : ''; 1238 | break; 1239 | case 'DAV::email': 1240 | $result[$i]['email'] = 1241 | isset($v['value']) ? $v['value'] : ''; 1242 | break; 1243 | } 1244 | } 1245 | 1246 | } 1247 | } 1248 | } else if ($this->httpResultCode != 200) { 1249 | return 'Unknown HTTP code'; 1250 | } 1251 | 1252 | return $result; 1253 | } 1254 | 1255 | /** 1256 | * Converts a RGBA hexadecimal string (#rrggbbXX) to RGB 1257 | */ 1258 | private function _rgba2rgb($s) { 1259 | if (strlen($s) == '9') { 1260 | return substr($s, 0, 7); 1261 | } else { 1262 | // Unknown string 1263 | return $s; 1264 | } 1265 | } 1266 | 1267 | public function printLastMessages() { 1268 | $string = ''; 1269 | $dom = new DOMDocument(); 1270 | $dom->preserveWhiteSpace = FALSE; 1271 | $dom->formatOutput = TRUE; 1272 | 1273 | $string .= '
';
1274 | 		$string .= 'last request:

'; 1275 | 1276 | $string .= $this->httpRequest; 1277 | 1278 | if(!empty($this->body)) { 1279 | $dom->loadXML($this->body); 1280 | $string .= htmlentities($dom->saveXml()); 1281 | } 1282 | 1283 | $string .= '
last response:

'; 1284 | 1285 | $string .= $this->httpResponse; 1286 | 1287 | if(!empty($this->xmlResponse)) { 1288 | $dom->loadXML($this->xmlResponse); 1289 | $string .= htmlentities($dom->saveXml()); 1290 | } 1291 | 1292 | $string .= '
'; 1293 | 1294 | echo $string; 1295 | } 1296 | } 1297 | 1298 | /** 1299 | * Error handeling functions 1300 | */ 1301 | 1302 | $debug = TRUE; 1303 | 1304 | function log_message ($type, $message) { 1305 | global $debug; 1306 | if ($debug) { 1307 | echo '['.$type.'] '.$message.'\n'; 1308 | } 1309 | } 1310 | --------------------------------------------------------------------------------