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

Revision 2251, 122.2 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #936 - Alterada a forma de apresentacao do acesso do compromisso

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