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