Note that the iCalendar class is DEPRECATED.
[awl.git] / inc / iCalendar.php
blobf9f51bfc1881daced1183bbab8714dfaafdd3b8f
1 <?php
2 /**
3 * A Class for handling iCalendar data.
5 * When parsed the underlying structure is roughly as follows:
7 * iCalendar( array(iCalComponent), array(iCalProp) )
9 * each iCalComponent is similarly structured:
11 * iCalComponent( array(iCalComponent), array(iCalProp) )
13 * Once parsed, $ical->component will point to the wrapping VCALENDAR component of
14 * the iCalendar. This will be fine for simple iCalendar usage as sampled below,
15 * but more complex iCalendar such as a VEVENT with RRULE which has repeat overrides
16 * will need quite a bit more thought to process correctly.
18 * @example
19 * To create a new iCalendar from several data values:
20 * $ical = new iCalendar( array('DTSTART' => $dtstart, 'SUMMARY' => $summary, 'DURATION' => $duration ) );
22 * @example
23 * To render it as an iCalendar string:
24 * echo $ical->Render();
26 * @example
27 * To render just the VEVENTs in the iCalendar with a restricted list of properties:
28 * echo $ical->Render( false, 'VEVENT', array( 'DTSTART', 'DURATION', 'DTEND', 'RRULE', 'SUMMARY') );
30 * @example
31 * To parse an existing iCalendar string for manipulation:
32 * $ical = new iCalendar( array('icalendar' => $icalendar_text ) );
34 * @example
35 * To clear any 'VALARM' components in an iCalendar object
36 * $ical->component->ClearComponents('VALARM');
38 * @example
39 * To replace any 'RRULE' property in an iCalendar object
40 * $ical->component->SetProperties( 'RRULE', $rrule_definition );
42 * @package awl
43 * @subpackage iCalendar
44 * @author Andrew McMillan <andrew@mcmillan.net.nz>
45 * @copyright Catalyst IT Ltd, Morphoss Ltd <http://www.morphoss.com/>
46 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later
49 require_once("XMLElement.php");
51 /**
52 * A Class for representing properties within an iCalendar
54 * @package awl
56 class iCalProp {
57 /**#@+
58 * @access private
61 /**
62 * The name of this property
64 * @var string
66 var $name;
68 /**
69 * An array of parameters to this property, represented as key/value pairs.
71 * @var array
73 var $parameters;
75 /**
76 * The value of this property.
78 * @var string
80 var $content;
82 /**
83 * The original value that this was parsed from, if that's the way it happened.
85 * @var string
87 var $rendered;
89 /**#@-*/
91 /**
92 * The constructor parses the incoming string, which is formatted as per RFC2445 as a
93 * propname[;param1=pval1[; ... ]]:propvalue
94 * however we allow ourselves to assume that the RFC2445 content unescaping has already
95 * happened when iCalComponent::ParseFrom() called iCalComponent::UnwrapComponent().
97 * @param string $propstring The string from the iCalendar which contains this property.
99 function iCalProp( $propstring = null ) {
100 $this->name = "";
101 $this->content = "";
102 $this->parameters = array();
103 unset($this->rendered);
104 if ( $propstring != null && gettype($propstring) == 'string' ) {
105 $this->ParseFrom($propstring);
111 * The constructor parses the incoming string, which is formatted as per RFC2445 as a
112 * propname[;param1=pval1[; ... ]]:propvalue
113 * however we allow ourselves to assume that the RFC2445 content unescaping has already
114 * happened when iCalComponent::ParseFrom() called iCalComponent::UnwrapComponent().
116 * @param string $propstring The string from the iCalendar which contains this property.
118 function ParseFrom( $propstring ) {
119 $this->rendered = (strlen($propstring) < 72 ? $propstring : null); // Only pre-rendered if we didn't unescape it
120 $pos = strpos( $propstring, ':');
121 $start = substr( $propstring, 0, $pos);
123 $unescaped = str_replace( '\\n', "\n", substr( $propstring, $pos + 1));
124 $unescaped = str_replace( '\\N', "\n", $unescaped);
125 $this->content = preg_replace( "/\\\\([,;:\"\\\\])/", '$1', $unescaped);
127 $parameters = explode(';',$start);
128 $this->name = array_shift( $parameters );
129 $this->parameters = array();
130 foreach( $parameters AS $k => $v ) {
131 $pos = strpos($v,'=');
132 $name = substr( $v, 0, $pos);
133 $value = substr( $v, $pos + 1);
134 $this->parameters[$name] = $value;
136 // dbg_error_log('iCalendar', " iCalProp::ParseFrom found '%s' = '%s' with %d parameters", $this->name, substr($this->content,0,200), count($this->parameters) );
141 * Get/Set name property
143 * @param string $newname [optional] A new name for the property
145 * @return string The name for the property.
147 function Name( $newname = null ) {
148 if ( $newname != null ) {
149 $this->name = $newname;
150 if ( isset($this->rendered) ) unset($this->rendered);
151 // dbg_error_log('iCalendar', " iCalProp::Name(%s)", $this->name );
153 return $this->name;
158 * Get/Set the content of the property
160 * @param string $newvalue [optional] A new value for the property
162 * @return string The value of the property.
164 function Value( $newvalue = null ) {
165 if ( $newvalue != null ) {
166 $this->content = $newvalue;
167 if ( isset($this->rendered) ) unset($this->rendered);
169 return $this->content;
174 * Get/Set parameters in their entirety
176 * @param array $newparams An array of new parameter key/value pairs
178 * @return array The current array of parameters for the property.
180 function Parameters( $newparams = null ) {
181 if ( $newparams != null ) {
182 $this->parameters = $newparams;
183 if ( isset($this->rendered) ) unset($this->rendered);
185 return $this->parameters;
190 * Test if our value contains a string
192 * @param string $search The needle which we shall search the haystack for.
194 * @return string The name for the property.
196 function TextMatch( $search ) {
197 if ( isset($this->content) ) return strstr( $this->content, $search );
198 return false;
203 * Get the value of a parameter
205 * @param string $name The name of the parameter to retrieve the value for
207 * @return string The value of the parameter
209 function GetParameterValue( $name ) {
210 if ( isset($this->parameters[$name]) ) return $this->parameters[$name];
214 * Set the value of a parameter
216 * @param string $name The name of the parameter to set the value for
218 * @param string $value The value of the parameter
220 function SetParameterValue( $name, $value ) {
221 if ( isset($this->rendered) ) unset($this->rendered);
222 $this->parameters[$name] = $value;
226 * Render the set of parameters as key1=value1[;key2=value2[; ...]] with
227 * any colons or semicolons escaped.
229 function RenderParameters() {
230 $rendered = "";
231 foreach( $this->parameters AS $k => $v ) {
232 $escaped = preg_replace( "/([;:\"])/", '\\\\$1', $v);
233 $rendered .= sprintf( ";%s=%s", $k, $escaped );
235 return $rendered;
240 * Render a suitably escaped RFC2445 content string.
242 function Render() {
243 // If we still have the string it was parsed in from, it hasn't been screwed with
244 // and we can just return that without modification.
245 if ( isset($this->rendered) ) return $this->rendered;
247 $property = preg_replace( '/[;].*$/', '', $this->name );
248 $escaped = $this->content;
249 switch( $property ) {
250 /** Content escaping does not apply to these properties culled from RFC2445 */
251 case 'ATTACH': case 'GEO': case 'PERCENT-COMPLETE': case 'PRIORITY':
252 case 'DURATION': case 'FREEBUSY': case 'TZOFFSETFROM': case 'TZOFFSETTO':
253 case 'TZURL': case 'ATTENDEE': case 'ORGANIZER': case 'RECURRENCE-ID':
254 case 'URL': case 'EXRULE': case 'SEQUENCE': case 'CREATED':
255 case 'RRULE': case 'REPEAT': case 'TRIGGER':
256 break;
258 case 'COMPLETED': case 'DTEND':
259 case 'DUE': case 'DTSTART':
260 case 'DTSTAMP': case 'LAST-MODIFIED':
261 case 'CREATED': case 'EXDATE':
262 case 'RDATE':
263 if ( isset($this->parameters['VALUE']) && $this->parameters['VALUE'] == 'DATE' ) {
264 $escaped = substr( $escaped, 0, 8);
266 break;
268 /** Content escaping applies by default to other properties */
269 default:
270 $escaped = str_replace( '\\', '\\\\', $escaped);
271 $escaped = preg_replace( '/\r?\n/', '\\n', $escaped);
272 $escaped = preg_replace( "/([,;\"])/", '\\\\$1', $escaped);
274 $property = sprintf( "%s%s:", $this->name, $this->RenderParameters() );
275 if ( (strlen($property) + strlen($escaped)) <= 72 ) {
276 $this->rendered = $property . $escaped;
278 else if ( (strlen($property) + strlen($escaped)) > 72 && (strlen($property) < 72) && (strlen($escaped) < 72) ) {
279 $this->rendered = $property . " \r\n " . $escaped;
281 else {
282 $this->rendered = wordwrap( $property . $escaped, 72, " \r\n ", true );
284 return $this->rendered;
291 * A Class for representing components within an iCalendar
293 * @package awl
295 class iCalComponent {
296 /**#@+
297 * @access private
301 * The type of this component, such as 'VEVENT', 'VTODO', 'VTIMEZONE', etc.
303 * @var string
305 var $type;
308 * An array of properties, which are iCalProp objects
310 * @var array
312 var $properties;
315 * An array of (sub-)components, which are iCalComponent objects
317 * @var array
319 var $components;
322 * The rendered result (or what was originally parsed, if there have been no changes)
324 * @var array
326 var $rendered;
328 /**#@-*/
331 * A basic constructor
333 function iCalComponent( $content = null ) {
334 $this->type = "";
335 $this->properties = array();
336 $this->components = array();
337 $this->rendered = "";
338 if ( $content != null && (gettype($content) == 'string' || gettype($content) == 'array') ) {
339 $this->ParseFrom($content);
345 * Apply standard properties for a VCalendar
346 * @param array $extra_properties Key/value pairs of additional properties
348 function VCalendar( $extra_properties = null ) {
349 $this->SetType('VCALENDAR');
350 $this->AddProperty('PRODID', '-//davical.org//NONSGML AWL Calendar//EN');
351 $this->AddProperty('VERSION', '2.0');
352 $this->AddProperty('CALSCALE', 'GREGORIAN');
353 if ( is_array($extra_properties) ) {
354 foreach( $extra_properties AS $k => $v ) {
355 $this->AddProperty($k,$v);
361 * Collect an array of all parameters of our properties which are the specified type
362 * Mainly used for collecting the full variety of references TZIDs
364 function CollectParameterValues( $parameter_name ) {
365 $values = array();
366 foreach( $this->components AS $k => $v ) {
367 $also = $v->CollectParameterValues($parameter_name);
368 $values = array_merge( $values, $also );
370 foreach( $this->properties AS $k => $v ) {
371 $also = $v->GetParameterValue($parameter_name);
372 if ( isset($also) && $also != "" ) {
373 // dbg_error_log( 'iCalendar', "::CollectParameterValues(%s) : Found '%s'", $parameter_name, $also);
374 $values[$also] = 1;
377 return $values;
382 * Parse the text $content into sets of iCalProp & iCalComponent within this iCalComponent
383 * @param string $content The raw RFC2445-compliant iCalendar component, including BEGIN:TYPE & END:TYPE
385 function ParseFrom( $content ) {
386 $this->rendered = $content;
387 $content = $this->UnwrapComponent($content);
389 $type = false;
390 $subtype = false;
391 $finish = null;
392 $subfinish = null;
394 $length = strlen($content);
395 $linefrom = 0;
396 while( $linefrom < $length ) {
397 $lineto = strpos( $content, "\n", $linefrom );
398 if ( $lineto === false ) {
399 $lineto = strpos( $content, "\r", $linefrom );
401 if ( $lineto > 0 ) {
402 $line = substr( $content, $linefrom, $lineto - $linefrom);
403 $linefrom = $lineto + 1;
405 else {
406 $line = substr( $content, $linefrom );
407 $linefrom = $length;
409 if ( preg_match('/^\s*$/', $line ) ) continue;
410 $line = rtrim( $line, "\r\n" );
411 // dbg_error_log( 'iCalendar', "::ParseFrom: Parsing line: $line");
413 if ( $type === false ) {
414 if ( preg_match( '/^BEGIN:(.+)$/', $line, $matches ) ) {
415 // We have found the start of the main component
416 $type = $matches[1];
417 $finish = "END:$type";
418 $this->type = $type;
419 dbg_error_log( 'iCalendar', "::ParseFrom: Start component of type '%s'", $type);
421 else {
422 dbg_error_log( 'iCalendar', "::ParseFrom: Ignoring crap before start of component: $line");
423 // unset($lines[$k]); // The content has crap before the start
424 if ( $line != "" ) $this->rendered = null;
427 else if ( $type == null ) {
428 dbg_error_log( 'iCalendar', "::ParseFrom: Ignoring crap after end of component");
429 unset($lines[$k]); // The content has crap after the end
430 if ( $line != "" ) $this->rendered = null;
432 else if ( $line == $finish ) {
433 dbg_error_log( 'iCalendar', "::ParseFrom: End of component");
434 $type = null; // We have reached the end of our component
436 else {
437 if ( $subtype === false && preg_match( '/^BEGIN:(.+)$/', $line, $matches ) ) {
438 // We have found the start of a sub-component
439 $subtype = $matches[1];
440 $subfinish = "END:$subtype";
441 $subcomponent = $line . "\r\n";
442 dbg_error_log( 'iCalendar', "::ParseFrom: Found a subcomponent '%s'", $subtype);
444 else if ( $subtype ) {
445 // We are inside a sub-component
446 $subcomponent .= $this->WrapComponent($line);
447 if ( $line == $subfinish ) {
448 dbg_error_log( 'iCalendar', "::ParseFrom: End of subcomponent '%s'", $subtype);
449 // We have found the end of a sub-component
450 $this->components[] = new iCalComponent($subcomponent);
451 $subtype = false;
453 // else
454 // dbg_error_log( 'iCalendar', "::ParseFrom: Inside a subcomponent '%s'", $subtype );
456 else {
457 // dbg_error_log( 'iCalendar', "::ParseFrom: Parse property of component");
458 // It must be a normal property line within a component.
459 $this->properties[] = new iCalProp($line);
467 * This unescapes the (CRLF + linear space) wrapping specified in RFC2445. According
468 * to RFC2445 we should always end with CRLF but the CalDAV spec says that normalising
469 * XML parsers often muck with it and may remove the CR. We accept either case.
471 function UnwrapComponent( $content ) {
472 return preg_replace('/\r?\n[ \t]/', '', $content );
476 * This imposes the (CRLF + linear space) wrapping specified in RFC2445. According
477 * to RFC2445 we should always end with CRLF but the CalDAV spec says that normalising
478 * XML parsers often muck with it and may remove the CR. We output RFC2445 compliance.
480 * In order to preserve pre-existing wrapping in the component, we split the incoming
481 * string on line breaks before running wordwrap over each component of that.
483 function WrapComponent( $content ) {
484 $strs = preg_split( "/\r?\n/", $content );
485 $wrapped = "";
486 foreach ($strs as $str) {
487 $wrapped .= wordwrap($str, 73, " \r\n ") . "\r\n";
489 return $wrapped;
493 * Return the type of component which this is
495 function GetType() {
496 return $this->type;
501 * Set the type of component which this is
503 function SetType( $type ) {
504 if ( isset($this->rendered) ) unset($this->rendered);
505 $this->type = $type;
506 return $this->type;
511 * Get all properties, or the properties matching a particular type
513 function GetProperties( $type = null ) {
514 $properties = array();
515 foreach( $this->properties AS $k => $v ) {
516 if ( $type == null || $v->Name() == $type ) {
517 $properties[$k] = $v;
520 return $properties;
525 * Get the value of the first property matching the name. Obviously this isn't
526 * so useful for properties which may occur multiply, but most don't.
528 * @param string $type The type of property we are after.
529 * @return string The value of the property, or null if there was no such property.
531 function GetPValue( $type ) {
532 foreach( $this->properties AS $k => $v ) {
533 if ( $v->Name() == $type ) return $v->Value();
535 return null;
540 * Get the value of the specified parameter for the first property matching the
541 * name. Obviously this isn't so useful for properties which may occur multiply, but most don't.
543 * @param string $type The type of property we are after.
544 * @param string $type The name of the parameter we are after.
545 * @return string The value of the parameter for the property, or null in the case that there was no such property, or no such parameter.
547 function GetPParamValue( $type, $parameter_name ) {
548 foreach( $this->properties AS $k => $v ) {
549 if ( $v->Name() == $type ) return $v->GetParameterValue($parameter_name);
551 return null;
556 * Clear all properties, or the properties matching a particular type
557 * @param string $type The type of property - omit for all properties
559 function ClearProperties( $type = null ) {
560 if ( $type != null ) {
561 // First remove all the existing ones of that type
562 foreach( $this->properties AS $k => $v ) {
563 if ( $v->Name() == $type ) {
564 unset($this->properties[$k]);
565 if ( isset($this->rendered) ) unset($this->rendered);
568 $this->properties = array_values($this->properties);
570 else {
571 if ( isset($this->rendered) ) unset($this->rendered);
572 $this->properties = array();
578 * Set all properties, or the ones matching a particular type
580 function SetProperties( $new_properties, $type = null ) {
581 if ( isset($this->rendered) && count($new_properties) > 0 ) unset($this->rendered);
582 $this->ClearProperties($type);
583 foreach( $new_properties AS $k => $v ) {
584 $this->AddProperty($v);
590 * Adds a new property
592 * @param iCalProp $new_property The new property to append to the set, or a string with the name
593 * @param string $value The value of the new property (default: param 1 is an iCalProp with everything
594 * @param array $parameters The key/value parameter pairs (default: none, or param 1 is an iCalProp with everything)
596 function AddProperty( $new_property, $value = null, $parameters = null ) {
597 if ( isset($this->rendered) ) unset($this->rendered);
598 if ( isset($value) && gettype($new_property) == 'string' ) {
599 $new_prop = new iCalProp();
600 $new_prop->Name($new_property);
601 $new_prop->Value($value);
602 if ( $parameters != null ) $new_prop->Parameters($parameters);
603 dbg_error_log('iCalendar'," Adding new property '%s'", $new_prop->Render() );
604 $this->properties[] = $new_prop;
606 else if ( gettype($new_property) ) {
607 $this->properties[] = $new_property;
613 * Get all sub-components, or at least get those matching a type
614 * @return array an array of the sub-components
616 function &FirstNonTimezone( $type = null ) {
617 foreach( $this->components AS $k => $v ) {
618 if ( $v->GetType() != 'VTIMEZONE' ) return $this->components[$k];
620 $result = false;
621 return $result;
626 * Return true if the person identified by the email address is down as an
627 * organizer for this meeting.
628 * @param string $email The e-mail address of the person we're seeking.
629 * @return boolean true if we found 'em, false if we didn't.
631 function IsOrganizer( $email ) {
632 if ( !preg_match( '#^mailto:#', $email ) ) $email = 'mailto:$email';
633 $props = $this->GetPropertiesByPath('!VTIMEZONE/ORGANIZER');
634 foreach( $props AS $k => $prop ) {
635 if ( $prop->Value() == $email ) return true;
637 return false;
642 * Return true if the person identified by the email address is down as an
643 * attendee or organizer for this meeting.
644 * @param string $email The e-mail address of the person we're seeking.
645 * @return boolean true if we found 'em, false if we didn't.
647 function IsAttendee( $email ) {
648 if ( !preg_match( '#^mailto:#', $email ) ) $email = 'mailto:$email';
649 if ( $this->IsOrganizer($email) ) return true; /** an organizer is an attendee, as far as we're concerned */
650 $props = $this->GetPropertiesByPath('!VTIMEZONE/ATTENDEE');
651 foreach( $props AS $k => $prop ) {
652 if ( $prop->Value() == $email ) return true;
654 return false;
659 * Get all sub-components, or at least get those matching a type, or failling to match,
660 * should the second parameter be set to false.
662 * @param string $type The type to match (default: All)
663 * @param boolean $normal_match Set to false to invert the match (default: true)
664 * @return array an array of the sub-components
666 function GetComponents( $type = null, $normal_match = true ) {
667 $components = $this->components;
668 if ( $type != null ) {
669 foreach( $components AS $k => $v ) {
670 if ( ($v->GetType() != $type) === $normal_match ) {
671 unset($components[$k]);
674 $components = array_values($components);
676 return $components;
681 * Clear all components, or the components matching a particular type
682 * @param string $type The type of component - omit for all components
684 function ClearComponents( $type = null ) {
685 if ( $type != null ) {
686 // First remove all the existing ones of that type
687 foreach( $this->components AS $k => $v ) {
688 if ( $v->GetType() == $type ) {
689 unset($this->components[$k]);
690 if ( isset($this->rendered) ) unset($this->rendered);
692 else {
693 if ( ! $this->components[$k]->ClearComponents($type) ) {
694 if ( isset($this->rendered) ) unset($this->rendered);
698 return isset($this->rendered);
700 else {
701 if ( isset($this->rendered) ) unset($this->rendered);
702 $this->components = array();
708 * Sets some or all sub-components of the component to the supplied new components
710 * @param array of iCalComponent $new_components The new components to replace the existing ones
711 * @param string $type The type of components to be replaced. Defaults to null, which means all components will be replaced.
713 function SetComponents( $new_component, $type = null ) {
714 if ( isset($this->rendered) ) unset($this->rendered);
715 if ( count($new_component) > 0 ) $this->ClearComponents($type);
716 foreach( $new_component AS $k => $v ) {
717 $this->components[] = $v;
723 * Adds a new subcomponent
725 * @param iCalComponent $new_component The new component to append to the set
727 function AddComponent( $new_component ) {
728 if ( is_array($new_component) && count($new_component) == 0 ) return;
729 if ( isset($this->rendered) ) unset($this->rendered);
730 if ( is_array($new_component) ) {
731 foreach( $new_component AS $k => $v ) {
732 $this->components[] = $v;
735 else {
736 $this->components[] = $new_component;
742 * Mask components, removing any that are not of the types in the list
743 * @param array $keep An array of component types to be kept
745 function MaskComponents( $keep ) {
746 foreach( $this->components AS $k => $v ) {
747 if ( ! in_array( $v->GetType(), $keep ) ) {
748 unset($this->components[$k]);
749 if ( isset($this->rendered) ) unset($this->rendered);
751 else {
752 $v->MaskComponents($keep);
759 * Mask properties, removing any that are not in the list
760 * @param array $keep An array of property names to be kept
761 * @param array $component_list An array of component types to check within
763 function MaskProperties( $keep, $component_list=null ) {
764 foreach( $this->components AS $k => $v ) {
765 $v->MaskProperties($keep, $component_list);
768 if ( !isset($component_list) || in_array($this->GetType(),$component_list) ) {
769 foreach( $this->components AS $k => $v ) {
770 if ( ! in_array( $v->GetType(), $keep ) ) {
771 unset($this->components[$k]);
772 if ( isset($this->rendered) ) unset($this->rendered);
780 * Clone this component (and subcomponents) into a confidential version of it. A confidential
781 * event will be scrubbed of any identifying characteristics other than time/date, repeat, uid
782 * and a summary which is just a translated 'Busy'.
784 function CloneConfidential() {
785 $confidential = clone($this);
786 $keep_properties = array( 'DTSTAMP', 'DTSTART', 'RRULE', 'DURATION', 'DTEND', 'UID', 'CLASS', 'TRANSP' );
787 $resource_components = array( 'VEVENT', 'VTODO', 'VJOURNAL' );
788 $confidential->MaskComponents(array( 'VTIMEZONE', 'VEVENT', 'VTODO', 'VJOURNAL' ));
789 $confidential->MaskProperties($keep_properties, $resource_components );
790 if ( in_array( $confidential->GetType(), $resource_components ) ) {
791 $confidential->AddProperty( 'SUMMARY', translate('Busy') );
793 foreach( $confidential->components AS $k => $v ) {
794 if ( in_array( $v->GetType(), $resource_components ) ) {
795 $v->AddProperty( 'SUMMARY', translate('Busy') );
799 return $confidential;
804 * Renders the component, possibly restricted to only the listed properties
806 function Render( $restricted_properties = null) {
808 $unrestricted = (!isset($restricted_properties) || count($restricted_properties) == 0);
810 if ( isset($this->rendered) && $unrestricted )
811 return $this->rendered;
813 $rendered = "BEGIN:$this->type\r\n";
814 foreach( $this->properties AS $k => $v ) {
815 if ( method_exists($v, 'Render') ) {
816 if ( $unrestricted || isset($restricted_properties[$v]) ) $rendered .= $v->Render() . "\r\n";
819 foreach( $this->components AS $v ) { $rendered .= $v->Render(); }
820 $rendered .= "END:$this->type\r\n";
822 if ( $unrestricted ) $this->rendered = $rendered;
824 return $rendered;
829 * Return an array of properties matching the specified path
831 * @return array An array of iCalProp within the tree which match the path given, in the form
832 * [/]COMPONENT[/...]/PROPERTY in a syntax kind of similar to our poor man's XML queries. We
833 * also allow COMPONENT and PROPERTY to be !COMPONENT and !PROPERTY for ++fun.
835 * @note At some point post PHP4 this could be re-done with an iterator, which should be more efficient for common use cases.
837 function GetPropertiesByPath( $path ) {
838 $properties = array();
839 dbg_error_log( 'iCalendar', "GetPropertiesByPath: Querying within '%s' for path '%s'", $this->type, $path );
840 if ( !preg_match( '#(/?)(!?)([^/]+)(/?.*)$#', $path, $matches ) ) return $properties;
842 $adrift = ($matches[1] == '');
843 $normal = ($matches[2] == '');
844 $ourtest = $matches[3];
845 $therest = $matches[4];
846 dbg_error_log( 'iCalendar', "GetPropertiesByPath: Matches: %s -- %s -- %s -- %s\n", $matches[1], $matches[2], $matches[3], $matches[4] );
847 if ( $ourtest == '*' || (($ourtest == $this->type) === $normal) && $therest != '' ) {
848 if ( preg_match( '#^/(!?)([^/]+)$#', $therest, $matches ) ) {
849 $normmatch = ($matches[1] =='');
850 $proptest = $matches[2];
851 foreach( $this->properties AS $k => $v ) {
852 if ( $proptest = '*' || (($v->Name() == $proptest) === $normmatch ) ) {
853 $properties[] = $v;
857 else {
859 * There is more to the path, so we recurse into that sub-part
861 foreach( $this->components AS $k => $v ) {
862 $properties = array_merge( $properties, $v->GetPropertiesByPath($therest) );
867 if ( $adrift ) {
869 * Our input $path was not rooted, so we recurse further
871 foreach( $this->components AS $k => $v ) {
872 $properties = array_merge( $properties, $v->GetPropertiesByPath($path) );
875 dbg_error_log('iCalendar', "GetPropertiesByPath: Found %d within '%s' for path '%s'\n", count($properties), $this->type, $path );
876 return $properties;
882 ************************************************************************************
883 * Pretty much everything below here is deprecated and should be avoided in favour
884 * of using, improving and enhancing the more sensible structures above.
885 ************************************************************************************
889 * A Class for handling Events on a calendar (DEPRECATED)
891 * @package awl
893 class iCalendar {
894 /**#@+
895 * @access private
899 * The component-ised version of the iCalendar
900 * @var component iCalComponent
902 var $component;
905 * An array of arbitrary properties, containing arbitrary arrays of arbitrary properties
906 * @var properties array
908 var $properties;
911 * An array of the lines of this iCalendar resource
912 * @var lines array
914 var $lines;
917 * The typical location name for the standard timezone such as "Pacific/Auckland"
918 * @var tz_locn string
920 var $tz_locn;
923 * The type of iCalendar data VEVENT/VTODO/VJOURNAL
924 * @var type string
926 var $type;
928 /**#@-*/
931 * The constructor takes an array of args. If there is an element called 'icalendar'
932 * then that will be parsed into the iCalendar object. Otherwise the array elements
933 * are converted into properties of the iCalendar object directly.
935 function iCalendar( $args ) {
936 global $c;
938 $this->tz_locn = "";
939 if ( !isset($args) || !(is_array($args) || is_object($args)) ) return;
940 if ( is_object($args) ) {
941 settype($args,'array');
944 $this->component = new iCalComponent();
945 if ( isset($args['icalendar']) ) {
946 $this->component->ParseFrom($args['icalendar']);
947 $this->lines = preg_split('/\r?\n/', $args['icalendar'] );
948 $this->SaveTimeZones();
949 $first =& $this->component->FirstNonTimezone();
950 if ( $first ) {
951 $this->type = $first->GetType();
952 $this->properties = $first->GetProperties();
954 else {
955 $this->properties = array();
957 $this->properties['VCALENDAR'] = array('***ERROR*** This class is being referenced in an unsupported way!');
958 return;
961 if ( isset($args['type'] ) ) {
962 $this->type = $args['type'];
963 unset( $args['type'] );
965 else {
966 $this->type = 'VEVENT'; // Default to event
968 $this->component->SetType('VCALENDAR');
969 $this->component->SetProperties(
970 array(
971 new iCalProp('PRODID:-//davical.org//NONSGML AWL Calendar//EN'),
972 new iCalProp('VERSION:2.0'),
973 new iCalProp('CALSCALE:GREGORIAN')
976 $first = new iCalComponent();
977 $first->SetType($this->type);
978 $this->properties = array();
980 foreach( $args AS $k => $v ) {
981 dbg_error_log( 'iCalendar', ":Initialise: %s to >>>%s<<<", $k, $v );
982 $property = new iCalProp();
983 $property->Name($k);
984 $property->Value($v);
985 $this->properties[] = $property;
987 $first->SetProperties($this->properties);
988 $this->component->SetComponents( array($first) );
990 $this->properties['VCALENDAR'] = array('***ERROR*** This class is being referenced in an unsupported way!');
993 * @todo Need to handle timezones!!!
995 if ( $this->tz_locn == "" ) {
996 $this->tz_locn = $this->Get("tzid");
997 if ( (!isset($this->tz_locn) || $this->tz_locn == "") && isset($c->local_tzid) ) {
998 $this->tz_locn = $c->local_tzid;
1005 * Save any timezones by TZID in the PostgreSQL database for future re-use.
1007 function SaveTimeZones() {
1008 global $c;
1010 $this->tzid_list = array_keys($this->component->CollectParameterValues('TZID'));
1011 if ( ! isset($this->tzid) && count($this->tzid_list) > 0 ) {
1012 dbg_error_log( 'iCalendar', "::TZID_List[0] = '%s', count=%d", $this->tzid_list[0], count($this->tzid_list) );
1013 $this->tzid = $this->tzid_list[0];
1016 $timezones = $this->component->GetComponents('VTIMEZONE');
1017 if ( $timezones === false || count($timezones) == 0 ) return;
1018 $this->vtimezone = $timezones[0]->Render(); // Backward compatibility
1020 $tzid = $this->Get('TZID');
1021 if ( isset($c->save_time_zone_defs) && $c->save_time_zone_defs ) {
1022 foreach( $timezones AS $k => $tz ) {
1023 $tzid = $tz->GetPValue('TZID');
1025 $qry = new PgQuery( "SELECT tz_locn FROM time_zone WHERE tz_id = ?;", $tzid );
1026 if ( $qry->Exec('iCalendar') && $qry->rows == 1 ) {
1027 $row = $qry->Fetch();
1028 if ( !isset($first_tzid) ) $first_tzid = $row->tz_locn;
1029 continue;
1032 if ( $tzid != "" && $qry->rows == 0 ) {
1034 $tzname = $tz->GetPValue('X-LIC-LOCATION');
1035 if ( !isset($tzname) ) {
1037 * Try and convert the TZID to a string like "Pacific/Auckland" if possible.
1039 $tzname = preg_replace('#^(.*[^a-z])?([a-z]+/[a-z]+)$#i','$2',$tzid );
1042 $qry2 = new PgQuery( "INSERT INTO time_zone (tz_id, tz_locn, tz_spec) VALUES( ?, ?, ? );",
1043 $tzid, $tzname, $tz->Render() );
1044 $qry2->Exec('iCalendar');
1048 if ( ! isset($this->tzid) && isset($first_tzid) ) $this->tzid = $first_tzid;
1050 if ( (!isset($this->tz_locn) || $this->tz_locn == '') && isset($first_tzid) && $first_tzid != '' ) {
1051 $tzname = preg_replace('#^(.*[^a-z])?([a-z]+/[a-z]+)$#i','$2', $first_tzid );
1052 if ( preg_match( '#\S+/\S+#', $tzname) ) {
1053 $this->tz_locn = $tzname;
1055 dbg_error_log( 'iCalendar', " TZCrap1: TZID '%s', Location '%s', Perhaps: %s", $tzid, $this->tz_locn, $tzname );
1058 if ( (!isset($this->tz_locn) || $this->tz_locn == "") && isset($c->local_tzid) ) {
1059 $this->tz_locn = $c->local_tzid;
1061 if ( ! isset($this->tzid) && isset($this->tz_locn) ) $this->tzid = $this->tz_locn;
1066 * An array of property names that we should always want when rendering an iCalendar
1068 * @deprecated This function is deprecated and will be removed eventually.
1069 * @todo Remove this function.
1071 function DefaultPropertyList() {
1072 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'DefaultPropertyList' );
1073 return array( "UID" => 1, "DTSTAMP" => 1, "DTSTART" => 1, "DURATION" => 1,
1074 "LAST-MODIFIED" => 1,"CLASS" => 1, "TRANSP" => 1, "SEQUENCE" => 1,
1075 "DUE" => 1, "SUMMARY" => 1, "RRULE" => 1 );
1079 * A function to extract the contents of a BEGIN:SOMETHING to END:SOMETHING (perhaps multiply)
1080 * and return just that bit (or, of course, those bits :-)
1082 * @var string The type of thing(s) we want returned.
1083 * @var integer The number of SOMETHINGS we want to get.
1085 * @return string A string from BEGIN:SOMETHING to END:SOMETHING, possibly multiple of these
1087 * @deprecated This function is deprecated and will be removed eventually.
1088 * @todo Remove this function.
1090 function JustThisBitPlease( $type, $count=1 ) {
1091 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'JustThisBitPlease' );
1092 $answer = "";
1093 $intags = false;
1094 $start = "BEGIN:$type";
1095 $finish = "END:$type";
1096 dbg_error_log( 'iCalendar', ":JTBP: Looking for %d subsets of type %s", $count, $type );
1097 reset($this->lines);
1098 foreach( $this->lines AS $k => $v ) {
1099 if ( !$intags && $v == $start ) {
1100 $answer .= $v . "\n";
1101 $intags = true;
1103 else if ( $intags && $v == $finish ) {
1104 $answer .= $v . "\n";
1105 $intags = false;
1107 else if ( $intags ) {
1108 $answer .= $v . "\n";
1111 return $answer;
1116 * Function to parse lines from BEGIN:SOMETHING to END:SOMETHING into a nested array structure
1118 * @var string The "SOMETHING" from the BEGIN:SOMETHING line we just met
1119 * @return arrayref An array of the things we found between (excluding) the BEGIN & END, some of which might be sub-arrays
1121 * @deprecated This function is deprecated and will be removed eventually.
1122 * @todo Remove this function.
1124 function &ParseSomeLines( $type ) {
1125 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'ParseSomeLines' );
1126 $props = array();
1127 $properties =& $props;
1128 while( isset($this->lines[$this->_current_parse_line]) ) {
1129 $i = $this->_current_parse_line++;
1130 $line =& $this->lines[$i];
1131 dbg_error_log( 'iCalendar', ":Parse:%s LINE %03d: >>>%s<<<", $type, $i, $line );
1132 if ( $this->parsing_vtimezone ) {
1133 $this->vtimezone .= $line."\n";
1135 if ( preg_match( '/^(BEGIN|END):([^:]+)$/', $line, $matches ) ) {
1136 if ( $matches[1] == 'END' && $matches[2] == $type ) {
1137 if ( $type == 'VTIMEZONE' ) {
1138 $this->parsing_vtimezone = false;
1140 return $properties;
1142 else if( $matches[1] == 'END' ) {
1143 dbg_error_log("ERROR"," iCalendar: parse error: Unexpected END:%s when we were looking for END:%s", $matches[2], $type );
1144 return $properties;
1146 else if( $matches[1] == 'BEGIN' ) {
1147 $subtype = $matches[2];
1148 if ( $subtype == 'VTIMEZONE' ) {
1149 $this->parsing_vtimezone = true;
1150 $this->vtimezone = $line."\n";
1152 if ( !isset($properties['INSIDE']) ) $properties['INSIDE'] = array();
1153 $properties['INSIDE'][] = $subtype;
1154 if ( !isset($properties[$subtype]) ) $properties[$subtype] = array();
1155 $properties[$subtype][] = $this->ParseSomeLines($subtype);
1158 else {
1159 // Parse the property
1160 @list( $property, $value ) = preg_split('/:/', $line, 2 );
1161 if ( strpos( $property, ';' ) > 0 ) {
1162 $parameterlist = preg_split('/;/', $property );
1163 $property = array_shift($parameterlist);
1164 foreach( $parameterlist AS $pk => $pv ) {
1165 if ( $pv == "VALUE=DATE" ) {
1166 $value .= 'T000000';
1168 elseif ( preg_match('/^([^;:=]+)=([^;:=]+)$/', $pv, $matches) ) {
1169 switch( $matches[1] ) {
1170 case 'TZID': $properties['TZID'] = $matches[2]; break;
1171 default:
1172 dbg_error_log( 'iCalendar', " FYI: Ignoring Resource '%s', Property '%s', Parameter '%s', Value '%s'", $type, $property, $matches[1], $matches[2] );
1177 if ( $this->parsing_vtimezone && (!isset($this->tz_locn) || $this->tz_locn == "") && $property == 'X-LIC-LOCATION' ) {
1178 $this->tz_locn = $value;
1180 $properties[strtoupper($property)] = $this->RFC2445ContentUnescape($value);
1183 return $properties;
1188 * Build the iCalendar object from a text string which is a single iCalendar resource
1190 * @var string The RFC2445 iCalendar resource to be parsed
1192 * @deprecated This function is deprecated and will be removed eventually.
1193 * @todo Remove this function.
1195 function BuildFromText( $icalendar ) {
1196 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'BuildFromText' );
1198 * This unescapes the (CRLF + linear space) wrapping specified in RFC2445. According
1199 * to RFC2445 we should always end with CRLF but the CalDAV spec says that normalising
1200 * XML parsers often muck with it and may remove the CR.
1202 $icalendar = preg_replace('/\r?\n[ \t]/', '', $icalendar );
1204 $this->lines = preg_split('/\r?\n/', $icalendar );
1206 $this->_current_parse_line = 0;
1207 $this->properties = $this->ParseSomeLines('');
1210 * Our 'type' is the type of non-timezone inside a VCALENDAR
1212 if ( isset($this->properties['VCALENDAR'][0]['INSIDE']) ) {
1213 foreach ( $this->properties['VCALENDAR'][0]['INSIDE'] AS $k => $v ) {
1214 if ( $v == 'VTIMEZONE' ) continue;
1215 $this->type = $v;
1216 break;
1224 * Returns a content string with the RFC2445 escaping removed
1226 * @param string $escaped The incoming string to be escaped.
1227 * @return string The string with RFC2445 content escaping removed.
1229 * @deprecated This function is deprecated and will be removed eventually.
1230 * @todo Remove this function.
1232 function RFC2445ContentUnescape( $escaped ) {
1233 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'RFC2445ContentUnescape' );
1234 $unescaped = str_replace( '\\n', "\n", $escaped);
1235 $unescaped = str_replace( '\\N', "\n", $unescaped);
1236 $unescaped = preg_replace( "/\\\\([,;:\"\\\\])/", '$1', $unescaped);
1237 return $unescaped;
1243 * Do what must be done with time zones from on file. Attempt to turn
1244 * them into something that PostgreSQL can understand...
1246 * @deprecated This function is deprecated and will be removed eventually.
1247 * @todo Remove this function.
1249 function DealWithTimeZones() {
1250 global $c;
1252 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'DealWithTimeZones' );
1253 $tzid = $this->Get('TZID');
1254 if ( isset($c->save_time_zone_defs) && $c->save_time_zone_defs ) {
1255 $qry = new PgQuery( "SELECT tz_locn FROM time_zone WHERE tz_id = ?;", $tzid );
1256 if ( $qry->Exec('iCalendar') && $qry->rows == 1 ) {
1257 $row = $qry->Fetch();
1258 $this->tz_locn = $row->tz_locn;
1260 dbg_error_log( 'iCalendar', " TZCrap2: TZID '%s', DB Rows=%d, Location '%s'", $tzid, $qry->rows, $this->tz_locn );
1263 if ( (!isset($this->tz_locn) || $this->tz_locn == '') && $tzid != '' ) {
1265 * In case there was no X-LIC-LOCATION defined, let's hope there is something in the TZID
1266 * that we can use. We are looking for a string like "Pacific/Auckland" if possible.
1268 $tzname = preg_replace('#^(.*[^a-z])?([a-z]+/[a-z]+)$#i','$1',$tzid );
1270 * Unfortunately this kind of thing will never work well :-(
1272 if ( strstr( $tzname, ' ' ) ) {
1273 $words = preg_split('/\s/', $tzname );
1274 $tzabbr = '';
1275 foreach( $words AS $i => $word ) {
1276 $tzabbr .= substr( $word, 0, 1);
1278 $this->tz_locn = $tzabbr;
1281 if ( preg_match( '#\S+/\S+#', $tzname) ) {
1282 $this->tz_locn = $tzname;
1284 dbg_error_log( 'iCalendar', " TZCrap3: TZID '%s', Location '%s', Perhaps: %s", $tzid, $this->tz_locn, $tzname );
1287 if ( $tzid != '' && isset($c->save_time_zone_defs) && $c->save_time_zone_defs && $qry->rows != 1 && isset($this->vtimezone) && $this->vtimezone != "" ) {
1288 $qry2 = new PgQuery( "INSERT INTO time_zone (tz_id, tz_locn, tz_spec) VALUES( ?, ?, ? );",
1289 $tzid, $this->tz_locn, $this->vtimezone );
1290 $qry2->Exec('iCalendar');
1293 if ( (!isset($this->tz_locn) || $this->tz_locn == "") && isset($c->local_tzid) ) {
1294 $this->tz_locn = $c->local_tzid;
1300 * Get the value of a property in the first non-VTIMEZONE
1302 function Get( $key ) {
1303 if ( strtoupper($key) == 'TZID' ) {
1304 // backward compatibility hack
1305 dbg_error_log( 'iCalendar', " Get(TZID): TZID '%s', Location '%s'", (isset($this->tzid)?$this->tzid:"[not set]"), $this->tz_locn );
1306 if ( isset($this->tzid) ) return $this->tzid;
1307 return $this->tz_locn;
1310 * The property we work on is the first non-VTIMEZONE we find.
1312 $component =& $this->component->FirstNonTimezone();
1313 if ( $component === false ) return null;
1314 return $component->GetPValue(strtoupper($key));
1319 * Set the value of a property
1321 function Set( $key, $value ) {
1322 if ( $value == "" ) return;
1323 $key = strtoupper($key);
1324 $property = new iCalProp();
1325 $property->Name($key);
1326 $property->Value($value);
1327 if (isset($this->component->rendered) ) unset( $this->component->rendered );
1328 $component =& $this->component->FirstNonTimezone();
1329 $component->SetProperties( array($property), $key);
1330 return $this->Get($key);
1335 * Add a new property/value, regardless of whether it exists already
1337 * @param string $key The property key
1338 * @param string $value The property value
1339 * @param string $parameters Any parameters to set for the property, as an array of key/value pairs
1341 function Add( $key, $value, $parameters = null ) {
1342 if ( $value == "" ) return;
1343 $key = strtoupper($key);
1344 $property = new iCalProp();
1345 $property->Name($key);
1346 $property->Value($value);
1347 if ( isset($parameters) && is_array($parameters) ) {
1348 $property->parameters = $parameters;
1350 $component =& $this->component->FirstNonTimezone();
1351 $component->AddProperty($property);
1352 if (isset($this->component->rendered) ) unset( $this->component->rendered );
1357 * Get all sub-components, or at least get those matching a type, or failling to match,
1358 * should the second parameter be set to false.
1360 * @param string $type The type to match (default: All)
1361 * @param boolean $normal_match Set to false to invert the match (default: true)
1362 * @return array an array of the sub-components
1364 function GetComponents( $type = null, $normal_match = true ) {
1365 return $this->component->GetComponents($type,$normal_match);
1370 * Clear all components, or the components matching a particular type
1371 * @param string $type The type of component - omit for all components
1373 function ClearComponents( $type = null ) {
1374 $this->component->ClearComponents($type);
1379 * Sets some or all sub-components of the component to the supplied new components
1381 * @param array of iCalComponent $new_components The new components to replace the existing ones
1382 * @param string $type The type of components to be replaced. Defaults to null, which means all components will be replaced.
1384 function SetComponents( $new_component, $type = null ) {
1385 $this->component->SetComponents( $new_component, $type );
1390 * Adds a new subcomponent
1392 * @param iCalComponent $new_component The new component to append to the set
1394 function AddComponent( $new_component ) {
1395 $this->component->AddComponent($new_component);
1400 * Mask components, removing any that are not of the types in the list
1401 * @param array $keep An array of component types to be kept
1403 function MaskComponents( $keep ) {
1404 $this->component->MaskComponents($keep);
1409 * Returns a PostgreSQL Date Format string suitable for returning HTTP (RFC2068) dates
1410 * Preferred is "Sun, 06 Nov 1994 08:49:37 GMT" so we do that.
1412 static function HttpDateFormat() {
1413 return "'Dy, DD Mon IYYY HH24:MI:SS \"GMT\"'";
1418 * Returns a PostgreSQL Date Format string suitable for returning iCal dates
1420 static function SqlDateFormat() {
1421 return "'YYYYMMDD\"T\"HH24MISS'";
1426 * Returns a PostgreSQL Date Format string suitable for returning dates which
1427 * have been cast to UTC
1429 static function SqlUTCFormat() {
1430 return "'YYYYMMDD\"T\"HH24MISS\"Z\"'";
1435 * Returns a PostgreSQL Date Format string suitable for returning iCal durations
1436 * - this doesn't work for negative intervals, but events should not have such!
1438 static function SqlDurationFormat() {
1439 return "'\"PT\"HH24\"H\"MI\"M\"'";
1443 * Returns a suitably escaped RFC2445 content string.
1445 * @param string $name The incoming name[;param] prefixing the string.
1446 * @param string $value The incoming string to be escaped.
1448 * @deprecated This function is deprecated and will be removed eventually.
1449 * @todo Remove this function.
1451 function RFC2445ContentEscape( $name, $value ) {
1452 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'RFC2445ContentEscape' );
1453 $property = preg_replace( '/[;].*$/', '', $name );
1454 switch( $property ) {
1455 /** Content escaping does not apply to these properties culled from RFC2445 */
1456 case 'ATTACH': case 'GEO': case 'PERCENT-COMPLETE': case 'PRIORITY':
1457 case 'COMPLETED': case 'DTEND': case 'DUE': case 'DTSTART':
1458 case 'DURATION': case 'FREEBUSY': case 'TZOFFSETFROM': case 'TZOFFSETTO':
1459 case 'TZURL': case 'ATTENDEE': case 'ORGANIZER': case 'RECURRENCE-ID':
1460 case 'URL': case 'EXDATE': case 'EXRULE': case 'RDATE':
1461 case 'RRULE': case 'REPEAT': case 'TRIGGER': case 'CREATED':
1462 case 'DTSTAMP': case 'LAST-MODIFIED': case 'SEQUENCE':
1463 break;
1465 /** Content escaping applies by default to other properties */
1466 default:
1467 $value = str_replace( '\\', '\\\\', $value);
1468 $value = preg_replace( '/\r?\n/', '\\n', $value);
1469 $value = preg_replace( "/([,;:\"])/", '\\\\$1', $value);
1471 $result = wordwrap("$name:$value", 73, " \r\n ", true ) . "\r\n";
1472 return $result;
1476 * Return all sub-components of the given type, which are part of the
1477 * component we pass in as an array of lines.
1479 * @param array $component The component to be parsed
1480 * @param string $type The type of sub-components to be extracted
1481 * @param int $count The number of sub-components to extract (default: 9999)
1483 * @return array The sub-component lines
1485 function ExtractSubComponent( $component, $type, $count=9999 ) {
1486 $answer = array();
1487 $intags = false;
1488 $start = "BEGIN:$type";
1489 $finish = "END:$type";
1490 dbg_error_log( 'iCalendar', ":ExtractSubComponent: Looking for %d subsets of type %s", $count, $type );
1491 reset($component);
1492 foreach( $component AS $k => $v ) {
1493 if ( !$intags && $v == $start ) {
1494 $answer[] = $v;
1495 $intags = true;
1497 else if ( $intags && $v == $finish ) {
1498 $answer[] = $v;
1499 $intags = false;
1501 else if ( $intags ) {
1502 $answer[] = $v;
1505 return $answer;
1510 * Extract a particular property from the provided component. In doing so we
1511 * assume that the content was unescaped when iCalComponent::ParseFrom()
1512 * called iCalComponent::UnwrapComponent().
1514 * @param array $component An array of lines of this component
1515 * @param string $type The type of parameter
1517 * @return array An array of iCalProperty objects
1519 function ExtractProperty( $component, $type, $count=9999 ) {
1520 $answer = array();
1521 dbg_error_log( 'iCalendar', ":ExtractProperty: Looking for %d properties of type %s", $count, $type );
1522 reset($component);
1523 foreach( $component AS $k => $v ) {
1524 if ( preg_match( "/$type"."[;:]/i", $v ) ) {
1525 $answer[] = new iCalProp($v);
1526 dbg_error_log( 'iCalendar', ":ExtractProperty: Found property %s", $type );
1527 if ( --$count < 1 ) return $answer;
1530 return $answer;
1535 * Applies the filter conditions, possibly recursively, to the value which will be either
1536 * a single property, or an array of lines of the component under test.
1538 * @todo Eventually we need to handle all of these possibilities, which will mean writing
1539 * several routines:
1540 * - Get Property from Component
1541 * - Get Parameter from Property
1542 * - Test TimeRange
1543 * For the moment we will leave these, until there is a perceived need.
1545 * @param array $filter An array of XMLElement defining the filter(s)
1546 * @param mixed $value Either a string which is the single property, or an array of lines, for the component.
1547 * @return boolean Whether the filter passed / failed.
1549 function ApplyFilter( $filter, $value ) {
1550 foreach( $filter AS $k => $v ) {
1551 $tag = $v->GetTag();
1552 $value_type = gettype($value);
1553 $value_defined = (isset($value) && $value_type == 'string') || ($value_type == 'array' && count($value) > 0 );
1554 if ( $tag == 'urn:ietf:params:xml:ns:caldav:is-not-defined' && $value_defined ) {
1555 dbg_error_log( 'iCalendar', ":ApplyFilter: Value is set ('%s'), want unset, for filter %s", count($value), $tag );
1556 return false;
1558 elseif ( $tag == 'urn:ietf:params:xml:ns:caldav:is-defined' && !$value_defined ) {
1559 dbg_error_log( 'iCalendar', ":ApplyFilter: Want value, but it is not set for filter %s", $tag );
1560 return false;
1562 else {
1563 switch( $tag ) {
1564 case 'urn:ietf:params:xml:ns:caldav:time-range':
1565 /** todo:: While this is unimplemented here at present, most time-range tests should occur at the SQL level. */
1566 break;
1567 case 'urn:ietf:params:xml:ns:caldav:text-match':
1568 $search = $v->GetContent();
1569 // In this case $value will either be a string, or an array of iCalProp objects
1570 // since TEXT-MATCH does not apply to COMPONENT level - only property/parameter
1571 if ( gettype($value) != 'string' ) {
1572 if ( gettype($value) == 'array' ) {
1573 $match = false;
1574 foreach( $value AS $k1 => $v1 ) {
1575 // $v1 could be an iCalProp object
1576 if ( $match = $v1->TextMatch($search)) break;
1579 else {
1580 dbg_error_log( 'iCalendar', ":ApplyFilter: TEXT-MATCH will only work on strings or arrays of iCalProp. %s unsupported", gettype($value) );
1581 return true; // We return _true_ in this case, so the client sees the item
1584 else {
1585 $match = strstr( $value, $search[0] );
1587 $negate = $v->GetAttribute("negate-condition");
1588 if ( isset($negate) && strtolower($negate) == "yes" && $match ) {
1589 dbg_error_log( 'iCalendar', ":ApplyFilter: TEXT-MATCH of %s'%s' against '%s'", (isset($negate) && strtolower($negate) == "yes"?'!':''), $search, $value );
1590 return false;
1592 break;
1593 case 'urn:ietf:params:xml:ns:caldav:comp-filter':
1594 $subfilter = $v->GetContent();
1595 $component = $this->ExtractSubComponent($value,$v->GetAttribute("name"));
1596 if ( ! $this->ApplyFilter($subfilter,$component) ) return false;
1597 break;
1598 case 'urn:ietf:params:xml:ns:caldav:prop-filter':
1599 $subfilter = $v->GetContent();
1600 $properties = $this->ExtractProperty($value,$v->GetAttribute("name"));
1601 if ( ! $this->ApplyFilter($subfilter,$properties) ) return false;
1602 break;
1603 case 'urn:ietf:params:xml:ns:caldav:param-filter':
1604 $subfilter = $v->GetContent();
1605 $parameter = $this->ExtractParameter($value,$v->GetAttribute("NAME"));
1606 if ( ! $this->ApplyFilter($subfilter,$parameter) ) return false;
1607 break;
1611 return true;
1615 * Test a PROP-FILTER or COMP-FILTER and return a true/false
1616 * COMP-FILTER (is-defined | is-not-defined | (time-range?, prop-filter*, comp-filter*))
1617 * PROP-FILTER (is-defined | is-not-defined | ((time-range | text-match)?, param-filter*))
1619 * @param array $filter An array of XMLElement defining the filter
1621 * @return boolean Whether or not this iCalendar passes the test
1623 function TestFilter( $filters ) {
1625 foreach( $filters AS $k => $v ) {
1626 $tag = $v->GetTag();
1627 $name = $v->GetAttribute("name");
1628 $filter = $v->GetContent();
1629 if ( $tag == "urn:ietf:params:xml:ns:caldav:prop-filter" ) {
1630 $value = $this->ExtractProperty($this->lines,$name);
1632 else {
1633 $value = $this->ExtractSubComponent($this->lines,$v->GetAttribute("name"));
1635 if ( count($value) == 0 ) unset($value);
1636 if ( ! $this->ApplyFilter($filter,$value) ) return false;
1638 return true;
1642 * Returns the header we always use at the start of our iCalendar resources
1644 * @deprecated This function is deprecated and will be removed eventually.
1645 * @todo Remove this function.
1647 static function iCalHeader() {
1648 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'iCalHeader' );
1649 return <<<EOTXT
1650 BEGIN:VCALENDAR\r
1651 PRODID:-//davical.org//NONSGML AWL Calendar//EN\r
1652 VERSION:2.0\r
1654 EOTXT;
1660 * Returns the footer we always use at the finish of our iCalendar resources
1662 * @deprecated This function is deprecated and will be removed eventually.
1663 * @todo Remove this function.
1665 static function iCalFooter() {
1666 dbg_error_log( "LOG", " iCalendar: Call to deprecated method '%s'", 'iCalFooter' );
1667 return "END:VCALENDAR\r\n";
1672 * Render the iCalendar object as a text string which is a single VEVENT (or other)
1674 * @param boolean $as_calendar Whether or not to wrap the event in a VCALENDAR
1675 * @param string $type The type of iCalendar object (VEVENT, VTODO, VFREEBUSY etc.)
1676 * @param array $restrict_properties The names of the properties we want in our rendered result.
1678 function Render( $as_calendar = true, $type = null, $restrict_properties = null ) {
1679 if ( $as_calendar ) {
1680 return $this->component->Render();
1682 else {
1683 $components = $this->component->GetComponents($type);
1684 $rendered = "";
1685 foreach( $components AS $k => $v ) {
1686 $rendered .= $v->Render($restrict_properties);
1688 return $rendered;