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