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

Revision 204, 110.1 KB checked in by niltonneto, 16 years ago (diff)

Ver Ticket #148:

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