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

Revision 1720, 121.6 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #682 - Adicionada verificacao se o delegado ja esta no evento

  • 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');
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 overlap($starttime,$endtime,$participants,$owner=0,$id=0,$restore_cache=False)
1508                {
1509//                      $retval = Array();
1510//                      $ok = False;
1511
1512/* This needs some attention.. by commenting this chunk of code it will fix bug #444265 */
1513
1514                        if($restore_cache)
1515                        {
1516                                $temp_cache_events = $this->cached_events;
1517                        }
1518
1519//                      $temp_start = (int)$GLOBALS['phpgw']->common->show_date($starttime,'Ymd');
1520//                      $temp_start_time = (int)($GLOBALS['phpgw']->common->show_date($starttime,'Hi');
1521//                      $temp_end = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Ymd');
1522//                      $temp_end_time = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Hi');
1523                        $temp_start = (int)(date('Ymd',$starttime));
1524                        $temp_start_time = (int)(date('Hi',$starttime));
1525                        $temp_end = (int)(date('Ymd',$endtime));
1526                        $temp_end_time = (int)(date('Hi',$endtime));
1527                        if($this->debug)
1528                        {
1529                                echo '<!-- Temp_Start: '.$temp_start.' -->'."\n";
1530                                echo '<!-- Temp_End: '.$temp_end.' -->'."\n";
1531                        }
1532
1533                        $users = Array();
1534                        if(count($participants))
1535                        {
1536                                while(list($user,$status) = each($participants))
1537                                {
1538                                        $users[] = $user;
1539                                }
1540                        }
1541                        else
1542                        {
1543                                $users[] = $this->owner;
1544                        }
1545
1546                        $possible_conflicts = $this->store_to_cache(
1547                                Array(
1548                                        'smonth'        => substr(strval($temp_start),4,2),
1549                                        'sday'  => substr(strval($temp_start),6,2),
1550                                        'syear' => substr(strval($temp_start),0,4),
1551                                        'emonth'        => substr(strval($temp_end),4,2),
1552                                        'eday'  => substr(strval($temp_end),6,2),
1553                                        'eyear' => substr(strval($temp_end),0,4),
1554                                        'owner' => $users
1555                                )
1556                        );
1557
1558                        if($this->debug)
1559                        {
1560                                echo '<!-- Possible Conflicts ('.($temp_start - 1).'): '.count($possible_conflicts[$temp_start - 1]).' -->'."\n";
1561                                echo '<!-- Possible Conflicts ('.$temp_start.'): '.count($possible_conflicts[$temp_start]).' '.count($id).' -->'."\n";
1562                        }
1563
1564                        if($possible_conflicts[$temp_start] || $possible_conflicts[$temp_end])
1565                        {
1566                                if($temp_start == $temp_end)
1567                                {
1568                                        if($this->debug)
1569                                        {
1570                                                echo '<!-- Temp_Start == Temp_End -->'."\n";
1571                                        }
1572                                        @reset($possible_conflicts[$temp_start]);
1573                                        while(list($key,$event) = each($possible_conflicts[$temp_start]))
1574                                        {
1575                                                $found = False;
1576                                                if($id)
1577                                                {
1578                                                        @reset($id);
1579                                                        while(list($key,$event_id) = each($id))
1580                                                        {
1581                                                                if($this->debug)
1582                                                                {
1583                                                                        echo '<!-- $id['.$key.'] = '.$id[$key].' = '.$event_id.' -->'."\n";
1584                                                                        echo '<!-- '.$event['id'].' == '.$event_id.' -->'."\n";
1585                                                                }
1586                                                                if($event['id'] == $event_id)
1587                                                                {
1588                                                                        $found = True;
1589                                                                }
1590                                                        }
1591                                                }
1592                                                if($this->debug)
1593                                                {
1594                                                        echo '<!-- Item found: '.$found.' -->'."<br>\n";
1595                                                }
1596                                                if(!$found)
1597                                                {
1598                                                        if($this->debug)
1599                                                        {
1600                                                                echo '<!-- Checking event id #'.$event['id'];
1601                                                        }
1602                                                        $temp_event_start = sprintf("%d%02d",$event['start']['hour'],$event['start']['min']);
1603                                                        $temp_event_end = sprintf("%d%02d",$event['end']['hour'],$event['end']['min']);
1604//                                                      if((($temp_start_time <= $temp_event_start) && ($temp_end_time >= $temp_event_start) && ($temp_end_time <= $temp_event_end)) ||
1605                                                        if(($temp_start_time <= $temp_event_start &&
1606                                                                $temp_end_time > $temp_event_start &&
1607                                                                $temp_end_time <= $temp_event_end ||
1608                                                                $temp_start_time >= $temp_event_start &&
1609                                                                $temp_start_time < $temp_event_end &&
1610                                                                $temp_end_time >= $temp_event_end ||
1611                                                                $temp_start_time <= $temp_event_start &&
1612                                                                $temp_end_time >= $temp_event_end ||
1613                                                                $temp_start_time >= $temp_event_start &&
1614                                                                $temp_end_time <= $temp_event_end) &&
1615                                                                $this->participants_not_rejected($participants,$event))
1616                                                        {
1617                                                                if($this->debug)
1618                                                                {
1619                                                                        echo ' Conflicts';
1620                                                                }
1621                                                                $retval[] = $event['id'];
1622                                                        }
1623                                                        if($this->debug)
1624                                                        {
1625                                                                echo ' -->'."\n";
1626                                                        }
1627                                                }
1628                                        }
1629                                }
1630                        }
1631                        else
1632                        {
1633                                $retval = False;
1634                        }
1635
1636                        if($restore_cache)
1637                        {
1638                                $this->cached_events = $temp_cache_events;
1639                        }
1640
1641                        return $retval;
1642                }
1643
1644                /*!
1645                @function check_perms( )
1646                @syntax check_perms($needed,$event=0,$other=0)
1647                @abstract Checks if the current user has the necessary ACL rights
1648                @author ralfbecker
1649                @discussion The check is performed on an event or general on the cal of an other user
1650                @param $needed necessary ACL right: PHPGW_ACL_{READ|EDIT|DELETE}
1651                @param $event event as array or the event-id or 0 for general check
1652                @param $other uid to check (if event==0) or 0 to check against $this->owner
1653                @note Participating in an event is considered as haveing read-access on that event, \
1654                        even if you have no general read-grant from that user.
1655                */
1656                function check_perms($needed,$event=0,$other=0)
1657                {
1658                        $event_in = $event;
1659                       
1660                        if (is_int($event) && $event == 0)
1661                        {
1662                                $owner = $other > 0 ? $other : $this->owner;
1663                        }
1664                        else
1665                        {
1666                                if (!is_array($event))
1667                                {
1668                                        $event = $this->so->read_entry((int) $event);
1669                                }
1670                                if (!is_array($event))
1671                                {
1672                                        if ($this->xmlrpc)
1673                                        {
1674                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['not_exist'],$GLOBALS['xmlrpcstr']['not_exist']);
1675                                        }
1676                                        return False;
1677                                }
1678                                $owner = $event['owner'];
1679                                $private = $event['public'] == False || $event['public'] == 0;
1680                        }
1681                        $user = $GLOBALS['phpgw_info']['user']['account_id'];
1682                        $grants = $this->grants[$owner];
1683
1684                        if (is_array($event) && $needed == PHPGW_ACL_READ)
1685                        {
1686                                // Check if the $user is one of the participants or has a read-grant from one of them
1687                                //
1688                                foreach($event['participants'] as $uid => $accept)
1689                                {
1690                                        if ($this->grants[$uid] & PHPGW_ACL_READ || $uid == $user)
1691                                        {
1692                                                $grants |= PHPGW_ACL_READ;
1693                                                // if the $user is one of the participants read-grant private (restricted) too.
1694                                                if($uid == $user || ($this->grants[$uid] & PHPGW_ACL_PRIVATE)) {
1695                                                        $grants |= PHPGW_ACL_PRIVATE;
1696                                                }
1697                                                //break;
1698                                        }
1699                                }
1700                        }
1701
1702                        if ($GLOBALS['phpgw']->accounts->get_type($owner) == 'g' && $needed == PHPGW_ACL_ADD)
1703                        {
1704                                $access = False;        // a group can't be the owner of an event
1705                        }
1706                        else
1707                        {
1708                                $access = $user == $owner || $grants & $needed && (!$private || $grants & PHPGW_ACL_PRIVATE);
1709                        }
1710                        //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";
1711
1712                        return $access;
1713                }
1714
1715
1716                function display_status($user_status)
1717                {
1718                        if(@$this->prefs['calendar']['display_status'] && $user_status)
1719                        {
1720                                $user_status = substr($this->get_long_status($user_status),0,1);
1721
1722                                return ' ('.$user_status.')';
1723                        }
1724                        else
1725                        {
1726                                return '';
1727                        }
1728                }
1729
1730                function get_long_status($status_short)
1731                {
1732                        switch ($status_short)
1733                        {
1734                                case 'A':
1735                                        $status = lang('Accepted');
1736                                        break;
1737                                case 'R':
1738                                        $status = lang('Rejected');
1739                                        break;
1740                                case 'T':
1741                                        $status = lang('Tentative');
1742                                        break;
1743                                case 'U':
1744                                        $status = lang('No Response');
1745                                        break;
1746                        }
1747                        return $status;
1748                }
1749
1750                function is_private($event,$owner)
1751                {
1752                        if($owner == 0)
1753                        {
1754                                $owner = $this->owner;
1755                        }
1756                        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'])
1757                        {
1758                                return False;
1759                        }
1760                        elseif($event['public'] == 0)
1761                        {
1762                                return True;
1763                        }
1764                        elseif($event['public'] == 2)
1765                        {
1766                                $is_private = True;
1767                                $groups = $GLOBALS['phpgw']->accounts->membership($owner);
1768                                while (list($key,$group) = each($groups))
1769                                {
1770                                        if (strpos(' '.implode(',',$event['groups']).' ',$group['account_id']))
1771                                        {
1772                                                return False;
1773                                        }
1774                                }
1775                        }
1776                        else
1777                        {
1778                                return False;
1779                        }
1780
1781                        return $is_private;
1782                }
1783
1784                function get_short_field($event,$is_private=True,$field='')
1785                {
1786                        if($is_private)
1787                        {
1788                                return lang('private');
1789                        }
1790
1791// cut off too long titles
1792                        elseif(strlen($event[$field]) > 19 && !$this->printer_friendly && $field=="title")
1793//                      elseif(strlen($event[$field]) > 19 && $this->printer_friendly)
1794                        {
1795// we dont use currently 160304
1796//                              return substr($event[$field], 0 , 19) . '&nbsp;...';
1797                                return $event[$field];
1798                        }
1799                        else
1800                        {
1801                                return $event[$field];
1802                        }
1803                }
1804
1805                function long_date($first,$last=0)
1806                {
1807                        if (!is_array($first))
1808                        {
1809                                $first = $this->time2array($raw = $first);
1810                                $first['raw'] = $raw;
1811                                $first['day'] = $first['mday'];
1812                        }
1813                        if ($last && !is_array($last))
1814                        {
1815                                $last = $this->time2array($raw = $last);
1816                                $last['raw'] = $raw;
1817                                $last['day'] = $last['mday'];
1818                        }
1819                        $datefmt = $this->prefs['common']['dateformat'];
1820
1821                        $month_before_day = strtolower($datefmt[0]) == 'm' ||
1822                                strtolower($datefmt[2]) == 'm' && $datefmt[4] == 'd';
1823
1824                        for ($i = 0; $i < 5; $i += 2)
1825                        {
1826                                switch($datefmt[$i])
1827                                {
1828                                        case 'd':
1829                                                $range .= $first['day'] . ($datefmt[1] == '.' ? '.' : '');
1830                                                if ($first['month'] != $last['month'] || $first['year'] != $last['year'])
1831                                                {
1832                                                        if (!$month_before_day)
1833                                                        {
1834                                                                $range .= ' '.lang(strftime('%B',$first['raw']));
1835                                                        }
1836                                                        if ($first['year'] != $last['year'] && $datefmt[0] != 'Y')
1837                                                        {
1838                                                                $range .= ($datefmt[0] != 'd' ? ', ' : ' ') . $first['year'];
1839                                                        }
1840                                                        if (!$last)
1841                                                        {
1842                                                                return $range;
1843                                                        }
1844                                                        $range .= ' - ';
1845
1846                                                        if ($first['year'] != $last['year'] && $datefmt[0] == 'Y')
1847                                                        {
1848                                                                $range .= $last['year'] . ', ';
1849                                                        }
1850
1851                                                        if ($month_before_day)
1852                                                        {
1853                                                                $range .= lang(strftime('%B',$last['raw']));
1854                                                        }
1855                                                }
1856                                                else
1857                                                {
1858                                                        $range .= ' - ';
1859                                                }
1860                                                $range .= ' ' . $last['day'] . ($datefmt[1] == '.' ? '.' : '');
1861                                                break;
1862                                        case 'm':
1863                                        case 'M':
1864                                                $range .= ' '.lang(strftime('%B',$month_before_day ? $first['raw'] : $last['raw'])) . ' ';
1865                                                break;
1866                                        case 'Y':
1867                                                $range .= ($datefmt[0] == 'm' ? ', ' : ' ') . ($datefmt[0] == 'Y' ? $first['year'].($datefmt[2] == 'd' ? ', ' : ' ') : $last['year'].' ');
1868                                                break;
1869                                }
1870                        }
1871                        return $range;
1872                }
1873
1874                function get_week_label()
1875                {
1876                        $first = $GLOBALS['phpgw']->datetime->gmtdate($GLOBALS['phpgw']->datetime->get_weekday_start($this->year, $this->month, $this->day));
1877                        $last = $GLOBALS['phpgw']->datetime->gmtdate($first['raw'] + 518400);
1878
1879                        return ($this->long_date($first,$last));
1880                }
1881
1882                function normalizeminutes(&$minutes)
1883                {
1884                        $hour = 0;
1885                        $min = (int)$minutes;
1886                        if($min >= 60)
1887                        {
1888                                $hour += $min / 60;
1889                                $min %= 60;
1890                        }
1891                        settype($minutes,'integer');
1892                        $minutes = $min;
1893                        return $hour;
1894                }
1895
1896                function splittime($time,$follow_24_rule=True)
1897                {
1898                        $temp = array('hour','minute','second','ampm');
1899                        $time = strrev($time);
1900                        $second = (int)(strrev(substr($time,0,2)));
1901                        $minute = (int)(strrev(substr($time,2,2)));
1902                        $hour   = (int)(strrev(substr($time,4)));
1903                        $hour += $this->normalizeminutes($minute);
1904                        $temp['second'] = $second;
1905                        $temp['minute'] = $minute;
1906                        $temp['hour']   = $hour;
1907                        $temp['ampm']   = '  ';
1908                        if($follow_24_rule == True)
1909                        {
1910                                if ($this->prefs['common']['timeformat'] == '24')
1911                                {
1912                                        return $temp;
1913                                }
1914
1915                                $temp['ampm'] = 'am';
1916
1917                                if ((int)$temp['hour'] > 12)
1918                                {
1919                                        $temp['hour'] = (int)((int)$temp['hour'] - 12);
1920                                        $temp['ampm'] = 'pm';
1921                                }
1922                                elseif ((int)$temp['hour'] == 12)
1923                                {
1924                                        $temp['ampm'] = 'pm';
1925                                }
1926                        }
1927                        return $temp;
1928                }
1929
1930                function get_exception_array($exception_str='')
1931                {
1932                        $exception = Array();
1933                        if(strpos(' '.$exception_str,','))
1934                        {
1935                                $exceptions = explode(',',$exception_str);
1936                                for($exception_count=0;$exception_count<count($exceptions);$exception_count++)
1937                                {
1938                                        $exception[] = (int)$exceptions[$exception_count];
1939                                }
1940                        }
1941                        elseif($exception_str != '')
1942                        {
1943                                $exception[] = (int)$exception_str;
1944                        }
1945                        return $exception;
1946                }
1947
1948                function build_time_for_display($fixed_time)
1949                {
1950                        $time = $this->splittime($fixed_time);
1951                        $str = $time['hour'].':'.((int)$time['minute']<=9?'0':'').$time['minute'];
1952
1953                        if ($this->prefs['common']['timeformat'] == '12')
1954                        {
1955                                $str .= ' ' . $time['ampm'];
1956                        }
1957
1958                        return $str;
1959                }
1960
1961                function sort_event($event,$date)
1962                {
1963                        $inserted = False;
1964                        if(isset($event['recur_exception']))
1965                        {
1966                                $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;
1967                                while($inserted == False && list($key,$exception_time) = each($event['recur_exception']))
1968                                {
1969                                        if($this->debug)
1970                                        {
1971                                                echo '<!-- checking exception datetime '.$exception_time.' to event datetime '.$event_time.' -->'."\n";
1972                                        }
1973                                        if($exception_time == $event_time)
1974                                        {
1975                                                $inserted = True;
1976                                        }
1977                                }
1978                        }
1979                        if($this->cached_events[$date] && $inserted == False)
1980                        {
1981
1982                                if($this->debug)
1983                                {
1984                                        echo '<!-- Cached Events found for '.$date.' -->'."\n";
1985                                }
1986                                $year = substr($date,0,4);
1987                                $month = substr($date,4,2);
1988                                $day = substr($date,6,2);
1989
1990                                if($this->debug)
1991                                {
1992                                        echo '<!-- Date : '.$date.' Count : '.count($this->cached_events[$date]).' -->'."\n";
1993                                }
1994
1995                                for($i=0;$i<count($this->cached_events[$date]);$i++)
1996                                {
1997                                        if($this->cached_events[$date][$i]['id'] == $event['id'] || $this->cached_events[$date][$i]['reference'] == $event['id'])
1998                                        {
1999                                                if($this->debug)
2000                                                {
2001                                                        echo '<!-- Item already inserted! -->'."\n";
2002                                                }
2003                                                $inserted = True;
2004                                                break;
2005                                        }
2006                                        /* This puts all spanning events across multiple days up at the top. */
2007                                        if($this->cached_events[$date][$i]['recur_type'] == MCAL_RECUR_NONE)
2008                                        {
2009                                                if($this->cached_events[$date][$i]['start']['mday'] != $day && $this->cached_events[$date][$i]['end']['mday'] >= $day)
2010                                                {
2011                                                        continue;
2012                                                }
2013                                        }
2014                                        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)))
2015                                        {
2016                                                for($j=count($this->cached_events[$date]);$j>=$i;$j--)
2017                                                {
2018                                                        $this->cached_events[$date][$j] = $this->cached_events[$date][$j-1];
2019                                                }
2020                                                if($this->debug)
2021                                                {
2022                                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
2023                                                }
2024                                                $inserted = True;
2025                                                $this->cached_events[$date][$i] = $event;
2026                                                break;
2027                                        }
2028                                }
2029                        }
2030                        if(!$inserted)
2031                        {
2032                                if($this->debug)
2033                                {
2034                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
2035                                }
2036                                $this->cached_events[$date][] = $event;
2037                        }
2038                }
2039
2040                function check_repeating_events($datetime)
2041                {
2042                        @reset($this->repeating_events);
2043                        $search_date_full = date('Ymd',$datetime);
2044                        $search_date_year = date('Y',$datetime);
2045                        $search_date_month = date('m',$datetime);
2046                        $search_date_day = date('d',$datetime);
2047                        $search_date_dow = date('w',$datetime);
2048                        $search_beg_day = mktime(12,0,0,$search_date_month,$search_date_day,$search_date_year);
2049                        if($this->debug)
2050                        {
2051                                echo '<!-- Search Date Full = '.$search_date_full.' -->'."\n";
2052                        }
2053                        $repeated = $this->repeating_events;
2054                        $r_events = count($repeated);
2055                        for ($i=0;$i<$r_events;$i++)
2056                        {
2057                                $rep_events = $this->repeating_events[$i];
2058                                $id = $rep_events['id'];
2059                                $event_beg_day = mktime(0,0,0,$rep_events['start']['month'],$rep_events['start']['mday'],$rep_events['start']['year']);
2060                                if($rep_events['recur_enddate']['month'] != 0 && $rep_events['recur_enddate']['mday'] != 0 && $rep_events['recur_enddate']['year'] != 0)
2061                                {
2062                                        $event_recur_time = $this->maketime($rep_events['recur_enddate']);
2063                                }
2064                                else
2065                                {
2066                                        $event_recur_time = mktime(0,0,0,1,1,2030);
2067                                }
2068                                $end_recur_date = date('Ymd',$event_recur_time);
2069                                $full_event_date = date('Ymd',$event_beg_day);
2070
2071                                if($this->debug)
2072                                {
2073                                        echo '<!-- check_repeating_events - Processing ID - '.$id.' -->'."\n";
2074                                        echo '<!-- check_repeating_events - Recurring End Date - '.$end_recur_date.' -->'."\n";
2075                                }
2076
2077                                // only repeat after the beginning, and if there is an rpt_end before the end date
2078                                if (($search_date_full > $end_recur_date) || ($search_date_full < $full_event_date))
2079                                {
2080                                        continue;
2081                                }
2082
2083                                if ($search_date_full == $full_event_date)
2084                                {
2085                                        $this->sort_event($rep_events,$search_date_full);
2086                                        continue;
2087                                }
2088                                else
2089                                {
2090                                        $freq = $rep_events['recur_interval'];
2091                                        $freq = $freq ? $freq : 1;
2092                                        $type = $rep_events['recur_type'];
2093                                        switch($type)
2094                                        {
2095                                                case MCAL_RECUR_DAILY:
2096                                                        if($this->debug)
2097                                                        {
2098                                                                echo '<!-- check_repeating_events - MCAL_RECUR_DAILY - '.$id.' -->'."\n";
2099                                                        }
2100                                                       
2101                                                        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)
2102                                                        {
2103                                                                $this->sort_event($rep_events,$search_date_full);
2104                                                        }
2105                                                        elseif (floor(($search_beg_day - $event_beg_day)/86400) % ($freq ? $freq : 1))
2106                                                        {
2107                                                                continue;
2108                                                        }
2109                                                        else
2110                                                        {
2111                                                                $this->sort_event($rep_events,$search_date_full);
2112                                                        }
2113                                                        break;
2114                                                case MCAL_RECUR_WEEKLY:
2115                                                        if (floor(($search_beg_day - $event_beg_day)/604800)  % ($freq ? $freq : 1))
2116                                                        {
2117                                                                continue;
2118                                                        }
2119                                                        $check = 0;
2120                                                        switch($search_date_dow)
2121                                                        {
2122                                                                case 0:
2123                                                                        $check = MCAL_M_SUNDAY;
2124                                                                        break;
2125                                                                case 1:
2126                                                                        $check = MCAL_M_MONDAY;
2127                                                                        break;
2128                                                                case 2:
2129                                                                        $check = MCAL_M_TUESDAY;
2130                                                                        break;
2131                                                                case 3:
2132                                                                        $check = MCAL_M_WEDNESDAY;
2133                                                                        break;
2134                                                                case 4:
2135                                                                        $check = MCAL_M_THURSDAY;
2136                                                                        break;
2137                                                                case 5:
2138                                                                        $check = MCAL_M_FRIDAY;
2139                                                                        break;
2140                                                                case 6:
2141                                                                        $check = MCAL_M_SATURDAY;
2142                                                                        break;
2143                                                        }
2144                                                        if ($rep_events['recur_data'] & $check)
2145                                                        {
2146                                                                $this->sort_event($rep_events,$search_date_full);
2147                                                        }
2148                                                        break;
2149                                                case MCAL_RECUR_MONTHLY_WDAY:
2150                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month']) % $freq)
2151                                                        {
2152                                                                continue;
2153                                                        }
2154
2155                                                        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)) &&
2156                                                                (ceil($rep_events['start']['mday']/7) == ceil($search_date_day/7)))
2157                                                        {
2158                                                                $this->sort_event($rep_events,$search_date_full);
2159                                                        }
2160                                                        break;
2161                                                case MCAL_RECUR_MONTHLY_MDAY:
2162                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month'])  % ($freq ? $freq : 1))
2163                                                        {
2164                                                                continue;
2165                                                        }
2166                                                        if ($search_date_day == $rep_events['start']['mday'])
2167                                                        {
2168                                                                $this->sort_event($rep_events,$search_date_full);
2169                                                        }
2170                                                        break;
2171                                                case MCAL_RECUR_YEARLY:
2172                                                        if (($search_date_year - $rep_events['start']['year']) % ($freq ? $freq : 1))
2173                                                        {
2174                                                                continue;
2175                                                        }
2176                                                        if (date('dm',$datetime) == date('dm',$event_beg_day))
2177                                                        {
2178                                                                $this->sort_event($rep_events,$search_date_full);
2179                                                        }
2180                                                        break;
2181                                        }
2182                                }
2183                        }       // end for loop
2184                }       // end function
2185
2186                function store_to_cache($params)
2187                {
2188                        if(!is_array($params))
2189                        {
2190                                return False;
2191                        }
2192                        if (isset($params['start']) && ($datearr = $GLOBALS['server']->iso86012date($params['start'])))
2193                        {
2194                                $syear = $datearr['year'];
2195                                $smonth = $datearr['month'];
2196                                $sday = $datearr['mday'];
2197                                $this->xmlrpc = True;
2198                        }
2199                        else
2200                        {
2201                                $syear = $params['syear'];
2202                                $smonth = $params['smonth'];
2203                                $sday = $params['sday'];
2204                        }
2205                        if (isset($params['end']) && ($datearr = $GLOBALS['server']->iso86012date($params['end'])))
2206                        {
2207                                $eyear = $datearr['year'];
2208                                $emonth = $datearr['month'];
2209                                $eday = $datearr['mday'];
2210                                $this->xmlrpc = True;
2211                        }
2212                        else
2213                        {
2214                                $eyear = (isset($params['eyear'])?$params['eyear']:0);
2215                                $emonth = (isset($params['emonth'])?$params['emonth']:0);
2216                                $eday = (isset($params['eday'])?$params['eday']:0);
2217                        }
2218                        if (!isset($params['owner']) && @$this->xmlrpc)
2219                        {
2220                                $owner_id = $GLOBALS['phpgw_info']['user']['user_id'];
2221                        }
2222                        else
2223                        {
2224                                $owner_id = (isset($params['owner'])?$params['owner']:0);
2225                                if($owner_id==0 && $this->is_group)
2226                                {
2227                                        unset($owner_id);
2228                                        $owner_id = $this->g_owner;
2229                                        if($this->debug)
2230                                        {
2231                                                echo '<!-- owner_id in ('.implode(',',$owner_id).') -->'."\n";
2232                                        }
2233                                }
2234                        }
2235                        if(!$eyear && !$emonth && !$eday)
2236                        {
2237                                $edate = mktime(23,59,59,$smonth + 1,$sday + 1,$syear);
2238                                $eyear = date('Y',$edate);
2239                                $emonth = date('m',$edate);
2240                                $eday = date('d',$edate);
2241                        }
2242                        else
2243                        {
2244                                if(!$eyear)
2245                                {
2246                                        $eyear = $syear;
2247                                }
2248                                //Tratamento do valor final (mes) da pesquisa de eventos feita em $this->so->list_events.
2249                                //Se $emonth nao tem valor, recebe o valor de $smonth (que recebe $params['smonth']) e soma 1.
2250                                //O valor $params['emonth'] indica o mes final para a pesquisa de eventos, e passou a ser
2251                                //informado na a impressao de eventos mensais. Mudancas feitas em class.uicalendar.inc.php,
2252                                //function display_month_print();
2253                                if(!$emonth)
2254                                {
2255                                        $emonth = $smonth + 1;
2256                                        if($emonth > 12)
2257                                        {
2258                                                $emonth = 1;
2259                                                $eyear++;
2260                                        }
2261                                }
2262                                if(!$eday)
2263                                {
2264                                        $eday = $sday + 1;
2265                                }
2266                                $edate = mktime(23,59,59,$emonth,$eday,$eyear);
2267                        }
2268                        //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";
2269                        if($this->debug)
2270                        {
2271                                echo '<!-- Start Date : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2272                                echo '<!-- End   Date : '.sprintf("%04d%02d%02d",$eyear,$emonth,$eday).' -->'."\n";
2273                        }
2274                        //A variavel $month_print recebe o parametro 'saux' com o mes de inicio da pesquisa de eventos por
2275                        //$this->so->list_events. O valor do mes final da pesquisa e tratado no codigo acima;
2276                        //$month_ini = $params['saux'];
2277
2278                        if($owner_id)
2279                        {
2280                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2281                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2282                        }
2283                        else
2284                        {
2285                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2286                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2287                        }
2288
2289                        $c_cached_ids = count($cached_event_ids);
2290                        $c_cached_ids_repeating = count($cached_event_ids_repeating);
2291
2292                        if($this->debug)
2293                        {
2294                                echo '<!-- events cached : '.$c_cached_ids.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2295                                echo '<!-- repeating events cached : '.$c_cached_ids_repeating.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2296                        }
2297
2298                        $this->cached_events = Array();
2299
2300                        if($c_cached_ids == 0 && $c_cached_ids_repeating == 0)
2301                        {
2302                                return;
2303                        }
2304
2305                        $cache_start = (int)(sprintf("%04d%02d%02d",$syear,$smonth,$sday));
2306                        $cached_event=$this->get_cached_event();
2307                        if($c_cached_ids)
2308                        {
2309                                for($i=0;$i<$c_cached_ids;$i++)
2310                                {
2311                                        $event = $this->so->read_entry($cached_event_ids[$i]);
2312                                        if ($event['recur_type'])
2313                                        {
2314                                                continue;       // fetch recuring events only in 2. loop
2315                                        }
2316                                        $startdate = (int)(date('Ymd',$this->maketime($event['start'])));
2317                                        $enddate = (int)(date('Ymd',$this->maketime($event['end'])));
2318                                        $this->cached_events[$startdate][] = $event;
2319                                        if($startdate != $enddate)
2320                                        {
2321                                                $start['year'] = (int)(substr($startdate,0,4));
2322                                                $start['month'] = (int)(substr($startdate,4,2));
2323                                                $start['mday'] = (int)(substr($startdate,6,2));
2324                                                for($j=$startdate,$k=0;$j<=$enddate;$k++,$j=(int)(date('Ymd',mktime(0,0,0,$start['month'],$start['mday'] + $k,$start['year']))))
2325                                                {
2326                                                        $c_evt_day = count($this->cached_events[$j]) - 1;
2327                                                        if($c_evt_day < 0)
2328                                                        {
2329                                                                $c_evt_day = 0;
2330                                                        }
2331                                                        if($this->debug)
2332                                                        {
2333                                                                echo '<!-- Date: '.$j.' Count : '.$c_evt_day.' -->'."\n";
2334                                                        }
2335                                                        if($this->cached_events[$j][$c_evt_day]['id'] != $event['id'])
2336                                                        {
2337                                                                if($this->debug)
2338                                                                {
2339                                                                        echo '<!-- Adding Event for Date: '.$j.' -->'."\n";
2340                                                                }
2341                                                                $this->cached_events[$j][] = $event;
2342                                                        }
2343                                                        if ($j >= $cache_start && (@$params['no_doubles'] || @$this->xmlrpc))
2344                                                        {
2345                                                                break;  // add event only once on it's startdate
2346                                                        }
2347                                                }
2348                                        }
2349                                }
2350                        }
2351
2352                        $this->repeating_events = Array();
2353                        if($c_cached_ids_repeating)
2354                        {
2355                                for($i=0;$i<$c_cached_ids_repeating;$i++)
2356                                {
2357                                        $this->repeating_events[$i] = $this->so->read_entry($cached_event_ids_repeating[$i]);
2358                                        if($this->debug)
2359                                        {
2360                                                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";
2361                                        }
2362                                }
2363                                for($date=mktime(0,0,0,$smonth,$sday,$syear);$date<=$edate;$date += 86400)
2364                                {
2365                                        if($this->debug)
2366                                        {
2367                                                $search_date = date('Ymd',$date);
2368                                                echo '<!-- Calling check_repeating_events('.$search_date.') -->'."\n";
2369                                        }
2370                                        $this->check_repeating_events($date);
2371                                        if($this->debug)
2372                                        {
2373                                                echo '<!-- Total events found matching '.$search_date.' = '.count($this->cached_events[$search_date]).' -->'."\n";
2374                                                for($i=0;$i<count($this->cached_events[$search_date]);$i++)
2375                                                {
2376                                                        echo '<!-- Date: '.$search_date.' ['.$i.'] = '.$this->cached_events[$search_date][$i]['id'].' -->'."\n";
2377                                                }
2378                                        }
2379                                }
2380                        }
2381                        $retval = Array();
2382                        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)))
2383                        {
2384                                if(is_array($this->cached_events[$j]))
2385                                {
2386                                        if ($this->xmlrpc)
2387                                        {
2388                                                foreach($this->cached_events[$j] as $event)
2389                                                {
2390                                                        $retval[] = $this->xmlrpc_prepare($event);
2391                                                }
2392                                        }
2393                                        else
2394                                        {
2395                                                $retval[$j] = $this->cached_events[$j];
2396                                        }
2397                                }
2398                        }
2399                        //echo "store_to_cache(".print_r($params,True).")=<pre>".print_r($retval,True)."</pre>\n";
2400                        $this->so->cal->event = $cached_event;
2401                        return $retval;
2402                }
2403
2404                function xmlrpc_prepare(&$event)
2405                {
2406                        $event['rights'] = $this->grants[$event['owner']];
2407
2408                        foreach(array('start','end','modtime','recur_enddate') as $name)
2409                        {
2410                                if (isset($event[$name]))
2411                                {
2412                                        $event[$name] = $GLOBALS['server']->date2iso8601($event[$name]);
2413                                }
2414                        }
2415                        if (is_array($event['recur_exception']))
2416                        {
2417                                foreach($event['recur_exception'] as $key => $timestamp)
2418                                {
2419                                        $event['recur_exception'][$key] = $GLOBALS['server']->date2iso8601($timestamp);
2420                                }
2421                        }
2422                        static $user_cache = array();
2423
2424                        if (!is_object($GLOBALS['phpgw']->perferences))
2425                        {
2426                                $GLOBALS['phpgw']->perferences = CreateObject('phpgwapi.preferences');
2427                        }
2428                        foreach($event['participants'] as $user_id => $status)
2429                        {
2430                                if (!isset($user_cache[$user_id]))
2431                                {
2432                                        $user_cache[$user_id] = array(
2433                                                'name'   => $GLOBALS['phpgw']->common->grab_owner_name($user_id),
2434                                                'email'  => $GLOBALS['phpgw']->perferences->email_address($user_id)
2435                                        );
2436                                }
2437                                $event['participants'][$user_id] = $user_cache[$user_id] + array(
2438                                        'status' => $status,
2439                                );
2440                        }
2441                        if (is_array($event['alarm']))
2442                        {
2443                                foreach($event['alarm'] as $id => $alarm)
2444                                {
2445                                        $event['alarm'][$id]['time'] = $GLOBALS['server']->date2iso8601($alarm['time']);
2446                                        if ($alarm['owner'] != $GLOBALS['phpgw_info']['user']['account_id'])
2447                                        {
2448                                                unset($event['alarm'][$id]);
2449                                        }
2450                                }
2451                        }
2452                        $event['category'] = $GLOBALS['server']->cats2xmlrpc(explode(',',$event['category']));
2453
2454                        // using access={public|privat} in all modules via xmlrpc
2455                        $event['access'] = $event['public'] ? 'public' : 'privat';
2456                        unset($event['public']);
2457
2458                        return $event;
2459                }
2460
2461                /* Begin Appsession Data */
2462                function store_to_appsession($event)
2463                {
2464                        $GLOBALS['phpgw']->session->appsession('entry','calendar',$event);
2465                }
2466
2467                function restore_from_appsession()
2468                {
2469                        $this->event_init();
2470                        $event = $GLOBALS['phpgw']->session->appsession('entry','calendar');
2471                        $this->so->cal->event = $event;
2472                        return $event;
2473                }
2474                /* End Appsession Data */
2475
2476                /* Begin of SO functions */
2477                function get_cached_event()
2478                {
2479                        return $this->so->get_cached_event();
2480                }
2481
2482                function add_attribute($var,$value,$index='**(**')
2483                {
2484                        $this->so->add_attribute($var,$value,$index);
2485                }
2486
2487                function event_init()
2488                {
2489                        $this->so->event_init();
2490                }
2491
2492                function set_start($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2493                {
2494                        $this->so->set_start($year,$month,$day,$hour,$min,$sec);
2495                }
2496
2497                function set_end($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2498                {
2499                        $this->so->set_end($year,$month,$day,$hour,$min,$sec);
2500                }
2501
2502                function set_title($title='')
2503                {
2504                        $this->so->set_title($title);
2505                }
2506
2507                function set_description($description='')
2508                {
2509                        $this->so->set_description($description);
2510                }
2511                function set_ex_participants($ex_participants='')
2512                {
2513                        $this->so->set_ex_participants($ex_participants);
2514                }
2515
2516                function set_class($class)
2517                {
2518                        $this->so->set_class($class);
2519                }
2520
2521                function set_category($category='')
2522                {
2523                        $this->so->set_category($category);
2524                }
2525
2526                function set_alarm($alarm)
2527                {
2528                        $this->so->set_alarm($alarm);
2529                }
2530
2531                function set_recur_none()
2532                {
2533                        $this->so->set_recur_none();
2534                }
2535
2536                function set_recur_daily($year,$month,$day,$interval)
2537                {
2538                        $this->so->set_recur_daily($year,$month,$day,$interval);
2539                }
2540
2541                function set_recur_weekly($year,$month,$day,$interval,$weekdays)
2542                {
2543                        $this->so->set_recur_weekly($year,$month,$day,$interval,$weekdays);
2544                }
2545
2546                function set_recur_monthly_mday($year,$month,$day,$interval)
2547                {
2548                        $this->so->set_recur_monthly_mday($year,$month,$day,$interval);
2549                }
2550
2551                function set_recur_monthly_wday($year,$month,$day,$interval)
2552                {
2553                        $this->so->set_recur_monthly_wday($year,$month,$day,$interval);
2554                }
2555
2556                function set_recur_yearly($year,$month,$day,$interval)
2557                {
2558                        $this->so->set_recur_yearly($year,$month,$day,$interval);
2559                }
2560                /* End of SO functions */
2561
2562                function prepare_matrix($interval,$increment,$part,$fulldate)
2563                {
2564                        for($h=0;$h<24;$h++)
2565                        {
2566                                for($m=0;$m<$interval;$m++)
2567                                {
2568                                        $index = (($h * 10000) + (($m * $increment) * 100));
2569                                        $time_slice[$index]['marker'] = '&nbsp';
2570                                        $time_slice[$index]['description'] = '';
2571                                }
2572                        }
2573                        foreach($this->cached_events[$fulldate] as $event)
2574                        {
2575                                if ($event['participants'][$part] == 'R')
2576                                {
2577                                        continue;       // dont show rejected invitations, as they are free time
2578                                }
2579                                $eventstart = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset);
2580                                $eventend = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset);
2581                                $start = ($eventstart['hour'] * 10000) + ($eventstart['minute'] * 100);
2582                                $starttemp = $this->splittime("$start",False);
2583                                $subminute = 0;
2584                                for($m=0;$m<$interval;$m++)
2585                                {
2586                                        $minutes = $increment * $m;
2587                                        if((int)$starttemp['minute'] > $minutes && (int)$starttemp['minute'] < ($minutes + $increment))
2588                                        {
2589                                                $subminute = ($starttemp['minute'] - $minutes) * 100;
2590                                        }
2591                                }
2592                                $start -= $subminute;
2593                                $end =  ($eventend['hour'] * 10000) + ($eventend['minute'] * 100);
2594                                $endtemp = $this->splittime("$end",False);
2595                                $addminute = 0;
2596                                for($m=0;$m<$interval;$m++)
2597                                {
2598                                        $minutes = ($increment * $m);
2599                                        if($endtemp['minute'] < ($minutes + $increment) && $endtemp['minute'] > $minutes)
2600                                        {
2601                                                $addminute = ($minutes + $increment - $endtemp['minute']) * 100;
2602                                        }
2603                                }
2604                                $end += $addminute;
2605                                $starttemp = $this->splittime("$start",False);
2606                                $endtemp = $this->splittime("$end",False);
2607
2608                                for($h=$starttemp['hour'];$h<=$endtemp['hour'];$h++)
2609                                {
2610                                        $startminute = 0;
2611                                        $endminute = $interval;
2612                                        $hour = $h * 10000;
2613                                        if($h == (int)$starttemp['hour'])
2614                                        {
2615                                                $startminute = ($starttemp['minute'] / $increment);
2616                                        }
2617                                        if($h == (int)$endtemp['hour'])
2618                                        {
2619                                                $endminute = ($endtemp['minute'] / $increment);
2620                                        }
2621                                        $private = $this->is_private($event,$part);
2622                                        $time_display = $GLOBALS['phpgw']->common->show_date($eventstart['raw'],$this->users_timeformat).'-'.$GLOBALS['phpgw']->common->show_date($eventend['raw'],$this->users_timeformat);
2623                                        $time_description = '('.$time_display.') '.$this->get_short_field($event,$private,'title').$this->display_status($event['participants'][$part]);
2624                                        for($m=$startminute;$m<$endminute;$m++)
2625                                        {
2626                                                $index = ($hour + (($m * $increment) * 100));
2627                                                $time_slice[$index]['marker'] = '-';
2628                                                $time_slice[$index]['description'] = $time_description;
2629                                                $time_slice[$index]['id'] = $event['id'];
2630                                        }
2631                                }
2632                        }
2633                        return $time_slice;
2634                }
2635
2636                /*!
2637                @function set_status
2638                @abstract set the participant response $status for event $cal_id and notifies the owner of the event
2639                */
2640                function set_status($cal_id,$status)
2641                {
2642                        $status2msg = array(
2643                                REJECTED  => MSG_REJECTED,
2644                                TENTATIVE => MSG_TENTATIVE,
2645                                ACCEPTED  => MSG_ACCEPTED
2646                        );
2647                        if (!isset($status2msg[$status]))
2648                        {
2649                                return False;
2650                        }
2651                        $event = $this->so->read_entry($cal_id);
2652                        $account_id = $GLOBALS['phpgw_info']['user']['account_id'];
2653                        if(($status2msg[$status] == "5" && $event['participants'][$account_id] == "A") ||
2654                         ($status2msg[$status] == "3" && $event['participants'][$account_id] == "R")) {
2655                                return True;
2656                        }
2657                        $this->so->set_status($cal_id,$status);
2658                        $event = $this->so->read_entry($cal_id);
2659                        $this->send_update($status2msg[$status],$event['participants'],$event);
2660
2661                }
2662
2663                /*!
2664                @function update_requested
2665                @abstract checks if $userid has requested (in $part_prefs) updates for $msg_type
2666                @syntax update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2667                @param $userid numerical user-id
2668                @param $part_prefs preferces of the user $userid
2669                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2670                @param $old_event Event before the change
2671                @param $new_event Event after the change
2672                @returns 0 = no update requested, > 0 update requested
2673                */
2674                function update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2675                {
2676                        if ($msg_type == MSG_ALARM)
2677                        {
2678                                return True;    // always True for now
2679                        }
2680                        $want_update = 0;
2681
2682                        // the following switch fall-through all cases, as each included the following too
2683                        //
2684                        $msg_is_response = $msg_type == MSG_REJECTED || $msg_type == MSG_ACCEPTED || $msg_type == MSG_TENTATIVE;
2685
2686                        switch($ru = $part_prefs['calendar']['receive_updates'])
2687                        {
2688                                case 'responses':
2689                                        if ($msg_is_response)
2690                                        {
2691                                                ++$want_update;
2692                                        }
2693                                case 'modifications':
2694                                        if ($msg_type == MSG_MODIFIED)
2695                                        {
2696                                                ++$want_update;
2697                                        }
2698                                case 'time_change_4h':
2699                                case 'time_change':
2700                                        $diff = max(abs($this->maketime($old_event['start'])-$this->maketime($new_event['start'])),
2701                                                abs($this->maketime($old_event['end'])-$this->maketime($new_event['end'])));
2702                                        $check = $ru == 'time_change_4h' ? 4 * 60 * 60 - 1 : 0;
2703                                        if ($msg_type == MSG_MODIFIED && $diff > $check)
2704                                        {
2705                                                ++$want_update;
2706                                        }
2707                                case 'add_cancel':
2708                                        if ($old_event['owner'] == $userid && $msg_is_response ||
2709                                                $msg_type == MSG_DELETED || $msg_type == MSG_ADDED)
2710                                        {
2711                                                ++$want_update;
2712                                        }
2713                                        break;
2714                                case 'no':
2715                                        break;
2716                        }
2717                        //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";
2718                        return $want_update > 0;
2719                }
2720
2721        function create_vcard($event_array)
2722        {
2723        if(!is_array($event_array))
2724                return null;
2725        $tmpattach="BEGIN:VCALENDAR\n"
2726        ."PRODID:-//Expresso Livre//Calendar//EN\n"
2727        ."VERSION:1.0\n";
2728                foreach ($event_array as $event)
2729                {
2730                        // It translates int to string
2731                        if (!is_object($event) && !is_array($event) || !array_key_exists  ('end', $event))
2732                                $event = $event_array;
2733                        if ( $event['end']['month'] < 10 )
2734                                $end_event_month="0".$event['end']['month'];
2735                        else
2736                                $end_event_month=$event['end']['month'];
2737                        if ( $event['start']['month'] < 10 )
2738                                $start_event_month="0".$event['start']['month'];
2739                        else
2740                                $start_event_month=$event['start']['month'];
2741                        if ( $event['end']['mday'] < 10 )
2742                                $end_event_day="0".$event['end']['mday'];
2743                        else
2744                                $end_event_day=$event['end']['mday'];
2745                        if ( $event['start']['mday'] < 10 )
2746                                $start_event_day="0".$event['start']['mday'];
2747                        else
2748                                $start_event_day=$event['start']['mday'];
2749                        if ( $event['start']['hour'] < 10)
2750                                $start_event_hour="0".$event['start']['hour'];
2751                        else
2752                                $start_event_hour=$event['start']['hour'];
2753                        if ( $event['end']['hour'] < 10)
2754                                $end_event_hour="0".$event['end']['hour'];
2755                        else
2756                                $end_event_hour=$event['end']['hour'];
2757                               
2758                        if ( $event['start']['min'] < 10)
2759                                $start_event_min="0".$event['start']['min'];
2760                        else
2761                                $start_event_min=$event['start']['min'];
2762                        if ( $event['end']['min'] < 10)
2763                                $end_event_min="0".$event['end']['min'];
2764                        else
2765                                $end_event_min=$event['end']['min'];   
2766               
2767
2768                        $tmpattach.="BEGIN:VEVENT\n"
2769                        ."DTSTART:".$event['start'][year].$start_event_month.$start_event_day."T".$start_event_hour.$start_event_min."00Z\n"
2770                        ."DTEND:".$event[end][year].$end_event_month.$end_event_day."T".$end_event_hour.$end_event_min."00Z\n"
2771                        ."UID:Expresso-".$event[id].$event[uid]."\n"
2772                        ."LAST-MODIFIED:".time()."\n"
2773                        ."DESCRIPTION:".$event[description]."\n"
2774                        ."SUMMARY:".$event[title]."\n"
2775                        ."LOCATION:".$event[location]."\n"
2776                        ."END:VEVENT"."\n";
2777                }
2778                        $tmpattach.="END:VCALENDAR\n";
2779                        return $tmpattach;
2780}
2781
2782                /*!
2783                @function send_update
2784                @abstract sends update-messages to certain participants of an event
2785                @syntax send_update($msg_type,$to_notify,$old_event,$new_event=False)
2786                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2787                @param $to_notify array with numerical user-ids as keys (!) (value is not used)
2788                @param $old_event Event before the change
2789                @param $new_event Event after the change
2790                */
2791                function send_update($msg_type,$to_notify,$old_event,$new_event=False,$user=False)
2792                {
2793                       
2794                        //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";
2795                        if (!is_array($to_notify))
2796                        {
2797                                $to_notify = array();
2798                        }
2799                        $owner = $old_event ? $old_event['owner'] : $new_event['owner'];
2800                        if ($owner && !isset($to_notify[$owner]) && $msg_type != MSG_ALARM)
2801                        {
2802                                $to_notify[$owner] = 'owner';   // always include the event-owner
2803                        }
2804                        $version = $GLOBALS['phpgw_info']['apps']['calendar']['version'];
2805
2806                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences();
2807                        $sender = $GLOBALS['phpgw_info']['user']['email'];
2808
2809                        $temp_tz_offset = $this->prefs['common']['tz_offset'];
2810                        $temp_timeformat = $this->prefs['common']['timeformat'];
2811                        $temp_dateformat = $this->prefs['common']['dateformat'];
2812
2813                        $tz_offset = ((60 * 60) * (int)$temp_tz_offset);
2814
2815                        if($old_event != False)
2816                        {
2817                                $t_old_start_time = $this->maketime($old_event['start']);
2818                                if($t_old_start_time < (time() - 86400))
2819                                {
2820                                        return False;
2821                                }
2822                        }
2823
2824                        $temp_user = $GLOBALS['phpgw_info']['user'];
2825
2826                        if (!$user)
2827                        {
2828                                $user = $this->owner;
2829                        }
2830                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences($user);
2831
2832                        $event = $msg_type == MSG_ADDED || $msg_type == MSG_MODIFIED ? $new_event : $old_event;
2833                        if($old_event != False)
2834                        {
2835                                $old_starttime = $t_old_start_time - $GLOBALS['phpgw']->datetime->tz_offset;
2836                        }
2837                        $starttime = $this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
2838                        $endtime   = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
2839
2840                        switch($msg_type)
2841                        {
2842                                case MSG_DELETED:
2843                                        $action = lang('Canceled');
2844                                        $msg = 'Canceled';
2845                                        $msgtype = '"calendar";';
2846                                        $method = 'cancel';
2847                                        $typesend = 1;
2848                                        break;
2849                                case MSG_MODIFIED:
2850                                        $action = lang('Modified');
2851                                        $msg = 'Modified';
2852                                        $msgtype = '"calendar"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2853                                        $method = 'request';
2854                                        $typesend = 2;
2855                                        break;
2856                                case MSG_ADDED:
2857                                        $action = lang('Added');
2858                                        $msg = 'Added';
2859                                        $msgtype = '"calendar"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
2860                                        $method = 'request';
2861                                        $typesend = 3;
2862                                        break;
2863                                case MSG_REJECTED:
2864                                        $action = lang('Rejected');
2865                                        $msg = 'Response';
2866                                        $msgtype = '"calendar";';
2867                                        $method = 'reply';
2868                                        $typesend = 4;
2869                                        break;
2870                                case MSG_TENTATIVE:
2871                                        $action = lang('Tentative');
2872                                        $msg = 'Response';
2873                                        $msgtype = '"calendar";';
2874                                        $method = 'reply';
2875                                        $typesend = 5;
2876                                        break;
2877                                case MSG_ACCEPTED:
2878                                        $action = lang('Accepted');
2879                                        $msg = 'Response';
2880                                        $msgtype = '"calendar";';
2881                                        $method = 'reply';
2882                                        $typesend = 6;
2883                                        break;
2884                                case MSG_ALARM:
2885                                        $action = lang('Alarm');
2886                                        $msg = 'Alarm';
2887                                        $msgtype = '"calendar";';
2888                                        $method = 'publish';    // duno if thats right
2889                                        $typesend = 7;
2890                                        break;
2891                                default:
2892                                        $method = 'publish';
2893                                        $typesend = 8;
2894                        }
2895                        $notify_msg = $this->prefs['calendar']['notify'.$msg];
2896                        if (empty($notify_msg))
2897                        {
2898                                $notify_msg = $this->prefs['calendar']['notifyAdded'];  // use a default
2899                        }
2900                        $details = array(                       // event-details for the notify-msg
2901                                'id'          => $msg_type == MSG_ADDED ? $new_event['id'] : $old_event['id'],
2902                                'action'      => $action,
2903                        );
2904                        $event_arr = $this->event2array($event);
2905                        foreach($event_arr as $key => $val)
2906                        {
2907                                $details[$key] = $val['data'];
2908                        }
2909                       
2910                        $details['participants'] = implode("\n",$details['participants']);
2911
2912                        $details['link'] = $GLOBALS['phpgw_info']['server']['webserver_url'].'/index.php?menuaction=calendar.uicalendar.view&cal_id='.$event['id'];
2913                        // if url is only a path, try guessing the rest ;-)
2914                        if ($GLOBALS['phpgw_info']['server']['webserver_url'][0] == '/')
2915                        {
2916                                $details['link'] = ($GLOBALS['phpgw_info']['server']['enforce_ssl'] ? 'https://' : 'http://').
2917                                        ($GLOBALS['phpgw_info']['server']['hostname'] ? $GLOBALS['phpgw_info']['server']['hostname'] : 'localhost').
2918                                        $details['link'];
2919                        }
2920                       
2921                        //Seta o email usando phpmailer
2922                        define('PHPGW_INCLUDE_ROOT','../');     
2923                        define('PHPGW_API_INC','../phpgwapi/inc');     
2924                        include_once(PHPGW_API_INC.'/class.phpmailer.inc.php');
2925                        $mail = new PHPMailer();
2926                        $mail->IsSMTP();
2927                        $boemailadmin = CreateObject('emailadmin.bo');
2928                        $emailadmin_profile = $boemailadmin->getProfileList();
2929                        $emailadmin = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
2930               
2931                        $mail->Host = $emailadmin['smtpServer'];
2932                        $mail->Port = $emailadmin['smtpPort'];
2933                        $mail->From = $GLOBALS['phpgw']->preferences->values['email'];
2934                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
2935                        $mail->IsHTML(true);
2936
2937                        // Aqui ï¿œ enviado o email
2938                        foreach($to_notify as $userid => $statusid)
2939                        {
2940                                $mail->ClearAttachments();
2941                               
2942                                $userid = (int)$userid;
2943
2944                                if ($statusid == 'R' || $GLOBALS['phpgw']->accounts->get_type($userid) == 'g')
2945                                {
2946                                        continue;       // dont notify rejected participants
2947                                }
2948                                if($userid != $GLOBALS['phpgw_info']['user']['account_id'] ||  $msg_type == MSG_ALARM)
2949                                {
2950                                        print_debug('Msg Type',$msg_type);
2951                                        print_debug('UserID',$userid);
2952
2953                                        $preferences = CreateObject('phpgwapi.preferences',$userid);
2954                                        $part_prefs = $preferences->read_repository();
2955
2956                                        if (!$this->update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event))
2957                                        {
2958                                                continue;
2959                                        }
2960                                        $GLOBALS['phpgw']->accounts->get_account_name($userid,$lid,$details['to-firstname'],$details['to-lastname']);
2961                                        $details['to-fullname'] = $GLOBALS['phpgw']->common->display_fullname('',$details['to-firstname'],$details['to-lastname']);
2962
2963                                        $to = $preferences->email_address($userid);
2964                                       
2965                                        if (empty($to) || $to[0] == '@' || $to[0] == '$')       // we have no valid email-address
2966                                        {
2967                                                //echo "<p>bocalendar::send_update: Empty email adress for user '".$details['to-fullname']."' ==> ignored !!!</p>\n";
2968                                                continue;
2969                                        }
2970                                        print_debug('Email being sent to',$to);
2971
2972                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $part_prefs['common']['tz_offset'];
2973                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $part_prefs['common']['timeformat'];
2974                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $part_prefs['common']['dateformat'];
2975
2976                                        $GLOBALS['phpgw']->datetime->tz_offset = ((60 * 60) * (int)$GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset']);
2977
2978                                        if($old_starttime)
2979                                        {
2980                                                $details['olddate'] = $GLOBALS['phpgw']->common->show_date($old_starttime);
2981                                        }
2982                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
2983                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
2984                                       
2985                                       
2986                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
2987                                       
2988                                        switch($part_prefs['calendar']['update_format'])
2989                                        {
2990                                                case  'extended':
2991                                                        //$body .= "\n\n".lang('Event Details follow').":\n";
2992                                                        $body = '';
2993                                                        $body .= "<br>".lang('Event Details follow')." :: ";
2994                                                        foreach($event_arr as $key => $val)
2995                                                        {
2996                                                                // titulo
2997                                                                if($key =='title')
2998                                                                {
2999                                                                        $var1 = $val['field'];
3000                                                                        $vardata1 = $details[$key];
3001                                                                }
3002                                                                //descricao
3003                                                                if($key =='description')
3004                                                                {
3005                                                                        $var2 = $val['field'];
3006                                                                        $vardata2 = $details[$key];
3007                                                                }
3008                                                                //dt inicio
3009                                                                if($key =='startdate')
3010                                                                {
3011                                                                        switch(trim($part_prefs['common']['dateformat']))
3012                                                                        {
3013                                                                               
3014                                                                                case ($part_prefs['common']['dateformat'] === "m/d/Y" || $part_prefs['common']['dateformat'] === "m-d-Y" || $part_prefs['common']['dateformat'] === "m.d.Y"):
3015                                                                                        $var3 = $val['field'];
3016                                                                                        $vardata3 = $details[$key];
3017                                                                                        $newmounth3 = substr($vardata3,0,2);
3018                                                                                        $newday3 = substr($vardata3,3,2);
3019                                                                                        $newyear3 = substr($vardata3,6,4);
3020                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3021                                                                                        break;
3022                                                                                       
3023                                                                                case    ($part_prefs['common']['dateformat'] === "Y/d/m" || $part_prefs['common']['dateformat'] === "Y-d-m" || $part_prefs['common']['dateformat'] === "Y.d.m"):
3024
3025                                                                                        $var3 = $val['field'];
3026                                                                                        $vardata3 = $details[$key];
3027                                                                                        $newyear3 = substr($vardata3,0,4);
3028                                                                                        $newday3 = substr($vardata3,5,2);
3029                                                                                        $newmounth3 = substr($vardata3,8,2);
3030                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3031                                                                                        break;
3032
3033                                                                                case ($part_prefs['common']['dateformat'] === "Y/m/d" || $part_prefs['common']['dateformat'] === "Y-m-d" || $part_prefs['common']['dateformat'] === "Y.m.d"):
3034
3035                                                                                        $var3 = $val['field'];
3036                                                                                        $vardata3 = $details[$key];
3037                                                                                        $newyear3 = substr($vardata3,0,4);
3038                                                                                        $newmounth3 = substr($vardata3,5,2);
3039                                                                                        $newday3 = substr($vardata3,8,2);
3040                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3041                                                                                        break;
3042
3043                                                                                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"):
3044                                                                               
3045                                                                                        $var3 = $val['field'];
3046                                                                                        $vardata3 = $details[$key];
3047                                                                                        $newday3 = substr($vardata3,0,2);
3048                                                                                        $newmounth3 = substr($vardata3,3,2);
3049                                                                                        $newyear3 = substr($vardata3,6,4);
3050                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3051                                                                                        break;
3052                                                                       
3053                                                                        }
3054                                                                       
3055                                                                }
3056                                                                //dt final
3057                                                                if($key =='enddate')
3058                                                                {
3059                                                                        $var4 = $val['field'];
3060                                                                        $vardata4 = $details[$key];
3061                                                                }
3062                                                                //localizacao
3063                                                                if($key =='location')
3064                                                                {
3065                                                                        $var8 = $val['field'];
3066                                                                        $vardata8 = $details[$key];
3067                                                                }
3068                                                                //participantes
3069                                                                if($key =='participants')
3070                                                                {
3071                                                                        $var5 = $val['field'];
3072                                                                        foreach($val['data'] as $NewKey => $NewVal)
3073                                                                        {
3074                                                                                //Research inside of ldap ( Pesquisa dentro do ldap )
3075                                                                                $newvalue = $this->so->search_uidNumber($to);
3076                                                                                foreach($newvalue as $tmp)
3077                                                                                {
3078                                                                                        $tmpmail = $tmp['mail'][0];
3079                                                                                        $tmpuid = $tmp['uidnumber'][0];
3080                                                                                        if( trim($tmpmail) == trim($to) & trim($tmpuid) == trim($NewKey))
3081                                                                                        {
3082                                                                                                        if($typesend == 3)
3083                                                                                                        {
3084
3085                                                                                                                $lang1 = lang("To See Commitment");
3086                                                                                                                $varbuttom = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.view&cal_id=$event[id]&date=$newall3' method='POST'>
3087                                                                                                                                                                  <input type='submit' value='$lang1'>
3088                                                                                                                                                                   </form>";
3089                                                                                                                $lang2 = lang("To accept");
3090                                                                                                                $varbuttom1 ="<input type='submit' value='$lang2' onClick='javascript:window.open(\"".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.set_action&cal_id=$event[id]&action=3&response=1\",\"frontpage\",\"height=100,width=400,statusbar=no,toolbar=no,scrollbars=no,menubar=no,left=300,top=200\")'>";
3091
3092                                                                                                                $lang3 = lang("To reject");
3093                                                                                                                $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\")'>";
3094                                                                                                               
3095                                                                                                                $lang4 = lang("Alarm");
3096                                                                                                                $varbuttom3 = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uialarm.manager method='POST'>
3097                                                                                                                                                                  <input type='submit' value='$lang4'>
3098                                                                                                                                                                  <input type='hidden' name='cal_id' value=$event[id]>
3099                                                                                                                                                                   </form>";
3100                                                                                                                                                                   
3101                                                                                                                $lang5 = lang("To Delegate");
3102                                                                                                                $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'>
3103                                                                                                                                                                  <input type='submit' value='$lang5'>
3104                                                                                                                                                                   </form>";
3105                                                                                                        }
3106                                                                                                        else
3107                                                                                                        {
3108                                                                                                                        $varbuttom  = "";
3109                                                                                                                        $varbuttom1 = "";
3110                                                                                                                        $varbuttom2 = "";
3111                                                                                                                        $varbuttom3 = "";
3112                                                                                                                        $varbuttom4 = "";
3113                                                                                                        }
3114                                                                                        }
3115                                                                                        // It only mounts variavel with the name of the participants of the list ( Monta a variavel somente com o nome dos participantes da lista)
3116                                                                                        if($typesend == 3)
3117                                                                                        {
3118                                                                                                list($tmpvardata5,$tmp2vardata5) = explode("(",$NewVal);
3119                                                                                                $vardata5 = $tmpvardata5."<br>";
3120                                                                                        }
3121                                                                                        else
3122                                                                                        {
3123                                                                                                $vardata5 = $NewVal."<br>";
3124                                                                                        }
3125                                                                               
3126                                                                                }
3127                                                                                $vardata6 .= $vardata5;
3128                                                                                unset($vardata5);
3129                                                                        }
3130                                                                }               
3131                                                        }
3132                                                        //To mount the message as text/html (Para montar a mensagem como text/html - /phpgwapi/inc/class.send.inc.php )
3133                                                        $content_type = "text/html";
3134                                                        //It mounts the body of the message (Monta o corpo da mensagem)
3135                                                       
3136                                                        // A constante PHPGW_APP_TPL nao existe para envio de alarmes (cront, asyncservice).
3137                                                        define ("PHPGW_APP_TPL",PHPGW_API_INC . "/../../calendar/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."");
3138                                                       
3139                                                        $body = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
3140                                                        $body->set_file(Array('calendar' => 'body_email.tpl'));
3141                                                        $body->set_block('calendar','list');
3142                                                        $var = Array(
3143                                                                'script'                        => $script,
3144                                                                'subject'                       => $body1,
3145                                                                'var1'                          => $var1,
3146                                                                'vardata1'                      => $vardata1,
3147                                                                'var2'                          => $var2,
3148                                                                'vardata2'                      => $vardata2,
3149                                                                'var3'                          => $var3,
3150                                                                'vardata3'                      => $vardata3,
3151                                                                'var4'                          => $var4,
3152                                                                'vardata4'                      => $vardata4,
3153                                                                'var5'                          => $var5,
3154                                                                'vardata6'                      => $vardata6,
3155                                                                'var8'                          => $var8,
3156                                                                'vardata8'                      => $vardata8,                                                   
3157                                                                'varbuttom'                     => $varbuttom,
3158                                                                'varbuttom1'            => $varbuttom1,
3159                                                                'varbuttom2'            => $varbuttom2,
3160                                                                'varbuttom3'            => $varbuttom3,
3161                                                                'varbuttom4'            => $varbuttom4
3162                                                               
3163                                                        );
3164                                                        $body->set_var($var);
3165                                                        $tmpbody = $body->fp('out','list');
3166                                                                                                               
3167                                                        break;
3168
3169                                                case 'ical':
3170                                                        $content_type = "calendar; method=$method; name=calendar.ics";
3171/*                                                      if ($body != '')
3172                                                        {
3173                                                                $boundary = '----Message-Boundary';
3174                                                                $body .= "\n\n\n$boundary\nContent-type: text/$content_type\n".
3175                                                                        "Content-Disposition: inline\nContent-transfer-encoding: 7BIT\n\n";
3176                                                                $content_type = '';
3177                                                        }
3178*/
3179                                                        $body = ExecMethod('calendar.boicalendar.export',array(
3180                                                                'l_event_id'  => $event['id'],
3181                                                                'method'      => $method,
3182                                                                'chunk_split' => False
3183                                                        ));
3184                                                        break;
3185                                        }
3186                                        $mail->AddAddress($to);
3187                                        $mail->Body = $tmpbody;
3188                                        $mail->From = $sender;
3189                                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3190                                        $mail->Sender = $mail->From;
3191                                        $mail->SenderName = $mail->FromName;
3192                                        $mail->Subject = $subject;
3193                                        unset($vardata5);
3194                                        unset($vardata6);
3195                                }
3196                        }
3197
3198                        //Inicializa variï¿œvel de retorno.
3199                        $returncode=true;                       
3200                        if(count($mail->to)) {                         
3201                                // Envia aviso a todos os participantes.
3202                                if(!$mail->Send()) {                           
3203                                        $returncode = false;
3204                                        $errorInfo['participants'] = $mail->ErrorInfo;
3205                                }
3206                                else
3207                                        $returncode =  true;
3208                        }
3209                       
3210                        if(count($to_notify) && $this->ex_participants){
3211                                $mail->ClearAllRecipients();
3212                                $var = explode(",",trim($this->ex_participants));
3213                                $to = array();
3214                                if(!$subject) {
3215                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
3216                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
3217                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
3218                                }
3219                               
3220                                foreach($var as $index => $ex_participant){
3221                                        $ex_participant = trim($ex_participant);
3222                                        $ex_participant = preg_replace('#"(.*)" <(.*)\@(.*)\.(.*)>#','\\2@\\3.\\4',$ex_participant);
3223                                                if($ex_participant)
3224                                                        $to[] = $ex_participant;
3225                                }               
3226                               
3227                                foreach($to as $i => $to_array)
3228                                        $mail->AddAddress($to_array);
3229                               
3230                                $_body = explode("<hr size='1' width='100%'>",$tmpbody);
3231                                $tmpbody = $_body[0] ? $_body[0] : $subject ;
3232                                $tmpbody.= "<br><b>".lang("external participants").":: </b> ".htmlentities($this->ex_participants);
3233                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3234                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";
3235                                $tmpbody.= "<br><br><hr size='1' width='100%'><font color='red'>"
3236                                .lang("This message was sent by server. You must send a message to sender to confirm this event")."<br>"
3237                                .lang("This is an external event. Even if it added to your expresso its can be changed any time at all")."</font><br>";
3238                               
3239                                if ($GLOBALS['bocalendar']->so->cal->event[start][month] > 10)
3240                                        $event_month=$GLOBALS['bocalendar']->so->cal->event[start][month];
3241                                else
3242                                        $event_month="0".$GLOBALS['bocalendar']->so->cal->event[start][month];
3243                                //attach extern vcard                   
3244                                // define('context','$GLOBALS.bocalendar.so.cal.event');
3245                                $tmpattach = $this->create_vcard($GLOBALS['bocalendar']->so->cal->event);
3246                                if($tmpattach){                                 
3247                                        $tmpbody .="<a href='../index.php?menuaction=calendar.uicalendar.add&date="
3248                                        .$GLOBALS['bocalendar']->so->cal->event[start][year]
3249                                .$event_month
3250                                .$GLOBALS['bocalendar']->so->cal->event[start][mday]
3251                                        ."&hour=".$GLOBALS['bocalendar']->so->cal->event[start][hour]
3252                                        ."&minute=".$GLOBALS['bocalendar']->so->cal->event[start][min]
3253                                        ."&title=".$GLOBALS['bocalendar']->so->cal->event['title']
3254                                        ."&description=".$GLOBALS['bocalendar']->so->cal->event['description']
3255                                        ."&location=".$GLOBALS['bocalendar']->so->cal->event['location']."'>"
3256                                        ."<h2>".lang("Add to my expresso")."</h2>";
3257                                        $tempdir = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
3258                                        srand((double)microtime()*1000000);
3259                                        $random_number = rand(100000000,999999999);
3260                                        $newfilename = md5(time() . getenv("REMOTE_ADDR") . $random_number );
3261                                        $filename = $tempdir . $newfilename;
3262                                        $attach_fd = fopen($filename,"w+");
3263                                        fwrite($attach_fd,$tmpattach);
3264                                        $mail->AddAttachment($filename, "extern.vcard", "base64", "text/plain"); // "application/octet-stream"
3265                                        fclose($attach_fd);
3266                                }
3267                                $mail->From = $sender;
3268                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3269                                $mail->Sender = $mail->From;
3270                                $mail->SenderName = $mail->FromName;
3271                                $mail->Subject = lang("External event from Expresso");
3272                                $mail->Body = $tmpbody;
3273                                                                                                                                               
3274                                if(!$mail->Send())
3275                                {
3276                                        $returncode=false;
3277                                        $errorInfo['ex_participants'] = $mail->ErrorInfo;
3278                                }
3279                                else
3280                                {
3281                                        $returncode=true;
3282                                }
3283                        }
3284
3285
3286                        if((is_int($this->user) && $this->user != $temp_user['account_id']) ||
3287                                (is_string($this->user) && $this->user != $temp_user['account_lid']))
3288                        {
3289                                $GLOBALS['phpgw_info']['user'] = $temp_user;
3290                        }       
3291
3292                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $temp_tz_offset;
3293                        $GLBOALS['phpgw']->datetime->tz_offset = ((60 * 60) * $temp_tz_offset);
3294                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $temp_timeformat;
3295                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $temp_dateformat;
3296                       
3297                        // Notifica por email o criador do compromisso, com as possï¿œveis falhas.                                             
3298                        if($errorInfo) {
3299                                $tmpbody = "<font color='red'>".lang("The following commitment had problems for DELIVERING the NOTIFICATION messages.").".</font><br>";
3300                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3301                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";                         
3302                                $tmpbody.= "<br><u>".lang("Failed to delivery")."</u><br>";
3303                                $failed = false;                               
3304                                if(strstr($errorInfo['participants'],"recipients_failed")){
3305                                        $failed = explode("recipients_failed",$errorInfo['participants']);
3306                                        $tmpbody.= lang("to").": ".$failed[1];
3307                                }
3308                                if(strstr($errorInfo['ex_participants'],"recipients_failed")){
3309                                        $failed = explode("recipients_failed",$errorInfo['ex_participants']);
3310                                        $tmpbody.= lang("to").": ".$failed[1];
3311                                }                       
3312                                if(!$failed) {
3313                                        $tmpbody.= lang("Description").":<br>";
3314                                        $tmpbody.= $errorInfo['participants'];
3315                                        $tmpbody.= "<br>".$errorInfo['ex_participants'];
3316                                }
3317                                $tmpbody.= "<br>".lang("Subject").": ".$subject;
3318                                // Reinicializa o objeto, devido ao erro anterior na entrega.
3319                               
3320                                $mail = new PHPMailer();
3321                                $mail->IsSMTP();
3322                                $mail->Host = $emailadmin['smtpServer'];
3323                                $mail->Port = $emailadmin['smtpPort'];
3324                                $mail->From = $sender;
3325                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3326                                $mail->Sender = $mail->From;
3327                                $mail->SenderName = $mail->FromName;
3328                                $mail->IsHTML(True);
3329                                $mail->Subject = lang("calendar event")." - ".lang("email notification");                                                       
3330                                $mail->Body = $tmpbody;                                 
3331                                $mail->AddAddress($sender);
3332                                if(!$mail->Send())                     
3333                                        $returncode = false;
3334                                else
3335                                        $returncode =  true;
3336                        }
3337                        return $returncode;
3338                }
3339               
3340                function send_alarm($alarm)
3341                {
3342                        //echo "<p>bocalendar::send_alarm("; print_r($alarm); echo ")</p>\n";
3343                       
3344                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->owner = $alarm['owner'];
3345
3346                        if (!$alarm['enabled'] || !$alarm['owner'] || !$alarm['cal_id'] || !($event = $this->so->read_entry($alarm['cal_id'])))
3347                        {
3348                                return False;   // event not found
3349                        }
3350                        if ($alarm['all'])
3351                        {
3352                                $to_notify = $event['participants'];
3353                        }
3354                        elseif ($this->check_perms(PHPGW_ACL_READ,$event))      // checks agains $this->owner set to $alarm[owner]
3355                        {
3356                                $to_notify[$alarm['owner']] = 'A';
3357                        }
3358                        else
3359                        {
3360                                return False;   // no rights
3361                        }
3362                        return $this->send_update(MSG_ALARM,$to_notify,$event,False,$alarm['owner']);
3363                }
3364
3365                function get_alarms($event_id)
3366                {
3367                        return $this->so->get_alarm($event_id);
3368                }
3369
3370                function alarm_today($event,$today,$starttime)
3371                {
3372                        $found = False;
3373                        @reset($event['alarm']);
3374                        $starttime_hi = $GLOBALS['phpgw']->common->show_date($starttime,'Hi');
3375                        $t_appt['month'] =$GLOBALS['phpgw']->common->show_date($today,'m');
3376                        $t_appt['mday'] = $GLOBALS['phpgw']->common->show_date($today,'d');
3377                        $t_appt['year'] = $GLOBALS['phpgw']->common->show_date($today,'Y');
3378                        $t_appt['hour'] = $GLOBALS['phpgw']->common->show_date($starttime,'H');
3379                        $t_appt['min']  = $GLOBALS['phpgw']->common->show_date($starttime,'i');
3380                        $t_appt['sec']  = 0;
3381                        $t_time = $this->maketime($t_appt) - $GLOBALS['phpgw']->datetime->tz_offset;
3382                        $y_time = $t_time - 86400;
3383                        $tt_time = $t_time + 86399;
3384                        print_debug('T_TIME',$t_time.' : '.$GLOBALS['phpgw']->common->show_date($t_time));
3385                        print_debug('Y_TIME',$y_time.' : '.$GLOBALS['phpgw']->common->show_date($y_time));
3386                        print_debug('TT_TIME',$tt_time.' : '.$GLOBALS['phpgw']->common->show_date($tt_time));
3387                        while(list($key,$alarm) = each($event['alarm']))
3388                        {
3389                                if($alarm['enabled'])
3390                                {
3391                                        print_debug('TIME',$alarm['time'].' : '.$GLOBALS['phpgw']->common->show_date($alarm['time']).' ('.$event['id'].')');
3392                                        if($event['recur_type'] != MCAL_RECUR_NONE)   /* Recurring Event */
3393                                        {
3394                                                print_debug('Recurring Event');
3395                                                if($alarm['time'] > $y_time && $GLOBALS['phpgw']->common->show_date($alarm['time'],'Hi') < $starttime_hi && $alarm['time'] < $t_time)
3396                                                {
3397                                                        $found = True;
3398                                                }
3399                                        }
3400                                        elseif($alarm['time'] > $y_time && $alarm['time'] < $t_time)
3401                                        {
3402                                                $found = True;
3403                                        }
3404                                }
3405                        }
3406                        print_debug('Found',$found);
3407                        return $found;
3408                }
3409
3410                function prepare_recipients(&$new_event,$old_event)
3411                {
3412                                               
3413                        // Find modified and deleted users.....
3414                        while(list($old_userid,$old_status) = each($old_event['participants']))
3415                        {
3416                                if(isset($new_event['participants'][$old_userid]))
3417                                {
3418                                        print_debug('Modifying event for user',$old_userid);
3419                                        $this->modified[(int)$old_userid] = $new_status;
3420                                }
3421                                else
3422                                {
3423                                        print_debug('Deleting user from the event',$old_userid);
3424                                        $this->deleted[(int)$old_userid] = $old_status;
3425                                }
3426                        }
3427                        // Find new users.....
3428                        while(list($new_userid,$new_status) = each($new_event['participants']))
3429                        {
3430                                if(!isset($old_event['participants'][$new_userid]))
3431                                {
3432                                        print_debug('Adding event for user',$new_userid);
3433                                        $this->added[$new_userid] = 'U';
3434                                        $new_event['participants'][$new_userid] = 'U';
3435                                }
3436                        }
3437                       
3438                        if(count($this->added) > 0 || count($this->modified) > 0 || count($this->deleted) > 0)
3439                        {
3440                                if(count($this->added) > 0)
3441                                {
3442                                        $this->ex_participants = '';
3443                                        $this->send_update(MSG_ADDED,$this->added,'',$new_event);
3444                                }
3445                                if(count($this->modified) > 0)
3446                                {
3447                                        $this->send_update(MSG_MODIFIED,$this->modified,$old_event,$new_event);
3448                                }
3449                                if(count($this->deleted) > 0)
3450                                {
3451                                        $this->ex_participants = '';
3452                                        $this->send_update(MSG_DELETED,$this->deleted,$old_event);
3453                                }
3454                        }
3455                }
3456
3457                function remove_doubles_in_cache($firstday,$lastday)
3458                {
3459                        $already_moved = Array();
3460                        for($v=$firstday;$v<=$lastday;$v++)
3461                        {
3462                                if (!$this->cached_events[$v])
3463                                {
3464                                        continue;
3465                                }
3466                                $cached = $this->cached_events[$v];
3467                                $this->cached_events[$v] = array();
3468                                while (list($g,$event) = each($cached))
3469                                {
3470                                        $end = date('Ymd',$this->maketime($event['end']));
3471                                        print_debug('EVENT',_debug_array($event,False));
3472                                        print_debug('start',$start);
3473                                        print_debug('v',$v);
3474
3475                                        if (!isset($already_moved[$event['id']]) || $event['recur_type'] && $v > $end)
3476                                        {
3477                                                $this->cached_events[$v][] = $event;
3478                                                $already_moved[$event['id']] = 1;
3479                                                print_debug('Event moved');
3480                                        }
3481                                }
3482                        }
3483                }
3484
3485                function get_dirty_entries($lastmod=-1)
3486                {
3487                        $events = false;
3488                        $event_ids = $this->so->cal->list_dirty_events($lastmod);
3489                        if(is_array($event_ids))
3490                        {
3491                                foreach($event_ids as $key => $id)
3492                                {
3493                                        $events[$id] = $this->so->cal->fetch_event($id);
3494                                }
3495                        }
3496                        unset($event_ids);
3497
3498                        $rep_event_ids = $this->so->cal->list_dirty_events($lastmod,$true);
3499                        if(is_array($rep_event_ids))
3500                        {
3501                                foreach($rep_event_ids as $key => $id)
3502                                {
3503                                        $events[$id] = $this->so->cal->fetch_event($id);
3504                                }
3505                        }
3506                        unset($rep_event_ids);
3507
3508                        return $events;
3509                }
3510
3511                function _debug_array($data)
3512                {
3513                        echo '<br>UI:';
3514                        _debug_array($data);
3515                }
3516
3517                /*!
3518                @function rejected_no_show
3519                @abstract checks if event is rejected from user and he's not the owner and dont want rejected
3520                @param $event to check
3521                @returns True if event should not be shown
3522                */
3523                function rejected_no_show($event)
3524                {
3525                        $ret = !$this->prefs['calendar']['show_rejected'] &&
3526                                $event['owner'] != $this->owner &&
3527                                $event['participants'][$this->owner] == 'R';
3528                        //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";
3529                        return $ret;
3530                }
3531
3532                /* This is called only by list_cals().  It was moved here to remove fatal error in php5 beta4 */
3533                function list_cals_add($id,&$users,&$groups)
3534                {
3535                        $name = $GLOBALS['phpgw']->common->grab_owner_name($id);
3536                        if (($type = $GLOBALS['phpgw']->accounts->get_type($id)) == 'g')
3537                        {
3538                                $arr = &$groups;
3539                        }
3540                        else
3541                        {
3542                                $arr = &$users;
3543                        }
3544                        $arr[$name] = Array(
3545                                'grantor' => $id,
3546                                'value'   => ($type == 'g' ? 'g_' : '') . $id,
3547                                'name'    => $name
3548                        );
3549                }
3550
3551                /*!
3552                @function list_cals
3553                @abstract generate list of user- / group-calendars for the selectbox in the header
3554                @returns alphabeticaly sorted array with groups first and then users
3555                */
3556                function list_cals()
3557                {
3558                        $users = $groups = array();
3559                        foreach($this->grants as $id => $rights)
3560                        {
3561                                $this->list_cals_add($id,$users,$groups);
3562                        }
3563                       
3564                        //by JakJr, melhora de performance na abertura da agenda
3565                        /*if ($memberships = $GLOBALS['phpgw']->accounts->membership($GLOBALS['phpgw_info']['user']['account_id']))
3566                        {
3567                                foreach($memberships as $group_info)
3568                                {
3569                                        $this->list_cals_add($group_info['account_id'],$users,$groups);
3570
3571                                        if ($account_perms = $GLOBALS['phpgw']->acl->get_ids_for_location($group_info['account_id'],PHPGW_ACL_READ,'calendar'))
3572                                        {
3573                                                foreach($account_perms as $id)
3574                                                {
3575                                                        $this->list_cals_add($id,$users,$groups);
3576                                                }
3577                                        }
3578                                }
3579                        }*/
3580                        uksort($users,'strnatcasecmp');
3581                        uksort($groups,'strnatcasecmp');
3582
3583                        return $users + $groups;        // users first and then groups, both alphabeticaly
3584                }
3585
3586          function translate($key,$vars=false, $not_found='*' )
3587          {
3588            if ($this->async)
3589              return $GLOBALS['phpgw']->translation->translate_async($key, $vars);
3590            return lang($key, $vars);
3591          }
3592
3593                /*!
3594                @function event2array
3595                @abstract create array with name, translated name and readable content of each attributes of an event
3596                @syntax event2array($event,$sep='<br>')
3597                @param $event event to use
3598                @returns array of attributes with fieldname as key and array with the 'field'=translated name \
3599                        'data' = readable content (for participants this is an array !)
3600                */
3601                function event2array($event)
3602                {
3603                       
3604                       
3605                  $var['title'] = Array(
3606                                'field'         => $this->translate('Title'),
3607                                'data'          => $event['title']
3608                        );
3609
3610                        // Some browser add a \n when its entered in the database. Not a big deal
3611                        // this will be printed even though its not needed.
3612                        $var['description'] = Array(
3613                                'field' => $this->translate('Description'),
3614                                'data'  => $event['description']
3615                        );
3616
3617                        $var['ex_participants'] = Array(
3618                                'field' => $this->translate('External Participants'),
3619                                'data'  => $event['ex_participants']
3620                        );
3621                       
3622                        $cats = Array();
3623                        $this->cat->categories($this->bo->owner,'calendar');
3624                        if(strpos($event['category'],','))
3625                        {
3626                                $cats = explode(',',$event['category']);
3627                        }
3628                        else
3629                        {
3630                                $cats[] = $event['category'];
3631                        }
3632                        foreach($cats as $cat_id)
3633                        {
3634                                list($cat) = $this->cat->return_single($cat_id);
3635                                $cat_string[] = $cat['name'];
3636                        }
3637                        $var['category'] = Array(
3638                                'field' => $this->translate('Category'),
3639                                'data'  => implode(', ',$cat_string)
3640                        );
3641
3642                        $var['location'] = Array(
3643                                'field' => $this->translate('Location'),
3644                                'data'  => $event['location']
3645                        );
3646
3647                        $var['startdate'] = Array(
3648                                'field' => $this->translate('Start Date/Time'),
3649                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset),
3650                        );
3651
3652                        $var['enddate'] = Array(
3653                                'field' => $this->translate('End Date/Time'),
3654                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset)
3655                        );
3656
3657                        $pri = Array(
3658                                1       => lang('Low'),
3659                                2       => lang('Normal'),
3660                                3       => lang('High')
3661                        );
3662                        $var['priority'] = Array(
3663                                'field' => lang('Priority'),
3664                                'data'  => $pri[$event['priority']]
3665                        );
3666
3667                        $var['owner'] = Array(
3668                                'field' => lang('Created By'),
3669                                'data'  => $GLOBALS['phpgw']->common->grab_owner_name($event['owner'])
3670                        );
3671
3672                        $var['updated'] = Array(
3673                                'field' => lang('Updated'),
3674                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['modtime']) - $GLOBALS['phpgw']->datetime->tz_offset)
3675                        );
3676
3677                        $var['access'] = Array(
3678                                'field' => lang('Access'),
3679                                'data'  => $event['public'] ? lang('Public') : lang('Private')
3680                        );
3681
3682                        if(@isset($event['groups'][0]))
3683                        {
3684                                $cal_grps = '';
3685                                for($i=0;$i<count($event['groups']);$i++)
3686                                {
3687                                        if($GLOBALS['phpgw']->accounts->exists($event['groups'][$i]))
3688                                        {
3689                                                $cal_grps .= ($i>0?'<br>':'').$GLOBALS['phpgw']->accounts->id2name($event['groups'][$i]);
3690                                        }
3691                                }
3692
3693                                $var['groups'] = Array(
3694                                        'field' => lang('Groups'),
3695                                        'data'  => $cal_grps
3696                                );
3697                        }
3698
3699                        $participants = array();
3700                        foreach($event['participants'] as $user => $short_status)
3701                        {
3702                                if($GLOBALS['phpgw']->accounts->exists($user))
3703                                {
3704                                        $participants[$user] = $GLOBALS['phpgw']->common->grab_owner_name($user).' ('.$this->get_long_status($short_status).')';
3705                                }
3706                        }
3707                        $var['participants'] = Array(
3708                                'field' => $this->translate('Participants'),
3709                                'data'  => $participants
3710                        );
3711
3712                        // Repeated Events
3713                        if($event['recur_type'] != MCAL_RECUR_NONE)
3714                        {
3715                                $str = lang($this->rpt_type[$event['recur_type']]);
3716
3717                                $str_extra = array();
3718                                if ($event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['month'] != 0 && $event['recur_enddate']['year'] != 0)
3719                                {
3720                                        $recur_end = $this->maketime($event['recur_enddate']);
3721                                        if($recur_end != 0)
3722                                        {
3723                                                $recur_end -= $GLOBALS['phpgw']->datetime->tz_offset;
3724                                                $str_extra[] = lang('ends').': '.lang($GLOBALS['phpgw']->common->show_date($recur_end,'l')).', '.$this->long_date($recur_end).' ';
3725                                        }
3726                                }
3727                                // only weekly uses the recur-data (days) !!!
3728                                if($event['recur_type'] == MCAL_RECUR_WEEKLY)
3729                                {
3730                                        $repeat_days = array();
3731                                        foreach ($this->rpt_day as $mcal_mask => $dayname)
3732                                        {
3733                                                if ($event['recur_data'] & $mcal_mask)
3734                                                {
3735                                                        $repeat_days[] = lang($dayname);
3736                                                }
3737                                        }
3738                                        if(count($repeat_days))
3739                                        {
3740                                                $str_extra[] = lang('days repeated').': '.implode(', ',$repeat_days);
3741                                        }
3742                                }
3743                                if($event['recur_interval'] != 0)
3744                                {
3745                                        $str_extra[] = lang('Interval').': '.$event['recur_interval'];
3746                                }
3747
3748                                if(count($str_extra))
3749                                {
3750                                        $str .= ' ('.implode(', ',$str_extra).')';
3751                                }
3752
3753                                $var['recure_type'] = Array(
3754                                        'field' => lang('Repetition'),
3755                                        'data'  => $str,
3756                                );
3757                        }
3758
3759                        if (!isset($this->fields))
3760                        {
3761                                $this->custom_fields = CreateObject('calendar.bocustom_fields');
3762                                $this->fields = &$this->custom_fields->fields;
3763                                $this->stock_fields = &$this->custom_fields->stock_fields;
3764                        }
3765                        foreach($this->fields as $field => $data)
3766                        {
3767                                if (!$data['disabled'])
3768                                {
3769                                        if (isset($var[$field]))
3770                                        {
3771                                                $sorted[$field] = $var[$field];
3772                                        }
3773                                        elseif (!isset($this->stock_fields[$field]) && strlen($event[$field]))  // Custom field
3774                                        {
3775                                                $lang = lang($name = substr($field,1));
3776                                                $sorted[$field] = array(
3777                                                        'field' => $lang == $name.'*' ? $name : $lang,
3778                                                        'data'  => $event[$field]
3779                                                );
3780                                        }
3781                                }
3782                                unset($var[$field]);
3783                        }
3784                        foreach($var as $name => $v)
3785                        {
3786                                $sorted[$name] = $v;
3787
3788                        }
3789                        return $sorted;
3790                }
3791
3792                /*!
3793                @function check_set_default_prefs
3794                @abstract sets the default prefs, if they are not already set (on a per pref. basis)
3795                @note It sets a flag in the app-session-data to be called only once per session
3796                */
3797                function check_set_default_prefs()
3798                {
3799                        if (($set = $GLOBALS['phpgw']->session->appsession('default_prefs_set','calendar')))
3800                        {
3801                                return;
3802                        }
3803                        $GLOBALS['phpgw']->session->appsession('default_prefs_set','calendar','set');
3804
3805                        //$default_prefs = $GLOBALS['phpgw']->preferences->default['calendar']; jakjr
3806
3807                        $subject = $this->translate('Calendar Event') . ' - $$action$$: $$startdate$$ $$title$$'."\n";
3808                        $defaults = array(
3809                                'defaultcalendar' => 'week',
3810                                'mainscreen_showevents' => '0',
3811                                'summary'         => 'no',
3812                                'receive_updates' => 'no',
3813                                'update_format'   => 'extended',        // leave it to extended for now, as iCal kills the message-body
3814                                'notifyAdded'     => $subject . $this->translate ('You have a meeting scheduled for %1',array('$$startdate$$')),
3815                                'notifyCanceled'  => $subject . $this->translate ('Your meeting scheduled for %1 has been canceled',array('$$startdate$$')),
3816                                'notifyModified'  => $subject . $this->translate ('Your meeting that had been scheduled for %1 has been rescheduled to %2',array('$$olddate$$','$$startdate$$')),
3817                                'notifyResponse'  => $subject . $this->translate ('On %1 %2 %3 your meeting request for %4', array('$$date$$','$$fullname$$','$$action$$','$$startdate$$')),
3818                                'notifyAlarm'     => $this->translate('Alarm for %1 at %2 in %3',array('$$title$$','$$startdate$$','$$location$$')) . "\n" . $this->translate('Here is your requested alarm.'),
3819                                'show_rejected'   => '0',
3820                                'hide_event_conflict'   => '0',
3821                                'display_status'  => '1',
3822                                'weekdaystarts'   => 'Monday',
3823                                'workdaystarts'   => '9',
3824                                'workdayends'     => '17',
3825                                'interval'        => '30',
3826                                'defaultlength'   => '60',
3827                                'planner_start_with_group' => $GLOBALS['phpgw']->accounts->name2id('Default'),
3828                                'planner_intervals_per_day'=> '4',
3829                                'defaultfilter'   => 'all',
3830                                'default_private' => '0',
3831                                'display_minicals'=> '1',
3832                                'print_black_white'=>'0'
3833                        );
3834                        foreach($defaults as $var => $default)
3835                        {
3836                                if (!isset($default_prefs[$var]) || $default_prefs[$var] == '')
3837                                {
3838                                        $GLOBALS['phpgw']->preferences->add('calendar',$var,$default,'default');
3839                                        $need_save = True;
3840                                }
3841                        }
3842                        if ($need_save)
3843                        {
3844                                $prefs = $GLOBALS['phpgw']->preferences->save_repository(False,'default');
3845                                $this->prefs['calendar'] = $prefs['calendar'];
3846                        }
3847                        if ($this->prefs['calendar']['send_updates'] && !isset($this->prefs['calendar']['receive_updates']))
3848                        {
3849                                $this->prefs['calendar']['receive_updates'] = $this->prefs['calendar']['send_updates'];
3850                                $GLOBALS['phpgw']->preferences->add('calendar','receive_updates',$this->prefs['calendar']['send_updates']);
3851                                $GLOBALS['phpgw']->preferences->delete('calendar','send_updates');
3852                                $prefs = $GLOBALS['phpgw']->preferences->save_repository();
3853                        }
3854                }
3855
3856                // return array with all infolog categories (for xmlrpc)
3857                function categories($complete = False)
3858                {
3859                        return $GLOBALS['server']->categories($complete);
3860                }
3861        }
3862?>
Note: See TracBrowser for help on using the repository browser.