source: contrib/Timesheet/inc/class.botimesheet.inc.php @ 3526

Revision 3526, 139.4 KB checked in by afernandes, 13 years ago (diff)

Ticket #1416 - Disponibilizado modulos Timesheet e DMS para a comunidade.

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