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

Revision 3196, 121.1 KB checked in by wmerlotto, 14 years ago (diff)

Ticket #1179 - Compatibilização do agendamento para Outlook.

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