source: branches/2.2.0.1/calendar/inc/class.bocalendar.inc.php @ 4159

Revision 4159, 140.1 KB checked in by brunocosta, 13 years ago (diff)

Ticket #1799 - Em eventos com anexos a notificação é enviada para o criador.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2  /**************************************************************************\
3  * eGroupWare - Calendar                                                    *
4  * http://www.eGroupWare.org                                                *
5  * Maintained and further developed by RalfBecker@outdoor-training.de       *
6  * Based on Webcalendar by Craig Knudsen <cknudsen@radix.net>               *
7  *          http://www.radix.net/~cknudsen                                  *
8  * Originaly modified by Mark Peters <skeeter@phpgroupware.org>             *
9  * --------------------------------------------                             *
10  *  This program is free software; you can redistribute it and/or modify it *
11  *  under the terms of the GNU General Public License as published by the   *
12  *  Free Software Foundation; either version 2 of the License, or (at your  *
13  *  option) any later version.                                              *
14  \**************************************************************************/
15
16
17        class bocalendar
18        {
19                var $public_functions = Array(
20                        'read_entry'      => True,
21                        'delete_entry'    => True,
22                        'delete_calendar' => True,
23                        'change_owner'    => True,
24                        'update'          => True,
25                        'check_set_default_prefs' => True,
26                        'store_to_cache'  => True,
27                        'export_event'    => True,
28                        'send_alarm'      => True,
29                        'reinstate'       => True
30                );
31
32                var $soap_functions = Array(
33                        'read_entry' => Array(
34                                'in' => Array(
35                                        'int'
36                                ),
37                                'out' => Array(
38                                        'SOAPStruct'
39                                )
40                        ),
41                        'delete_entry' => Array(
42                                'in' => Array(
43                                        'int'
44                                ),
45                                'out' => Array(
46                                        'int'
47                                )
48                        ),
49                        'delete_calendar' => Array(
50                                'in' => Array(
51                                        'int'
52                                ),
53                                'out' => Array(
54                                        'int'
55                                )
56                        ),
57                        'change_owner' => Array(
58                                'in' => Array(
59                                        'array'
60                                ),
61                                'out' => Array(
62                                        'int'
63                                )
64                        ),
65                        'update' => Array(
66                                'in' => Array(
67                                        'array',
68                                        'array',
69                                        'array',
70                                        'array',
71                                        'array'
72                                ),
73                                'out' => Array(
74                                        'array'
75                                )
76                        ),
77                        'store_to_cache'        => Array(
78                                'in' => Array(
79                                        'struct'
80                                ),
81                                'out' => Array(
82                                        'SOAPStruct'
83                                )
84                        ),
85                        'store_to_cache'        => Array(
86                                'in' => Array(
87                                        'array'
88                                ),
89                                'out' => Array(
90                                        'string'
91                                )
92                        ),
93                        'categories' => array(
94                                'in'  => array('bool'),
95                                'out' => array('array')
96                        ),
97                );
98
99                var $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_attachment($l_cal['attachment']);
1192                                $this->so->set_ex_participants($l_cal['ex_participants']);
1193                                $this->so->set_start($l_start['year'],$l_start['month'],$l_start['mday'],$l_start['hour'],$l_start['min'],0);
1194                                $this->so->set_end($l_end['year'],$l_end['month'],$l_end['mday'],$l_end['hour'],$l_end['min'],0);
1195                                $this->so->set_class($is_public);
1196                                $this->so->add_attribute('reference',(@isset($l_cal['reference']) && $l_cal['reference']?$l_cal['reference']:0));
1197                                $this->so->add_attribute('location',(@isset($l_cal['location']) && $l_cal['location']?$l_cal['location']:''));
1198                                $this->so->add_attribute('repeat',(@isset($l_cal['recur_type']) && $l_cal['recur_type']?$l_cal['recur_type']:''));
1199                                $this->so->add_attribute('alarmd',(@isset($l_cal['alarmdays'])?$l_cal['alarmdays']:0));
1200                                $this->so->add_attribute('alarmh',(@isset($l_cal['alarmhours'])?$l_cal['alarmhours']:0));
1201                                $this->so->add_attribute('alarmm',(@isset($l_cal['alarmminutes'])?$l_cal['alarmminutes']:0));
1202                                if($l_cal['id'])
1203                                {
1204                                        $this->so->add_attribute('id',$l_cal['id']);
1205                                }
1206
1207                                if($l_cal['rpt_use_end'] != 'y')
1208                                {
1209                                        $l_recur_enddate['year'] = 0;
1210                                        $l_recur_enddate['month'] = 0;
1211                                        $l_recur_enddate['mday'] = 0;
1212                                }
1213                                elseif (isset($l_recur_enddate['str']))
1214                                {
1215                                        $l_recur_enddate = $this->jscal->input2date($l_recur_enddate['str'],False,'mday');
1216                                }
1217
1218                                switch((int)$l_cal['recur_type'])
1219                                {
1220                                        case MCAL_RECUR_NONE:
1221                                                $this->so->set_recur_none();
1222
1223                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1224                                                $this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
1225                                                $this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
1226
1227                                                break;
1228                                        case MCAL_RECUR_DAILY:
1229                                                $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']);
1230
1231                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1232                                                $this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
1233
1234                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
1235                                                $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;
1236
1237                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
1238                                                {
1239                                                        $this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
1240                                                       
1241                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
1242                                                        $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;
1243
1244                                                }else { // se nao existe data final da repeticao (agendamento infinito):
1245
1246                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1247                                                }
1248                                                break;
1249                                        case MCAL_RECUR_WEEKLY:
1250
1251                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1252                                                $this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
1253
1254                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
1255                                                $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;
1256
1257                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
1258                                                {
1259
1260                                                        $this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
1261                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
1262                                                        $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;
1263
1264                                                }else { // se nao existe data final da repeticao (agendamento infinito):
1265
1266                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1267                                                }
1268
1269                                                foreach(array('rpt_sun','rpt_mon','rpt_tue','rpt_wed','rpt_thu','rpt_fri','rpt_sat') as $rpt_day)
1270                                                {
1271                                                        $l_cal['recur_data'] += (int)$l_cal[$rpt_day];
1272                                                }
1273                                                if (is_array($l_cal['rpt_day']))
1274                                                {
1275                                                        foreach ($l_cal['rpt_day'] as $mask)
1276                                                        {
1277                                                                $l_cal['recur_data'] |= (int)$mask;
1278                                                                $rpt_wdays = $l_cal['recur_data']; // recebe os dias da semana (somatorio) para repetir o alarme;
1279                                                        }
1280                                                }
1281                                                $this->so->add_attribute('rpt_wdays',(@isset($rpt_wdays) && $rpt_wdays?$rpt_wdays:''));
1282                                                $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']);
1283                                                break;
1284                                        case MCAL_RECUR_MONTHLY_MDAY:
1285                                                $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']);
1286
1287                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1288                                                $this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
1289
1290                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
1291                                                $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;
1292
1293                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
1294                                                {
1295                                                        $this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
1296                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
1297                                                        $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;
1298
1299                                                }else { // se nao existe data final da repeticao (agendamento infinito):
1300
1301                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1302                                                }
1303                                                break;
1304                                        case MCAL_RECUR_MONTHLY_WDAY:
1305                                                $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']);
1306                                                break;
1307                                        case MCAL_RECUR_YEARLY:
1308                                                $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']);
1309
1310                                                $repetido = (int)$l_cal['recur_type']; // recebe o tipo de repeticao;
1311                                                $this->so->add_attribute('recur_type',(@isset($repetido) && $repetido?$repetido:0));
1312
1313                                                $tmp_init = explode("/",$_POST['start']['str']); // recebe a data inicial da repeticao;
1314                                                $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;
1315
1316                                                if($l_cal['rpt_use_end'] == 'y') // verifica se foi indicada data final da repeticao, se sim:
1317                                                {
1318                                                        $this->so->add_attribute('rpt_end_use',(@isset($l_cal['rpt_use_end']) && $l_cal['rpt_use_end']?$l_cal['rpt_use_end']:''));
1319                                                        $tmp_end = explode("/",$_POST['recur_enddate']['str']); // recebe data final da repeticao;
1320                                                        $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;
1321
1322                                                }else { // se nao existe data final da repeticao (agendamento infinito):
1323
1324                                                        $end_rept = 0; // variavel recebe zero e nao sera adicionado nenhum alarme para o agendamento;
1325                                                }
1326                                                break;
1327                                }
1328
1329                                if($l_participants)
1330                                {
1331                                        $parts = $l_participants;
1332                                        $minparts = min($l_participants);
1333                                        $part = Array();
1334                                        for($i=0;$i<count($parts);$i++)
1335                                        {
1336                                                if (($accept_type = substr($parts[$i],-1,1)) == '0' || (int)$accept_type > 0)
1337                                                {
1338                                                        $accept_type = 'U';
1339                                                }
1340                                                $acct_type = $GLOBALS['phpgw']->accounts->get_type((int)$parts[$i]);
1341                                                if($acct_type == 'u')
1342                                                {
1343                                                        $part[(int)$parts[$i]] = $accept_type;
1344                                                }
1345                                                elseif($acct_type == 'g')
1346                                                {
1347                                                        $part[(int)$parts[$i]] = $accept_type;
1348                                                        $groups[] = $parts[$i];
1349                                                        /* This pulls ALL users of a group and makes them as participants to the event */
1350                                                        /* I would like to turn this back into a group thing. */
1351                                                        $acct = CreateObject('phpgwapi.accounts',(int)$parts[$i]);
1352                                                        $members = $acct->member((int)$parts[$i]);
1353                                                        unset($acct);
1354                                                        if($members == False)
1355                                                        {
1356                                                                continue;
1357                                                        }
1358                                                        while($member = each($members))
1359                                                        {
1360                                                                $part[$member[1]['account_id']] = $accept_type;
1361                                                        }
1362                                                }
1363                                        }
1364                                }
1365                                else
1366                                {
1367                                        $part = False;
1368                                }
1369
1370                                if($part)
1371                                {
1372                                        @reset($part);
1373                                        while(list($key,$accept_type) = each($part))
1374                                        {
1375                                                $this->so->add_attribute('participants',$accept_type,(int)$key);
1376                                        }
1377                                }
1378
1379                                if($groups)
1380                                {
1381                                        @reset($groups);
1382                                        $this->so->add_attribute('groups',(int)$group_id);
1383                                }
1384
1385                                $event = $this->get_cached_event();
1386                                if(!is_int($minparts))
1387                                {
1388                                        $minparts = $this->owner;
1389                                }
1390                                if(!@isset($event['participants'][$l_cal['owner']]))
1391                                {
1392                                        $this->so->add_attribute('owner',$minparts);
1393                                }
1394                                else
1395                                {
1396                                        $this->so->add_attribute('owner',$l_cal['owner']);
1397                                }
1398                                $this->so->add_attribute('priority',$l_cal['priority']);
1399
1400                                foreach($l_cal as $name => $value)
1401                                {
1402                                        if ($name[0] == '#')    // Custom field
1403                                        {
1404                                                $this->so->add_attribute($name,stripslashes($value));
1405                                        }
1406                                }
1407                                if (isset($_POST['preserved']) && is_array($preserved = unserialize(stripslashes($_POST['preserved']))))
1408                                {
1409                                        foreach($preserved as $name => $value)
1410                                        {
1411                                                switch($name)
1412                                                {
1413                                                        case 'owner':
1414                                                                $this->so->add_attribute('participants',$value,$l_cal['owner']);
1415                                                                break;
1416                                                        default:
1417                                                                $this->so->add_attribute($name,str_replace(array('&amp;','&quot;','&lt;','&gt;'),array('&','"','<','>'),$value));
1418                                                }
1419                                        }
1420                                }
1421                                $event = $this->get_cached_event();
1422
1423                                if ($l_cal['alarmdays'] > 0 || $l_cal['alarmhours'] > 0 ||
1424                                                $l_cal['alarmminutes'] > 0)
1425                                {
1426                                        $offset = ($l_cal['alarmdays'] * 24 * 3600) +
1427                                                ($l_cal['alarmhours'] * 3600) + ($l_cal['alarmminutes'] * 60);
1428
1429                                        $time = $this->maketime($event['start']) - $offset;
1430
1431                                        $event['alarm'][] = Array(
1432                                                'time'    => $time,
1433                                                'offset'  => $offset,
1434                                                'owner'   => $this->owner,
1435                                                'enabled' => 1,
1436                                                'repeat'  => $repetido, // para repetir alarme;
1437                                                'init_rept' => $init_rept, // inicio repeticao;
1438                                                'end_rept' => $end_rept, // fim repeticao;
1439                                                'rpt_wdays' => $rpt_wdays // dias repeticao da semana;
1440                                        );
1441                                }
1442
1443                                $this->store_to_appsession($event);
1444                                $datetime_check = $this->validate_update($event);
1445                                print_debug('bo->validated_update() returnval',$datetime_check);
1446                                if($datetime_check)
1447                                {
1448                                        if (!$send_to_ui)
1449                                        {
1450                                                return array($datetime_check => 'invalid input data');
1451                                        }
1452                                        ExecMethod($ui_return,
1453                                                Array(
1454                                                        'cd'            => $datetime_check,
1455                                                        'readsess'      => 1
1456                                                )
1457                                        );
1458                                        if(!$params['from_mobile'])
1459                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
1460                                        else
1461                                                return;
1462                                }
1463
1464                                if($event['id'])
1465                                {
1466                                        $event_ids[] = $event['id'];
1467                                }
1468                                if($event['reference'])
1469                                {
1470                                        $event_ids[] = $event['reference'];
1471                                }
1472
1473                                if (isset($repetido) and $repetido > 0){
1474                                    $events = $this->expand_repetition($event);
1475                                    $overlapping_events = False;
1476                                    foreach($events as $evt){
1477                                        $overlap = $this->overlap(
1478                                            $evt['start'],
1479                                            $evt['end'],
1480                                            $evt['participants'],
1481                                            $evt['owner'],
1482                                            $event_ids);
1483                                        if ($overlap)
1484                                        {
1485                                            if (!$overlapping_events)
1486                                            {
1487                                                $overlapping_events = Array();
1488                                            }
1489                                            array_push($overlapping_events, $overlap);
1490                                        }
1491                                    }
1492                                }
1493                                else {
1494                                    $overlapping_events = $this->overlap(
1495                                        $this->maketime($event['start']),
1496                                        $this->maketime($event['end']),
1497                                        $event['participants'],
1498                                        $event['owner'],
1499                                        $event_ids
1500                                    );
1501                                }
1502                        }
1503                        if(!$this->ex_participants)
1504                                $this->ex_participants = $event['ex_participants'];                     
1505                        if($overlapping_events)
1506                        {
1507                                if($send_to_ui)
1508                                {
1509                                        $event['ex_participants'] = $this->ex_participants;
1510                                        unset($GLOBALS['phpgw_info']['flags']['noheader']);
1511                                        unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
1512                                        ExecMethod($ui_overlap,
1513                                                Array(
1514                                                        'o_events'      => $overlapping_events,
1515                                                        'this_event'    => $event
1516                                                )
1517                                        );
1518                                        if(!$params['from_mobile'])
1519                                                $GLOBALS['phpgw']->common->phpgw_exit(True);
1520                                        else
1521                                                return;
1522                                }
1523                                else
1524                                {
1525                                        return $overlapping_events;
1526                                }
1527                        }
1528                        else
1529                        {
1530                                if(!$event['id'])
1531                                {
1532                                        $this->so->add_entry($event);
1533                                        $this->send_update(MSG_ADDED,$event['participants'],'',$this->get_cached_event());
1534                                        print_debug('New Event ID',$event['id']);
1535                                }
1536                                else
1537                                {
1538                                        print_debug('Updating Event ID',$event['id']);
1539                                        $new_event = $event;
1540                                        $old_event = $this->read_entry($event['id']);
1541                                        // if old event has alarm and the start-time changed => update them
1542                                        //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";
1543                                        if ($old_event['alarm'] &&
1544                                                $this->maketime($old_event['start']) != $this->maketime($event['start']))
1545                                        {
1546                                                $this->so->delete_alarms($old_event['id']);
1547                                                foreach($old_event['alarm'] as $id => $alarm)
1548                                                {
1549                                                        $alarm['time'] = $this->maketime($event['start']) - $alarm['offset'];
1550                                                        $event['alarm'][] = $alarm;
1551                                                }
1552                                                //echo "updated alarms<pre>".print_r($event['alarm'],True)."</pre>\n";
1553                                        }
1554                                        $this->so->cal->event = $event;
1555                                        $this->so->add_entry($event);
1556                                        $this->prepare_recipients($new_event,$old_event);
1557                                }
1558
1559                                $date = sprintf("%04d%02d%02d",$event['start']['year'],$event['start']['month'],$event['start']['mday']);
1560                                if($send_to_ui)
1561                                {
1562                                        $this->read_sessiondata();
1563                                        if ($this->return_to)
1564                                        {
1565                                                $GLOBALS['phpgw']->redirect_link('/index.php','menuaction='.$this->return_to);
1566                                                $GLOBALS['phpgw']->common->phpgw_exit();
1567                                        }
1568                                        Execmethod($ui_index);
1569                                }
1570                                else
1571                                {
1572                                        return (int)$event['id'];
1573                                }
1574                        }
1575                        return True;
1576                }
1577
1578                /* Private functions */
1579                function read_holidays($year=0)
1580                {
1581                        if(!$year)
1582                        {
1583                                $year = $this->year;
1584                        }
1585                        $holiday = CreateObject('calendar.boholiday');
1586                        $holiday->prepare_read_holidays($year,$this->owner);
1587                        $this->cached_holidays = $holiday->read_holiday();
1588                        unset($holiday);
1589                }
1590
1591                function user_is_a_member($event,$user)
1592                {
1593                        @reset($event['participants']);
1594                        $uim = False;
1595                        $security_equals = $GLOBALS['phpgw']->accounts->membership($user);
1596                        while(!$uim && $event['participants'] && $security_equals && list($participant,$status) = each($event['participants']))
1597                        {
1598                                if($GLOBALS['phpgw']->accounts->get_type($participant) == 'g')
1599                                {
1600                                        @reset($security_equals);
1601                                        while(list($key,$group_info) = each($security_equals))
1602                                        {
1603                                                if($group_info['account_id'] == $participant)
1604                                                {
1605                                                        return True;
1606                                                        $uim = True;
1607                                                }
1608                                        }
1609                                }
1610                        }
1611                        return $uim;
1612                }
1613
1614                function maketime($time)
1615                {
1616                        return mktime(intval($time['hour']),intval($time['min']),intval($time['sec']),intval($time['month']),intval($time['mday']),intval($time['year']));
1617                }
1618
1619                /*!
1620                @function time2array
1621                @abstract returns a date-array suitable for the start- or endtime of an event from a timestamp
1622                @syntax time2array($time,$alarm=0)
1623                @param $time the timestamp for the values of the array
1624                @param $alarm (optional) alarm field of the array, defaults to 0
1625                @author ralfbecker
1626                */
1627                function time2array($time,$alarm = 0)
1628                {
1629                        return array(
1630                                'year'  => (int)(date('Y',$time)),
1631                                'month' => (int)(date('m',$time)),
1632                                'mday'  => (int)(date('d',$time)),
1633                                'hour'  => (int)(date('H',$time)),
1634                                'min'   => (int)(date('i',$time)),
1635                                'sec'   => (int)(date('s',$time)),
1636                                'alarm' => (int)($alarm)
1637                        );
1638                }
1639
1640                /*!
1641                @function set_recur_date
1642                @abstract set the start- and enddates of a recuring event for a recur-date
1643                @syntax set_recur_date(&$event,$date)
1644                @param $event the event which fields to set (has to be the original event for start-/end-times)
1645                @param $date  the recuring date in form 'Ymd', eg. 20030226
1646                @author ralfbecker
1647                */
1648                function set_recur_date(&$event,$date)
1649                {
1650                        $org_start = $this->maketime($event['start']);
1651                        $org_end   = $this->maketime($event['end']);
1652                        $start = mktime($event['start']['hour'],$event['start']['min'],0,substr($date,4,2),substr($date,6,2),substr($date,0,4));
1653                        $end   = $org_end + $start - $org_start;
1654                        $event['start'] = $this->time2array($start);
1655                        $event['end']   = $this->time2array($end);
1656                }
1657
1658                function fix_update_time(&$time_param)
1659                {
1660                        if (isset($time_param['str']))
1661                        {
1662                                if (!is_object($this->jscal))
1663                                {
1664                                        $this->jscal = CreateObject('phpgwapi.jscalendar');
1665                                }
1666                                $time_param += $this->jscal->input2date($time_param['str'],False,'mday');
1667                                unset($time_param['str']);
1668                        }
1669                        if ($this->prefs['common']['timeformat'] == '12')
1670                        {
1671                                if ($time_param['ampm'] == 'pm')
1672                                {
1673                                        if ($time_param['hour'] <> 12)
1674                                        {
1675                                                $time_param['hour'] += 12;
1676                                        }
1677                                }
1678                                elseif ($time_param['ampm'] == 'am')
1679                                {
1680                                        if ($time_param['hour'] == 12)
1681                                        {
1682                                                $time_param['hour'] -= 12;
1683                                        }
1684                                }
1685
1686                                if($time_param['hour'] > 24)
1687                                {
1688                                        $time_param['hour'] -= 12;
1689                                }
1690                        }
1691                }
1692
1693                function validate_update($event)
1694                {
1695                        $error = 0;
1696                        // do a little form verifying
1697                        if (!count($event['participants']))
1698                        {
1699                                $error = 43;
1700                        }
1701                        elseif ($event['title'] == '')
1702                        {
1703                                $error = 40;
1704                        }
1705                        elseif ($event['repeat'] != 0)
1706                        {
1707                                if( $event['rpt_end_use'] != 'y')
1708                                {
1709                                        $error = 46;
1710                                }
1711                        //}
1712                          if ($event['repeat'] == 2)
1713                          {
1714                                if($event['rpt_wdays'] == '') {
1715                                        $error = 44;
1716                                }
1717                                if( $event['rpt_end_use'] != 'y')
1718                                {
1719                                        $error = 46;
1720                                }
1721
1722                                if (  ( isset($event['alarmd'])  && ($event['alarmd'] != 0) ) || ( isset($event['alarmh'])  && ($event['alarmh'] != 0) ) || ( isset($event['alarmm'])  && ($event['alarmm'] != 0) ) )
1723                                {
1724                                        if( isset($event['recur_type']) && ($event['recur_type'] != 0) )
1725                                        {
1726                                                if( $event['rpt_end_use'] != 'y')
1727                                                {
1728                                                        $error = 45;
1729                                                }
1730                                        }
1731                                }
1732                           }
1733
1734                        //}
1735                  if (  ( isset($event['alarmd'])  && ($event['alarmd'] != 0) ) || ( isset($event['alarmh'])  && ($event['alarmh'] != 0) ) || ( isset($event['alarmm'])  && ($event['alarmm'] != 0) ) )
1736                  {
1737                        if( isset($event['recur_type']) && ($event['recur_type'] != 0) )
1738                        {
1739                                if( $event['rpt_end_use'] != 'y')
1740                                {
1741                                        $error = 45;
1742                                }
1743                        }
1744                  }
1745                }
1746                        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))
1747                        {
1748                                $error = 41;
1749                        }
1750                        elseif (($GLOBALS['phpgw']->datetime->date_valid($event['start']['year'],$event['start']['month'],$event['start']['mday']) == False) || ($GLOBALS['phpgw']->datetime->date_valid($event['end']['year'],$event['end']['month'],$event['end']['mday']) == False) || ($GLOBALS['phpgw']->datetime->date_compare($event['start']['year'],$event['start']['month'],$event['start']['mday'],$event['end']['year'],$event['end']['month'],$event['end']['mday']) == 1))
1751                        {
1752                                $error = 42;
1753                        }
1754                        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)
1755                        {
1756                                if ($GLOBALS['phpgw']->datetime->time_compare($event['start']['hour'],$event['start']['min'],0,$event['end']['hour'],$event['end']['min'],0) == 1)
1757                                {
1758                                        $error = 47;
1759                                }
1760                        }
1761                        if($event['attachment'] == 'ERROR')
1762                            $error = 99;
1763                       
1764                        return $error;
1765                }
1766
1767                /*!
1768                @function participants_not_rejected($participants,$event)
1769                @abstract checks if any of the $particpants participates in $event and has not rejected it
1770                */
1771                function participants_not_rejected($participants,$event)
1772                {
1773                        //echo "participants_not_rejected()<br>participants =<pre>"; print_r($participants); echo "</pre><br>event[participants]=<pre>"; print_r($event['participants']); echo "</pre>\n";
1774                        foreach($participants as $uid => $status)
1775                        {
1776                                //echo "testing event[participants][uid=$uid] = '".$event['participants'][$uid]."'<br>\n";
1777                                if (isset($event['participants'][$uid]) && $event['participants'][$uid] != 'R' &&
1778                                        $status != 'R')
1779                                {
1780                                        return True;    // found not rejected participant in event
1781                                }
1782                        }
1783                        return False;
1784                }
1785               
1786                function participants_unanswered($participants,$event)
1787                {
1788                        foreach($participants as $uid => $status)
1789                        {                               
1790                                if (isset($event['participants'][$uid]) && $event['participants'][$uid] == 'U' && $status == 'U')
1791                                {
1792                                        return False;
1793                                }
1794                        }
1795                        return True;
1796                }
1797
1798                function overlap($starttime,$endtime,$participants,$owner=0,$id=0,$restore_cache=False)
1799                {
1800//                      $retval = Array();
1801//                      $ok = False;
1802
1803/* This needs some attention.. by commenting this chunk of code it will fix bug #444265 */
1804
1805                        if($restore_cache)
1806                        {
1807                                $temp_cache_events = $this->cached_events;
1808                        }
1809
1810//                      $temp_start = (int)$GLOBALS['phpgw']->common->show_date($starttime,'Ymd');
1811//                      $temp_start_time = (int)($GLOBALS['phpgw']->common->show_date($starttime,'Hi');
1812//                      $temp_end = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Ymd');
1813//                      $temp_end_time = (int)$GLOBALS['phpgw']->common->show_date($endtime,'Hi');
1814                        $temp_start = (int)(date('Ymd',$starttime));
1815                        $temp_start_time = (int)(date('Hi',$starttime));
1816                        $temp_end = (int)(date('Ymd',$endtime));
1817                        $temp_end_time = (int)(date('Hi',$endtime));
1818                        if($this->debug)
1819                        {
1820                                echo '<!-- Temp_Start: '.$temp_start.' -->'."\n";
1821                                echo '<!-- Temp_End: '.$temp_end.' -->'."\n";
1822                        }
1823
1824                        $users = Array();
1825                        if(count($participants))
1826                        {
1827                                while(list($user,$status) = each($participants))
1828                                {
1829                                        $users[] = $user;
1830                                }
1831                        }
1832                        else
1833                        {
1834                                $users[] = $this->owner;
1835                        }
1836
1837                        $possible_conflicts = $this->store_to_cache(
1838                                Array(
1839                                        'smonth'        => substr(strval($temp_start),4,2),
1840                                        'sday'  => substr(strval($temp_start),6,2),
1841                                        'syear' => substr(strval($temp_start),0,4),
1842                                        'emonth'        => substr(strval($temp_end),4,2),
1843                                        'eday'  => substr(strval($temp_end),6,2),
1844                                        'eyear' => substr(strval($temp_end),0,4),
1845                                        'owner' => $users
1846                                )
1847                        );
1848
1849                        if($this->debug)
1850                        {
1851                                echo '<!-- Possible Conflicts ('.($temp_start - 1).'): '.count($possible_conflicts[$temp_start - 1]).' -->'."\n";
1852                                echo '<!-- Possible Conflicts ('.$temp_start.'): '.count($possible_conflicts[$temp_start]).' '.count($id).' -->'."\n";
1853                        }
1854
1855                        if($possible_conflicts[$temp_start] || $possible_conflicts[$temp_end])
1856                        {
1857                                if($temp_start == $temp_end)
1858                                {
1859                                        if($this->debug)
1860                                        {
1861                                                echo '<!-- Temp_Start == Temp_End -->'."\n";
1862                                        }
1863                                        @reset($possible_conflicts[$temp_start]);
1864                                        while(list($key,$event) = each($possible_conflicts[$temp_start]))
1865                                        {
1866                                                $found = False;
1867                                                if($id)
1868                                                {
1869                                                        @reset($id);
1870                                                        while(list($key,$event_id) = each($id))
1871                                                        {
1872                                                                if($this->debug)
1873                                                                {
1874                                                                        echo '<!-- $id['.$key.'] = '.$id[$key].' = '.$event_id.' -->'."\n";
1875                                                                        echo '<!-- '.$event['id'].' == '.$event_id.' -->'."\n";
1876                                                                }
1877                                                                if($event['id'] == $event_id)
1878                                                                {
1879                                                                        $found = True;
1880                                                                }
1881                                                        }
1882                                                }
1883                                                if($this->debug)
1884                                                {
1885                                                        echo '<!-- Item found: '.$found.' -->'."<br>\n";
1886                                                }
1887                                                if(!$found)
1888                                                {
1889                                                        if($this->debug)
1890                                                        {
1891                                                                echo '<!-- Checking event id #'.$event['id'];
1892                                                        }
1893                                                        $temp_event_start = sprintf("%d%02d",$event['start']['hour'],$event['start']['min']);
1894                                                        $temp_event_end = sprintf("%d%02d",$event['end']['hour'],$event['end']['min']);
1895//                                                      if((($temp_start_time <= $temp_event_start) && ($temp_end_time >= $temp_event_start) && ($temp_end_time <= $temp_event_end)) ||
1896                                                        if(($temp_start_time <= $temp_event_start &&
1897                                                                $temp_end_time > $temp_event_start &&
1898                                                                $temp_end_time <= $temp_event_end ||
1899                                                                $temp_start_time >= $temp_event_start &&
1900                                                                $temp_start_time < $temp_event_end &&
1901                                                                $temp_end_time >= $temp_event_end ||
1902                                                                $temp_start_time <= $temp_event_start &&
1903                                                                $temp_end_time >= $temp_event_end ||
1904                                                                $temp_start_time >= $temp_event_start &&
1905                                                                $temp_end_time <= $temp_event_end) &&
1906                                                                $this->participants_not_rejected($participants,$event) && $this->participants_unanswered($participants,$event))
1907                                                        {
1908                                                                if($this->debug)
1909                                                                {
1910                                                                        echo ' Conflicts';
1911                                                                }
1912                                                                $retval[] = $event['id'];
1913                                                        }
1914                                                        if($this->debug)
1915                                                        {
1916                                                                echo ' -->'."\n";
1917                                                        }
1918                                                }
1919                                        }
1920                                }
1921                        }
1922                        else
1923                        {
1924                                $retval = False;
1925                        }
1926
1927                        if($restore_cache)
1928                        {
1929                                $this->cached_events = $temp_cache_events;
1930                        }
1931
1932                        return $retval;
1933                }
1934
1935                /*!
1936                @function check_perms( )
1937                @syntax check_perms($needed,$event=0,$other=0)
1938                @abstract Checks if the current user has the necessary ACL rights
1939                @author ralfbecker
1940                @discussion The check is performed on an event or general on the cal of an other user
1941                @param $needed necessary ACL right: PHPGW_ACL_{READ|EDIT|DELETE}
1942                @param $event event as array or the event-id or 0 for general check
1943                @param $other uid to check (if event==0) or 0 to check against $this->owner
1944                @note Participating in an event is considered as haveing read-access on that event, \
1945                        even if you have no general read-grant from that user.
1946                */
1947                function check_perms($needed,$event=0,$other=0)
1948                {
1949                        $event_in = $event;
1950                       
1951                        if (is_int($event) && $event == 0)
1952                        {
1953                                $owner = $other > 0 ? $other : $this->owner;
1954                        }
1955                        else
1956                        {
1957                                if (!is_array($event))
1958                                {
1959                                        $event = $this->so->read_entry((int) $event);
1960                                }
1961                                if (!is_array($event))
1962                                {
1963                                        if ($this->xmlrpc)
1964                                        {
1965                                                $GLOBALS['server']->xmlrpc_error($GLOBALS['xmlrpcerr']['not_exist'],$GLOBALS['xmlrpcstr']['not_exist']);
1966                                        }
1967                                        return False;
1968                                }
1969                                $owner = $event['owner'];
1970                                $private = $event['public'] == False || $event['public'] == 0;
1971                        }
1972                        $user = $GLOBALS['phpgw_info']['user']['account_id'];
1973                        $grants = $this->grants[$owner];
1974
1975                        if (is_array($event) && $needed == PHPGW_ACL_READ)
1976                        {
1977                                // Check if the $user is one of the participants or has a read-grant from one of them
1978                                //
1979                                foreach($event['participants'] as $uid => $accept)
1980                                {
1981                                        if ($this->grants[$uid] & PHPGW_ACL_READ || $uid == $user)
1982                                        {
1983                                                $grants |= PHPGW_ACL_READ;
1984                                                // if the $user is one of the participants read-grant private (restricted) too.
1985                                                if($uid == $user || ($this->grants[$uid] & PHPGW_ACL_PRIVATE)) {
1986                                                        $grants |= PHPGW_ACL_PRIVATE;
1987                                                }
1988                                                //break;
1989                                        }
1990                                }
1991                        }
1992
1993                        if ($GLOBALS['phpgw']->accounts->get_type($owner) == 'g' && $needed == PHPGW_ACL_ADD)
1994                        {
1995                                $access = False;        // a group can't be the owner of an event
1996                        }
1997                        else
1998                        {
1999                                $access = $user == $owner || $grants & $needed && (!$private || $grants & PHPGW_ACL_PRIVATE);
2000                        }
2001                        //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";
2002
2003                        return $access;
2004                }
2005
2006
2007                function display_status($user_status)
2008                {
2009                        if(@$this->prefs['calendar']['display_status'] && $user_status)
2010                        {
2011                                $user_status = substr($this->get_long_status($user_status),0,1);
2012
2013                                return ' ('.$user_status.')';
2014                        }
2015                        else
2016                        {
2017                                return '';
2018                        }
2019                }
2020
2021                function get_long_status($status_short)
2022                {
2023                        switch ($status_short)
2024                        {
2025                                case 'A':
2026                                        $status = lang('Accepted');
2027                                        break;
2028                                case 'R':
2029                                        $status = lang('Rejected');
2030                                        break;
2031                                case 'T':
2032                                        $status = lang('Tentative');
2033                                        break;
2034                                case 'U':
2035                                        $status = lang('No Response');
2036                                        break;
2037                        }
2038                        return $status;
2039                }
2040
2041                function is_private($event,$owner)
2042                {
2043                        if($owner == 0)
2044                        {
2045                                $owner = $this->owner;
2046                        }
2047                        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'])
2048                        {
2049                                return False;
2050                        }
2051                        elseif($event['public'] == 0)
2052                        {
2053                                return True;
2054                        }
2055                        elseif($event['public'] == 2)
2056                        {
2057                                $is_private = True;
2058                                $groups = $GLOBALS['phpgw']->accounts->membership($owner);
2059                                while (list($key,$group) = each($groups))
2060                                {
2061                                        if (strpos(' '.implode(',',$event['groups']).' ',$group['account_id']))
2062                                        {
2063                                                return False;
2064                                        }
2065                                }
2066                        }
2067                        else
2068                        {
2069                                return False;
2070                        }
2071
2072                        return $is_private;
2073                }
2074
2075                function get_short_field($event,$is_private=True,$field='')
2076                {
2077                        if($is_private)
2078                        {
2079                                return lang('private');
2080                        }
2081
2082// cut off too long titles
2083                        elseif(strlen($event[$field]) > 19 && !$this->printer_friendly && $field=="title")
2084//                      elseif(strlen($event[$field]) > 19 && $this->printer_friendly)
2085                        {
2086// we dont use currently 160304
2087//                              return substr($event[$field], 0 , 19) . '&nbsp;...';
2088                                return $event[$field];
2089                        }
2090                        else
2091                        {
2092                                return $event[$field];
2093                        }
2094                }
2095
2096                function long_date($first,$last=0)
2097                {
2098                        if (!is_array($first))
2099                        {
2100                                $first = $this->time2array($raw = $first);
2101                                $first['raw'] = $raw;
2102                                $first['day'] = $first['mday'];
2103                        }
2104                        if ($last && !is_array($last))
2105                        {
2106                                $last = $this->time2array($raw = $last);
2107                                $last['raw'] = $raw;
2108                                $last['day'] = $last['mday'];
2109                        }
2110                        $datefmt = $this->prefs['common']['dateformat'];
2111
2112                        $month_before_day = strtolower($datefmt[0]) == 'm' ||
2113                                strtolower($datefmt[2]) == 'm' && $datefmt[4] == 'd';
2114
2115                        for ($i = 0; $i < 5; $i += 2)
2116                        {
2117                                switch($datefmt[$i])
2118                                {
2119                                        case 'd':
2120                                                $range .= $first['day'] . ($datefmt[1] == '.' ? '.' : '');
2121                                                if ($first['month'] != $last['month'] || $first['year'] != $last['year'])
2122                                                {
2123                                                        if (!$month_before_day)
2124                                                        {
2125                                                                $range .= ' '.lang(strftime('%B',$first['raw']));
2126                                                        }
2127                                                        if ($first['year'] != $last['year'] && $datefmt[0] != 'Y')
2128                                                        {
2129                                                                $range .= ($datefmt[0] != 'd' ? ', ' : ' ') . $first['year'];
2130                                                        }
2131                                                        if (!$last)
2132                                                        {
2133                                                                return $range;
2134                                                        }
2135                                                        $range .= ' - ';
2136
2137                                                        if ($first['year'] != $last['year'] && $datefmt[0] == 'Y')
2138                                                        {
2139                                                                $range .= $last['year'] . ', ';
2140                                                        }
2141
2142                                                        if ($month_before_day)
2143                                                        {
2144                                                                $range .= lang(strftime('%B',$last['raw']));
2145                                                        }
2146                                                }
2147                                                else
2148                                                {
2149                                                        $range .= ' - ';
2150                                                }
2151                                                $range .= ' ' . $last['day'] . ($datefmt[1] == '.' ? '.' : '');
2152                                                break;
2153                                        case 'm':
2154                                        case 'M':
2155                                                $range .= ' '.lang(strftime('%B',$month_before_day ? $first['raw'] : $last['raw'])) . ' ';
2156                                                break;
2157                                        case 'Y':
2158                                                $range .= ($datefmt[0] == 'm' ? ', ' : ' ') . ($datefmt[0] == 'Y' ? $first['year'].($datefmt[2] == 'd' ? ', ' : ' ') : $last['year'].' ');
2159                                                break;
2160                                }
2161                        }
2162                        return $range;
2163                }
2164
2165                function get_week_label()
2166                {
2167                        $first = $GLOBALS['phpgw']->datetime->gmtdate($GLOBALS['phpgw']->datetime->get_weekday_start($this->year, $this->month, $this->day));
2168                        $last = $GLOBALS['phpgw']->datetime->gmtdate($first['raw'] + 518400);
2169
2170                        return ($this->long_date($first,$last));
2171                }
2172
2173                function normalizeminutes(&$minutes)
2174                {
2175                        $hour = 0;
2176                        $min = (int)$minutes;
2177                        if($min >= 60)
2178                        {
2179                                $hour += $min / 60;
2180                                $min %= 60;
2181                        }
2182                        settype($minutes,'integer');
2183                        $minutes = $min;
2184                        return $hour;
2185                }
2186
2187                function splittime($time,$follow_24_rule=True)
2188                {
2189                        $temp = array('hour','minute','second','ampm');
2190                        $time = strrev($time);
2191                        $second = (int)(strrev(substr($time,0,2)));
2192                        $minute = (int)(strrev(substr($time,2,2)));
2193                        $hour   = (int)(strrev(substr($time,4)));
2194                        $hour += $this->normalizeminutes($minute);
2195                        $temp['second'] = $second;
2196                        $temp['minute'] = $minute;
2197                        $temp['hour']   = $hour;
2198                        $temp['ampm']   = '  ';
2199                        if($follow_24_rule == True)
2200                        {
2201                                if ($this->prefs['common']['timeformat'] == '24')
2202                                {
2203                                        return $temp;
2204                                }
2205
2206                                $temp['ampm'] = 'am';
2207
2208                                if ((int)$temp['hour'] > 12)
2209                                {
2210                                        $temp['hour'] = (int)((int)$temp['hour'] - 12);
2211                                        $temp['ampm'] = 'pm';
2212                                }
2213                                elseif ((int)$temp['hour'] == 12)
2214                                {
2215                                        $temp['ampm'] = 'pm';
2216                                }
2217                        }
2218                        return $temp;
2219                }
2220
2221                function get_exception_array($exception_str='')
2222                {
2223                        $exception = Array();
2224                        if(strpos(' '.$exception_str,','))
2225                        {
2226                                $exceptions = explode(',',$exception_str);
2227                                for($exception_count=0;$exception_count<count($exceptions);$exception_count++)
2228                                {
2229                                        $exception[] = (int)$exceptions[$exception_count];
2230                                }
2231                        }
2232                        elseif($exception_str != '')
2233                        {
2234                                $exception[] = (int)$exception_str;
2235                        }
2236                        return $exception;
2237                }
2238
2239                function build_time_for_display($fixed_time)
2240                {
2241                        $time = $this->splittime($fixed_time);
2242                        $str = $time['hour'].':'.((int)$time['minute']<=9?'0':'').$time['minute'];
2243
2244                        if ($this->prefs['common']['timeformat'] == '12')
2245                        {
2246                                $str .= ' ' . $time['ampm'];
2247                        }
2248
2249                        return $str;
2250                }
2251
2252                function sort_event($event,$date)
2253                {
2254                        $inserted = False;
2255                        if(isset($event['recur_exception']))
2256                        {
2257                                $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;
2258                                while($inserted == False && list($key,$exception_time) = each($event['recur_exception']))
2259                                {
2260                                        if($this->debug)
2261                                        {
2262                                                echo '<!-- checking exception datetime '.$exception_time.' to event datetime '.$event_time.' -->'."\n";
2263                                        }
2264                                        if($exception_time == $event_time)
2265                                        {
2266                                                $inserted = True;
2267                                        }
2268                                }
2269                        }
2270                        if($this->cached_events[$date] && $inserted == False)
2271                        {
2272
2273                                if($this->debug)
2274                                {
2275                                        echo '<!-- Cached Events found for '.$date.' -->'."\n";
2276                                }
2277                                $year = substr($date,0,4);
2278                                $month = substr($date,4,2);
2279                                $day = substr($date,6,2);
2280
2281                                if($this->debug)
2282                                {
2283                                        echo '<!-- Date : '.$date.' Count : '.count($this->cached_events[$date]).' -->'."\n";
2284                                }
2285
2286                                for($i=0;$i<count($this->cached_events[$date]);$i++)
2287                                {
2288                                        if($this->cached_events[$date][$i]['id'] == $event['id'] || $this->cached_events[$date][$i]['reference'] == $event['id'])
2289                                        {
2290                                                if($this->debug)
2291                                                {
2292                                                        echo '<!-- Item already inserted! -->'."\n";
2293                                                }
2294                                                $inserted = True;
2295                                                break;
2296                                        }
2297                                        /* This puts all spanning events across multiple days up at the top. */
2298                                        if($this->cached_events[$date][$i]['recur_type'] == MCAL_RECUR_NONE)
2299                                        {
2300                                                if($this->cached_events[$date][$i]['start']['mday'] != $day && $this->cached_events[$date][$i]['end']['mday'] >= $day)
2301                                                {
2302                                                        continue;
2303                                                }
2304                                        }
2305                                        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)))
2306                                        {
2307                                                for($j=count($this->cached_events[$date]);$j>=$i;$j--)
2308                                                {
2309                                                        $this->cached_events[$date][$j] = $this->cached_events[$date][$j-1];
2310                                                }
2311                                                if($this->debug)
2312                                                {
2313                                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
2314                                                }
2315                                                $inserted = True;
2316                                                $this->cached_events[$date][$i] = $event;
2317                                                break;
2318                                        }
2319                                }
2320                        }
2321                        if(!$inserted)
2322                        {
2323                                if($this->debug)
2324                                {
2325                                        echo '<!-- Adding event ID: '.$event['id'].' to cached_events -->'."\n";
2326                                }
2327                                $this->cached_events[$date][] = $event;
2328                        }
2329                }
2330
2331                function check_repeating_events($datetime)
2332                {
2333                        @reset($this->repeating_events);
2334                        $search_date_full = date('Ymd',$datetime);
2335                        $search_date_year = date('Y',$datetime);
2336                        $search_date_month = date('m',$datetime);
2337                        $search_date_day = date('d',$datetime);
2338                        $search_date_dow = date('w',$datetime);
2339                        $search_beg_day = mktime(12,0,0,$search_date_month,$search_date_day,$search_date_year);
2340                        if($this->debug)
2341                        {
2342                                echo '<!-- Search Date Full = '.$search_date_full.' -->'."\n";
2343                        }
2344                        $repeated = $this->repeating_events;
2345                        $r_events = count($repeated);
2346                        for ($i=0;$i<$r_events;$i++)
2347                        {
2348                                $rep_events = $this->repeating_events[$i];
2349                                $id = $rep_events['id'];
2350                                $event_beg_day = mktime(0,0,0,$rep_events['start']['month'],$rep_events['start']['mday'],$rep_events['start']['year']);
2351                                if($rep_events['recur_enddate']['month'] != 0 && $rep_events['recur_enddate']['mday'] != 0 && $rep_events['recur_enddate']['year'] != 0)
2352                                {
2353                                        $event_recur_time = $this->maketime($rep_events['recur_enddate']);
2354                                }
2355                                else
2356                                {
2357                                        $event_recur_time = mktime(0,0,0,1,1,2030);
2358                                }
2359                                $end_recur_date = date('Ymd',$event_recur_time);
2360                                $full_event_date = date('Ymd',$event_beg_day);
2361
2362                                if($this->debug)
2363                                {
2364                                        echo '<!-- check_repeating_events - Processing ID - '.$id.' -->'."\n";
2365                                        echo '<!-- check_repeating_events - Recurring End Date - '.$end_recur_date.' -->'."\n";
2366                                }
2367
2368                                // only repeat after the beginning, and if there is an rpt_end before the end date
2369                                if (($search_date_full > $end_recur_date) || ($search_date_full < $full_event_date))
2370                                {
2371                                        continue;
2372                                }
2373
2374                                if ($search_date_full == $full_event_date)
2375                                {
2376                                        $this->sort_event($rep_events,$search_date_full);
2377                                        continue;
2378                                }
2379                                else
2380                                {
2381                                        $freq = $rep_events['recur_interval'];
2382                                        $freq = $freq ? $freq : 1;
2383                                        $type = $rep_events['recur_type'];
2384                                        switch($type)
2385                                        {
2386                                                case MCAL_RECUR_DAILY:
2387                                                        if($this->debug)
2388                                                        {
2389                                                                echo '<!-- check_repeating_events - MCAL_RECUR_DAILY - '.$id.' -->'."\n";
2390                                                        }
2391                                                       
2392                                                        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)
2393                                                        {
2394                                                                $this->sort_event($rep_events,$search_date_full);
2395                                                        }
2396                                                        elseif (floor(($search_beg_day - $event_beg_day)/86400) % ($freq ? $freq : 1))
2397                                                        {
2398                                                                continue;
2399                                                        }
2400                                                        else
2401                                                        {
2402                                                                $this->sort_event($rep_events,$search_date_full);
2403                                                        }
2404                                                        break;
2405                                                case MCAL_RECUR_WEEKLY:
2406                                                        if (floor(($search_beg_day - $event_beg_day)/604800)  % ($freq ? $freq : 1))
2407                                                        {
2408                                                                continue;
2409                                                        }
2410                                                        $check = 0;
2411                                                        switch($search_date_dow)
2412                                                        {
2413                                                                case 0:
2414                                                                        $check = MCAL_M_SUNDAY;
2415                                                                        break;
2416                                                                case 1:
2417                                                                        $check = MCAL_M_MONDAY;
2418                                                                        break;
2419                                                                case 2:
2420                                                                        $check = MCAL_M_TUESDAY;
2421                                                                        break;
2422                                                                case 3:
2423                                                                        $check = MCAL_M_WEDNESDAY;
2424                                                                        break;
2425                                                                case 4:
2426                                                                        $check = MCAL_M_THURSDAY;
2427                                                                        break;
2428                                                                case 5:
2429                                                                        $check = MCAL_M_FRIDAY;
2430                                                                        break;
2431                                                                case 6:
2432                                                                        $check = MCAL_M_SATURDAY;
2433                                                                        break;
2434                                                        }
2435                                                        if ($rep_events['recur_data'] & $check)
2436                                                        {
2437                                                                $this->sort_event($rep_events,$search_date_full);
2438                                                        }
2439                                                        break;
2440                                                case MCAL_RECUR_MONTHLY_WDAY:
2441                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month']) % $freq)
2442                                                        {
2443                                                                continue;
2444                                                        }
2445
2446                                                        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)) &&
2447                                                                (ceil($rep_events['start']['mday']/7) == ceil($search_date_day/7)))
2448                                                        {
2449                                                                $this->sort_event($rep_events,$search_date_full);
2450                                                        }
2451                                                        break;
2452                                                case MCAL_RECUR_MONTHLY_MDAY:
2453                                                        if ((($search_date_year - $rep_events['start']['year']) * 12 + $search_date_month - $rep_events['start']['month'])  % ($freq ? $freq : 1))
2454                                                        {
2455                                                                continue;
2456                                                        }
2457                                                        if ($search_date_day == $rep_events['start']['mday'])
2458                                                        {
2459                                                                $this->sort_event($rep_events,$search_date_full);
2460                                                        }
2461                                                        break;
2462                                                case MCAL_RECUR_YEARLY:
2463                                                        if (($search_date_year - $rep_events['start']['year']) % ($freq ? $freq : 1))
2464                                                        {
2465                                                                continue;
2466                                                        }
2467                                                        if (date('dm',$datetime) == date('dm',$event_beg_day))
2468                                                        {
2469                                                                $this->sort_event($rep_events,$search_date_full);
2470                                                        }
2471                                                        break;
2472                                        }
2473                                }
2474                        }       // end for loop
2475                }       // end function
2476
2477                function store_to_cache($params)
2478                {
2479                        if(!is_array($params))
2480                        {
2481                                return False;
2482                        }
2483                        if (isset($params['start']) && ($datearr = $GLOBALS['server']->iso86012date($params['start'])))
2484                        {
2485                                $syear = $datearr['year'];
2486                                $smonth = $datearr['month'];
2487                                $sday = $datearr['mday'];
2488                                $this->xmlrpc = True;
2489                        }
2490                        else
2491                        {
2492                                $syear = $params['syear'];
2493                                $smonth = $params['smonth'];
2494                                $sday = $params['sday'];
2495                        }
2496                        if (isset($params['end']) && ($datearr = $GLOBALS['server']->iso86012date($params['end'])))
2497                        {
2498                                $eyear = $datearr['year'];
2499                                $emonth = $datearr['month'];
2500                                $eday = $datearr['mday'];
2501                                $this->xmlrpc = True;
2502                        }
2503                        else
2504                        {
2505                                $eyear = (isset($params['eyear'])?$params['eyear']:0);
2506                                $emonth = (isset($params['emonth'])?$params['emonth']:0);
2507                                $eday = (isset($params['eday'])?$params['eday']:0);
2508                        }
2509                        if (!isset($params['owner']) && @$this->xmlrpc)
2510                        {
2511                                $owner_id = $GLOBALS['phpgw_info']['user']['user_id'];
2512                        }
2513                        else
2514                        {
2515                                $owner_id = (isset($params['owner'])?$params['owner']:0);
2516                                if($owner_id==0 && $this->is_group)
2517                                {
2518                                        unset($owner_id);
2519                                        $owner_id = $this->g_owner;
2520                                        if($this->debug)
2521                                        {
2522                                                echo '<!-- owner_id in ('.implode(',',$owner_id).') -->'."\n";
2523                                        }
2524                                }
2525                        }
2526                        if(!$eyear && !$emonth && !$eday)
2527                        {
2528                                $edate = mktime(23,59,59,$smonth + 1,$sday + 1,$syear);
2529                                $eyear = date('Y',$edate);
2530                                $emonth = date('m',$edate);
2531                                $eday = date('d',$edate);
2532                        }
2533                        else
2534                        {
2535                                if(!$eyear)
2536                                {
2537                                        $eyear = $syear;
2538                                }
2539                                //Tratamento do valor final (mes) da pesquisa de eventos feita em $this->so->list_events.
2540                                //Se $emonth nao tem valor, recebe o valor de $smonth (que recebe $params['smonth']) e soma 1.
2541                                //O valor $params['emonth'] indica o mes final para a pesquisa de eventos, e passou a ser
2542                                //informado na a impressao de eventos mensais. Mudancas feitas em class.uicalendar.inc.php,
2543                                //function display_month_print();
2544                                if(!$emonth)
2545                                {
2546                                        $emonth = $smonth + 1;
2547                                        if($emonth > 12)
2548                                        {
2549                                                $emonth = 1;
2550                                                $eyear++;
2551                                        }
2552                                }
2553                                if(!$eday)
2554                                {
2555                                        $eday = $sday + 1;
2556                                }
2557                                $edate = mktime(23,59,59,$emonth,$eday,$eyear);
2558                        }
2559                        //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";
2560                        if($this->debug)
2561                        {
2562                                echo '<!-- Start Date : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2563                                echo '<!-- End   Date : '.sprintf("%04d%02d%02d",$eyear,$emonth,$eday).' -->'."\n";
2564                        }
2565                        //A variavel $month_print recebe o parametro 'saux' com o mes de inicio da pesquisa de eventos por
2566                        //$this->so->list_events. O valor do mes final da pesquisa e tratado no codigo acima;
2567                        //$month_ini = $params['saux'];
2568
2569                        if($owner_id)
2570                        {
2571                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2572                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday,$owner_id);
2573                        }
2574                        else
2575                        {
2576                                $cached_event_ids = $this->so->list_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2577                                $cached_event_ids_repeating = $this->so->list_repeated_events($syear,$smonth,$sday,$eyear,$emonth,$eday);
2578                        }
2579
2580                        $c_cached_ids = count($cached_event_ids);
2581                        $c_cached_ids_repeating = count($cached_event_ids_repeating);
2582
2583                        if($this->debug)
2584                        {
2585                                echo '<!-- events cached : '.$c_cached_ids.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2586                                echo '<!-- repeating events cached : '.$c_cached_ids_repeating.' : for : '.sprintf("%04d%02d%02d",$syear,$smonth,$sday).' -->'."\n";
2587                        }
2588
2589                        $this->cached_events = Array();
2590
2591                        if($c_cached_ids == 0 && $c_cached_ids_repeating == 0)
2592                        {
2593                                return;
2594                        }
2595
2596                        $cache_start = (int)(sprintf("%04d%02d%02d",$syear,$smonth,$sday));
2597                        $cached_event=$this->get_cached_event();
2598                        if($c_cached_ids)
2599                        {
2600                                for($i=0;$i<$c_cached_ids;$i++)
2601                                {
2602                                        $event = $this->so->read_entry($cached_event_ids[$i]);
2603                                        if ($event['recur_type'])
2604                                        {
2605                                                continue;       // fetch recuring events only in 2. loop
2606                                        }
2607                                        $startdate = (int)(date('Ymd',$this->maketime($event['start'])));
2608                                        $enddate = (int)(date('Ymd',$this->maketime($event['end'])));
2609                                        $this->cached_events[$startdate][] = $event;
2610                                        if($startdate != $enddate)
2611                                        {
2612                                                $start['year'] = (int)(substr($startdate,0,4));
2613                                                $start['month'] = (int)(substr($startdate,4,2));
2614                                                $start['mday'] = (int)(substr($startdate,6,2));
2615                                                for($j=$startdate,$k=0;$j<=$enddate;$k++,$j=(int)(date('Ymd',mktime(0,0,0,$start['month'],$start['mday'] + $k,$start['year']))))
2616                                                {
2617                                                        $c_evt_day = count($this->cached_events[$j]) - 1;
2618                                                        if($c_evt_day < 0)
2619                                                        {
2620                                                                $c_evt_day = 0;
2621                                                        }
2622                                                        if($this->debug)
2623                                                        {
2624                                                                echo '<!-- Date: '.$j.' Count : '.$c_evt_day.' -->'."\n";
2625                                                        }
2626                                                        if($this->cached_events[$j][$c_evt_day]['id'] != $event['id'])
2627                                                        {
2628                                                                if($this->debug)
2629                                                                {
2630                                                                        echo '<!-- Adding Event for Date: '.$j.' -->'."\n";
2631                                                                }
2632                                                                $this->cached_events[$j][] = $event;
2633                                                        }
2634                                                        if ($j >= $cache_start && (@$params['no_doubles'] || @$this->xmlrpc))
2635                                                        {
2636                                                                break;  // add event only once on it's startdate
2637                                                        }
2638                                                }
2639                                        }
2640                                }
2641                        }
2642
2643                        $this->repeating_events = Array();
2644                        if($c_cached_ids_repeating)
2645                        {
2646                                for($i=0;$i<$c_cached_ids_repeating;$i++)
2647                                {
2648                                        $this->repeating_events[$i] = $this->so->read_entry($cached_event_ids_repeating[$i]);
2649                                        if($this->debug)
2650                                        {
2651                                                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";
2652                                        }
2653                                }
2654                                for($date=mktime(0,0,0,$smonth,$sday,$syear);$date<=$edate;$date += 86400)
2655                                {
2656                                        if($this->debug)
2657                                        {
2658                                                $search_date = date('Ymd',$date);
2659                                                echo '<!-- Calling check_repeating_events('.$search_date.') -->'."\n";
2660                                        }
2661                                        $this->check_repeating_events($date);
2662                                        if($this->debug)
2663                                        {
2664                                                echo '<!-- Total events found matching '.$search_date.' = '.count($this->cached_events[$search_date]).' -->'."\n";
2665                                                for($i=0;$i<count($this->cached_events[$search_date]);$i++)
2666                                                {
2667                                                        echo '<!-- Date: '.$search_date.' ['.$i.'] = '.$this->cached_events[$search_date][$i]['id'].' -->'."\n";
2668                                                }
2669                                        }
2670                                }
2671                        }
2672                        $retval = Array();
2673                        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)))
2674                        {
2675                                if(is_array($this->cached_events[$j]))
2676                                {
2677                                        if ($this->xmlrpc)
2678                                        {
2679                                                foreach($this->cached_events[$j] as $event)
2680                                                {
2681                                                        $retval[] = $this->xmlrpc_prepare($event);
2682                                                }
2683                                        }
2684                                        else
2685                                        {
2686                                                $retval[$j] = $this->cached_events[$j];
2687                                        }
2688                                }
2689                        }
2690                        //echo "store_to_cache(".print_r($params,True).")=<pre>".print_r($retval,True)."</pre>\n";
2691                        $this->so->cal->event = $cached_event;
2692                        return $retval;
2693                }
2694
2695                function xmlrpc_prepare(&$event)
2696                {
2697                        $event['rights'] = $this->grants[$event['owner']];
2698
2699                        foreach(array('start','end','modtime','recur_enddate') as $name)
2700                        {
2701                                if (isset($event[$name]))
2702                                {
2703                                        $event[$name] = $GLOBALS['server']->date2iso8601($event[$name]);
2704                                }
2705                        }
2706                        if (is_array($event['recur_exception']))
2707                        {
2708                                foreach($event['recur_exception'] as $key => $timestamp)
2709                                {
2710                                        $event['recur_exception'][$key] = $GLOBALS['server']->date2iso8601($timestamp);
2711                                }
2712                        }
2713                        static $user_cache = array();
2714
2715                        if (!is_object($GLOBALS['phpgw']->perferences))
2716                        {
2717                                $GLOBALS['phpgw']->perferences = CreateObject('phpgwapi.preferences');
2718                        }
2719                        foreach($event['participants'] as $user_id => $status)
2720                        {
2721                                if (!isset($user_cache[$user_id]))
2722                                {
2723                                        $user_cache[$user_id] = array(
2724                                                'name'   => $GLOBALS['phpgw']->common->grab_owner_name($user_id),
2725                                                'email'  => $GLOBALS['phpgw']->perferences->email_address($user_id)
2726                                        );
2727                                }
2728                                $event['participants'][$user_id] = $user_cache[$user_id] + array(
2729                                        'status' => $status,
2730                                );
2731                        }
2732                        if (is_array($event['alarm']))
2733                        {
2734                                foreach($event['alarm'] as $id => $alarm)
2735                                {
2736                                        $event['alarm'][$id]['time'] = $GLOBALS['server']->date2iso8601($alarm['time']);
2737                                        if ($alarm['owner'] != $GLOBALS['phpgw_info']['user']['account_id'])
2738                                        {
2739                                                unset($event['alarm'][$id]);
2740                                        }
2741                                }
2742                        }
2743                        $event['category'] = $GLOBALS['server']->cats2xmlrpc(explode(',',$event['category']));
2744
2745                        // using access={public|privat} in all modules via xmlrpc
2746                        $event['access'] = $event['public'] ? 'public' : 'privat';
2747                        unset($event['public']);
2748
2749                        return $event;
2750                }
2751
2752                /* Begin Appsession Data */
2753                function store_to_appsession($event)
2754                {
2755                        $GLOBALS['phpgw']->session->appsession('entry','calendar',$event);
2756                }
2757
2758                function restore_from_appsession()
2759                {
2760                        $this->event_init();
2761                        $event = $GLOBALS['phpgw']->session->appsession('entry','calendar');
2762                        $this->so->cal->event = $event;
2763                        return $event;
2764                }
2765                /* End Appsession Data */
2766
2767                /* Begin of SO functions */
2768                function get_cached_event()
2769                {
2770                        return $this->so->get_cached_event();
2771                }
2772
2773                function add_attribute($var,$value,$index='**(**')
2774                {
2775                        $this->so->add_attribute($var,$value,$index);
2776                }
2777
2778                function event_init()
2779                {
2780                        $this->so->event_init();
2781                }
2782
2783                function set_start($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2784                {
2785                        $this->so->set_start($year,$month,$day,$hour,$min,$sec);
2786                }
2787
2788                function set_end($year,$month,$day=0,$hour=0,$min=0,$sec=0)
2789                {
2790                        $this->so->set_end($year,$month,$day,$hour,$min,$sec);
2791                }
2792
2793                function set_title($title='')
2794                {
2795                        $this->so->set_title($title);
2796                }
2797
2798                function set_description($description='')
2799                {
2800                        $this->so->set_description($description);
2801                }
2802                function set_ex_participants($ex_participants='')
2803                {
2804                        $this->so->set_ex_participants($ex_participants);
2805                }
2806
2807                function set_class($class)
2808                {
2809                        $this->so->set_class($class);
2810                }
2811
2812                function set_category($category='')
2813                {
2814                        $this->so->set_category($category);
2815                }
2816
2817                function set_alarm($alarm)
2818                {
2819                        $this->so->set_alarm($alarm);
2820                }
2821
2822                function set_recur_none()
2823                {
2824                        $this->so->set_recur_none();
2825                }
2826
2827                function set_recur_daily($year,$month,$day,$interval)
2828                {
2829                        $this->so->set_recur_daily($year,$month,$day,$interval);
2830                }
2831
2832                function set_recur_weekly($year,$month,$day,$interval,$weekdays)
2833                {
2834                        $this->so->set_recur_weekly($year,$month,$day,$interval,$weekdays);
2835                }
2836
2837                function set_recur_monthly_mday($year,$month,$day,$interval)
2838                {
2839                        $this->so->set_recur_monthly_mday($year,$month,$day,$interval);
2840                }
2841
2842                function set_recur_monthly_wday($year,$month,$day,$interval)
2843                {
2844                        $this->so->set_recur_monthly_wday($year,$month,$day,$interval);
2845                }
2846
2847                function set_recur_yearly($year,$month,$day,$interval)
2848                {
2849                        $this->so->set_recur_yearly($year,$month,$day,$interval);
2850                }
2851                /* End of SO functions */
2852
2853                function prepare_matrix($interval,$increment,$part,$fulldate)
2854                {
2855                        for($h=0;$h<24;$h++)
2856                        {
2857                                for($m=0;$m<$interval;$m++)
2858                                {
2859                                        $index = (($h * 10000) + (($m * $increment) * 100));
2860                                        $time_slice[$index]['marker'] = '&nbsp';
2861                                        $time_slice[$index]['description'] = '';
2862                                }
2863                        }
2864                        foreach($this->cached_events[$fulldate] as $event)
2865                        {
2866                                if ($event['participants'][$part] == 'R')
2867                                {
2868                                        continue;       // dont show rejected invitations, as they are free time
2869                                }
2870                                $eventstart = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset);
2871                                $eventend = $GLOBALS['phpgw']->datetime->localdates($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset);
2872                                $start = ($eventstart['hour'] * 10000) + ($eventstart['minute'] * 100);
2873                                $starttemp = $this->splittime("$start",False);
2874                                $subminute = 0;
2875                                for($m=0;$m<$interval;$m++)
2876                                {
2877                                        $minutes = $increment * $m;
2878                                        if((int)$starttemp['minute'] > $minutes && (int)$starttemp['minute'] < ($minutes + $increment))
2879                                        {
2880                                                $subminute = ($starttemp['minute'] - $minutes) * 100;
2881                                        }
2882                                }
2883                                $start -= $subminute;
2884                                $end =  ($eventend['hour'] * 10000) + ($eventend['minute'] * 100);
2885                                $endtemp = $this->splittime("$end",False);
2886                                $addminute = 0;
2887                                for($m=0;$m<$interval;$m++)
2888                                {
2889                                        $minutes = ($increment * $m);
2890                                        if($endtemp['minute'] < ($minutes + $increment) && $endtemp['minute'] > $minutes)
2891                                        {
2892                                                $addminute = ($minutes + $increment - $endtemp['minute']) * 100;
2893                                        }
2894                                }
2895                                $end += $addminute;
2896                                $starttemp = $this->splittime("$start",False);
2897                                $endtemp = $this->splittime("$end",False);
2898
2899                                for($h=$starttemp['hour'];$h<=$endtemp['hour'];$h++)
2900                                {
2901                                        $startminute = 0;
2902                                        $endminute = $interval;
2903                                        $hour = $h * 10000;
2904                                        if($h == (int)$starttemp['hour'])
2905                                        {
2906                                                $startminute = ($starttemp['minute'] / $increment);
2907                                        }
2908                                        if($h == (int)$endtemp['hour'])
2909                                        {
2910                                                $endminute = ($endtemp['minute'] / $increment);
2911                                        }
2912                                        $private = $this->is_private($event,$part);
2913                                        $time_display = $GLOBALS['phpgw']->common->show_date($eventstart['raw'],$this->users_timeformat).'-'.$GLOBALS['phpgw']->common->show_date($eventend['raw'],$this->users_timeformat);
2914                                        $time_description = '('.$time_display.') '.$this->get_short_field($event,$private,'title').$this->display_status($event['participants'][$part]);
2915                                        for($m=$startminute;$m<$endminute;$m++)
2916                                        {
2917                                                $index = ($hour + (($m * $increment) * 100));
2918                                                $time_slice[$index]['marker'] = '-';
2919                                                $time_slice[$index]['description'] = $time_description;
2920                                                $time_slice[$index]['id'] = $event['id'];
2921                                        }
2922                                }
2923                        }
2924                        return $time_slice;
2925                }
2926
2927                /*!
2928                @function set_status
2929                @abstract set the participant response $status for event $cal_id and notifies the owner of the event
2930                */
2931                function set_status($cal_id,$status)
2932                {
2933                        $status2msg = array(
2934                                REJECTED  => MSG_REJECTED,
2935                                TENTATIVE => MSG_TENTATIVE,
2936                                ACCEPTED  => MSG_ACCEPTED
2937                        );
2938                        if (!isset($status2msg[$status]))
2939                        {
2940                                return False;
2941                        }
2942                        $event = $this->so->read_entry($cal_id);
2943                        $account_id = $GLOBALS['phpgw_info']['user']['account_id'];
2944                        if(($status2msg[$status] == "5" && $event['participants'][$account_id] == "A") ||
2945                         ($status2msg[$status] == "3" && $event['participants'][$account_id] == "R")) {
2946                                return True;
2947                        }
2948                        $this->so->set_status($cal_id,$status);
2949                        $event = $this->so->read_entry($cal_id);
2950                        $this->send_update($status2msg[$status],$event['participants'],$event);
2951
2952                }
2953
2954                /*!
2955                @function update_requested
2956                @abstract checks if $userid has requested (in $part_prefs) updates for $msg_type
2957                @syntax update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2958                @param $userid numerical user-id
2959                @param $part_prefs preferces of the user $userid
2960                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
2961                @param $old_event Event before the change
2962                @param $new_event Event after the change
2963                @returns 0 = no update requested, > 0 update requested
2964                */
2965                function update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event)
2966                {
2967                        if ($msg_type == MSG_ALARM)
2968                        {
2969                                return True;    // always True for now
2970                        }
2971                        $want_update = 0;
2972
2973                        // the following switch fall-through all cases, as each included the following too
2974                        //
2975                        $msg_is_response = $msg_type == MSG_REJECTED || $msg_type == MSG_ACCEPTED || $msg_type == MSG_TENTATIVE;
2976
2977                        switch($ru = $part_prefs['calendar']['receive_updates'])
2978                        {
2979                                case 'responses':
2980                                        if ($msg_is_response)
2981                                        {
2982                                                ++$want_update;
2983                                        }
2984                                case 'modifications':
2985                                        if ($msg_type == MSG_MODIFIED)
2986                                        {
2987                                                ++$want_update;
2988                                        }
2989                                case 'time_change_4h':
2990                                case 'time_change':
2991                                        $diff = max(abs($this->maketime($old_event['start'])-$this->maketime($new_event['start'])),
2992                                                abs($this->maketime($old_event['end'])-$this->maketime($new_event['end'])));
2993                                        $check = $ru == 'time_change_4h' ? 4 * 60 * 60 - 1 : 0;
2994                                        if ($msg_type == MSG_MODIFIED && $diff > $check)
2995                                        {
2996                                                ++$want_update;
2997                                        }
2998                                case 'add_cancel':
2999                                        if ($old_event['owner'] == $userid && $msg_is_response ||
3000                                                $msg_type == MSG_DELETED || $msg_type == MSG_ADDED)
3001                                        {
3002                                                ++$want_update;
3003                                        }
3004                                        break;
3005                                case 'no':
3006                                        break;
3007                        }
3008                        //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";
3009                        return $want_update > 0;
3010                }
3011
3012                function create_vcard($event_arrays)
3013                {
3014            if(!is_array($event_arrays))
3015                                return null;
3016
3017                        $sender = $GLOBALS['phpgw_info']['user']['email'];
3018                        $uid_dono = $GLOBALS['phpgw_info']['user']['account_lid'];
3019                        $tmpattach="BEGIN:VCALENDAR\n"
3020                        ."PRODID:-//Expresso Livre//Calendar//EN\n"
3021                        ."VERSION:1.0\n";
3022            foreach ($event_arrays as $event)
3023            {
3024                                // It translates int to string
3025                                if (!is_object($event) && !is_array($event) || !array_key_exists  ('end', $event))
3026                                        $event = $event_arrays;
3027
3028                                //set to GMT
3029                                //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.
3030                                $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;
3031                                $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;
3032                               
3033                                $start_time = date("Ymd\THis\Z", $start_time);
3034                                $end_time = date("Ymd\THis\Z", $end_time);
3035       
3036                                // Necessário espaços após quebra-de-linha, na descrição, caso contrário
3037                                // ocorrerá erro ao importar o agendamento no Outlook (erro lunar).
3038                                $description = str_replace("\n","\n ", $event['description']);
3039                               
3040                                $tmpattach.="BEGIN:VEVENT\r\n"
3041                                ."DTSTART:".$start_time."\r\n"
3042                                ."DTEND:".$end_time."\r\n"
3043                                ."LAST-MODIFIED:".gmdate("Ymd\THis\Z")."\r\n" //Hora no formato UTC
3044                                //."UID:Expresso-".$event['id'].$event['uid']."\r\n"
3045                                ."UID:Expresso-".$event[id]."@".$uid_dono."\n"
3046                                ."DESCRIPTION:".$description."\r\n"
3047                                ."SUMMARY:".$event['title']."\r\n"
3048                                ."LOCATION:".$event['location']."\r\n"
3049                                ."ORGANIZER:mailto:".$sender."\n";
3050                                $expart=preg_split('/,/', $event['ex_participants']);
3051
3052                                foreach ($expart as $mail)
3053                                {
3054                                    if($mail != "")
3055                                    {
3056                                        $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
3057                                    }
3058                                }
3059                               
3060                                while (list($id,$status) = each($event['participants']))
3061                                {
3062
3063                                      $preferences = CreateObject('phpgwapi.preferences',$id);
3064                                      $mail = $preferences->email_address($id);
3065                                      if ( $sender != $mail)
3066                                      {
3067                                         if($status == 'U' ){
3068                                                  $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
3069                                                        }
3070                                         elseif($status == 'A' ){
3071                                                 $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=ACCEPTED;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
3072                                                        }
3073                                         elseif($status == 'T' ){
3074                                                 $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=TENTATIVE;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
3075                                                         }
3076                                         else
3077                                                  {
3078                                                     $tmpattach.="ATTENDEE;RSVP=TRUE;PARTSTAT=DECLINED;ROLE=REQ-PARTICIPANT:mailto:".$mail."\n";
3079                                                   }
3080                                      }
3081                                }
3082                                $tmpattach.="END:VEVENT"."\n";
3083                                //."END:VEVENT\r\n";
3084                        }
3085                    $tmpattach.="END:VCALENDAR\r\n";
3086                    return $tmpattach;
3087                }
3088
3089                /*!
3090                @function send_update
3091                @abstract sends update-messages to certain participants of an event
3092                @syntax send_update($msg_type,$to_notify,$old_event,$new_event=False)
3093                @param $msg_type type of the notification: MSG_ADDED, MSG_MODIFIED, MSG_ACCEPTED, ...
3094                @param $to_notify array with numerical user-ids as keys (!) (value is not used)
3095                @param $old_event Event before the change
3096                @param $new_event Event after the change
3097                */
3098                function send_update($msg_type,$to_notify,$old_event,$new_event=False,$user=False)
3099                {                       
3100                        if (!is_array($to_notify))
3101                        {
3102                                $to_notify = array();
3103                        }
3104                        $owner = $old_event ? $old_event['owner'] : $new_event['owner'];
3105                        if ($owner && !isset($to_notify[$owner]) && $msg_type != MSG_ALARM)
3106                        {
3107                                $to_notify[$owner] = 'owner';   // always include the event-owner
3108                        }
3109                        $version = $GLOBALS['phpgw_info']['apps']['calendar']['version'];
3110
3111                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences();
3112                        $sender = $GLOBALS['phpgw_info']['user']['email'];
3113
3114                        $temp_tz_offset = $this->prefs['common']['tz_offset'];
3115                        $temp_timeformat = $this->prefs['common']['timeformat'];
3116                        $temp_dateformat = $this->prefs['common']['dateformat'];
3117
3118                        $tz_offset = ((60 * 60) * (int)$temp_tz_offset);
3119
3120                        if($old_event != False)
3121                        {
3122                                $t_old_start_time = $this->maketime($old_event['start']);
3123                                if($t_old_start_time < (time() - 86400))
3124                                {
3125                                        return False;
3126                                }
3127                        }
3128
3129                        $temp_user = $GLOBALS['phpgw_info']['user'];
3130
3131                        if (!$user)
3132                        {
3133                                $user = $this->owner;
3134                        }
3135                        $GLOBALS['phpgw_info']['user']['preferences'] = $GLOBALS['phpgw']->preferences->create_email_preferences($user);
3136
3137                        $event = $msg_type == MSG_ADDED || $msg_type == MSG_MODIFIED ? $new_event : $old_event;
3138                        if($old_event != False)
3139                        {
3140                                $old_starttime = $t_old_start_time - $GLOBALS['phpgw']->datetime->tz_offset;
3141                        }
3142                        $starttime = $this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
3143                        $endtime   = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
3144
3145                        switch($msg_type)
3146                        {
3147                                case MSG_DELETED:
3148                                        $action = lang('Canceled');
3149                                        $msg = 'Canceled';
3150                                        $msgtype = '"calendar";';
3151                                        $method = 'cancel';
3152                                        $typesend = 1;
3153                                        break;
3154                                case MSG_MODIFIED:
3155                                        $action = lang('Modified');
3156                                        $msg = 'Modified';
3157                                        $msgtype = '"calendar"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
3158                                        $method = 'request';
3159                                        $typesend = 2;
3160                                        break;
3161                                case MSG_ADDED:
3162                                        $action = lang('Added');
3163                                        $msg = 'Added';
3164                                        $msgtype = '"calendar"; Version="'.$version.'"; Id="'.$new_event['id'].'"';
3165                                        $method = 'request';
3166                                        $typesend = 3;
3167                                        break;
3168                                case MSG_REJECTED:
3169                                        $action = lang('Rejected');
3170                                        $msg = 'Response';
3171                                        $msgtype = '"calendar";';
3172                                        $method = 'reply';
3173                                        $typesend = 4;
3174                                        break;
3175                                case MSG_TENTATIVE:
3176                                        $action = lang('Tentative');
3177                                        $msg = 'Response';
3178                                        $msgtype = '"calendar";';
3179                                        $method = 'reply';
3180                                        $typesend = 5;
3181                                        break;
3182                                case MSG_ACCEPTED:
3183                                        $action = lang('Accepted');
3184                                        $msg = 'Response';
3185                                        $msgtype = '"calendar";';
3186                                        $method = 'reply';
3187                                        $typesend = 6;
3188                                        break;
3189                                case MSG_ALARM:
3190                                        $action = lang('Alarm');
3191                                        $msg = 'Alarm';
3192                                        $msgtype = '"calendar";';
3193                                        $method = 'publish';    // duno if thats right
3194                                        $typesend = 7;
3195                                        break;
3196                                default:
3197                                        $method = 'publish';
3198                                        $typesend = 8;
3199                        }
3200                        $notify_msg = $this->prefs['calendar']['notify'.$msg];
3201                        if (empty($notify_msg))
3202                        {
3203                                $notify_msg = $this->prefs['calendar']['notifyAdded'];  // use a default
3204                        }
3205                        $details = array(                       // event-details for the notify-msg
3206                                'id'          => $msg_type == MSG_ADDED ? $new_event['id'] : $old_event['id'],
3207                                'action'      => $action,
3208                        );
3209                        $event_arr = $this->event2array($event);
3210                        foreach($event_arr as $key => $val)
3211                        {
3212                                $details[$key] = $val['data'];
3213                        }
3214                       
3215                        $details['participants'] = implode("\n",$details['participants']);
3216
3217                        $details['link'] = $GLOBALS['phpgw_info']['server']['webserver_url'].'/index.php?menuaction=calendar.uicalendar.view&cal_id='.$event['id'];
3218                        // if url is only a path, try guessing the rest ;-)
3219                        if ($GLOBALS['phpgw_info']['server']['webserver_url'][0] == '/')
3220                        {
3221                                $details['link'] = ($GLOBALS['phpgw_info']['server']['enforce_ssl'] ? 'https://' : 'http://').
3222                                        ($GLOBALS['phpgw_info']['server']['hostname'] ? $GLOBALS['phpgw_info']['server']['hostname'] : 'localhost').
3223                                        $details['link'];
3224                        }
3225                       
3226                        //Seta o email usando phpmailer
3227                        define('PHPGW_INCLUDE_ROOT','../');     
3228                        define('PHPGW_API_INC','../phpgwapi/inc');     
3229                        include_once(PHPGW_API_INC.'/class.phpmailer.inc.php');
3230                        $mail = new PHPMailer();
3231                        $mail->IsSMTP();
3232                        $boemailadmin = CreateObject('emailadmin.bo');
3233                        $emailadmin_profile = $boemailadmin->getProfileList();
3234                        $emailadmin = $boemailadmin->getProfile($emailadmin_profile[0]['profileID']);
3235               
3236                        $mail->Host = $emailadmin['smtpServer'];
3237                        $mail->Port = $emailadmin['smtpPort'];
3238                        $mail->From = $GLOBALS['phpgw']->preferences->values['email'];
3239                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3240                        //$mail->IsHTML(true);
3241                        $mail->IsCalendar(true);
3242
3243                        // Aqui e enviado o email
3244                        foreach($to_notify as $userid => $statusid)
3245                        {
3246                                $mail->ClearAttachments();
3247                               
3248                                $userid = (int)$userid;
3249
3250                                if ($statusid == 'R' || $GLOBALS['phpgw']->accounts->get_type($userid) == 'g')
3251                                {
3252                                        continue;       // dont notify rejected participants
3253                                }
3254                                if($userid != $GLOBALS['phpgw_info']['user']['account_id'] ||  $msg_type == MSG_ALARM || isset($new_event['attachment']))
3255                                {
3256                                        print_debug('Msg Type',$msg_type);
3257                                        print_debug('UserID',$userid);
3258
3259                                        $preferences = CreateObject('phpgwapi.preferences',$userid);
3260                                        $part_prefs = $preferences->read_repository();
3261
3262                                        if (!$this->update_requested($userid,$part_prefs,$msg_type,$old_event,$new_event))
3263                                        {
3264                                                continue;
3265                                        }
3266                                        $GLOBALS['phpgw']->accounts->get_account_name($userid,$lid,$details['to-firstname'],$details['to-lastname']);
3267                                        $details['to-fullname'] = $GLOBALS['phpgw']->common->display_fullname('',$details['to-firstname'],$details['to-lastname']);
3268
3269                                        $to = $preferences->email_address($userid);
3270                                       
3271                                        if (empty($to) || $to[0] == '@' || $to[0] == '$')       // we have no valid email-address
3272                                        {
3273                                                //echo "<p>bocalendar::send_update: Empty email adress for user '".$details['to-fullname']."' ==> ignored !!!</p>\n";
3274                                                continue;
3275                                        }
3276                                        print_debug('Email being sent to',$to);
3277
3278                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $part_prefs['common']['tz_offset'];
3279                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $part_prefs['common']['timeformat'];
3280                                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $part_prefs['common']['dateformat'];
3281
3282                                        $GLOBALS['phpgw']->datetime->tz_offset = ((60 * 60) * (int)$GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset']);
3283
3284                                        if($old_starttime)
3285                                        {
3286                                                $details['olddate'] = $GLOBALS['phpgw']->common->show_date($old_starttime);
3287                                        }
3288                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
3289                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
3290                                       
3291                                       
3292                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
3293                                       
3294                                        switch($part_prefs['calendar']['update_format'])
3295                                        {
3296                                                case  'extended':
3297                                                        //$body .= "\n\n".lang('Event Details follow').":\n";
3298                                                        $body = '';
3299                                                        $body .= "<br>".lang('Event Details follow')." :: ";
3300                                                        foreach($event_arr as $key => $val)
3301                                                        {
3302                                                                // titulo
3303                                                                if($key =='title')
3304                                                                {
3305                                                                        $var1 = $val['field'];
3306                                                                        $vardata1 = $details[$key];
3307                                                                }
3308                                                                //descricao
3309                                                                if($key =='description')
3310                                                                {
3311                                                                        $var2 = $val['field'];
3312                                                                        $vardata2 = $details[$key];
3313                                                                }
3314                                                                //dt inicio
3315                                                                if($key =='startdate')
3316                                                                {
3317                                                                        switch(trim($part_prefs['common']['dateformat']))
3318                                                                        {
3319                                                                               
3320                                                                                case ($part_prefs['common']['dateformat'] === "m/d/Y" || $part_prefs['common']['dateformat'] === "m-d-Y" || $part_prefs['common']['dateformat'] === "m.d.Y"):
3321                                                                                        $var3 = $val['field'];
3322                                                                                        $vardata3 = $details[$key];
3323                                                                                        $newmounth3 = substr($vardata3,0,2);
3324                                                                                        $newday3 = substr($vardata3,3,2);
3325                                                                                        $newyear3 = substr($vardata3,6,4);
3326                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3327                                                                                        break;
3328                                                                                       
3329                                                                                case    ($part_prefs['common']['dateformat'] === "Y/d/m" || $part_prefs['common']['dateformat'] === "Y-d-m" || $part_prefs['common']['dateformat'] === "Y.d.m"):
3330
3331                                                                                        $var3 = $val['field'];
3332                                                                                        $vardata3 = $details[$key];
3333                                                                                        $newyear3 = substr($vardata3,0,4);
3334                                                                                        $newday3 = substr($vardata3,5,2);
3335                                                                                        $newmounth3 = substr($vardata3,8,2);
3336                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3337                                                                                        break;
3338
3339                                                                                case ($part_prefs['common']['dateformat'] === "Y/m/d" || $part_prefs['common']['dateformat'] === "Y-m-d" || $part_prefs['common']['dateformat'] === "Y.m.d"):
3340
3341                                                                                        $var3 = $val['field'];
3342                                                                                        $vardata3 = $details[$key];
3343                                                                                        $newyear3 = substr($vardata3,0,4);
3344                                                                                        $newmounth3 = substr($vardata3,5,2);
3345                                                                                        $newday3 = substr($vardata3,8,2);
3346                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3347                                                                                        break;
3348
3349                                                                                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"):
3350                                                                               
3351                                                                                        $var3 = $val['field'];
3352                                                                                        $vardata3 = $details[$key];
3353                                                                                        $newday3 = substr($vardata3,0,2);
3354                                                                                        $newmounth3 = substr($vardata3,3,2);
3355                                                                                        $newyear3 = substr($vardata3,6,4);
3356                                                                                        $newall3 =$newyear3.$newmounth3.$newday3;
3357                                                                                        break;
3358                                                                       
3359                                                                        }
3360                                                                       
3361                                                                }
3362                                                                //dt final
3363                                                                if($key =='enddate')
3364                                                                {
3365                                                                        $var4 = $val['field'];
3366                                                                        $vardata4 = $details[$key];
3367                                                                }
3368                                                                //localizacao
3369                                                                if($key =='location')
3370                                                                {
3371                                                                        $var8 = $val['field'];
3372                                                                        $vardata8 = $details[$key];
3373                                                                }
3374                                                                //participantes
3375                                                                if($key =='participants')
3376                                                                {
3377                                                                        $var5 = $val['field'];
3378                                                                        foreach($val['data'] as $NewKey => $NewVal)
3379                                                                        {
3380                                                                                //Research inside of ldap ( Pesquisa dentro do ldap )
3381                                                                                $newvalue = $this->so->search_uidNumber($to);
3382                                                                                foreach($newvalue as $tmp)
3383                                                                                {
3384                                                                                        $tmpmail = $tmp['mail'][0];
3385                                                                                        $tmpuid = $tmp['uidnumber'][0];
3386                                                                                        if( trim($tmpmail) == trim($to) & trim($tmpuid) == trim($NewKey))
3387                                                                                        {
3388                                                                                                        if( ( $typesend == 3 ) || ( $typesend == 2 ) )
3389                                                                                                        {
3390                                                                                                                $question = "";
3391                                                                                                               
3392                                                                                                                if( $typesend == 2 )
3393                                                                                                                        $question = lang("Do you wish to change your participation in this event?");
3394
3395                                                                                                                $lang1 = lang("To See Commitment");
3396                                                                                                                $varbuttom = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uicalendar.view&cal_id=$event[id]&date=$newall3' method='POST'>
3397                                                                                                                                                                  <input type='submit' value='$lang1'>
3398                                                                                                                                                                   </form>";
3399                                                                                                                $lang2 = lang("To accept");
3400                                                                                                                $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\")'>";
3401
3402                                                                                                                $lang3 = lang("To reject");
3403                                                                                                                $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\")'>";
3404                                                                                                               
3405                                                                                                                $lang4 = lang("Alarm");
3406                                                                                                                $varbuttom3 = "<form action=".$GLOBALS['phpgw_info']['server']['webserver_url']."/index.php?menuaction=calendar.uialarm.manager method='POST'>
3407                                                                                                                                                                  <input type='submit' value='$lang4'>
3408                                                                                                                                                                  <input type='hidden' name='cal_id' value=$event[id]>
3409                                                                                                                                                                   </form>";
3410                                                                                                                                                                   
3411                                                                                                                $lang5 = lang("Delegate");
3412                                                                                                                $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'>
3413                                                                                                                                                                  <input type='submit' value='$lang5'>
3414                                                                                                                                                                   </form>";
3415                                                                                                               
3416                                                                                                                $lang6 = lang("Tentative");
3417                                                                                                                $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\")'>";                                                                                                             
3418                                                                                                        }
3419                                                                                                        else
3420                                                                                                        {
3421                                                                                                                        $varbuttom  = "";
3422                                                                                                                        $varbuttom1 = "";
3423                                                                                                                        $varbuttom2 = "";
3424                                                                                                                        $varbuttom3 = "";
3425                                                                                                                        $varbuttom4 = "";
3426                                                                                                                        $varbuttom5 = "";
3427                                                                                                        }
3428                                                                                        }
3429                                                                                        // It only mounts variavel with the name of the participants of the list ( Monta a variavel somente com o nome dos participantes da lista)
3430                                                                                        if($typesend == 3)
3431                                                                                        {
3432                                                                                                list($tmpvardata5,$tmp2vardata5) = explode("(",$NewVal);
3433                                                                                                $vardata5 = $tmpvardata5."<br>";
3434                                                                                        }
3435                                                                                        else
3436                                                                                        {
3437                                                                                                $vardata5 = $NewVal."<br>";
3438                                                                                        }
3439                                                                               
3440                                                                                }
3441                                                                                $vardata6 .= $vardata5;
3442                                                                                unset($vardata5);
3443                                                                        }
3444                                                                }               
3445                                                        }
3446                                                        //To mount the message as text/html (Para montar a mensagem como text/html - /phpgwapi/inc/class.send.inc.php )
3447                                                        $content_type = "text/html";
3448                                                        //It mounts the body of the message (Monta o corpo da mensagem)
3449                                                       
3450                                                        // A constante PHPGW_APP_TPL nao existe para envio de alarmes (cront, asyncservice).
3451                                                        define ("PHPGW_APP_TPL",PHPGW_API_INC . "/../../calendar/templates/".$GLOBALS['phpgw_info']['user']['preferences']['common']['template_set']."");
3452                                                       
3453                                                        $body = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
3454                                                        $body->set_file(Array('calendar' => 'body_email.tpl'));
3455                                                        $body->set_block('calendar','list');
3456                                                        $var = Array(
3457                                                                'script'                        => $script,
3458                                                                'subject'                       => $body1,
3459                                                                'var1'                          => $var1,
3460                                                                'vardata1'                      => $vardata1,
3461                                                                'var2'                          => $var2,
3462                                                                'vardata2'                      => $vardata2,
3463                                                                'var3'                          => $var3,
3464                                                                'vardata3'                      => $vardata3,
3465                                                                'var4'                          => $var4,
3466                                                                'vardata4'                      => $vardata4,
3467                                                                'var5'                          => $var5,
3468                                                                'vardata6'                      => $vardata6,
3469                                                                'var8'                          => $var8,
3470                                                                'vardata8'                      => $vardata8,
3471                                                                'question'                      => $question,                                                                                                                   
3472                                                                'varbuttom'                     => $varbuttom,
3473                                                                'varbuttom1'            => $varbuttom1,
3474                                                                'varbuttom2'            => $varbuttom2,
3475                                                                'varbuttom3'            => $varbuttom3,
3476                                                                'varbuttom4'            => $varbuttom4,
3477                                                                'varbuttom5'            => $varbuttom5
3478                                                        );
3479                                                        $body->set_var($var);
3480                                                        $tmpbody = $body->fp('out','list');
3481                                                                                                               
3482                                                        break;
3483
3484                                                case 'ical':
3485                                                        $content_type = "calendar; method=$method; name=calendar.ics";
3486/*                                                      if ($body != '')
3487                                                        {
3488                                                                $boundary = '----Message-Boundary';
3489                                                                $body .= "\n\n\n$boundary\nContent-type: text/$content_type\n".
3490                                                                        "Content-Disposition: inline\nContent-transfer-encoding: 7BIT\n\n";
3491                                                                $content_type = '';
3492                                                        }
3493*/
3494                                                        $body = ExecMethod('calendar.boicalendar.export',array(
3495                                                                'l_event_id'  => $event['id'],
3496                                                                'method'      => $method,
3497                                                                'chunk_split' => False
3498                                                        ));
3499                                                        break;
3500                                        }
3501                                        $mail->AddAddress($to);
3502                                        //$mail->Body = $tmpbody;
3503                                        $tmpattach_n = $this->create_vcard($GLOBALS['bocalendar']->so->cal->event);
3504                                        $tmpattach = str_replace("Expresso-","",$tmpattach_n);
3505                                        $mail->Body = "This is a multi-part message in MIME format.";
3506                                        $mail->Body .= "\n--01BD3665.3AF0D360\n";
3507                                        $mail->Body .= "Content-Type: text/html; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: 8bit\n";
3508                                        $mail->Body .= $tmpbody;
3509                                        $mail->Body .= "\n--01BD3665.3AF0D360\n";
3510                                        $mail->Body .="Content-Type:text/calendar; method=REQUEST; charset=US-ASCII\nContent-Transfer-Encoding:7bit\n\n";
3511                                        $mail->Body .= $tmpattach;
3512                                        $mail->Body .= "\n--01BD3665.3AF0D360--\n";
3513                                        $mail->From = $sender;
3514                                        $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3515                                        $mail->Sender = $mail->From;
3516                                        $mail->SenderName = $mail->FromName;
3517                                        $mail->Subject = $subject;
3518                                        unset($vardata5);
3519                                        unset($vardata6);
3520                                }
3521                        }
3522
3523                        //Inicializa variï¿œvel de retorno.
3524                        $returncode=true;                       
3525                        if(count($mail->to)) {
3526
3527                            if(isset($new_event['attachment'])){
3528                                foreach($new_event['attachment'] as $attach){
3529                                    $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $attach['type']);
3530                                }
3531                            }
3532                                // Envia aviso a todos os participantes.
3533                                if(!$mail->Send()) {                           
3534                                        $returncode = false;
3535                                        $errorInfo['participants'] = $mail->ErrorInfo;
3536                                }
3537                                else
3538                                        $returncode =  true;
3539                        }
3540                       
3541                        if(count($to_notify) && $this->ex_participants){
3542                                $mail->ClearAllRecipients();
3543                                $var = explode(",",trim($this->ex_participants));
3544                                $mail->IsHTML(true);
3545                                $to = array();
3546                                if(!$subject) {
3547                                        $details['startdate'] = $GLOBALS['phpgw']->common->show_date($starttime);
3548                                        $details['enddate']   = $GLOBALS['phpgw']->common->show_date($endtime);
3549                                        list($subject,$body1) = split("\n",$GLOBALS['phpgw']->preferences->parse_notify($notify_msg,$details),2);
3550                                }
3551                               
3552                                foreach($var as $index => $ex_participant){
3553                                        $ex_participant = trim($ex_participant);
3554                                        $ex_participant = preg_replace('#"(.*)" <(.*)\@(.*)\.(.*)>#','\\2@\\3.\\4',$ex_participant);
3555                                                if($ex_participant)
3556                                                        $to[] = $ex_participant;
3557                                }               
3558                               
3559                                foreach($to as $i => $to_array)
3560                                        $mail->AddAddress($to_array);
3561                               
3562                                $_body = explode("<hr size='1' width='100%'>",$tmpbody);
3563                                $tmpbody = $_body[0] ? $_body[0] : $subject ;
3564                                $tmpbody.= "<br><b>".lang("external participants").":: </b> ".htmlentities($this->ex_participants);
3565                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3566                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";
3567                                $tmpbody.= "<br><br><hr size='1' width='100%'><font color='red'>"
3568                                .lang("This message was sent by server. You must send a message to sender to confirm this event")."<br>"
3569                                .lang("This is an external event. Even if it added to your expresso its can be changed any time at all")."</font><br>";
3570                               
3571                                if ($GLOBALS['bocalendar']->so->cal->event[start][month] > 10)
3572                                        $event_month=$GLOBALS['bocalendar']->so->cal->event[start][month];
3573                                else
3574                                        $event_month="0".$GLOBALS['bocalendar']->so->cal->event[start][month];
3575                                //attach extern vcalendar/icalendar (ics)                       
3576                                // define('context','$GLOBALS.bocalendar.so.cal.event');
3577                                $tmpattach = $this->create_vcard($GLOBALS['bocalendar']->so->cal->event);
3578                                if($tmpattach){                                 
3579                                        $tmpbody .="<a href='../index.php?menuaction=calendar.uicalendar.add&date="
3580                                        .$GLOBALS['bocalendar']->so->cal->event[start][year]
3581                                .$event_month
3582                                .$GLOBALS['bocalendar']->so->cal->event[start][mday]
3583                                        ."&hour=".$GLOBALS['bocalendar']->so->cal->event[start][hour]
3584                                        ."&minute=".$GLOBALS['bocalendar']->so->cal->event[start][min]
3585                                        ."&title=".$GLOBALS['bocalendar']->so->cal->event['title']
3586                                        ."&description=".$GLOBALS['bocalendar']->so->cal->event['description']
3587                                        ."&location=".$GLOBALS['bocalendar']->so->cal->event['location']."'>"
3588                                        ."<h2>".lang("Add to my expresso")."</h2>";
3589                                        $tempdir = $GLOBALS['phpgw_info']['server']['temp_dir'] . SEP;
3590                                        srand((double)microtime()*1000000);
3591                                        $random_number = rand(100000000,999999999);
3592                                        $newfilename = md5(time() . getenv("REMOTE_ADDR") . $random_number );
3593                                        $filename = $tempdir . $newfilename;
3594                                        $attach_fd = fopen($filename,"w+");
3595                                        fwrite($attach_fd,$tmpattach);
3596                                        $mail->AddAttachment($filename, "extern.ics", "base64", "text/plain"); // "application/octet-stream"
3597                                        fclose($attach_fd);
3598                                }
3599
3600                                if(isset($new_event['attachment'])){
3601                                    foreach($new_event['attachment'] as $attach){
3602                                        $mail->AddAttachment($attach['tmp_name'], $attach['name'], "base64", $attach['type']);
3603                                    }
3604                                }
3605                               
3606                                $mail->From = $sender;
3607                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3608                                $mail->Sender = $mail->From;
3609                                $mail->SenderName = $mail->FromName;
3610                                $mail->Subject = lang("External event from Expresso");
3611                                $mail->Body = $tmpbody;
3612                                                                                                                                               
3613                                if(!$mail->Send())
3614                                {
3615                                        $returncode=false;
3616                                        $errorInfo['ex_participants'] = $mail->ErrorInfo;
3617                                }
3618                                else
3619                                {
3620                                        $returncode=true;
3621                                }
3622                        }
3623
3624
3625                        if((is_int($this->user) && $this->user != $temp_user['account_id']) ||
3626                                (is_string($this->user) && $this->user != $temp_user['account_lid']))
3627                        {
3628                                $GLOBALS['phpgw_info']['user'] = $temp_user;
3629                        }       
3630
3631                        $GLOBALS['phpgw_info']['user']['preferences']['common']['tz_offset'] = $temp_tz_offset;
3632                        $GLBOALS['phpgw']->datetime->tz_offset = ((60 * 60) * $temp_tz_offset);
3633                        $GLOBALS['phpgw_info']['user']['preferences']['common']['timeformat'] = $temp_timeformat;
3634                        $GLOBALS['phpgw_info']['user']['preferences']['common']['dateformat'] = $temp_dateformat;
3635                       
3636                        // Notifica por email o criador do compromisso, com as possï¿œveis falhas.                                             
3637                        if($errorInfo) {
3638                                $tmpbody = "<font color='red'>".lang("The following commitment had problems for DELIVERING the NOTIFICATION messages.").".</font><br>";
3639                                $tmpbody.= "<br>".lang("Summary").": ".$this->so->cal->event[title]."<br>";
3640                                $tmpbody.= "<br>".lang("Start time").": ".$GLOBALS['phpgw']->common->show_date($starttime)."<br>".lang("End date").": ".$GLOBALS['phpgw']->common->show_date($endtime)."<br>";                         
3641                                $tmpbody.= "<br><u>".lang("Failed to delivery")."</u><br>";
3642                                $failed = false;                               
3643                                if(strstr($errorInfo['participants'],"recipients_failed")){
3644                                        $failed = explode("recipients_failed",$errorInfo['participants']);
3645                                        $tmpbody.= lang("to").": ".$failed[1];
3646                                }
3647                                if(strstr($errorInfo['ex_participants'],"recipients_failed")){
3648                                        $failed = explode("recipients_failed",$errorInfo['ex_participants']);
3649                                        $tmpbody.= lang("to").": ".$failed[1];
3650                                }                       
3651                                if(!$failed) {
3652                                        $tmpbody.= lang("Description").":<br>";
3653                                        $tmpbody.= $errorInfo['participants'];
3654                                        $tmpbody.= "<br>".$errorInfo['ex_participants'];
3655                                }
3656                                $tmpbody.= "<br>".lang("Subject").": ".$subject;
3657                                // Reinicializa o objeto, devido ao erro anterior na entrega.
3658                               
3659                                $mail = new PHPMailer();
3660                                $mail->IsSMTP();
3661                                $mail->Host = $emailadmin['smtpServer'];
3662                                $mail->Port = $emailadmin['smtpPort'];
3663                                $mail->From = $sender;
3664                                $mail->FromName = $GLOBALS['phpgw_info']['user']['fullname'];
3665                                $mail->Sender = $mail->From;
3666                                $mail->SenderName = $mail->FromName;
3667                                $mail->IsHTML(True);
3668                                $mail->Subject = lang("calendar event")." - ".lang("email notification");                                                       
3669                                $mail->Body = $tmpbody;                                 
3670                                $mail->AddAddress($sender);
3671                                if(!$mail->Send())                     
3672                                        $returncode = false;
3673                                else
3674                                        $returncode =  true;
3675                        }
3676                        return $returncode;
3677                }
3678               
3679                function send_alarm($alarm)
3680                {
3681                        //echo "<p>bocalendar::send_alarm("; print_r($alarm); echo ")</p>\n";
3682                       
3683                        $GLOBALS['phpgw_info']['user']['account_id'] = $this->owner = $alarm['owner'];
3684
3685                        if (!$alarm['enabled'] || !$alarm['owner'] || !$alarm['cal_id'] || !($event = $this->so->read_entry($alarm['cal_id'])))
3686                        {
3687                                return False;   // event not found
3688                        }
3689                        if ($alarm['all'])
3690                        {
3691                                $to_notify = $event['participants'];
3692                        }
3693                        elseif ($this->check_perms(PHPGW_ACL_READ,$event))      // checks agains $this->owner set to $alarm[owner]
3694                        {
3695                                $to_notify[$alarm['owner']] = 'A';
3696                        }
3697                        else
3698                        {
3699                                return False;   // no rights
3700                        }
3701                        return $this->send_update(MSG_ALARM,$to_notify,$event,False,$alarm['owner']);
3702                }
3703
3704                function get_alarms($event_id)
3705                {
3706                        return $this->so->get_alarm($event_id);
3707                }
3708
3709                function alarm_today($event,$today,$starttime)
3710                {
3711                        $found = False;
3712                        @reset($event['alarm']);
3713                        $starttime_hi = $GLOBALS['phpgw']->common->show_date($starttime,'Hi');
3714                        $t_appt['month'] =$GLOBALS['phpgw']->common->show_date($today,'m');
3715                        $t_appt['mday'] = $GLOBALS['phpgw']->common->show_date($today,'d');
3716                        $t_appt['year'] = $GLOBALS['phpgw']->common->show_date($today,'Y');
3717                        $t_appt['hour'] = $GLOBALS['phpgw']->common->show_date($starttime,'H');
3718                        $t_appt['min']  = $GLOBALS['phpgw']->common->show_date($starttime,'i');
3719                        $t_appt['sec']  = 0;
3720                        $t_time = $this->maketime($t_appt) - $GLOBALS['phpgw']->datetime->tz_offset;
3721                        $y_time = $t_time - 86400;
3722                        $tt_time = $t_time + 86399;
3723                        print_debug('T_TIME',$t_time.' : '.$GLOBALS['phpgw']->common->show_date($t_time));
3724                        print_debug('Y_TIME',$y_time.' : '.$GLOBALS['phpgw']->common->show_date($y_time));
3725                        print_debug('TT_TIME',$tt_time.' : '.$GLOBALS['phpgw']->common->show_date($tt_time));
3726                        while(list($key,$alarm) = each($event['alarm']))
3727                        {
3728                                if($alarm['enabled'])
3729                                {
3730                                        print_debug('TIME',$alarm['time'].' : '.$GLOBALS['phpgw']->common->show_date($alarm['time']).' ('.$event['id'].')');
3731                                        if($event['recur_type'] != MCAL_RECUR_NONE)   /* Recurring Event */
3732                                        {
3733                                                print_debug('Recurring Event');
3734                                                if($alarm['time'] > $y_time && $GLOBALS['phpgw']->common->show_date($alarm['time'],'Hi') < $starttime_hi && $alarm['time'] < $t_time)
3735                                                {
3736                                                        $found = True;
3737                                                }
3738                                        }
3739                                        elseif($alarm['time'] > $y_time && $alarm['time'] < $t_time)
3740                                        {
3741                                                $found = True;
3742                                        }
3743                                }
3744                        }
3745                        print_debug('Found',$found);
3746                        return $found;
3747                }
3748
3749                function prepare_recipients(&$new_event,$old_event)
3750                {
3751                                               
3752                        // Find modified and deleted users.....
3753                        while(list($old_userid,$old_status) = each($old_event['participants']))
3754                        {
3755                                if(isset($new_event['participants'][$old_userid]))
3756                                {
3757                                        print_debug('Modifying event for user',$old_userid);
3758                                        $this->modified[(int)$old_userid] = $new_status;
3759                                }
3760                                else
3761                                {
3762                                        print_debug('Deleting user from the event',$old_userid);
3763                                        $this->deleted[(int)$old_userid] = $old_status;
3764                                }
3765                        }
3766                        // Find new users.....
3767                        while(list($new_userid,$new_status) = each($new_event['participants']))
3768                        {
3769                                if(!isset($old_event['participants'][$new_userid]))
3770                                {
3771                                        print_debug('Adding event for user',$new_userid);
3772                                        $this->added[$new_userid] = 'U';
3773                                        $new_event['participants'][$new_userid] = 'U';
3774                                }
3775                        }
3776                       
3777                        if(count($this->added) > 0 || count($this->modified) > 0 || count($this->deleted) > 0)
3778                        {
3779                                if(count($this->added) > 0)
3780                                {
3781                                        $this->ex_participants = '';
3782                                        $this->send_update(MSG_ADDED,$this->added,'',$new_event);
3783                                }
3784                                if(count($this->modified) > 0)
3785                                {
3786                                        $this->send_update(MSG_MODIFIED,$this->modified,$old_event,$new_event);
3787                                }
3788                                if(count($this->deleted) > 0)
3789                                {
3790                                        $this->ex_participants = '';
3791                                        $this->send_update(MSG_DELETED,$this->deleted,$old_event);
3792                                }
3793                        }
3794                }
3795
3796                function remove_doubles_in_cache($firstday,$lastday)
3797                {
3798                        $already_moved = Array();
3799                        for($v=$firstday;$v<=$lastday;$v++)
3800                        {
3801                                if (!$this->cached_events[$v])
3802                                {
3803                                        continue;
3804                                }
3805                                $cached = $this->cached_events[$v];
3806                                $this->cached_events[$v] = array();
3807                                while (list($g,$event) = each($cached))
3808                                {
3809                                        $end = date('Ymd',$this->maketime($event['end']));
3810                                        print_debug('EVENT',_debug_array($event,False));
3811                                        print_debug('start',$start);
3812                                        print_debug('v',$v);
3813
3814                                        if (!isset($already_moved[$event['id']]) || $event['recur_type'] && $v > $end)
3815                                        {
3816                                                $this->cached_events[$v][] = $event;
3817                                                $already_moved[$event['id']] = 1;
3818                                                print_debug('Event moved');
3819                                        }
3820                                }
3821                        }
3822                }
3823
3824                function get_dirty_entries($lastmod=-1)
3825                {
3826                        $events = false;
3827                        $event_ids = $this->so->cal->list_dirty_events($lastmod);
3828                        if(is_array($event_ids))
3829                        {
3830                                foreach($event_ids as $key => $id)
3831                                {
3832                                        $events[$id] = $this->so->cal->fetch_event($id);
3833                                }
3834                        }
3835                        unset($event_ids);
3836
3837                        $rep_event_ids = $this->so->cal->list_dirty_events($lastmod,$true);
3838                        if(is_array($rep_event_ids))
3839                        {
3840                                foreach($rep_event_ids as $key => $id)
3841                                {
3842                                        $events[$id] = $this->so->cal->fetch_event($id);
3843                                }
3844                        }
3845                        unset($rep_event_ids);
3846
3847                        return $events;
3848                }
3849
3850                function _debug_array($data)
3851                {
3852                        echo '<br>UI:';
3853                        _debug_array($data);
3854                }
3855
3856                /*!
3857                @function rejected_no_show
3858                @abstract checks if event is rejected from user and he's not the owner and dont want rejected
3859                @param $event to check
3860                @returns True if event should not be shown
3861                */
3862                function rejected_no_show($event)
3863                {
3864                        $ret = !$this->prefs['calendar']['show_rejected'] &&
3865                                $event['owner'] != $this->owner &&
3866                                $event['participants'][$this->owner] == 'R';
3867                        //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";
3868                        return $ret;
3869                }
3870
3871                /* This is called only by list_cals().  It was moved here to remove fatal error in php5 beta4 */
3872                function list_cals_add($id,&$users,&$groups)
3873                {
3874                        $name = $GLOBALS['phpgw']->common->grab_owner_name($id);
3875                        if (($type = $GLOBALS['phpgw']->accounts->get_type($id)) == 'g')
3876                        {
3877                                $arr = &$groups;
3878                        }
3879                        else
3880                        {
3881                                $arr = &$users;
3882                        }
3883                        $arr[$name] = Array(
3884                                'grantor' => $id,
3885                                'value'   => ($type == 'g' ? 'g_' : '') . $id,
3886                                'name'    => $name
3887                        );
3888                }
3889
3890                /*!
3891                @function list_cals
3892                @abstract generate list of user- / group-calendars for the selectbox in the header
3893                @returns alphabeticaly sorted array with groups first and then users
3894                */
3895                function list_cals()
3896                {
3897                        $users = $groups = array();
3898                        foreach($this->grants as $id => $rights)
3899                        {
3900                                $this->list_cals_add($id,$users,$groups);
3901                        }
3902                       
3903                        //by JakJr, melhora de performance na abertura da agenda
3904                        /*if ($memberships = $GLOBALS['phpgw']->accounts->membership($GLOBALS['phpgw_info']['user']['account_id']))
3905                        {
3906                                foreach($memberships as $group_info)
3907                                {
3908                                        $this->list_cals_add($group_info['account_id'],$users,$groups);
3909
3910                                        if ($account_perms = $GLOBALS['phpgw']->acl->get_ids_for_location($group_info['account_id'],PHPGW_ACL_READ,'calendar'))
3911                                        {
3912                                                foreach($account_perms as $id)
3913                                                {
3914                                                        $this->list_cals_add($id,$users,$groups);
3915                                                }
3916                                        }
3917                                }
3918                        }*/
3919                        uksort($users,'strnatcasecmp');
3920                        uksort($groups,'strnatcasecmp');
3921
3922                        return $users + $groups;        // users first and then groups, both alphabeticaly
3923                }
3924
3925          function translate($key,$vars=false, $not_found='*' )
3926          {
3927            if ($this->async)
3928              return $GLOBALS['phpgw']->translation->translate_async($key, $vars);
3929            return lang($key, $vars);
3930          }
3931
3932                /*!
3933                @function event2array
3934                @abstract create array with name, translated name and readable content of each attributes of an event
3935                @syntax event2array($event,$sep='<br>')
3936                @param $event event to use
3937                @returns array of attributes with fieldname as key and array with the 'field'=translated name \
3938                        'data' = readable content (for participants this is an array !)
3939                */
3940                function event2array($event)
3941                {
3942                       
3943                       
3944                  $var['title'] = Array(
3945                                'field'         => $this->translate('Title'),
3946                                'data'          => $event['title']
3947                        );
3948
3949                        // Some browser add a \n when its entered in the database. Not a big deal
3950                        // this will be printed even though its not needed.
3951                        $var['description'] = Array(
3952                                'field' => $this->translate('Description'),
3953                                'data'  => $event['description']
3954                        );
3955
3956                        $var['ex_participants'] = Array(
3957                                'field' => $this->translate('External Participants'),
3958                                'data'  => $event['ex_participants']
3959                        );
3960                       
3961                        $cats = Array();
3962                        $this->cat->categories($this->bo->owner,'calendar');
3963                        if(strpos($event['category'],','))
3964                        {
3965                                $cats = explode(',',$event['category']);
3966                        }
3967                        else
3968                        {
3969                                $cats[] = $event['category'];
3970                        }
3971                        foreach($cats as $cat_id)
3972                        {
3973                                list($cat) = $this->cat->return_single($cat_id);
3974                                $cat_string[] = $cat['name'];
3975                        }
3976                        $var['category'] = Array(
3977                                'field' => $this->translate('Category'),
3978                                'data'  => implode(', ',$cat_string)
3979                        );
3980
3981                        $var['location'] = Array(
3982                                'field' => $this->translate('Location'),
3983                                'data'  => $event['location']
3984                        );
3985
3986                        $var['startdate'] = Array(
3987                                'field' => $this->translate('Start Date/Time'),
3988                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset),
3989                        );
3990
3991                        $var['enddate'] = Array(
3992                                'field' => $this->translate('End Date/Time'),
3993                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset)
3994                        );
3995
3996                        $pri = Array(
3997                                1       => lang('Low'),
3998                                2       => lang('Normal'),
3999                                3       => lang('High')
4000                        );
4001                        $var['priority'] = Array(
4002                                'field' => lang('Priority'),
4003                                'data'  => $pri[$event['priority']]
4004                        );
4005
4006                        $var['owner'] = Array(
4007                                'field' => lang('Created By'),
4008                                'data'  => $GLOBALS['phpgw']->common->grab_owner_name($event['owner'])
4009                        );
4010
4011                        $var['updated'] = Array(
4012                                'field' => lang('Updated'),
4013                                'data'  => $GLOBALS['phpgw']->common->show_date($this->maketime($event['modtime']) - $GLOBALS['phpgw']->datetime->tz_offset)
4014                        );
4015
4016                        $var['observations'] = Array(
4017                                'field' => $this->translate('Observations'),
4018                                'data'  => $event['observations']
4019                        );
4020                       
4021                        $var['attachment'] = Array(
4022                                'field' => $this->translate('Attachment'),
4023                                'data'  => $event['attachment']
4024                        );
4025
4026                        $var['alter_by'] = Array(
4027                                'field' => $this->translate('Alter by'),
4028                                'data'  => $event['alter_by']
4029                        );
4030
4031                        $var['access'] = Array(
4032                                'field' => lang('Access'),
4033                                'data'  => $event['public'] ? lang('Public') : lang('Private')
4034                        );
4035
4036                        if(@isset($event['groups'][0]))
4037                        {
4038                                $cal_grps = '';
4039                                for($i=0;$i<count($event['groups']);$i++)
4040                                {
4041                                        if($GLOBALS['phpgw']->accounts->exists($event['groups'][$i]))
4042                                        {
4043                                                $cal_grps .= ($i>0?'<br>':'').$GLOBALS['phpgw']->accounts->id2name($event['groups'][$i]);
4044                                        }
4045                                }
4046
4047                                $var['groups'] = Array(
4048                                        'field' => lang('Groups'),
4049                                        'data'  => $cal_grps
4050                                );
4051                        }
4052
4053                        $participants = array();
4054                        foreach($event['participants'] as $user => $short_status)
4055                        {
4056                                if($GLOBALS['phpgw']->accounts->exists($user))
4057                                {
4058                                        $participants[$user] = $GLOBALS['phpgw']->common->grab_owner_name($user).' ('.$this->get_long_status($short_status).')';
4059                                }
4060                        }
4061                        $var['participants'] = Array(
4062                                'field' => $this->translate('Participants'),
4063                                'data'  => $participants
4064                        );
4065
4066                        // Repeated Events
4067                        if($event['recur_type'] != MCAL_RECUR_NONE)
4068                        {
4069                                $str = lang($this->rpt_type[$event['recur_type']]);
4070
4071                                $str_extra = array();
4072                                if ($event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['month'] != 0 && $event['recur_enddate']['year'] != 0)
4073                                {
4074                                        $recur_end = $this->maketime($event['recur_enddate']);
4075                                        if($recur_end != 0)
4076                                        {
4077                                                $recur_end -= $GLOBALS['phpgw']->datetime->tz_offset;
4078                                                $str_extra[] = lang('ends').': '.lang($GLOBALS['phpgw']->common->show_date($recur_end,'l')).', '.$this->long_date($recur_end).' ';
4079                                        }
4080                                }
4081                                // only weekly uses the recur-data (days) !!!
4082                                if($event['recur_type'] == MCAL_RECUR_WEEKLY)
4083                                {
4084                                        $repeat_days = array();
4085                                        foreach ($this->rpt_day as $mcal_mask => $dayname)
4086                                        {
4087                                                if ($event['recur_data'] & $mcal_mask)
4088                                                {
4089                                                        $repeat_days[] = lang($dayname);
4090                                                }
4091                                        }
4092                                        if(count($repeat_days))
4093                                        {
4094                                                $str_extra[] = lang('days repeated').': '.implode(', ',$repeat_days);
4095                                        }
4096                                }
4097                                if($event['recur_interval'] != 0)
4098                                {
4099                                        $str_extra[] = lang('Interval').': '.$event['recur_interval'];
4100                                }
4101
4102                                if(count($str_extra))
4103                                {
4104                                        $str .= ' ('.implode(', ',$str_extra).')';
4105                                }
4106
4107                                $var['recure_type'] = Array(
4108                                        'field' => lang('Repetition'),
4109                                        'data'  => $str,
4110                                );
4111                        }
4112
4113                        if (!isset($this->fields))
4114                        {
4115                                $this->custom_fields = CreateObject('calendar.bocustom_fields');
4116                                $this->fields = &$this->custom_fields->fields;
4117                                $this->stock_fields = &$this->custom_fields->stock_fields;
4118                        }
4119                        foreach($this->fields as $field => $data)
4120                        {
4121                                if (!$data['disabled'])
4122                                {
4123                                        if (isset($var[$field]))
4124                                        {
4125                                                $sorted[$field] = $var[$field];
4126                                        }
4127                                        elseif (!isset($this->stock_fields[$field]) && strlen($event[$field]))  // Custom field
4128                                        {
4129                                                $lang = lang($name = substr($field,1));
4130                                                $sorted[$field] = array(
4131                                                        'field' => $lang == $name.'*' ? $name : $lang,
4132                                                        'data'  => $event[$field]
4133                                                );
4134                                        }
4135                                }
4136                                unset($var[$field]);
4137                        }
4138                        foreach($var as $name => $v)
4139                        {
4140                                $sorted[$name] = $v;
4141
4142                        }
4143                        return $sorted;
4144                }
4145
4146                /*!
4147                @function check_set_default_prefs
4148                @abstract sets the default prefs, if they are not already set (on a per pref. basis)
4149                @note It sets a flag in the app-session-data to be called only once per session
4150                */
4151                function check_set_default_prefs()
4152                {
4153                        if (($set = $GLOBALS['phpgw']->session->appsession('default_prefs_set','calendar')))
4154                        {
4155                                return;
4156                        }
4157                        $GLOBALS['phpgw']->session->appsession('default_prefs_set','calendar','set');
4158
4159                        $default_prefs = $GLOBALS['phpgw']->preferences->default['calendar'];
4160
4161                        $subject = $this->translate('Calendar Event') . ' - $$action$$: $$startdate$$ $$title$$'."\n";
4162                        $defaults = array(
4163                                'defaultcalendar' => 'week',
4164                                'mainscreen_showevents' => '0',
4165                                'summary'         => 'no',
4166                                'receive_updates' => 'no',
4167                                'update_format'   => 'extended',        // leave it to extended for now, as iCal kills the message-body
4168                                'notifyAdded'     => $subject . $this->translate ('You have a meeting scheduled for %1',array('$$startdate$$')),
4169                                'notifyCanceled'  => $subject . $this->translate ('Your meeting scheduled for %1 has been canceled',array('$$startdate$$')),
4170                                'notifyModified'  => $subject . $this->translate ('Your meeting that had been scheduled for %1 has been rescheduled to %2',array('$$olddate$$','$$startdate$$')),
4171                                'notifyResponse'  => $subject . $this->translate ('On %1 %2 %3 your meeting request for %4', array('$$date$$','$$fullname$$','$$action$$','$$startdate$$')),
4172                                'notifyAlarm'     => $this->translate('Alarm for %1 at %2 in %3',array('$$title$$','$$startdate$$','$$location$$')) . "\n" . $this->translate('Here is your requested alarm.'),
4173                                'show_rejected'   => '0',
4174                                'hide_event_conflict'   => '0',
4175                                'display_status'  => '1',
4176                                'weekdaystarts'   => 'Monday',
4177                                'workdaystarts'   => '9',
4178                                'workdayends'     => '17',
4179                                'interval'        => '30',
4180                                'defaultlength'   => '60',
4181                                'planner_start_with_group' => $GLOBALS['phpgw']->accounts->name2id('Default'),
4182                                'planner_intervals_per_day'=> '4',
4183                                'defaultfilter'   => 'all',
4184                                'default_private' => '0',
4185                                'display_minicals'=> '1',
4186                                'print_black_white'=>'0'
4187                        );
4188                        foreach($defaults as $var => $default)
4189                        {
4190                                if (!isset($default_prefs[$var]) || $default_prefs[$var] == '')
4191                                {
4192                                        $GLOBALS['phpgw']->preferences->add('calendar',$var,$default,'default');
4193                                        $need_save = True;
4194                                }
4195                        }
4196                        if ($need_save)
4197                        {
4198                                $prefs = $GLOBALS['phpgw']->preferences->save_repository(False,'default');
4199                                $this->prefs['calendar'] = $prefs['calendar'];
4200                        }
4201                        if ($this->prefs['calendar']['send_updates'] && !isset($this->prefs['calendar']['receive_updates']))
4202                        {
4203                                $this->prefs['calendar']['receive_updates'] = $this->prefs['calendar']['send_updates'];
4204                                $GLOBALS['phpgw']->preferences->add('calendar','receive_updates',$this->prefs['calendar']['send_updates']);
4205                                $GLOBALS['phpgw']->preferences->delete('calendar','send_updates');
4206                                $prefs = $GLOBALS['phpgw']->preferences->save_repository();
4207                        }
4208                }
4209
4210                // return array with all infolog categories (for xmlrpc)
4211                function categories($complete = False)
4212                {
4213                        return $GLOBALS['server']->categories($complete);
4214                }
4215        }
4216?>
Note: See TracBrowser for help on using the repository browser.