source: sandbox/2.3-MailArchiver/calendar/inc/class.bocalendar.inc.php @ 6779

Revision 6779, 141.1 KB checked in by rafaelraymundo, 12 years ago (diff)

Ticket #2946 - Liberado Expresso(branch 2.3) integrado ao MailArchiver?.

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