source: branches/2.2/calendar/inc/class.bocalendar.inc.php @ 4896

Revision 4896, 133.4 KB checked in by diegomoreno, 13 years ago (diff)

Ticket #2179 - calendar - Ajuste do agendamento mensalmente por dia

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