source: trunk/zpush/backend/zarafa/mapi/class.recurrence.php @ 7589

Revision 7589, 73.8 KB checked in by douglas, 11 years ago (diff)

Ticket #3209 - Integrar módulo de sincronização Z-push ao Expresso

Line 
1<?php
2/*
3 * Copyright 2005 - 2012  Zarafa B.V.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License, version 3,
7 * as published by the Free Software Foundation with the following additional
8 * term according to sec. 7:
9 *
10 * According to sec. 7 of the GNU Affero General Public License, version
11 * 3, the terms of the AGPL are supplemented with the following terms:
12 *
13 * "Zarafa" is a registered trademark of Zarafa B.V. The licensing of
14 * the Program under the AGPL does not imply a trademark license.
15 * Therefore any rights, title and interest in our trademarks remain
16 * entirely with us.
17 *
18 * However, if you propagate an unmodified version of the Program you are
19 * allowed to use the term "Zarafa" to indicate that you distribute the
20 * Program. Furthermore you may use our trademarks where it is necessary
21 * to indicate the intended purpose of a product or service provided you
22 * use it in accordance with honest practices in industrial or commercial
23 * matters.  If you want to propagate modified versions of the Program
24 * under the name "Zarafa" or "Zarafa Server", you may only do so if you
25 * have a written permission by Zarafa B.V. (to acquire a permission
26 * please contact Zarafa at trademark@zarafa.com).
27 *
28 * The interactive user interface of the software displays an attribution
29 * notice containing the term "Zarafa" and/or the logo of Zarafa.
30 * Interactive user interfaces of unmodified and modified versions must
31 * display Appropriate Legal Notices according to sec. 5 of the GNU
32 * Affero General Public License, version 3, when you propagate
33 * unmodified or modified versions of the Program. In accordance with
34 * sec. 7 b) of the GNU Affero General Public License, version 3, these
35 * Appropriate Legal Notices must retain the logo of Zarafa or display
36 * the words "Initial Development by Zarafa" if the display of the logo
37 * is not reasonably feasible for technical reasons. The use of the logo
38 * of Zarafa in Legal Notices is allowed for unmodified and modified
39 * versions of the software.
40 *
41 * This program is distributed in the hope that it will be useful,
42 * but WITHOUT ANY WARRANTY; without even the implied warranty of
43 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 * GNU Affero General Public License for more details.
45 *
46 * You should have received a copy of the GNU Affero General Public License
47 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
48 *
49 */
50
51    include_once('backend/zarafa/mapi/class.baserecurrence.php');
52
53    /**
54     * Recurrence
55     * @author Steve Hardy <steve@zarafa.com>
56     * @author Michel de Ron <michel@zarafa.com>
57     */
58    class Recurrence extends BaseRecurrence
59    {
60        /*
61         * ABOUT TIMEZONES
62         *
63         * Timezones are rather complicated here so here are some rules to think about:
64         *
65         * - Timestamps in mapi-like properties (so in PT_SYSTIME properties) are always in GMT (including
66         *   the 'basedate' property in exceptions !!)
67         * - Timestamps for recurrence (so start/end of recurrence, and basedates for exceptions (everything
68         *   outside the 'basedate' property in the exception !!), and start/endtimes for exceptions) are
69         *   always in LOCAL time.
70         */
71
72        // All properties for a recipient that are interesting
73        var $recipprops = Array(
74            PR_ENTRYID,
75            PR_SEARCH_KEY,
76            PR_DISPLAY_NAME,
77            PR_EMAIL_ADDRESS,
78            PR_RECIPIENT_ENTRYID,
79            PR_RECIPIENT_TYPE,
80            PR_SEND_INTERNET_ENCODING,
81            PR_SEND_RICH_INFO,
82            PR_RECIPIENT_DISPLAY_NAME,
83            PR_ADDRTYPE,
84            PR_DISPLAY_TYPE,
85            PR_DISPLAY_TYPE_EX,
86            PR_RECIPIENT_TRACKSTATUS,
87            PR_RECIPIENT_TRACKSTATUS_TIME,
88            PR_RECIPIENT_FLAGS,
89            PR_ROWID
90        );
91
92        /**
93         * Constructor
94         * @param resource $store MAPI Message Store Object
95         * @param resource $message the MAPI (appointment) message
96         */
97        function Recurrence($store, $message)
98        {
99
100            $properties = array();
101            $properties["entryid"] = PR_ENTRYID;
102            $properties["parent_entryid"] = PR_PARENT_ENTRYID;
103            $properties["message_class"] = PR_MESSAGE_CLASS;
104            $properties["icon_index"] = PR_ICON_INDEX;
105            $properties["subject"] = PR_SUBJECT;
106            $properties["display_to"] = PR_DISPLAY_TO;
107            $properties["importance"] = PR_IMPORTANCE;
108            $properties["sensitivity"] = PR_SENSITIVITY;
109            $properties["startdate"] = "PT_SYSTIME:PSETID_Appointment:0x820d";
110            $properties["duedate"] = "PT_SYSTIME:PSETID_Appointment:0x820e";
111            $properties["recurring"] = "PT_BOOLEAN:PSETID_Appointment:0x8223";
112            $properties["recurring_data"] = "PT_BINARY:PSETID_Appointment:0x8216";
113            $properties["busystatus"] = "PT_LONG:PSETID_Appointment:0x8205";
114            $properties["label"] = "PT_LONG:PSETID_Appointment:0x8214";
115            $properties["alldayevent"] = "PT_BOOLEAN:PSETID_Appointment:0x8215";
116            $properties["private"] = "PT_BOOLEAN:PSETID_Common:0x8506";
117            $properties["meeting"] = "PT_LONG:PSETID_Appointment:0x8217";
118            $properties["startdate_recurring"] = "PT_SYSTIME:PSETID_Appointment:0x8235";
119            $properties["enddate_recurring"] = "PT_SYSTIME:PSETID_Appointment:0x8236";
120            $properties["recurring_pattern"] = "PT_STRING8:PSETID_Appointment:0x8232";
121            $properties["location"] = "PT_STRING8:PSETID_Appointment:0x8208";
122            $properties["duration"] = "PT_LONG:PSETID_Appointment:0x8213";
123            $properties["responsestatus"] = "PT_LONG:PSETID_Appointment:0x8218";
124            $properties["reminder"] = "PT_BOOLEAN:PSETID_Common:0x8503";
125            $properties["reminder_minutes"] = "PT_LONG:PSETID_Common:0x8501";
126            $properties["recurrencetype"] = "PT_LONG:PSETID_Appointment:0x8231";
127            $properties["contacts"] = "PT_MV_STRING8:PSETID_Common:0x853a";
128            $properties["contacts_string"] = "PT_STRING8:PSETID_Common:0x8586";
129            $properties["categories"] = "PT_MV_STRING8:PS_PUBLIC_STRINGS:Keywords";
130            $properties["reminder_time"] = "PT_SYSTIME:PSETID_Common:0x8502";
131            $properties["commonstart"] = "PT_SYSTIME:PSETID_Common:0x8516";
132            $properties["commonend"] = "PT_SYSTIME:PSETID_Common:0x8517";
133            $properties["basedate"] = "PT_SYSTIME:PSETID_Appointment:0x8228";
134            $properties["timezone_data"] = "PT_BINARY:PSETID_Appointment:0x8233";
135            $properties["timezone"] = "PT_STRING8:PSETID_Appointment:0x8234";
136            $properties["flagdueby"] = "PT_SYSTIME:PSETID_Common:0x8560";
137            $properties["side_effects"] = "PT_LONG:PSETID_Common:0x8510";
138            $properties["hideattachments"] = "PT_BOOLEAN:PSETID_Common:0x8514";
139
140            $this->proptags = getPropIdsFromStrings($store, $properties);
141
142            parent::BaseRecurrence($store, $message);
143        }
144
145        /**
146         * Create an exception
147         * @param array $exception_props the exception properties (same properties as normal recurring items)
148         * @param date $base_date the base date of the exception (LOCAL time of non-exception occurrence)
149         * @param boolean $delete true - delete occurrence, false - create new exception or modify existing
150         * @param array $exception_recips true - delete occurrence, false - create new exception or modify existing
151         * @param mapi_message $copy_attach_from mapi message from which attachments should be copied
152         */
153        function createException($exception_props, $base_date, $delete = false, $exception_recips = array(), $copy_attach_from = false)
154        {
155            $baseday = $this->dayStartOf($base_date);
156            $basetime = $baseday + $this->recur["startocc"] * 60;
157
158            // Remove any pre-existing exception on this base date
159            if($this->isException($baseday)) {
160                $this->deleteException($baseday); // note that deleting an exception is different from creating a deleted exception (deleting an occurrence).
161            }
162
163            if(!$delete) {
164                if(isset($exception_props[$this->proptags["startdate"]]) && !$this->isValidExceptionDate($base_date, $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]))) {
165                    return false;
166                }
167                // Properties in the attachment are the properties of the base object, plus $exception_props plus the base date
168                foreach (array("subject", "location", "label", "reminder", "reminder_minutes", "alldayevent", "busystatus") as $propname) {
169                    if(isset($this->messageprops[$this->proptags[$propname]]))
170                        $props[$this->proptags[$propname]] = $this->messageprops[$this->proptags[$propname]];
171                }
172
173                $props[PR_MESSAGE_CLASS] = "IPM.OLE.CLASS.{00061055-0000-0000-C000-000000000046}";
174                unset($exception_props[PR_MESSAGE_CLASS]);
175                unset($exception_props[PR_ICON_INDEX]);
176                $props = $exception_props + $props;
177
178                // Basedate in the exception attachment is the GMT time at which the original occurrence would have been
179                $props[$this->proptags["basedate"]] = $this->toGMT($this->tz, $basetime);
180
181                if (!isset($exception_props[$this->proptags["startdate"]])) {
182                    $props[$this->proptags["startdate"]] = $this->getOccurrenceStart($base_date);
183                }
184
185                if (!isset($exception_props[$this->proptags["duedate"]])) {
186                    $props[$this->proptags["duedate"]] = $this->getOccurrenceEnd($base_date);
187                }
188
189                // synchronize commonstart/commonend with startdate/duedate
190                if(isset($props[$this->proptags["startdate"]])) {
191                    $props[$this->proptags["commonstart"]] = $props[$this->proptags["startdate"]];
192                }
193
194                if(isset($props[$this->proptags["duedate"]])) {
195                    $props[$this->proptags["commonend"]] = $props[$this->proptags["duedate"]];
196                }
197
198                // Save the data into an attachment
199                $this->createExceptionAttachment($props, $exception_recips, $copy_attach_from);
200
201                $changed_item = array();
202
203                $changed_item["basedate"] = $baseday;
204                $changed_item["start"] = $this->fromGMT($this->tz, $props[$this->proptags["startdate"]]);
205                $changed_item["end"] = $this->fromGMT($this->tz, $props[$this->proptags["duedate"]]);
206
207                if(array_key_exists($this->proptags["subject"], $exception_props)) {
208                    $changed_item["subject"] = $exception_props[$this->proptags["subject"]];
209                }
210
211                if(array_key_exists($this->proptags["location"], $exception_props)) {
212                    $changed_item["location"] = $exception_props[$this->proptags["location"]];
213                }
214
215                if(array_key_exists($this->proptags["label"], $exception_props)) {
216                    $changed_item["label"] = $exception_props[$this->proptags["label"]];
217                }
218
219                if(array_key_exists($this->proptags["reminder"], $exception_props)) {
220                    $changed_item["reminder_set"] = $exception_props[$this->proptags["reminder"]];
221                }
222
223                if(array_key_exists($this->proptags["reminder_minutes"], $exception_props)) {
224                    $changed_item["remind_before"] = $exception_props[$this->proptags["reminder_minutes"]];
225                }
226
227                if(array_key_exists($this->proptags["alldayevent"], $exception_props)) {
228                    $changed_item["alldayevent"] = $exception_props[$this->proptags["alldayevent"]];
229                }
230
231                if(array_key_exists($this->proptags["busystatus"], $exception_props)) {
232                    $changed_item["busystatus"] = $exception_props[$this->proptags["busystatus"]];
233                }
234
235                // Add the changed occurrence to the list
236                array_push($this->recur["changed_occurences"], $changed_item);
237            } else {
238                // Delete the occurrence by placing it in the deleted occurrences list
239                array_push($this->recur["deleted_occurences"], $baseday);
240            }
241
242            // Turn on hideattachments, because the attachments in this item are the exceptions
243            mapi_setprops($this->message, array ( $this->proptags["hideattachments"] => true ));
244
245            // Save recurrence data to message
246            $this->saveRecurrence();
247
248            return true;
249        }
250
251        /**
252         * Modifies an existing exception, but only updates the given properties
253         * NOTE: You can't remove properites from an exception, only add new ones
254         */
255        function modifyException($exception_props, $base_date, $exception_recips = array(), $copy_attach_from = false)
256        {
257            if(isset($exception_props[$this->proptags["startdate"]]) && !$this->isValidExceptionDate($base_date, $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]))) {
258                return false;
259            }
260
261            $baseday = $this->dayStartOf($base_date);
262            $basetime = $baseday + $this->recur["startocc"] * 60;
263            $extomodify = false;
264
265            for($i = 0, $len = count($this->recur["changed_occurences"]); $i < $len; $i++) {
266                if($this->isSameDay($this->recur["changed_occurences"][$i]["basedate"], $baseday))
267                    $extomodify = &$this->recur["changed_occurences"][$i];
268            }
269
270            if(!$extomodify)
271                return false;
272
273            // remove basedate property as we want to preserve the old value
274            // client will send basedate with time part as zero, so discard that value
275            unset($exception_props[$this->proptags["basedate"]]);
276
277            if(array_key_exists($this->proptags["startdate"], $exception_props)) {
278                $extomodify["start"] = $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]);
279            }
280
281            if(array_key_exists($this->proptags["duedate"], $exception_props)) {
282                $extomodify["end"] =   $this->fromGMT($this->tz, $exception_props[$this->proptags["duedate"]]);
283            }
284
285            if(array_key_exists($this->proptags["subject"], $exception_props)) {
286                $extomodify["subject"] = $exception_props[$this->proptags["subject"]];
287            }
288
289            if(array_key_exists($this->proptags["location"], $exception_props)) {
290                $extomodify["location"] = $exception_props[$this->proptags["location"]];
291            }
292
293            if(array_key_exists($this->proptags["label"], $exception_props)) {
294                $extomodify["label"] = $exception_props[$this->proptags["label"]];
295            }
296
297            if(array_key_exists($this->proptags["reminder"], $exception_props)) {
298                $extomodify["reminder_set"] = $exception_props[$this->proptags["reminder"]];
299            }
300
301            if(array_key_exists($this->proptags["reminder_minutes"], $exception_props)) {
302                $extomodify["remind_before"] = $exception_props[$this->proptags["reminder_minutes"]];
303            }
304
305            if(array_key_exists($this->proptags["alldayevent"], $exception_props)) {
306                $extomodify["alldayevent"] = $exception_props[$this->proptags["alldayevent"]];
307            }
308
309            if(array_key_exists($this->proptags["busystatus"], $exception_props)) {
310                $extomodify["busystatus"] = $exception_props[$this->proptags["busystatus"]];
311            }
312
313            $exception_props[PR_MESSAGE_CLASS] = "IPM.OLE.CLASS.{00061055-0000-0000-C000-000000000046}";
314
315            // synchronize commonstart/commonend with startdate/duedate
316            if(isset($exception_props[$this->proptags["startdate"]])) {
317                $exception_props[$this->proptags["commonstart"]] = $exception_props[$this->proptags["startdate"]];
318            }
319
320            if(isset($exception_props[$this->proptags["duedate"]])) {
321                $exception_props[$this->proptags["commonend"]] = $exception_props[$this->proptags["duedate"]];
322            }
323
324            $attach = $this->getExceptionAttachment($baseday);
325            if(!$attach) {
326                if ($copy_attach_from) {
327                    $this->deleteExceptionAttachment($base_date);
328                    $this->createException($exception_props, $base_date, false, $exception_recips, $copy_attach_from);
329                } else {
330                    $this->createExceptionAttachment($exception_props, $exception_recips, $copy_attach_from);
331                }
332            } else {
333                $message = mapi_attach_openobj($attach, MAPI_MODIFY);
334
335                // Set exception properties on embedded message and save
336                mapi_setprops($message, $exception_props);
337                $this->setExceptionRecipients($message, $exception_recips, false);
338                mapi_savechanges($message);
339
340                // If a new start or duedate is provided, we update the properties 'PR_EXCEPTION_STARTTIME' and 'PR_EXCEPTION_ENDTIME'
341                // on the attachment which holds the embedded msg and save everything.
342                $props = array();
343                if (isset($exception_props[$this->proptags["startdate"]])) {
344                    $props[PR_EXCEPTION_STARTTIME] = $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]);
345                }
346                if (isset($exception_props[$this->proptags["duedate"]])) {
347                    $props[PR_EXCEPTION_ENDTIME] = $this->fromGMT($this->tz, $exception_props[$this->proptags["duedate"]]);
348                }
349                if (!empty($props)) {
350                    mapi_setprops($attach, $props);
351                }
352
353                mapi_savechanges($attach);
354            }
355
356            // Save recurrence data to message
357            $this->saveRecurrence();
358
359            return true;
360        }
361
362        // Checks to see if the following is true:
363        // 1) The exception to be created doesn't create two exceptions starting on one day (however, they can END on the same day by modifying duration)
364        // 2) The exception to be created doesn't 'jump' over another occurrence (which may be an exception itself!)
365        //
366        // Both $basedate and $start are in LOCAL time
367        function isValidExceptionDate($basedate, $start)
368        {
369            // The way we do this is to look at the days that we're 'moving' the item in the exception. Each
370            // of these days may only contain the item that we're modifying. Any other item violates the rules.
371
372            if($this->isException($basedate)) {
373                // If we're modifying an exception, we want to look at the days that we're 'moving' compared to where
374                // the exception used to be.
375                $oldexception = $this->getChangeException($basedate);
376                $prevday = $this->dayStartOf($oldexception["start"]);
377            } else {
378                // If its a new exception, we want to look at the original placement of this item.
379                $prevday = $basedate;
380            }
381
382            $startday = $this->dayStartOf($start);
383
384            // Get all the occurrences on the days between the basedate (may be reversed)
385            if($prevday < $startday)
386                $items = $this->getItems($this->toGMT($this->tz, $prevday), $this->toGMT($this->tz, $startday + 24 * 60 * 60));
387            else
388                $items = $this->getItems($this->toGMT($this->tz, $startday), $this->toGMT($this->tz, $prevday + 24 * 60 * 60));
389
390            // There should now be exactly one item, namely the item that we are modifying. If there are any other items in the range,
391            // then we abort the change, since one of the rules has been violated.
392            return count($items) == 1;
393        }
394
395        /**
396         * Check to see if the exception proposed at a certain basedate is allowed concerning reminder times:
397         *
398         * Both must be true:
399         * - reminder time of this item is not before the starttime of the previous recurring item
400         * - reminder time of the next item is not before the starttime of this item
401         *
402         * @param date $basedate the base date of the exception (LOCAL time of non-exception occurrence)
403         * @param string $reminderminutes reminder minutes which is set of the item
404         * @param date $startdate the startdate of the selected item
405         * @returns boolean if the reminder minutes value valid (FALSE if either of the rules above are FALSE)
406         */
407        function isValidReminderTime($basedate, $reminderminutes, $startdate)
408        {
409            $isreminderrangeset = false;
410
411            // get all occurence items before the seleceted items occurence starttime
412            $occitems = $this->getItems($this->messageprops[$this->proptags["startdate"]], $this->toGMT($this->tz, $basedate));
413
414            if(!empty($occitems)) {
415                // as occitems array is sorted in ascending order of startdate, to get the previous occurence we take the last items in occitems .
416                $previousitem_startdate = $occitems[count($occitems) - 1][$this->proptags["startdate"]];
417
418                // if our reminder is set before or equal to the beginning of the previous occurrence, then that's not allowed
419                if($startdate - ($reminderminutes*60) <= $previousitem_startdate)
420                    return false;
421            }
422
423            // Get the endtime of the current occurrence and find the next two occurrences (including the current occurrence)
424            $currentOcc = $this->getItems($this->toGMT($this->tz, $basedate), 0x7ff00000, 2, true);
425
426            // If there are another two occurrences, then the first is the current occurrence, and the one after that
427            // is the next occurrence.
428            if(count($currentOcc) > 1) {
429                $next = $currentOcc[1];
430                // Get reminder time of the next occurrence.
431                $nextOccReminderTime = $next[$this->proptags["startdate"]] - ($next[$this->proptags["reminder_minutes"]] * 60);
432                // If the reminder time of the next item is before the start of this item, then that's not allowed
433                if($nextOccReminderTime <= $startdate)
434                    return false;
435            }
436
437            // All was ok
438            return true;
439        }
440
441        function setRecurrence($tz, $recur)
442        {
443            // only reset timezone if specified
444            if($tz)
445                $this->tz = $tz;
446
447            $this->recur = $recur;
448
449            if(!isset($this->recur["changed_occurences"]))
450                $this->recur["changed_occurences"] = Array();
451
452            if(!isset($this->recur["deleted_occurences"]))
453                $this->recur["deleted_occurences"] = Array();
454
455            $this->deleteAttachments();
456            $this->saveRecurrence();
457
458            // if client has not set the recurring_pattern then we should generate it and save it
459            $messageProps = mapi_getprops($this->message, Array($this->proptags["recurring_pattern"]));
460            if(empty($messageProps[$this->proptags["recurring_pattern"]])) {
461                $this->saveRecurrencePattern();
462            }
463        }
464
465        // Returns the start or end time of the occurrence on the given base date.
466        // This assumes that the basedate you supply is in LOCAL time
467        function getOccurrenceStart($basedate)  {
468            $daystart = $this->dayStartOf($basedate);
469            return $this->toGMT($this->tz, $daystart + $this->recur["startocc"] * 60);
470        }
471
472        function getOccurrenceEnd($basedate)  {
473            $daystart = $this->dayStartOf($basedate);
474            return $this->toGMT($this->tz, $daystart + $this->recur["endocc"] * 60);
475        }
476
477
478        // Backwards compatible code
479        function getOccurenceStart($basedate)  {
480            return $this->getOccurrenceStart($basedate);
481        }
482        function getOccurenceEnd($basedate)  {
483            return $this->getOccurrenceEnd($basedate);
484        }
485
486        /**
487        * This function returns the next remindertime starting from $timestamp
488        * When no next reminder exists, false is returned.
489        *
490        * Note: Before saving this new reminder time (when snoozing), you must check for
491        *       yourself if this reminder time is earlier than your snooze time, else
492        *       use your snooze time and not this reminder time.
493        */
494        function getNextReminderTime($timestamp)
495        {
496            /**
497             * Get next item from now until forever, but max 1 item with reminder set
498             * Note 0x7ff00000 instead of 0x7fffffff because of possible overflow failures when converting to GMT....
499             * Here for getting next 10 occurences assuming that next here we will be able to find
500             * nextreminder occurence in 10 occureneces
501             */
502            $items = $this->getItems($timestamp, 0x7ff00000, 10, true);
503
504            // Initially setting nextreminder to false so when no next reminder exists, false is returned.
505            $nextreminder = false;
506            /**
507             * Loop through all reminder which we get in items variable
508             * and check whether the remindertime is greater than timestamp.
509             * On the first occurence of greater nextreminder break the loop
510             * and return the value to calling function.
511             */
512            for($i = 0, $len = count($items); $i < $len; $i++)
513            {
514                $item = $items[$i];
515                $tempnextreminder = $item[$this->proptags["startdate"]] - ( $item[$this->proptags["reminder_minutes"]] * 60 );
516
517                // If tempnextreminder is greater than timestamp then save it in nextreminder and break from the loop.
518                if($tempnextreminder > $timestamp)
519                {
520                    $nextreminder = $tempnextreminder;
521                    break;
522                }
523            }
524            return $nextreminder;
525        }
526
527        /**
528         * Note: Static function, more like a utility function.
529         *
530         * Gets all the items (including recurring items) in the specified calendar in the given timeframe. Items are
531         * included as a whole if they overlap the interval <$start, $end> (non-inclusive). This means that if the interval
532         * is <08:00 - 14:00>, the item [6:00 - 8:00> is NOT included, nor is the item [14:00 - 16:00>. However, the item
533         * [7:00 - 9:00> is included as a whole, and is NOT capped to [8:00 - 9:00>.
534         *
535         * @param $store resource The store in which the calendar resides
536         * @param $calendar resource The calendar to get the items from
537         * @param $viewstart int Timestamp of beginning of view window
538         * @param $viewend int Timestamp of end of view window
539         * @param $propsrequested array Array of properties to return
540         * @param $rows array Array of rowdata as if they were returned directly from mapi_table_queryrows. Each recurring item is
541         *                    expanded so that it seems that there are only many single appointments in the table.
542         */
543        static function getCalendarItems($store, $calendar, $viewstart, $viewend, $propsrequested)
544        {
545            return getCalendarItems($store, $calendar, $viewstart, $viewend, $propsrequested);
546        }
547
548
549        /*****************************************************************************************************************
550         * CODE BELOW THIS LINE IS FOR INTERNAL USE ONLY
551         *****************************************************************************************************************
552         */
553
554        /**
555         * Generates and stores recurrence pattern string to recurring_pattern property.
556         */
557        function saveRecurrencePattern()
558        {
559            // Start formatting the properties in such a way we can apply
560            // them directly into the recurrence pattern.
561            $type = $this->recur['type'];
562            $everyn = $this->recur['everyn'];
563            $start = $this->recur['start'];
564            $end = $this->recur['end'];
565            $term = $this->recur['term'];
566            $numocc = isset($this->recur['numoccur']) ? $this->recur['numoccur'] : false;
567            $startocc = $this->recur['startocc'];
568            $endocc = $this->recur['endocc'];
569            $pattern = '';
570            $occSingleDayRank = false;
571            $occTimeRange = ($startocc != 0 && $endocc != 0);
572
573            switch ($type) {
574                // Daily
575                case 0x0A:
576                    if ($everyn == 1) {
577                        $type = _('workday');
578                        $occSingleDayRank = true;
579                    } else if ($everyn == (24 * 60)) {
580                        $type = _('day');
581                        $occSingleDayRank = true;
582                    } else {
583                        $everyn /= (24 * 60);
584                        $type = _('days');
585                        $occSingleDayRank = false;
586                    }
587                    break;
588                // Weekly
589                case 0x0B:
590                    if ($everyn == 1) {
591                        $type = _('week');
592                        $occSingleDayRank = true;
593                    } else {
594                        $type = _('weeks');
595                        $occSingleDayRank = false;
596                    }
597                    break;
598                // Monthly
599                case 0x0C:
600                    if ($everyn == 1) {
601                        $type = _('month');
602                        $occSingleDayRank = true;
603                    } else {
604                        $type = _('months');
605                        $occSingleDayRank = false;
606                    }
607                    break;
608                // Yearly
609                case 0x0D:
610                    if ($everyn <= 12) {
611                        $everyn = 1;
612                        $type = _('year');
613                        $occSingleDayRank = true;
614                    } else {
615                        $everyn = $everyn / 12;
616                        $type = _('years');
617                        $occSingleDayRank = false;
618                    }
619                    break;
620            }
621
622            // get timings of the first occurence
623            $firstoccstartdate = isset($startocc) ? $start + (((int) $startocc) * 60) : $start;
624            $firstoccenddate = isset($endocc) ? $end + (((int) $endocc) * 60) : $end;
625
626            $start = gmdate(_('d-m-Y'), $firstoccstartdate);
627            $end = gmdate(_('d-m-Y'), $firstoccenddate);
628            $startocc = gmdate(_('G:i'), $firstoccstartdate);
629            $endocc = gmdate(_('G:i'), $firstoccenddate);
630
631            // Based on the properties, we need to generate the recurrence pattern string.
632            // This is obviously very easy since we can simply concatenate a bunch of strings,
633            // however this messes up translations for languages which order their words
634            // differently.
635            // To improve translation quality we create a series of default strings, in which
636            // we only have to fill in the correct variables. The base string is thus selected
637            // based on the available properties.
638            if ($term == 0x23) {
639                // Never ends
640                if ($occTimeRange) {
641                    if ($occSingleDayRank) {
642                        $pattern = sprintf(_('Occurs every %s effective %s from %s to %s.'), $type, $start, $startocc, $endocc);
643                    } else {
644                        $pattern = sprintf(_('Occurs every %s %s effective %s from %s to %s.'), $everyn, $type, $start, $startocc, $endocc);
645                    }
646                } else {
647                    if ($occSingleDayRank) {
648                        $pattern = sprintf(_('Occurs every %s effective %s.'), $type, $start);
649                    } else {
650                        $pattern = sprintf(_('Occurs every %s %s effective %s.'), $everyn, $type, $start);
651                    }
652                }
653            } else if ($term == 0x22) {
654                // After a number of times
655                if ($occTimeRange) {
656                    if ($occSingleDayRank) {
657                        $pattern = sprintf(ngettext('Occurs every %s effective %s for %s occurence from %s to %s.',
658                                                'Occurs every %s effective %s for %s occurences from %s to %s.', $numocc), $type, $start, $numocc, $startocc, $endocc);
659                    } else {
660                        $pattern = sprintf(ngettext('Occurs every %s %s effective %s for %s occurence from %s to %s.',
661                                                'Occurs every %s %s effective %s for %s occurences %s to %s.', $numocc), $everyn, $type, $start, $numocc, $startocc, $endocc);
662                    }
663                } else {
664                    if ($occSingleDayRank) {
665                        $pattern = sprintf(ngettext('Occurs every %s effective %s for %s occurence.',
666                                                     'Occurs every %s effective %s for %s occurences.', $numocc), $type, $start, $numocc);
667                    } else {
668                        $pattern = sprintf(ngettext('Occurs every %s %s effective %s for %s occurence.',
669                                                         'Occurs every %s %s effective %s for %s occurences.', $numocc), $everyn, $type, $start, $numocc);
670                    }
671                }
672            } else if ($term == 0x21) {
673                // After the given enddate
674                if ($occTimeRange) {
675                    if ($occSingleDayRank) {
676                        $pattern = sprintf(_('Occurs every %s effective %s until %s from %s to %s.'), $type, $start, $end, $startocc, $endocc);
677                    } else {
678                        $pattern = sprintf(_('Occurs every %s %s effective %s until %s from %s to %s.'), $everyn, $type, $start, $end, $startocc, $endocc);
679                    }
680                } else {
681                    if ($occSingleDayRank) {
682                        $pattern = sprintf(_('Occurs every %s effective %s until %s.'), $type, $start, $end);
683                    } else {
684                        $pattern = sprintf(_('Occurs every %s %s effective %s until %s.'), $everyn, $type, $start, $end);
685                    }
686                }
687            }
688
689            if(!empty($pattern)) {
690                mapi_setprops($this->message, Array($this->proptags["recurring_pattern"] => $pattern ));
691            }
692        }
693
694        /*
695         * Remove an exception by base_date. This is the base date in local daystart time
696         */
697        function deleteException($base_date)
698        {
699            // Remove all exceptions on $base_date from the deleted and changed occurrences lists
700
701            // Remove all items in $todelete from deleted_occurences
702            $new = Array();
703
704            foreach($this->recur["deleted_occurences"] as $entry) {
705                if($entry != $base_date)
706                    $new[] = $entry;
707            }
708            $this->recur["deleted_occurences"] = $new;
709
710            $new = Array();
711
712            foreach($this->recur["changed_occurences"] as $entry) {
713                if(!$this->isSameDay($entry["basedate"], $base_date))
714                    $new[] = $entry;
715                else
716                    $this->deleteExceptionAttachment($this->toGMT($this->tz, $base_date + $this->recur["startocc"] * 60));
717            }
718
719            $this->recur["changed_occurences"] = $new;
720        }
721
722        /**
723         * Function which saves the exception data in an attachment.
724         * @param array $exception_props the exception data (like any other MAPI appointment)
725         * @param array $exception_recips list of recipients
726         * @param mapi_message $copy_attach_from mapi message from which attachments should be copied
727         * @return array properties of the exception
728         */
729        function createExceptionAttachment($exception_props, $exception_recips = array(), $copy_attach_from = false)
730        {
731              // Create new attachment.
732              $attachment = mapi_message_createattach($this->message);
733              $props = array();
734              $props[PR_ATTACHMENT_FLAGS] = 2;
735              $props[PR_ATTACHMENT_HIDDEN] = true;
736              $props[PR_ATTACHMENT_LINKID] = 0;
737              $props[PR_ATTACH_FLAGS] = 0;
738              $props[PR_ATTACH_METHOD] = 5;
739              $props[PR_DISPLAY_NAME] = "Exception";
740              $props[PR_EXCEPTION_STARTTIME] = $this->fromGMT($this->tz, $exception_props[$this->proptags["startdate"]]);
741              $props[PR_EXCEPTION_ENDTIME] = $this->fromGMT($this->tz, $exception_props[$this->proptags["duedate"]]);
742              mapi_message_setprops($attachment, $props);
743
744            $imessage = mapi_attach_openobj($attachment, MAPI_CREATE | MAPI_MODIFY);
745
746            if ($copy_attach_from) {
747                $attachmentTable = mapi_message_getattachmenttable($copy_attach_from);
748                if($attachmentTable) {
749                    $attachments = mapi_table_queryallrows($attachmentTable, array(PR_ATTACH_NUM, PR_ATTACH_SIZE, PR_ATTACH_LONG_FILENAME, PR_ATTACHMENT_HIDDEN, PR_DISPLAY_NAME, PR_ATTACH_METHOD));
750
751                    foreach($attachments as $attach_props){
752                        $attach_old = mapi_message_openattach($copy_attach_from, (int) $attach_props[PR_ATTACH_NUM]);
753                        $attach_newResourceMsg = mapi_message_createattach($imessage);
754                        mapi_copyto($attach_old, array(), array(), $attach_newResourceMsg, 0);
755                        mapi_savechanges($attach_newResourceMsg);
756                    }
757                }
758            }
759
760            $props = $props + $exception_props;
761
762            // FIXME: the following piece of code is written to fix the creation
763            // of an exception. This is only a quickfix as it is not yet possible
764            // to change an existing exception.
765            // remove mv properties when needed
766            foreach($props as $propTag=>$propVal){
767                if ((mapi_prop_type($propTag) & MV_FLAG) == MV_FLAG && is_null($propVal)){
768                    unset($props[$propTag]);
769                }
770            }
771
772            mapi_message_setprops($imessage, $props);
773
774            $this->setExceptionRecipients($imessage, $exception_recips, true);
775
776            mapi_message_savechanges($imessage);
777            mapi_message_savechanges($attachment);
778        }
779
780        /**
781         * Function which deletes the attachment of an exception.
782         * @param date $base_date base date of the attachment. Should be in GMT. The attachment
783         *                        actually saves the real time of the original date, so we have
784         *                          to check whether it's on the same day.
785         */
786        function deleteExceptionAttachment($base_date)
787        {
788            $attachments = mapi_message_getattachmenttable($this->message);
789            $attachTable = mapi_table_queryallrows($attachments, Array(PR_ATTACH_NUM));
790
791            foreach($attachTable as $attachRow)
792            {
793                $tempattach = mapi_message_openattach($this->message, $attachRow[PR_ATTACH_NUM]);
794                $exception = mapi_attach_openobj($tempattach);
795
796                  $data = mapi_message_getprops($exception, array($this->proptags["basedate"]));
797
798                  if($this->dayStartOf($this->fromGMT($this->tz, $data[$this->proptags["basedate"]])) == $this->dayStartOf($base_date)) {
799                      mapi_message_deleteattach($this->message, $attachRow[PR_ATTACH_NUM]);
800                  }
801            }
802        }
803
804        /**
805         * Function which deletes all attachments of a message.
806         */
807        function deleteAttachments()
808        {
809            $attachments = mapi_message_getattachmenttable($this->message);
810            $attachTable = mapi_table_queryallrows($attachments, Array(PR_ATTACH_NUM, PR_ATTACHMENT_HIDDEN));
811
812            foreach($attachTable as $attachRow)
813            {
814                if(isset($attachRow[PR_ATTACHMENT_HIDDEN]) && $attachRow[PR_ATTACHMENT_HIDDEN]) {
815                    mapi_message_deleteattach($this->message, $attachRow[PR_ATTACH_NUM]);
816                }
817            }
818        }
819
820        /**
821         * Get an exception attachment based on its basedate
822         */
823        function getExceptionAttachment($base_date)
824        {
825            // Retrieve only embedded messages
826            $attach_res = Array(RES_AND,
827                            Array(
828                                Array(RES_PROPERTY,
829                                    Array(RELOP => RELOP_EQ,
830                                        ULPROPTAG => PR_ATTACH_METHOD,
831                                        VALUE => array(PR_ATTACH_METHOD => 5)
832                                    )
833                                )
834                            )
835            );
836            $attachments = mapi_message_getattachmenttable($this->message);
837            $attachRows = mapi_table_queryallrows($attachments, Array(PR_ATTACH_NUM), $attach_res);
838
839            if(is_array($attachRows)) {
840                foreach($attachRows as $attachRow)
841                {
842                    $tempattach = mapi_message_openattach($this->message, $attachRow[PR_ATTACH_NUM]);
843                    $exception = mapi_attach_openobj($tempattach);
844
845                    $data = mapi_message_getprops($exception, array($this->proptags["basedate"]));
846
847                    if($this->isSameDay($this->fromGMT($this->tz,$data[$this->proptags["basedate"]]), $base_date)) {
848                        return $tempattach;
849                    }
850                }
851            }
852
853            return false;
854        }
855
856        /**
857         * processOccurrenceItem, adds an item to a list of occurrences, but only if the following criteria are met:
858         * - The resulting occurrence (or exception) starts or ends in the interval <$start, $end>
859         * - The ocurrence isn't specified as a deleted occurrence
860         * @param array $items reference to the array to be added to
861         * @param date $start start of timeframe in GMT TIME
862         * @param date $end end of timeframe in GMT TIME
863         * @param date $basedate (hour/sec/min assumed to be 00:00:00) in LOCAL TIME OF THE OCCURRENCE
864         * @param int $startocc start of occurrence since beginning of day in minutes
865         * @param int $endocc end of occurrence since beginning of day in minutes
866         * @param int $tz the timezone info for this occurrence ( applied to $basedate / $startocc / $endocc )
867         * @param bool $reminderonly If TRUE, only add the item if the reminder is set
868         */
869        function processOccurrenceItem(&$items, $start, $end, $basedate, $startocc, $endocc, $tz, $reminderonly)
870        {
871            $exception = $this->isException($basedate);
872            if($exception){
873                return false;
874            }else{
875                $occstart = $basedate + $startocc * 60;
876                $occend = $basedate + $endocc * 60;
877
878                // Convert to GMT
879                $occstart = $this->toGMT($tz, $occstart);
880                $occend = $this->toGMT($tz, $occend);
881
882                /**
883                 * FIRST PART : Check range criterium. Exact matches (eg when $occstart == $end), do NOT match since you cannot
884                 * see any part of the appointment. Partial overlaps DO match.
885                 *
886                 * SECOND PART : check if occurence is not a zero duration occurrence which
887                 * starts at 00:00 and ends on 00:00. if it is so, then process
888                 * the occurrence and send it in response.
889                 */
890                if(($occstart  >= $end || $occend <=  $start) && !($occstart == $occend && $occstart == $start))
891                    return;
892
893                // Properties for this occurrence are the same as the main object,
894                // With these properties overridden
895                $newitem = $this->messageprops;
896                $newitem[$this->proptags["startdate"]] = $occstart;
897                $newitem[$this->proptags["duedate"]] = $occend;
898                $newitem[$this->proptags["commonstart"]] = $occstart;
899                $newitem[$this->proptags["commonend"]] = $occend;
900                $newitem["basedate"] = $basedate;
901            }
902
903            // If reminderonly is set, only add reminders
904            if($reminderonly && (!isset($newitem[$this->proptags["reminder"]]) || $newitem[$this->proptags["reminder"]] == false))
905                return;
906
907            $items[] = $newitem;
908        }
909
910        /**
911         * processExceptionItem, adds an all exception item to a list of occurrences, without any constraint on timeframe
912         * @param array $items reference to the array to be added to
913         * @param date $start start of timeframe in GMT TIME
914         * @param date $end end of timeframe in GMT TIME
915         */
916        function processExceptionItems(&$items, $start, $end)
917        {
918            $limit = 0;
919            foreach($this->recur["changed_occurences"] as $exception) {
920
921                // Convert to GMT
922                $occstart = $this->toGMT($this->tz, $exception["start"]);
923                $occend = $this->toGMT($this->tz, $exception["end"]);
924
925                // Check range criterium. Exact matches (eg when $occstart == $end), do NOT match since you cannot
926                // see any part of the appointment. Partial overlaps DO match.
927                if($occstart >= $end || $occend <= $start)
928                    continue;
929
930                array_push($items, $this->getExceptionProperties($exception));
931                if($limit && (count($items) == $limit))
932                    break;
933                }
934        }
935
936        /**
937         * Function which verifies if on the given date an exception, delete or change, occurs.
938         * @param date $date the date
939         * @return array the exception, true - if an occurrence is deleted on the given date, false - no exception occurs on the given date
940         */
941        function isException($basedate)
942        {
943            if($this->isDeleteException($basedate))
944                return true;
945
946            if($this->getChangeException($basedate) != false)
947                return true;
948
949            return false;
950        }
951
952        /**
953         * Returns TRUE if there is a DELETE exception on the given base date
954         */
955        function isDeleteException($basedate)
956        {
957            // Check if the occurrence is deleted on the specified date
958            foreach($this->recur["deleted_occurences"] as $deleted)
959            {
960                if($this->isSameDay($deleted, $basedate))
961                    return true;
962            }
963
964            return false;
965        }
966
967        /**
968         * Returns the exception if there is a CHANGE exception on the given base date, or FALSE otherwise
969         */
970        function getChangeException($basedate)
971        {
972            // Check if the occurrence is modified on the specified date
973            foreach($this->recur["changed_occurences"] as $changed)
974            {
975                if($this->isSameDay($changed["basedate"], $basedate))
976                    return $changed;
977            }
978
979            return false;
980        }
981
982        /**
983         * Function to see if two dates are on the same day
984         * @param date $time1 date 1
985         * @param date $time2 date 2
986         * @return boolean Returns TRUE when both dates are on the same day
987         */
988        function isSameDay($date1, $date2)
989        {
990            $time1 = $this->gmtime($date1);
991            $time2 = $this->gmtime($date2);
992
993            return $time1["tm_mon"] == $time2["tm_mon"] && $time1["tm_year"] == $time2["tm_year"] && $time1["tm_mday"] == $time2["tm_mday"];
994        }
995
996        /**
997         * Function to get all properties of a single changed exception.
998         * @param date $date base date of exception
999         * @return array associative array of properties for the exception, compatible with
1000         */
1001        function getExceptionProperties($exception)
1002        {
1003            // Exception has same properties as main object, with some properties overridden:
1004            $item = $this->messageprops;
1005
1006            // Special properties
1007            $item["exception"] = true;
1008            $item["basedate"] = $exception["basedate"]; // note that the basedate is always in local time !
1009
1010            // MAPI-compatible properties (you can handle an exception as a normal calendar item like this)
1011            $item[$this->proptags["startdate"]] = $this->toGMT($this->tz, $exception["start"]);
1012            $item[$this->proptags["duedate"]] = $this->toGMT($this->tz, $exception["end"]);
1013            $item[$this->proptags["commonstart"]] = $item[$this->proptags["startdate"]];
1014            $item[$this->proptags["commonend"]] = $item[$this->proptags["duedate"]];
1015
1016            if(isset($exception["subject"])) {
1017                $item[$this->proptags["subject"]] = $exception["subject"];
1018            }
1019
1020            if(isset($exception["label"])) {
1021                $item[$this->proptags["label"]] = $exception["label"];
1022            }
1023
1024            if(isset($exception["alldayevent"])) {
1025                $item[$this->proptags["alldayevent"]] = $exception["alldayevent"];
1026            }
1027
1028            if(isset($exception["location"])) {
1029                $item[$this->proptags["location"]] = $exception["location"];
1030            }
1031
1032            if(isset($exception["remind_before"])) {
1033                $item[$this->proptags["reminder_minutes"]] = $exception["remind_before"];
1034            }
1035
1036            if(isset($exception["reminder_set"])) {
1037                $item[$this->proptags["reminder"]] = $exception["reminder_set"];
1038            }
1039
1040            if(isset($exception["busystatus"])) {
1041                $item[$this->proptags["busystatus"]] = $exception["busystatus"];
1042            }
1043
1044            return $item;
1045        }
1046
1047        /**
1048         * Function which sets recipients for an exception.
1049         *
1050         * The $exception_recips can be provided in 2 ways:
1051         *  - A delta which indicates which recipients must be added, removed or deleted.
1052         *  - A complete array of the recipients which should be applied to the message.
1053         *
1054         * The first option is preferred as it will require less work to be executed.
1055         *
1056         * @param resource $message exception attachment of recurring item
1057         * @param array $exception_recips list of recipients
1058         * @param boolean $copy_orig_recips True to copy all recipients which are on the original
1059         * message to the attachment by default. False if only the $exception_recips changes should
1060         * be applied.
1061         */
1062        function setExceptionRecipients($message, $exception_recips, $copy_orig_recips = true)
1063        {
1064            if (isset($exception_recips['add']) || isset($exception_recips['remove']) || isset($exception_recips['modify'])) {
1065                $this->setDeltaExceptionRecipients($message, $exception_recips, $copy_orig_recips);
1066            } else {
1067                $this->setAllExceptionRecipients($message, $exception_recips);
1068            }
1069        }
1070
1071        /**
1072         * Function which applies the provided delta for recipients changes to the exception.
1073         *
1074         * The $exception_recips should be an array containing the following keys:
1075         *  - "add": this contains an array of recipients which must be added
1076         *  - "remove": This contains an array of recipients which must be removed
1077         *  - "modify": This contains an array of recipients which must be modified
1078         *
1079         * @param resource $message exception attachment of recurring item
1080         * @param array $exception_recips list of recipients
1081         * @param boolean $copy_orig_recips True to copy all recipients which are on the original
1082         * message to the attachment by default. False if only the $exception_recips changes should
1083         * be applied.
1084         */
1085        function setDeltaExceptionRecipients($exception, $exception_recips, $copy_orig_recips)
1086        {
1087            // Check if the recipients from the original message should be copied,
1088            // if so, open the recipient table of the parent message and apply all
1089            // rows on the target recipient.
1090            if ($copy_orig_recips === true) {
1091                $origTable = mapi_message_getrecipienttable($this->message);
1092                $recipientRows = mapi_table_queryallrows($origTable, $this->recipprops);
1093                mapi_message_modifyrecipients($exception, MODRECIP_ADD, $recipientRows);
1094            }
1095
1096            // Add organizer to meeting only if it is not organized.
1097            $msgprops = mapi_getprops($exception, array(PR_SENT_REPRESENTING_ENTRYID, PR_SENT_REPRESENTING_EMAIL_ADDRESS, PR_SENT_REPRESENTING_NAME, PR_SENT_REPRESENTING_ADDRTYPE, $this->proptags['responsestatus']));
1098            if (isset($msgprops[$this->proptags['responsestatus']]) && $msgprops[$this->proptags['responsestatus']] != olResponseOrganized){
1099                $this->addOrganizer($msgprops, $exception_recips['add']);
1100            }
1101
1102            // Remove all deleted recipients
1103            if (isset($exception_recips['remove'])) {
1104                foreach ($exception_recips['remove'] as &$recip) {
1105                    if (!isset($recipient[PR_RECIPIENT_FLAGS]) || $recip[PR_RECIPIENT_FLAGS] != (recipReserved | recipExceptionalDeleted | recipSendable)) {
1106                        $recip[PR_RECIPIENT_FLAGS] = recipSendable | recipExceptionalDeleted;
1107                    } else {
1108                        $recip[PR_RECIPIENT_FLAGS] = recipReserved | recipExceptionalDeleted | recipSendable;
1109                    }
1110                    $recip[PR_RECIPIENT_TRACKSTATUS] = olResponseNone;        // No Response required
1111                }
1112                unset($recip);
1113                mapi_message_modifyrecipients($exception, MODRECIP_MODIFY, $exception_recips['remove']);
1114            }
1115
1116            // Add all new recipients
1117            if (isset($exception_recips['add'])) {
1118                mapi_message_modifyrecipients($exception, MODRECIP_ADD, $exception_recips['add']);
1119            }
1120
1121            // Modify the existing recipients
1122            if (isset($exception_recips['modify'])) {
1123                mapi_message_modifyrecipients($exception, MODRECIP_MODIFY, $exception_recips['modify']);
1124            }
1125        }
1126
1127        /**
1128         * Function which applies the provided recipients to the exception, also checks for deleted recipients.
1129         *
1130         * The $exception_recips should be an array containing all recipients which must be applied
1131         * to the exception. This will copy all recipients from the original message and then start filter
1132         * out all recipients which are not provided by the $exception_recips list.
1133         *
1134         * @param resource $message exception attachment of recurring item
1135         * @param array $exception_recips list of recipients
1136         */
1137        function setAllExceptionRecipients($message, $exception_recips)
1138        {
1139            $deletedRecipients = array();
1140            $useMessageRecipients = false;
1141
1142            $recipientTable = mapi_message_getrecipienttable($message);
1143            $recipientRows = mapi_table_queryallrows($recipientTable, $this->recipprops);
1144
1145            if (empty($recipientRows)) {
1146                $useMessageRecipients = true;
1147                $recipientTable = mapi_message_getrecipienttable($this->message);
1148                $recipientRows = mapi_table_queryallrows($recipientTable, $this->recipprops);
1149            }
1150
1151            // Add organizer to meeting only if it is not organized.
1152            $msgprops = mapi_getprops($message, array(PR_SENT_REPRESENTING_ENTRYID, PR_SENT_REPRESENTING_EMAIL_ADDRESS, PR_SENT_REPRESENTING_NAME, PR_SENT_REPRESENTING_ADDRTYPE, $this->proptags['responsestatus']));
1153            if (isset($msgprops[$this->proptags['responsestatus']]) && $msgprops[$this->proptags['responsestatus']] != olResponseOrganized){
1154                $this->addOrganizer($msgprops, $exception_recips);
1155            }
1156
1157            if (!empty($exception_recips)) {
1158                foreach($recipientRows as $key => $recipient) {
1159                    $found = false;
1160                    foreach($exception_recips as $excep_recip) {
1161                        if (isset($recipient[PR_SEARCH_KEY]) && isset($excep_recip[PR_SEARCH_KEY]) && $recipient[PR_SEARCH_KEY] == $excep_recip[PR_SEARCH_KEY])
1162                            $found = true;
1163                    }
1164
1165                    if (!$found) {
1166                       $foundInDeletedRecipients = false;
1167                       // Look if the $recipient is in the list of deleted recipients
1168                       if (!empty($deletedRecipients)) {
1169                               foreach($deletedRecipients as $recip) {
1170                                   if ($recip[PR_SEARCH_KEY] == $recipient[PR_SEARCH_KEY]){
1171                                       $foundInDeletedRecipients = true;
1172                                       break;
1173                                   }
1174                               }
1175                       }
1176
1177                       // If recipient is not in list of deleted recipient, add him
1178                       if (!$foundInDeletedRecipients) {
1179                            if (!isset($recipient[PR_RECIPIENT_FLAGS]) || $recipient[PR_RECIPIENT_FLAGS] != (recipReserved | recipExceptionalDeleted | recipSendable)) {
1180                                $recipient[PR_RECIPIENT_FLAGS] = recipSendable | recipExceptionalDeleted;
1181                            } else {
1182                                $recipient[PR_RECIPIENT_FLAGS] = recipReserved | recipExceptionalDeleted | recipSendable;
1183                            }
1184                            $recipient[PR_RECIPIENT_TRACKSTATUS] = olRecipientTrackStatusNone;    // No Response required
1185                            $deletedRecipients[] = $recipient;
1186                        }
1187                    }
1188
1189                    // When $message contains a non-empty recipienttable, we must delete the recipients
1190                    // before re-adding them. However, when $message is doesn't contain any recipients,
1191                    // we are using the recipient table of the original message ($this->message)
1192                    // rather then $message. In that case, we don't need to remove the recipients
1193                    // from the $message, as the recipient table is already empty, and
1194                    // mapi_message_modifyrecipients() will throw an error.
1195                    if ($useMessageRecipients === false) {
1196                        mapi_message_modifyrecipients($message, MODRECIP_REMOVE, array($recipient));
1197                    }
1198                }
1199                $exception_recips = array_merge($exception_recips, $deletedRecipients);
1200            } else {
1201                $exception_recips = $recipientRows;
1202            }
1203
1204            if (!empty($exception_recips)) {
1205                // Set the new list of recipients on the exception message, this also removes the existing recipients
1206                mapi_message_modifyrecipients($message, 0, $exception_recips);
1207            }
1208        }
1209
1210        /**
1211         * Function returns basedates of all changed occurrences
1212         *@return array array(
1213                            0 => 123459321
1214                        )
1215         */
1216        function getAllExceptions()
1217        {
1218            $result = false;
1219            if (!empty($this->recur["changed_occurences"])) {
1220                $result = array();
1221                foreach($this->recur["changed_occurences"] as $exception) {
1222                    $result[] = $exception["basedate"];
1223                }
1224                return $result;
1225            }
1226            return $result;
1227        }
1228
1229        /**
1230         *  Function which adds organizer to recipient list which is passed.
1231         *  This function also checks if it has organizer.
1232         *
1233         * @param array $messageProps message properties
1234         * @param array $recipients    recipients list of message.
1235         * @param boolean $isException true if we are processing recipient of exception
1236         */
1237        function addOrganizer($messageProps, &$recipients, $isException = false){
1238
1239            $hasOrganizer = false;
1240            // Check if meeting already has an organizer.
1241            foreach ($recipients as $key => $recipient){
1242                if (isset($recipient[PR_RECIPIENT_FLAGS]) && $recipient[PR_RECIPIENT_FLAGS] == (recipSendable | recipOrganizer)) {
1243                    $hasOrganizer = true;
1244                } else if ($isException && !isset($recipient[PR_RECIPIENT_FLAGS])){
1245                    // Recipients for an occurrence
1246                    $recipients[$key][PR_RECIPIENT_FLAGS] = recipSendable | recipExceptionalResponse;
1247                }
1248            }
1249
1250            if (!$hasOrganizer){
1251                // Create organizer.
1252                $organizer = array();
1253                $organizer[PR_ENTRYID] = $messageProps[PR_SENT_REPRESENTING_ENTRYID];
1254                $organizer[PR_DISPLAY_NAME] = $messageProps[PR_SENT_REPRESENTING_NAME];
1255                $organizer[PR_EMAIL_ADDRESS] = $messageProps[PR_SENT_REPRESENTING_EMAIL_ADDRESS];
1256                $organizer[PR_RECIPIENT_TYPE] = MAPI_TO;
1257                $organizer[PR_RECIPIENT_DISPLAY_NAME] = $messageProps[PR_SENT_REPRESENTING_NAME];
1258                $organizer[PR_ADDRTYPE] = empty($messageProps[PR_SENT_REPRESENTING_ADDRTYPE])?'SMTP':$messageProps[PR_SENT_REPRESENTING_ADDRTYPE];
1259                $organizer[PR_RECIPIENT_TRACKSTATUS] = olRecipientTrackStatusNone;
1260                $organizer[PR_RECIPIENT_FLAGS] = recipSendable | recipOrganizer;
1261
1262                // Add organizer to recipients list.
1263                array_unshift($recipients, $organizer);
1264            }
1265        }
1266    }
1267
1268    /*
1269
1270    From http://www.ohelp-one.com/new-6765483-3268.html:
1271
1272    Recurrence Data Structure Offset Type Value
1273
1274    0 ULONG (?) Constant : { 0x04, 0x30, 0x04, 0x30}
1275
1276    4 UCHAR 0x0A + recurrence type: 0x0A for daily, 0x0B for weekly, 0x0C for
1277    monthly, 0x0D for yearly
1278
1279    5 UCHAR Constant: { 0x20}
1280
1281    6 ULONG Seems to be a variant of the recurrence type: 1 for daily every n
1282    days, 2 for daily every weekday and weekly, 3 for monthly or yearly. The
1283    special exception is regenerating tasks that regenerate on a weekly basis: 0
1284    is used in that case (I have no idea why).
1285
1286    Here's the recurrence-type-specific data. Because the daily every N days
1287    data are 4 bytes shorter than the data for the other types, the offsets for
1288    the rest of the data will be 4 bytes off depending on the recurrence type.
1289
1290    Daily every N days:
1291
1292    10 ULONG ( N - 1) * ( 24 * 60). I'm not sure what this is used for, but it's consistent.
1293
1294    14 ULONG N * 24 * 60: minutes between recurrences
1295
1296    18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
1297    regenerating tasks.
1298
1299    Daily every weekday (this is essentially a subtype of weekly recurrence):
1300
1301    10 ULONG 6 * 24 * 60: minutes between recurrences ( a week... sort of)
1302
1303    14 ULONG 1: recur every week (corresponds to the second parameter for weekly
1304    recurrence)
1305
1306    18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
1307    regenerating tasks.
1308
1309    22 ULONG 0x3E: bitmask for recurring every weekday (corresponds to fourth
1310    parameter for weekly recurrence)
1311
1312    Weekly every N weeks for all events and non-regenerating tasks:
1313
1314    10 ULONG 6 * 24 * 60: minutes between recurrences (a week... sort of)
1315
1316    14 ULONG N: recurrence interval
1317
1318    18 ULONG Constant: 0
1319
1320    22 ULONG Bitmask for determining which days of the week the event recurs on
1321    ( 1 << dayOfWeek, where Sunday is 0).
1322
1323    Weekly every N weeks for regenerating tasks: 10 ULONG Constant: 0
1324
1325    14 ULONG N * 7 * 24 * 60: recurrence interval in minutes between occurrences
1326
1327    18 ULONG Constant: 1
1328
1329    Monthly every N months on day D:
1330
1331    10 ULONG This is the most complicated value
1332    in the entire mess. It's basically a very complicated way of stating the
1333    recurrence interval. I tweaked fbs' basic algorithm. DateTime::MonthInDays
1334    simply returns the number of days in a given month, e.g. 31 for July for 28
1335    for February (the algorithm doesn't take into account leap years, but it
1336    doesn't seem to matter). My DateTime object, like Microsoft's COleDateTime,
1337    uses 1-based months (i.e. January is 1, not 0). With that in mind, this
1338    works:
1339
1340    long monthIndex = ( ( ( ( 12 % schedule-=GetInterval()) *
1341
1342    ( ( schedule-=GetStartDate().GetYear() - 1601) %
1343
1344    schedule-=GetInterval())) % schedule-=GetInterval()) +
1345
1346    ( schedule-=GetStartDate().GetMonth() - 1)) % schedule-=GetInterval();
1347
1348    for( int i = 0; i < monthIndex; i++)
1349
1350    {
1351
1352    value += DateTime::GetDaysInMonth( ( i % 12) + 1) * 24 * 60;
1353
1354    }
1355
1356    This should work for any recurrence interval, including those greater than
1357    12.
1358
1359    14 ULONG N: recurrence interval
1360
1361    18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
1362    regenerating tasks.
1363
1364    22 ULONG D: day of month the event recurs on (if this value is greater than
1365    the number of days in a given month [e.g. 31 for and recurs in June], then
1366    the event will recur on the last day of the month)
1367
1368    Monthly every N months on the Xth Y (e.g. "2nd Tuesday"):
1369
1370    10 ULONG See above: same as for monthly every N months on day D
1371
1372    14 ULONG N: recurrence interval
1373
1374    18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
1375    regenerating tasks.
1376
1377    22 ULONG Y: bitmask for determining which day of the week the event recurs
1378    on (see weekly every N weeks). Some useful values are 0x7F for any day, 0x3E
1379    for a weekday, or 0x41 for a weekend day.
1380
1381    26 ULONG X: 1 for first occurrence, 2 for second, etc. 5 for last
1382    occurrence. E.g. for "2nd Tuesday", you should have values of 0x04 for the
1383    prior value and 2 for this one.
1384
1385    Yearly on day D of month M:
1386
1387    10 ULONG M (sort of): This is another messy
1388    value. It's the number of minute since the startning of the year to the
1389    given month. For an explanation of GetDaysInMonth, see monthly every N
1390    months. This will work:
1391
1392    ULONG monthOfYearInMinutes = 0;
1393
1394    for( int i = DateTime::cJanuary; i < schedule-=GetMonth(); i++)
1395
1396    {
1397
1398    monthOfYearInMinutes += DateTime::GetDaysInMonth( i) * 24 * 60;
1399
1400    }
1401
1402
1403
1404    14 ULONG 12: recurrence interval in months. Naturally, 12.
1405
1406    18 ULONG 0 for all events and non-regenerating recurring tasks. 1 for
1407    regenerating tasks.
1408
1409    22 ULONG D: day of month the event recurs on. See monthly every N months on
1410    day D.
1411
1412    Yearly on the Xth Y of month M: 10 ULONG M (sort of): See yearly on day D of
1413    month M.
1414
1415    14 ULONG 12: recurrence interval in months. Naturally, 12.
1416
1417    18 ULONG Constant: 0
1418
1419    22 ULONG Y: see monthly every N months on the Xth Y.
1420
1421    26 ULONG X: see monthly every N months on the Xth Y.
1422
1423    After these recurrence-type-specific values, the offsets will change
1424    depending on the type. For every type except daily every N days, the offsets
1425    will grow by at least 4. For those types using the Xth Y, the offsets will
1426    grow by an additional 4, for a total of 8. The offsets for the rest of these
1427    values will be given for the most basic case, daily every N days, i.e.
1428    without any growth. Adjust as necessary. Also, the presence of exceptions
1429    will change the offsets following the exception data by a variable number of
1430    bytes, so the offsets given in the table are accurate only for those
1431    recurrence patterns without any exceptions.
1432
1433
1434    22 UCHAR Type of pattern termination: 0x21 for terminating on a given date, 0x22 for terminating
1435    after a given number of recurrences, or 0x23 for never terminating
1436    (recurring infinitely)
1437
1438    23 UCHARx3 Constant: { 0x20, 0x00, 0x00}
1439
1440    26 ULONG Number of occurrences in pattern: 0 for infinite recurrence,
1441    otherwise supply the value, even if it terminates on a given date, not after
1442    a given number
1443
1444    30 ULONG Constant: 0
1445
1446    34 ULONG Number of exceptions to pattern (i.e. deleted or changed
1447    occurrences)
1448
1449    .... ULONGxN Base date of each exception, given in hundreds of nanoseconds
1450    since 1601, so see below to turn them into a comprehensible format. The base
1451    date of an exception is the date (and only the date-- not the time) the
1452    exception would have occurred on in the pattern. They must occur in
1453    ascending order.
1454
1455    38 ULONG Number of changed exceptions (i.e. total number of exceptions -
1456    number of deleted exceptions): if there are changed exceptions, again, more
1457    data will be needed, but that will wait
1458
1459    .... ULONGxN Start date (and only the date-- not the time) of each changed
1460    exception, i.e. the exceptions which aren't deleted. These must also occur
1461    in ascending order. If all of the exceptions are deleted, this data will be
1462    absent. If present, they will be in the format above. Any dates that are in
1463    the first list but not in the second are exceptions that have been deleted
1464    (i.e. the difference between the two sets). Note that this is the start date
1465    (including time), not the base date. Given that the values are unordered and
1466    that they can't be matched up against the previous list in this iteration of
1467    the recurrence data (they could in previous ones), it is very difficult to
1468    tell which exceptions are deleted and which are changed. Fortunately, for
1469    this new format, the base dates are given on the attachment representing the
1470    changed exception (described below), so you can simply ignore this list of
1471    changed exceptions. Just create a list of exceptions from the previous list
1472    and assume they're all deleted unless you encounter an attachment with a
1473    matching base date later on.
1474
1475    42 ULONG Start date of pattern given in hundreds of nanoseconds since 1601;
1476    see below for an explanation.
1477
1478    46 ULONG End date of pattern: see start date of pattern
1479
1480    50 ULONG Constant: { 0x06, 0x30, 0x00, 0x00}
1481
1482    NOTE: I find the following 8-byte sequence of bytes to be very useful for
1483    orienting myself when looking at the raw data. If you can find { 0x06, 0x30,
1484    0x00, 0x00, 0x08, 0x30, 0x00, 0x00}, you can use these tables to work either
1485    forwards or backwards to find the data you need. The sequence sort of
1486    delineates certain critical exception-related data and delineates the
1487    exceptions themselves from the rest of the data and is relatively easy to
1488    find. If you're going to be meddling in here a lot, I suggest making a
1489    friend of ol' 0x00003006.
1490
1491    54 UCHAR This number is some kind of version indicator. Use 0x08 for Outlook
1492    2003. I believe 0x06 is Outlook 2000 and possibly 98, while 0x07 is Outlook
1493    XP. This number must be consistent with the features of the data structure
1494    generated by the version of Outlook indicated thereby-- there are subtle
1495    differences between the structures, and, if the version doesn't match the
1496    data, Outlook will sometimes failto read the structure.
1497
1498    55 UCHARx3 Constant: { 0x30, 0x00, 0x00}
1499
1500    58 ULONG Start time of occurrence in minutes: e.g. 0 for midnight or 720 for
1501    12 PM
1502
1503    62 ULONG End time of occurrence in minutes: i.e. start time + duration, e.g.
1504    900 for an event that starts at 12 PM and ends at 3PM
1505
1506    Exception Data 66 USHORT Number of changed exceptions: essentially a check
1507    on the prior occurrence of this value; should be equivalent.
1508
1509    NOTE: The following structure will occur N many times (where N = number of
1510    changed exceptions), and each structure can be of variable length.
1511
1512    .... ULONG Start date of changed exception given in hundreds of nanoseconds
1513    since 1601
1514
1515    .... ULONG End date of changed exception given in hundreds of nanoseconds
1516    since 1601
1517
1518    .... ULONG This is a value I don't clearly understand. It seems to be some
1519    kind of archival value that matches the start time most of the time, but
1520    will lag behind when the start time is changed and then match up again under
1521    certain conditions later. In any case, setting to the same value as the
1522    start time seems to work just fine (more information on this value would be
1523    appreciated).
1524
1525    .... USHORT Bitmask of changes to the exception (see below). This will be 0
1526    if the only changes to the exception were to its start or end time.
1527
1528    .... ULONGxN Numeric values (e.g. label or minutes to remind before the
1529    event) changed in the exception. These will occur in the order of their
1530    corresponding bits (see below). If no numeric values were changed, then
1531    these values will be absent.
1532
1533    NOTE: The following three values constitute a single sub-structure that will
1534    occur N many times, where N is the number of strings that are changed in the
1535    exception. Since there are at most 2 string values that can be excepted
1536    (i.e. subject [or description], and location), there can at most be two of
1537    these, but there may be none.
1538
1539    .... USHORT Length of changed string value with NULL character
1540
1541    .... USHORT Length of changed string value without NULL character (i.e.
1542    previous value - 1)
1543
1544    .... CHARxN Changed string value (without NULL terminator)
1545
1546    Unicode Data NOTE: If a string value was changed on an exception, those
1547    changed string values will reappear here in Unicode format after 8 bytes of
1548    NULL padding (possibly a Unicode terminator?). For each exception with a
1549    changed string value, there will be an identifier, followed by the changed
1550    strings in Unicode. The strings will occur in the order of their
1551    corresponding bits (see below). E.g., if both subject and location were
1552    changed in the exception, there would be the 3-ULONG identifier, then the
1553    length of the subject, then the subject, then the length of the location,
1554    then the location.
1555
1556    70 ULONGx2 Constant: { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}. This
1557    padding serves as a barrier between the older data structure and the
1558    appended Unicode data. This is the same sequence as the Unicode terminator,
1559    but I'm not sure whether that's its identity or not.
1560
1561    .... ULONGx3 These are the three times used to identify the exception above:
1562    start date, end date, and repeated start date. These should be the same as
1563    they were above.
1564
1565    .... USHORT Length of changed string value without NULL character. This is
1566    given as count of WCHARs, so it should be identical to the value above.
1567
1568    .... WCHARxN Changed string value in Unicode (without NULL terminator)
1569
1570    Terminator ... ULONGxN Constant: { 0x00, 0x00, 0x00, 0x00}. 4 bytes of NULL
1571    padding per changed exception. If there were no changed exceptions, all
1572    you'll need is the final terminator below.
1573
1574    .... ULONGx2 Constant: { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}.
1575
1576    */
1577?>
Note: See TracBrowser for help on using the repository browser.