source: trunk/calendar/inc/class.socalendar_sql.inc.php @ 7673

Revision 7673, 36.7 KB checked in by douglasz, 11 years ago (diff)

Ticket #3236 - Correcoes para Performance: Function Within Loop Declaration.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1<?php
2  /**************************************************************************\
3  * eGroupWare - Calendar                                                    *
4  * http://www.eGroupWare.org                                                *
5  * Maintained and further developed by RalfBecker@outdoor-training.de       *
6  * Based on Webcalendar by Craig Knudsen <cknudsen@radix.net>               *
7  *          http://www.radix.net/~cknudsen                                  *
8  * Originaly modified by Mark Peters <skeeter@phpgroupware.org>             *
9  * --------------------------------------------                             *
10  *  This program is free software; you can redistribute it and/or modify it *
11  *  under the terms of the GNU General Public License as published by the   *
12  *  Free Software Foundation; either version 2 of the License, or (at your  *
13  *  option) any later version.                                              *
14  \**************************************************************************/
15require_once dirname(__FILE__).'/../../services/class.servicelocator.php';
16
17if(isset($_SESSION['isCrun']))
18        $_SESSION['isCrun'] = false;
19   
20        if (@$GLOBALS['phpgw_info']['flags']['included_classes']['socalendar_'])
21        {
22                return;
23        }
24
25        $GLOBALS['phpgw_info']['flags']['included_classes']['socalendar_'] = True;
26
27        class socalendar_ extends socalendar__
28        {
29                var $deleted_events = Array();
30
31                var $cal_event;
32                var $today = Array('raw','day','month','year','full','dow','dm','bd');
33
34
35                function socalendar_()
36                {
37                        $this->socalendar__();
38
39                        if (!is_object($GLOBALS['phpgw']->asyncservice))
40                        {
41                                $GLOBALS['phpgw']->asyncservice = CreateObject('phpgwapi.asyncservice');
42                        }
43                        $this->async = &$GLOBALS['phpgw']->asyncservice;
44                }
45
46                function open($calendar='',$user='',$passwd='',$options='')
47                {
48                        if($user=='')
49                        {
50        //                      settype($user,'integer');
51                                $this->user = $GLOBALS['phpgw_info']['user']['account_id'];
52                        }
53                        elseif(is_int($user))
54                        {
55                                $this->user = $user;
56                        }
57                        elseif(is_string($user))
58                        {
59                                $this->user = $GLOBALS['phpgw']->accounts->name2id($user);
60                        }
61
62                        $this->stream = $GLOBALS['phpgw']->db;
63                        return $this->stream;
64                }
65
66                function popen($calendar='',$user='',$passwd='',$options='')
67                {
68                        return $this->open($calendar,$user,$passwd,$options);
69                }
70
71                function reopen($calendar,$options='')
72                {
73                        return $this->stream;
74                }
75
76                function close($options='')
77                {
78                        return True;
79                }
80
81                function create_calendar($calendar='')
82                {
83                        return $calendar;
84                }
85
86                function rename_calendar($old_name='',$new_name='')
87                {
88                        return $new_name;
89                }
90
91                function delete_calendar($calendar='')
92                {
93                        $this->stream->query('SELECT cal_id FROM phpgw_cal WHERE owner='.(int)$calendar,__LINE__,__FILE__);
94                        if($this->stream->num_rows())
95                        {
96                                while($this->stream->next_record())
97                                {
98                                        $this->delete_event((int)$this->stream->f('cal_id'));
99                                }
100                                $this->expunge();
101                        }
102                        $this->stream->lock(array('phpgw_cal_user'));
103                        $this->stream->query('DELETE FROM phpgw_cal_user WHERE cal_login='.(int)$calendar,__LINE__,__FILE__);
104                        $this->stream->unlock();
105
106                        return $calendar;
107                }
108
109                /*!
110                @function read_alarms
111                @abstract read the alarms of a calendar-event specified by $cal_id
112                @returns array of alarms with alarm-id as key
113                @note the alarm-id is a string of 'cal:'.$cal_id.':'.$alarm_nr, it is used as the job-id too
114                */
115                function read_alarms($cal_id)
116                {
117                        $alarms = array();
118
119                        if ($jobs = $this->async->read('cal:'.(int)$cal_id.':%'))
120                        {
121                                foreach($jobs as $id => $job)
122                                {
123                                        $alarm         = $job['data'];  // text, enabled
124                                        $alarm['id']   = $id;
125                                        $alarm['time'] = $job['next'];
126
127                                        $alarms[$id] = $alarm;
128                                }
129                        }
130                        return $alarms;
131                }
132
133                /*!
134                @function read_alarm
135                @abstract read a single alarm specified by it's $id
136                @returns array with data of the alarm
137                @note the alarm-id is a string of 'cal:'.$cal_id.':'.$alarm_nr, it is used as the job-id too
138                */
139                function read_alarm($id)
140                {
141                        if (!($jobs = $this->async->read($id)))
142                        {
143                                return False;
144                        }
145                        list($id,$job) = each($jobs);
146                        $alarm         = $job['data'];  // text, enabled
147                        $alarm['id']   = $id;
148                        $alarm['time'] = $job['next'];
149
150                        //echo "<p>read_alarm('$id')="; print_r($alarm); echo "</p>\n";
151                        return $alarm;
152                }
153
154/* Funcao save_alarm modificada para gerar alarmes repetidos, caso seja marcado um evento igualmente repetido. A funcao recebe qual o tipo
155de repeticao escolhido pelo usuario (diario, semanal, mensal, anual) e insere alarmes nas respectivas repeticoes do evento. */
156                /*!
157                @function save_alarm
158                @abstract saves a new or updated alarm
159                @syntax save_alarm($cal_id,$alarm,$id=False)
160                @param $cal_id Id of the calendar-entry
161                @param $alarm array with fields: text, owner, enabled, ..
162                @returns the id of the alarm
163                */
164                function save_alarm($cal_id,$alarm)
165                {
166
167                        if (!($id = $alarm['id']))
168                        {
169                                $alarm['time'] -= $GLOBALS['phpgw']->datetime->tz_offset;       // time should be stored in server timezone
170                                $alarms = $this->read_alarms($cal_id);  // find a free alarm#
171
172                                if($alarm['repeat'] == 1) // repeticao do tipo "Diariamente";
173                                {
174                                        $n = 0;
175
176                                        while(@isset($alarms[$id]));
177                                        {
178
179                                                $init_alarm = $alarm['init_rept'];
180                                                $end_alarm = $alarm['end_rept'];
181
182                                                if($end_alarm != 0)
183                                                {
184                                                        while($init_alarm <= $end_alarm)
185                                                        {
186                                                                $id = 'cal:'.(int)$cal_id.':'.$n;
187                                                                ++$n;
188                                                               
189                                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
190
191                                                                unset($alarm['repeat']);
192                                                                unset($alarm['init_rept']);
193                                                                unset($alarm['end_rept']);
194                                                                unset($alarm['rpt_wdays']);
195
196                                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
197                                                                {
198                                                                        return False;
199                                                                }
200
201                                                                $alarm['time'] += 86400;
202                                                                $init_alarm += 86400;
203                                                        }
204                                                }
205                                        }
206
207                                }elseif($alarm['repeat'] == 2) { // repeticao do tipo "Semanalmente";
208
209                                        $n = 0;
210
211                                        $init_alarm = $data_atual = $alarm['init_rept'];
212                                        $end_alarm = $alarm['end_rept'];
213
214                                        $rpt_alarm_wdays = $alarm['rpt_wdays'];
215
216                                        $divisor = 64;
217                                        $quociente = 0;
218                                        $resto = 0;
219
220                                        $dia_semana = date("w",$init_alarm);
221
222                                        switch($dia_semana)
223                                        {
224                                                case 0:
225                                                        $dia = array(
226                                                                        0 => 'domingo',
227                                                                        1 => 'segunda',
228                                                                        2 => 'terca',
229                                                                        3 => 'quarta',
230                                                                        4 => 'quinta',
231                                                                        5 => 'sexta',
232                                                                        6 => 'sabado'
233                                                        );
234                                                        break;
235                                                case 1:
236                                                        $dia = array(
237                                                                        0 => 'segunda',
238                                                                        1 => 'terca',
239                                                                        2 => 'quarta',
240                                                                        3 => 'quinta',
241                                                                        4 => 'sexta',
242                                                                        5 => 'sabado',
243                                                                        6 => 'domingo'
244                                                        );
245                                                        break;
246                                                case 2:
247                                                        $dia = array(
248                                                                        0 => 'terca',
249                                                                        1 => 'quarta',
250                                                                        2 => 'quinta',
251                                                                        3 => 'sexta',
252                                                                        4 => 'sabado',
253                                                                        5 => 'domingo',
254                                                                        6 => 'segunda'
255                                                        );
256                                                        break;
257                                                case 3:
258                                                        $dia = array(
259                                                                        0 => 'quarta',
260                                                                        1 => 'quinta',
261                                                                        2 => 'sexta',
262                                                                        3 => 'sabado',
263                                                                        4 => 'domingo',
264                                                                        5 => 'segunda',
265                                                                        6 => 'terca'
266                                                        );
267                                                        break;
268                                                case 4:
269                                                        $dia = array(
270                                                                        0 => 'quinta',
271                                                                        1 => 'sexta',
272                                                                        2 => 'sabado',
273                                                                        3 => 'domingo',
274                                                                        4 => 'segunda',
275                                                                        5 => 'terca',
276                                                                        6 => 'quarta'
277                                                        );
278                                                        break;
279                                                case 5:
280                                                        $dia = array(
281                                                                        0 => 'sexta',
282                                                                        1 => 'sabado',
283                                                                        2 => 'domingo',
284                                                                        3 => 'segunda',
285                                                                        4 => 'terca',
286                                                                        5 => 'quarta',
287                                                                        6 => 'quinta'
288                                                        );
289                                                        break;
290                                                case 6:
291                                                        $dia = array(
292                                                                        0 => 'sabado',
293                                                                        1 => 'domingo',
294                                                                        2 => 'segunda',
295                                                                        3 => 'terca',
296                                                                        4 => 'quarta',
297                                                                        5 => 'quinta',
298                                                                        6 => 'sexta'
299                                                        );
300                                                        break;
301                                        }
302
303
304                                        $dias_semana = array(
305                                                                64 => 'sabado',
306                                                                32 => 'sexta',
307                                                                16 => 'quinta',
308                                                                8 => 'quarta',
309                                                                4 => 'terca',
310                                                                2 => 'segunda',
311                                                                1 => 'domingo'
312                                                        );
313
314                                        $result = array();
315                                        do
316                                        {
317
318                                                $resto = ($rpt_alarm_wdays % $divisor);
319                                                $quociente = floor($rpt_alarm_wdays / $divisor);
320
321                                                if($quociente == 1)
322                                                {
323                                                        $result[] = $dias_semana[$divisor];
324
325                                                        $divisor = $divisor / 2;
326                                                        $rpt_alarm_wdays = $resto;
327
328                                                }else {
329
330                                                        while($rpt_alarm_wdays < $divisor)
331                                                        {
332                                                                $divisor = $divisor / 2;
333                                                        }
334
335                                                        $resto = ($rpt_alarm_wdays % $divisor);
336                                                        $quociente = floor($rpt_alarm_wdays / $divisor);
337
338                                                        if($quociente == 1)
339                                                        {
340
341                                                                $result[] = $dias_semana[$divisor];
342
343                                                                $divisor = $divisor / 2;
344                                                                $rpt_alarm_wdays = $resto;
345                                                        }
346                                                }
347
348                                        }
349                                        while($resto != 0);
350
351                                        krsort($result);
352
353                                        $week_num = 0;
354                                        $y = 0;
355
356                                        while(@isset($alarms[$id]));
357                                        {
358
359                                                if($end_alarm != 0)
360                                                {
361
362                                                        while($data_atual <= $end_alarm)
363                                                        {
364
365                                                                foreach($dia as $index => $value)
366                                                                {
367                                                                        if(in_array($value,$result))
368                                                                        {
369
370                                                                                $nova_data = $init_alarm + (86400 * ($index + (7 * $y)));
371
372                                                                                if($nova_data == $init_alarm){
373
374                                                                                        continue;
375                                                                                }
376
377                                                                                $id = 'cal:'.(int)$cal_id.':'.$n;
378                                                                                ++$n;
379
380                                                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
381
382                                                                                unset($alarm['repeat']);
383                                                                                unset($alarm['init_rept']);
384                                                                                unset($alarm['end_rept']);
385                                                                                unset($alarm['rpt_wdays']);
386                                                                               
387                                                                                $data_atual = $nova_data;
388
389                                                                                if($data_atual > $end_alarm){
390                                                                                        if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
391                                                                                        {
392                                                                                                return False;
393                                                                                        }
394                                                                                        break;
395                                                                                }
396
397                                                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
398                                                                                {
399                                                                                        return False;
400                                                                                }
401                                                                                        $alarm['time'] = $nova_data - $alarm['offset'] - $GLOBALS['phpgw']->datetime->tz_offset;
402                                                                        }
403                                                                }
404                                                                ++$y;
405                                                        }
406                                                }
407                                        }
408
409                                }elseif($alarm['repeat'] == 3) { // repeticao do tipo "Mensalmente (por data)";
410
411                                        $n = 0;
412
413                                        $init_alarm = $alarm['init_rept'];
414                                        $end_alarm = $alarm['end_rept'];
415                                       
416                                        while(@isset($alarms[$id]));
417                                        {
418
419                                                if($end_alarm != 0)
420                                                {
421                                                        while($init_alarm <= $end_alarm)
422                                                        {
423
424                                                                $next_month = date("n",$init_alarm) + 1;
425                                                                $next_alarm = mktime(date("G",$alarm['time']),date("i",$alarm['time']),date("s",$alarm['time']),$next_month,date("j",$alarm['time']),date("Y",$alarm['time']));
426
427                                                                $id = 'cal:'.(int)$cal_id.':'.$n;
428                                                                ++$n;
429
430                                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
431
432                                                                unset($alarm['repeat']);
433                                                                unset($alarm['init_rept']);
434                                                                unset($alarm['end_rept']);
435                                                                unset($alarm['rpt_wdays']);
436
437                                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
438                                                                {
439                                                                        return False;
440                                                                }
441
442                                                                $alarm['time'] = $next_alarm;
443                                                                $init_alarm = $next_alarm;
444
445                                                        }
446                                                }
447                                        }
448
449                                }elseif($alarm['repeat'] == 5) { // repeticao do tipo "Anualmente";
450
451                                        $n = 0;
452
453                                        $init_alarm = $alarm['init_rept'];
454                                        $end_alarm = $alarm['end_rept'];
455                                       
456                                        while(@isset($alarms[$id]));
457                                        {
458
459
460                                                if($end_alarm != 0)
461                                                {
462                                                        while($init_alarm < $end_alarm)
463                                                        {
464
465                                                                $next_year = date("Y",$init_alarm) + 1;
466                                                                $next_alarm = mktime(date("G",$alarm['time']),date("i",$alarm['time']),date("s",$alarm['time']),date("n",$alarm['time']),date("j",$alarm['time']),$next_year);
467
468                                                                $id = 'cal:'.(int)$cal_id.':'.$n;
469                                                                ++$n;
470
471                                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
472
473                                                                unset($alarm['repeat']);
474                                                                unset($alarm['init_rept']);
475                                                                unset($alarm['end_rept']);
476                                                                unset($alarm['rpt_wdays']);
477
478                                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
479                                                                {
480                                                                        return False;
481                                                                }
482
483                                                                $alarm['time'] = $next_alarm;
484                                                                $init_alarm = $next_alarm;
485                                                        }
486                                                }
487                                        }
488
489                                }else {
490                                        $alarm['time'] -= $GLOBALS['phpgw']->datetime->tz_offset;       // time should be stored in server timezone
491                                        $n = count($alarms);
492                                        while(@isset($alarms[$id]));
493                                        {
494
495                                                $id = 'cal:'.(int)$cal_id.':'.$n;
496
497                                                unset($alarm['repeat']);
498                                                unset($alarm['init_rept']);
499                                                unset($alarm['end_rept']);
500                                                unset($alarm['rpt_wdays']);
501
502                                                $alarm['cal_id'] = $cal_id;             // we need the back-reference
503                                                if (!$this->async->set_timer($alarm['time'],$id,'calendar.bocalendar.send_alarm',$alarm))
504                                                {
505                                                        return False;
506                                                }
507
508                                                ++$n;
509                                        }
510                                }
511
512                        }
513                        else
514                        {
515                                $this->async->cancel_timer($id);
516                        }
517                        $alarm['time'] -= $GLOBALS['phpgw']->datetime->tz_offset;       // time should be stored in server timezone
518                        return $id;
519                }
520
521                /*!
522                @function delete_alarms($cal_id)
523                @abstract delete all alarms of a calendar-entry
524                @returns the number of alarms deleted
525                */
526                function delete_alarms($cal_id)
527                {
528                        $alarms = $this->read_alarms($cal_id);
529
530                        foreach($alarms as $id => $alarm)
531                        {
532                                $this->async->cancel_timer($id);
533                        }
534                        return count($alarms);
535                }
536
537                /*!
538                @function delete_alarm($id)
539                @abstract delete one alarms identified by its id
540                @returns the number of alarms deleted
541                */
542                function delete_alarm($id)
543                {
544                        return $this->async->cancel_timer($id);
545                }
546
547                function fetch_event($event_id,$options='')
548                {
549                        if(!isset($this->stream))
550                        {
551                                return False;
552                        }
553
554                        $event_id = (int)$event_id;
555
556                        $this->stream->lock(array('phpgw_cal','phpgw_cal_user','phpgw_cal_repeats','phpgw_cal_extra'/* OLD-ALARM,'phpgw_cal_alarm'*/));
557
558                        $this->stream->query('SELECT * FROM phpgw_cal WHERE cal_id='.$event_id,__LINE__,__FILE__);
559
560                        if($this->stream->num_rows() > 0)
561                        {
562                                $this->event_init();
563
564                                $this->stream->next_record();
565                                // Load the calendar event data from the db into $event structure
566                                // Use http://www.php.net/manual/en/function.mcal-fetch-event.php as the reference
567                                $this->add_attribute('owner',(int)$this->stream->f('owner'));
568                                $this->add_attribute('id',(int)$this->stream->f('cal_id'));
569                                $this->add_attribute('type',$this->stream->f('cal_type'));
570                                $this->set_class((int)$this->stream->f('is_public'));
571                                $this->set_category($this->stream->f('category'));
572                                $this->set_title(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('title'))));
573                                $this->set_description(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('description'))));
574                                $this->set_ex_participants(stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('ex_participants'))));
575                                $this->add_attribute('uid',$GLOBALS['phpgw']->strip_html($this->stream->f('uid')));
576                                $this->add_attribute('location',stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('location'))));
577                                $this->add_attribute('organizer',stripslashes($GLOBALS['phpgw']->strip_html($this->stream->f('organizer'))));
578                                $this->add_attribute('reference',(int)$this->stream->f('reference'));
579
580                                // This is the preferred method once everything is normalized...
581                                //$this->event->alarm = (int)$this->stream->f('alarm');
582                                // But until then, do it this way...
583                                //Legacy Support (New)
584
585                                $datetime = $GLOBALS['phpgw']->datetime->localdates($this->stream->f('datetime'));
586                                $this->set_start($datetime['year'],$datetime['month'],$datetime['day'],$datetime['hour'],$datetime['minute'],$datetime['second']);
587
588                                $datetime = $GLOBALS['phpgw']->datetime->localdates($this->stream->f('mdatetime'));
589                                $this->set_date('modtime',$datetime['year'],$datetime['month'],$datetime['day'],$datetime['hour'],$datetime['minute'],$datetime['second']);
590
591                                $datetime = $GLOBALS['phpgw']->datetime->localdates($this->stream->f('edatetime'));
592                                $this->set_end($datetime['year'],$datetime['month'],$datetime['day'],$datetime['hour'],$datetime['minute'],$datetime['second']);
593
594                        //Legacy Support
595                                $this->add_attribute('priority',(int)$this->stream->f('priority'));
596                                if($this->stream->f('cal_group') || $this->stream->f('groups') != 'NULL')
597                                {
598                                        $groups = explode(',',$this->stream->f('groups'));
599                    $groups_count = count($groups) - 1;
600                                        for($j=1;$j<$groups_count;++$j)
601                                        {
602                                                $this->add_attribute('groups',$groups[$j],$j-1);
603                                        }
604                                }
605
606                                $this->stream->query('SELECT * FROM phpgw_cal_repeats WHERE cal_id='.$event_id,__LINE__,__FILE__);
607                                if($this->stream->num_rows())
608                                {
609                                        $this->stream->next_record();
610
611                                        $this->add_attribute('recur_type',(int)$this->stream->f('recur_type'));
612                                        $this->add_attribute('recur_interval',(int)$this->stream->f('recur_interval'));
613                                        $enddate = $this->stream->f('recur_enddate');
614                                        if($enddate != 0 && $enddate != Null)
615                                        {
616                                                $datetime = $GLOBALS['phpgw']->datetime->localdates($enddate);
617                                                $this->add_attribute('recur_enddate',$datetime['year'],'year');
618                                                $this->add_attribute('recur_enddate',$datetime['month'],'month');
619                                                $this->add_attribute('recur_enddate',$datetime['day'],'mday');
620                                                $this->add_attribute('recur_enddate',$datetime['hour'],'hour');
621                                                $this->add_attribute('recur_enddate',$datetime['minute'],'min');
622                                                $this->add_attribute('recur_enddate',$datetime['second'],'sec');
623                                        }
624                                        else
625                                        {
626                                                $this->add_attribute('recur_enddate',0,'year');
627                                                $this->add_attribute('recur_enddate',0,'month');
628                                                $this->add_attribute('recur_enddate',0,'mday');
629                                                $this->add_attribute('recur_enddate',0,'hour');
630                                                $this->add_attribute('recur_enddate',0,'min');
631                                                $this->add_attribute('recur_enddate',0,'sec');
632                                        }
633                                        $this->add_attribute('recur_enddate',0,'alarm');
634                                        if($this->debug)
635                                        {
636                                                echo 'Event ID#'.$this->event['id'].' : Enddate = '.$enddate."<br>\n";
637                                        }
638                                        $this->add_attribute('recur_data',$this->stream->f('recur_data'));
639
640                                        $exception_list = $this->stream->f('recur_exception');
641                                        $exceptions = Array();
642                                        if(strpos(' '.$exception_list,','))
643                                        {
644                                                $exceptions = explode(',',$exception_list);
645                                        }
646                                        elseif($exception_list != '')
647                                        {
648                                                $exceptions[]= $exception_list;
649                                        }
650                                        $this->add_attribute('recur_exception',$exceptions);
651                                }
652
653                        //Legacy Support
654                                $this->stream->query('SELECT * FROM phpgw_cal_user WHERE cal_id='.$event_id,__LINE__,__FILE__);
655                                if($this->stream->num_rows())
656                                {
657                                        while($this->stream->next_record())
658                                        {
659                                                if((int)$this->stream->f('cal_login') == (int)$this->user)
660                                                {
661                                                        $this->add_attribute('users_status',$this->stream->f('cal_status'));
662                                                }
663                                                $this->add_attribute('participants',$this->stream->f('cal_status'),(int)$this->stream->f('cal_login'));
664                                        }
665                                }
666
667                        // Custom fields
668                                $this->stream->query('SELECT * FROM phpgw_cal_extra WHERE cal_id='.$event_id,__LINE__,__FILE__);
669                                if($this->stream->num_rows())
670                                {
671                                        while($this->stream->next_record())
672                                        {
673                                                $this->add_attribute('#'.$this->stream->f('cal_extra_name'),$this->stream->f('cal_extra_value'));
674                                        }
675                                }
676
677        /* OLD-ALARM
678                                if($this->event['reference'])
679                                {
680                                        // What is event['reference']???
681                                        $alarm_cal_id = $event_id.','.$this->event['reference'];
682                                }
683                                else
684                                {
685                                        $alarm_cal_id = $event_id;
686                                }
687
688                                //echo '<!-- cal_id='.$alarm_cal_id.' -->'."\n";
689                                //$this->stream->query('SELECT * FROM phpgw_cal_alarm WHERE cal_id in ('.$alarm_cal_id.') AND cal_owner='.$this->user,__LINE__,__FILE__);
690                                $this->stream->query('SELECT * FROM phpgw_cal_alarm WHERE cal_id='.$event_id.' AND cal_owner='.$this->user,__LINE__,__FILE__);
691                                if($this->stream->num_rows())
692                                {
693                                        while($this->stream->next_record())
694                                        {
695                                                $this->event['alarm'][] = Array(
696                                                        'id'            => (int)$this->stream->f('alarm_id'),
697                                                        'time'  => (int)$this->stream->f('cal_time'),
698                                                        'text'  => $this->stream->f('cal_text'),
699                                                        'enabled'       => (int)$this->stream->f('alarm_enabled')
700                                                );
701                                        }
702                                }
703        */
704                        }
705                        else
706                        {
707                                $this->event = False;
708                        }
709
710                        $this->stream->unlock();
711
712                        if ($this->event)
713                        {
714                                $this->event['alarm'] = $this->read_alarms($event_id);
715
716                                if($this->event['reference'])
717                                {
718                                        $this->event['alarm'] += $this->read_alarms($event_id);
719                                }
720                        }
721                        return $this->event;
722                }
723
724                function list_events($startYear,$startMonth,$startDay,$endYear=0,$endMonth=0,$endDay=0,$extra='',$tz_offset=0,$owner_id=0)
725                {
726                        if(!isset($this->stream))
727                        {
728                                return False;
729                        }
730
731                        $datetime = mktime(0,0,0,$startMonth,$startDay,$startYear) - $tz_offset;
732
733                        $user_where = ' AND (phpgw_cal_user.cal_login in (';
734                        if(is_array($owner_id) && count($owner_id))
735                        {
736                                $user_where .= implode(',',$owner_id);
737                        }
738                        else
739                        {
740                                $user_where .= $this->user . ') OR (phpgw_cal.owner=' . $this->user;
741                        }
742                        $member_groups = $GLOBALS['phpgw']->accounts->membership($this->user);
743                        @reset($member_groups);
744                        while($member_groups != False && list($key,$group_info) = each($member_groups))
745                        {
746                                $member[] = $group_info['account_id'];
747                        }
748                        @reset($member);
749        //              $user_where .= ','.implode(',',$member);
750                        $user_where .= ')) ';
751
752                        if($this->debug)
753                        {
754                                echo '<!-- '.$user_where.' -->'."\n";
755                        }
756
757                        $startDate = 'AND ( ( (phpgw_cal.datetime >= '.$datetime.') ';
758
759                        $enddate = '';
760                        if($endYear != 0 && $endMonth != 0 && $endDay != 0)
761                        {
762                                $edatetime = mktime(23,59,59,(int)$endMonth,(int)$endDay,(int)$endYear) - $tz_offset;
763                                $endDate .= 'AND (phpgw_cal.edatetime <= '.$edatetime.') ) '
764                                        . 'OR ( (phpgw_cal.datetime <= '.$datetime.') '
765                                        . 'AND (phpgw_cal.edatetime >= '.$edatetime.') ) '
766                                        . 'OR ( (phpgw_cal.datetime >= '.$datetime.') '
767                                        . 'AND (phpgw_cal.datetime <= '.$edatetime.') '
768                                        . 'AND (phpgw_cal.edatetime >= '.$edatetime.') ) '
769                                        . 'OR ( (phpgw_cal.datetime <= '.$datetime.') '
770                                        . 'AND (phpgw_cal.edatetime >= '.$datetime.') '
771                                        . 'AND (phpgw_cal.edatetime <= '.$edatetime.') ';
772                        }
773                        $endDate .= ') ) ';
774
775                        $order_by = 'ORDER BY phpgw_cal.datetime ASC, phpgw_cal.edatetime ASC, phpgw_cal.priority ASC';
776                        if($this->debug)
777                        {
778                                echo "SQL : ".$user_where.$startDate.$endDate.$extra."<br>\n";
779                        }
780                        return $this->get_event_ids(False,$user_where.$startDate.$endDate.$extra.$order_by);
781                }
782
783                function append_event()
784                {
785                        $this->save_event($this->event);
786                        $this->send_update(MSG_ADDED,$this->event->participants,'',$this->event);
787                        return $this->event['id'];
788                }
789
790                function store_event()
791                {
792                        return $this->save_event($this->event);
793                }
794
795                function delete_event($event_id)
796                {
797                        $this->deleted_events[] = $event_id;
798                }
799
800                function snooze($event_id)
801                {
802                //Turn off an alarm for an event
803                //Returns true.
804                }
805
806                function list_alarms($begin_year='',$begin_month='',$begin_day='',$end_year='',$end_month='',$end_day='')
807                {
808                //Return a list of events that has an alarm triggered at the given datetime
809                //Returns an array of event ID's
810                }
811
812                // The function definition doesn't look correct...
813                // Need more information for this function
814                function next_recurrence($weekstart,$next)
815                {
816        //              return next_recurrence (int stream, int weekstart, array next);
817                }
818
819                function expunge()
820                {
821                        if(count($this->deleted_events) <= 0)
822                        {
823                                return 1;
824                        }
825                        $this_event = $this->event;
826                        $locks = Array(
827                                'phpgw_cal',
828                                'phpgw_cal_user',
829                                'phpgw_cal_repeats',
830                                'phpgw_cal_extra'
831        // OLD-ALARM                    'phpgw_cal_alarm'
832                        );
833                        $this->stream->lock($locks);
834                        foreach($this->deleted_events as $cal_id)
835                        {
836                                foreach ($locks as $table)
837                                {
838                                        $this->stream->query('DELETE FROM '.$table.' WHERE cal_id='.$cal_id,__LINE__,__FILE__);
839                                }
840                        }
841                        $this->stream->unlock();
842
843                        foreach($this->deleted_events as $cal_id)
844                        {
845                                $this->delete_alarms($cal_id);
846                        }
847                        $this->deleted_events = array();
848
849                        $this->event = $this_event;
850                        return 1;
851                }
852
853                /***************** Local functions for SQL based Calendar *****************/
854
855                function get_event_ids($search_repeats=False,$extra='',$search_extra=False)
856                {
857                        $from = $where = ' ';
858                        if($search_repeats)
859                        {
860                                $from  = ', phpgw_cal_repeats ';
861                                $where = 'AND (phpgw_cal_repeats.cal_id = phpgw_cal.cal_id) ';
862                        }
863                        if($search_extra)
864                        {
865                                $from  .= 'LEFT JOIN phpgw_cal_extra ON phpgw_cal_extra.cal_id = phpgw_cal.cal_id ';
866                        }
867
868                        $sql = 'SELECT DISTINCT phpgw_cal.cal_id,'
869                                        . 'phpgw_cal.datetime,phpgw_cal.edatetime,'
870                                        . 'phpgw_cal.priority '
871                                        . 'FROM phpgw_cal_user, phpgw_cal'
872                                        . $from
873                                        . 'WHERE (phpgw_cal_user.cal_id = phpgw_cal.cal_id) '
874                                        . $where . $extra;
875
876                        if($this->debug)
877                        {
878                                echo "FULL SQL : ".$sql."<br>\n";
879                        }
880
881                        $this->stream->query($sql,__LINE__,__FILE__);
882
883                        $retval = Array();
884                        if($this->stream->num_rows() == 0)
885                        {
886                                if($this->debug)
887                                {
888                                        echo "No records found!<br>\n";
889                                }
890                                return $retval;
891                        }
892
893                        while($this->stream->next_record())
894                        {
895                                $retval[] = (int)$this->stream->f('cal_id');
896                        }
897                        if($this->debug)
898                        {
899                                echo "Records found!<br>\n";
900                        }
901                        return $retval;
902                }
903
904                function save_event(&$event,$sendMail = true, $importAccount = false)
905                {
906
907                        $GLOBALS['calendar']->bocalendar = CreateObject('calendar.bocalendar');
908
909                        $locks = Array(
910                                'phpgw_cal',
911                                'phpgw_cal_user',
912                                'phpgw_cal_repeats',
913                                'phpgw_cal_extra'
914        // OLD-ALARM                    'phpgw_cal_alarm'
915                        );
916                        $this->stream->lock($locks);
917                        if($event['id'] == 0)
918                        {
919                                if(!$event['uid'])
920                                {
921                                        if ($GLOBALS['phpgw_info']['server']['hostname'] != '')
922                                        {
923                                                $id_suffix = $GLOBALS['phpgw_info']['server']['hostname'];
924                                        }
925                                        else
926                                        {
927                                                $id_suffix = $GLOBALS['phpgw']->common->randomstring(3).'local';
928                                        }
929                                        $parts = Array(
930                                                0 => 'title',
931                                                1 => 'description',
932                                                2 => 'ex_participants'
933                                        );
934                                        @reset($parts);
935                                        while(list($key,$field) = each($parts))
936                                        {
937                                                $part[$key] = substr($GLOBALS['phpgw']->crypto->encrypt($event[$field]),0,20);
938                                                if(!$GLOBALS['phpgw']->crypto->enabled)
939                                                {
940                                                        $part[$key] = bin2hex(unserialize($part[$key]));
941                                                }
942                                        }
943                                        $event['uid'] = $part[0].'-'.$part[1].'@'.$id_suffix;
944                                }
945                                $returned_id = $this->stream->query('INSERT INTO phpgw_cal(uid,title,owner,priority,is_public,category) '
946                                        . "values('".$event['uid']."','".$this->stream->db_addslashes($event['title'])
947                                        . "',".(int)$event['owner'].','.(int)$event['priority'].','.(int)$event['public'].",'"
948                                        . $event['category']."') RETURNING cal_id",__LINE__,__FILE__);
949
950                                // get_last_insert_id não funciona direito com Postgres 9
951                                $event['id'] =  $returned_id->fields['cal_id']; //$this->stream->get_last_insert_id('phpgw_cal','cal_id');
952                                $last_status = true;
953                        }
954
955                        $date = $this->maketime($event['start']) - $GLOBALS['phpgw']->datetime->tz_offset;
956                        $enddate = $this->maketime($event['end']) - $GLOBALS['phpgw']->datetime->tz_offset;
957                        $today = time() - $GLOBALS['phpgw']->datetime->tz_offset;
958
959
960                                if ($event['type'] == 'hourAppointment')
961                                        $type = 'H';
962                                else if($event['type'] == 'privateHiddenFields'){
963                                        $type = 'P';
964                                }else
965                                        $type = 'E';
966
967
968                        $sql = 'UPDATE phpgw_cal SET '
969                                        . 'owner='.(int)$event['owner'].', '
970                                        . 'datetime='.(int)$date.', '
971                                        . 'mdatetime='.(int)$today.', '
972                                        . 'edatetime='.(int)$enddate.', '
973                                        . 'priority='.(int)$event['priority'].', '
974                                        . "category='".$this->stream->db_addslashes($event['category'])."', "
975                                        . "cal_type='".$this->stream->db_addslashes($type)."', "
976                                        . 'is_public='.(int)$event['public'].', '
977                                        . "title='".$this->stream->db_addslashes($event['title'])."', "
978                                        . "description='".$this->stream->db_addslashes($event['description'])."', "
979                                        . "ex_participants='".$this->stream->db_addslashes($event['ex_participants'])."', "
980                                        . "organizer='".$this->stream->db_addslashes($event['organizer'])."', "
981                                        . "location='".$this->stream->db_addslashes($event['location'])."', "
982                                        . ($event['groups']?"groups='".(count($event['groups'])>1?implode(',',$event['groups']):','.$event['groups'][0].',')."', ":'')
983                                        . 'reference='.(int)$event['reference'].' '
984                                        . ',last_status = '.($last_status ? "'N'" : "'U'").',last_update = '.time()."000". ' '
985                                        . 'WHERE cal_id='.(int)$event['id'];
986
987                        $this->stream->query($sql,__LINE__,__FILE__);
988
989                        $this->stream->query('DELETE FROM phpgw_cal_user WHERE cal_id='.(int)$event['id'],__LINE__,__FILE__);
990
991                        @reset($event['participants']);
992                        while (list($key,$value) = @each($event['participants']))
993                        {
994                                if((int)$key == $event['owner'])
995                                {
996                                        $value = 'A';
997                                }
998                                $this->stream->query('INSERT INTO phpgw_cal_user(cal_id,cal_login,cal_status) '
999                                        . 'VALUES('.(int)$event['id'].','.(int)$key.",'".$this->stream->db_addslashes($value)."')",__LINE__,__FILE__);
1000                        }
1001
1002                        if($event['recur_type'] != MCAL_RECUR_NONE)
1003                        {
1004                                if($event['recur_enddate']['month'] != 0 && $event['recur_enddate']['mday'] != 0 && $event['recur_enddate']['year'] != 0)
1005                                {
1006                                        $end = $this->maketime($event['recur_enddate']) - $GLOBALS['phpgw']->datetime->tz_offset;
1007                                }
1008                                else
1009                                {
1010                                        $end = 0;
1011                                }
1012
1013                                $this->stream->query('SELECT count(cal_id) FROM phpgw_cal_repeats WHERE cal_id='.(int)$event['id'],__LINE__,__FILE__);
1014                                $this->stream->next_record();
1015                                $num_rows = $this->stream->f(0);
1016                                if($num_rows == 0)
1017                                {
1018                                        $this->stream->query('INSERT INTO phpgw_cal_repeats(cal_id,recur_type,recur_enddate,recur_data,recur_interval) '
1019                                                .'VALUES('.(int)$event['id'].','.$event['recur_type'].','.(int)$end.','.$event['recur_data'].','.$event['recur_interval'].')',__LINE__,__FILE__);
1020                                }
1021                                else
1022                                {
1023                                        $this->stream->query('UPDATE phpgw_cal_repeats '
1024                                                . 'SET recur_type='.$event['recur_type'].', '
1025                                                . 'recur_enddate='.(int)$end.', '
1026                                                . 'recur_data='.$event['recur_data'].', '
1027                                                . 'recur_interval='.$event['recur_interval'].', '
1028                                                . "recur_exception='".(count($event['recur_exception'])>1?implode(',',$event['recur_exception']):(count($event['recur_exception'])==1?$event['recur_exception'][0]:''))."' "
1029                                                . 'WHERE cal_id='.$event['id'],__LINE__,__FILE__);
1030                                }
1031
1032                        }
1033                        else
1034                        {
1035                                $this->stream->query('DELETE FROM phpgw_cal_repeats WHERE cal_id='.$event['id'],__LINE__,__FILE__);
1036                        }
1037                        // Custom fields
1038                        $this->stream->query('DELETE FROM phpgw_cal_extra WHERE cal_id='.$event['id'],__LINE__,__FILE__);
1039
1040                        foreach($event as $name => $value)
1041                        {
1042                                if ($name[0] == '#' && strlen($value))
1043                                {
1044                                        $this->stream->query('INSERT INTO phpgw_cal_extra (cal_id,cal_extra_name,cal_extra_value) '
1045                                        . 'VALUES('.$event['id'].",'".addslashes(substr($name,1))."','".addslashes($value)."')",__LINE__,__FILE__);
1046                                }
1047                        }
1048        /*
1049                        $alarmcount = count($event['alarm']);
1050                        if ($alarmcount > 1)
1051                        {
1052                                // this should never happen, $event['alarm'] should only be set
1053                                // if creating a new event and uicalendar only sets up 1 alarm
1054                                // the user must use "Alarm Management" to create/establish multiple
1055                                // alarms or to edit/change an alarm
1056                                echo '<!-- how did this happen, too many alarms -->'."\n";
1057                                $this->stream->unlock();
1058                                return True;
1059                        }
1060
1061                        if ($alarmcount == 1)
1062                        {
1063
1064                                list($key,$alarm) = @each($event['alarm']);
1065
1066                                $this->stream->query('INSERT INTO phpgw_cal_alarm(cal_id,cal_owner,cal_time,cal_text,alarm_enabled) VALUES('.$event['id'].','.$event['owner'].','.$alarm['time'].",'".$alarm['text']."',".$alarm['enabled'].')',__LINE__,__FILE__);
1067                                $this->stream->query('SELECT LAST_INSERT_ID()');
1068                                $this->stream->next_record();
1069                                $alarm['id'] = $this->stream->f(0);
1070                        }
1071        */
1072                        print_debug('Event Saved: ID #',$event['id']);
1073
1074                        $this->stream->unlock();
1075
1076                        if (is_array($event['alarm']))
1077                        {
1078                                foreach ($event['alarm'] as $alarm)     // this are all new alarms
1079                                {
1080                                        $this->save_alarm($event['id'],$alarm);
1081                                }
1082                        }
1083                        $GLOBALS['phpgw_info']['cal_new_event_id'] = $event['id'];
1084                        $this->event = $event;
1085
1086                        if($sendMail)
1087                        {
1088                            if($importAccount)
1089                                $this->sendEmailEvendAccepted($event,$importAccount);
1090                            else
1091                                $this->sendEmailEvendAccepted($event);
1092                        }
1093       
1094                        return True;
1095                }
1096
1097                function sendEmailEvendAccepted($event,$importAccount = false)
1098                {
1099
1100                    if(!$importAccount)
1101                        $importAccount['mail'] = $GLOBALS['phpgw_info']['user']['email'];
1102
1103                    //verifica se eh um evento externo se sim envia o vcard de aceitação em anexo
1104                    if($event['owner'] == '-2')
1105                    {
1106                        $mailService = ServiceLocator::getService('mail');
1107
1108                        $tmpbody.= "<b>".lang("Event Accepted")."</b> ";
1109                        $tmpbody.= "<br><br>".lang("name").": ".$event['title']."<br>";
1110                        $tmpbody.= "<br>".lang("description").": ".$event['description']."<br>";
1111
1112                        $ev[0] = $event;
1113
1114                        $tmpattach=  $GLOBALS['calendar']->bocalendar->create_vcard($ev,'REPLY',true,$importAccount);
1115                       
1116                        $mailService->addStringAttachment($tmpattach, 'suggestion.ics', 'application/ics');
1117                        $mailService->addStringAttachment($tmpattach, 'vcalendar.ics', 'utf-8', 'text/calendar; charset=utf-8; method=REPLY;', '7bit', '');
1118                 
1119                        if(strchr($event['organizer'],'@') && strchr($event['organizer'],'<') && strchr($event['organizer'],'>'))
1120                        {
1121                            $mail = substr($event['organizer'], strpos($event['organizer'],'<'), strpos($event['organizer'],'>'));
1122                            $mail = str_replace('<','', str_replace('>','',$mail));
1123                        }
1124
1125                        if($mail)
1126                            $mailService->sendMail($mail,$importAccount['mail'],$event['title'],$tmpbody);
1127
1128                    }
1129                    else
1130                        $GLOBALS['calendar']->bocalendar->send_update(MSG_ACCEPTED, $event['participants'],$event);
1131
1132                    return;
1133                }
1134
1135                function get_alarm($cal_id)
1136                {
1137        /* OLD-ALARM
1138                        $this->stream->query('SELECT cal_time, cal_text FROM phpgw_cal_alarm WHERE cal_id='.$id.' AND cal_owner='.$this->user,__LINE__,__FILE__);
1139                        if($this->stream->num_rows())
1140                        {
1141                                while($this->stream->next_record())
1142                                {
1143                                        $alarm[$this->stream->f('cal_time')] = $this->stream->f('cal_text');
1144                                }
1145                                @reset($alarm);
1146                                return $alarm;
1147                        }
1148                        else
1149                        {
1150                                return False;
1151                        }
1152        */
1153                        $alarms = $this->read_alarms($cal_id);
1154                        $ret = False;
1155
1156                        foreach($alarms as $alarm)
1157                        {
1158                                if ($alarm['owner'] == $this->user || !$alarm['owner'])
1159                                {
1160                                        $ret[$alarm['time']] = $alarm['text'];
1161                                }
1162                        }
1163                        return $ret;
1164                }
1165
1166                function set_status($id,$owner,$status)
1167                {
1168                        $status_code_short = Array(
1169                                REJECTED =>     'R',
1170                                NO_RESPONSE     => 'U',
1171                                TENTATIVE       =>      'T',
1172                                ACCEPTED        =>      'A'
1173                        );
1174
1175                        $this->stream->query("UPDATE phpgw_cal_user SET cal_status='".$status_code_short[$status]."' WHERE cal_id=".$id." AND cal_login=".$owner,__LINE__,__FILE__);
1176        /* OLD-ALARM
1177                        if ($status == 'R')
1178                        {
1179                                $this->stream->query('UPDATE phpgw_cal_alarm set alarm_enabled=0 where cal_id='.$id.' and cal_owner='.$owner,__LINE__,__FILE__);
1180                        }
1181        */
1182                        return True;
1183                }
1184
1185        // End of ICal style support.......
1186
1187                function group_search($owner=0)
1188                {
1189                        $owner = ($owner==$GLOBALS['phpgw_info']['user']['account_id']?0:$owner);
1190                        $groups = substr($GLOBALS['phpgw']->common->sql_search('phpgw_cal.groups',(int)$owner),4);
1191                        if (!$groups)
1192                        {
1193                                return '';
1194                        }
1195                        else
1196                        {
1197                                return "(phpgw_cal.is_public=2 AND (". $groups .')) ';
1198                        }
1199                }
1200
1201                function splittime_($time)
1202                {
1203                        $temp = array('hour','minute','second','ampm');
1204                        $time = strrev($time);
1205                        $second = (int)strrev(substr($time,0,2));
1206                        $minute = (int)strrev(substr($time,2,2));
1207                        $hour   = (int)strrev(substr($time,4));
1208                        $temp['second'] = (int)$second;
1209                        $temp['minute'] = (int)$minute;
1210                        $temp['hour']   = (int)$hour;
1211                        $temp['ampm']   = '  ';
1212
1213                        return $temp;
1214                }
1215
1216                function date_to_epoch($d)
1217                {
1218                        return $this->localdates(mktime(0,0,0,(int)(substr($d,4,2)),(int)(substr($d,6,2)),(int)(substr($d,0,4))));
1219                }
1220
1221                function list_dirty_events($lastmod=-1,$repeats=false)
1222                {
1223                        if(!isset($this->stream))
1224                        {
1225                                return False;
1226                        }
1227                        $lastmod = (int)  $lastmod;
1228                        $repeats = (bool) $repeats;
1229
1230                        $user_where = " AND phpgw_cal_user.cal_login = $this->user";
1231
1232                        $member_groups = $GLOBALS['phpgw']->accounts->membership($this->user);
1233                        @reset($member_groups);
1234                        while($member_groups != False && list($key,$group_info) = each($member_groups))
1235                        {
1236                                $member[] = $group_info['account_id'];
1237                        }
1238                        @reset($member);
1239        //              $user_where .= ','.implode(',',$member);
1240                        //$user_where .= ')) ';
1241
1242                        if($this->debug)
1243                        {
1244                                echo '<!-- '.$user_where.' -->'."\n";
1245                        }
1246
1247                        if($lastmod > 0)
1248                        {
1249                                $wheremod = "AND mdatetime = $lastmod";
1250                        }
1251
1252                        $order_by = ' ORDER BY phpgw_cal.cal_id ASC';
1253                        if($this->debug)
1254                        {
1255                                echo "SQL : ".$user_where.$wheremod.$extra."<br>\n";
1256                        }
1257                        return $this->get_event_ids($repeats,$user_where.$wheremod.$extra.$order_by);
1258                }
1259
1260        /* OLD-ALARM
1261                function add_alarm($eventid,$alarm,$owner)
1262                {
1263                        $this->stream->query('INSERT INTO phpgw_cal_alarm(cal_id,cal_owner,cal_time,cal_text,alarm_enabled) VALUES('.$eventid.','.$owner.','.$alarm['time'].",'".$alarm['text']."',1)",__LINE__,__FILE__);
1264                        $this->stream->query('SELECT LAST_INSERT_ID()');
1265                        $this->stream->next_record();
1266                        return($this->stream->f(0));
1267                }
1268                function delete_alarm($alarmid)
1269                {
1270                        $this->stream->query('DELETE FROM phpgw_cal_alarm WHERE alarm_id='.$alarmid,__LINE__,__FILE__);
1271                }
1272        */
1273        }
Note: See TracBrowser for help on using the repository browser.