source: trunk/calendar/inc/class.bocalendar.inc.php @ 363

Revision 363, 111.7 KB checked in by niltonneto, 16 years ago (diff)

Vide changelog, versão 0.9.23.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2  /**************************************************************************\
3  * eGroupWare - Calendar                                                    *
4  * http://www.eGroupWare.org                                                *
5  * Maintained and further developed by RalfBecker@outdoor-training.de       *
6  * Based on Webcalendar by Craig Knudsen <cknudsen@radix.net>               *
7  *          http://www.radix.net/~cknudsen                                  *
8  * Originaly modified by Mark Peters <skeeter@phpgroupware.org>             *
9  * --------------------------------------------                             *
10  *  This program is free software; you can redistribute it and/or modify it *
11  *  under the terms of the GNU General Public License as published by the   *
12  *  Free Software Foundation; either version 2 of the License, or (at your  *
13  *  option) any later version.                                              *
14  \**************************************************************************/
15
16
17        class bocalendar
18        {
19                var $public_functions = Array(
20                        'read_entry'      => True,
21                        'delete_entry'    => True,
22                        'delete_calendar' => True,
23                        'change_owner'    => True,
24                        'update'          => True,
25                        'check_set_default_prefs' => True,
26                        'store_to_cache'  => True,
27                        'export_event'    => True,
28                        'send_alarm'      => True,
29                        'reinstate'       => True
30                );
31
32                var $soap_functions = Array(
33                        'read_entry' => Array(
34                                'in' => Array(
35                                        'int'
36                                ),
37                                'out' => Array(
38                                        'SOAPStruct'
39                                )
40                        ),
41                        'delete_entry' => Array(
42                                'in' => Array(
43                                        'int'
44                                ),
45                                'out' => Array(
46                                        'int'
47                                )
48                        ),
49                        'delete_calendar' => Array(
50                                'in' => Array(
51                                        'int'
52                                ),
53                                'out' => Array(
54                                        'int'
55                                )
56                        ),
57                        'change_owner' => Array(
58                                'in' => Array(
59                                        'array'
60                                ),
61                                'out' => Array(
62                                        'int'
63                                )
64                        ),
65                        'update' => Array(
66                                'in' => Array(
67                                        'array',
68                                        'array',
69                                        'array',
70                                        'array',
71                                        'array'
72                                ),
73                                'out' => Array(
74                                        'array'
75                                )
76                        ),
77                        'store_to_cache'        => Array(
78                                'in' => Array(
79                                        'struct'
80                                ),
81                                'out' => Array(
82                                        'SOAPStruct'
83                                )
84                        ),
85                        'store_to_cache'        => Array(
86                                'in' => Array(
87                                        'array'
88                                ),
89                                'out' => Array(
90                                        'string'
91                                )
92                        ),
93                        'categories' => array(
94                                'in'  => array('bool'),
95                                'out' => array('array')
96                        ),
97                );
98
99                var $debug = False;
100//              var $debug = True;
101
102                var $so;
103                var $so1;
104                var $ex_participants;
105                var $cached_events;
106                var $repeating_events;
107                var $day;
108                var $month;
109                var $year;
110                var $prefs;
111
112                var $owner;
113                var $holiday_color;
114                var $printer_friendly = False;
115
116                var $cached_holidays;
117
118                var $g_owner = 0;
119
120                var $filter;
121                var $cat_id;
122                var $users_timeformat;
123
124                var $modified;
125                var $deleted;
126                var $added;
127
128                var $is_group = False;
129
130                var $soap = False;
131
132                var $use_session = False;
133
134                var $today;
135                var $debug_string;
136
137                var $sortby;
138                var $num_months;
139                var $xmlrpc = False;    // not called via xmlrpc
140        var $async = false;
141
142                function bocalendar($session=0)
143                {
144                        $this->cat = CreateObject('phpgwapi.categories');
145                        $this->grants = $GLOBALS['phpgw']->acl->get_grants('calendar');
146                        @reset($this->grants);
147                        if(DEBUG_APP)
148                        {
149                                if(floor(phpversion()) >= 4)
150                                {
151                                        $this->debug_string = '';
152                                        ob_start();
153                                }
154
155                                foreach($this->grants as $grantor => $rights)
156                                {
157                                        print_debug('Grantor',$grantor);
158                                        print_debug('Rights',$rights);
159                                }
160                        }
161
162                        print_debug('Read use_session',$session);
163
164                        if($session)
165                        {
166                                $this->read_sessiondata();
167                                $this->use_session = True;
168                        }
169                        print_debug('BO Filter',$this->filter);
170                        print_debug('Owner',$this->owner);
171
172                        if ($GLOBALS['argv']) {
173                          $this->async = true;
174                          $this->load_lang();
175                        }
176
177                        $this->prefs['calendar']    = $GLOBALS['phpgw_info']['user']['preferences']['calendar'];
178                        $this->check_set_default_prefs();
179
180                        $owner = get_var('owner',array('GET','POST'),$GLOBALS['owner']);
181
182                        ereg('menuaction=([a-zA-Z.]+)',$_SERVER['HTTP_REFERER'],$regs);
183                        $from = $regs[1];
184                        if ((substr($_SERVER['PHP_SELF'],-8) == 'home.php' && substr($this->prefs['calendar']['defaultcalendar'],0,7) == 'planner'
185                                || $_GET['menuaction'] == 'calendar.uicalendar.planner' &&
186                                $from  != 'calendar.uicalendar.planner' && !$this->save_owner)
187                                && (int)$this->prefs['calendar']['planner_start_with_group'] > 0)
188                        {
189                                // entering planner for the first time ==> saving owner in save_owner, setting owner to default
190                                //
191                                $this->save_owner = $this->owner;
192                                $owner = 'g_'.$this->prefs['calendar']['planner_start_with_group'];
193                        }
194                        elseif ($_GET['menuaction'] != 'calendar.uicalendar.planner' &&
195                                $this->save_owner)
196                        {
197                                // leaving planner with an unchanged user/owner ==> setting owner back to save_owner
198                                //
199                                $owner = (int)(isset($_GET['owner']) ? $_GET['owner'] : $this->save_owner);
200                                unset($this->save_owner);
201                        }
202                        elseif (!empty($owner) && $owner != $this->owner && $from == 'calendar.uicalendar.planner')
203                        {
204                                // user/owner changed within planner ==> forgetting save_owner
205                                //
206                                unset($this->save_owner);
207                        }
208
209                        if(isset($owner) && $owner!='' && substr($owner,0,2) == 'g_')
210                        {
211                                $this->set_owner_to_group(substr($owner,2));
212                        }
213                        elseif(isset($owner) && $owner!='')
214                        {
215                                $this->owner = (int)$owner;
216                        }
217                        elseif(!@isset($this->owner) || !@$this->owner)
218                        {
219                                $this->owner = (int)$GLOBALS['phpgw_info']['user']['account_id'];
220                        }
221                        elseif(isset($this->owner) && $GLOBALS['phpgw']->accounts->get_type($this->owner) == 'g')
222                        {
223                                $this->set_owner_to_group((int)$this->owner);
224                        }
225
226                        $this->prefs['common']    = $GLOBALS['phpgw_info']['user']['preferences']['common'];
227
228                        if ($this->prefs['common']['timeformat'] == '12')
229                        {
230                                $this->users_timeformat = 'h:ia';
231                        }
232                        else
233                        {
234                                $this->users_timeformat = 'H:i';
235                        }
236                        $this->holiday_color = (substr($GLOBALS['phpgw_info']['theme']['bg07'],0,1)=='#'?'':'#').$GLOBALS['phpgw_info']['theme']['bg07'];
237
238                        $friendly = (isset($_GET['friendly'])?$_GET['friendly']:'');
239                        $friendly = ($friendly=='' && isset($_POST['friendly'])?$_POST['friendly']:$friendly);
240
241                        $this->printer_friendly = ((int)$friendly == 1?True:False);
242
243                        if(isset($_POST['filter'])) { $this->filter = $_POST['filter']; }
244                        if(isset($_POST['sortby'])) { $this->sortby = $_POST['sortby']; }
245                        if(isset($_POST['cat_id'])) { $this->cat_id = $_POST['cat_id']; }
246
247                        if(!isset($this->filter))
248                        {
249                                $this->filter = ' '.$this->prefs['calendar']['defaultfilter'].' ';
250                        }
251
252                        if(!isset($this->sortby))
253                        {
254                                $this->sortby = $this->prefs['calendar']['defaultcalendar'] == 'planner_user' ? 'user' : 'category';
255                        }
256
257                        if($GLOBALS['phpgw']->accounts->get_type($this->owner)=='g')
258                        {
259                                $this->filter = ' all ';
260                        }
261
262                        $this->so = CreateObject('calendar.socalendar',
263                                Array(
264                                        'owner'         => $this->owner,
265                                        'filter'        => $this->filter,
266                                        'category'      => $this->cat_id,
267                                        'g_owner'       => $this->g_owner
268                                )
269                        );
270                        $this->rpt_day = array( // need to be after creation of socalendar
271                                MCAL_M_SUNDAY    => 'Sunday',
272                                MCAL_M_MONDAY    => 'Monday',
273                                MCAL_M_TUESDAY   => 'Tuesday',
274                                MCAL_M_WEDNESDAY => 'Wednesday',
275                                MCAL_M_THURSDAY  => 'Thursday',
276                                MCAL_M_FRIDAY    => 'Friday',
277                                MCAL_M_SATURDAY  => 'Saturday'
278                        );
279                        if($this->bo->prefs['calendar']['weekdaystarts'] != 'Sunday')
280                        {
281                                $mcals = array_keys($this->rpt_day);
282                                $days  = array_values($this->rpt_day);
283                                $this->rpt_day = array();
284                                list($n) = $found = array_keys($days,$this->prefs['calendar']['weekdaystarts']);
285                                for ($i = 0; $i < 7; ++$i,++$n)
286                                {
287                                        $this->rpt_day[$mcals[$n % 7]] = $days[$n % 7];
288                                }
289                        }
290                        $this->rpt_type = Array(
291                                MCAL_RECUR_NONE         => 'None',
292                                MCAL_RECUR_DAILY        => 'Daily',
293                                MCAL_RECUR_WEEKLY       => 'Weekly',
294                                MCAL_RECUR_MONTHLY_WDAY => 'Monthly (by day)',
295                                MCAL_RECUR_MONTHLY_MDAY => 'Monthly (by date)',
296                                MCAL_RECUR_YEARLY       => 'Yearly'
297                        );
298
299                        $localtime = $GLOBALS['phpgw']->datetime->users_localtime;
300
301                        $date = (isset($GLOBALS['date'])?$GLOBALS['date']:'');
302                        $date = (isset($_GET['date'])?$_GET['date']:$date);
303                        $date = ($date=='' && isset($_POST['date'])?$_POST['date']:$date);
304
305                        $year = (isset($_GET['year'])?$_GET['year']:'');
306                        $year = ($year=='' && isset($_POST['year'])?$_POST['year']:$year);
307
308                        $month = (isset($_GET['month'])?$_GET['month']:'');
309                        $month = ($month=='' && isset($_POST['month'])?$_POST['month']:$month);
310
311                        $day = (isset($_GET['day'])?$_GET['day']:'');
312                        $day = ($day=='' && isset($_POST['day'])?$_POST['day']:'');
313
314                        $num_months = (isset($_GET['num_months'])?$_GET['num_months']:'');
315                        $num_months = ($num_months=='' && isset($_POST['num_months'])?$_POST['num_months']:$num_months);
316
317                        if(isset($date) && $date!='')
318                        {
319                                $this->year  = (int)(substr($date,0,4));
320                                $this->month = (int)(substr($date,4,2));
321                                $this->day   = (int)(substr($date,6,2));
322                        }
323                        else
324                        {
325                                if(isset($year) && $year!='')
326                                {
327                                        $this->year = $year;
328                                }
329                                else
330                                {
331                                        $this->year = date('Y',$localtime);
332                                }
333                                if(isset($month) && $month!='')
334                                {
335                                        $this->month = $month;
336                                }
337                                else
338                                {
339                                        $this->month = date('m',$localtime);
340                                }
341                                if(isset($day) && $day!='')
342                                {
343                                        $this->day = $day;
344                                }
345                                else
346                                {
347                                        $this->day = date('d',$localtime);
348                                }
349                        }
350
351                        if(isset($num_months) && $num_months!='')
352                        {
353                                $this->num_months = $num_months;
354                        }
355                        elseif($this->num_months == 0)
356                        {
357                                $this->num_months = 1;
358                        }
359
360                        $this->today = date('Ymd',$GLOBALS['phpgw']->datetime->users_localtime);
361
362                        if(DEBUG_APP)
363                        {
364                                print_debug('BO Filter','('.$this->filter.')');
365                                print_debug('Owner',$this->owner);
366                                print_debug('Today',$this->today);
367                                if(floor(phpversion()) >= 4)
368                                {
369                                        $this->debug_string .= ob_get_contents();
370                                        ob_end_clean();
371                                }
372                        }
373                        $this->xmlrpc = is_object($GLOBALS['server']) && $GLOBALS['server']->last_method;
374                }
375
376          function load_lang() {
377            if(!$_SESSION['phpgw_info']['calendar']['langAlarm'])
378              {
379                $array_keys = array();
380                $fn = '../../calendar/setup/phpgw_alarm_'.$GLOBALS['phpgw_info']['user']['preferences']['common']['lang'].'.lang';                     
381                echo $fn;
382                if (file_exists($fn)){
383                  $fp = fopen($fn,'r');
384                  while ($data = fgets($fp,16000))      {
385                    list($message_id,$app_name,$null,$content) = explode("\t",substr($data,0,-1));                     
386                    $_SESSION['phpgw_info']['calendar']['langAlarm'][$message_id] =  $content;
387                  }
388                  fclose($fp);
389                }
390              }
391          }
392                function list_methods($_type='xmlrpc')
393                {
394                        /*
395                          This handles introspection or discovery by the logged in client,
396                          in which case the input might be an array.  The server always calls
397                          this function to fill the server dispatch map using a string.
398                        */
399                        if (is_array($_type))
400                        {
401                                $_type = $_type['type'];
402                        }
403                        switch($_type)
404                        {
405                                case 'xmlrpc':
406                                        $xml_functions = array(
407                                                'list_methods' => array(
408                                                        'function'  => 'list_methods',
409                                                        'signature' => array(array(xmlrpcStruct,xmlrpcString)),
410                                                        'docstring' => lang('Read this list of methods.')
411                                                ),
412                                                'read' => array(
413                                                        'function'  => 'read_entry',
414                                                        'signature' => array(array(xmlrpcStruct,xmlrpcInt)),
415                                                        'docstring' => lang('Read a single entry by passing the id and fieldlist.')
416                                                ),
417                                                'read_entry' => array(  // deprecated, use read
418                                                        'function'  => 'read_entry',
419                                                        'signature' => array(array(xmlrpcStruct,xmlrpcInt)),
420                                                        'docstring' => lang('Read a single entry by passing the id and fieldlist.')
421                                                ),
422                                                'write' => array(
423                                                        'function'  => 'update',
424                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
425                                                        'docstring' => lang('Add or update a single entry by passing the fields.')
426                                                ),
427                                                'add_entry' => array(   // deprecated, use write
428                                                        'function'  => 'update',
429                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
430                                                        'docstring' => lang('Add a single entry by passing the fields.')
431                                                ),
432                                                'update_entry' => array(        // deprecated, use write
433                                                        'function'  => 'update',
434                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
435                                                        'docstring' => lang('Update a single entry by passing the fields.')
436                                                ),
437                                                'delete' => array(
438                                                        'function'  => 'delete_entry',
439                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
440                                                        'docstring' => lang('Delete a single entry by passing the id.')
441                                                ),
442                                                'delete_entry' => array(        // deprecated, use delete
443                                                        'function'  => 'delete_entry',
444                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
445                                                        'docstring' => lang('Delete a single entry by passing the id.')
446                                                ),
447                                                'delete_calendar' => array(
448                                                        'function'  => 'delete_calendar',
449                                                        'signature' => array(array(xmlrpcInt,xmlrpcInt)),
450                                                        'docstring' => lang('Delete an entire users calendar.')
451                                                ),
452                                                'change_owner' => array(
453                                                        'function'  => 'change_owner',
454                                                        'signature' => array(array(xmlrpcInt,xmlrpcStruct)),
455                                                        'docstring' => lang('Change all events for $params[\'old_owner\'] to $params[\'new_owner\'].')
456                                                ),
457                                                'search' => array(
458                                                        'function'  => 'store_to_cache',
459                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
460                                                        'docstring' => lang('Read a list of entries.')
461                                                ),
462                                                'store_to_cache' => array(      // deprecated, use search
463                                                        'function'  => 'store_to_cache',
464                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
465                                                        'docstring' => lang('Read a list of entries.')
466                                                ),
467                                                'export_event' => array(
468                                                        'function'  => 'export_event',
469                                                        'signature' => array(array(xmlrpcString,xmlrpcStruct)),
470                                                        'docstring' => lang('Export a list of entries in iCal format.')
471                                                ),
472                                                'categories' => array(
473                                                        'function'  => 'categories',
474                                                        'signature' => array(array(xmlrpcStruct,xmlrpcStruct)),
475                                                        'docstring' => lang('List all categories.')
476                                                ),
477                                        );
478                                        return $xml_functions;
479                                        break;
480                                case 'soap':
481                                        return $this->soap_functions;
482                                        break;
483                                default:
484                                        return array();
485                                        break;
486                        }
487                }
488
489                function set_owner_to_group($owner)
490                {
491                        print_debug('calendar::bocalendar::set_owner_to_group:owner',$owner);
492                        $this->owner = (int)$owner;
493                        $this->is_group = True;
494                        $this->g_owner = Array();
495                        $members = $GLOBALS['phpgw']->accounts->member($owner);
496                        if (is_array($members))
497                        {
498                                foreach($members as $user)
499                                {
500                                        // use only members which gave the user a read-grant
501                                        if ($this->check_perms(PHPGW_ACL_READ,0,$user['account_id']))
502                                        {
503                                                $this->g_owner[] = $user['account_id'];
504                                        }
505                                }
506                        }
507                        //echo "<p>".function_backtrace().": set_owner_to_group($owner) = ".print_r($this->g_owner,True)."</p>\n";
508                }
509
510                function member_of_group($owner=0)
511                {
512                        $owner = ($owner==0?$GLOBALS['phpgw_info']['user']['account_id']:$owner);
513                        $group_owners = $GLOBALS['phpgw']->accounts->membership();
514                        while($group_owners && list($index,$group_info) = each($group_owners))
515                        {
516                                if($this->owner == $group_info['account_id'])
517                                {
518                                        return True;
519                                }
520                        }
521                        return False;
522                }
523
524                function save_sessiondata($data='')
525                {
526                        if ($this->use_session)
527                        {
528                                if (!is_array($data))
529                                {
530                                        $data = array(
531                                                'filter'     => $this->filter,
532                                                'cat_id'     => $this->cat_id,
533                                                'owner'      => $this->owner,
534                                                'save_owner' => $this->save_owner,
535                                                'year'       => $this->year,
536                                                'month'      => $this->month,
537                                                'day'        => $this->day,
538                                                'date'       => $this->date,
539                                                'sortby'     => $this->sortby,
540                                                'num_months' => $this->num_months,
541                                                'return_to'  => $this->return_to
542                                        );
543                                }
544                                if($this->debug)
545                                {
546                                        if(floor(phpversion()) >= 4)
547                                        {
548                                                ob_start();
549                                        }
550                                        echo '<!-- '."\n".'Save:'."\n"._debug_array($data,False)."\n".' -->'."\n";
551                                        if(floor(phpversion()) >= 4)
552                                        {
553                                                $this->debug_string .= ob_get_contents();
554                                                ob_end_clean();
555                                        }
556                                }
557                                $GLOBALS['phpgw']->session->appsession('session_data','calendar',$data);
558                        }
559                }
560
561                function read_sessiondata()
562                {
563                        $data = $GLOBALS['phpgw']->session->appsession('session_data','calendar');
564                        print_debug('Read',_debug_array($data,False));
565
566                        $this->filter = $data['filter'];
567                        $this->cat_id = $data['cat_id'];
568                        $this->sortby = $data['sortby'];
569                        $this->owner  = (int)$data['owner'];
570                        $this->save_owner = (int)$data['save_owner'];
571                        $this->year   = (int)$data['year'];
572                        $this->month  = (int)$data['month'];
573                        $this->day    = (int)$data['day'];
574                        $this->num_months = (int)$data['num_months'];
575                        $this->return_to = $data['return_to'];
576                }
577
578                function read_entry($id,$ignore_acl=False)
579                {
580                        if (is_array($id) && count($id) == 1)
581                        {
582                                list(,$id) = each($id);
583                        }
584                        if($ignore_acl || $this->check_perms(PHPGW_ACL_READ,$id))
585                        {
586                                $event = $this->so->read_entry($id);
587                                if(!isset($event['participants'][$this->owner]) && $this->user_is_a_member($event,$this->owner))
588                                {
589                                        $this->so->add_attribute('participants','U',(int)$this->owner);
590                                        $this->so->add_entry($event);
591                                        $event = $this->get_cached_event();
592                                }
593                                return $this->xmlrpc ? $this->xmlrpc_prepare($event) : $event;
594                        }
595                        if ($this->xmlrpc)
596                        {
597                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
598                        }
599                        return False;
600                }
601
602                function delete_single($param)
603                {
604                        if($this->check_perms(PHPGW_ACL_DELETE,(int)$param['id']))
605                        {
606                                $temp_event = $this->get_cached_event();
607                                $event = $this->read_entry((int)$param['id']);
608//                              if($this->owner == $event['owner'])
609//                              {
610                                $exception_time = mktime($event['start']['hour'],$event['start']['min'],0,$param['month'],$param['day'],$param['year']) - $GLOBALS['phpgw']->datetime->tz_offset;
611                                $event['recur_exception'][] = (int)$exception_time;
612                                $this->so->cal->event = $event;
613//                              print_debug('exception time',$event['recur_exception'][count($event['recur_exception']) -1]);
614//                              print_debug('count event exceptions',count($event['recur_exception']));
615                                $this->so->add_entry($event);
616                                $cd = 16;
617
618                                $this->so->cal->event = $temp_event;
619                                unset($temp_event);
620                        }
621                        else
622                        {
623                                $cd = 60;
624                        }
625//                      }
626                        return $cd;
627                }
628
629                function delete_entry($id)
630                {
631                        if (is_array($id) && count($id) == 1)
632                        {
633                                list(,$id) = each($id);
634                        }
635                        if($this->check_perms(PHPGW_ACL_DELETE,$id))
636                        {
637                                $this->so->delete_entry($id);
638
639                                if ($this->xmlrpc)
640                                {
641                                        $this->so->expunge($id);
642                                }
643                                return $this->xmlrpc ? True : 16;
644                        }
645                        if ($this->xmlrpc)
646                        {
647                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
648                        }
649                        return 60;
650                }
651
652                function reinstate($params='')
653                {
654                        if($this->check_perms(PHPGW_ACL_EDIT,$params['cal_id']) && isset($params['reinstate_index']))
655                        {
656                                $event = $this->so->read_entry($params['cal_id']);
657                                @reset($params['reinstate_index']);
658                                print_debug('Count of reinstate_index',count($params['reinstate_index']));
659                                if(count($params['reinstate_index']) > 1)
660                                {
661                                        while(list($key,$value) = each($params['reinstate_index']))
662                                        {
663                                                print_debug('reinstate_index ['.$key.']',(int)$value);
664                                                print_debug('exception time',$event['recur_exception'][(int)$value]);
665                                                unset($event['recur_exception'][(int)$value]);
666                                                print_debug('count event exceptions',count($event['recur_exception']));
667                                        }
668                                }
669                                else
670                                {
671                                        print_debug('reinstate_index[0]',(int)$params['reinstate_index'][0]);
672                                        print_debug('exception time',$event['recur_exception'][(int)$params['reinstate_index'][0]]);
673                                        unset($event['recur_exception'][(int)$params['reinstate_index'][0]]);
674                                        print_debug('count event exceptions',count($event['recur_exception']));
675                                }
676                                $this->so->cal->event = $event;
677                                $this->so->add_entry($event);
678                                return 42;
679                        }
680                        else
681                        {
682                                return 43;
683                        }
684                }
685
686                function delete_calendar($owner)
687                {
688                        if($GLOBALS['phpgw_info']['user']['apps']['admin'])
689                        {
690                                $this->so->delete_calendar($owner);
691                        }
692                }
693
694                function change_owner($params='')
695                {
696                        if($GLOBALS['phpgw_info']['server']['calendar_type'] == 'sql')
697                        {
698                                if(is_array($params))
699                                {
700                                        $this->so->change_owner($params['old_owner'],$params['new_owner']);
701                                }
702                        }
703                }
704
705                function expunge()
706                {
707                        reset($this->so->cal->deleted_events);
708                        while(list($i,$event_id) = each($this->so->cal->deleted_events))
709                        {
710                                $event = $this->so->read_entry($event_id);
711                                if(!$this->ex_participants)
712                                        $this->ex_participants = html_entity_decode($event['ex_participants']);                 
713                                if($this->check_perms(PHPGW_ACL_DELETE,$event))
714                                {
715                                        $this->send_update(MSG_DELETED,$event['participants'],$event);
716                                }
717                                else
718                                {
719                                        unset($this->so->cal->deleted_events[$i]);
720                                }
721                        }
722                        $this->so->expunge();
723                }
724
725                function search_keywords($keywords)
726                {
727                        $type = $GLOBALS['phpgw']->accounts->get_type($this->owner);
728
729                        if($type == 'g')
730                        {
731                                $members = $GLOBALS['phpgw']->acl->get_ids_for_location($this->owner, 1, 'phpgw_group');
732                        }
733                        else
734                        {
735                                $members = array_keys($this->grants);
736
737                                if (!in_array($this->owner,$members))
738                                {
739                                        $members[] = $this->owner;
740                                }
741                        }
742                        foreach($members as $n => $uid)
743                        {
744                                if (!($this->grants[$uid] & PHPGW_ACL_READ))
745                                {
746                                        unset($members[$n]);
747                                }
748                        }
749                        return $this->so->list_events_keyword($keywords,$members);
750                }
751
752                function update($params='')
753                {
754                       
755                        $l_cal = (@isset($params['cal']) && $params['cal']?$params['cal']:$_POST['cal']);
756                        $l_participants = (@$params['participants']?$params['participants']:$_POST['participants']);
757                        $this->ex_participants = (@$params['ex_participants']?$params['ex_participants']:$_POST['ex_participants']);
758                        $l_categories = (@$params['categories']?$params['categories']:$_POST['categories']);
759                        $l_start = (@isset($params['start']) && $params['start']?$params['start']:$_POST['start']);
760                        $l_end = (@isset($params['end']) && $params['end']?$params['end']:$_POST['end']);
761                        $l_recur_enddate = (@isset($params['recur_enddate']) && $params['recur_enddate']?$params['recur_enddate']:$_POST['recur_enddate']);
762                       
763                        $send_to_ui = True;
764                        //if ((!is_array($l_start) || !is_array($l_end)) && !isset($_GET['readsess']))  // xmlrpc call
765                        if ($this->xmlrpc)      // xmlrpc call
766                        {
767                                $send_to_ui = False;
768
769                                $l_cal = $params;       // no extra array
770
771                                foreach(array('start','end','recur_enddate') as $name)
772                                {
773                                        $var = 'l_'.$name;
774                                        $$var = $GLOBALS['server']->iso86012date($params[$name]);
775                                        unset($l_cal[$name]);
776                                }
777                                if (!is_array($l_participants) || !count($l_participants))
778                                {
779                                        $l_participants = array($GLOBALS['phpgw_info']['user']['account_id'].'A');
780                                }
781                                else
782                                {
783                                        $l_participants = array();
784                                        foreach($params['participants'] as $user => $data)
785                                        {
786                                                $l_participants[] = $user.$data['status'];
787                                        }
788                                }
789                                unset($l_cal['participants']);
790
791                                if (!is_object($GLOBALS['phpgw']->categories))
792                                {
793                                        $GLOBALS['phpgw']->categories = CreateObject('phpgwapi.categories');
794                                }
795                                $l_categories = $GLOBALS['server']->xmlrpc2cats($params['category']);
796                                unset($l_cal['category']);
797
798                                // using access={public|private} in all modules via xmlrpc
799                                $l_cal['public'] = $params['access'] != 'private';
800                                unset($l_cal['access']);
801/*
802                                $fp = fopen('/tmp/xmlrpc.log','a+');
803                                ob_start();
804                                echo "\nbocalendar::update("; print_r($params); echo ")\n";
805                                //echo "\nl_start="; print_r($l_start);
806                                //echo "\nl_end="; print_r($l_end);
807                                fwrite($fp,ob_get_contents());
808                                ob_end_clean();
809                                fclose($fp);
810*/
811                        }
812                        print_debug('ID',$l_cal['id']);
813
814                        // don't wrap to the next day for no time
815                        if ($l_end['hour'] == 24 && $l_end['min'] == 0)
816                        {
817                                $l_end['hour'] = 23;
818                                $l_end['min'] = 59;
819                        }
820
821                        if(isset($_GET['readsess']))
822                        {
823                                $event = $this->restore_from_appsession();
824                                $event['title'] = stripslashes($event['title']);
825                                $event['description'] = stripslashes($event['description']);
826                                $event['ex_participants'] = stripslashes($event['ex_participants']);
827                                $datetime_check = $this->validate_update($event);
828                                if($datetime_check)
829                                {
830                                        ExecMethod('calendar.uicalendar.edit',
831                                                Array(
832                                                        'cd'            => $datetime_check,
833                                                        'readsess'      => 1
834                                                )
835                                        );
836                                        $GLOBALS['phpgw']->common->phpgw_exit(True);
837                                }
838                                $overlapping_events = False;
839                        }
840                        else
841                        {
842                                if((!$l_cal['id'] && !$this->check_perms(PHPGW_ACL_ADD)) ||
843                                   ($l_cal['id'] && !$this->check_perms(PHPGW_ACL_EDIT,$l_cal['id'])))
844                                {
845                                        if ($this->xmlrpc)
846                                        {
847                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['no_access'],$GLOBALS['xmlrpcstr']['no_access']);
848                                        }
849                                        if (!$send_to_ui)
850                                        {
851                                                return array(($l_cal['id']?1:2) => 'permission denied');
852                                        }
853                                        ExecMethod('calendar.uicalendar.index');
854                                        $GLOBALS['phpgw']->common->phpgw_exit();
855                                }
856
857                                print_debug('Prior to fix_update_time()');
858                                $this->fix_update_time($l_start);
859                                $this->fix_update_time($l_end);
860
861                                if(!isset($l_cal['private']))
862                                {
863                                        $l_cal['private'] = 'public';
864                                }
865                                if(!isset($l_cal['ex_participants']))
866                                {
867                                        $l_cal['ex_participants'] = $this->ex_participants;
868                                }
869
870                                if(!isset($l_categories))
871                                {
872                                        $l_categories = 0;
873                                }
874
875                                $is_public = (int)(isset($l_cal['public']) ? $l_cal['public'] : $l_cal['private'] == 'public');
876                                $this->so->event_init();
877                                $this->add_attribute('uid',$l_cal['uid']);
878                                if($l_cal['ex_participants']) {
879                                        $this->add_attribute('ex_participants',$l_cal['ex_participants']);
880                                }
881                                if(count($l_categories) >= 2)
882                                {
883                                        $this->so->set_category(implode(',',$l_categories));
884                                }
885                                else
886                                {
887                                        $this->so->set_category(strval($l_categories[0]));
888                                }
889                                $this->so->set_title($l_cal['title']);
890                                $this->so->set_description($l_cal['description']);
891                                $this->so->set_ex_participants($l_cal['ex_participants']);
892                                $this->so->set_start($l_start['year'],$l_start['month'],$l_start['mday'],$l_start['hour'],$l_start['min'],0);
893                                $this->so->set_end($l_end['year'],$l_end['month'],$l_end['mday'],$l_end['hour'],$l_end['min'],0);
894                                $this->so->set_class($is_public);
895                                $this->so->add_attribute('reference',(@isset($l_cal['reference']) && $l_cal['reference']?$l_cal['reference']:0));
896                                $this->so->add_attribute('location',(@isset($l_cal['location']) && $l_cal['location']?$l_cal['location']:''));
897                                if($l_cal['id'])
898                                {
899                                        $this->so->add_attribute('id',$l_cal['id']);
900                                }
901
902                                if($l_cal['rpt_use_end'] != 'y')
903                                {
904                                        $l_recur_enddate['year'] = 0;
905                                        $l_recur_enddate['month'] = 0;
906                                        $l_recur_enddate['mday'] = 0;
907                                }
908                                elseif (isset($l_recur_enddate['str']))
909                                {
910                                        $l_recur_enddate = $this->jscal->input2date($l_recur_enddate['str'],False,'mday');
911                                }
912
913                                switch((int)$l_cal['recur_type'])
914                                {
915                                        case MCAL_RECUR_NONE:
916                                                $this->so->set_recur_none();
917                                                break;
918                                        case MCAL_RECUR_DAILY:
919                                                $this->so->set_recur_daily((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
920                                                break;
921                                        case MCAL_RECUR_WEEKLY:
922                                                foreach(array('rpt_sun','rpt_mon','rpt_tue','rpt_wed','rpt_thu','rpt_fri','rpt_sat') as $rpt_day)
923                                                {
924                                                        $l_cal['recur_data'] += (int)$l_cal[$rpt_day];
925                                                }
926                                                if (is_array($l_cal['rpt_day']))
927                                                {
928                                                        foreach ($l_cal['rpt_day'] as $mask)
929                                                        {
930                                                                $l_cal['recur_data'] |= (int)$mask;
931                                                        }
932                                                }
933                                                $this->so->set_recur_weekly((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval'],$l_cal['recur_data']);
934                                                break;
935                                        case MCAL_RECUR_MONTHLY_MDAY:
936                                                $this->so->set_recur_monthly_mday((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
937                                                break;
938                                        case MCAL_RECUR_MONTHLY_WDAY:
939                                                $this->so->set_recur_monthly_wday((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
940                                                break;
941                                        case MCAL_RECUR_YEARLY:
942                                                $this->so->set_recur_yearly((int)$l_recur_enddate['year'],(int)$l_recur_enddate['month'],(int)$l_recur_enddate['mday'],(int)$l_cal['recur_interval']);
943                                                break;
944                                }
945
946                                if($l_participants)
947                                {
948                                        $parts = $l_participants;
949                                        $minparts = min($l_participants);
950                                        $part = Array();
951                                        for($i=0;$i<count($parts);$i++)
952                                        {
953                                                if (($accept_type = substr($parts[$i],-1,1)) == '0' || (int)$accept_type > 0)
954                                                {
955                                                        $accept_type = 'U';
956                                                }
957                                                $acct_type = $GLOBALS['phpgw']->accounts->get_type((int)$parts[$i]);
958                                                if($acct_type == 'u')
959                                                {
960                                                        $part[(int)$parts[$i]] = $accept_type;
961                                                }
962                                                elseif($acct_type == 'g')
963                                                {
964                                                        $part[(int)$parts[$i]] = $accept_type;
965                                                        $groups[] = $parts[$i];
966                                                        /* This pulls ALL users of a group and makes them as participants to the event */
967                                                        /* I would like to turn this back into a group thing. */
968                                                        $acct = CreateObject('phpgwapi.accounts',(int)$parts[$i]);
969                                                        $members = $acct->member((int)$parts[$i]);
970                                                        unset($acct);
971                                                        if($members == False)
972                                                        {
973                                                                continue;
974                                                        }
975                                                        while($member = each($members))
976                                                        {
977                                                                $part[$member[1]['account_id']] = $accept_type;
978                                                        }
979                                                }
980                                        }
981                                }
982                                else
983                                {
984                                        $part = False;
985                                }
986
987                                if($part)
988                                {
989                                        @reset($part);
990                                        while(list($key,$accept_type) = each($part))
991                                        {
992                                                $this->so->add_attribute('participants',$accept_type,(int)$key);
993                                        }
994                                }
995
996                                if($groups)
997                                {
998                                        @reset($groups);
999                                        $this->so->add_attribute('groups',(int)$group_id);
1000                                }
1001
1002                                $event = $this->get_cached_event();
1003                                if(!is_int($minparts))
1004                                {
1005                                        $minparts = $this->owner;
1006                                }
1007                                if(!@isset($event['participants'][$l_cal['owner']]))
1008                                {
1009                                        $this->so->add_attribute('owner',$minparts);
1010                                }
1011                                else
1012                                {
1013                                        $this->so->add_attribute('owner',$l_cal['owner']);
1014                                }
1015                                $this->so->add_attribute('priority',$l_cal['priority']);
1016
1017                                foreach($l_cal as $name => $value)
1018                                {
1019                                        if ($name[0] == '#')    // Custom field
1020                                        {
1021                                                $this->so->add_attribute($name,stripslashes($value));
1022                                        }
1023                                }
1024                                if (isset($_POST['preserved']) && is_array($preserved = unserialize(stripslashes($_POST['preserved']))))
1025                                {
1026                                        foreach($preserved as $name => $value)
1027                                        {
1028                                                switch($name)
1029                                                {
1030                                                        case 'owner':
1031                                                                $this->so->add_attribute('participants',$value,$l_cal['owner']);
1032                                                                break;
1033                                                        default:
1034                                                                $this->so->add_attribute($name,str_replace(array('&amp;','&quot;','&lt;','&gt;'),array('&','"','<','>'),$value));
1035                                                }
1036                                        }
1037                                }
1038                                $event = $this->get_cached_event();
1039
1040                                if ($l_cal['alarmdays'] > 0 || $l_cal['alarmhours'] > 0 ||
1041                                                $l_cal['alarmminutes'] > 0)
1042                                {
1043                                        $offset = ($l_cal['alarmdays'] * 24 * 3600) +
1044                                                ($l_cal['alarmhours'] * 3600) + ($l_cal['alarmminutes'] * 60);
1045
1046                                        $time = $this->maketime($event['start']) - $offset;
1047
1048                                        $event['alarm'][] = Array(
1049                                                'time'    => $time,
1050                                                'offset'  => $offset,
1051                                                'owner'   => $this->owner,
1052                                                'enabled' => 1
1053                                        );
1054                                }
1055
1056                                $this->store_to_appsession($event);
1057                                $datetime_check = $this->validate_update($event);
1058                                print_debug('bo->validated_update() returnval',$datetime_check);
1059                                if($datetime_check)
1060                                {
1061                                        if (!$send_to_ui)
1062                                        {
1063                                                return array($datetime_check => 'invalid input data');
1064                                        }
1065                                        ExecMethod('calendar.uicalendar.edit',
1066                                                Array(
1067                                                        'cd'            => $datetime_check,
1068                                                        'readsess'      => 1
1069                                                )
1070                                        );
1071                                        $GLOBALS['phpgw']->common->phpgw_exit(True);
1072                                }
1073
1074                                if($event['id'])
1075                                {
1076                                        $event_ids[] = $event['id'];
1077                                }
1078                                if($event['reference'])
1079                                {
1080                                        $event_ids[] = $event['reference'];
1081                                }
1082
1083                                $overlapping_events = $this->overlap(
1084                                        $this->maketime($event['start']),
1085                                        $this->maketime($event['end']),
1086                                        $event['participants'],
1087                                        $event['owner'],
1088                                        $event_ids
1089                                );
1090                        }
1091                        if(!$this->ex_participants)
1092                                $this->ex_participants = $event['ex_participants'];                     
1093                        if($overlapping_events)
1094                        {
1095                                if($send_to_ui)
1096                                {
1097                                        $event['ex_participants'] = $this->ex_participants;
1098                                        unset($GLOBALS['phpgw_info']['flags']['noheader']);
1099                                        unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
1100                                        ExecMethod('calendar.uicalendar.overlap',
1101                                                Array(
1102                                                        'o_events'      => $overlapping_events,
1103                                                        'this_event'    => $event
1104                                                )
1105                                        );
1106                                        $GLOBALS['phpgw']->common->phpgw_exit(True);
1107                                }
1108                                else
1109                                {
1110                                        return $overlapping_events;
1111                                }
1112                        }
1113                        else
1114                        {
1115                                if(!$event['id'])
1116                                {
1117                                        $this->so->add_entry($event);
1118                                        $this->send_update(MSG_ADDED,$event['participants'],'',$this->get_cached_event());
1119                                        print_debug('New Event ID',$event['id']);
1120                                }
1121                                else
1122                                {
1123                                        print_debug('Updating Event ID',$event['id']);
1124                                        $new_event = $event;
1125                                        $old_event = $this->read_entry($event['id']);
1126                                        // if old event has alarm and the start-time changed => update them
1127                                        //echo "<p>checking ".count($old_event['alarm'])." alarms of event #$event[id] start moved from ".print_r($old_event['start'],True)." to ".print_r($event['start'],True)."</p>\n";
1128                                        if ($old_event['alarm'] &&
1129                                                $this->maketime($old_event['start']) != $this->maketime($event['start']))
1130                                        {
1131                                                $this->so->delete_alarms($old_event['id']);
1132                                                foreach($old_event['alarm'] as $id => $alarm)
1133                                                {
1134                                                        $alarm['time'] = $this->maketime($event['start']) - $alarm['offset'];
1135                                                        $event['alarm'][] = $alarm;
1136                                                }
1137                                                //echo "updated alarms<pre>".print_r($event['alarm'],True)."</pre>\n";
1138                                        }
1139                                        $this->so->cal->event = $event;
1140                                        $this->so->add_entry($event);
1141                                        $this->prepare_recipients($new_event,$old_event);
1142                                }
1143
1144                                $date = sprintf("%04d%02d%02d",$event['start']['year'],$event['start']['month'],$event['start']['mday']);
1145                                if($send_to_ui)
1146                                {
1147                                        $this->read_sessiondata();
1148                                        if ($this->return_to)
1149                                        {
1150                                                $GLOBALS['phpgw']->redirect_link('/index.php','menuaction='.$this->return_to);
1151                                                $GLOBALS['phpgw']->common->phpgw_exit();
1152                                        }
1153                                        Execmethod('calendar.uicalendar.index');
1154                                }
1155                                else
1156                                {
1157                                        return (int)$event['id'];
1158                                }
1159                        }
1160                        return True;
1161                }
1162
1163                /* Private functions */
1164                function read_holidays($year=0)
1165                {
1166                        if(!$year)
1167                        {
1168                                $year = $this->year;
1169                        }
1170                        $holiday = CreateObject('calendar.boholiday');
1171                        $holiday->prepare_read_holidays($year,$this->owner);
1172                        $this->cached_holidays = $holiday->read_holiday();
1173                        unset($holiday);
1174                }
1175
1176                function user_is_a_member($event,$user)
1177                {
1178                        @reset($event['participants']);
1179                        $uim = False;
1180                        $security_equals = $GLOBALS['phpgw']->accounts->membership($user);
1181                        while(!$uim && $event['participants'] && $security_equals && list($participant,$status) = each($event['participants']))
1182                        {
1183                                if($GLOBALS['phpgw']->accounts->get_type($participant) == 'g')
1184                                {
1185                                        @reset($security_equals);
1186                                        while(list($key,$group_info) = each($security_equals))
1187                                        {
1188                                                if($group_info['account_id'] == $participant)
1189                                                {
1190                                                        return True;
1191                                                        $uim = True;
1192                                                }
1193                                        }
1194                                }
1195                        }
1196                        return $uim;
1197                }
1198
1199                function maketime($time)
1200                {
1201                        return mktime(intval($time['hour']),intval($time['min']),intval($time['sec']),intval($time['month']),intval($time['mday']),intval($time['year']));
1202                }
1203
1204                /*!
1205                @function time2array
1206                @abstract returns a date-array suitable for the start- or endtime of an event from a timestamp
1207                @syntax time2array($time,$alarm=0)
1208                @param $time the timestamp for the values of the array
1209                @param $alarm (optional) alarm field of the array, defaults to 0
1210                @author ralfbecker
1211                */
1212                function time2array($time,$alarm = 0)
1213                {
1214                        return array(
1215                                'year'  => (int)(date('Y',$time)),
1216                                'month' => (int)(date('m',$time)),
1217                                'mday'  => (int)(date('d',$time)),
1218                                'hour'  => (int)(date('H',$time)),
1219                                'min'   => (int)(date('i',$time)),
1220                                'sec'   => (int)(date('s',$time)),
1221                                'alarm' => (int)($alarm)
1222                        );
1223                }
1224
1225                /*!
1226                @function set_recur_date
1227                @abstract set the start- and enddates of a recuring event for a recur-date
1228                @syntax set_recur_date(&$event,$date)
1229                @param $event the event which fields to set (has to be the original event for start-/end-times)
1230                @param $date  the recuring date in form 'Ymd', eg. 20030226
1231                @author ralfbecker
1232                */
1233                function set_recur_date(&$event,$date)
1234                {
1235                        $org_start = $this->maketime($event['start']);
1236                        $org_end   = $this->maketime($event['end']);
1237                        $start = mktime($event['start']['hour'],$event['start']['min'],0,substr($date,4,2),substr($date,6,2),substr($date,0,4));
1238                        $end   = $org_end + $start - $org_start;
1239                        $event['start'] = $this->time2array($start);
1240                        $event['end']   = $this->time2array($end);
1241                }
1242
1243                function fix_update_time(&$time_param)
1244                {
1245                        if (isset($time_param['str']))
1246                        {
1247                                if (!is_object($this->jscal))
1248                                {
1249                                        $this->jscal = CreateObject('phpgwapi.jscalendar');
1250                                }
1251                                $time_param += $this->jscal->input2date($time_param['str'],False,'mday');
1252                                unset($time_param['str']);
1253                        }
1254                        if ($this->prefs['common']['timeformat'] == '12')
1255                        {
1256                                if ($time_param['ampm'] == 'pm')
1257                                {
1258                                        if ($time_param['hour'] <> 12)
1259                                        {
1260                                                $time_param['hour'] += 12;
1261                                        }
1262                                }
1263                                elseif ($time_param['ampm'] == 'am')
1264                                {
1265                                        if ($time_param['hour'] == 12)
1266                                        {
1267                                                $time_param['hour'] -= 12;
1268                                        }
1269                                }
1270
1271                                if($time_param['hour'] > 24)
1272                                {
1273                                        $time_param['hour'] -= 12;
1274                                }
1275                        }
1276                }
1277
1278                function validate_update($event)
1279                {
1280                        $error = 0;
1281                        // do a little form verifying
1282                        if (!count($event['participants']))
1283                        {
1284                                $error = 43;
1285                        }
1286                        elseif ($event['title'] == '')
1287                        {
1288                                $error = 40;
1289                        }
1290                        elseif (($GLOBALS['phpgw']->datetime->time_valid($event['start']['hour'],$event['start']['min'],0) == False) || ($GLOBALS['phpgw']->datetime->time_valid($event['end']['hour'],$event['end']['min'],0) == False))
1291                        {
1292                                $error = 41;
1293                        }
1294                        elseif (($GLOBALS['phpgw']->datetime->date_valid($event['start']['year'],$event['start']['month'],$event['start']['mday']) == False) || ($GLOBALS['phpgw']->datetime->date_valid($event['end']['year'],$event['end']['month'],$event['end']['mday']) == False) || ($GLOBALS['phpgw']->datetime->date_compare($event['start']['year'],$event['start']['month'],$event['start']['mday'],$event['end']['year'],$event['end']['month'],$event['end']['mday']) == 1))
1295                        {
1296                                $error = 42;
1297                        }
1298                        elseif ($GLOBALS['phpgw']->datetime->date_compare($event['start']['year'],$event['start']['month'],$event['start']['mday'],$event['end']['year'],$event['end']['month'],$event['end']['mday']) == 0)
1299                        {
1300                                if ($GLOBALS['phpgw']->datetime->time_compare($event['start']['hour'],$event['start']['min'],0,$event['end']['hour'],$event['end']['min'],0) == 1)
1301                                {
1302                                        $error = 42;
1303                                }
1304                        }
1305                        return $error;
1306                }
1307
1308                /*!
1309                @function participants_not_rejected($participants,$event)
1310                @abstract checks if any of the $particpants participates in $event and has not rejected it
1311                */
1312                function participants_not_rejected($participants,$event)
1313                {
1314                        //echo "participants_not_rejected()<br>participants =<pre>"; print_r($participants); echo "</pre><br>event[participants]=<pre>"; print_r($event['participants']); echo "</pre>\n";
1315                        foreach($participants as $uid => $status)
1316                        {
1317                                //echo "testing event[participants][uid=$uid] = '".$event['participants'][$uid]."'<br>\n";
1318                                if (isset($event['participants'][$uid]) && $event['participants'][$uid] != 'R' &&
1319                                        $status != 'R')
1320                                {
1321                                        return True;    // found not rejected participant in event
1322                                }
1323                        }
1324                        return False;
1325                }
1326
1327                function overlap($starttime,$endtime,$participants,$owner=0,$id=0,$restore_cache=False)
1328                {
1329//                      $retval = Array();
1330//                      $ok = False;
1331
1332/* This needs some attention.. by commenting this chunk of code it will fix bug #444265 */
1333
1334                        if($restore_cache)
1335                        {
1336                                $temp_cache_events = $this->cached_events;
1337                        }
1338
1339//                      $temp_start = (int)$GLOBALS['phpgw']->common->show_date($starttime,'Ymd');
1340//                      $temp_start_time = (int)($GLOBALS['phpgw']->common->show_date($starttime,'Hi');
1341//                      $temp_end = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Ymd');
1342//                      $temp_end_time = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Hi');
1343                        $temp_start = (int)(date('Ymd',$starttime));
1344                        $temp_start_time = (int)(date('Hi',$starttime));
1345                        $temp_end = (int)(date('Ymd',$endtime));
1346                        $temp_end_time = (int)(date('Hi',$endtime));
1347                        if($this->debug)
1348                        {
1349                                echo '<!-- Temp_Start: '.$temp_start.' -->'."\n";
1350                                echo '<!-- Temp_End: '.$temp_end.' -->'."\n";
1351                        }
1352
1353                        $users = Array();
1354                        if(count($participants))
1355                        {
1356                                while(list($user,$status) = each($participants))
1357                                {
1358                                        $users[] = $user;
1359                                }
1360                        }
1361                        else
1362                        {
1363                                $users[] = $this->owner;
1364                        }
1365
1366                        $possible_conflicts = $this->store_to_cache(
1367                                Array(
1368                                        'smonth'        => substr(strval($temp_start),4,2),
1369                                        'sday'  => substr(strval($temp_start),6,2),
1370                                        'syear' => substr(strval($temp_start),0,4),
1371                                        'emonth'        => substr(strval($temp_end),4,2),
1372                                        'eday'  => substr(strval($temp_end),6,2),
1373                                        'eyear' => substr(strval($temp_end),0,4),
1374                                        'owner' => $users
1375                                )
1376                        );
1377
1378                        if($this->debug)
1379                        {
1380                                echo '<!-- Possible Conflicts ('.($temp_start - 1).'): '.count($possible_conflicts[$temp_start - 1]).' -->'."\n";
1381                                echo '<!-- Possible Conflicts ('.$temp_start.'): '.count($possible_conflicts[$temp_start]).' '.count($id).' -->'."\n";
1382                        }
1383
1384                        if($possible_conflicts[$temp_start] || $possible_conflicts[$temp_end])
1385                        {
1386                                if($temp_start == $temp_end)
1387                                {
1388                                        if($this->debug)
1389                                        {
1390                                                echo '<!-- Temp_Start == Temp_End -->'."\n";
1391                                        }
1392                                        @reset($possible_conflicts[$temp_start]);
1393                                        while(list($key,$event) = each($possible_conflicts[$temp_start]))
1394                                        {
1395                                                $found = False;
1396                                                if($id)
1397                                                {
1398                                                        @reset($id);
1399                                                        while(list($key,$event_id) = each($id))
1400                                                        {
1401                                                                if($this->debug)
1402                                                                {
1403                                                                        echo '<!-- $id['.$key.'] = '.$id[$key].' = '.$event_id.' -->'."\n";
1404                                                                        echo '<!-- '.$event['id'].' == '.$event_id.' -->'."\n";
1405                                                                }
1406                                                                if($event['id'] == $event_id)
1407                                                                {
1408                                                                        $found = True;
1409                                                                }
1410                                                        }
1411                                                }
1412                                                if($this->debug)
1413                                                {
1414                                                        echo '<!-- Item found: '.$found.' -->'."<br>\n";
1415                                                }
1416                                                if(!$found)
1417                                                {
1418                                                        if($this->debug)
1419                                                        {
1420                                                                echo '<!-- Checking event id #'.$event['id'];
1421                                                        }
1422                                                        $temp_event_start = sprintf("%d%02d",$event['start']['hour'],$event['start']['min']);
1423                                                        $temp_event_end = sprintf("%d%02d",$event['end']['hour'],$event['end']['min']);
1424//                                                      if((($temp_start_time <= $temp_event_start) && ($temp_end_time >= $temp_event_start) && ($temp_end_time <= $temp_event_end)) ||
1425                                                        if(($temp_start_time <= $temp_event_start &&
1426                                                                $temp_end_time > $temp_event_start &&
1427                                                                $temp_end_time <= $temp_event_end ||
1428                                                                $temp_start_time >= $temp_event_start &&
1429                                                                $temp_start_time < $temp_event_end &&
1430                                                                $temp_end_time >= $temp_event_end ||
1431                                                                $temp_start_time <= $temp_event_start &&
1432                                                                $temp_end_time >= $temp_event_end ||
1433                                                                $temp_start_time >= $temp_event_start &&
1434                                                                $temp_end_time <= $temp_event_end) &&
1435                                                                $this->participants_not_rejected($participants,$event))
1436                                                        {
1437                                                                if($this->debug)
1438                                                                {
1439                                                                        echo ' Conflicts';
1440                                                                }
1441                                                                $retval[] = $event['id'];
1442                                                        }
1443                                                        if($this->debug)
1444                                                        {
1445                                                                echo ' -->'."\n";
1446                                                        }
1447                                                }
1448                                        }
1449                                }
1450                        }
1451                        else
1452                        {
1453                                $retval = False;
1454                        }
1455
1456                        if($restore_cache)
1457                        {
1458                                $this->cached_events = $temp_cache_events;
1459                        }
1460
1461                        return $retval;
1462                }
1463
1464                /*!
1465                @function check_perms( )
1466                @syntax check_perms($needed,$event=0,$other=0)
1467                @abstract Checks if the current user has the necessary ACL rights
1468                @author ralfbecker
1469                @discussion The check is performed on an event or general on the cal of an other user
1470                @param $needed necessary ACL right: PHPGW_ACL_{READ|EDIT|DELETE}
1471                @param $event event as array or the event-id or 0 for general check
1472                @param $other uid to check (if event==0) or 0 to check against $this->owner
1473                @note Participating in an event is considered as haveing read-access on that event, \
1474                        even if you have no general read-grant from that user.
1475                */
1476                function check_perms($needed,$event=0,$other=0)
1477                {
1478                        $event_in = $event;
1479                        if (is_int($event) && $event == 0)
1480                        {
1481                                $owner = $other > 0 ? $other : $this->owner;
1482                        }
1483                        else
1484                        {
1485                                if (!is_array($event))
1486                                {
1487                                        $event = $this->so->read_entry((int) $event);
1488                                }
1489                                if (!is_array($event))
1490                                {
1491                                        if ($this->xmlrpc)
1492                                        {
1493                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['not_exist'],$GLOBALS['xmlrpcstr']['not_exist']);
1494                                        }
1495                                        return False;
1496                                }
1497                                $owner = $event['owner'];
1498                                $private = $event['public'] == False || $event['public'] == 0;
1499                        }
1500                        $user = $GLOBALS['phpgw_info']['user']['account_id'];
1501                        $grants = $this->grants[$owner];
1502
1503                        if (is_array($event) && $needed == PHPGW_ACL_READ)
1504                        {
1505                                // Check if the $user is one of the participants or has a read-grant from one of them
1506                                //
1507                                foreach($event['participants'] as $uid => $accept)
1508                                {
1509                                        if ($this->grants[$uid] & PHPGW_ACL_READ || $uid == $user)
1510                                        {
1511                                                $grants |= PHPGW_ACL_READ;
1512                                                break;
1513                                        }
1514                                }
1515                        }
1516
1517                        if ($GLOBALS['phpgw']->accounts->get_type($owner) == 'g' && $needed == PHPGW_ACL_ADD)
1518                        {
1519                                $access = False;        // a group can't be the owner of an event
1520                        }
1521                        else
1522                        {
1523                                $access = $user == $owner || $grants & $needed && (!$private || $grants & PHPGW_ACL_PRIVATE);
1524                        }
1525                        //echo "<p>".function_backtrace()." check_perms($needed,$event_id,$other) for user $user and needed_acl $needed: event='$event[title]': owner=$owner, private=$private, grants=$grants ==> access=$access</p>\n";
1526
1527                        return $access;
1528                }
1529
1530
1531                function display_status($user_status)
1532                {
1533                        if(@$this->prefs['calendar']['display_status'] && $user_status)
1534                        {
1535                                $user_status = substr($this->get_long_status($user_status),0,1);
1536
1537                                return ' ('.$user_status.')';
1538                        }
1539                        else
1540                        {
1541                                return '';
1542                        }
1543                }
1544
1545                function get_long_status($status_short)
1546                {
1547                        switch ($status_short)
1548                        {
1549                                case 'A':
1550                                        $status = lang('Accepted');
1551                                        break;
1552                                case 'R':
1553                                        $status = lang('Rejected');
1554                                        break;
1555                                case 'T':
1556                                        $status = lang('Tentative');
1557                                        break;
1558                                case 'U':
1559                                        $status = lang('No Response');
1560                                        break;
1561                        }
1562                        return $status;
1563                }
1564
1565                function is_private($event,$owner)
1566                {
1567                        if($owner == 0)
1568                        {
1569                                $owner = $this->owner;
1570                        }
1571                        if ($owner == $GLOBALS['phpgw_info']['user']['account_id'] || ($event['public']==1) || ($this->check_perms(PHPGW_ACL_PRIVATE,$event) && $event['public']==0) || $event['owner'] == $GLOBALS['phpgw_info']['user']['account_id'])
1572                        {
1573                                return False;
1574                        }
1575                        elseif($event['public'] == 0)
1576                        {
1577                                return True;
1578                        }
1579                        elseif($event['public'] == 2)
1580                        {
1581                                $is_private = True;
1582                                $groups = $GLOBALS['phpgw']->accounts->membership($owner);
1583                                while (list($key,$group) = each($groups))
1584                                {
1585                                        if (strpos(' '.implode(',',$event['groups']).' ',$group['account_id']))
1586                                        {
1587                                                return False;
1588                                        }
1589                                }
1590                        }
1591                        else
1592                        {
1593                                return False;
1594                        }
1595
1596                        return $is_private;
1597                }
1598
1599                function get_short_field($event,$is_private=True,$field='')
1600                {
1601                        if($is_private)
1602                        {
1603                                return 'private';
1604                        }
1605
1606// cut off too long titles
1607                        elseif(strlen($event[$field]) > 19 && !$this->printer_friendly && $field=="title")
1608//                      elseif(strlen($event[$field]) > 19 && $this->printer_friendly)
1609                        {
1610// we dont use currently 160304
1611//                              return substr($event[$field], 0 , 19) . '&nbsp;...';
1612                                return $event[$field];
1613                        }
1614                        else
1615                        {
1616                                return $event[$field];
1617                        }
1618                }
1619
1620                function long_date($first,$last=0)
1621                {
1622                        if (!is_array($first))
1623                        {
1624                                $first = $this->time2array($raw = $first);
1625                                $first['raw'] = $raw;
1626                                $first['day'] = $first['mday'];
1627                        }
1628                        if ($last && !is_array($last))
1629                        {
1630                                $last = $this->time2array($raw = $last);
1631                                $last['raw'] = $raw;
1632                                $last['day'] = $last['mday'];
1633                        }
1634                        $datefmt = $this->prefs['common']['dateformat'];
1635
1636                        $month_before_day = strtolower($datefmt[0]) == 'm' ||
1637                                strtolower($datefmt[2]) == 'm' && $datefmt[4] == 'd';
1638
1639                        for ($i = 0; $i < 5; $i += 2)
1640                        {
1641                                switch($datefmt[$i])
1642                                {
1643                                        case 'd':
1644                                                $range .= $first['day'] . ($datefmt[1] == '.' ? '.' : '');
1645                                                if ($first['month'] != $last['month'] || $first['year'] != $last['year'])
1646                                                {
1647                                                        if (!$month_before_day)
1648                                                        {
1649                                                                $range .= ' '.lang(strftime('%B',$first['raw']));
1650                                                        }
1651                                                        if ($first['year'] != $last['year'] && $datefmt[0] != 'Y')
1652                                                        {
1653                                                                $range .= ($datefmt[0] != 'd' ? ', ' : ' ') . $first['year'];
1654                                                        }
1655                                                        if (!$last)
1656                                                        {
1657                                                                return $range;
1658                                                        }
1659                                                        $range .= ' - ';
1660
1661                                                        if ($first['year'] != $last['year'] && $datefmt[0] == 'Y')
1662                                                        {
1663                                                                $range .= $last['year'] . ', ';
1664                                                        }
1665
1666                                                        if ($month_before_day)
1667                                                        {
1668                                                                $range .= lang(strftime('%B',$last['raw']));
1669                                                        }
1670                                                }
1671                                                else
1672                                                {
1673                                                        $range .= ' - ';
1674                                                }
1675                                                $range .= ' ' . $last['day'] . ($datefmt[1] == '.' ? '.' : '');
1676                                                break;
1677                                        case 'm':
1678                                        case 'M':
1679                                                $range .= ' '.lang(strftime('%B',$month_before_day ? $first['raw'] : $last['raw'])) . ' ';
1680                                                break;
1681                                        case 'Y':
1682                                                $range .= ($datefmt[0] == 'm' ? ', ' : ' ') . ($datefmt[0] == 'Y' ? $first['year'].($datefmt[2] == 'd' ? ', ' : ' ') : $last['year'].' ');
1683                                                break;
1684                                }
1685                        }
1686                        return $range;
1687                }
1688
1689                function get_week_label()
1690                {
1691                        $first = $GLOBALS['phpgw']->datetime->gmtdate($GLOBALS['phpgw']->datetime->get_weekday_start($this->year, $this->month, $this->day));
1692                        $last = $GLOBALS['phpgw']->datetime->gmtdate($first['raw'] + 518400);
1693
1694                        return ($this->long_date($first,$last));
1695                }
1696
1697                function normalizeminutes(&$minutes)
1698                {
1699                        $hour = 0;
1700                        $min = (int)$minutes;
1701                        if($min >= 60)
1702                        {
1703                                $hour += $min / 60;
1704                                $min %= 60;
1705                        }
1706                        settype($minutes,'integer');
1707                        $minutes = $min;
1708                        return $hour;
1709                }
1710
1711                function splittime($time,$follow_24_rule=True)
1712                {
1713                        $temp = array('hour','minute','second','ampm');
1714                        $time = strrev($time);
1715                        $second = (int)(strrev(substr($time,0,2)));
1716                        $minute = (int)(strrev(substr($time,2,2)));
1717                        $hour   = (int)(strrev(substr($time,4)));
1718                        $hour += $this->normalizeminutes($minute);
1719                        $temp['second'] = $second;
1720                        $temp['minute'] = $minute;
1721                        $temp['hour']   = $hour;
1722                        $temp['ampm']   = '  ';
1723                        if($follow_24_rule == True)
1724                        {
1725                                if ($this->prefs['common']['timeformat'] == '24')
1726                                {
1727                                        return $temp;
1728                                }
1729
1730                                $temp['ampm'] = 'am';
1731
1732                                if ((int)$temp['hour'] > 12)
1733                                {
1734                                        $temp['hour'] = (int)((int)$temp['hour'] - 12);
1735                                        $temp['ampm'] = 'pm';
1736                                }
1737                                elseif ((int)$temp['hour'] == 12)
1738                                {
1739                                        $temp['ampm'] = 'pm';
1740                                }
1741                        }
1742                        return $temp;
1743                }
1744
1745                function get_exception_array($exception_str='')
1746                {
1747                        $exception = Array();
1748                        if(strpos(' '.$exception_str,','))
1749                        {
1750                                $exceptions = explode(',',$exception_str);
1751                                for($exception_count=0;$exception_count<count($exceptions);$exception_count++)
1752                                {
1753                                        $exception[] = (int)$exceptions[$exception_count];
1754                                }
1755                        }
1756                        elseif($exception_str != '')
1757                        {
1758                                $exception[] = (int)$exception_str;
1759                        }
1760                        return $exception;
1761                }
1762
1763                function build_time_for_display($fixed_time)
1764                {
1765                        $time = $this->splittime($fixed_time);
1766                        $str = $time['hour'].':'.((int)$time['minute']<=9?'0':'').$time['minute'];
1767
1768                        if ($this->prefs['common']['timeformat'] == '12')
1769                        {
1770                                $str .= ' ' . $time['ampm'];
1771                        }
1772
1773                        return $str;
1774                }
1775
1776                function sort_event($event,$date)
1777                {
1778                        $inserted = False;
1779                        if(isset($event['recur_exception']))
1780                        {
1781                                $event_time = mktime($event['start']['hour'],$event['start']['min'],0,(int)(substr($date,4,2)),(int)(substr($date,6,2)),(int)(substr($date,0,4))) - $GLOBALS['phpgw']->datetime->tz_offset;
1782                                while($inserted == False && list($key,$exception_time) = each($event['recur_exception']))
1783                                {
1784                                        if($this->debug)
1785                                        {
1786                                                echo '<!-- checking exception datetime '.$exception_time.' to event datetime '.$event_time.' -->'."\n";
1787                                        }
1788                                        if($exception_time == $event_time)
1789                                        {
1790                                                $inserted = True;
1791                                        }
1792                                }
1793                        }
1794                        if($this->cached_events[$date] && $inserted == False)
1795                        {
1796
1797                                if($this->debug)
1798                                {
1799                                        echo '<!-- Cached Events found for '.$date.' -->'."\n";
1800                                }
1801                                $year = substr($date,0,4);
1802                                $month = substr($date,4,2);
1803                                $day = substr($date,6,2);
1804
1805                                if($this->debug)
1806                                {
1807                                        echo '<!-- Date : '.$date.' Count : '.count($this->cached_events[$date]).' -->'."\n";
1808                                }
1809
1810                                for($i=0;$i<count($this->cached_events[$date]);$i++)
1811                                {
1812                                        if($this->cached_events[$date][$i]['id'] == $event['id'] || $this->cached_events[$date][$i]['reference'] == $event['id'])
1813                                        {
1814                                                if($this->debug)
1815                                                {
1816                                                        echo '<!-- Item already inserted! -->'."\n";
1817                                                }
1818                                                $inserted = True;
1819                                                break;
1820                                        }
1821                                        /* This puts all spanning events across multiple days up at the top. */
1822                                        if($this->cached_events[$date][$i]['recur_type'] == MCAL_RECUR_NONE)
1823                                        {
1824                                                if($this->cached_events[$date][$i]['start']['mday'] != $day && $this->cached_events[$date][$i]['end']['mday'] >= $day)
1825                                                {
1826                                                        continue;
1827                                                }
1828                                        }
1829                                        if(date('Hi',mktime($event['start']['hour'],$event['start']['min'],$event['start']['sec'],$month,$day,$year)) < date('Hi',mktime($this->cached_events[$date][$i]['start']['hour'],$this->cached_events[$date][$i]['start']['min'],$this->cached_events[$date][$i]['start']['sec'],$month,$day,$year)))
1830                                        {
1831                                                for($j=count($this->cached_events[$date]);$j>=$i;$j--)
1832                                                {
1833                                                        $this->cached_events[$date][$j] = $this->cached_events[$date][$j-1];
1834                                                }
1835                                                if($this->debug)
1836                                                {
1837                                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
1838                                                }
1839                                                $inserted = True;
1840                                                $this->cached_events[$date][$i] = $event;
1841                                                break;
1842                                        }
1843                                }
1844                        }
1845                        if(!$inserted)
1846                        {
1847                                if($this->debug)
1848                                {
1849                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
1850                                }
1851                                $this->cached_events[$date][] = $event;
1852                        }
1853                }
1854
1855                function check_repeating_events($datetime)
1856                {
1857                        @reset($this->repeating_events);
1858                        $search_date_full = date('Ymd',$datetime);
1859                        $search_date_year = date('Y',$datetime);
1860                        $search_date_month = date('m',$datetime);
1861                        $search_date_day = date('d',$datetime);
1862                        $search_date_dow = date('w',$datetime);
1863                        $search_beg_day = mktime(0,0,0,$search_date_month,$search_date_day,$search_date_year);
1864                        if($this->debug)
1865                        {
1866                                echo '<!-- Search Date Full = '.$search_date_full.' -->'."\n";
1867                        }
1868                        $repeated = $this->repeating_events;
1869                        $r_events = count($repeated);
1870                        for ($i=0;$i<$r_events;$i++)
1871                        {
1872                                $rep_events = $this->repeating_events[$i];
1873                                $id = $rep_events['id'];
1874                                $event_beg_day = mktime(0,0,0,$rep_events['start']['month'],$rep_events['start']['mday'],$rep_events['start']['year']);
1875                                if($rep_events['recur_enddate']['month'] != 0 && $rep_events['recur_enddate']['mday'] != 0 && $rep_events['recur_enddate']['year'] != 0)
1876                                {
1877                                        $event_recur_time = $this->maketime($rep_events['recur_enddate']);
1878                                }
1879                                else
1880                                {
1881                                        $event_recur_time = mktime(0,0,0,1,1,2030);
1882                                }
1883                                $end_recur_date = date('Ymd',$event_recur_time);
1884                                $full_event_date = date('Ymd',$event_beg_day);
1885
1886                                if($this->debug)
1887                                {
1888                                        echo '<!-- check_repeating_events - Processing ID - '.$id.' -->'."\n";
1889                                        echo '<!-- check_repeating_events - Recurring End Date - '.$end_recur_date.' -->'."\n";
1890                                }
1891
1892                                // only repeat after the beginning, and if there is an rpt_end before the end date
1893                                if (($search_date_full > $end_recur_date) || ($search_date_full < $full_event_date))
1894                                {
1895                                        continue;
1896                                }
1897
1898                                if ($search_date_full == $full_event_date)
1899                                {
1900                                        $this->sort_event($rep_events,$search_date_full);
1901                                        continue;
1902                                }
1903                                else
1904                                {
1905                                        $freq = $rep_events['recur_interval'];
1906                                        $freq = $freq ? $freq : 1;
1907                                        $type = $rep_events['recur_type'];
1908                                        switch($type)
1909                                        {
1910                                                case MCAL_RECUR_DAILY:
1911                                                        if($this->debug)
1912                                                        {
1913                                                                echo '<!-- check_repeating_events - MCAL_RECUR_DAILY - '.$id.' -->'."\n";
1914                                                        }
1915                                                       
1916                                                        if ($freq == 1 && $rep_events['recur_enddate']['month'] != 0 && $rep_events['recur_enddate']['mday'] != 0 && $rep_events['recur_enddate']['year'] != 0 && $search_date_full <= $end_recur_date)
1917                                                        {
1918                                                                $this->sort_event($rep_events,$search_date_full);
1919                                                        }
1920                                                        elseif (floor(($search_beg_day - $event_beg_day)/86400) % ($freq ? $freq : 1))
1921                                                        {
1922                                                                continue;
1923                                                        }
1924                                                        else
1925                                                        {
1926                                                                $this->sort_event($rep_events,$search_date_full);
1927                                                        }
1928                                                        break;
1929                                                case MCAL_RECUR_WEEKLY:
1930                                                        if (floor(($search_beg_day - $event_beg_day)/604800)  % ($freq ? $freq : 1))
1931                                                        {
1932                                                                continue;
1933                                                        }
1934                                                        $check = 0;
1935                                                        switch($search_date_dow)
1936                                                        {
1937                                                                case 0:
1938                                                                        $check = MCAL_M_SUNDAY;
1939                                                                        break;
1940                                                                case 1:
1941                                                                        $check = MCAL_M_MONDAY;
1942                                                                        break;
1943                                                                case 2:
1944                                                                        $check = MCAL_M_TUESDAY;
1945                                                                        break;
1946                                                                case 3:
1947                                                                        $check = MCAL_M_WEDNESDAY;
1948                                                                        break;
1949                                                                case 4:
1950                                                                        $check = MCAL_M_THURSDAY;
1951                                                                        break;
1952                                                                case 5:
1953                                                                        $check = MCAL_M_FRIDAY;
1954                                                                        break;
1955                                                                case 6:
1956                                                                        $check = MCAL_M_SATURDAY;
1957                                                                        break;
1958                                                        }
1959                                                        if ($rep_events['recur_data'] & $check)
1960                                                        {
1961                                                                $this->sort_event($rep_events,$search_date_full);
1962                                                        }
1963                                                        break;
1964                                                case MCAL_RECUR_MONTHLY_WDAY:
1965                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month']) % $freq)
1966                                                        {
1967                                                                continue;
1968                                                        }
1969
1970                                                        if (($GLOBALS['phpgw']->datetime->day_of_week($rep_events['start']['year'],$rep_events['start']['month'],$rep_events['start']['mday']) == $GLOBALS['phpgw']->datetime->day_of_week($search_date_year,$search_date_month,$search_date_day)) &&
1971                                                                (ceil($rep_events['start']['mday']/7) == ceil($search_date_day/7)))
1972                                                        {
1973                                                                $this->sort_event($rep_events,$search_date_full);
1974                                                        }
1975                                                        break;
1976                                                case MCAL_RECUR_MONTHLY_MDAY:
1977                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month'])  % ($freq ? $freq : 1))
1978                                                        {
1979                                                                continue;
1980                                                        }
1981                                                        if ($search_date_day == $rep_events['start']['mday'])
1982                                                        {
1983                                                                $this->sort_event($rep_events,$search_date_full);
1984                                                        }
1985                                                        break;
1986                                                case MCAL_RECUR_YEARLY:
1987                                                        if (($search_date_year - $rep_events['start']['year']) % ($freq ? $freq : 1))
1988                                                        {
1989                                                                continue;
1990                                                        }
1991                                                        if (date('dm',$datetime) == date('dm',$event_beg_day))
1992                                                        {
1993                                                                $this->sort_event($rep_events,$search_date_full);
1994                                                        }
1995                                                        break;
1996                                        }
1997                                }
1998                        }       // end for loop
1999                }       // end function
2000
2001                function store_to_cache($params)
2002                {
2003                        if(!is_array($params))
2004                        {
2005                                return False;
2006                        }
2007                        if (isset($params['start']) && ($datearr = $GLOBALS['server']->iso86012date($params['start'])))
2008                        {
2009                                $syear = $datearr['year'];
2010                                $smonth = $datearr['month'];
2011                                $sday = $datearr['mday'];
2012                                $this->xmlrpc = True;
2013                        }
2014                        else
2015                        {
2016                                $syear = $params['syear'];
2017                                $smonth = $params['smonth'];
2018                                $sday = $params['sday'];
2019                        }
2020                        if (isset($params['end']) && ($datearr = $GLOBALS['server']->iso86012date($params['end'])))
2021                        {
2022                                $eyear = $datearr['year'];
2023                                $emonth = $datearr['month'];
2024                                $eday = $datearr['mday'];
2025                                $this->xmlrpc = True;
2026                        }
2027                        else
2028                        {
2029                                $eyear = (isset($params['eyear'])?$params['eyear']:0);
2030                                $emonth = (isset($params['emonth'])?$params['emonth']:0);
2031                                $eday = (isset($params['eday'])?$params['eday']:0);
2032                        }
2033                        if (!isset($params['owner']) && @$this->xmlrpc)
2034                        {
2035                                $owner_id = $GLOBALS['phpgw_info']['user']['user_id'];
2036                        }
2037                        else
2038                        {
2039                                $owner_id = (isset($params['owner'])?$params['owner']:0);
2040                                if($owner_id==0 && $this->is_group)
2041                                {
2042                                        unset($owner_id);
2043                                        $owner_id = $this->g_owner;
2044                                        if($this->debug)
2045                                        {
2046                                                echo '<!-- owner_id in ('.implode(',',$owner_id).') -->'."\n";
2047                                        }
2048                                }
2049                        }
2050                        if(!$eyear && !$emonth && !$eday)
2051                        {
2052                                $edate = mktime(23,59,59,$smonth + 1,$sday + 1,$syear);
2053                                $eyear = date('Y',$edate);
2054                                $emonth = date('m',$edate);
2055                                $eday = date('d',$edate);
2056                        }
2057                        else
2058                        {
2059                                if(!$eyear)
2060                                {
2061                                        $eyear = $syear;
2062                                }
2063                                if(!$emonth)
2064                                {
2065                                        $emonth = $smonth + 1;
2066                                        if($emonth > 12)
2067                                        {
2068                                                $emonth = 1;
2069                                                $eyear++;
2070                                        }
2071                                }
2072                                if(!$eday)
2073                                {
2074                                        $eday = $sday + 1;
2075                                }
2076                                $edate = mktime(23,59,59,$emonth,$eday,$eyear);
2077                        }
2078                        //echo "<p>bocalendar::store_to_cache(".print_r($params,True).") syear=$syear, smonth=$smonth, sday=$sday, eyear=$eyear, emonth=$emonth, eday=$eday, xmlrpc='$param[xmlrpc]'</p>\n";
2079                        if($this->debug)
2080                        {
2081                                echo '<!-- Start Date : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2082                                echo '<!-- End   Date : '.sprintf("%04d%02d%02d",$eyear,$emonth,$eday).' -->'."\n";
2083                        }
2084
2085                        if($owner_id)
2086                        {
2087                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2088                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2089                        }
2090                        else
2091                        {
2092                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2093                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2094                        }
2095
2096                        $c_cached_ids = count($cached_event_ids);
2097                        $c_cached_ids_repeating = count($cached_event_ids_repeating);
2098
2099                        if($this->debug)
2100                        {
2101                                echo '<!-- events cached : '.$c_cached_ids.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2102                                echo '<!-- repeating events cached : '.$c_cached_ids_repeating.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2103                        }
2104
2105                        $this->cached_events = Array();
2106
2107                        if($c_cached_ids == 0 && $c_cached_ids_repeating == 0)
2108                        {
2109                                return;
2110                        }
2111
2112                        $cache_start = (int)(sprintf("%04d%02d%02d",$syear,$smonth,$sday));
2113                        $cached_event=$this->get_cached_event();
2114                        if($c_cached_ids)
2115                        {
2116                                for($i=0;$i<$c_cached_ids;$i++)
2117                                {
2118                                        $event = $this->so->read_entry($cached_event_ids[$i]);
2119                                        if ($event['recur_type'])
2120                                        {
2121                                                continue;       // fetch recuring events only in 2. loop
2122                                        }
2123                                        $startdate = (int)(date('Ymd',$this->maketime($event['start'])));
2124                                        $enddate = (int)(date('Ymd',$this->maketime($event['end'])));
2125                                        $this->cached_events[$startdate][] = $event;
2126                                        if($startdate != $enddate)
2127                                        {
2128                                                $start['year'] = (int)(substr($startdate,0,4));
2129                                                $start['month'] = (int)(substr($startdate,4,2));
2130                                                $start['mday'] = (int)(substr($startdate,6,2));
2131                                                for($j=$startdate,$k=0;$j<=$enddate;$k++,$j=(int)(date('Ymd',mktime(0,0,0,$start['month'],$start['mday'] + $k,$start['year']))))
2132                                                {
2133                                                        $c_evt_day = count($this->cached_events[$j]) - 1;
2134                                                        if($c_evt_day < 0)
2135                                                        {
2136                                                                $c_evt_day = 0;
2137                                                        }
2138                                                        if($this->debug)
2139                                                        {
2140                                                                echo '<!-- Date: '.$j.' Count : '.$c_evt_day.' -->'."\n";
2141                                                        }
2142                                                        if($this->cached_events[$j][$c_evt_day]['id'] != $event['id'])
2143                                                        {
2144                                                                if($this->debug)
2145                                                                {
2146                                                                        echo '<!-- Adding Event for Date: '.$j.' -->'."\n";
2147                                                                }
2148                                                                $this->cached_events[$j][] = $event;
2149                                                        }
2150                                                        if ($j >= $cache_start && (@$params['no_doubles'] || @$this->xmlrpc))
2151                                                        {
2152                                                                break;  // add event only once on it's startdate
2153                                                        }
2154                                                }
2155                                        }
2156                                }
2157                        }
2158
2159                        $this->repeating_events = Array();
2160                        if($c_cached_ids_repeating)
2161                        {
2162                                for($i=0;$i<$c_cached_ids_repeating;$i++)
2163                                {
2164                                        $this->repeating_events[$i] = $this->so->read_entry($cached_event_ids_repeating[$i]);
2165                                        if($this->debug)
2166                                        {
2167                                                echo '<!-- Cached Events ID: '.$cached_event_ids_repeating[$i].' ('.sprintf("%04d%02d%02d",$this->repeating_events[$i]['start']['year'],$this->repeating_events[$i]['start']['month'],$this->repeating_events[$i]['start']['mday']).') -->'."\n";
2168                                        }
2169                                }
2170                                for($date=mktime(0,0,0,$smonth,$sday,$syear);$date<=$edate;$date += 86400)
2171                                {
2172                                        if($this->debug)
2173                                        {
2174                                                $search_date = date('Ymd',$date);
2175                                                echo '<!-- Calling check_repeating_events('.$search_date.') -->'."\n";
2176                                        }
2177                                        $this->check_repeating_events($date);
2178                                        if($this->debug)
2179                                        {
2180                                                echo '<!-- Total events found matching '.$search_date.' = '.count($this->cached_events[$search_date]).' -->'."\n";
2181                                                for($i=0;$i<count($this->cached_events[$search_date]);$i++)
2182                                                {
2183                                                        echo '<!-- Date: '.$search_date.' ['.$i.'] = '.$this->cached_events[$search_date][$i]['id'].' -->'."\n";
2184                                                }
2185                                        }
2186                                }
2187                        }
2188                        $retval = Array();
2189                        for($j=date('Ymd',mktime(0,0,0,$smonth,$sday,$syear)),$k=0;$j<=date('Ymd',mktime(0,0,0,$emonth,$eday,$eyear));$k++,$j=date('Ymd',mktime(0,0,0,$smonth,$sday + $k,$syear)))
2190                        {
2191                                if(is_array($this->cached_events[$j]))
2192                                {
2193                                        if ($this->xmlrpc)
2194                                        {
2195                                                foreach($this->cached_events[$j] as $event)
2196                                                {
2197                                                        $retval[] = $this->xmlrpc_prepare($event);
2198                                                }
2199                                        }
2200                                        else
2201                                        {
2202                                                $retval[$j] = $this->cached_events[$j];
2203                                        }
2204                                }
2205                        }
2206                        //echo "store_to_cache(".print_r($params,True).")=<pre>".print_r($retval,True)."</pre>\n";
2207                        $this->so->cal->event = $cached_event;
2208                        return $retval;
2209                }
2210
2211                function xmlrpc_prepare(&$event)
2212                {
2213                        $event['rights'] = $this->grants[$event['owner']];
2214
2215                        foreach(array('start','end','modtime','recur_enddate') as $name)
2216                        {
2217                                if (isset($event[$name]))
2218                                {
2219                                        $event[$name] = $GLOBALS['server']->date2iso8601($event[$name]);
2220                                }
2221                        }
2222                        if (is_array($event['recur_exception']))
2223                        {
2224                                foreach($event['recur_exception'] as $key => $timestamp)
2225                                {
2226                                        $event['recur_exception'][$key] = $GLOBALS['server']->date2iso8601($timestamp);
2227                                }
2228                        }
2229                        static $user_cache = array();
2230
2231                        if (!is_object($GLOBALS['phpgw']->perferences))
2232                        {
2233                                $GLOBALS['phpgw']->perferences = CreateObject('phpgwapi.preferences');
2234                        }
2235                        foreach($event['participants'] as $user_id => $status)
2236                        {
2237                                if (!isset($user_cache[$user_id]))
2238                                {
2239                                        $user_cache[$user_id] = array(
2240                                                'name'   => $GLOBALS['phpgw']->common->grab_owner_name($user_id),
2241                                                'email'  => $GLOBALS['phpgw']->perferences->email_address($user_id)
2242                                        );
2243                                }
2244                                $event['participants'][$user_id] = $user_cache[$user_id] + array(
2245                                        'status' => $status,
2246                                );
2247                        }
2248                        if (is_array($event['alarm']))
2249                        {
2250                                foreach($event['alarm'] as $id => $alarm)
2251                                {
2252                                        $event['alarm'][$id]['time'] = $GLOBALS['server']->date2iso8601($alarm['time']);
2253                                        if ($alarm['owner'] != $GLOBALS['phpgw_info']['user']['account_id'])
2254                                        {
2255                                                unset($event['alarm'][$id]);
2256                                        }
2257                                }
2258                        }
2259                        $event['category'] = $GLOBALS['server']->cats2xmlrpc(explode(',',$event['category']));
2260
2261                        // using access={public|privat} in all modules via xmlrpc
2262                        $event['access'] = $event['public'] ? 'public' : 'privat';
2263                        unset($event['public']);
2264
2265                        return $event;
2266                }
2267
2268                /* Begin Appsession Data */
2269                function store_to_appsession($event)
2270                {
2271                        $GLOBALS['phpgw']->session->appsession('entry','calendar',$event);
2272                }
2273
2274                function restore_from_appsession()
2275                {
2276                        $this->event_init();
2277                        $event = $GLOBALS['phpgw']->session->appsession('entry','calendar');
2278                        $this->so->cal->event = $event;
2279                        return $event;
2280                }
2281                /* End Appsession Data */
2282
2283                /* Begin of SO functions */
2284                function get_cached_event()
2285                {
2286                        return $this->so->get_cached_event();
2287                }
2288
2289                function add_attribute($var,$value,$index='**(**')
2290                {
2291                        $this->so->add_attribute($var,$value,$index);
2292                }
2293
2294                function event_init()
2295                {
2296                        $this->so->event_init();
2297                }
2298
2299                function set_start($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2300                {
2301                        $this->so->set_start($year,$month,$day,$hour,$min,$sec);
2302                }
2303
2304                function set_end($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2305                {
2306                        $this->so->set_end($year,$month,$day,$hour,$min,$sec);
2307                }
2308
2309                function set_title($title='')
2310                {
2311                        $this->so->set_title($title);
2312                }
2313
2314                function set_description($description='')
2315                {
2316                        $this->so->set_description($description);
2317                }
2318                function set_ex_participants($ex_participants='')
2319                {
2320                        $this->so->set_ex_participants($ex_participants);
2321                }
2322
2323                function set_class($class)
2324                {
2325                        $this->so->set_class($class);
2326                }
2327
2328                function set_category($category='')
2329                {
2330                        $this->so->set_category($category);
2331                }
2332
2333                function set_alarm($alarm)
2334                {
2335                        $this->so->set_alarm($alarm);
2336                }
2337
2338                function set_recur_none()
2339                {
2340                        $this->so->set_recur_none();
2341                }
2342
2343                function set_recur_daily($year,$month,$day,$interval)
2344                {
2345                        $this->so->set_recur_daily($year,$month,$day,$interval);
2346                }
2347
2348                function set_recur_weekly($year,$month,$day,$interval,$weekdays)
2349                {
2350                        $this->so->set_recur_weekly($year,$month,$day,$interval,$weekdays);
2351                }
2352
2353                function set_recur_monthly_mday($year,$month,$day,$interval)
2354                {
2355                        $this->so->set_recur_monthly_mday($year,$month,$day,$interval);
2356                }
2357
2358                function set_recur_monthly_wday($year,$month,$day,$interval)
2359                {
2360                        $this->so->set_recur_monthly_wday($year,$month,$day,$interval);
2361                }
2362
2363                function set_recur_yearly($year,$month,$day,$interval)
2364                {
2365                        $this->so->set_recur_yearly($year,$month,$day,$interval);
2366                }
2367                /* End of SO functions */
2368
2369                function prepare_matrix($interval,$increment,$part,$fulldate)
2370                {
2371                        for($h=0;$h<24;$h++)
2372                        {
2373                                for($m=0;$m<$interval;$m++)
2374                                {
2375                                        $index = (($h * 10000) + (($m * $increment) * 100));
2376                                        $time_slice[$index]['marker'] = '&nbsp';
2377                                        $time_slice[$index]['description'] = '';
2378                                }
2379                        }
2380                        foreach($this->cached_events[$fulldate] as $event)
2381                        {
2382                                if ($event['participants'][$part] == 'R')
2383                                {
2384                                        continue;       // dont show rejected invitations, as they are free time
2385                                }
2386                                $eventstart = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset);
2387                                $eventend = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset);
2388                                $start = ($eventstart['hour'] * 10000) + ($eventstart['minute'] * 100);
2389                                $starttemp = $this->splittime("$start",False);
2390                                $subminute = 0;
2391                                for($m=0;$m<$interval;$m++)
2392                                {
2393                                        $minutes = $increment * $m;
2394                                        if((int)$starttemp['minute'] > $minutes && (int)$starttemp['minute'] < ($minutes + $increment))
2395                                        {
2396                                                $subminute = ($starttemp['minute'] - $minutes) * 100;
2397                                        }
2398                                }
2399                                $start -= $subminute;
2400                                $end =  ($eventend['hour'] * 10000) + ($eventend['minute'] * 100);
2401                                $endtemp = $this->splittime("$end",False);
2402                                $addminute = 0;
2403                                for($m=0;$m<$interval;$m++)
2404                                {
2405                                        $minutes = ($increment * $m);
2406                                        if($endtemp['minute'] < ($minutes + $increment) && $endtemp['minute'] > $minutes)
2407                                        {
2408                                                $addminute = ($minutes + $increment - $endtemp['minute']) * 100;
2409                                        }
2410                                }
2411                                $end += $addminute;
2412                                $starttemp = $this->splittime("$start",False);
2413                                $endtemp = $this->splittime("$end",False);
2414
2415                                for($h=$starttemp['hour'];$h<=$endtemp['hour'];$h++)
2416                                {
2417                                        $startminute = 0;
2418                                        $endminute = $interval;
2419                                        $hour = $h * 10000;
2420                                        if($h == (int)$starttemp['hour'])
2421                                        {
2422                                                $startminute = ($starttemp['minute'] / $increment);
2423                                        }
2424                                        if($h == (int)$endtemp['hour'])
2425                                        {
2426                                                $endminute = ($endtemp['minute'] / $increment);
2427                                        }
2428                                        $private = $this->is_private($event,$part);
2429                                        $time_display = $GLOBALS['phpgw']->common->show_date($eventstart['raw'],$this->users_timeformat).'-'.$GLOBALS['phpgw']->common->show_date($eventend['raw'],$this->users_timeformat);
2430                                        $time_description = '('.$time_display.') '.$this->get_short_field($event,$private,'title').$this->display_status($event['participants'][$part]);
2431                                        for($m=$startminute;$m<$endminute;$m++)
2432                                        {
2433                                                $index = ($hour + (($m * $increment) * 100));
2434                                                $time_slice[$index]['marker'] = '-';
2435                                                $time_slice[$index]['description'] = $time_description;
2436                                                $time_slice[$index]['id'] = $event['id'];
2437                                        }
2438                                }
2439                        }
2440                        return $time_slice;
2441                }
2442
2443                /*!
2444                @function set_status
2445                @abstract set the participant response $status for event $cal_id and notifies the owner of the event
2446                */
2447                function set_status($cal_id,$status)
2448                {
2449                        $status2msg = array(
2450                                REJECTED  => MSG_REJECTED,
2451                                TENTATIVE => MSG_TENTATIVE,
2452                                ACCEPTED  => MSG_ACCEPTED
2453                        );
2454                        if (!isset($status2msg[$status]))
2455                        {
2456                                return False;
2457                        }
2458                        $event = $this->so->read_entry($cal_id);
2459                        $account_id = $GLOBALS['phpgw_info']['user']['account_id'];
2460                        if(($status2msg[$status] == "5" && $event['participants'][$account_id] == "A") ||
2461                         ($status2msg[$status] == "3" && $event['participants'][$account_id] == "R")) {
2462                                return True;
2463                        }
2464                        $this->so->set_status($cal_id,$status);
2465                        $event = $this->so->read_entry($cal_id);
2466                        $this->send_update($status2msg[$status],$event['participants'],$event);
2467
2468                }
2469
2470                /*!
2471                @function update_requested
2472                @abstract checks if $userid has requested (in $part_prefs) updates for $msg_type
2473                @syntax update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2474                @param $userid numerical user-id
2475                @param $part_prefs preferces of the user $userid
2476                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2477                @param $old_event Event before the change
2478                @param $new_event Event after the change
2479                @returns 0 = no update requested, > 0 update requested
2480                */
2481                function update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2482                {
2483                        if ($msg_type == MSG_ALARM)
2484                        {
2485                                return True;    // always True for now
2486                        }
2487                        $want_update = 0;
2488
2489                        // the following switch fall-through all cases, as each included the following too
2490                        //
2491                        $msg_is_response = $msg_type == MSG_REJECTED || $msg_type == MSG_ACCEPTED || $msg_type == MSG_TENTATIVE;
2492
2493                        switch($ru = $part_prefs['calendar']['receive_updates'])
2494                        {
2495                                case 'responses':
2496                                        if ($msg_is_response)
2497                                        {
2498                                                ++$want_update;
2499                                        }
2500                                case 'modifications':
2501                                        if ($msg_type == MSG_MODIFIED)
2502                                        {
2503                                                ++$want_update;
2504                                        }
2505                                case 'time_change_4h':
2506                                case 'time_change':
2507                                        $diff = max(abs($this->maketime($old_event['start'])-$this->maketime($new_event['start'])),
2508                                                abs($this->maketime($old_event['end'])-$this->maketime($new_event['end'])));
2509                                        $check = $ru == 'time_change_4h' ? 4 * 60 * 60 - 1 : 0;
2510                                        if ($msg_type == MSG_MODIFIED && $diff > $check)
2511                                        {
2512                                                ++$want_update;
2513                                        }
2514                                case 'add_cancel':
2515                                        if ($old_event['owner'] == $userid && $msg_is_response ||
2516                                                $msg_type == MSG_DELETED || $msg_type == MSG_ADDED)
2517                                        {
2518                                                ++$want_update;
2519                                        }
2520                                        break;
2521                                case 'no':
2522                                        break;
2523                        }
2524                        //echo "<p>bocalendar::update_requested(user=$userid,pref=".$part_prefs['calendar']['receive_updates'] .",msg_type=$msg_type,".($old_event?$old_event['title']:'False').",".($old_event?$old_event['title']:'False').") = $want_update</p>\n";
2525                        return $want_update > 0;
2526                }
2527
2528        function create_vcard($event_array)
2529        {
2530        if(!$event_array)
2531                return null;
2532        $tmpattach="BEGIN:VCALENDAR\n"
2533        ."PRODID:-//Expresso Livre//Calendar//EN\n"
2534        ."VERSION:1.0\n";
2535                foreach ($event_array as $event)
2536                {
2537                        // It translates int to string
2538                        if (!is_object($event)  || !is_array($event) || !array_key_exists  ('end', $event))
2539                                $event = $event_array;
2540                        if ( $event['end']['month'] < 10 )
2541                                $end_event_month="0".$event['end']['month'];
2542                        else
2543                                $end_event_month=$event['end']['month'];
2544                        if ( $event['start']['month'] < 10 )
2545                                $start_event_month="0".$event['start']['month'];
2546                        else
2547                                $start_event_month=$event['start']['month'];
2548                        if ( $event['end']['mday'] < 10 )
2549                                $end_event_day="0".$event['end']['mday'];
2550                        else
2551                                $end_event_day=$event['end']['mday'];
2552                        if ( $event['start']['mday'] < 10 )
2553                                $start_event_day="0".$event['start']['mday'];
2554                        else
2555                                $start_event_day=$event['start']['mday'];
2556                        if ( $event['start']['hour'] < 10)
2557                                $start_event_hour="0".$event['start']['hour'];
2558                        else
2559                                $start_event_hour=$event['start']['hour'];
2560                        if ( $event['end']['hour'] < 10)
2561                                $end_event_hour="0".$event['end']['hour'];
2562                        else
2563                                $end_event_hour=$event['end']['hour'];
2564                               
2565                        if ( $event['start']['min'] < 10)
2566                                $start_event_min="0".$event['start']['min'];
2567                        else
2568                                $start_event_min=$event['start']['min'];
2569                        if ( $event['end']['min'] < 10)
2570                                $end_event_min="0".$event['end']['min'];
2571                        else
2572                                $end_event_min=$event['end']['min'];   
2573               
2574
2575                        $tmpattach.="BEGIN:VEVENT\n"
2576                        ."DTSTART:".$event['start'][year].$start_event_month.$start_event_day."T".$start_event_hour.$start_event_min."00Z\n"
2577                        ."DTEND:".$event[end][year].$end_event_month.$end_event_day."T".$end_event_hour.$end_event_min."00Z\n"
2578                        ."UID:Expresso-".$event[id].$event[uid]."\n"
2579                        ."LAST-MODIFIED:".time()."\n"
2580                        ."DESCRIPTION:".$event[description]."\n"
2581                        ."SUMMARY:".$event[title]."\n"
2582                        ."LOCATION:".$event[location]."\n"
2583                        ."END:VEVENT"."\n";
2584                }
2585                        $tmpattach.="END:VCALENDAR\n";
2586                        return $tmpattach;
2587}
2588
2589                /*!
2590                @function send_update
2591                @abstract sends update-messages to certain participants of an event
2592                @syntax send_update($msg_type,$to_notify,$old_event,$new_event=False)
2593                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2594                @param $to_notify array with numerical user-ids as keys (!) (value is not used)
2595                @param $old_event Event before the change
2596                @param $new_event Event after the change
2597                */
2598                function send_update($msg_type,$to_notify,$old_event,$new_event=False,$user=False)
2599                {
2600                       
2601                        //echo "<p>bocalendar::send_update(type=$msg_type,to_notify="; print_r($to_notify); echo ", old_event="; print_r($old_event); echo ", new_event="; print_r($new_event); echo ", user=$user)</p>\n";
2602                        if (!is_array($to_notify))
2603                        {
2604                                $to_notify = array();
2605                        }
2606                        $owner = $old_event ? $old_event['owner'] : $new_event['owner'];
2607                        if ($owner && !isset($to_notify[$owner]) && $msg_type != MSG_ALARM)
2608                        {
2609                                $to_notify[$owner] = 'owner';   // always include the event-owner
2610                        }
2611                        $version = $GLOBALS['phpgw_info']['apps']['calendar']['version'];
2612
2613                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences();
2614                        $sender = $GLOBALS['phpgw_info']['user']['email'];
2615
2616                        $temp_tz_offset = $this->prefs['common']['tz_offset'];
2617                        $temp_timeformat = $this->prefs['common']['timeformat'];
2618                        $temp_dateformat = $this->prefs['common']['dateformat'];
2619
2620                        $tz_offset = ((60 * 60) * (int)$temp_tz_offset);
2621
2622                        if($old_event != False)
2623                        {
2624                                $t_old_start_time = $this->maketime($old_event['start']);
2625                                if($t_old_start_time < (time() - 86400))
2626                                {
2627                                        return False;
2628                                }
2629                        }
2630
2631                        $temp_user = $GLOBALS['phpgw_info']['user'];
2632
2633                        if (!$user)
2634                        {
2635                                $user = $this->owner;
2636                        }
2637                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences($user);
2638
2639                        $event = $msg_type == MSG_ADDED || $msg_type == MSG_MODIFIED ? $new_event : $old_event;
2640                        if($old_event != False)
2641                        {
2642                                $old_starttime = $t_old_start_time - $GLOBALS['phpgw']->datetime->tz_offset;
2643                        }
2644                        $starttime = $this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
2645                        $endtime   = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
2646
2647                        switch($msg_type)
2648                        {
2649                                case MSG_DELETED:
2650                                        $action = lang('Canceled');
2651                                        $msg = 'Canceled';
2652                                        $msgtype = '"calendar";';
2653                                        $method = 'cancel';
2654                                        $typesend = 1;
2655                                        break;
2656                                case MSG_MODIFIED:
2657                                        $action = lang('Modified');
2658                                        $msg = 'Modified';
2659                                        $msgtype = '"calendar"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2660                                        $method = 'request';
2661                                        $typesend = 2;
2662                                        break;
2663                                case MSG_ADDED:
2664                                        $action = lang('Added');
2665                                        $msg = 'Added';
2666                                        $msgtype = '"calendar"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2667                                        $method = 'request';
2668                                        $typesend = 3;
2669                                        break;
2670                                case MSG_REJECTED:
2671                                        $action = lang('Rejected');
2672                                        $msg = 'Response';
2673                                        $msgtype = '"calendar";';
2674                                        $method = 'reply';
2675                                        $typesend = 4;
2676                                        break;
2677                                case MSG_TENTATIVE:
2678                                        $action = lang('Tentative');
2679                                        $msg = 'Response';
2680                                        $msgtype = '"calendar";';
2681                                        $method = 'reply';
2682                                        $typesend = 5;
2683                                        break;
2684                                case MSG_ACCEPTED:
2685                                        $action = lang('Accepted');
2686                                        $msg = 'Response';
2687                                        $msgtype = '"calendar";';
2688                                        $method = 'reply';
2689                                        $typesend = 6;
2690                                        break;
2691                                case MSG_ALARM:
2692                                        $action = lang('Alarm');
2693                                        $msg = 'Alarm';
2694                                        $msgtype = '"calendar";';
2695                                        $method = 'publish';    // duno if thats right
2696                                        $typesend = 7;
2697                                        break;
2698                                default:
2699                                        $method = 'publish';
2700                                        $typesend = 8;
2701                        }
2702                        $notify_msg = $this->prefs['calendar']['notify'.$msg];
2703                        if (empty($notify_msg))
2704                        {
2705                                $notify_msg = $this->prefs['calendar']['notifyAdded'];  // use a default
2706                        }
2707                        $details = array(                       // event-details for the notify-msg
2708                                'id'          => $msg_type == MSG_ADDED ? $new_event['id'] : $old_event['id'],
2709                                'action'      => $action,
2710                        );
2711                        $event_arr = $this->event2array($event);
2712                        foreach($event_arr as $key => $val)
2713                        {
2714                                $details[$key] = $val['data'];
2715                        }
2716                       
2717                        $details['participants'] = implode("\n",$details['participants']);
2718
2719                        $details['link'] = $GLOBALS['phpgw_info']['server']['webserver_url'].'/index.php?menuaction=calendar.uicalendar.view&cal_id='.$event['id'];
2720                        // if url is only a path, try guessing the rest ;-)
2721                        if ($GLOBALS['phpgw_info']['server']['webserver_url'][0] == '/')
2722                        {
2723                                $details['link'] = ($GLOBALS['phpgw_info']['server']['enforce_ssl'] ? 'https://' : 'http://').
2724                                        ($GLOBALS['phpgw_info']['server']['hostname'] ? $GLOBALS['phpgw_info']['server']['hostname'] : 'localhost').
2725                                        $details['link'];
2726                        }
2727                       
2728                        //Seta o email usando phpmailer
2729                        define('PHPGW_INCLUDE_ROOT','../');     
2730                        define('PHPGW_API_INC','../phpgwapi/inc');     
2731                        include_once(PHPGW_API_INC.'/class.phpmailer.inc.php');
2732                        $mail = new PHPMailer();
2733                        $mail->IsSMTP();
2734                        $boemailadmin = CreateObject('emailadmin.bo');
2735                        $emailadmin_profile = $boemailadmin->getProfileList();
2736                        $emailadmin = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
2737               
2738                        $mail->Host = $emailadmin['smtpServer'];
2739                        $mail->Port = $emailadmin['smtpPort'];
2740                        $mail->From = $GLOBALS['phpgw']->preferences->values['email'];
2741                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
2742                        $mail->IsHTML(true);
2743
2744                        // Aqui é enviado o email
2745                        foreach($to_notify as $userid => $statusid)
2746                        {
2747                                $mail->ClearAttachments();
2748                               
2749                                $userid = (int)$userid;
2750
2751                                if ($statusid == 'R' || $GLOBALS['phpgw']->accounts->get_type($userid) == 'g')
2752                                {
2753                                        continue;       // dont notify rejected participants
2754                                }
2755                                if($userid != $GLOBALS['phpgw_info']['user']['account_id'] ||  $msg_type == MSG_ALARM)
2756                                {
2757                                        print_debug('Msg Type',$msg_type);
2758                                        print_debug('UserID',$userid);
2759
2760                                        $preferences = CreateObject('phpgwapi.preferences',$userid);
2761                                        $part_prefs = $preferences->read_repository();
2762
2763                                        if (!$this->update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event))
2764                                        {
2765                                                continue;
2766                                        }
2767                                        $GLOBALS['phpgw']->accounts->get_account_name($userid,$lid,$details['to-firstname'],$details['to-lastname']);
2768                                        $details['to-fullname'] = $GLOBALS['phpgw']->common->display_fullname('',$details['to-firstname'],$details['to-lastname']);
2769
2770                                        $to = $preferences->email_address($userid);
2771                                       
2772                                        if (empty($to) || $to[0] == '@' || $to[0] == '$')       // we have no valid email-address
2773                                        {
2774                                                //echo "<p>bocalendar::send_update: Empty email adress for user '".$details['to-fullname']."' ==> ignored !!!</p>\n";
2775                                                continue;
2776                                        }
2777                                        print_debug('Email being sent to',$to);
2778
2779                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $part_prefs['common']['tz_offset'];
2780                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $part_prefs['common']['timeformat'];
2781                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $part_prefs['common']['dateformat'];
2782
2783                                        $GLOBALS['phpgw']->datetime->tz_offset = ((60 * 60) * (int)$GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset']);
2784
2785                                        if($old_starttime)
2786                                        {
2787                                                $details['olddate'] = $GLOBALS['phpgw']->common->show_date($old_starttime);
2788                                        }
2789                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
2790                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
2791                                       
2792                                       
2793                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
2794                                       
2795                                        switch($part_prefs['calendar']['update_format'])
2796                                        {
2797                                                case  'extended':
2798                                                        //$body .= "\n\n".lang('Event Details follow').":\n";
2799                                                        $body = '';
2800                                                        $body .= "<br>".lang('Event Details follow')." :: ";
2801                                                        foreach($event_arr as $key => $val)
2802                                                        {
2803                                                                // titulo
2804                                                                if($key =='title')
2805                                                                {
2806                                                                        $var1 = $val['field'];
2807                                                                        $vardata1 = $details[$key];
2808                                                                }
2809                                                                //descricao
2810                                                                if($key =='description')
2811                                                                {
2812                                                                        $var2 = $val['field'];
2813                                                                        $vardata2 = $details[$key];
2814                                                                }
2815                                                                //dt inicio
2816                                                                if($key =='startdate')
2817                                                                {
2818                                                                        switch(trim($part_prefs['common']['dateformat']))
2819                                                                        {
2820                                                                               
2821                                                                                case ($part_prefs['common']['dateformat'] === "m/d/Y" || $part_prefs['common']['dateformat'] === "m-d-Y" || $part_prefs['common']['dateformat'] === "m.d.Y"):
2822                                                                                        $var3 = $val['field'];
2823                                                                                        $vardata3 = $details[$key];
2824                                                                                        $newmounth3 = substr($vardata3,0,2);
2825                                                                                        $newday3 = substr($vardata3,3,2);
2826                                                                                        $newyear3 = substr($vardata3,6,4);
2827                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
2828                                                                                        break;
2829                                                                                       
2830                                                                                case    ($part_prefs['common']['dateformat'] === "Y/d/m" || $part_prefs['common']['dateformat'] === "Y-d-m" || $part_prefs['common']['dateformat'] === "Y.d.m"):
2831
2832                                                                                        $var3 = $val['field'];
2833                                                                                        $vardata3 = $details[$key];
2834                                                                                        $newyear3 = substr($vardata3,0,4);
2835                                                                                        $newday3 = substr($vardata3,5,2);
2836                                                                                        $newmounth3 = substr($vardata3,8,2);
2837                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
2838                                                                                        break;
2839
2840                                                                                case ($part_prefs['common']['dateformat'] === "Y/m/d" || $part_prefs['common']['dateformat'] === "Y-m-d" || $part_prefs['common']['dateformat'] === "Y.m.d"):
2841
2842                                                                                        $var3 = $val['field'];
2843                                                                                        $vardata3 = $details[$key];
2844                                                                                        $newyear3 = substr($vardata3,0,4);
2845                                                                                        $newmounth3 = substr($vardata3,5,2);
2846                                                                                        $newday3 = substr($vardata3,8,2);
2847                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
2848                                                                                        break;
2849
2850                                                                                case ($part_prefs['common']['dateformat'] === "d/m/Y" || $part_prefs['common']['dateformat'] === "d-m-Y" || $part_prefs['common']['dateformat'] === "d.m.Y" || $part_prefs['common']['dateformat'] === "d-M-Y"):
2851                                                                               
2852                                                                                        $var3 = $val['field'];
2853                                                                                        $vardata3 = $details[$key];
2854                                                                                        $newday3 = substr($vardata3,0,2);
2855                                                                                        $newmounth3 = substr($vardata3,3,2);
2856                                                                                        $newyear3 = substr($vardata3,6,4);
2857                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
2858                                                                                        break;
2859                                                                       
2860                                                                        }
2861                                                                       
2862                                                                }
2863                                                                //dt final
2864                                                                if($key =='enddate')
2865                                                                {
2866                                                                        $var4 = $val['field'];
2867                                                                        $vardata4 = $details[$key];
2868                                                                }
2869                                                                //localizacao
2870                                                                if($key =='location')
2871                                                                {
2872                                                                        $var8 = $val['field'];
2873                                                                        $vardata8 = $details[$key];
2874                                                                }
2875                                                                //participantes
2876                                                                if($key =='participants')
2877                                                                {
2878                                                                        $var5 = $val['field'];
2879                                                                        foreach($val['data'] as $NewKey => $NewVal)
2880                                                                        {
2881                                                                                //Research inside of ldap ( Pesquisa dentro do ldap )
2882                                                                                $newvalue = $this->so->search_uidNumber($to);
2883                                                                                foreach($newvalue as $tmp)
2884                                                                                {
2885                                                                                        $tmpmail = $tmp['mail'][0];
2886                                                                                        $tmpuid = $tmp['uidnumber'][0];
2887                                                                                        if( trim($tmpmail) == trim($to) & trim($tmpuid) == trim($NewKey))
2888                                                                                        {
2889                                                                                                        if($typesend == 3)
2890                                                                                                        {
2891
2892                                                                                                                $lang1 = lang("To See Commitment");
2893                                                                                                                $varbuttom = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.view&cal_id=$event[id]&date=$newall3' method='POST'>
2894                                                                                                                                                                  <input type='submit' value='$lang1'>
2895                                                                                                                                                                   </form>";
2896                                                                                                                $lang2 = lang("To accept");
2897                                                                                                                $varbuttom1 ="<input type='submit' value='$lang2' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=3&response=1\",\"frontpage\",\"height=100,width=400,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
2898
2899                                                                                                                $lang3 = lang("To reject");
2900                                                                                                                $varbuttom2 ="<input type='submit' value='$lang3' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=0&response=0\",\"frontpage\",\"height=100,width=400,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
2901                                                                                                               
2902                                                                                                                $lang4 = lang("Alarm");
2903                                                                                                                $varbuttom3 = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uialarm.manager method='POST'>
2904                                                                                                                                                                  <input type='submit' value='$lang4'>
2905                                                                                                                                                                  <input type='hidden' name='cal_id' value=$event[id]>
2906                                                                                                                                                                   </form>";
2907                                                                                                        }
2908                                                                                                        else
2909                                                                                                        {
2910                                                                                                                        $varbuttom  = "";
2911                                                                                                                        $varbuttom1 = "";
2912                                                                                                                        $varbuttom2 = "";
2913                                                                                                                        $varbuttom3 = "";
2914                                                                                                        }
2915                                                                                        }
2916                                                                                        // It only mounts variavel with the name of the participants of the list ( Monta a variavel somente com o nome dos participantes da lista)
2917                                                                                        if($typesend == 3)
2918                                                                                        {
2919                                                                                                list($tmpvardata5,$tmp2vardata5) = explode("(",$NewVal);
2920                                                                                                $vardata5 = $tmpvardata5."<br>";
2921                                                                                        }
2922                                                                                        else
2923                                                                                        {
2924                                                                                                $vardata5 = $NewVal."<br>";
2925                                                                                        }
2926                                                                               
2927                                                                                }
2928                                                                                $vardata6 .= $vardata5;
2929                                                                                unset($vardata5);
2930                                                                        }
2931                                                                }               
2932                                                        }
2933                                                        //To mount the message as text/html (Para montar a mensagem como text/html - /phpgwapi/inc/class.send.inc.php )
2934                                                        $content_type = "text/html";
2935                                                        //It mounts the body of the message (Monta o corpo da mensagem)
2936                                                       
2937                                                        // A constante PHPGW_APP_TPL nao existe para envio de alarmes (cront, asyncservice).
2938                                                        define ("PHPGW_APP_TPL",PHPGW_API_INC . "/../../calendar/templates/celepar");
2939                                                       
2940                                                        $body = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
2941                                                        $body->set_file(Array('calendar' => 'body_email.tpl'));
2942                                                        $body->set_block('calendar','list');
2943                                                        $var = Array(
2944                                                                'script'                        => $script,
2945                                                                'subject'                       => $body1,
2946                                                                'var1'                          => $var1,
2947                                                                'vardata1'                      => $vardata1,
2948                                                                'var2'                          => $var2,
2949                                                                'vardata2'                      => $vardata2,
2950                                                                'var3'                          => $var3,
2951                                                                'vardata3'                      => $vardata3,
2952                                                                'var4'                          => $var4,
2953                                                                'vardata4'                      => $vardata4,
2954                                                                'var5'                          => $var5,
2955                                                                'vardata6'                      => $vardata6,
2956                                                                'var8'                          => $var8,
2957                                                                'vardata8'                      => $vardata8,                                                   
2958                                                                'varbuttom'                     => $varbuttom,
2959                                                                'varbuttom1'            => $varbuttom1,
2960                                                                'varbuttom2'            => $varbuttom2,
2961                                                                'varbuttom3'            => $varbuttom3
2962                                                               
2963                                                        );
2964                                                        $body->set_var($var);
2965                                                        $tmpbody = $body->fp('out','list');
2966                                                                                                               
2967                                                        break;
2968
2969                                                case 'ical':
2970                                                        $content_type = "calendar; method=$method; name=calendar.ics";
2971/*                                                      if ($body != '')
2972                                                        {
2973                                                                $boundary = '----Message-Boundary';
2974                                                                $body .= "\n\n\n$boundary\nContent-type: text/$content_type\n".
2975                                                                        "Content-Disposition: inline\nContent-transfer-encoding: 7BIT\n\n";
2976                                                                $content_type = '';
2977                                                        }
2978*/
2979                                                        $body = ExecMethod('calendar.boicalendar.export',array(
2980                                                                'l_event_id'  => $event['id'],
2981                                                                'method'      => $method,
2982                                                                'chunk_split' => False
2983                                                        ));
2984                                                        break;
2985                                        }
2986                                        $mail->AddAddress($to);
2987                                        $mail->Body = $tmpbody;
2988                                        $mail->From = $sender;
2989                                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
2990                                        $mail->Sender = $mail->From;
2991                                        $mail->SenderName = $mail->FromName;
2992                                        $mail->Subject = $subject;
2993                                        unset($vardata5);
2994                                        unset($vardata6);
2995                                }
2996                        }
2997
2998                        //Inicializa variável de retorno.
2999                        $returncode=true;                       
3000                        if(count($mail->to)) {                         
3001                                // Envia aviso a todos os participantes.
3002                                if(!$mail->Send()) {                           
3003                                        $returncode = false;
3004                                        $errorInfo['participants'] = $mail->ErrorInfo;
3005                                }
3006                                else
3007                                        $returncode =  true;
3008                        }
3009                       
3010                        if(count($to_notify) && $this->ex_participants){
3011                                $mail->ClearAllRecipients();
3012                                $var = explode(",",trim($this->ex_participants));
3013                                $to = array();
3014                                if(!$subject) {
3015                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
3016                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
3017                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
3018                                }
3019                               
3020                                foreach($var as $index => $ex_participant){
3021                                        $ex_participant = trim($ex_participant);
3022                                        $ex_participant = preg_replace('#"(.*)" <(.*)\@(.*)\.(.*)>#','\\2@\\3.\\4',$ex_participant);
3023                                                if($ex_participant)
3024                                                        $to[] = $ex_participant;
3025                                }               
3026                               
3027                                foreach($to as $i => $to_array)
3028                                        $mail->AddAddress($to_array);
3029                               
3030                                $_body = explode("<hr size='1' width='100%'>",$tmpbody);
3031                                $tmpbody = $_body[0] ? $_body[0] : $subject ;
3032                                $tmpbody.= "<br><b>".lang("external participants").":: </b> ".htmlentities($this->ex_participants);
3033                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3034                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";
3035                                $tmpbody.= "<br><br><hr size='1' width='100%'><font color='red'>"
3036                                .lang("This message was sent by server. You must send a message to sender to confirm this event")."<br>"
3037                                .lang("This is an external event. Even if it added to your expresso its can be changed any time at all")."</font><br>";
3038                               
3039                                if ($GLOBALS['bocalendar']->so->cal->event[start][month] > 10)
3040                                        $event_month=$GLOBALS['bocalendar']->so->cal->event[start][month];
3041                                else
3042                                        $event_month="0".$GLOBALS['bocalendar']->so->cal->event[start][month];
3043                                //attach extern vcard                   
3044                                // define('context','$GLOBALS.bocalendar.so.cal.event');
3045                                $tmpattach = $this->create_vcard($GLOBALS['bocalendar']->so->cal->event);
3046                                if($tmpattach){                                 
3047                                        $tmpbody .="<a href='../index.php?menuaction=calendar.uicalendar.add&date="
3048                                        .$GLOBALS['bocalendar']->so->cal->event[start][year]
3049                                .$event_month
3050                                .$GLOBALS['bocalendar']->so->cal->event[start][mday]
3051                                        ."&hour=".$GLOBALS['bocalendar']->so->cal->event[start][hour]
3052                                        ."&minute=".$GLOBALS['bocalendar']->so->cal->event[start][min]
3053                                        ."&title=".$GLOBALS['bocalendar']->so->cal->event['title']
3054                                        ."&description=".$GLOBALS['bocalendar']->so->cal->event['description']
3055                                        ."&location=".$GLOBALS['bocalendar']->so->cal->event['location']."'>"
3056                                        ."<h2>".lang("Add to my expresso")."</h2>";
3057                                        $tempdir = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
3058                                        srand((double)microtime()*1000000);
3059                                        $random_number = rand(100000000,999999999);
3060                                        $newfilename = md5(time() . getenv("REMOTE_ADDR") . $random_number );
3061                                        $filename = $tempdir . $newfilename;
3062                                        $attach_fd = fopen($filename,"w+");
3063                                        fwrite($attach_fd,$tmpattach);
3064                                        $mail->AddAttachment($filename, "extern.vcard", "base64", "text/plain"); // "application/octet-stream"
3065                                        fclose($attach_fd);
3066                                }
3067                                $mail->From = $sender;
3068                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3069                                $mail->Sender = $mail->From;
3070                                $mail->SenderName = $mail->FromName;
3071                                $mail->Subject = lang("External event from Expresso");
3072                                $mail->Body = $tmpbody;
3073                                                                                                                                               
3074                                if(!$mail->Send())
3075                                {
3076                                        $returncode=false;
3077                                        $errorInfo['ex_participants'] = $mail->ErrorInfo;
3078                                }
3079                                else
3080                                {
3081                                        $returncode=true;
3082                                }
3083                        }
3084
3085
3086                        if((is_int($this->user) && $this->user != $temp_user['account_id']) ||
3087                                (is_string($this->user) && $this->user != $temp_user['account_lid']))
3088                        {
3089                                $GLOBALS['phpgw_info']['user'] = $temp_user;
3090                        }       
3091
3092                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $temp_tz_offset;
3093                        $GLBOALS['phpgw']->datetime->tz_offset = ((60 * 60) * $temp_tz_offset);
3094                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $temp_timeformat;
3095                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $temp_dateformat;
3096                       
3097                        // Notifica por email o criador do compromisso, com as possíveis falhas.                                               
3098                        if($errorInfo) {
3099                                $tmpbody = "<font color='red'>".lang("The following commitment had problems for DELIVERING the NOTIFICATION messages.").".</font><br>";
3100                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3101                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";                         
3102                                $tmpbody.= "<br><u>".lang("Failed to delivery")."</u><br>";
3103                                $failed = false;                               
3104                                if(strstr($errorInfo['participants'],"recipients_failed")){
3105                                        $failed = explode("recipients_failed",$errorInfo['participants']);
3106                                        $tmpbody.= lang("to").": ".$failed[1];
3107                                }
3108                                if(strstr($errorInfo['ex_participants'],"recipients_failed")){
3109                                        $failed = explode("recipients_failed",$errorInfo['ex_participants']);
3110                                        $tmpbody.= lang("to").": ".$failed[1];
3111                                }                       
3112                                if(!$failed) {
3113                                        $tmpbody.= lang("Description").":<br>";
3114                                        $tmpbody.= $errorInfo['participants'];
3115                                        $tmpbody.= "<br>".$errorInfo['ex_participants'];
3116                                }
3117                                $tmpbody.= "<br>".lang("Subject").": ".$subject;
3118                                // Reinicializa o objeto, devido ao erro anterior na entrega.
3119                               
3120                                $mail = new PHPMailer();
3121                                $mail->IsSMTP();
3122                                $mail->Host = $emailadmin['smtpServer'];
3123                                $mail->Port = $emailadmin['smtpPort'];
3124                                $mail->From = $sender;
3125                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3126                                $mail->Sender = $mail->From;
3127                                $mail->SenderName = $mail->FromName;
3128                                $mail->IsHTML(True);
3129                                $mail->Subject = lang("calendar event")." - ".lang("email notification");                                                       
3130                                $mail->Body = $tmpbody;                                 
3131                                $mail->AddAddress($sender);
3132                                if(!$mail->Send())                     
3133                                        $returncode = false;
3134                                else
3135                                        $returncode =  true;
3136                        }
3137                        return $returncode;
3138                }
3139               
3140                function send_alarm($alarm)
3141                {
3142                        //echo "<p>bocalendar::send_alarm("; print_r($alarm); echo ")</p>\n";
3143                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->owner = $alarm['owner'];
3144
3145                        if (!$alarm['enabled'] || !$alarm['owner'] || !$alarm['cal_id'] || !($event = $this->so->read_entry($alarm['cal_id'])))
3146                        {
3147                                return False;   // event not found
3148                        }
3149                        if ($alarm['all'])
3150                        {
3151                                $to_notify = $event['participants'];
3152                        }
3153                        elseif ($this->check_perms(PHPGW_ACL_READ,$event))      // checks agains $this->owner set to $alarm[owner]
3154                        {
3155                                $to_notify[$alarm['owner']] = 'A';
3156                        }
3157                        else
3158                        {
3159                                return False;   // no rights
3160                        }
3161                        return $this->send_update(MSG_ALARM,$to_notify,$event,False,$alarm['owner']);
3162                }
3163
3164                function get_alarms($event_id)
3165                {
3166                        return $this->so->get_alarm($event_id);
3167                }
3168
3169                function alarm_today($event,$today,$starttime)
3170                {
3171                        $found = False;
3172                        @reset($event['alarm']);
3173                        $starttime_hi = $GLOBALS['phpgw']->common->show_date($starttime,'Hi');
3174                        $t_appt['month'] =$GLOBALS['phpgw']->common->show_date($today,'m');
3175                        $t_appt['mday'] = $GLOBALS['phpgw']->common->show_date($today,'d');
3176                        $t_appt['year'] = $GLOBALS['phpgw']->common->show_date($today,'Y');
3177                        $t_appt['hour'] = $GLOBALS['phpgw']->common->show_date($starttime,'H');
3178                        $t_appt['min']  = $GLOBALS['phpgw']->common->show_date($starttime,'i');
3179                        $t_appt['sec']  = 0;
3180                        $t_time = $this->maketime($t_appt) - $GLOBALS['phpgw']->datetime->tz_offset;
3181                        $y_time = $t_time - 86400;
3182                        $tt_time = $t_time + 86399;
3183                        print_debug('T_TIME',$t_time.' : '.$GLOBALS['phpgw']->common->show_date($t_time));
3184                        print_debug('Y_TIME',$y_time.' : '.$GLOBALS['phpgw']->common->show_date($y_time));
3185                        print_debug('TT_TIME',$tt_time.' : '.$GLOBALS['phpgw']->common->show_date($tt_time));
3186                        while(list($key,$alarm) = each($event['alarm']))
3187                        {
3188                                if($alarm['enabled'])
3189                                {
3190                                        print_debug('TIME',$alarm['time'].' : '.$GLOBALS['phpgw']->common->show_date($alarm['time']).' ('.$event['id'].')');
3191                                        if($event['recur_type'] != MCAL_RECUR_NONE)   /* Recurring Event */
3192                                        {
3193                                                print_debug('Recurring Event');
3194                                                if($alarm['time'] > $y_time && $GLOBALS['phpgw']->common->show_date($alarm['time'],'Hi') < $starttime_hi && $alarm['time'] < $t_time)
3195                                                {
3196                                                        $found = True;
3197                                                }
3198                                        }
3199                                        elseif($alarm['time'] > $y_time && $alarm['time'] < $t_time)
3200                                        {
3201                                                $found = True;
3202                                        }
3203                                }
3204                        }
3205                        print_debug('Found',$found);
3206                        return $found;
3207                }
3208
3209                function prepare_recipients(&$new_event,$old_event)
3210                {
3211                                               
3212                        // Find modified and deleted users.....
3213                        while(list($old_userid,$old_status) = each($old_event['participants']))
3214                        {
3215                                if(isset($new_event['participants'][$old_userid]))
3216                                {
3217                                        print_debug('Modifying event for user',$old_userid);
3218                                        $this->modified[(int)$old_userid] = $new_status;
3219                                }
3220                                else
3221                                {
3222                                        print_debug('Deleting user from the event',$old_userid);
3223                                        $this->deleted[(int)$old_userid] = $old_status;
3224                                }
3225                        }
3226                        // Find new users.....
3227                        while(list($new_userid,$new_status) = each($new_event['participants']))
3228                        {
3229                                if(!isset($old_event['participants'][$new_userid]))
3230                                {
3231                                        print_debug('Adding event for user',$new_userid);
3232                                        $this->added[$new_userid] = 'U';
3233                                        $new_event['participants'][$new_userid] = 'U';
3234                                }
3235                        }
3236                       
3237                        if(count($this->added) > 0 || count($this->modified) > 0 || count($this->deleted) > 0)
3238                        {
3239                                if(count($this->added) > 0)
3240                                {
3241                                        $this->ex_participants = '';
3242                                        $this->send_update(MSG_ADDED,$this->added,'',$new_event);
3243                                }
3244                                if(count($this->modified) > 0)
3245                                {
3246                                        $this->send_update(MSG_MODIFIED,$this->modified,$old_event,$new_event);
3247                                }
3248                                if(count($this->deleted) > 0)
3249                                {
3250                                        $this->ex_participants = '';
3251                                        $this->send_update(MSG_DELETED,$this->deleted,$old_event);
3252                                }
3253                        }
3254                }
3255
3256                function remove_doubles_in_cache($firstday,$lastday)
3257                {
3258                        $already_moved = Array();
3259                        for($v=$firstday;$v<=$lastday;$v++)
3260                        {
3261                                if (!$this->cached_events[$v])
3262                                {
3263                                        continue;
3264                                }
3265                                $cached = $this->cached_events[$v];
3266                                $this->cached_events[$v] = array();
3267                                while (list($g,$event) = each($cached))
3268                                {
3269                                        $end = date('Ymd',$this->maketime($event['end']));
3270                                        print_debug('EVENT',_debug_array($event,False));
3271                                        print_debug('start',$start);
3272                                        print_debug('v',$v);
3273
3274                                        if (!isset($already_moved[$event['id']]) || $event['recur_type'] && $v > $end)
3275                                        {
3276                                                $this->cached_events[$v][] = $event;
3277                                                $already_moved[$event['id']] = 1;
3278                                                print_debug('Event moved');
3279                                        }
3280                                }
3281                        }
3282                }
3283
3284                function get_dirty_entries($lastmod=-1)
3285                {
3286                        $events = false;
3287                        $event_ids = $this->so->cal->list_dirty_events($lastmod);
3288                        if(is_array($event_ids))
3289                        {
3290                                foreach($event_ids as $key => $id)
3291                                {
3292                                        $events[$id] = $this->so->cal->fetch_event($id);
3293                                }
3294                        }
3295                        unset($event_ids);
3296
3297                        $rep_event_ids = $this->so->cal->list_dirty_events($lastmod,$true);
3298                        if(is_array($rep_event_ids))
3299                        {
3300                                foreach($rep_event_ids as $key => $id)
3301                                {
3302                                        $events[$id] = $this->so->cal->fetch_event($id);
3303                                }
3304                        }
3305                        unset($rep_event_ids);
3306
3307                        return $events;
3308                }
3309
3310                function _debug_array($data)
3311                {
3312                        echo '<br>UI:';
3313                        _debug_array($data);
3314                }
3315
3316                /*!
3317                @function rejected_no_show
3318                @abstract checks if event is rejected from user and he's not the owner and dont want rejected
3319                @param $event to check
3320                @returns True if event should not be shown
3321                */
3322                function rejected_no_show($event)
3323                {
3324                        $ret = !$this->prefs['calendar']['show_rejected'] &&
3325                                $event['owner'] != $this->owner &&
3326                                $event['participants'][$this->owner] == 'R';
3327                        //echo "<p>rejected_no_show($event[title])='$ret': user=$this->owner, event-owner=$event[owner], status='".$event['participants'][$this->owner]."', show_rejected='".$this->prefs['calendar']['show_rejected']."'</p>\n";
3328                        return $ret;
3329                }
3330
3331                /* This is called only by list_cals().  It was moved here to remove fatal error in php5 beta4 */
3332                function list_cals_add($id,&$users,&$groups)
3333                {
3334                        $name = $GLOBALS['phpgw']->common->grab_owner_name($id);
3335                        if (($type = $GLOBALS['phpgw']->accounts->get_type($id)) == 'g')
3336                        {
3337                                $arr = &$groups;
3338                        }
3339                        else
3340                        {
3341                                $arr = &$users;
3342                        }
3343                        $arr[$name] = Array(
3344                                'grantor' => $id,
3345                                'value'   => ($type == 'g' ? 'g_' : '') . $id,
3346                                'name'    => $name
3347                        );
3348                }
3349
3350                /*!
3351                @function list_cals
3352                @abstract generate list of user- / group-calendars for the selectbox in the header
3353                @returns alphabeticaly sorted array with groups first and then users
3354                */
3355                function list_cals()
3356                {
3357                        $users = $groups = array();
3358                        foreach($this->grants as $id => $rights)
3359                        {
3360                                $this->list_cals_add($id,$users,$groups);
3361                        }
3362                       
3363                        //by JakJr, melhora de performance na abertura da agenda
3364                        /*if ($memberships = $GLOBALS['phpgw']->accounts->membership($GLOBALS['phpgw_info']['user']['account_id']))
3365                        {
3366                                foreach($memberships as $group_info)
3367                                {
3368                                        $this->list_cals_add($group_info['account_id'],$users,$groups);
3369
3370                                        if ($account_perms = $GLOBALS['phpgw']->acl->get_ids_for_location($group_info['account_id'],PHPGW_ACL_READ,'calendar'))
3371                                        {
3372                                                foreach($account_perms as $id)
3373                                                {
3374                                                        $this->list_cals_add($id,$users,$groups);
3375                                                }
3376                                        }
3377                                }
3378                        }*/
3379                        uksort($users,'strnatcasecmp');
3380                        uksort($groups,'strnatcasecmp');
3381
3382                        return $users + $groups;        // users first and then groups, both alphabeticaly
3383                }
3384
3385          function translate($key,$vars=false, $not_found='*' )
3386          {
3387            if ($this->async)
3388              return $GLOBALS['phpgw']->translation->translate_async($key, $vars);
3389            return lang($key, $vars);
3390          }
3391
3392                /*!
3393                @function event2array
3394                @abstract create array with name, translated name and readable content of each attributes of an event
3395                @syntax event2array($event,$sep='<br>')
3396                @param $event event to use
3397                @returns array of attributes with fieldname as key and array with the 'field'=translated name \
3398                        'data' = readable content (for participants this is an array !)
3399                */
3400                function event2array($event)
3401                {
3402                       
3403                       
3404                  $var['title'] = Array(
3405                                'field'         => $this->translate('Title'),
3406                                'data'          => $event['title']
3407                        );
3408
3409                        // Some browser add a \n when its entered in the database. Not a big deal
3410                        // this will be printed even though its not needed.
3411                        $var['description'] = Array(
3412                                'field' => $this->translate('Description'),
3413                                'data'  => $event['description']
3414                        );
3415
3416                        $var['ex_participants'] = Array(
3417                                'field' => $this->translate('External Participants'),
3418                                'data'  => $event['ex_participants']
3419                        );
3420                       
3421                        $cats = Array();
3422                        $this->cat->categories($this->bo->owner,'calendar');
3423                        if(strpos($event['category'],','))
3424                        {
3425                                $cats = explode(',',$event['category']);
3426                        }
3427                        else
3428                        {
3429                                $cats[] = $event['category'];
3430                        }
3431                        foreach($cats as $cat_id)
3432                        {
3433                                list($cat) = $this->cat->return_single($cat_id);
3434                                $cat_string[] = $cat['name'];
3435                        }
3436                        $var['category'] = Array(
3437                                'field' => $this->translate('Category'),
3438                                'data'  => implode(', ',$cat_string)
3439                        );
3440
3441                        $var['location'] = Array(
3442                                'field' => $this->translate('Location'),
3443                                'data'  => $event['location']
3444                        );
3445
3446                        $var['startdate'] = Array(
3447                                'field' => $this->translate('Start Date/Time'),
3448                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset),
3449                        );
3450
3451                        $var['enddate'] = Array(
3452                                'field' => $this->translate('End Date/Time'),
3453                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset)
3454                        );
3455
3456                        $pri = Array(
3457                                1       => lang('Low'),
3458                                2       => lang('Normal'),
3459                                3       => lang('High')
3460                        );
3461                        $var['priority'] = Array(
3462                                'field' => lang('Priority'),
3463                                'data'  => $pri[$event['priority']]
3464                        );
3465
3466                        $var['owner'] = Array(
3467                                'field' => lang('Created By'),
3468                                'data'  => $GLOBALS['phpgw']->common->grab_owner_name($event['owner'])
3469                        );
3470
3471                        $var['updated'] = Array(
3472                                'field' => lang('Updated'),
3473                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['modtime']) - $GLOBALS['phpgw']->datetime->tz_offset)
3474                        );
3475
3476                        $var['access'] = Array(
3477                                'field' => lang('Access'),
3478                                'data'  => $event['public'] ? lang('Public') : lang('Private')
3479                        );
3480
3481                        if(@isset($event['groups'][0]))
3482                        {
3483                                $cal_grps = '';
3484                                for($i=0;$i<count($event['groups']);$i++)
3485                                {
3486                                        if($GLOBALS['phpgw']->accounts->exists($event['groups'][$i]))
3487                                        {
3488                                                $cal_grps .= ($i>0?'<br>':'').$GLOBALS['phpgw']->accounts->id2name($event['groups'][$i]);
3489                                        }
3490                                }
3491
3492                                $var['groups'] = Array(
3493                                        'field' => lang('Groups'),
3494                                        'data'  => $cal_grps
3495                                );
3496                        }
3497
3498                        $participants = array();
3499                        foreach($event['participants'] as $user => $short_status)
3500                        {
3501                                if($GLOBALS['phpgw']->accounts->exists($user))
3502                                {
3503                                        $participants[$user] = $GLOBALS['phpgw']->common->grab_owner_name($user).' ('.$this->get_long_status($short_status).')';
3504                                }
3505                        }
3506                        $var['participants'] = Array(
3507                                'field' => $this->translate('Participants'),
3508                                'data'  => $participants
3509                        );
3510
3511                        // Repeated Events
3512                        if($event['recur_type'] != MCAL_RECUR_NONE)
3513                        {
3514                                $str = lang($this->rpt_type[$event['recur_type']]);
3515
3516                                $str_extra = array();
3517                                if ($event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['month'] != 0 && $event['recur_enddate']['year'] != 0)
3518                                {
3519                                        $recur_end = $this->maketime($event['recur_enddate']);
3520                                        if($recur_end != 0)
3521                                        {
3522                                                $recur_end -= $GLOBALS['phpgw']->datetime->tz_offset;
3523                                                $str_extra[] = lang('ends').': '.lang($GLOBALS['phpgw']->common->show_date($recur_end,'l')).', '.$this->long_date($recur_end).' ';
3524                                        }
3525                                }
3526                                // only weekly uses the recur-data (days) !!!
3527                                if($event['recur_type'] == MCAL_RECUR_WEEKLY)
3528                                {
3529                                        $repeat_days = array();
3530                                        foreach ($this->rpt_day as $mcal_mask => $dayname)
3531                                        {
3532                                                if ($event['recur_data'] & $mcal_mask)
3533                                                {
3534                                                        $repeat_days[] = lang($dayname);
3535                                                }
3536                                        }
3537                                        if(count($repeat_days))
3538                                        {
3539                                                $str_extra[] = lang('days repeated').': '.implode(', ',$repeat_days);
3540                                        }
3541                                }
3542                                if($event['recur_interval'] != 0)
3543                                {
3544                                        $str_extra[] = lang('Interval').': '.$event['recur_interval'];
3545                                }
3546
3547                                if(count($str_extra))
3548                                {
3549                                        $str .= ' ('.implode(', ',$str_extra).')';
3550                                }
3551
3552                                $var['recure_type'] = Array(
3553                                        'field' => lang('Repetition'),
3554                                        'data'  => $str,
3555                                );
3556                        }
3557
3558                        if (!isset($this->fields))
3559                        {
3560                                $this->custom_fields = CreateObject('calendar.bocustom_fields');
3561                                $this->fields = &$this->custom_fields->fields;
3562                                $this->stock_fields = &$this->custom_fields->stock_fields;
3563                        }
3564                        foreach($this->fields as $field => $data)
3565                        {
3566                                if (!$data['disabled'])
3567                                {
3568                                        if (isset($var[$field]))
3569                                        {
3570                                                $sorted[$field] = $var[$field];
3571                                        }
3572                                        elseif (!isset($this->stock_fields[$field]) && strlen($event[$field]))  // Custom field
3573                                        {
3574                                                $lang = lang($name = substr($field,1));
3575                                                $sorted[$field] = array(
3576                                                        'field' => $lang == $name.'*' ? $name : $lang,
3577                                                        'data'  => $event[$field]
3578                                                );
3579                                        }
3580                                }
3581                                unset($var[$field]);
3582                        }
3583                        foreach($var as $name => $v)
3584                        {
3585                                $sorted[$name] = $v;
3586
3587                        }
3588                        return $sorted;
3589                }
3590
3591                /*!
3592                @function check_set_default_prefs
3593                @abstract sets the default prefs, if they are not already set (on a per pref. basis)
3594                @note It sets a flag in the app-session-data to be called only once per session
3595                */
3596                function check_set_default_prefs()
3597                {
3598                        if (($set = $GLOBALS['phpgw']->session->appsession('default_prefs_set','calendar')))
3599                        {
3600                                return;
3601                        }
3602                        $GLOBALS['phpgw']->session->appsession('default_prefs_set','calendar','set');
3603
3604                        //$default_prefs = $GLOBALS['phpgw']->preferences->default['calendar']; jakjr
3605
3606                        $subject = $this->translate('Calendar Event') . ' - $$action$$: $$startdate$$ $$title$$'."\n";
3607                        $defaults = array(
3608                                'defaultcalendar' => 'week',
3609                                'mainscreen_showevents' => '0',
3610                                'summary'         => 'no',
3611                                'receive_updates' => 'no',
3612                                'update_format'   => 'extended',        // leave it to extended for now, as iCal kills the message-body
3613                                'notifyAdded'     => $subject . $this->translate ('You have a meeting scheduled for %1',array('$$startdate$$')),
3614                                'notifyCanceled'  => $subject . $this->translate ('Your meeting scheduled for %1 has been canceled',array('$$startdate$$')),
3615                                'notifyModified'  => $subject . $this->translate ('Your meeting that had been scheduled for %1 has been rescheduled to %2',array('$$olddate$$','$$startdate$$')),
3616                                'notifyResponse'  => $subject . $this->translate ('On %1 %2 %3 your meeting request for %4', array('$$date$$','$$fullname$$','$$action$$','$$startdate$$')),
3617                                'notifyAlarm'     => $this->translate('Alarm for %1 at %2 in %3',array('$$title$$','$$startdate$$','$$location$$')) . "\n" . $this->translate('Here is your requested alarm.'),
3618                                'show_rejected'   => '0',
3619                                'display_status'  => '1',
3620                                'weekdaystarts'   => 'Monday',
3621                                'workdaystarts'   => '9',
3622                                'workdayends'     => '17',
3623                                'interval'        => '30',
3624                                'defaultlength'   => '60',
3625                                'planner_start_with_group' => $GLOBALS['phpgw']->accounts->name2id('Default'),
3626                                'planner_intervals_per_day'=> '4',
3627                                'defaultfilter'   => 'all',
3628                                'default_private' => '0',
3629                                'display_minicals'=> '1',
3630                                'print_black_white'=>'0'
3631                        );
3632                        foreach($defaults as $var => $default)
3633                        {
3634                                if (!isset($default_prefs[$var]) || $default_prefs[$var] == '')
3635                                {
3636                                        $GLOBALS['phpgw']->preferences->add('calendar',$var,$default,'default');
3637                                        $need_save = True;
3638                                }
3639                        }
3640                        if ($need_save)
3641                        {
3642                                $prefs = $GLOBALS['phpgw']->preferences->save_repository(False,'default');
3643                                $this->prefs['calendar'] = $prefs['calendar'];
3644                        }
3645                        if ($this->prefs['calendar']['send_updates'] && !isset($this->prefs['calendar']['receive_updates']))
3646                        {
3647                                $this->prefs['calendar']['receive_updates'] = $this->prefs['calendar']['send_updates'];
3648                                $GLOBALS['phpgw']->preferences->add('calendar','receive_updates',$this->prefs['calendar']['send_updates']);
3649                                $GLOBALS['phpgw']->preferences->delete('calendar','send_updates');
3650                                $prefs = $GLOBALS['phpgw']->preferences->save_repository();
3651                        }
3652                }
3653
3654                // return array with all infolog categories (for xmlrpc)
3655                function categories($complete = False)
3656                {
3657                        return $GLOBALS['server']->categories($complete);
3658                }
3659        }
3660?>
Note: See TracBrowser for help on using the repository browser.