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

Revision 1949, 121.9 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #715 - Corrigido a montagem do combo tipo de evento e alterado o tipo do compromisso privado de e para P

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