Ignore:
Timestamp:
04/30/12 15:42:36 (12 years ago)
Author:
acoutinho
Message:

Ticket #2672 - Erro ao importar alguns ics vindos de outros aplicativos

Location:
trunk/prototype/modules/calendar
Files:
6 edited

Legend:

Unmodified
Added
Removed
  • trunk/prototype/modules/calendar/interceptors/DBMapping.php

    r6011 r6066  
    11<?php 
     2 
    23//Definindo Constantes 
    3 require_once ROOTPATH.'/modules/calendar/constants.php'; 
    4  
    5 require_once ROOTPATH.'/modules/calendar/interceptors/Helpers.php'; 
    6  
    7 class DBMapping extends Helpers {        
    8             
    9     public function encodeCreateSchedulable( &$uri , &$params , &$criteria , $original ){ 
     4require_once ROOTPATH . '/modules/calendar/constants.php'; 
     5 
     6require_once ROOTPATH . '/modules/calendar/interceptors/Helpers.php'; 
     7 
     8class DBMapping extends Helpers { 
     9 
     10    public function encodeCreateSchedulable(&$uri, &$params, &$criteria, $original) { 
    1011        $params['type_id'] = EVENT_ID; 
    1112 
    12         if(!is_numeric($params['startTime']) ) 
    13           $params['startTime'] =   self::parseTimeDate( $params['startTime'], $params['timezone'] );  
    14                  
    15         if (!is_numeric($params['endTime'])){ 
    16           $params['endTime'] =    self::parseTimeDate( $params['endTime'], $params['timezone'] );  
    17  
    18           if($params['allDay']) 
    19             $params['endTime'] =  $params['endTime']  + 86400000; 
    20         } 
    21     //        if( !isset( $new['repeat'] )) 
    22     //            $new['range_end'] = '7287926400'; // 12/12/2200 
    23     //        else 
    24             $params['rangeEnd'] = $params['endTime']; 
    25             $params['rangeStart'] =  $params['startTime']; 
    26  
    27             /////////////////////////////////////////////////////////////////// 
    28  
    29             $params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] :time().'000';  
    30             $params['lastUpdate'] = (isset($params['lastUpdate'])) ? $params['lastUpdate'] :time().'000';  
    31             $params['type'] = EVENT_ID; 
    32             $params['uid'] = isset($params['uid']) ? $params['uid'] : $this->_makeUid(); 
    33     } 
    34  
    35     static function parseTimeDate($time, $timezone){ 
    36         return strtotime( $time . ' ' .$timezone).'000';          
    37    }     
    38                  
    39     public function encodeCreateAlarm( &$uri , &$params , &$criteria , $original ){ 
    40          
    41         if(!isset($params['schedulable']) || !isset($params['rangeStart']) || !isset($params['rangeEnd']) ) 
    42         { 
    43             $participant = Controller::read( array( 'concept' => 'participant' , 'id' => $params['participant'] ) , array('schedulable')  );  
    44             $schedulable = Controller::read( array( 'concept' => 'schedulable' , 'id' => $participant['schedulable'] ) , array('startTime' , 'endTime' )  ); 
    45  
    46             $params['schedulable'] = $participant['schedulable']; 
    47             $params['rangeStart'] = strtotime('- '.$params['time'].' '.self::codeAlarmUnit($params['unit']) , (int)($schedulable['startTime'] / 1000)).'000'; 
    48             $params['rangeEnd'] = $schedulable['endTime']; 
    49         } 
    50          
    51         $params['type'] = self::codeAlarmType($params['type']); 
    52          
    53         }   
    54          
    55         public function encodeCreateSuggestion( &$uri , &$params , &$criteria , $original ){                     
    56         $params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] :time().'000';           
    57     }    
    58          
    59         public function encodeUpdateAlarm( &$uri , &$params , &$criteria , $original ){ 
    60             if(isset($params['type'])) 
    61                 $params['type'] = self::codeAlarmType($params['type']); 
    62         } 
    63          
    64     public function encodeCreateAttachment( &$uri , &$params , &$criteria , $original ){ 
    65          
    66                 if(!isset($params['source'])) return false; 
    67                  
    68                 if(isset($_FILES[$params['source']])) 
    69                         if(isset($params['id'])) 
    70                                 $params =  array_merge($_FILES[$params['source']], array('id' => $params['id'])); 
    71                         else 
    72                                 $params =  $_FILES[$params['source']]; 
    73                  
    74                 if(isset($params['owner'])) 
    75                         $params['owner'] = Config::me('uidNumber'); 
    76                  
    77         } 
     13        if (!is_numeric($params['startTime'])) 
     14            $params['startTime'] = self::parseTimeDate($params['startTime'], $params['timezone']); 
     15 
     16        if (!is_numeric($params['endTime'])) { 
     17            $params['endTime'] = self::parseTimeDate($params['endTime'], $params['timezone']); 
     18 
     19            if ($params['allDay']) 
     20                $params['endTime'] = $params['endTime'] + 86400000; 
     21        } 
     22        //        if( !isset( $new['repeat'] )) 
     23        //            $new['range_end'] = '7287926400'; // 12/12/2200 
     24        //        else 
     25        $params['rangeEnd'] = $params['endTime']; 
     26        $params['rangeStart'] = $params['startTime']; 
     27 
     28        /////////////////////////////////////////////////////////////////// 
     29 
     30        $params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] : time() . '000'; 
     31        $params['lastUpdate'] = (isset($params['lastUpdate'])) ? $params['lastUpdate'] : time() . '000'; 
     32        $params['type'] = EVENT_ID; 
     33        $params['uid'] = isset($params['uid']) ? $params['uid'] : $this->_makeUid(); 
     34    } 
     35 
     36    static function parseTimeDate($time, $timezone) { 
     37        return strtotime($time . ' ' . $timezone) . '000'; 
     38    } 
     39 
     40    public function encodeCreateAlarm(&$uri, &$params, &$criteria, $original) { 
     41 
     42        if (!isset($params['schedulable']) || !isset($params['rangeStart']) || !isset($params['rangeEnd'])) { 
     43            $participant = Controller::read(array('concept' => 'participant', 'id' => $params['participant']), array('schedulable')); 
     44            $schedulable = Controller::read(array('concept' => 'schedulable', 'id' => $participant['schedulable']), array('startTime', 'endTime')); 
     45 
     46            $params['schedulable'] = $participant['schedulable']; 
     47            $params['rangeStart'] = strtotime('- ' . $params['time'] . ' ' . self::codeAlarmUnit($params['unit']), (int) ($schedulable['startTime'] / 1000)) . '000'; 
     48            $params['rangeEnd'] = $schedulable['endTime']; 
     49        } 
     50 
     51        $params['type'] = self::codeAlarmType($params['type']); 
     52    } 
     53 
     54    public function encodeCreateSuggestion(&$uri, &$params, &$criteria, $original) { 
     55        $params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] : time() . '000'; 
     56    } 
     57 
     58    public function encodeUpdateAlarm(&$uri, &$params, &$criteria, $original) { 
     59        if (isset($params['type'])) 
     60            $params['type'] = self::codeAlarmType($params['type']); 
     61    } 
     62 
     63    public function encodeCreateAttachment(&$uri, &$params, &$criteria, $original) { 
     64 
     65        if (!isset($params['source'])) 
     66            return false; 
     67 
     68        if (isset($_FILES[$params['source']])) 
     69            if (isset($params['id'])) 
     70                $params = array_merge($_FILES[$params['source']], array('id' => $params['id'])); 
     71            else 
     72                $params = $_FILES[$params['source']]; 
     73 
     74        if (isset($params['owner'])) 
     75            $params['owner'] = Config::me('uidNumber'); 
     76    } 
    7877 
    7978/////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    80          
    81     public function encodeSignatureAlarmType( &$uri , &$params , &$criteria , $original ){ 
    82         $params['type'] = self::codeAlarmType($params['type']); 
    83     }   
    84          
    85  
    86     public function insertOwnerLink (&$uri , &$params , &$criteria , $original ){ 
    87             $params['owner'] = Config::me('uidNumber');  
    88       }   
    89         
    90     public function encodeServiceUser (&$uri , &$params , &$criteria , $original ){ 
    91            if(isset($params['isExternal']) && $params['isExternal'] == '1') 
    92                 $uri['service'] = 'PostgreSQL';  
    93     } 
    94  
    95     public function prepareRepeat(&$uri , &$params , &$criteria , $original ){ 
    96  
    97         if( isset($params['startTime']) || isset($params['endTime']) ) 
    98         { 
    99           $timezone = Controller::read( array( 'concept' => 'schedulable', 'id' => $params['schedulable'] ), array('timezone') ); 
    100  
    101           if( isset($params['startTime']) ) 
    102             $params['startTime'] = self::parseTimeDate( $params['startTime'], $timezone['timezone'] ); 
    103           if( isset($params['endTime']) ) 
    104             $params['endTime'] = self::parseTimeDate( $params['endTime'], $timezone['timezone'] ); 
    105         } 
    106     } 
    107        
    108     public function findSchedulable( &$uri , &$params , &$criteria , $original ) 
    109    { 
    110        if(isset($criteria['filter'][3][1]) && $criteria['filter'][3][1] == 'calendar') 
    111        { 
    112           $start = $criteria['filter'][1][2]; 
    113           $end = $criteria['filter'][2][2]; 
    114  
    115           $ids = array(); 
    116           $occ = array(); 
    117  
    118           if( $occurrences = self::checkOccurrences( $start, $end ) ) 
    119               foreach( $occurrences as $id => $occurrence ) 
    120               { 
    121                   $ids[] = $id; 
    122                   $occ[] = $occurrence; 
    123               } 
    124  
    125          $sql = ' SELECT calendar_object.id as id ,calendar_object.cal_uid as "uid", calendar_object.type_id as "type", calendar_object.dtstart as "startTime", calendar_object.summary as "summary", calendar_object.description as "description", calendar_object.dtend as "endTime" , calendar_object.location as "location", calendar_object.allday as "allDay", calendar_object.transp as "transparent", calendar_object.class_id as "class", calendar_object.repeat as "repeat", calendar_object.range_start as "rangeStart",calendar_object.range_end as "rangeEnd", calendar_object.last_update as "lastUpdate", calendar_object.dtstamp as "dtstamp", calendar_object.sequence as "sequence",  calendar_object.tzid as "timezone" ,calendar_to_calendar_object.calendar_id as calendar FROM calendar_to_calendar_object , calendar_object WHERE (range_start >= \''.$start.'\' AND range_end <= \''.$end.'\' AND calendar_to_calendar_object.calendar_id IN (\''.  implode('\',\'', $criteria['filter'][3][2]).'\')) AND calendar_to_calendar_object.calendar_object_id = calendar_object.id'.( !empty($ids) ? ' AND calendar_object.id NOT IN (\'' .implode( '\',\'', $ids ). '\')' : ''); 
    126  
    127          $params = Controller::service('PostgreSQL')->execResultSql($sql); 
    128  
    129          $params = array_merge( $params, $occ ); 
    130          $params = self::deepnessFindEvent( $uri , $params , $criteria , $original); 
    131  
    132          return false; 
    133        } 
    134    } 
    135  
    136   public function deepnessFindRepeatOccurrence( &$uri , &$result , &$criteria , $original ) 
    137   { 
    138  
    139     if( !isset($criteria['deepness']) || $criteria['deepness'] == 0 ) 
    140           return; 
    141  
    142       foreach( $result as $i => &$res ) 
    143           if( isset($res['repeat']) ) 
    144               $res['repeat'] = Controller::read( array( 'concept' => 'repeat', 'id' => $res['repeat'] ), false, array( 'deepness' => intval( $criteria['deepness'] ) - 1 ) ); 
    145   } 
    146  
    147   public function deepnessRepeat( &$uri , &$result , &$criteria , $original ) 
    148   { 
    149  
    150       if( !isset($criteria['deepness']) || $criteria['deepness'] == 0 ) 
    151           return; 
    152  
    153         $result['schedulable'] = Controller::find( array( 'concept' => 'schedulable' ), false, array( 'filter' => array( '=', 'id', $result['schedulable'] ), 'deepness' => intval( $criteria['deepness'] ) - 1 ) ); 
     79 
     80    public function encodeSignatureAlarmType(&$uri, &$params, &$criteria, $original) { 
     81        $params['type'] = self::codeAlarmType($params['type']); 
     82    } 
     83 
     84    public function insertOwnerLink(&$uri, &$params, &$criteria, $original) { 
     85        $params['owner'] = Config::me('uidNumber'); 
     86    } 
     87 
     88    public function encodeServiceUser(&$uri, &$params, &$criteria, $original) { 
     89        if (isset($params['isExternal']) && $params['isExternal'] == '1') 
     90            $uri['service'] = 'PostgreSQL'; 
     91    } 
     92 
     93    public function prepareRepeat(&$uri, &$params, &$criteria, $original) { 
     94 
     95        if (isset($params['startTime']) || isset($params['endTime'])) { 
     96            $timezone = Controller::read(array('concept' => 'schedulable', 'id' => $params['schedulable']), array('timezone')); 
     97 
     98            if (isset($params['startTime'])) 
     99                $params['startTime'] = self::parseTimeDate($params['startTime'], $timezone['timezone']); 
     100            if (isset($params['endTime'])) 
     101                $params['endTime'] = self::parseTimeDate($params['endTime'], $timezone['timezone']); 
     102        } 
     103    } 
     104 
     105    public function findSchedulable(&$uri, &$params, &$criteria, $original) { 
     106        if (isset($criteria['filter'][3][1]) && $criteria['filter'][3][1] == 'calendar') { 
     107            $start = $criteria['filter'][1][2]; 
     108            $end = $criteria['filter'][2][2]; 
     109 
     110            $ids = array(); 
     111            $occ = array(); 
     112 
     113            if ($occurrences = self::checkOccurrences($start, $end)) 
     114                foreach ($occurrences as $id => $occurrence) { 
     115                    $ids[] = $id; 
     116                    $occ[] = $occurrence; 
     117                } 
     118 
     119            $sql = ' SELECT calendar_object.id as id ,calendar_object.cal_uid as "uid", calendar_object.type_id as "type", calendar_object.dtstart as "startTime", calendar_object.summary as "summary", calendar_object.description as "description", calendar_object.dtend as "endTime" , calendar_object.location as "location", calendar_object.allday as "allDay", calendar_object.transp as "transparent", calendar_object.class_id as "class", calendar_object.repeat as "repeat", calendar_object.range_start as "rangeStart",calendar_object.range_end as "rangeEnd", calendar_object.last_update as "lastUpdate", calendar_object.dtstamp as "dtstamp", calendar_object.sequence as "sequence",  calendar_object.tzid as "timezone" ,calendar_to_calendar_object.calendar_id as calendar FROM calendar_to_calendar_object , calendar_object WHERE (range_start >= \'' . $start . '\' AND range_end <= \'' . $end . '\' AND calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $criteria['filter'][3][2]) . '\')) AND calendar_to_calendar_object.calendar_object_id = calendar_object.id' . (!empty($ids) ? ' AND calendar_object.id NOT IN (\'' . implode('\',\'', $ids) . '\')' : ''); 
     120 
     121            $params = Controller::service('PostgreSQL')->execResultSql($sql); 
     122 
     123            $params = array_merge($params, $occ); 
     124            $params = self::deepnessFindEvent($uri, $params, $criteria, $original); 
     125 
     126            return false; 
     127        } 
     128    } 
     129 
     130    public function deepnessFindRepeatOccurrence(&$uri, &$result, &$criteria, $original) { 
     131 
     132        if (!isset($criteria['deepness']) || $criteria['deepness'] == 0) 
     133            return; 
     134 
     135        foreach ($result as $i => &$res) 
     136            if (isset($res['repeat'])) 
     137                $res['repeat'] = Controller::read(array('concept' => 'repeat', 'id' => $res['repeat']), false, array('deepness' => intval($criteria['deepness']) - 1)); 
     138    } 
     139 
     140    public function deepnessRepeat(&$uri, &$result, &$criteria, $original) { 
     141 
     142        if (!isset($criteria['deepness']) || $criteria['deepness'] == 0) 
     143            return; 
     144 
     145        $result['schedulable'] = Controller::find(array('concept' => 'schedulable'), false, array('filter' => array('=', 'id', $result['schedulable']), 'deepness' => intval($criteria['deepness']) - 1)); 
    154146        $result['schedulable'] = $result['schedulable'][0]; 
    155   } 
    156  
    157 public function saveOccurrences( &$uri , &$result , &$criteria , $original ){ 
    158         $ranges = Controller::find( array( 'concept' => 'repeatRange' ), array( 'rangeStart', 'rangeEnd' ),  array( 'filter' => array( '=', 'user', Config::me("uidNumber") ) ) ); 
    159  
    160         if( !is_array( $ranges ) || !isset( $ranges[0]['rangeStart'] ) || !isset( $ranges[0]['rangeEnd'] ) ) 
     147    } 
     148 
     149    public function saveOccurrences(&$uri, &$result, &$criteria, $original) { 
     150        $ranges = Controller::find(array('concept' => 'repeatRange'), array('rangeStart', 'rangeEnd'), array('filter' => array('=', 'user', Config::me("uidNumber")))); 
     151 
     152        if (!is_array($ranges) || !isset($ranges[0]['rangeStart']) || !isset($ranges[0]['rangeEnd'])) 
    161153            return; 
    162154 
    163         if( isset( $result['id'] ) ) 
    164              $id = $result['id']; 
     155        if (isset($result['id'])) 
     156            $id = $result['id']; 
    165157        else 
    166              $id = $uri['id'];  
    167  
    168         $repeat = Controller::read( array( 'concept' => 'repeat', 'id' => $id ) ); 
    169  
    170         unset( $repeat['schedulable'] ); 
    171         unset( $repeat['id'] ); 
     158            $id = $uri['id']; 
     159 
     160        $repeat = Controller::read(array('concept' => 'repeat', 'id' => $id)); 
     161 
     162        unset($repeat['schedulable']); 
     163        unset($repeat['id']); 
    172164 
    173165        $exceptions = array(); 
    174166 
    175         if( isset( $original['properties']['exceptions'] ) ) 
    176         { 
    177             $exceptions = explode( ',', $original['properties']['exceptions'] ); 
    178             unset( $repeat['exceptions'] ); 
    179         } 
    180  
    181         $lastExceptions = Controller::find( array( 'concept' => 'repeatOccurrence' ), array("occurrence") , array( 'filter' => array('AND', array( '=', 'repeat', $id ) , array( '=', 'exception', 1 ) ) )); 
    182          
    183         //Recurepa as execeções anteriores caso exista 
    184         if(isset($lastExceptions) && count($lastExceptions) && $lastExceptions) 
    185             foreach($lastExceptions as $key => $value) 
    186                 array_push($exceptions, $lastExceptions[$key]['occurrence']); 
    187          
    188         $params = array_diff( self::decodeRepeat( $repeat, $ranges[0]['rangeStart'], $ranges[0]['rangeEnd'] ), $exceptions ); 
    189          
    190         Controller::delete( array( 'concept' => 'repeatOccurrence' ), false, array( 'filter' => array( '=', 'repeat', $id ) ) ); 
    191  
    192         if( !empty($params) ) 
    193             Controller::service('PostgreSQL')->execResultSql( "INSERT INTO calendar_repeat_occurrence(repeat_id,exception,occurrence)VALUES('".$id."','0','".implode( "'),('".$id."','0','", $params )."')".( empty($exceptions) ? "" : ",('".$id."','1','".implode( "'),('".$id."','1','", $exceptions )."')" ) ); 
    194     } 
    195  
    196     public function checkOccurrences( $start, $end ){ 
    197  
    198         $ranges = Controller::find( array( 'concept' => 'repeatRange' ), array( 'rangeStart', 'rangeEnd' ),  array( 'filter' => array( '=', 'user', Config::me("uidNumber") ) ) ); 
     167        if (isset($original['properties']['exceptions'])) { 
     168            $exceptions = explode(',', $original['properties']['exceptions']); 
     169            unset($repeat['exceptions']); 
     170        } 
     171 
     172        $lastExceptions = Controller::find(array('concept' => 'repeatOccurrence'), array("occurrence"), array('filter' => array('AND', array('=', 'repeat', $id), array('=', 'exception', 1)))); 
     173 
     174        //Recurepa as execeções anteriores caso exista 
     175        if (isset($lastExceptions) && count($lastExceptions) && $lastExceptions) 
     176            foreach ($lastExceptions as $key => $value) 
     177                array_push($exceptions, $lastExceptions[$key]['occurrence']); 
     178 
     179        $params = array_diff(self::decodeRepeat($repeat, $ranges[0]['rangeStart'], $ranges[0]['rangeEnd']), $exceptions); 
     180 
     181        Controller::delete(array('concept' => 'repeatOccurrence'), false, array('filter' => array('=', 'repeat', $id))); 
     182 
     183        if (!empty($params)) 
     184            Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,exception,occurrence)VALUES('" . $id . "','0','" . implode("'),('" . $id . "','0','", $params) . "')" . ( empty($exceptions) ? "" : ",('" . $id . "','1','" . implode("'),('" . $id . "','1','", $exceptions) . "')" )); 
     185    } 
     186 
     187    public function checkOccurrences($start, $end) { 
     188 
     189        $ranges = Controller::find(array('concept' => 'repeatRange'), array('rangeStart', 'rangeEnd'), array('filter' => array('=', 'user', Config::me("uidNumber")))); 
    199190        $ranges = $ranges[0]; 
    200191 
     
    202193        $origEnd = $end; 
    203194 
    204         if( $initialized = (isset($ranges['rangeStart']) && isset($ranges['rangeEnd'])) ) 
    205         { 
    206             if( $ranges['rangeStart'] <= $start ) 
     195        if ($initialized = (isset($ranges['rangeStart']) && isset($ranges['rangeEnd']))) { 
     196            if ($ranges['rangeStart'] <= $start) 
    207197                $start = false; 
    208             if( $ranges['rangeEnd'] >= $end ) 
     198            if ($ranges['rangeEnd'] >= $end) 
    209199                $end = false; 
    210200        } 
     
    212202        $repeats = self::findRepeats(); 
    213203 
    214         if( !is_array( $repeats ) || empty( $repeats ) ) 
     204        if (!is_array($repeats) || empty($repeats)) 
    215205            return( false ); 
    216206 
     
    218208        $ids = array(); 
    219209 
    220         foreach( $repeats as $repeat ) 
    221         { 
    222             $ids[] = $id = $repeat['id']; unset( $repeat['id'] );  
    223  
    224             if( !isset( $result[ $id ] ) ) 
    225                 $result[ $id ] = !$initialized ?  array( $repeat['startTime'] ) : array(); 
    226  
    227             if( !$initialized ) 
    228                 $result[ $id ] = array_merge( $result[ $id ], self::decodeRepeat( $repeat, $start, $end ) ); 
    229             else 
    230             { 
    231                 if( $start ) 
    232                     $result[ $id ] = array_merge( $result[ $id ], self::decodeRepeat( $repeat, $start, $ranges['rangeStart'] ) ); 
    233  
    234                 if( $end ) 
    235                     $result[ $id ] = array_merge( $result[ $id ], self::decodeRepeat( $repeat, $ranges['rangeEnd'], $end ) ); 
    236             } 
    237  
    238             if( empty( $result[ $id ] ) ) 
    239                 unset( $result[ $id ] ); 
    240         } 
    241  
    242         if( $start || $end ) 
    243         { 
    244             Controller::begin( array( 'service' => 'PostgreSQL') ); 
    245  
    246             foreach( $result as $id => $res ) 
    247                 Controller::service('PostgreSQL')->execResultSql( "INSERT INTO calendar_repeat_occurrence(repeat_id,occurrence)VALUES('".$id."','".implode( "'),('".$id."', '", $res )."')" ); 
     210        foreach ($repeats as $repeat) { 
     211            $ids[] = $id = $repeat['id']; 
     212            unset($repeat['id']); 
     213 
     214            if (!isset($result[$id])) 
     215                $result[$id] = !$initialized ? array($repeat['startTime']) : array(); 
     216 
     217            if (!$initialized) 
     218                $result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $start, $end)); 
     219            else { 
     220                if ($start) 
     221                    $result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $start, $ranges['rangeStart'])); 
     222 
     223                if ($end) 
     224                    $result[$id] = array_merge($result[$id], self::decodeRepeat($repeat, $ranges['rangeEnd'], $end)); 
     225            } 
     226 
     227            if (empty($result[$id])) 
     228                unset($result[$id]); 
     229        } 
     230 
     231        if ($start || $end) { 
     232            Controller::begin(array('service' => 'PostgreSQL')); 
     233 
     234            foreach ($result as $id => $res) 
     235                Controller::service('PostgreSQL')->execResultSql("INSERT INTO calendar_repeat_occurrence(repeat_id,occurrence)VALUES('" . $id . "','" . implode("'),('" . $id . "', '", $res) . "')"); 
    248236 
    249237            $data = array(); 
    250238 
    251             if( $start ) 
     239            if ($start) 
    252240                $data['rangeStart'] = $start; 
    253241 
    254             if( $end ) 
     242            if ($end) 
    255243                $data['rangeEnd'] = $end; 
    256244 
    257             if( !$initialized ) 
    258                 $data['user'] = Config::me( 'uidNumber' ); 
    259  
    260             Controller::call( ( $initialized ? 'replace' : 'create' ), array( 'concept' => 'repeatRange' ), $data, array( 'filter' => array( '=', 'user', Config::me('uidNumber') ) ) ); 
    261  
    262             Controller::commit( array( 'service' => 'PostgreSQL' ) ); 
     245            if (!$initialized) 
     246                $data['user'] = Config::me('uidNumber'); 
     247 
     248            Controller::call(( $initialized ? 'replace' : 'create'), array('concept' => 'repeatRange'), $data, array('filter' => array('=', 'user', Config::me('uidNumber')))); 
     249 
     250            Controller::commit(array('service' => 'PostgreSQL')); 
    263251        } 
    264252 
    265253//      $return = Controller::find( array( 'concept' => 'repeatOccurrence' ), false, array( 'filter' => array( 'AND', array( '>=', 'occurrence', $origStart ), array( '<=', 'occurrence', $origEnd ), array( 'IN', 'repeat', $ids ) ), 'deepness' => $deep ) ); 
    266254 
    267         $return = Controller::service('PostgreSQL')->execResultSql( 'SELECT calendar_repeat_occurrence.occurrence as "occurrence", calendar_repeat.object_id as "schedulable" FROM calendar_repeat, calendar_repeat_occurrence WHERE calendar_repeat_occurrence.occurrence >= \''.$origStart.'\' AND calendar_repeat_occurrence.occurrence <= \''.$origEnd.'\' AND calendar_repeat_occurrence.repeat_id IN (\''.implode( '\',\'', $ids ).'\') AND calendar_repeat.id = calendar_repeat_occurrence.repeat_id AND calendar_repeat_occurrence.exception != 1' ); 
    268  
    269         if( !is_array( $return ) ) 
    270           return( false ); 
     255        $return = Controller::service('PostgreSQL')->execResultSql('SELECT calendar_repeat_occurrence.occurrence as "occurrence", calendar_repeat.object_id as "schedulable" FROM calendar_repeat, calendar_repeat_occurrence WHERE calendar_repeat_occurrence.occurrence >= \'' . $origStart . '\' AND calendar_repeat_occurrence.occurrence <= \'' . $origEnd . '\' AND calendar_repeat_occurrence.repeat_id IN (\'' . implode('\',\'', $ids) . '\') AND calendar_repeat.id = calendar_repeat_occurrence.repeat_id AND calendar_repeat_occurrence.exception != 1'); 
     256 
     257        if (!is_array($return)) 
     258            return( false ); 
    271259 
    272260        $result = array(); 
    273261        $params = array(); 
    274262 
    275         foreach( $return as $ret ) 
    276         { 
    277               $currentId = $ret['schedulable']; 
    278  
    279               if( !isset( $result[ $currentId ] ) ) 
    280               { 
    281                     $result[ $currentId ] = Controller::read( array( 'concept' => 'schedulable', 'id' => $currentId ) ); 
    282                     $result[ $currentId ][ 'occurrences' ] = array(); 
    283  
    284                     $calendarToCalendarObj = self::schedulable2calendarToObject( $currentId ); 
    285                     $result[ $currentId ]['calendar'] = $calendarToCalendarObj[0]['calendar_id']; 
    286               } 
    287        
    288               $result[ $currentId  ][ 'occurrences' ][] = $ret['occurrence']; 
     263        foreach ($return as $ret) { 
     264            $currentId = $ret['schedulable']; 
     265 
     266            if (!isset($result[$currentId])) { 
     267                $result[$currentId] = Controller::read(array('concept' => 'schedulable', 'id' => $currentId)); 
     268                $result[$currentId]['occurrences'] = array(); 
     269 
     270                $calendarToCalendarObj = self::schedulable2calendarToObject($currentId); 
     271                $result[$currentId]['calendar'] = $calendarToCalendarObj[0]['calendar_id']; 
     272            } 
     273 
     274            $result[$currentId]['occurrences'][] = $ret['occurrence']; 
    289275        } 
    290276 
     
    292278    } 
    293279 
    294     public static function findRepeats() 
    295     { 
    296         return Controller::service('PostgreSQL')->execResultSql( 'SELECT calendar_repeat.wkst as "wkst", calendar_repeat.byweekno as "byweekno", calendar_repeat.byminute as "byminute", calendar_repeat.bysecond as "bysecond", calendar_repeat.byyearday as "byyearday", calendar_repeat.bymonthday as "bymonthday", calendar_repeat.bysetpos as "bysetpos", calendar_repeat.byday as "byday", calendar_repeat.byhour as "byhour", calendar_repeat.interval as "interval", calendar_repeat.frequency as "frequency", calendar_repeat.until as "endTime", calendar_repeat.id as "id", calendar_repeat.count as "count", calendar_repeat.dtstart as "startTime" FROM calendar_repeat, calendar_participant WHERE calendar_repeat.object_id = calendar_participant.object_id AND calendar_participant.user_info_id = \''.Config::me('uidNumber').'\'' ); 
    297     } 
    298          
     280    public static function findRepeats() { 
     281        return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_repeat.wkst as "wkst", calendar_repeat.byweekno as "byweekno", calendar_repeat.byminute as "byminute", calendar_repeat.bysecond as "bysecond", calendar_repeat.byyearday as "byyearday", calendar_repeat.bymonthday as "bymonthday", calendar_repeat.bysetpos as "bysetpos", calendar_repeat.byday as "byday", calendar_repeat.byhour as "byhour", calendar_repeat.interval as "interval", calendar_repeat.frequency as "frequency", calendar_repeat.until as "endTime", calendar_repeat.id as "id", calendar_repeat.count as "count", calendar_repeat.dtstart as "startTime" FROM calendar_repeat, calendar_participant WHERE calendar_repeat.object_id = calendar_participant.object_id AND calendar_participant.user_info_id = \'' . Config::me('uidNumber') . '\''); 
     282    } 
     283 
    299284//HELPERS 
    300     public static function decodeRepeat( $repeat , $start , $end ) { 
    301  
    302     date_default_timezone_set( 'UTC' ); 
    303  
    304     require_once ROOTPATH.'/plugins/when/When.php'; 
    305  
    306     $r = new When(); 
    307  
    308     if( $repeat['frequency'] === 'none' ) 
    309         return( array() ); 
    310   
    311     //Nao deve ser usando o horário da repeticao pois nela contem apenas o dias, 
    312     //deve se recuperar o horário do evento para um correto calculo. 
    313     if(max( $start, $repeat['startTime']  ) != $repeat['startTime']){ 
    314         $time = new DateTime( '@'.(int)( $repeat['startTime'] / 1000 ), new DateTimeZone('UTC') ); 
    315          
    316         $hoursOcurrence = new DateTime( '@'.(int)( $start / 1000 ), new DateTimeZone('UTC') ); 
    317         $hoursOcurrence = $hoursOcurrence->format('H'); 
    318          
    319         $diffTime = ((($time->format('H') - $hoursOcurrence) * (3600000)) + ($time->format('i') * (60000))); 
    320         $start =  new DateTime( '@'.(int)( ( $start + $diffTime )  / 1000 ), new DateTimeZone('UTC') );     
    321          
    322          
    323     }else 
    324         $start =  new DateTime( '@'.(int)( max( $start, $repeat['startTime']  ) / 1000 ), new DateTimeZone('UTC') );     
    325      
    326     foreach($repeat as $rule => $value) 
    327     { 
    328             if( !isset( $value ) || !$value || $value === "0" ) 
     285    public static function decodeRepeat($repeat, $start, $end) { 
     286 
     287        date_default_timezone_set('UTC'); 
     288 
     289        require_once ROOTPATH . '/plugins/when/When.php'; 
     290 
     291        $r = new When(); 
     292 
     293        if ($repeat['frequency'] === 'none') 
     294            return( array() ); 
     295 
     296        //Nao deve ser usando o horário da repeticao pois nela contem apenas o dias, 
     297        //deve se recuperar o horário do evento para um correto calculo. 
     298        if (max($start, $repeat['startTime']) != $repeat['startTime']) { 
     299            $time = new DateTime('@' . (int) ( $repeat['startTime'] / 1000 ), new DateTimeZone('UTC')); 
     300 
     301            $hoursOcurrence = new DateTime('@' . (int) ( $start / 1000 ), new DateTimeZone('UTC')); 
     302            $hoursOcurrence = $hoursOcurrence->format('H'); 
     303 
     304            $diffTime = ((($time->format('H') - $hoursOcurrence) * (3600000)) + ($time->format('i') * (60000))); 
     305            $start = new DateTime('@' . (int) ( ( $start + $diffTime ) / 1000 ), new DateTimeZone('UTC')); 
     306        }else 
     307            $start = new DateTime('@' . (int) ( max($start, $repeat['startTime']) / 1000 ), new DateTimeZone('UTC')); 
     308 
     309        foreach ($repeat as $rule => $value) { 
     310            if (!isset($value) || !$value || $value === "0") 
    329311                continue; 
    330312 
    331             switch(strtolower($rule)) 
    332             { 
    333                     case "starttime": break; 
    334                     case "frequency": 
    335                             $r->recur( $start, $value ); 
    336                             break; 
    337                     case "endtime": 
    338                             $r->until( new DateTime( '@'.(int)( $value / 1000 ) ) ); 
    339                             break; 
    340                     case "count": case "interval":  case "wkst": 
    341                             $r->$rule( $value ); 
    342                             break; 
    343                     default : 
    344                             $r->$rule( !is_array( $value ) ? explode( ',' , $value ) : $value ); 
    345                             break; 
    346             } 
    347     } 
    348  
    349     $return = array(); 
    350      
    351     while($result = $r->next()) 
    352     {  
    353        $u = $result->format('U') * 1000; 
    354  
    355        if( $u  > $end ) //data da repetição atual maior que a data final da busca do usuario ? 
    356            break; 
    357  
    358       $return[] = $u; 
    359     } 
    360  
    361     return( $return ); 
    362 } 
    363     
     313            switch (strtolower($rule)) { 
     314                case "starttime": break; 
     315                case "frequency": 
     316                    $r->recur($start, $value); 
     317                    break; 
     318                case "endtime": 
     319                    $r->until(new DateTime('@' . (int) ( $value / 1000 ))); 
     320                    break; 
     321                case "count": case "interval": case "wkst": 
     322                    $r->$rule($value); 
     323                    break; 
     324                default : 
     325                    $r->$rule(!is_array($value) ? explode(',', $value) : $value ); 
     326                    break; 
     327            } 
     328        } 
     329 
     330        $return = array(); 
     331 
     332        while ($result = $r->next()) { 
     333            $u = $result->format('U') * 1000; 
     334 
     335            if ($u > $end) //data da repetição atual maior que a data final da busca do usuario ? 
     336                break; 
     337 
     338            $return[] = $u; 
     339        } 
     340 
     341        return( $return ); 
     342    } 
     343 
    364344/////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    365345 
    366     public function updateCalendar( &$uri , &$params , &$criteria , $original ){ 
    367         if( isset($params['calendar'])) 
    368         {  
    369             $calendarObjects = self::schedulable2calendarToObject( $uri['id'] ); 
    370             $params2['calendar'] = $params['calendar'];  
    371             
    372             foreach ($calendarObjects as $calendarObject) 
    373                 Controller::update( array('concept' => 'calendarToSchedulable' , 'id' => $calendarObject['calendar_to_calendar_object']) , $params2 ); 
    374           
    375             unset( $params['calendar'] ); 
    376              
    377             if(count($params) < 1) return false; 
    378         } 
    379     }  
    380       
     346    public function updateCalendar(&$uri, &$params, &$criteria, $original) { 
     347        if (isset($params['calendar'])) { 
     348            $calendarObjects = self::schedulable2calendarToObject($uri['id']); 
     349            $params2['calendar'] = $params['calendar']; 
     350 
     351            foreach ($calendarObjects as $calendarObject) 
     352                Controller::update(array('concept' => 'calendarToSchedulable', 'id' => $calendarObject['calendar_to_calendar_object']), $params2); 
     353 
     354            unset($params['calendar']); 
     355 
     356            if (count($params) < 1) 
     357                return false; 
     358        } 
     359    } 
     360 
    381361//Encode Update 
    382362 
    383     public function encodeUpdateSchedulable( &$uri , &$params , &$criteria , $original ){        
    384          
    385                 $event = Controller::find( array( 'concept' => 'schedulable' , array('timezone', 'allDay') ,'id' => $params['id'] ) );   
    386                  
    387                 if(isset($params['startTime'])){ 
    388                          
    389                         if(!is_numeric($params['startTime']) ) 
    390                                 $params['startTime'] =  strtotime( $params['startTime'] . ' ' .$event['timezone']).'000'; 
    391                          
    392                         $params['rangeStart'] = $params['startTime'] ; 
    393                     
    394                 }if(isset($params['endTime'])){ 
    395                          
    396                         if (!is_numeric($params['endTime'])){ 
    397                                 $params['endTime'] =   strtotime( $params['endTime'] . ' ' .$event['timezone']).'000'; 
    398                                  
    399                                 if($event['allDay']) 
    400                                         $params['endTime'] =  $params['endTime']  + 86400000; 
     363    public function encodeUpdateSchedulable(&$uri, &$params, &$criteria, $original) { 
     364 
     365        $event = Controller::find(array('concept' => 'schedulable', array('timezone', 'allDay'), 'id' => $params['id'])); 
     366 
     367        if (isset($params['startTime'])) { 
     368 
     369            if (!is_numeric($params['startTime'])) 
     370                $params['startTime'] = strtotime($params['startTime'] . ' ' . $event['timezone']) . '000'; 
     371 
     372            $params['rangeStart'] = $params['startTime']; 
     373        }if (isset($params['endTime'])) { 
     374 
     375            if (!is_numeric($params['endTime'])) { 
     376                $params['endTime'] = strtotime($params['endTime'] . ' ' . $event['timezone']) . '000'; 
     377 
     378                if ($event['allDay']) 
     379                    $params['endTime'] = $params['endTime'] + 86400000; 
     380            } 
     381            $params['rangeEnd'] = $params['endTime']; 
     382        } 
     383    } 
     384 
     385    static function putEvent(&$uri, &$result, &$criteria, $original) { 
     386        if (Config::module('useCaldav', 'expressoCalendar')) { //Ignorar Put dos eventos ja vindos do caldav 
     387            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php'; 
     388 
     389            $eventID = (isset($result['id'])) ? $result['id'] : $uri['id']; 
     390            $event = Controller::read(array('concept' => 'schedulable', 'id' => $eventID)); 
     391 
     392            $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $eventID))); 
     393 
     394            if (is_array($participants) && count($participants) > 0) 
     395                foreach ($participants as $ii => $vv) { 
     396                    if ($vv['isExternal'] == 1) 
     397                        $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL')); 
     398                    else 
     399                        $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'])); 
     400                } 
     401 
     402            $event['URI']['concept'] = 'schedulable'; 
     403            $event['participants'] = $participants; 
     404 
     405            $ical = Controller::format(array('service' => 'iCal'), array($event)); 
     406            $calendars = self::schedulable2calendarToObject($original['properties']['id']); //Busca os calendarios do usuario logado que contenham o evento 
     407            if (is_array($calendars)) 
     408                foreach ($calendars as $calendar) 
     409                    DAViCalAdapter::putIcal($ical, array('uid' => $event['uid'], 'location' => $calendar['calendar_location'])); 
     410        } 
     411    } 
     412 
     413/////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
     414 
     415    public function verifyCalendarLocation(&$uri, &$params, &$criteria, $original) { 
     416        if (!isset($params['location'])) 
     417            $params['location'] = Config::me('uid') . '/' . $params['name']; 
     418    } 
     419 
     420    //TODO: Remover apos suporte a ManytoMany na api  
     421    public function createCalendarToSchedulable(&$uri, &$result, &$criteria, $original) { 
     422 
     423        Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $original['properties']['calendar'], 'schedulable' => $result['id'])); 
     424    } 
     425 
     426    public function createCreateSchedulableToAttachment(&$uri, &$params, &$criteria, $original) { 
     427        if (array_key_exists('attachments', $original['properties'])) 
     428            foreach ($original['properties']['attachments'] as $key => $value) { 
     429                if (isset($params['id'])) 
     430                    Controller::create(array('concept' => 'schedulableToAttachment'), array('attachment' => $value['attachment'], 'schedulable' => $params['id'])); 
     431            } 
     432    } 
     433 
     434    public function deepnessFindCalendarShared(&$uri, &$result, &$criteria, $original) { 
     435        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != '0' && count($result) > 0) { 
     436            $calendarIds = array(); 
     437            foreach ($result as $key => $value) 
     438                array_push($calendarIds, $value['calendar']); 
     439 
     440            $calendar = Controller::find(array('concept' => 'calendar'), false, array('filter' => array('AND', array('IN', 'id', $calendarIds), $original['criteria']['filter']))); 
     441 
     442            if (!is_array($calendar)) 
     443                $result = ''; 
     444 
     445            $newResult = array(); 
     446            foreach ($calendar as $key => $value) { 
     447                foreach ($result as $k => $r) { 
     448 
     449                    if ($r['calendar'] == $value['id']) { 
     450                        $r['calendar'] = $value; 
     451                        array_push($newResult, $r); 
     452                    } 
     453                } 
     454            } 
     455 
     456            foreach ($newResult as $key => &$value) { 
     457                if ($value['user'] != 0) { 
     458                    $user = $value['user']; 
     459                    $value['user'] = Controller::read(array('concept' => 'user', 'id' => $user)); 
     460 
     461                    if (!$value['user']) 
     462                        $value['user'] = Controller::read(array('concept' => 'group', 'id' => $user)); 
     463                } 
     464            } 
     465 
     466 
     467            $result = $newResult; 
     468        } 
     469    } 
     470 
     471    //TODO: Remover apos suporte a deepness na api  
     472    public function deepnessFindEvent(&$uri, &$result, &$criteria, $original) { 
     473        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) { 
     474 
     475            $Time = new DateTime('now', new DateTimeZone('UTC')); 
     476            $DayLigth = array(); 
     477            foreach ($result as $i => $v) { 
     478 
     479                if (!isset($currentTimezone) || $currentTimezone != $original['criteria']['timezones'][$v['calendar']]) { 
     480                    $currentTimezone = isset($original['criteria']['timezones'][$v['calendar']]) ? $original['criteria']['timezones'][$v['calendar']] : $v['timezone']; 
     481                    $Time->setTimezone(new DateTimeZone($currentTimezone)); 
     482                } 
     483 
     484                $Time->setTimestamp((int) ($v['startTime'] / 1000)); 
     485                $DayLigth['calendar']['startTime'] = $Time->format('I') ? 1 : 0; 
     486 
     487                $Time->setTimestamp((int) ($v['endTime'] / 1000)); 
     488                $DayLigth['calendar']['endTime'] = $Time->format('I') ? 1 : 0; 
     489 
     490                if ($currentTimezone != $v['timezone']) { 
     491                    $currentTimezone = $v['timezone']; 
     492                    $Time->setTimezone(new DateTimeZone($v['timezone'])); 
     493 
     494                    $Time->setTimestamp((int) ($v['startTime'] / 1000)); 
     495                    $DayLigth['event']['startTime'] = $Time->format('I') ? 1 : 0; 
     496 
     497                    $Time->setTimestamp((int) ($v['endTime'] / 1000)); 
     498                    $DayLigth['event']['endTime'] = $Time->format('I') ? 1 : 0; 
     499                }else 
     500                    $DayLigth['event'] = $DayLigth['calendar']; 
     501 
     502 
     503                $result[$i]['DayLigth'] = $DayLigth; 
     504 
     505                if (isset($v['id'])) { 
     506                    $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $v['id']))); 
     507 
     508                    if (is_array($participants) && count($participants) > 0) 
     509                        foreach ($participants as $ii => $vv) { 
     510                            if ($vv['isExternal'] == 1) 
     511                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL')); 
     512                            else 
     513                                $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'])); 
     514 
     515                            if ($participants[$ii]['user']['id'] == Config::me('uidNumber')) 
     516                                $participants[$ii]['alarms'] = Controller::find(array('concept' => 'alarm'), null, array('filter' => array('AND', array('=', 'participant', $vv['id']), array('=', 'schedulable', $v['id'])))); 
    401517                        } 
    402                         $params['rangeEnd'] = $params['endTime'] ;        
    403                                  
    404                 }     
    405      }         
    406       
    407     static function putEvent(&$uri , &$result , &$criteria , $original) 
    408     {           
    409             if(Config::module('useCaldav' , 'expressoCalendar')) //Ignorar Put dos eventos ja vindos do caldav 
    410             { 
    411                 require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php'; 
    412  
    413                 $eventID = (isset($result['id'])) ? $result['id'] : $uri['id']; 
    414                 $event = Controller::read( array( 'concept' => 'schedulable' , 'id' => $eventID ) ); 
    415  
    416                 $participants = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=' ,  'schedulable' ,  $eventID) ));  
    417  
    418                 if(is_array($participants) && count($participants) > 0) 
    419                     foreach ($participants as $ii => $vv) 
    420                     { 
    421                         if($vv['isExternal'] == 1 ) 
    422                             $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] , 'service' => 'PostgreSQL' ) ); 
    423                         else 
    424                            $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] )); 
    425                     }  
    426  
    427                 $event['URI']['concept'] = 'schedulable'; 
    428                 $event['participants'] = $participants; 
    429                 
    430                 $ical = Controller::format( array( 'service' => 'iCal' ) , array($event) );                   
    431                 $calendars =  self::schedulable2calendarToObject($original['properties']['id']); //Busca os calendarios do usuario logado que contenham o evento 
    432                 if( is_array($calendars) ) 
    433                     foreach ($calendars as $calendar) 
    434                         DAViCalAdapter::putIcal($ical , array('uid' => $event['uid'] , 'location' => $calendar['calendar_location'] )); 
    435             } 
    436     }  
    437 /////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
    438      
    439     public function verifyCalendarLocation( &$uri , &$params , &$criteria , $original ){ 
    440         if(!isset($params['location'])) 
    441             $params['location'] = Config::me('uid').'/'.$params['name']; 
    442     }  
    443      
    444        
    445     //TODO: Remover apos suporte a ManytoMany na api  
    446     public function createCalendarToSchedulable( &$uri , &$result , &$criteria , $original ){            
    447  
    448                 Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $original['properties']['calendar'], 'schedulable' => $result['id'] )); 
    449  
    450    } 
    451  
    452         public function createCreateSchedulableToAttachment( &$uri , &$params , &$criteria , $original ){                
    453                 if(array_key_exists('attachments', $original['properties']))     
    454                         foreach($original['properties']['attachments'] as $key => $value){                               
    455                                 if(isset($params['id'])) 
    456                                         Controller::create(array('concept' => 'schedulableToAttachment'), array('attachment' => $value['attachment'], 'schedulable' => $params['id'] )); 
    457                         } 
    458         } 
    459       
    460          public function deepnessFindCalendarShared( &$uri , &$result , &$criteria , $original ){                                
    461                 if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != '0' && count($result) > 0){ 
    462                         $calendarIds = array(); 
    463                         foreach($result as $key => $value) 
    464                                 array_push($calendarIds, $value['calendar']); 
    465                          
    466                         $calendar = Controller::find( array( 'concept' => 'calendar' ) , false ,array( 'filter' => array('AND', array('IN','id', $calendarIds), $original['criteria']['filter'])));  
    467                          
    468                         if(!is_array($calendar)) 
    469                                 $result = ''; 
    470  
    471                         $newResult = array(); 
    472                         foreach($calendar as $key => $value){ 
    473                                 foreach($result as $k => $r){ 
    474  
    475                                         if($r['calendar'] == $value['id']){ 
    476                                                 $r['calendar'] = $value; 
    477                                                 array_push($newResult, $r); 
    478                                         } 
    479                                 } 
    480                         } 
    481                          
    482                         foreach($newResult as $key => &$value){ 
    483                                 if($value['user']  != 0){ 
    484                                     $user = $value['user']; 
    485                                     $value['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $user )); 
    486  
    487                                     if(!$value['user']) 
    488                                         $value['user'] = Controller::read( array( 'concept' => 'group' , 'id' => $user )); 
    489                                 } 
    490                         } 
    491  
    492  
    493                 $result = $newResult; 
    494                 } 
    495     }    
    496   
    497     //TODO: Remover apos suporte a deepness na api  
    498     public function deepnessFindEvent( &$uri , &$result , &$criteria , $original ){ 
    499        if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) 
    500        { 
    501                          
    502             $Time = new DateTime( 'now', new DateTimeZone('UTC') ); 
    503             $DayLigth = array(); 
    504            foreach ($result as $i => $v) 
    505            { 
    506  
    507                                 if(!isset($currentTimezone) || $currentTimezone  != $original['criteria']['timezones'][$v['calendar']]){ 
    508                                         $currentTimezone = isset($original['criteria']['timezones'][$v['calendar']]) ?  $original['criteria']['timezones'][$v['calendar']] : $v['timezone']; 
    509                                         $Time->setTimezone(new DateTimeZone($currentTimezone)); 
    510                                 } 
    511  
    512                                 $Time->setTimestamp( (int)($v['startTime'] / 1000)); 
    513                                 $DayLigth['calendar']['startTime'] =  $Time->format('I') ? 1 : 0; 
    514                                  
    515                                 $Time->setTimestamp( (int)($v['endTime'] / 1000)); 
    516                                 $DayLigth['calendar']['endTime'] =  $Time->format('I') ? 1 : 0; 
    517                                  
    518                                 if($currentTimezone != $v['timezone']){ 
    519                                         $currentTimezone = $v['timezone']; 
    520                                         $Time->setTimezone(new DateTimeZone($v['timezone'])); 
    521                                  
    522                                         $Time->setTimestamp( (int)($v['startTime'] / 1000)); 
    523                                         $DayLigth['event']['startTime'] =  $Time->format('I') ? 1 : 0; 
    524  
    525                                         $Time->setTimestamp( (int)($v['endTime'] / 1000)); 
    526                                         $DayLigth['event']['endTime'] =  $Time->format('I') ? 1 : 0; 
    527                                 }else 
    528                                         $DayLigth['event'] = $DayLigth['calendar']; 
    529                                          
    530                                  
    531                                 $result[$i]['DayLigth'] = $DayLigth; 
    532                                  
    533                 if(isset($v['id'])) 
    534                 { 
    535                     $participants = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=', 'schedulable'  ,  $v['id']) ));  
    536                      
    537                     if(is_array($participants) && count($participants) > 0) 
    538                     foreach ($participants as $ii => $vv) 
    539                     { 
    540                         if($vv['isExternal'] == 1 ) 
    541                             $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] , 'service' => 'PostgreSQL' ) ); 
    542                         else 
    543                            $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] )); 
    544                      
    545                         if($participants[$ii]['user']['id'] == Config::me('uidNumber')) 
    546                            $participants[$ii]['alarms'] = Controller::find( array( 'concept' => 'alarm' ) , null , array('filter' => array('AND' , array('=', 'participant' ,$vv['id'] ) ,array('=' , 'schedulable', $v['id'])) ) );  
    547                     }        
    548                     $result[$i]['participants'] = $participants; 
    549                                          
    550                                          
    551                      
    552                     $attachmentRelation = Controller::find( array( 'concept' => 'schedulableToAttachment' ) , false ,array( 'filter' => array('=', 'schedulable'  ,  $v['id']) ));  
    553                     if(is_array($attachmentRelation)){ 
    554                             $attachments = array(); 
    555                             foreach($attachmentRelation as $key => $value) 
    556                                     if(isset($value['attachment']) || !!$value['attachment']) 
    557                                             $attachments[$key]  = $value['attachment']; 
    558                             //Pega os anexos sem source 
    559                             $result[$i]['attachments'] = Controller::find( array( 'concept' => 'attachment' ) , array('id', 'name', 'type', 'size') ,array( 'filter' => array('IN', 'id' , $attachments) ));  
     518                    $result[$i]['participants'] = $participants; 
     519 
     520 
     521 
     522                    $attachmentRelation = Controller::find(array('concept' => 'schedulableToAttachment'), false, array('filter' => array('=', 'schedulable', $v['id']))); 
     523                    if (is_array($attachmentRelation)) { 
     524                        $attachments = array(); 
     525                        foreach ($attachmentRelation as $key => $value) 
     526                            if (isset($value['attachment']) || !!$value['attachment']) 
     527                                $attachments[$key] = $value['attachment']; 
     528                        //Pega os anexos sem source 
     529                        $result[$i]['attachments'] = Controller::find(array('concept' => 'attachment'), array('id', 'name', 'type', 'size'), array('filter' => array('IN', 'id', $attachments))); 
    560530                    } 
    561531 
    562                     $repeat = Controller::find( array( 'concept' => 'repeat' ), false, array( 'filter' => array( '=', 'schedulable', $v['id'] ) ) ); 
    563  
    564                     unset( $result[$i]['repeat'] ); 
    565  
    566                     if( is_array($repeat) ) 
     532                    $repeat = Controller::find(array('concept' => 'repeat'), false, array('filter' => array('=', 'schedulable', $v['id']))); 
     533 
     534                    unset($result[$i]['repeat']); 
     535 
     536                    if (is_array($repeat)) 
    567537                        $result[$i]['repeat'] = $repeat[0]; 
    568538                } 
    569                  
    570            } 
    571        } 
    572         
    573        return $result; 
    574         
    575    }  
     539            } 
     540        } 
     541 
     542        return $result; 
     543    } 
    576544 
    577545    //TODO: Remover apos suporte a deepness na api  
    578     public function deepnessReadEvent( &$uri , &$result , &$criteria , $original ){              
    579         
    580        if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) 
    581        { 
    582             if(isset($result['id'])) 
    583             { 
    584                 $participants = Controller::find( array( 'concept' => 'participant' ) , false ,array( 'filter' => array('=' ,  'schedulable' ,  $result['id']) ));  
    585                 if(is_array($participants)) 
    586                     foreach ($participants as $ii => $vv) 
    587                     { 
    588                         if($vv['isExternal'] == 1 ) 
    589                             $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] , 'service' => 'PostgreSQL' ) ); 
    590                         else 
    591                            $participants[$ii]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $vv['user'] )); 
    592  
    593                         if($participants[$ii]['user']['id'] == Config::me('uidNumber')) 
    594                            $participants[$ii]['alarms'] = Controller::find( array( 'concept' => 'alarm' ) , null , array('filter' => array('AND' , array('=', 'participant' ,$vv['id'] ) ,array('=' , 'schedulable', $result['id'])) ) );  
    595                }   
    596                 $repeat =  Controller::find( array( 'concept' => 'repeat' ), false, array( 'filter' => array( '=', 'schedulable', $result['id'] ) ) ); 
    597                 if(is_array($repeat)) 
    598                     $result['repeat'] = $repeat[0] ; 
    599                  
     546    public function deepnessReadEvent(&$uri, &$result, &$criteria, $original) { 
     547 
     548        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) { 
     549            if (isset($result['id'])) { 
     550                $participants = Controller::find(array('concept' => 'participant'), false, array('filter' => array('=', 'schedulable', $result['id']))); 
     551                if (is_array($participants)) 
     552                    foreach ($participants as $ii => $vv) { 
     553                        if ($vv['isExternal'] == 1) 
     554                            $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'], 'service' => 'PostgreSQL')); 
     555                        else 
     556                            $participants[$ii]['user'] = Controller::read(array('concept' => 'user', 'id' => $vv['user'])); 
     557 
     558                        if ($participants[$ii]['user']['id'] == Config::me('uidNumber')) 
     559                            $participants[$ii]['alarms'] = Controller::find(array('concept' => 'alarm'), null, array('filter' => array('AND', array('=', 'participant', $vv['id']), array('=', 'schedulable', $result['id'])))); 
     560                    } 
     561                $repeat = Controller::find(array('concept' => 'repeat'), false, array('filter' => array('=', 'schedulable', $result['id']))); 
     562                if (is_array($repeat)) 
     563                    $result['repeat'] = $repeat[0]; 
     564 
    600565                $result['participants'] = $participants; 
    601                 } 
    602        } 
    603    }  
    604     
     566            } 
     567        } 
     568    } 
     569 
    605570    //TODO: Remover apos suporte a deepness na api 
    606     public function deepnessReadParticipant( &$uri , &$result , &$criteria , $original ){                
    607         
    608        if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) 
    609        { 
    610             if(isset($result['id'])) 
    611             { 
    612                 if($result['isExternal'] == 1 ) 
    613                     $result['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result['user'] , 'service' => 'PostgreSQL' ) ); 
    614                 else 
    615                    $result['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result['user'] )); 
    616             } 
    617        } 
    618  
    619    }  
    620     
     571    public function deepnessReadParticipant(&$uri, &$result, &$criteria, $original) { 
     572 
     573        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) { 
     574            if (isset($result['id'])) { 
     575                if ($result['isExternal'] == 1) 
     576                    $result['user'] = Controller::read(array('concept' => 'user', 'id' => $result['user'], 'service' => 'PostgreSQL')); 
     577                else 
     578                    $result['user'] = Controller::read(array('concept' => 'user', 'id' => $result['user'])); 
     579            } 
     580        } 
     581    } 
     582 
    621583    //TODO: Remover apos suporte a deepness na api  
    622     public function deepnessFindParticipant( &$uri , &$result , &$criteria , $original ){                
    623         
    624        if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) 
    625        { 
    626            foreach ($result as $i => $v) 
    627            { 
    628                 if(isset($v['id'])) 
    629                 { 
    630                     if($result[$i]['isExternal'] == 1 ) 
    631                         $result[$i]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result[$i]['user'] , 'service' => 'PostgreSQL' ) ); 
    632                     else 
    633                        $result[$i]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $result[$i]['user'] )); 
    634                 } 
    635            } 
    636        } 
    637         
    638    }  
    639     
     584    public function deepnessFindParticipant(&$uri, &$result, &$criteria, $original) { 
     585 
     586        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) { 
     587            foreach ($result as $i => $v) { 
     588                if (isset($v['id'])) { 
     589                    if ($result[$i]['isExternal'] == 1) 
     590                        $result[$i]['user'] = Controller::read(array('concept' => 'user', 'id' => $result[$i]['user'], 'service' => 'PostgreSQL')); 
     591                    else 
     592                        $result[$i]['user'] = Controller::read(array('concept' => 'user', 'id' => $result[$i]['user'])); 
     593                } 
     594            } 
     595        } 
     596    } 
     597 
    640598    //TODO: Remover apos suporte a deepness na api  
    641     public function deepnessReadCalendarSignature( &$uri , &$result , &$criteria , $original ){          
    642         
    643        if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) 
    644             if(isset($result['calendar'])){ 
    645                 $result['calendar'] = Controller::read( array( 'concept' => 'calendar' , 'id' => $result['calendar']));  
    646                                 $result['defaultAlarms'] = Controller::find( array( 'concept' => 'calendarSignatureAlarm' ) , false ,array( 'filter' => array('=', 'calendarSignature'  ,  $result['id']) ));      
     599    public function deepnessReadCalendarSignature(&$uri, &$result, &$criteria, $original) { 
     600 
     601        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) 
     602            if (isset($result['calendar'])) { 
     603                $result['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $result['calendar'])); 
     604                $result['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $result['id']))); 
     605            } 
     606    } 
     607 
     608    //TODO: Remover apos suporte a deepness na api  
     609    public function deepnessFindCalendarSignature(&$uri, &$result, &$criteria, $original) { 
     610 
     611        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) { 
     612            foreach ($result as $i => $v) { 
     613                if (isset($v['calendar'])) { 
     614                    $result[$i]['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $v['calendar']), false, false); 
     615                    $result[$i]['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $v['id']))); 
     616                    //Caso não seja o dono da agenda retorna o objeto permission com as acls 
     617                    if ($result[$i]['isOwner'] == 0) { 
     618                        $permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'user', Config::me('uidNumber'))))); 
     619 
     620                        if (!is_array($permission) || !$permission) { 
     621 
     622                            $permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'type', '1')))); 
    647623                        } 
    648              
    649    }  
    650     
    651      //TODO: Remover apos suporte a deepness na api  
    652     public function deepnessFindCalendarSignature( &$uri , &$result , &$criteria , $original ){          
    653  
    654         if(isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) 
    655        { 
    656            foreach ($result as $i => $v) 
    657            { 
    658                 if(isset($v['calendar'])){ 
    659                     $result[$i]['calendar'] = Controller::read( array( 'concept' => 'calendar' , 'id' => $v['calendar']), false, false);  
    660                     $result[$i]['defaultAlarms'] = Controller::find( array( 'concept' => 'calendarSignatureAlarm' ) , false ,array( 'filter' => array('=', 'calendarSignature'  ,  $v['id']) ));     
    661                     //Caso não seja o dono da agenda retorna o objeto permission com as acls 
    662                     if($result[$i]['isOwner'] == 0){ 
    663                             $permission = Controller::find( array( 'concept' => 'calendarToPermission'), false ,array( 'filter' => array('AND', array('=', 'calendar' ,  $v['calendar']), array('=', 'user', Config::me('uidNumber') ) ) ) );  
    664  
    665                             if(!is_array($permission) || !$permission  ){ 
    666  
    667                                     $permission = Controller::find( array( 'concept' => 'calendarToPermission'), false ,array( 'filter' => array('AND', array('=', 'calendar' ,  $v['calendar']), array('=', 'type', '1' ) ) ) );     
    668  
    669                             } 
    670                             $result[$i]['permission'] = $permission[0]; 
    671                     } 
    672             } 
    673             //TODO - Padronizar retorno do deepness 
    674             if(isset($v['user'])) 
    675                 $result[$i]['user'] = Controller::read( array( 'concept' => 'user' , 'id' => $v['user']), false, false);  
    676           } 
    677        }        
    678    }  
     624                        $result[$i]['permission'] = $permission[0]; 
     625                    } 
     626                } 
     627                //TODO - Padronizar retorno do deepness 
     628                if (isset($v['user'])) 
     629                    $result[$i]['user'] = Controller::read(array('concept' => 'user', 'id' => $v['user']), false, false); 
     630            } 
     631        } 
     632    } 
     633 
    679634//Decode Find        
    680     public function decodeFindConcept( &$uri , &$result , &$criteria , $original ){              
    681         if($result && is_array($result) )  
    682         { 
    683             $m = array_flip(self::${$uri['concept'].'Map'}); 
    684             $new = array(); 
    685             foreach ($result as $i => $v) 
    686                 $new[$i] = self::parseConcept( $result[$i] , $m ); 
    687  
    688  
    689             $result = $new; 
    690         } 
    691     } 
    692      
    693     public function decodeFindSchedulable( &$uri , &$result , &$criteria , $original ){          
    694         if($result && is_array($result) )  
    695         { 
    696             $m = array_flip(self::${$uri['concept'].'Map'}); 
    697             $m['calendar_id'] = 'calendar'; 
    698             $new = array(); 
    699             foreach ($result as $i => $v) 
    700                 $new[$i] = self::parseConcept( $result[$i] , $m ); 
    701  
    702  
    703             $result = $new; 
    704         } 
    705     } 
    706  
    707     public function decodeFindAttachment( &$uri , &$result , &$criteria , $original ){           
    708                 if(isset($result)) 
    709                 foreach($result as $key => &$value) 
    710                         $value['source'] = base64_decode($value['source']); 
    711     } 
    712  
    713          
    714         public function decodeSignatureAlarmType( &$uri , &$result , &$criteria , $original ){   
    715             if( is_array($result) ) 
    716             foreach($result as &$param) 
    717                 if(isset($param['type'])) 
    718                     $param['type'] = self::decodeAlarmType($param['type']); 
    719          
    720     } 
    721          
     635    public function decodeFindConcept(&$uri, &$result, &$criteria, $original) { 
     636        if ($result && is_array($result)) { 
     637            $m = array_flip(self::${$uri['concept'] . 'Map'}); 
     638            $new = array(); 
     639            foreach ($result as $i => $v) 
     640                $new[$i] = self::parseConcept($result[$i], $m); 
     641 
     642 
     643            $result = $new; 
     644        } 
     645    } 
     646 
     647    public function decodeFindSchedulable(&$uri, &$result, &$criteria, $original) { 
     648        if ($result && is_array($result)) { 
     649            $m = array_flip(self::${$uri['concept'] . 'Map'}); 
     650            $m['calendar_id'] = 'calendar'; 
     651            $new = array(); 
     652            foreach ($result as $i => $v) 
     653                $new[$i] = self::parseConcept($result[$i], $m); 
     654 
     655 
     656            $result = $new; 
     657        } 
     658    } 
     659 
     660    public function decodeFindAttachment(&$uri, &$result, &$criteria, $original) { 
     661        if (isset($result)) 
     662            foreach ($result as $key => &$value) 
     663                $value['source'] = base64_decode($value['source']); 
     664    } 
     665 
     666    public function decodeSignatureAlarmType(&$uri, &$result, &$criteria, $original) { 
     667        if (is_array($result)) 
     668            foreach ($result as &$param) 
     669                if (isset($param['type'])) 
     670                    $param['type'] = self::decodeAlarmType($param['type']); 
     671    } 
     672 
    722673///////////////////////////////////////////////////////////////////////// 
    723      
    724     static function dayAlarm( &$uri , &$params , &$criteria , $original ) {      
    725         if(isset($criteria['filter'][1]) && $criteria['filter'][1] == 'date') 
    726         { 
    727             $filter = array( 'AND',  
    728                       array( '='  , 'sent' , '0') ,   
    729                       array( '='  , 'type' ,  ALARM_ALERT) ,   
    730                       array( '>=' , 'rangeStart' , $criteria['filter'][2]) , 
    731                       array( '<=' , 'rangeEnd' , $criteria['filter'][2] + 86400000) );  
    732  
    733             //Busca os Alarmes no Range 
    734             $al = Controller::find( array('concept' => 'alarm'), false ,array( 'filter' => $filter)); 
    735              
    736             if(is_array($al)) 
    737             foreach ($al as $i => $v) 
    738             { 
    739                 $ev =  Controller::read( array( 'concept' => 'schedulable' , 'id' => $v['schedulable']) ) ; 
    740  
    741                 $unit = 0; 
    742                 switch (strtolower($v['unit'])) { 
    743                         case 'm': $unit = 60; break; 
    744                         case 'H': $unit = 3600; break; 
    745                         case 'd': $unit = 216000; break; } 
    746                  
    747                   $al[$i]['sendTime'] = (((int)( $ev['startTime'] / 1000 )) - ( $v['time'] * $unit )); 
    748                   $al[$i]['schedulable'] =   $ev; 
    749                          
    750             } 
    751              
    752             $params = $al; 
    753             return false; 
    754         } 
    755     }  
    756  
    757     public function deleteSchedulable( &$uri , &$params , &$criteria , $original ){ 
    758  
    759        if(Config::module('useCaldav' , 'expressoCalendar')) 
    760             require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php'; 
    761  
    762         $calendarsToSchedulable = self::schedulable2calendarToObject($uri['id']); 
    763          
    764         if( !self::ownerSchedulable($uri['id']) && !self::isAllowDeleteInCalendar($calendarsToSchedulable[0]['calendar_id'])) 
    765         { 
    766              
    767              foreach ($calendarsToSchedulable as $i => $v) 
    768              { 
    769                    Controller::delete(array('concept' => 'calendarToSchedulable' , 'id' => $v['calendar_to_calendar_object'])); 
    770                     
    771                    if(Config::module('useCaldav' , 'expressoCalendar')) 
    772                         DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location'])); 
    773              } 
    774               
    775              /* Seta o participante como rejeitado */ 
    776              Controller::update(array('concept' => 'participant'), array('status' => STATUS_CANCELLED) ,  
    777              array('filter' =>  
    778                  array('AND', 
    779                         array('=' , 'user'  ,Config::me('uidNumber') ), 
    780                         array('=' , 'schedulable'  , $uri['id'] ) 
    781                      ))); 
    782              
    783             return false; /* Mata o restante da execução */ 
    784         }  
    785                  
    786         if(Config::module('useCaldav' , 'expressoCalendar')) 
    787             foreach ($calendarsToSchedulable as $i => $v) 
    788                 DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location'])); 
    789  
    790      } 
    791       
    792       
    793     public function deleteCalendarToPermissionDependences( &$uri , &$params , &$criteria , $original ){ 
    794         $permission = Controller::read($uri, array('user','calendar')); 
    795  
    796         $calendarSignature = Controller::find( array( 'concept' => 'calendarSignature' ) , array('id') ,array( 'filter' => array('AND', array('=','calendar', $permission['calendar']), array('=','user',$permission['user']), array('=','isOwner','0'))));  
    797  
    798         if($calendarSignature) 
     674 
     675    static function dayAlarm(&$uri, &$params, &$criteria, $original) { 
     676        if (isset($criteria['filter'][1]) && $criteria['filter'][1] == 'date') { 
     677            $filter = array('AND', 
     678                array('=', 'sent', '0'), 
     679                array('=', 'type', ALARM_ALERT), 
     680                array('>=', 'rangeStart', $criteria['filter'][2]), 
     681                array('<=', 'rangeEnd', $criteria['filter'][2] + 86400000)); 
     682 
     683            //Busca os Alarmes no Range 
     684            $al = Controller::find(array('concept' => 'alarm'), false, array('filter' => $filter)); 
     685 
     686            if (is_array($al)) 
     687                foreach ($al as $i => $v) { 
     688                    $ev = Controller::read(array('concept' => 'schedulable', 'id' => $v['schedulable'])); 
     689 
     690                    $unit = 0; 
     691                    switch (strtolower($v['unit'])) { 
     692                        case 'm': $unit = 60; 
     693                            break; 
     694                        case 'H': $unit = 3600; 
     695                            break; 
     696                        case 'd': $unit = 216000; 
     697                            break; 
     698                    } 
     699 
     700                    $al[$i]['sendTime'] = (((int) ( $ev['startTime'] / 1000 )) - ( $v['time'] * $unit )); 
     701                    $al[$i]['schedulable'] = $ev; 
     702                } 
     703 
     704            $params = $al; 
     705            return false; 
     706        } 
     707    } 
     708 
     709    public function deleteSchedulable(&$uri, &$params, &$criteria, $original) { 
     710 
     711        if (Config::module('useCaldav', 'expressoCalendar')) 
     712            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php'; 
     713 
     714        $calendarsToSchedulable = self::schedulable2calendarToObject($uri['id']); 
     715 
     716        if (!self::ownerSchedulable($uri['id']) && !self::isAllowDeleteInCalendar($calendarsToSchedulable[0]['calendar_id'])) { 
     717 
     718            foreach ($calendarsToSchedulable as $i => $v) { 
     719                Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $v['calendar_to_calendar_object'])); 
     720 
     721                if (Config::module('useCaldav', 'expressoCalendar')) 
     722                    DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location'])); 
     723            } 
     724 
     725            /* Seta o participante como rejeitado */ 
     726            Controller::update(array('concept' => 'participant'), array('status' => STATUS_CANCELLED), array('filter' => 
     727                array('AND', 
     728                    array('=', 'user', Config::me('uidNumber')), 
     729                    array('=', 'schedulable', $uri['id']) 
     730                    ))); 
     731 
     732            return false; /* Mata o restante da execução */ 
     733        } 
     734 
     735        if (Config::module('useCaldav', 'expressoCalendar')) 
     736            foreach ($calendarsToSchedulable as $i => $v) 
     737                DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location'])); 
     738    } 
     739 
     740    public function deleteCalendarToPermissionDependences(&$uri, &$params, &$criteria, $original) { 
     741        $permission = Controller::read($uri, array('user', 'calendar')); 
     742 
     743        $calendarSignature = Controller::find(array('concept' => 'calendarSignature'), array('id'), array('filter' => array('AND', array('=', 'calendar', $permission['calendar']), array('=', 'user', $permission['user']), array('=', 'isOwner', '0')))); 
     744 
     745        if ($calendarSignature) 
    799746            Controller::delete(array('concept' => 'calendarSignature', 'id' => $calendarSignature[0]['id'])); 
    800747    } 
    801748 
    802     public function deleteCalendarSignatureDependences( &$uri , &$params , &$criteria , $original ){ 
    803          $signature = Controller::read($uri,array('isOwner','calendar')); 
    804              
    805         if($signature['isOwner'] == '1') 
    806         { 
    807            $calendarToSchedulables = Controller::find(array('concept' => 'calendarToSchedulable') , null , array('filter' => array('=' , 'calendar' , $signature['calendar'] ))); 
    808             
    809            $schedulables = array(); 
    810            if(is_array($calendarToSchedulables)) 
    811            foreach ($calendarToSchedulables as $key => $calendarToSchedulable)  
    812                  $schedulables[] = $calendarToSchedulable['schedulable'] ;  
    813              
    814            if( !empty( $schedulables ) ) 
    815               Controller::deleteALL(array('concept' => 'schedulable'),null , array('filter' => array('IN' , 'id' , $schedulables))); 
    816  
    817            Controller::delete(array('concept' => 'calendar', 'id' => $signature['calendar'])); 
    818         } 
    819          
    820      }  
    821           
    822         public function deleteAttachmentDependences( &$uri , &$params , &$criteria , $original ){ 
    823  
    824                 if(isset($original['URI']['id'])) 
    825                         Controller::delete(array('concept' => 'schedulableToAttachment', null , array('filter' => array('=' , 'attachment' , $original['URI']['id'])))); 
    826     } 
    827  
    828     public function createDefaultSignature( &$uri , &$result , &$criteria , $original ){ 
     749    public function deleteCalendarSignatureDependences(&$uri, &$params, &$criteria, $original) { 
     750        $signature = Controller::read($uri, array('isOwner', 'calendar')); 
     751 
     752        if ($signature['isOwner'] == '1') { 
     753            $calendarToSchedulables = Controller::find(array('concept' => 'calendarToSchedulable'), null, array('filter' => array('=', 'calendar', $signature['calendar']))); 
     754 
     755            $schedulables = array(); 
     756            if (is_array($calendarToSchedulables)) 
     757                foreach ($calendarToSchedulables as $key => $calendarToSchedulable) 
     758                    $schedulables[] = $calendarToSchedulable['schedulable']; 
     759 
     760            if (!empty($schedulables)) 
     761                Controller::deleteALL(array('concept' => 'schedulable'), null, array('filter' => array('IN', 'id', $schedulables))); 
     762 
     763            Controller::delete(array('concept' => 'calendar', 'id' => $signature['calendar'])); 
     764        } 
     765    } 
     766 
     767    public function deleteAttachmentDependences(&$uri, &$params, &$criteria, $original) { 
     768 
     769        if (isset($original['URI']['id'])) 
     770            Controller::delete(array('concept' => 'schedulableToAttachment', null, array('filter' => array('=', 'attachment', $original['URI']['id'])))); 
     771    } 
     772 
     773    public function createDefaultSignature(&$uri, &$result, &$criteria, $original) { 
    829774 
    830775        //Caso uma busca não retorne nenhum resultado e foi buscado pelas assinaturas do usuario logado apenas 
     
    832777 
    833778        //Veirifica pois o usuário pode ter varias assinaturas mas não ser dona de nenhuma 
    834         if(count($result) > 0){ 
    835             foreach($result as $key){    
    836                 if($key['isOwner'] != 0) 
     779        if (count($result) > 0) { 
     780            foreach ($result as $key) { 
     781                if ($key['isOwner'] != 0) 
    837782                    $isValidSignature = true; 
    838783            } 
    839784        } 
    840785 
    841     if(!$isValidSignature &&  
    842             ( $original['criteria']['filter'][1][0] == '=' && 
    843               $original['criteria']['filter'][1][1] == 'user' && 
    844               $original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id'] 
    845             )) 
    846     {         
    847          
    848         if( Config::module('useCaldav' , 'expressoCalendar') ) 
    849         { 
    850             require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php'; 
    851              
    852             $calendario = DAViCalAdapter::findCalendars(); 
    853         } 
    854          
    855         if( Config::module('useCaldav' , 'expressoCalendar') && is_array($calendario) && count($calendario) > 0) 
    856         {      
    857             foreach ($calendario as $i => $v) 
    858             { 
    859                  
    860                 $urlA = explode('/', $v->url); 
    861                 $name = isset($v->displayname)? $v->displayname : $urlA[ (count($urlA)-2) ]; 
    862                 $cal = array('name' => $name, 
    863                              'description' =>  isset($v->description)? $v->description : $name, 
    864                              'timezone' => isset($v->timezone) ? $v->timezone : (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo', 
    865                              'dtstamp' => time().'000', 
    866                              'location' => $urlA[ (count($urlA)-3) ].'/'.$urlA[ (count($urlA)-2) ] 
    867                             ); 
    868  
    869                 $calCreated =  Controller::create( array('concept' => 'calendar') , $cal );   
    870                  
    871                  
    872  
    873                 $sig = array( 'user' => $_SESSION['wallet']['user']['uidNumber'], 
    874                                   'calendar' => $calCreated['id'], 
    875                                   'isOwner' => '1', 
    876                                   'dtstamp' => time().'000', 
    877                                   'fontColor' => 'FFFFFF', 
    878                                   'backgroundColor' => '3366CC', 
    879                                   'borderColor' => '3366CC', 
    880                                 ); 
    881  
    882                 $sigCreated =  Controller::create( array('concept' => 'calendarSignature') , $sig ); 
    883                 
    884    
    885                DAViCalAdapter::importCollection($v->url , $calCreated['id']); 
    886               
    887             } 
    888         } 
    889         else 
    890         { 
    891          //Criaremos uma agenda padrão 
    892           $cal = array('name' => 'Calendario', 
    893                          'description' => 'Calendario Padrão', 
    894                          'timezone' =>  (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo', 
    895                          'dtstamp' => time().'000' 
    896                         );  
    897            
    898           $calCreated =  Controller::create( array('concept' => 'calendar') , $cal );   
    899            
    900           $sig = array( 'user' => $_SESSION['wallet']['user']['uidNumber'], 
    901                           'calendar' => $calCreated['id'], 
    902                           'isOwner' => '1', 
    903                           'dtstamp' => time().'000', 
    904                           'fontColor' => 'FFFFFF', 
    905                           'backgroundColor' => '3366CC', 
    906                           'borderColor' => '3366CC', 
    907                         ); 
    908              
    909           $sigCreated =  Controller::create( array('concept' => 'calendarSignature') , $sig ); 
    910         } 
    911          
    912         $result = Controller::find($original['URI'] , $original['properties'] ? $original['properties'] : null , $original['criteria']  ); 
    913         return false;   
    914     } 
    915      
     786        if (!$isValidSignature && 
     787                ( $original['criteria']['filter'][1][0] == '=' && 
     788                $original['criteria']['filter'][1][1] == 'user' && 
     789                $original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id'] 
     790                )) { 
     791 
     792            if (Config::module('useCaldav', 'expressoCalendar')) { 
     793                require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php'; 
     794 
     795                $calendario = DAViCalAdapter::findCalendars(); 
     796            } 
     797 
     798            if (Config::module('useCaldav', 'expressoCalendar') && is_array($calendario) && count($calendario) > 0) { 
     799                foreach ($calendario as $i => $v) { 
     800 
     801                    $urlA = explode('/', $v->url); 
     802                    $name = isset($v->displayname) ? $v->displayname : $urlA[(count($urlA) - 2)]; 
     803                    $cal = array('name' => $name, 
     804                        'description' => isset($v->description) ? $v->description : $name, 
     805                        'timezone' => isset($v->timezone) ? $v->timezone : (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo', 
     806                        'dtstamp' => time() . '000', 
     807                        'location' => $urlA[(count($urlA) - 3)] . '/' . $urlA[(count($urlA) - 2)] 
     808                    ); 
     809 
     810                    $calCreated = Controller::create(array('concept' => 'calendar'), $cal); 
     811 
     812 
     813 
     814                    $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'], 
     815                        'calendar' => $calCreated['id'], 
     816                        'isOwner' => '1', 
     817                        'dtstamp' => time() . '000', 
     818                        'fontColor' => 'FFFFFF', 
     819                        'backgroundColor' => '3366CC', 
     820                        'borderColor' => '3366CC', 
     821                    ); 
     822 
     823                    $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig); 
     824 
     825 
     826                    DAViCalAdapter::importCollection($v->url, $calCreated['id']); 
     827                } 
     828            } else { 
     829                //Criaremos uma agenda padrão 
     830                $cal = array('name' => 'Calendario', 
     831                    'description' => 'Calendario Padrão', 
     832                    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo', 
     833                    'dtstamp' => time() . '000' 
     834                ); 
     835 
     836                $calCreated = Controller::create(array('concept' => 'calendar'), $cal); 
     837 
     838                $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'], 
     839                    'calendar' => $calCreated['id'], 
     840                    'isOwner' => '1', 
     841                    'dtstamp' => time() . '000', 
     842                    'fontColor' => 'FFFFFF', 
     843                    'backgroundColor' => '3366CC', 
     844                    'borderColor' => '3366CC', 
     845                ); 
     846 
     847                $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig); 
     848            } 
     849 
     850            $result = Controller::find($original['URI'], $original['properties'] ? $original['properties'] : null, $original['criteria']); 
     851            return false; 
     852        } 
     853    } 
     854 
     855    //TODO - Criar conceito separado para participantes externos e remover o criterio notExternal 
     856    public function findExternalPaticipants(&$uri, &$result, &$criteria, $original) { 
     857        if (Config::me('uidNumber') && !isset($criteria['notExternal'])) { 
     858            $newuri['concept'] = 'user'; 
     859            $newuri['service'] = 'PostgreSQL'; 
     860 
     861            $newCriteria = $original['criteria']; 
     862            $valid = true; 
     863 
     864            $newCriteria['filter'] = array('AND', $newCriteria['filter'], array('=', 'owner', Config::me('uidNumber'))); 
     865            $externalUsers = Controller::find($newuri, $original['properties'] ? $original['properties'] : null, $newCriteria); 
     866 
     867            if (is_array($externalUsers)) { 
     868                foreach ($externalUsers as $i => $v) 
     869                    $externalUsers[$i]['isExternal'] = '1'; 
     870            } 
     871            else 
     872                $externalUsers = array(); 
     873 
     874            if (!is_array($result)) 
     875                $result = array(); 
     876 
     877            return array_merge($result, $externalUsers); 
     878        } 
     879    } 
     880 
     881    public function davcalCreateCollection(&$uri, &$params, &$criteria, $original) { 
     882        if (Config::module('useCaldav', 'expressoCalendar')) { 
     883            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php'; 
     884            DAViCalAdapter::mkcalendar($params['location'], $params['name'], isset($params['description']) ? $params['description'] : '' ); 
     885        } 
     886    } 
     887 
     888    public function davcalDeleteCollection(&$uri, &$params, &$criteria, $original) { 
     889        if (Config::module('useCaldav', 'expressoCalendar') && Config::module('onRemoveCascadeCalDav')) { 
     890            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php'; 
     891            $calendar = Controller::read($uri); 
     892            DAViCalAdapter::rmCalendar($calendar['location']); 
     893        } 
     894    } 
     895 
     896    public function davcalUpdateCollection(&$uri, &$params, &$criteria, $original) { 
     897        if (Config::module('useCaldav', 'expressoCalendar')) { 
     898            require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php'; 
     899            if (isset($params['location'])) { 
     900                $calendar = Controller::read($uri); 
     901                if ($calendar['location'] !== $params['location']) 
     902                    DAViCalAdapter::mvcalendar($calendar['location'], $params['location']); 
     903            } 
     904        } 
     905    } 
     906 
     907    private function _makeUid() { 
     908 
     909        $date = date('Ymd\THisT'); 
     910        $unique = substr(microtime(), 2, 4); 
     911        $base = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPrRsStTuUvVxXuUvVwWzZ1234567890'; 
     912        $start = 0; 
     913        $end = strlen($base) - 1; 
     914        $length = 6; 
     915        $str = null; 
     916        for ($p = 0; $p < $length; $p++) 
     917            $unique .= $base{mt_rand($start, $end)}; 
     918 
     919        return $date . $unique . '@expresso-calendar'; 
     920    } 
     921 
     922    private function getStatus($id) { 
     923        $a = array( 
     924            STATUS_CONFIRMED => 'CONFIRMED', 
     925            STATUS_CANCELLED => 'CANCELLED', 
     926            STATUS_TENATIVE => 'TENATIVE', 
     927            STATUS_UNANSWERED => 'NEEDS-ACTION', 
     928            STATUS_DELEGATED => 'DELEGATED' 
     929        ); 
     930        return $a[$id]; 
     931    } 
     932 
     933    private static function decodeAlarmType($id) { 
     934        $a = array(ALARM_ALERT => 'alert', 
     935            ALARM_MAIL => 'mail', 
     936            ALARM_SMS => 'sms'); 
     937 
     938        return $a[$id]; 
     939    } 
     940 
     941    private static function codeAlarmType($type) { 
     942        $a = array('alert' => ALARM_ALERT, 
     943            'mail' => ALARM_MAIL, 
     944            'sms' => ALARM_SMS); 
     945 
     946        return $a[$type]; 
     947    } 
     948 
     949    private static function codeAlarmUnit($u) { 
     950        if ($u === 'd') 
     951            return 'days'; 
     952        if ($u === 'm') 
     953            return 'minutes'; 
     954        if ($u === 'H') 
     955            return 'hours'; 
     956    } 
     957 
     958    private static function ownerSchedulable($id) { 
     959 
     960        $isOwner = Controller::find(array('concept' => 'participant'), array('id'), array('filter' => 
     961                    array('AND', 
     962                        array('=', 'isOrganizer', '1'), 
     963                        array('=', 'user', $_SESSION['wallet']['user']['uidNumber']), 
     964                        array('=', 'schedulable', $id) 
     965                        ))); 
     966 
     967        return ( isset($isOwner[0]['id']) ) ? true : false; 
     968    } 
     969 
     970    private static function schedulable2calendarToObject($Schedulable) { 
     971        return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object , calendar.name as calendar_name ,calendar.location as calendar_location, calendar.id as calendar_id FROM calendar_to_calendar_object , calendar , calendar_signature' 
     972                        . ' WHERE calendar_signature.user_uidnumber = ' . $_SESSION['wallet']['user']['uidNumber'] 
     973                        //      .' AND calendar_signature.is_owner = 1' 
     974                        . ' AND calendar_signature.calendar_id = calendar.id' 
     975                        . ' AND calendar_to_calendar_object.calendar_id = calendar.id' 
     976                        . ' AND calendar_to_calendar_object.calendar_object_id = ' . addslashes($Schedulable)); 
     977    } 
     978 
     979    protected static function isAllowDeleteInCalendar($calendar) { 
     980        $f = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'user', Config::me('uidNumber')), array('=', 'calendar', $calendar)))); 
     981        return (strpos($f[0]['acl'], CALENDAR_ACL_REMOVE) === false) ? false : true; 
     982    } 
     983 
    916984} 
    917     //TODO - Criar conceito separado para participantes externos e remover o criterio notExternal 
    918     public function findExternalPaticipants( &$uri , &$result , &$criteria , $original ) { 
    919         if(Config::me('uidNumber') && !isset($criteria['notExternal'])) 
    920         { 
    921             $newuri['concept'] = 'user'; 
    922             $newuri['service'] = 'PostgreSQL'; 
    923             
    924             $newCriteria = $original['criteria']; 
    925             $valid = true; 
    926              
    927             $newCriteria['filter'] = array('AND',$newCriteria['filter'] , array('=' , 'owner', Config::me('uidNumber')) );         
    928             $externalUsers = Controller::find( $newuri , $original['properties'] ? $original['properties'] : null , $newCriteria ); 
    929              
    930             if(is_array($externalUsers)) 
    931             { 
    932                  foreach ($externalUsers as $i => $v) 
    933                     $externalUsers[$i]['isExternal'] = '1'; 
    934             } 
    935             else 
    936                 $externalUsers = array(); 
    937  
    938             if(!is_array($result)) 
    939                 $result = array(); 
    940  
    941             return array_merge($result, $externalUsers);     
    942         } 
    943         
    944     } 
    945  
    946     public function davcalCreateCollection( &$uri , &$params , &$criteria , $original ){         
    947         if( Config::module('useCaldav' , 'expressoCalendar') ) 
    948         { 
    949            require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php'; 
    950            DAViCalAdapter::mkcalendar($params['location'] , $params['name'], isset($params['description']) ? $params['description'] : '' ); 
    951         } 
    952     } 
    953      
    954    public function davcalDeleteCollection( &$uri , &$params , &$criteria , $original ){  
    955         if( Config::module('useCaldav' , 'expressoCalendar') &&  Config::module('onRemoveCascadeCalDav')) 
    956         { 
    957            require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php'; 
    958            $calendar = Controller::read($uri); 
    959            DAViCalAdapter::rmCalendar($calendar['location']); 
    960         } 
    961     } 
    962          
    963    public function davcalUpdateCollection( &$uri , &$params , &$criteria , $original ){  
    964         if( Config::module('useCaldav' , 'expressoCalendar') ) 
    965         { 
    966            require_once ROOTPATH.'/modules/calendar/interceptors/DAViCalAdapter.php'; 
    967            if(isset($params['location'])) 
    968            { 
    969                 $calendar = Controller::read($uri); 
    970                 if($calendar['location'] !== $params['location']) 
    971                     DAViCalAdapter::mvcalendar($calendar['location'], $params['location']); 
    972            } 
    973         } 
    974     } 
    975  
    976     private function _makeUid() { 
    977  
    978             $date   = date('Ymd\THisT'); 
    979             $unique = substr(microtime(), 2, 4); 
    980             $base   = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPrRsStTuUvVxXuUvVwWzZ1234567890'; 
    981             $start  = 0; 
    982             $end    = strlen( $base ) - 1; 
    983             $length = 6; 
    984             $str    = null; 
    985             for( $p = 0; $p < $length; $p++ ) 
    986               $unique .= $base{mt_rand( $start, $end )}; 
    987  
    988             return $date.$unique.'@expresso-calendar'; 
    989     } 
    990     private function getStatus( $id ){ 
    991              $a = array( 
    992                                             STATUS_CONFIRMED =>  'CONFIRMED', 
    993                                             STATUS_CANCELLED =>  'CANCELLED', 
    994                                             STATUS_TENATIVE =>   'TENATIVE', 
    995                                             STATUS_UNANSWERED => 'NEEDS-ACTION', 
    996                                             STATUS_DELEGATED =>  'DELEGATED' 
    997                                             ); 
    998              return $a[ $id ]; 
    999     } 
    1000     private static function decodeAlarmType( $id ){ 
    1001              $a = array(        ALARM_ALERT =>  'alert', 
    1002                                 ALARM_MAIL =>  'mail', 
    1003                                 ALARM_SMS =>   'sms' ); 
    1004  
    1005              return $a[ $id ]; 
    1006     } 
    1007     private static function codeAlarmType( $type ){ 
    1008              $a = array(        'alert' => ALARM_ALERT  , 
    1009                                 'mail' => ALARM_MAIL   , 
    1010                                 'sms' => ALARM_SMS   ); 
    1011  
    1012              return $a[ $type ]; 
    1013     } 
    1014     private static function codeAlarmUnit( $u ){ 
    1015                 if($u === 'd') return 'days'; 
    1016                 if($u === 'm') return 'minutes'; 
    1017                 if($u === 'H') return 'hours'; 
    1018         }    
    1019    
    1020     private static function ownerSchedulable( $id ){ 
    1021          
    1022        $isOwner = Controller::find(array('concept' => 'participant'), array('id') ,  
    1023              array('filter' =>  
    1024                  array('AND',  
    1025                         array('=' , 'isOrganizer' , '1'), 
    1026                         array('=' , 'user'  ,$_SESSION['wallet']['user']['uidNumber'] ), 
    1027                         array('=' , 'schedulable'  ,$id ) 
    1028                      ))); 
    1029         
    1030         return ( isset( $isOwner[0]['id'] ) ) ? true : false;  
    1031     } 
    1032  
    1033     private static function schedulable2calendarToObject($Schedulable) 
    1034     { 
    1035       return Controller::service('PostgreSQL')->execResultSql('SELECT calendar_to_calendar_object.id as calendar_to_calendar_Object , calendar.name as calendar_name ,calendar.location as calendar_location, calendar.id as calendar_id FROM calendar_to_calendar_object , calendar , calendar_signature'  
    1036                 .' WHERE calendar_signature.user_uidnumber = '.$_SESSION['wallet']['user']['uidNumber'] 
    1037           //      .' AND calendar_signature.is_owner = 1' 
    1038                 .' AND calendar_signature.calendar_id = calendar.id' 
    1039                 .' AND calendar_to_calendar_object.calendar_id = calendar.id' 
    1040                 .' AND calendar_to_calendar_object.calendar_object_id = '.addslashes($Schedulable)); 
    1041     } 
    1042                  
    1043     protected static function isAllowDeleteInCalendar( $calendar ) { 
    1044          $f = Controller::find(array('concept' => 'calendarToPermission') , false , array('filter' => array('AND' , array('=', 'user' , Config::me('uidNumber') ) , array('=', 'calendar' , $calendar))));        
    1045          return (strpos($f[0]['acl'], CALENDAR_ACL_REMOVE) === false) ? false : true;         
    1046     } 
    1047      
    1048 } 
    1049985 
    1050986?> 
  • trunk/prototype/modules/calendar/js/calendar.codecs.js

    r5953 r6066  
    22   
    33    init: function(){ 
    4                 this.moduleName = 'expressoCalendar';  
    5                 this.me = DataLayer.dispatch( "me" ); 
    6                  
    7                  
    8                 this.timezones = Timezone.timezones; 
    9                 this.isDaylightSaving = Timezone.daylightSaving; 
    10                 this.load();       
     4        this.moduleName = 'expressoCalendar';  
     5        this.me = DataLayer.dispatch( "me" ); 
     6                 
     7                 
     8        this.timezones = Timezone.timezones; 
     9        this.isDaylightSaving = Timezone.daylightSaving; 
     10        this.load();       
    1111    },              
    1212   
    1313    load: function(){ 
    1414 
    15                 var defaultPreferences = { dateFormat: "dd/MM/yyyy", 
    16                         hourFormat: "HH:mm", 
    17                         defaultCalView: "month", 
    18                         defaultDuration: 30, 
    19                         backgroundColor: "36C", 
    20                         borderColor: "36C", 
    21                         fontColor: "fff", 
    22                         timezone: 'America/Sao_Paulo', 
    23                         weekStart: 'SUN' 
    24                   }; 
    25  
    26                 var pref = DataLayer.get( "modulePreference:detail", ['and',[ "=", "user", this.me.id ], [ "=", "module", this.moduleName ]] ); 
    27  
    28                 this.preferences = DataLayer.merge( defaultPreferences, pref.values || {} ); 
    29                 this.preferenceIds = pref.ids; 
     15        var defaultPreferences = { 
     16            dateFormat: "dd/MM/yyyy", 
     17            hourFormat: "HH:mm", 
     18            defaultCalView: "month", 
     19            defaultDuration: 30, 
     20            backgroundColor: "36C", 
     21            borderColor: "36C", 
     22            fontColor: "fff", 
     23            timezone: 'America/Sao_Paulo', 
     24            weekStart: 'SUN' 
     25        }; 
     26 
     27        var pref = DataLayer.get( "modulePreference:detail", ['and',[ "=", "user", this.me.id ], [ "=", "module", this.moduleName ]] ); 
     28 
     29        this.preferences = DataLayer.merge( defaultPreferences, pref.values || {} ); 
     30        this.preferenceIds = pref.ids; 
    3031    } 
    3132} 
    3233 
    3334constantsParticipant = { 
    34         'o' : 'organization', 
    35         'w' : 'write', 
    36         'p' : 'participationRequired', 
    37         'i' : 'inviteGuests', 
    38         'r' : 'read' 
     35    'o' : 'organization', 
     36    'w' : 'write', 
     37    'p' : 'participationRequired', 
     38    'i' : 'inviteGuests', 
     39    'r' : 'read' 
    3940} 
    4041 
    4142constantsCalendarShared = { 
    42         'r' : 'read', 
    43         'w' : 'write', 
    44         'd' : 'remove', 
    45         'b' : 'busy', 
    46         's' : 'shared', 
    47         'p' : 'required' 
     43    'r' : 'read', 
     44    'w' : 'write', 
     45    'd' : 'remove', 
     46    'b' : 'busy', 
     47    's' : 'shared', 
     48    'p' : 'required' 
    4849} 
    4950 
    5051UI = { 
    51         dialogs: { 
    52                 addEvent: null, 
    53                 importCalendar: null, 
    54                 sharedCalendar: null, 
    55                 copyCalendar: null 
    56         } 
     52    dialogs: { 
     53        addEvent: null, 
     54        importCalendar: null, 
     55        sharedCalendar: null, 
     56        copyCalendar: null 
     57    } 
    5758} 
    5859 
    5960DataLayer.codec( "calendarSignature", "calendar", { 
    6061   
    61         decoder: function(){}, 
     62    decoder: function(){}, 
    6263       
    63         encoder: function( signatures ){ 
    64                 return $.map( signatures, function( signature ){ 
    65                         return { events: function( start, end, callback ){ 
    66                                 var viewKey = start + ':' + end; 
    67                                 if( Calendar.currentViewKey !== viewKey ){ 
    68                                     Calendar.currentViewKey = viewKey; 
    69                                     Calendar.currentView = DataLayer.get( 'schedulable:calendar', { start: start, end: end } ); 
    70                                 } 
    71                                 var view = Calendar.currentView[ signature.calendar.id ]; 
    72                                 callback( view && !view.hidden ? view : [] ); 
    73                            }, 
    74  
    75                            backgroundColor: '#' + signature.backgroundColor || User.preferences.backgroundColor, 
    76                            borderColor: '#' + signature.borderColor || User.preferences.borderColor, 
    77                            textColor: '#' + signature.fontColor || User.preferences.fontColor, 
    78                            editable:  signature.isOwner } 
    79                }); 
    80       } 
     64    encoder: function( signatures ){ 
     65        return $.map( signatures, function( signature ){ 
     66            return { 
     67                events: function( start, end, callback ){ 
     68                    var viewKey = start + ':' + end; 
     69                    if( Calendar.currentViewKey !== viewKey ){ 
     70                        Calendar.currentViewKey = viewKey; 
     71                        Calendar.currentView = DataLayer.get( 'schedulable:calendar', { 
     72                            start: start,  
     73                            end: end 
     74                        } ); 
     75                    } 
     76                    var view = Calendar.currentView[ signature.calendar.id ]; 
     77                    callback( view && !view.hidden ? view : [] ); 
     78                }, 
     79 
     80                backgroundColor: '#' + signature.backgroundColor || User.preferences.backgroundColor, 
     81                borderColor: '#' + signature.borderColor || User.preferences.borderColor, 
     82                textColor: '#' + signature.fontColor || User.preferences.fontColor, 
     83                editable:  signature.isOwner 
     84                } 
     85        }); 
     86    } 
    8187 
    8288       
     
    8490 
    8591DataLayer.codec( "calendarToPermission", "detail", { 
    86         decoder: function( evtObj ){ 
    87 /*              Encoder.EncodeType = "entity"; 
     92    decoder: function( evtObj ){ 
     93    /*          Encoder.EncodeType = "entity"; 
    8894                 
    8995                if( notArray = $.type(evtObj) !== "array" ) 
     
    103109        return notArray ? res[0] : res; 
    104110        */ 
    105         }, 
     111    }, 
    106112 
    107113    encoder: function( evtObj ){ 
    108114         
    109                 if(evtObj == "") 
    110                         return ""; 
     115        if(evtObj == "") 
     116            return ""; 
    111117                         
    112                 var notArray = false; 
     118        var notArray = false; 
    113119                   
    114                 if( notArray = $.type(evtObj) !== "array" ) 
    115                         evtObj = [ evtObj ]; 
    116                  
    117                 var constantAcl = function(acl){ 
    118                         var returns = {}; 
    119                         for (var i in constantsCalendarShared){ 
    120                                 returns[constantsCalendarShared[i]] = acl.indexOf(i) >= 0 ? true : false 
    121                         } 
    122                         return returns; 
    123                 }; 
    124  
    125                 var res = $.map(evtObj, function( objEvent ){                    
    126                         return { 
    127                             id: objEvent.id, 
    128                             type: objEvent.type, 
    129                             calendar: objEvent.calendar, 
    130                             user: objEvent.user, 
    131                                 acl: constantAcl(objEvent.acl)  , 
    132                                 aclValues: objEvent.acl 
    133                         }; 
    134                 });      
     120        if( notArray = $.type(evtObj) !== "array" ) 
     121            evtObj = [ evtObj ]; 
     122                 
     123        var constantAcl = function(acl){ 
     124            var returns = {}; 
     125            for (var i in constantsCalendarShared){ 
     126                returns[constantsCalendarShared[i]] = acl.indexOf(i) >= 0 ? true : false 
     127            } 
     128            return returns; 
     129        }; 
     130 
     131        var res = $.map(evtObj, function( objEvent ){                    
     132            return { 
     133                id: objEvent.id, 
     134                type: objEvent.type, 
     135                calendar: objEvent.calendar, 
     136                user: objEvent.user, 
     137                acl: constantAcl(objEvent.acl)  , 
     138                aclValues: objEvent.acl 
     139            }; 
     140        });      
    135141        return notArray ? res[0] : res; 
    136         } 
     142    } 
    137143}); 
    138144 
     
    140146Calendar = { 
    141147   
    142         load: function(){ 
    143                 this.lastView = 0; 
    144                 var filter = ['=', 'user', User.me.id]; 
    145                 if(!!User.me.gidNumber){ 
    146                         if(!$.isArray(User.me.gidNumber)) 
    147                                 User.me.gidNumber = [User.me.gidNumber]; 
    148  
    149                         filter = ['OR', filter, ['IN', 'user', User.me.gidNumber]]; 
    150                 } 
    151  
    152                 //var descart = DataLayer.get("calendarSignature", {filter: filter, criteria: {deepness: 2}}); 
    153                 this.signatures  = DataLayer.get("calendarSignature", {filter: filter, criteria: {deepness: 2}}); 
     148    load: function(){ 
     149        this.lastView = 0; 
     150        var filter = ['=', 'user', User.me.id]; 
     151        if(!!User.me.gidNumber){ 
     152            if(!$.isArray(User.me.gidNumber)) 
     153                User.me.gidNumber = [User.me.gidNumber]; 
     154 
     155            filter = ['OR', filter, ['IN', 'user', User.me.gidNumber]]; 
     156        } 
     157 
     158        //var descart = DataLayer.get("calendarSignature", {filter: filter, criteria: {deepness: 2}}); 
     159        this.signatures  = DataLayer.get("calendarSignature", { 
     160            filter: filter,  
     161            criteria: { 
     162                deepness: 2 
     163            } 
     164        }); 
    154165           
    155                 var prevSources = this.sources; 
    156  
    157                 this.sources = DataLayer.encode( "calendarSignature:calendar", this.signatures ); 
    158  
    159                 if( prevSources ){      
    160                         var newSources = DataLayer.diff( { 'diff': prevSources }, { 'diff': this.sources } ).diff; 
    161  
    162                         for( var i = 0; i < newSources.length; i++ ) 
    163                                 $('#calendar').fullCalendar( 'addEventSource', newSources[i] ); 
    164  
    165                         var removeSources = DataLayer.diff( { 'diff': newSources }, { 'diff': prevSources } ).diff; 
    166  
    167                         for( var i = 0; i < removeSources.length; i++ ) 
    168                                 $('#calendar').fullCalendar( 'removeEventSource', removeSources[i] ); 
    169                 } 
    170  
    171                 this.calendarIds = [], this.signatureOf = {}, this.calendars = [], this.calendarOf= {}; 
    172  
    173                 for( var i = 0; i < this.signatures.length; i++ ){ 
    174                         if(this.signatures[i].isOwner == "0") 
    175                                 this.signatures[i].permission =  DataLayer.encode('calendarToPermission:detail', this.signatures[i].permission); 
    176                         this.signatureOf[ this.calendarIds[i] = ( this.calendars[ this.calendars.length ] = this.calendarOf[ this.signatures[i].id ] = this.signatures[i].calendar ).id ] = this.signatures[i]; 
    177                 } 
    178  
    179                 delete Calendar.currentViewKey; 
    180         }, 
    181  
    182         rerenderView: function(force){ 
    183  
    184                 if(force){ 
    185                         delete Calendar.currentViewKey; 
     166    var prevSources = this.sources; 
     167 
     168    this.sources = DataLayer.encode( "calendarSignature:calendar", this.signatures ); 
     169 
     170    if( prevSources ){      
     171        var newSources = DataLayer.diff( { 
     172            'diff': prevSources 
     173        }, { 
     174            'diff': this.sources 
     175            } ).diff; 
     176 
     177        for( var i = 0; i < newSources.length; i++ ) 
     178            $('#calendar').fullCalendar( 'addEventSource', newSources[i] ); 
     179 
     180        var removeSources = DataLayer.diff( { 
     181            'diff': newSources 
     182        }, { 
     183            'diff': prevSources 
     184        } ).diff; 
     185 
     186        for( var i = 0; i < removeSources.length; i++ ) 
     187            $('#calendar').fullCalendar( 'removeEventSource', removeSources[i] ); 
     188    } 
     189 
     190    this.calendarIds = [], this.signatureOf = {}, this.calendars = [], this.calendarOf= {}; 
     191 
     192    for( var i = 0; i < this.signatures.length; i++ ){ 
     193        if(this.signatures[i].isOwner == "0") 
     194            this.signatures[i].permission =  DataLayer.encode('calendarToPermission:detail', this.signatures[i].permission); 
     195        this.signatureOf[ this.calendarIds[i] = ( this.calendars[ this.calendars.length ] = this.calendarOf[ this.signatures[i].id ] = this.signatures[i].calendar ).id ] = this.signatures[i]; 
     196    } 
     197 
     198    delete Calendar.currentViewKey; 
     199}, 
     200 
     201rerenderView: function(force){ 
     202 
     203    if(force){ 
     204        delete Calendar.currentViewKey; 
    186205                         
    187                         $('#calendar').fullCalendar( 'refetchEvents' ); 
    188                 } 
    189  
    190                 var calendarNotSelected = getSelectedCalendars( true ); 
    191                 for(var i = 0; i < calendarNotSelected.length; i++) 
    192                         if(!!Calendar.currentView[ calendarNotSelected[i] ]) 
    193                                 Calendar.currentView[ calendarNotSelected[i] ].hidden = true; 
    194  
    195                 $('#calendar').fullCalendar( 'refetchEvents' );  
     206        $('#calendar').fullCalendar( 'refetchEvents' ); 
     207    } 
     208 
     209    var calendarNotSelected = getSelectedCalendars( true ); 
     210    for(var i = 0; i < calendarNotSelected.length; i++) 
     211        if(!!Calendar.currentView[ calendarNotSelected[i] ]) 
     212            Calendar.currentView[ calendarNotSelected[i] ].hidden = true; 
     213 
     214    $('#calendar').fullCalendar( 'refetchEvents' );      
    196215                 
    197                 contentMenu(); 
     216    contentMenu(); 
     217} 
     218} 
     219 
     220Alarms = { 
     221    load: function(){ 
     222        var eventsDay = DataLayer.get('alarm:schedulable',['=', 'date', Date.today().getTime()]); 
     223        for(var i = 0; i < eventsDay.length; i++){ 
     224            this.addAlarm( eventsDay[i] ); 
    198225        } 
     226    }, 
     227         
     228    addAlarm: function( eventDay ){             
     229        if(!DataLayer.tasks[parseInt(eventDay.sendTime)]){ 
     230            DataLayer.task( parseInt(eventDay.sendTime) , function( timestamp ){ 
     231                var path = User.moduleName == 'expressoCalendar' ? '' : '../prototype/modules/calendar/'; 
     232                DataLayer.render(path+'templates/alarm.ejs',{ 
     233                    event: eventDay 
     234                }, function( html ){                                 
     235                    $.Zebra_Dialog(html , { 
     236                        'type':     'question', 
     237                        'overlay_opacity': '0.5', 
     238                        'buttons':  ['Fechar'], 
     239                        'onClose':  function(clicked) {} 
     240                    }); 
     241                }); 
     242            }); 
     243        } 
     244    } 
    199245} 
    200246 
    201 Alarms = { 
    202         load: function(){ 
    203                 var eventsDay = DataLayer.get('alarm:schedulable',['=', 'date', Date.today().getTime()]); 
    204                 for(var i = 0; i < eventsDay.length; i++){ 
    205                         this.addAlarm( eventsDay[i] ); 
    206                 } 
    207         }, 
    208          
    209         addAlarm: function( eventDay ){             
    210                 if(!DataLayer.tasks[parseInt(eventDay.sendTime)]){ 
    211                     DataLayer.task( parseInt(eventDay.sendTime) , function( timestamp ){ 
    212                         var path = User.moduleName == 'expressoCalendar' ? '' : '../prototype/modules/calendar/'; 
    213                         DataLayer.render(path+'templates/alarm.ejs',{event: eventDay}, function( html ){                                 
    214                                 $.Zebra_Dialog(html , { 
    215                                     'type':     'question', 
    216                                     'overlay_opacity': '0.5', 
    217                                     'buttons':  ['Fechar'], 
    218                                     'onClose':  function(clicked) {} 
    219                                }); 
    220                         }); 
    221                     }); 
    222                 } 
     247DataLayer.codec( "modulePreference", "detail", { 
     248    decoder: function( evtObj ){ 
     249 
     250        if( notArray = $.type(evtObj) !== "array" ) 
     251            evtObj = [ evtObj ]; 
     252                 
     253        var res = $.map(evtObj, function( form ){ 
     254 
     255            var returns = []; 
     256 
     257            for (var name in form) 
     258                returns[ returns.length ] = { 
     259                    name: name, 
     260                    user: User.me.id, 
     261                    value: form[name], 
     262                    module: User.moduleName, 
     263                    id: User.preferenceIds[ name ] || undefined 
     264                }; 
     265 
     266            return [returns]; 
     267        }); 
     268         
     269        return notArray ? res[0] : res; 
     270    }, 
     271 
     272    encoder: function( evtObj ){ 
     273        var val = {}, id = {}; 
     274        for (var i in evtObj){ 
     275                         
     276            if( evtObj[i].value && evtObj[i].id ) 
     277            { 
     278                val[evtObj[i].name] = evtObj[i].value; 
     279                id[evtObj[i].name] = evtObj[i].id; 
     280            } 
    223281        } 
    224 } 
    225  
    226 DataLayer.codec( "modulePreference", "detail", { 
    227         decoder: function( evtObj ){ 
    228  
    229         if( notArray = $.type(evtObj) !== "array" ) 
    230                 evtObj = [ evtObj ]; 
    231                  
    232                 var res = $.map(evtObj, function( form ){ 
    233  
    234                         var returns = []; 
    235  
    236                         for (var name in form) 
    237                                 returns[ returns.length ] = { 
    238                                         name: name, 
    239                                         user: User.me.id, 
    240                                         value: form[name], 
    241                                         module: User.moduleName, 
    242                                         id: User.preferenceIds[ name ] || undefined 
    243                                 }; 
    244  
    245                         return [returns]; 
    246                 }); 
    247          
    248         return notArray ? res[0] : res; 
    249         }, 
    250  
    251     encoder: function( evtObj ){ 
    252                 var val = {}, id = {}; 
    253                 for (var i in evtObj){ 
    254                          
    255                         if( evtObj[i].value && evtObj[i].id ) 
    256                         { 
    257                             val[evtObj[i].name] = evtObj[i].value; 
    258                             id[evtObj[i].name] = evtObj[i].id; 
    259                         } 
    260                 } 
    261                 return {values: val,ids: id}; 
    262          
    263         } 
     282        return { 
     283            values: val, 
     284            ids: id 
     285        }; 
     286         
     287    } 
    264288}); 
    265289 
     
    273297   
    274298    if( status === 'serverclient' ){ 
    275                 DataLayer.commit( false, false, function(){      
    276                         if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') == 0){ 
    277                                 Calendar.rerenderView(true); 
    278                         }else if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') != 0) 
    279                                 pageselectCallback($('.events-list-win.active [name=keyword]').val(), 0); 
    280                         //Recarrega os alarmes de eventos     
    281                         Alarms.load(); 
    282                 }); 
     299        DataLayer.commit( false, false, function(){      
     300            if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') == 0){ 
     301                Calendar.rerenderView(true); 
     302            }else if((typeof($tabs) != "undefined") && $tabs.tabs('option' ,'selected') != 0) 
     303                pageselectCallback($('.events-list-win.active [name=keyword]').val(), 0); 
     304            //Recarrega os alarmes de eventos     
     305            Alarms.load(); 
     306        }); 
    283307    } 
    284308}); 
     
    304328 
    305329    switch( status ){ 
    306                 case 'serverclient':  DataLayer.commit( false, false, function(){ 
    307                         User.load(); 
    308                 }); 
    309                 break; 
    310                 case 'client':   
    311                 break; 
     330        case 'serverclient': 
     331            DataLayer.commit( false, false, function(){ 
     332            User.load(); 
     333        }); 
     334        break; 
     335        case 'client': 
     336            break; 
    312337    } 
    313338 
     
    316341DataLayer.listen( "alarm", function( created, updated, deleted ){ 
    317342 
    318 }); 
     343    }); 
    319344 
    320345/*DataLayer.listen( "calendar", function( status, updateData ){ 
     
    335360 
    336361DataLayer.codec( "calendarSignature", "configure", { 
    337         decoder: function( evtObj ){ 
    338                 Encoder.EncodeType = "entity"; 
    339                  
    340                 if( notArray = $.type(evtObj) !== "array" ) 
    341                         evtObj = [ evtObj ]; 
    342                  
    343                 var res = $.map(evtObj, function( form ){ 
    344                         return{ 
    345                                 id: form.signature, 
    346                                 user: User.me.id,        
    347                                 calendar: { 
    348                                         id: Calendar.calendarOf[form.signature].id, 
    349                                         name: Encoder.htmlEncode(form.name), 
    350                                         description: Encoder.htmlEncode(form.description), 
    351                                         timezone: form.timezone, 
    352                                         defaultDuration: form.duration != "" ? form.duration : 30, 
    353                                         location: form.location 
    354                                 }, 
    355                         //      isOwner: 1, 
    356                                 fontColor: Encoder.htmlEncode(form.fontColor.substring(1)), 
    357                                 backgroundColor: Encoder.htmlEncode(form.backgroundColor.substring(1)), 
    358                                 borderColor: Encoder.htmlEncode(form.borderColor.substring(1)), 
    359                                 msgAdd: Encoder.htmlEncode(form.msgAdd), 
    360                                 msgCancel: Encoder.htmlEncode(form.msgCancel), 
    361                                 msgUpdate: Encoder.htmlEncode(form.msgUpdate), 
    362                                 msgReply: Encoder.htmlEncode(form.msgReply), 
    363                                 msgAlarm: Encoder.htmlEncode(form.msgAlarm), 
    364                                 calendarSignatureAlarms: $.map( form.alarmTime || [], function( alarmTime, i ){ 
    365                                         return (!!form.alarmId[i] ? 
    366                                                         {type: form.alarmType[i],       unit: form.alarmUnit[i], time: form.alarmTime[i], id: form.alarmId[i]} : 
    367                                                         {type: form.alarmType[i],       unit: form.alarmUnit[i], time: form.alarmTime[i]}); 
    368                                 }) 
    369                         }; 
    370                  
    371                 }); 
     362    decoder: function( evtObj ){ 
     363        Encoder.EncodeType = "entity"; 
     364                 
     365        if( notArray = $.type(evtObj) !== "array" ) 
     366            evtObj = [ evtObj ]; 
     367                 
     368        var res = $.map(evtObj, function( form ){ 
     369            return{ 
     370                id: form.signature, 
     371                user: User.me.id,        
     372                calendar: { 
     373                    id: Calendar.calendarOf[form.signature].id, 
     374                    name: Encoder.htmlEncode(form.name), 
     375                    description: Encoder.htmlEncode(form.description), 
     376                    timezone: form.timezone, 
     377                    defaultDuration: form.duration != "" ? form.duration : 30, 
     378                    location: form.location 
     379                }, 
     380                //      isOwner: 1, 
     381                fontColor: Encoder.htmlEncode(form.fontColor.substring(1)), 
     382                backgroundColor: Encoder.htmlEncode(form.backgroundColor.substring(1)), 
     383                borderColor: Encoder.htmlEncode(form.borderColor.substring(1)), 
     384                msgAdd: Encoder.htmlEncode(form.msgAdd), 
     385                msgCancel: Encoder.htmlEncode(form.msgCancel), 
     386                msgUpdate: Encoder.htmlEncode(form.msgUpdate), 
     387                msgReply: Encoder.htmlEncode(form.msgReply), 
     388                msgAlarm: Encoder.htmlEncode(form.msgAlarm), 
     389                calendarSignatureAlarms: $.map( form.alarmTime || [], function( alarmTime, i ){ 
     390                    return (!!form.alarmId[i] ? 
     391                    { 
     392                        type: form.alarmType[i],         
     393                        unit: form.alarmUnit[i],  
     394                        time: form.alarmTime[i],  
     395                        id: form.alarmId[i] 
     396                        } : 
     397{ 
     398                        type: form.alarmType[i],         
     399                        unit: form.alarmUnit[i],  
     400                        time: form.alarmTime[i] 
     401                        }); 
     402                }) 
     403            }; 
     404                 
     405        }); 
    372406         
    373407        return notArray ? res[0] : res; 
    374         }, 
     408    }, 
    375409 
    376410    encoder: function( evtObj ){} 
     
    381415    decoder: function( evtObj ){}, 
    382416         
    383         encoder: function (evtObjt){ 
    384          
    385                         if(notArray = typeof(evtObjt) == 'array' ) 
    386                                 evtObjt = [evtObjt]; 
     417    encoder: function (evtObjt){ 
     418         
     419        if(notArray = typeof(evtObjt) == 'array' ) 
     420            evtObjt = [evtObjt]; 
    387421                         
    388                         var res = $.map(evtObjt, function( objEvent ){   
    389  
    390                                 var time = parseInt(objEvent.schedulable.startTime); 
     422        var res = $.map(evtObjt, function( objEvent ){   
     423 
     424            var time = parseInt(objEvent.schedulable.startTime); 
    391425                                                                                         
    392                                 return{ 
    393                                         id: objEvent.id, 
    394                                         event_start: new Date( time ).setTimezoneOffset(Timezone.timezones[objEvent.schedulable.timezone]).toString( User.preferences.dateFormat), 
    395                                         sendTime: objEvent.sendTime, 
    396                                         schedulable: { 
    397                                                 startTime: dateCalendar.formatDate(Timezone.getDateEvent(new Date(time), objEvent.schedulable.timezone, objEvent.schedulable.DayLigth, 'startTime'), User.preferences.hourFormat), 
    398                                                 id: objEvent.schedulable.id, 
    399                                                 summary: objEvent.schedulable.summary, 
    400                                                 time: objEvent.time,     
    401                                                 unit: dateCalendar.timeunit[objEvent.unit.toLowerCase()] + ( parseInt(objEvent.time) > 1 ? 's' : '' ) 
    402                                         } 
    403                                 } 
    404                         }); 
    405                 return notArray ? res[0] : res; 
    406         } 
     426            return{ 
     427                id: objEvent.id, 
     428                event_start: new Date( time ).setTimezoneOffset(Timezone.timezones[objEvent.schedulable.timezone]).toString( User.preferences.dateFormat), 
     429                sendTime: objEvent.sendTime, 
     430                schedulable: { 
     431                    startTime: dateCalendar.formatDate(Timezone.getDateEvent(new Date(time), objEvent.schedulable.timezone, objEvent.schedulable.DayLigth, 'startTime'), User.preferences.hourFormat), 
     432                    id: objEvent.schedulable.id, 
     433                    summary: objEvent.schedulable.summary, 
     434                    time: objEvent.time,         
     435                    unit: dateCalendar.timeunit[objEvent.unit.toLowerCase()] + ( parseInt(objEvent.time) > 1 ? 's' : '' ) 
     436                } 
     437            } 
     438        }); 
     439        return notArray ? res[0] : res; 
     440    } 
    407441}); 
    408442 
     
    410444 
    411445    decoder: function( evtObj ){ 
    412                 if( notArray = $.type(evtObj) !== "array" ) 
    413                         evtObj = [ evtObj ]; 
    414  
    415  
    416  
    417                 var meAttendee = function(attendees){ 
    418                         for(var i = 0; i < attendees.length; i++) 
    419                                 if(DataLayer.get('participant', attendees[i]).user == User.me.id) 
    420                                         return attendee; 
    421                 }; 
    422  
    423                 var res = $.map(evtObj, function( form ){        
    424                         return { 
    425                                 participant : meAttendee(form.attendee),  
    426                                 startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'), 
    427                                 endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'), 
    428                                 allDay: ( !!form.allDay ? 1 : 0 ), 
    429                                 schedulable: form.idEvent 
    430                         } 
    431                 });      
     446        if( notArray = $.type(evtObj) !== "array" ) 
     447            evtObj = [ evtObj ]; 
     448 
     449 
     450 
     451        var meAttendee = function(attendees){ 
     452            for(var i = 0; i < attendees.length; i++) 
     453                if(DataLayer.get('participant', attendees[i]).user == User.me.id) 
     454                    return attendee; 
     455        }; 
     456 
     457        var res = $.map(evtObj, function( form ){        
     458            return { 
     459                participant : meAttendee(form.attendee),  
     460                startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'), 
     461                endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'), 
     462                allDay: ( !!form.allDay ? 1 : 0 ), 
     463                schedulable: form.idEvent 
     464            } 
     465        });      
    432466         
    433467 
    434468        return notArray ? res[0] : res; 
    435         }, 
    436          
    437         encoder: function( evtObj ){} 
     469    }, 
     470         
     471    encoder: function( evtObj ){} 
    438472         
    439473}); 
     
    441475DataLayer.codec( "attachment", "detail", { 
    442476   
    443         decoder: function(evtObj){ 
    444          
    445                 if( notArray = $.type(evtObj) !== "array" ) 
    446                         evtObj = [ evtObj ]; 
    447  
    448                 var res = $.map(evtObj, function( form){ 
    449                         return [$.map(form.files , function( files){ 
    450                                         return { source: files }; 
    451                                 })]; 
    452                 }); 
     477    decoder: function(evtObj){ 
     478         
     479        if( notArray = $.type(evtObj) !== "array" ) 
     480            evtObj = [ evtObj ]; 
     481 
     482        var res = $.map(evtObj, function( form){ 
     483            return [$.map(form.files , function( files){ 
     484                return { 
     485                    source: files 
     486                }; 
     487            })]; 
     488        }); 
    453489        return notArray ? res[0] : res; 
    454         }, 
     490    }, 
    455491       
    456         encoder: function(){} 
     492    encoder: function(){} 
    457493 
    458494       
     
    462498 
    463499    decoder: function( evtObj ){ 
    464                 Encoder.EncodeType = "entity"; 
    465          
    466                 if( notArray = $.type(evtObj) !== "array" ) 
    467                         evtObj = [ evtObj ]; 
    468  
    469                 var pref = User.preferences; 
    470                  
    471                 var Owner = decodeOwnerCalendar(evtObj.calendar);        
    472  
    473                 var res = $.map(evtObj, function( form ){ 
     500        Encoder.EncodeType = "entity"; 
     501         
     502        if( notArray = $.type(evtObj) !== "array" ) 
     503            evtObj = [ evtObj ]; 
     504 
     505        var pref = User.preferences; 
     506                 
     507        var Owner = decodeOwnerCalendar(evtObj.calendar);        
     508 
     509        var res = $.map(evtObj, function( form ){ 
    474510                         
    475                         return { 
    476                                 id: form.idEvent, 
    477                                 calendar: form.calendar, 
    478                                 participants : $.map(form.attendee, function( attendee, i ){ 
    479                                         if(isNaN(attendee)){ 
    480                                             return{ 
    481                                                     id: attendee, 
    482                                                     acl: form.attendeeAcl[i], 
    483                                                     delegatedFrom: !!form.delegatedFrom[i] ? form.delegatedFrom[i] : 0, 
    484                                                     isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ), 
    485                                                     isExternal: !!parseInt(form.attendeeType[i]) ? 1 : 0, 
    486                                                     acl: form.attendeeAcl[i].replace('o', '') 
    487                                             }; 
    488                                         }else{ 
    489                                                 if(DataLayer.get('participant', attendee).user == Owner.id){ 
    490                                                         var me = { 
    491                                                             user: User.id, 
    492                                                             status: form.status, 
    493                                                             id: attendee, 
    494                                                             isOrganizer: 0, 
    495                                                             receiveNotification : (!!form.receiveNotification ? 1 : 0), 
    496                                                             alarms: typeof(form.alarmTime) != 'undefined' ?  
    497                                                                 $.map( form.alarmTime || [], function( alarmTime, i ){ 
    498  
    499                                                                     if( alarmTime === "" ) 
    500                                                                             return( null ); 
    501  
    502                                                                     return !!form.alarmId[i] ? 
    503                                                                             { type: form.alarmType[i], unit: form.alarmUnit[i], time: form.alarmTime[i], id: form.alarmId[i] } :  
    504                                                                             { type: form.alarmType[i],unit: form.alarmUnit[i], time: form.alarmTime[i] }; 
    505                                                                     }) : [] 
    506                                                     }; 
     511            return { 
     512                id: form.idEvent, 
     513                calendar: form.calendar, 
     514                participants : $.map(form.attendee, function( attendee, i ){ 
     515                    if(isNaN(attendee)){ 
     516                        return{ 
     517                            id: attendee, 
     518                            acl: form.attendeeAcl[i], 
     519                            delegatedFrom: !!form.delegatedFrom[i] ? form.delegatedFrom[i] : 0, 
     520                            isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ), 
     521                            isExternal: !!parseInt(form.attendeeType[i]) ? 1 : 0, 
     522                            acl: form.attendeeAcl[i].replace('o', '') 
     523                        }; 
     524                    }else{ 
     525                        if(DataLayer.get('participant', attendee).user == Owner.id){ 
     526                            var me = { 
     527                                user: User.id, 
     528                                status: form.status, 
     529                                id: attendee, 
     530                                isOrganizer: 0, 
     531                                receiveNotification : (!!form.receiveNotification ? 1 : 0), 
     532                                alarms: typeof(form.alarmTime) != 'undefined' ?  
     533                                $.map( form.alarmTime || [], function( alarmTime, i ){ 
     534 
     535                                    if( alarmTime === "" ) 
     536                                        return( null ); 
     537 
     538                                    return !!form.alarmId[i] ? 
     539                                    { 
     540                                        type: form.alarmType[i],  
     541                                        unit: form.alarmUnit[i],  
     542                                        time: form.alarmTime[i],  
     543                                        id: form.alarmId[i] 
     544                                        } :  
     545{ 
     546                                        type: form.alarmType[i], 
     547                                        unit: form.alarmUnit[i],  
     548                                        time: form.alarmTime[i] 
     549                                        }; 
     550                                }) : [] 
     551                            }; 
    507552                                                         
    508                                                         if(form.startDate){ 
    509                                                                 var tzId =  DataLayer.get('schedulable', form.idEvent).timezone || User.preferences.timezone, 
    510                                                                 formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? pref.dateFormat+" HH:mm" : pref.dateFormat + " " + pref.hourFormat; 
     553                            if(form.startDate){ 
     554                                var tzId =  DataLayer.get('schedulable', form.idEvent).timezone || User.preferences.timezone, 
     555                                formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? pref.dateFormat+" HH:mm" : pref.dateFormat + " " + pref.hourFormat; 
    511556                                                                 
    512                                                                 DataLayer.put('notification', { 
    513                                                                     participant: me.id, 
    514                                                                     type: 'suggestion', 
    515                                                                     startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'), 
    516                                                                     endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'), 
    517                                                                     allDay: ( !!form.allDay ? 1 : 0 ), 
    518                                                                     schedulable: form.idEvent 
    519                                                                 }); 
     557                                DataLayer.put('notification', { 
     558                                    participant: me.id, 
     559                                    type: 'suggestion', 
     560                                    startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'), 
     561                                    endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'), 
     562                                    allDay: ( !!form.allDay ? 1 : 0 ), 
     563                                    schedulable: form.idEvent 
     564                                }); 
    520565                                                         
    521                                                         } 
    522                                                         return me; 
    523                                                 }else return(null); 
    524                                         }; 
    525                                 }) 
    526                         } 
    527                 }); 
    528                 return notArray ? res[0] : res; 
     566                            } 
     567                            return me; 
     568                        }else return(null); 
     569                    }; 
     570                }) 
     571            } 
     572        }); 
     573        return notArray ? res[0] : res; 
    529574    }, 
    530575 
     
    543588         
    544589        for( var i = 0; i < statusLabels.length; i++ ) 
    545                 statusParticipants[ statusLabels[i] ] = 0; 
     590            statusParticipants[ statusLabels[i] ] = 0; 
    546591         
    547592        var res = $.map(evtObj, function( objEvent ){                    
    548593                     
    549                         if(!(typeof(objEvent) == 'object')) 
    550                                 return (null); 
    551  
    552                         var Owner = decodeOwnerCalendar(objEvent.calendar); 
    553  
    554                         var participantInfo = {}, delegatedFrom = {}, me = DataLayer.copy( Owner ); 
     594            if(!(typeof(objEvent) == 'object')) 
     595                return (null); 
     596 
     597            var isAttendee = false; 
     598            var Owner = decodeOwnerCalendar(objEvent.calendar); 
     599 
     600            var participantInfo = {}, delegatedFrom = {}, me = DataLayer.copy( Owner ); 
    555601                         
    556                         var constantAcl = function(acl){ 
    557                         var returns = {}; 
    558                         for (var i in constantsParticipant){ 
    559                                 returns[constantsParticipant[i]] = acl.indexOf(i) >= 0 ? true : false 
    560                         } 
    561                         return returns; 
     602            var constantAcl = function(acl){ 
     603                var returns = {}; 
     604                for (var i in constantsParticipant){ 
     605                    returns[constantsParticipant[i]] = acl.indexOf(i) >= 0 ? true : false 
     606                } 
     607                return returns; 
     608            }; 
     609 
     610            return { 
     611                "class": objEvent["class"], 
     612                id: objEvent.id, 
     613                repeat: encodeRepeat( objEvent.repeat ), 
     614                location: objEvent.location, 
     615                category: objEvent.category, 
     616                calendars: Calendar.calendars, 
     617                calendar: objEvent.calendar, 
     618                summary: objEvent.summary, 
     619                description: objEvent.description, 
     620                timezone: objEvent.timezone, 
     621                timezones: Timezone.timezones, 
     622                startDate: new Date( parseInt(objEvent.startTime) ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ), 
     623                startHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date( parseInt(objEvent.startTime)), objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'startTime'), User.preferences.hourFormat), 
     624                endDate: new Date( parseInt(objEvent.endTime) - (!!parseInt(objEvent.allDay) ? 86400000 : 0)  ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ), 
     625                endHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date(parseInt(objEvent.endTime)),  objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'endTime'), User.preferences.hourFormat), 
     626                allDay: !!parseInt( objEvent.allDay ), 
     627                attachments: $.map(objEvent.attachments || [], function( attachment, i ){ 
     628                    var attach = DataLayer.get('schedulableToAttachment', attachment, false); 
     629                    var ext = attach.name.split('.'); 
     630                    attach.name = attach.name.length < 10 ?  attach.name : ( ext.length == 1 ? attach.name.substr(0, 10) : (attach.name.substr(0, 6) + '.' +  ext[ext.length -1])); 
     631                    attach.size = formatBytes(attach.size); 
     632                    return attach; 
     633                }),                                              
     634                attendee: $.map(objEvent.participants || [], function( participant, i ){                                                 
     635 
     636                    if(delegateAttendee[participant]) 
     637                        return(null); 
     638 
     639                    var attend = DataLayer.get('participant', (participant.id || participant)); 
     640                    attend.user = DataLayer.get('user', attend.user); 
     641 
     642                    statusParticipants[ statusLabels[attend.status] ]++;         
     643 
     644                    if(attend.user.mail == User.me.mail) 
     645                        isAttendee = true; 
     646 
     647                    if( attend.user.id ===  me.id ){ 
     648                        participantInfo.user = { 
     649                            id: attend.id, 
     650                            status : attend.status, 
     651                            delegatedFrom: attend.delegatedFrom || '0', 
     652                            acl: attend.acl, 
     653                            receiveNotification : attend.receiveNotification, 
     654                            alarms : $.map(attend.alarms || [], function( alarm ){ 
     655                                var alarm = DataLayer.get('alarm', alarm); 
     656                                return (alarm == "" ? (null) : alarm); 
     657                            }) 
    562658                        }; 
    563  
    564                     return { 
    565                             "class": objEvent["class"], 
    566                             id: objEvent.id, 
    567                             repeat: encodeRepeat( objEvent.repeat ), 
    568                             location: objEvent.location, 
    569                             category: objEvent.category, 
    570                             calendars: Calendar.calendars, 
    571                             calendar: objEvent.calendar, 
    572                             summary: objEvent.summary, 
    573                             description: objEvent.description, 
    574                             timezone: objEvent.timezone, 
    575                             timezones: Timezone.timezones, 
    576                             startDate: new Date( parseInt(objEvent.startTime) ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ), 
    577                             startHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date( parseInt(objEvent.startTime)), objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'startTime'), User.preferences.hourFormat), 
    578                             endDate: new Date( parseInt(objEvent.endTime) - (!!parseInt(objEvent.allDay) ? 86400000 : 0)  ).setTimezoneOffset( Timezone.timezone( objEvent.timezone ) ).toString( User.preferences.dateFormat ), 
    579                             endHour: dateCalendar.formatDate(Timezone.getDateEvent(new Date(parseInt(objEvent.endTime)),  objEvent.timezone, objEvent.calendar, objEvent.DayLigth, 'endTime'), User.preferences.hourFormat), 
    580                             allDay: !!parseInt( objEvent.allDay ), 
    581                             attachments: $.map(objEvent.attachments || [], function( attachment, i ){ 
    582                                         var attach = DataLayer.get('schedulableToAttachment', attachment, false); 
    583                                         var ext = attach.name.split('.'); 
    584                                         attach.name = attach.name.length < 10 ?  attach.name : ( ext.length == 1 ? attach.name.substr(0, 10) : (attach.name.substr(0, 6) + '.' +  ext[ext.length -1])); 
    585                                         attach.size = formatBytes(attach.size); 
    586                                         return attach; 
    587                                 }),                                              
    588                             attendee: $.map(objEvent.participants || [], function( participant, i ){                                             
    589  
    590                                 if(delegateAttendee[participant]) 
    591                                         return(null); 
    592  
    593                                 var attend = DataLayer.get('participant', (participant.id || participant)); 
    594                                 attend.user = DataLayer.get('user', attend.user); 
    595  
    596                                 statusParticipants[ statusLabels[attend.status] ]++;     
    597  
    598                                 if( attend.user.id ===  me.id ){ 
    599                                     participantInfo.user = { 
    600                                         id: attend.id, 
    601                                         status : attend.status, 
    602                                         delegatedFrom: attend.delegatedFrom || '0', 
    603                                         acl: attend.acl, 
    604                                         receiveNotification : attend.receiveNotification, 
    605                                         alarms : $.map(attend.alarms || [], function( alarm ){ 
    606                                             var alarm = DataLayer.get('alarm', alarm); 
    607                                             return (alarm == "" ? (null) : alarm); 
    608                                         }) 
    609                                     }; 
    610                                     me.id = attend.id; 
    611                                     return(null); 
    612                                 }; 
    613  
    614                                 var person = { 
    615                                     id: attend.id, 
    616                                     name: attend.user.name != 'false' ? attend.user.name : '', 
    617                                     mail: attend.user.mail, 
    618                                     status : attend.status, 
    619                                     isExternal: attend.isExternal, 
    620                                     acl: attend.acl, 
    621                                     delegatedFrom: attend.delegatedFrom 
    622                                 }; 
    623  
    624                                 if(!!parseInt(attend.delegatedFrom)){ 
    625                                     delegatedFrom[attend.delegatedFrom] = DataLayer.copy(person); 
    626                                         return(null); 
    627                                 } 
    628  
    629                                 if( !!parseInt(attend.isOrganizer )){ 
    630                                     participantInfo.organizer = DataLayer.copy(person); 
    631                                         return(null); 
    632                                 };                                       
    633  
    634                                 return (person); 
    635                             }), 
    636                             organizer: participantInfo.organizer || me, 
    637                             alarms: !!participantInfo.user ? participantInfo.user.alarms : [], 
    638                             status: !!participantInfo.user ? participantInfo.user.status : 1, 
    639                                 acl: !!participantInfo.user ? constantAcl(participantInfo.user.acl) : constantAcl( 'rowi' ), 
    640                                 isShared: !this.id ? false : (!!objEvent.calendar) && parseInt(Calendar.signatureOf[objEvent.calendar].isOwner) ? false : true, 
    641                             me: !!participantInfo.user ? DataLayer.merge(participantInfo.user, me) : DataLayer.merge(this.isShared ? this.organizer :  me, {acl:  !this.isShared ? 'rowi' : Calendar.signatureOf[objEvent.calendar].permission.aclValues, delegatedFrom: 0, receiveNotification: 1}), 
    642                                 delegatedFrom: delegatedFrom, 
     659                        me.id = attend.id; 
     660                        return(null); 
     661                    }; 
     662 
     663                    var person = { 
     664                        id: attend.id, 
     665                        name: attend.user.name != 'false' ? attend.user.name : '', 
     666                        mail: attend.user.mail, 
     667                        status : attend.status, 
     668                        isExternal: attend.isExternal, 
     669                        acl: attend.acl, 
     670                        delegatedFrom: attend.delegatedFrom 
     671                    }; 
     672 
     673                    if(!!parseInt(attend.delegatedFrom)){ 
     674                        delegatedFrom[attend.delegatedFrom] = DataLayer.copy(person); 
     675                        return(null); 
     676                    } 
     677 
     678                    if( !!parseInt(attend.isOrganizer )){ 
     679                        participantInfo.organizer = DataLayer.copy(person); 
     680                        return(null); 
     681                    };                                   
     682 
     683                    return (person); 
     684                }), 
     685                organizer: participantInfo.organizer || me, 
     686                alarms: !!participantInfo.user ? participantInfo.user.alarms : [], 
     687                status: !!participantInfo.user ? participantInfo.user.status : 1, 
     688                acl: !!participantInfo.user ? constantAcl(participantInfo.user.acl) : ( ( !objEvent.id || isAttendee ) ? constantAcl( 'rowi' ) : constantAcl( 'r' )), 
     689                isShared: !this.id ? false : (!!objEvent.calendar) && parseInt(Calendar.signatureOf[objEvent.calendar].isOwner) ? false : true, 
     690                isAttendee: (isAttendee ? true : (objEvent.id && !this.isShared ? false : true)), 
     691                me: ((!objEvent.id) || ( objEvent.id && isAttendee)) ? (!!participantInfo.user ? DataLayer.merge(participantInfo.user, me) : DataLayer.merge(this.isShared ? this.organizer :  me, { 
     692                    acl:  !this.isShared ? 'rowi' : Calendar.signatureOf[objEvent.calendar].permission.aclValues,  
     693                    delegatedFrom: 0,  
     694                    receiveNotification: 1 
     695                })) : (DataLayer.merge( ( participantInfo.organizer || me), { 
     696                    acl: 'r' 
     697                } ) ), 
     698                delegatedFrom: delegatedFrom, 
    643699                                 
    644                                 statusParticipants: statusParticipants 
    645                         }; 
    646                 }); 
     700                statusParticipants: statusParticipants 
     701            }; 
     702        }); 
    647703        return (notArray ? res[0] : res); 
    648704    } 
     
    652708function decodeOwnerCalendar(calendar){ 
    653709    if(calendar && !parseInt(Calendar.signatureOf[calendar].isOwner)){ 
    654         var Owner = DataLayer.get('calendarSignature', {filter: ['AND', ['=','calendar', calendar], ['=','isOwner','1']], criteria: {deepness: 2}}); 
    655  
    656         if($.isArray(Owner)) 
    657             Owner = Owner[0]; 
    658          
    659         return Owner.user; 
    660     } 
    661     return User.me; 
     710        var Owner = DataLayer.get('calendarSignature', { 
     711            filter: ['AND', ['=','calendar', calendar], ['=','isOwner','1']],  
     712            criteria: { 
     713                deepness: 2 
     714            } 
     715        }); 
     716 
     717    if($.isArray(Owner)) 
     718        Owner = Owner[0]; 
     719         
     720    return Owner.user; 
     721} 
     722return User.me; 
    662723 
    663724     
     
    666727function decodeRepeat ( form ) { 
    667728 
    668         var patati = {}; 
    669          
    670         if( form.repeatId ) 
    671             patati['id'] = form.repeatId; 
    672  
    673         patati['frequency'] = form.frequency; 
    674  
    675         patati['bymonthday'] = patati['byyearday'] = patati['byday'] = ''; 
    676          
    677         patati['interval'] = patati['endTime'] = patati['count'] = patati['startTime'] = 0; 
    678          
    679         if( form.frequency === 'none' ) 
    680             return( patati ); 
    681          
    682         var day = []; 
    683  
    684         $("input[type=checkbox][name='repeatweekly[]']:checked").each(function() {  
    685                 day[ day.length ] = $(this).val(); 
    686         }); 
    687  
    688         patati['byday'] = day.join(','); 
    689  
    690         var formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? User.preferences.dateFormat+" HH:mm" : User.preferences.dateFormat + " " + User.preferences.hourFormat; 
    691  
    692         var date = Date.parseExact( form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ); 
    693          
    694         patati['startTime'] = date.toString('yyyy-MM-dd HH:mm:00'); 
    695          
    696         if( !patati['byday'] ) 
    697               switch(form.frequency) { 
    698               case 'weekly':       
    699                       break; 
    700               case 'daily': 
    701                       break; 
    702               case 'monthly': 
    703                       patati['bymonthday'] = date.getDate(); 
    704                       break; 
    705               case 'yearly': 
    706                       patati['byyearday'] = date.getDayOfYear(); 
    707                       break; 
    708               default : 
    709                       return patati; 
    710               } 
    711  
    712         if (($(".endRepeat").val() == 'occurrences'))  
    713                 patati['count'] = $(".occurrencesEnd").val();  
    714          
    715         if (($(".endRepeat").val() == 'customDate')) 
    716                 patati['endTime'] = Date.parseExact( $(".customDateEnd").val() + (!!form.allDay ? " 00:00": " "+$.trim(form.endHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'); 
    717          
    718         patati['interval']  = $(".eventInterval").val(); 
    719  
    720         /** 
     729    var patati = {}; 
     730         
     731    if( form.repeatId ) 
     732        patati['id'] = form.repeatId; 
     733 
     734    patati['frequency'] = form.frequency; 
     735 
     736    patati['bymonthday'] = patati['byyearday'] = patati['byday'] = ''; 
     737         
     738    patati['interval'] = patati['endTime'] = patati['count'] = patati['startTime'] = 0; 
     739         
     740    if( form.frequency === 'none' ) 
     741        return( patati ); 
     742         
     743    var day = []; 
     744 
     745    $("input[type=checkbox][name='repeatweekly[]']:checked").each(function() {  
     746        day[ day.length ] = $(this).val(); 
     747    }); 
     748 
     749    patati['byday'] = day.join(','); 
     750 
     751    var formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? User.preferences.dateFormat+" HH:mm" : User.preferences.dateFormat + " " + User.preferences.hourFormat; 
     752 
     753    var date = Date.parseExact( form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ); 
     754         
     755    patati['startTime'] = date.toString('yyyy-MM-dd HH:mm:00'); 
     756         
     757    if( !patati['byday'] ) 
     758        switch(form.frequency) { 
     759            case 'weekly': 
     760                break; 
     761            case 'daily': 
     762                break; 
     763            case 'monthly': 
     764                patati['bymonthday'] = date.getDate(); 
     765                break; 
     766            case 'yearly': 
     767                patati['byyearday'] = date.getDayOfYear(); 
     768                break; 
     769            default : 
     770                return patati; 
     771        } 
     772 
     773    if (($(".endRepeat").val() == 'occurrences'))  
     774        patati['count'] = $(".occurrencesEnd").val();  
     775         
     776    if (($(".endRepeat").val() == 'customDate')) 
     777        patati['endTime'] = Date.parseExact( $(".customDateEnd").val() + (!!form.allDay ? " 00:00": " "+$.trim(form.endHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'); 
     778         
     779    patati['interval']  = $(".eventInterval").val(); 
     780 
     781    /** 
    721782        wkst = [ 'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU' ] 
    722783        weekno = number 
     
    740801function encodeRepeat( repeat ){ 
    741802   
    742         if( !repeat ) 
    743             return( false ); 
    744         if(typeof(repeat) == "object") 
    745             return repeat; 
    746  
    747         return DataLayer.get( 'repeat', repeat ); 
     803    if( !repeat ) 
     804        return( false ); 
     805    if(typeof(repeat) == "object") 
     806        return repeat; 
     807 
     808    return DataLayer.get( 'repeat', repeat ); 
    748809} 
    749810 
     
    755816         
    756817        if( notArray = $.type(evtObj) !== "array" ) 
    757                 evtObj = [ evtObj ]; 
     818            evtObj = [ evtObj ]; 
    758819 
    759820        var pref = User.preferences; 
     
    761822        var res = $.map(evtObj, function( form ){ 
    762823     
    763                     var tzId =  form.timezone || Calendar.signatureOf[form.calendar].calendar.timezone || User.preferences.timezone, 
    764  
    765                     formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? pref.dateFormat+" HH:mm" : pref.dateFormat + " " + pref.hourFormat; 
    766  
    767                     var Owner = decodeOwnerCalendar(form.calendar); 
    768  
     824            var tzId =  form.timezone || Calendar.signatureOf[form.calendar].calendar.timezone || User.preferences.timezone, 
     825 
     826            formatString = ( typeof form.allDay !== "undefined" && !!form.allDay )? pref.dateFormat+" HH:mm" : pref.dateFormat + " " + pref.hourFormat; 
     827 
     828            var Owner = decodeOwnerCalendar(form.calendar); 
     829 
     830            return { 
     831                "class": form["class"], 
     832                startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'), 
     833                endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'),  //+ (!!form.allDay ? 86400000 : 0) , 
     834                allDay: ( !!form.allDay ? 1 : 0 ),        
     835                id: form.idEvent, 
     836                location: form.location, 
     837                category: form.category, 
     838                calendar: form.calendar, 
     839                summary: form.summary, 
     840                description: form.description, 
     841                timezone: tzId, 
     842                attachments: $.map(form.attachment || [], function( attachment, i ){ 
    769843                    return { 
    770                             "class": form["class"], 
    771                             startTime: Date.parseExact(form.startDate + (!!form.allDay ? " 00:00": " "+$.trim(form.startHour)) , formatString ).toString('yyyy-MM-dd HH:mm:00'), 
    772                             endTime:  Date.parseExact(form.endDate + ( !!form.allDay ? " 00:00": " "+$.trim(form.endHour)), formatString ).toString('yyyy-MM-dd HH:mm:00'),  //+ (!!form.allDay ? 86400000 : 0) , 
    773                             allDay: ( !!form.allDay ? 1 : 0 ),        
    774                             id: form.idEvent, 
    775                             location: form.location, 
    776                             category: form.category, 
    777                             calendar: form.calendar, 
    778                             summary: form.summary, 
    779                             description: form.description, 
    780                             timezone: tzId, 
    781                             attachments: $.map(form.attachment || [], function( attachment, i ){ 
    782                                         return {attachment: attachment} 
     844                        attachment: attachment 
     845                    } 
     846                }), 
     847                repeat: this.decodeRepeat( form ), 
     848                participants: $.map( form.attendee || [], function( attendee, i ){ 
     849 
     850                    if( !attendee || attendee === "" ) 
     851                        return( null ); 
     852 
     853                    var participant = {}; 
     854                    participant.user = (attendee!= User.me.id) ? DataLayer.get('participant', attendee).user : attendee ; 
     855 
     856                    if( participant.user === Owner.id ){ 
     857                        return DataLayer.merge({ 
     858                            id: attendee, 
     859                            isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ), 
     860                            acl: form.attendee_organizer == attendee ? (form.attendeeAcl[i].indexOf('o') < 0 ? form.attendeeAcl[i]+'o' : form.attendeeAcl[i]) : form.attendeeAcl[i].replace('o', ''), 
     861                            alarms: participant.alarms = $.map( form.alarmTime || [], function( alarmTime, i ){ 
     862                                if( alarmTime === "" ) 
     863                                    return( null ); 
     864                                return !!form.alarmId[i] ? { 
     865                                    type: form.alarmType[i],  
     866                                    unit: form.alarmUnit[i],  
     867                                    time: form.alarmTime[i],  
     868                                    id: form.alarmId[i] 
     869                                    }: 
     870 
     871                                    { 
     872                                    type: form.alarmType[i], 
     873                                    unit: form.alarmUnit[i],  
     874                                    time: form.alarmTime[i] 
     875                                    }; 
    783876                            }), 
    784                             repeat: this.decodeRepeat( form ), 
    785                             participants: $.map( form.attendee || [], function( attendee, i ){ 
    786  
    787                                 if( !attendee || attendee === "" ) 
    788                                     return( null ); 
    789  
    790                                 var participant = {}; 
    791                                 participant.user = (attendee!= User.me.id) ? DataLayer.get('participant', attendee).user : attendee ; 
    792  
    793                                 if( participant.user === Owner.id ){ 
    794                                     return DataLayer.merge({ 
    795                                     id: attendee, 
    796                                     isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ), 
    797                                     acl: form.attendee_organizer == attendee ? (form.attendeeAcl[i].indexOf('o') < 0 ? form.attendeeAcl[i]+'o' : form.attendeeAcl[i]) : form.attendeeAcl[i].replace('o', ''), 
    798                                     alarms: participant.alarms = $.map( form.alarmTime || [], function( alarmTime, i ){ 
    799                                         if( alarmTime === "" ) 
    800                                             return( null ); 
    801                                         return !!form.alarmId[i] ? { type: form.alarmType[i], unit: form.alarmUnit[i], time: form.alarmTime[i], id: form.alarmId[i] }: 
    802                                             { type: form.alarmType[i],unit: form.alarmUnit[i], time: form.alarmTime[i] }; 
    803                                         }), 
    804                                     status: !!form.status ? form.status : 3 
    805                                     }, form.delegatedFrom[i] != '0' ? {delegatedFrom: form.delegatedFrom[i]} : {}); 
    806                                 }else{ 
    807                                     return DataLayer.merge({ 
    808                                         id: attendee, 
    809                                         acl: form.attendeeAcl[i], 
    810                                         isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ), 
    811                                         isExternal: !!parseInt(form.attendeeType[i]) ? 1 : 0, 
    812                                         acl: form.attendee_organizer == attendee ? (form.attendeeAcl[i].indexOf('o') < 0 ? form.attendeeAcl[i]+'o' : form.attendeeAcl[i]) : form.attendeeAcl[i].replace('o', '') 
    813                                     }, form.delegatedFrom[i] != '0' ? {delegatedFrom: form.delegatedFrom[i]} : {}); 
    814                                 }; 
    815                             }) 
    816                         }; 
    817                     }); 
     877                            status: !!form.status ? form.status : 3 
     878                        }, (form.delegatedFrom[i] != '0' && form.delegatedFrom[i] != '')  ? { 
     879                            delegatedFrom: form.delegatedFrom[i] 
     880                            } : {}); 
     881                    }else{ 
     882                        return DataLayer.merge({ 
     883                            id: attendee, 
     884                            acl: form.attendeeAcl[i], 
     885                            isOrganizer: (form.attendee_organizer == attendee ? 1 : 0 ), 
     886                            isExternal: !!parseInt(form.attendeeType[i]) ? 1 : 0, 
     887                            acl: form.attendee_organizer == attendee ? (form.attendeeAcl[i].indexOf('o') < 0 ? form.attendeeAcl[i]+'o' : form.attendeeAcl[i]) : form.attendeeAcl[i].replace('o', '') 
     888                        }, form.delegatedFrom[i] != '0' ? { 
     889                            delegatedFrom: form.delegatedFrom[i] 
     890                            } : {}); 
     891                    }; 
     892                }) 
     893            }; 
     894        }); 
    818895 
    819896        return notArray ? res[0] : res; 
     
    823900    encoder: function( evtObj ){ 
    824901         
    825                 if(!(!!evtObj)) 
    826                         return undefined; 
    827  
    828                 var notArray = false; 
     902        if(!(!!evtObj)) 
     903            return undefined; 
     904 
     905        var notArray = false; 
    829906                   
    830                 if( notArray = $.type(evtObj) !== "array" ) 
    831                         evtObj = [ evtObj ]; 
    832  
    833                 var pref = User.preferences; 
    834  
    835                 var res =  DataLayer.encode('schedulable:preview', evtObj); 
    836  
    837                 if( !notArray ){ 
    838                         var dates = {}; 
    839                         var typeRepeat = {'none': false,  
    840                                         'daily': 'Repetição diária', 
    841                                         'weekly': 'Repetição semanal', 
    842                                         'monthly': 'Repetição mensal', 
    843                                         'yearly': 'repetição anual'} 
    844  
    845                         for (var i=0; i < res.length; i++) { 
     907        if( notArray = $.type(evtObj) !== "array" ) 
     908            evtObj = [ evtObj ]; 
     909 
     910        var pref = User.preferences; 
     911 
     912        var res =  DataLayer.encode('schedulable:preview', evtObj); 
     913 
     914        if( !notArray ){ 
     915            var dates = {}; 
     916            var typeRepeat = { 
     917                'none': false,  
     918                'daily': 'Repetição diária', 
     919                'weekly': 'Repetição semanal', 
     920                'monthly': 'Repetição mensal', 
     921                'yearly': 'repetição anual' 
     922            } 
     923 
     924            for (var i=0; i < res.length; i++) { 
    846925                           
    847                                 var startDate = Date.parseExact( res[i]['startDate'], User.preferences.dateFormat ); 
    848                                 var endDate   = Date.parseExact( res[i]['endDate'], User.preferences.dateFormat ); 
     926                var startDate = Date.parseExact( res[i]['startDate'], User.preferences.dateFormat ); 
     927                var endDate   = Date.parseExact( res[i]['endDate'], User.preferences.dateFormat ); 
    849928                           
    850                                 var duration = parseInt( endDate.getTime() ) - parseInt( startDate.getTime() ); 
    851                  
    852                                 var occurrences = [ startDate.getTime() ]; 
     929                var duration = parseInt( endDate.getTime() ) - parseInt( startDate.getTime() ); 
     930                 
     931                var occurrences = [ startDate.getTime() ]; 
    853932                                 
    854                                 if( res[i].occurrences ) 
    855                                 { 
    856                                     occurrences = res[i].occurrences; 
    857                                 } 
    858  
    859                                 for( var ii = 0; ii < occurrences.length; ii++ ) 
    860                                 { 
    861                                     var currentDate = new Date( occurrences[ii] ); 
    862                                     var counter = currentDate.clone(); 
     933                if( res[i].occurrences ) 
     934                { 
     935                    occurrences = res[i].occurrences; 
     936                } 
     937 
     938                for( var ii = 0; ii < occurrences.length; ii++ ) 
     939                { 
     940                    var currentDate = new Date( occurrences[ii] ); 
     941                    var counter = currentDate.clone(); 
    863942                                     
    864                                     var res2 = $.extend( {}, res[i], {'startDate': currentDate.toString( User.preferences.dateFormat ), 'endDate': new Date( occurrences[ii] + duration ).toString( User.preferences.dateFormat ) } ); 
     943                    var res2 = $.extend( {}, res[i], { 
     944                        'startDate': currentDate.toString( User.preferences.dateFormat ),  
     945                        'endDate': new Date( occurrences[ii] + duration ).toString( User.preferences.dateFormat ) 
     946                        } ); 
    865947                                   
    866948                                   
    867949                                   
    868950                                   
    869                                     res2.repeat = typeRepeat[res[i].repeat.frequency]; 
     951                    res2.repeat = typeRepeat[res[i].repeat.frequency]; 
    870952                                   
    871                                     while (counter.compareTo( currentDate ) == 0) { 
    872  
    873                                             if (!dates[counter.toString(User.preferences.dateFormat)])  
    874                                                     dates[counter.toString(User.preferences.dateFormat)] = { startDate:false, events:[] }; 
    875                                             if (!dates[counter.toString(User.preferences.dateFormat)].startDate)  
    876                                                     dates[counter.toString(User.preferences.dateFormat)].startDate = counter.toString(User.preferences.dateFormat); 
    877  
    878                                             dates[counter.toString(User.preferences.dateFormat)].events.push(res2); 
    879                                             counter.addDays(-1); 
    880                                     }       
    881                                 } 
    882                         } 
    883                         res = { events_list: dates, 
    884                                         count : res.length 
    885                                 }; 
     953                    while (counter.compareTo( currentDate ) == 0) { 
     954 
     955                        if (!dates[counter.toString(User.preferences.dateFormat)])  
     956                            dates[counter.toString(User.preferences.dateFormat)] = { 
     957                                startDate:false,  
     958                                events:[] 
     959                            }; 
     960                        if (!dates[counter.toString(User.preferences.dateFormat)].startDate)  
     961                            dates[counter.toString(User.preferences.dateFormat)].startDate = counter.toString(User.preferences.dateFormat); 
     962 
     963                        dates[counter.toString(User.preferences.dateFormat)].events.push(res2); 
     964                        counter.addDays(-1); 
     965                    }       
    886966                } 
    887  
    888                 return notArray ? res[0] : res; 
     967            } 
     968            res = { 
     969                events_list: dates, 
     970                count : res.length 
     971            }; 
     972        } 
     973 
     974        return notArray ? res[0] : res; 
    889975    } 
    890976 
     
    895981    encoder: function( participants ){ 
    896982 
    897                 var result = {}; 
    898                 for( var i = 0; i< participants.length; i++ ){ 
    899                         result[ participants[i].user.id || participants[i].user ] = participants[i]; 
    900                 } 
    901                 return( result ); 
     983        var result = {}; 
     984        for( var i = 0; i< participants.length; i++ ){ 
     985            result[ participants[i].user.id || participants[i].user ] = participants[i]; 
     986        } 
     987        return( result ); 
    902988    } 
    903989}); 
     
    907993    encoder: function( calendars ){ 
    908994 
    909                 var result = { my_calendars: [], others_calendars: [] }; 
    910  
    911                 for( var i = 0; i < calendars.length; i++ ) 
    912                 { 
    913                         !!Calendar.signatureOf[ calendars[i].id ].isOwner ? 
    914                                 result.my_calendars.push( calendars[i] ) : 
    915                                 result.others_calendars.push( calendars[i] ); 
    916                 } 
    917  
    918                 return { agendas_usuario: result }; 
     995        var result = { 
     996            my_calendars: [],  
     997            others_calendars: [] 
     998        }; 
     999 
     1000        for( var i = 0; i < calendars.length; i++ ) 
     1001        { 
     1002            !!Calendar.signatureOf[ calendars[i].id ].isOwner ? 
     1003            result.my_calendars.push( calendars[i] ) : 
     1004            result.others_calendars.push( calendars[i] ); 
     1005        } 
     1006 
     1007        return { 
     1008            agendas_usuario: result 
     1009        }; 
    9191010 
    9201011    } 
     
    9311022        var res = $.map(evtObj, function( evt ){ 
    9321023 
    933                     return { id: evt.id, 
    934                              summary: evt.title, 
    935                              startTime: evt.start.getTime(), 
    936                              endTime: ( !!evt.allDay ? (( evt.end || evt.start ).getTime() + 86400000) :( evt.end || evt.start ).getTime()), 
    937                              allDay: ( !!evt.allDay ? 1 : 0 ) 
    938                              /*calendar: evt.id && User.calendarOf[ evt.id ].id*/ }; 
     1024            return { 
     1025                id: evt.id, 
     1026                summary: evt.title, 
     1027                startTime: evt.start.getTime(), 
     1028                endTime: ( !!evt.allDay ? (( evt.end || evt.start ).getTime() + 86400000) :( evt.end || evt.start ).getTime()), 
     1029                allDay: ( !!evt.allDay ? 1 : 0 ) 
     1030            /*calendar: evt.id && User.calendarOf[ evt.id ].id*/ }; 
    9391031        }); 
    9401032 
     
    9481040 
    9491041        var filtered = evtObj; 
    950 //  
     1042        //  
    9511043        var grouped = {}; 
    9521044 
    9531045        $.map(filtered, function( evt ){ 
    9541046                 
    955                 if(!(typeof(evt) == 'object') || (evt.id.indexOf('java') >= 0)) 
    956                         return (null); 
    957  
    958                 evt.calendar = evt.calendar || "1"; 
    959  
    960                 if( !grouped[ evt.calendar ] ) 
    961                     grouped[ evt.calendar ] = []; 
     1047            if(!(typeof(evt) == 'object') || (evt.id.indexOf('java') >= 0)) 
     1048                return (null); 
     1049 
     1050            evt.calendar = evt.calendar || "1"; 
     1051 
     1052            if( !grouped[ evt.calendar ] ) 
     1053                grouped[ evt.calendar ] = []; 
    9621054                         
    963                 var calendar = DataLayer.get('calendar', evt.calendar); 
    964                  
    965                 var eventEditable = function(idEvent, isRecurrence, Recurrence){ 
    966                         if(Calendar.signatureOf[calendar.id].isOwner == "1"){ 
    967                                 var attendee = {}; 
    968                                 for(var i = 0; i < evt.participants.length; i++){ 
    969                                         attendee = DataLayer.get('participant', evt.participants[i]); 
    970                                                 if(attendee.user == User.me.id) 
    971                                                         return (attendee.acl.indexOf('w') >= 0 || attendee.acl.indexOf('o') >= 0 ) ? {selectable: true, className: 'fullcalendar-context-menu  event-id-'+idEvent+ (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '')} : { editable: false, selectable: true ,className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent}; 
    972                                 } 
    973                                 return {editable: false, className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent,  selectable: true, disableDragging: isRecurrence }; 
    974                         } 
    975                         else{ 
    976                                 var aclSignature = Calendar.signatureOf[calendar.id].permission; 
     1055            var calendar = DataLayer.get('calendar', evt.calendar); 
     1056                 
     1057            var eventEditable = function(idEvent, isRecurrence, Recurrence){ 
     1058                if(Calendar.signatureOf[calendar.id].isOwner == "1"){ 
     1059                    var attendee = {}; 
     1060                    for(var i = 0; i < evt.participants.length; i++){ 
     1061                        attendee = DataLayer.get('participant', evt.participants[i]); 
     1062                        if(attendee.user == User.me.id) 
     1063                            return (attendee.acl.indexOf('w') >= 0 || attendee.acl.indexOf('o') >= 0 ) ? { 
     1064                                selectable: true,  
     1065                                className: 'fullcalendar-context-menu  event-id-'+idEvent+ (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '') 
     1066                                } : { 
     1067                                editable: false,  
     1068                                selectable: true , 
     1069                                className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent 
     1070                                }; 
     1071                    } 
     1072                    return { 
     1073                        editable: false,  
     1074                        className: 'blocked-event-permision  fullcalendar-not-context-menu event-id-'+idEvent,   
     1075                        selectable: true,  
     1076                        disableDragging: isRecurrence 
     1077                    }; 
     1078                } 
     1079                else{ 
     1080                    var aclSignature = Calendar.signatureOf[calendar.id].permission; 
    9771081                                 
    978                                 var mountClass =  function(acl){ 
    979                                         var returns = "" 
    980                                         returns += acl['write'] ? "" :  'blocked-event-permision '; 
    981                                         returns += acl['busy'] ? 'fullcalendar-not-context-menu ' : (acl['read']  ?  'fullcalendar-context-menu '+ idEvent + (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '') : ''); 
    982                                         returns += 'event-id-'+idEvent; 
    983                                         return returns; 
    984                                 }                                
    985                                 return DataLayer.merge({ 
    986                                         editable: aclSignature.acl['write'] && !isRecurrence, 
    987                                         disableResizing : (((aclSignature.acl['busy'] && !aclSignature.acl['write']) || (!aclSignature.acl['write'] && aclSignature.acl['read'])) ? true : false), 
    988                                         disableDragging  : (((aclSignature.acl['busy'] && !aclSignature.acl['write']) || (!aclSignature.acl['write'] && aclSignature.acl['read'])) ? true: false), 
    989                                         className: mountClass(aclSignature.acl) 
    990                                 }, aclSignature.acl['busy'] ? {title: 'Ocupado', selectable: false } : {selectable: true}); 
    991                         } 
     1082                    var mountClass =  function(acl){ 
     1083                        var returns = "" 
     1084                        returns += acl['write'] ? "" :  'blocked-event-permision '; 
     1085                        returns += acl['busy'] ? 'fullcalendar-not-context-menu ' : (acl['read']  ?  'fullcalendar-context-menu '+ idEvent + (isRecurrence ? ' isRecurrence Recurrence-id-'+Recurrence : '') : ''); 
     1086                        returns += 'event-id-'+idEvent; 
     1087                        return returns; 
     1088                    }                            
     1089                    return DataLayer.merge({ 
     1090                        editable: aclSignature.acl['write'] && !isRecurrence, 
     1091                        disableResizing : (((aclSignature.acl['busy'] && !aclSignature.acl['write']) || (!aclSignature.acl['write'] && aclSignature.acl['read'])) ? true : false), 
     1092                        disableDragging  : (((aclSignature.acl['busy'] && !aclSignature.acl['write']) || (!aclSignature.acl['write'] && aclSignature.acl['read'])) ? true: false), 
     1093                        className: mountClass(aclSignature.acl) 
     1094                    }, aclSignature.acl['busy'] ? { 
     1095                        title: 'Ocupado',  
     1096                        selectable: false 
     1097                    } : { 
     1098                        selectable: true 
     1099                    }); 
     1100                } 
    9921101                         
    993                 } 
    994                  
    995                 var duration = parseInt( evt.endTime ) - parseInt( evt.startTime ), isRepeat = false; 
    996                  
    997                 var occurrences = []; 
    998                  
    999                 if( evt.occurrences ) 
    1000                 { 
    1001                     isRepeat = true; 
    1002                     occurrences = evt.occurrences; 
    1003                 }else 
    1004                     occurrences[ occurrences.length ] = evt.startTime; 
    1005  
    1006                 //occurrences = DataLayer.unique( occurrences ).sort(); 
     1102            } 
     1103                 
     1104            var duration = parseInt( evt.endTime ) - parseInt( evt.startTime ), isRepeat = false; 
     1105                 
     1106            var occurrences = []; 
     1107                 
     1108            if( evt.occurrences ) 
     1109            { 
     1110                isRepeat = true; 
     1111                occurrences = evt.occurrences; 
     1112            }else 
     1113                occurrences[ occurrences.length ] = evt.startTime; 
     1114 
     1115            //occurrences = DataLayer.unique( occurrences ).sort(); 
    10071116                   
    1008                 for( var i = 0; i < occurrences.length; i++ ) 
    1009                     grouped[ evt.calendar ].push( DataLayer.merge({ id: evt.URI || evt.id+ '-' + i, 
    1010                     title: Encoder.htmlDecode(evt.summary), 
    1011                     start: Timezone.getDateCalendar(new Date( parseInt( occurrences[i] ) ), calendar.timezone,  !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving), 
    1012                     end:   Timezone.getDateCalendar(new Date( parseInt( occurrences[i] ) + duration - (!!parseInt(evt.allDay) ? 86400000 : 0)), calendar.timezone, !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving), 
    1013                     allDay: parseInt( evt.allDay ), 
    1014                     isRepeat: isRepeat, 
    1015                     occurrence: i, 
    1016                     calendar: evt.calendar}, eventEditable(evt.id, isRepeat, i ) ) ); 
     1117            for( var i = 0; i < occurrences.length; i++ ) 
     1118                grouped[ evt.calendar ].push( DataLayer.merge({ 
     1119                    id: evt.URI || evt.id+ '-' + i, 
     1120                    title: Encoder.htmlDecode(evt.summary), 
     1121                    start: Timezone.getDateCalendar(new Date( parseInt( occurrences[i] ) ), calendar.timezone,  !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving), 
     1122                    end:   Timezone.getDateCalendar(new Date( parseInt( occurrences[i] ) + duration - (!!parseInt(evt.allDay) ? 86400000 : 0)), calendar.timezone, !!evt.DayLigth ? evt.DayLigth.calendar.startTime : Timezone.daylightSaving), 
     1123                    allDay: parseInt( evt.allDay ), 
     1124                    isRepeat: isRepeat, 
     1125                    occurrence: i, 
     1126                    calendar: evt.calendar 
     1127                    }, eventEditable(evt.id, isRepeat, i ) ) ); 
    10171128        }); 
    10181129 
     
    10221133    criteria: function( filter ){ 
    10231134       
    1024                 if( $.type(filter.start) !== 'date' ) 
    1025                         filter.start = new Date( filter.start * 1000 ); 
    1026                 if( $.type(filter.end) !== 'date' ) 
    1027                         filter.end = new Date( filter.end * 1000 ); 
    1028  
    1029                 var timezone = {}; 
    1030                 for(var i in Calendar.signatureOf) 
    1031                         timezone[i] = Calendar.signatureOf[i].calendar.timezone; 
    1032                  
    1033                 return { filter: ["AND",  
    1034  
    1035                                         [ ">=", "rangeStart", filter.start.getTime() ], 
    1036                                         [ "<=", "rangeEnd", filter.end.getTime() ], 
    1037                                         [ "IN", "calendar", Calendar.calendarIds ] 
    1038  
    1039                                   ],  
    1040                  criteria: { deepness: 2, timezones: timezone } } 
    1041     } 
     1135        if( $.type(filter.start) !== 'date' ) 
     1136            filter.start = new Date( filter.start * 1000 ); 
     1137        if( $.type(filter.end) !== 'date' ) 
     1138            filter.end = new Date( filter.end * 1000 ); 
     1139 
     1140        var timezone = {}; 
     1141        for(var i in Calendar.signatureOf) 
     1142            timezone[i] = Calendar.signatureOf[i].calendar.timezone; 
     1143                 
     1144        return { 
     1145            filter: ["AND",  
     1146 
     1147            [ ">=", "rangeStart", filter.start.getTime() ], 
     1148            [ "<=", "rangeEnd", filter.end.getTime() ], 
     1149            [ "IN", "calendar", Calendar.calendarIds ] 
     1150 
     1151            ],  
     1152            criteria: { 
     1153                deepness: 2,  
     1154                timezones: timezone 
     1155            } 
     1156        } 
     1157} 
    10421158}); 
    10431159 
     
    10451161DataLayer.codec( "preference", "detail", { 
    10461162   
    1047         decoder:function( pref ){ 
    1048          
    1049                 var res = []; 
    1050  
    1051                 pref.defaultAlarm = $.map( pref.alarmTime || [], function( alarmTime, i ){ 
     1163    decoder:function( pref ){ 
     1164         
     1165        var res = []; 
     1166 
     1167        pref.defaultAlarm = $.map( pref.alarmTime || [], function( alarmTime, i ){ 
    10521168                   
    1053                         return { type: pref.alarmType[i],  
    1054                                 time: alarmTime, 
    1055                                 unit: pref.alarmUnit[i] }; 
    1056                         }); 
    1057  
    1058                 $.each( pref, function( i, el ){ 
    1059  
    1060                         res[ res.length ] = { name: i, value: el }; 
    1061  
    1062                 }); 
    1063                  
    1064                 return( res ); 
     1169            return { 
     1170                type: pref.alarmType[i],  
     1171                time: alarmTime, 
     1172                unit: pref.alarmUnit[i] 
     1173                }; 
     1174        }); 
     1175 
     1176        $.each( pref, function( i, el ){ 
     1177 
     1178            res[ res.length ] = { 
     1179                name: i,  
     1180                value: el 
     1181            }; 
     1182 
     1183        }); 
     1184                 
     1185        return( res ); 
    10651186       
    1066         }, 
    1067  
    1068         encoder:function( pref ){ 
    1069                 return( pref ); 
    1070         } 
     1187    }, 
     1188 
     1189    encoder:function( pref ){ 
     1190        return( pref ); 
     1191    } 
    10711192 
    10721193}); 
     
    10741195DataLayer.codec( "schedulable", "export", { 
    10751196   
    1076         decoder: function(){}, 
     1197    decoder: function(){}, 
    10771198       
    10781199    encoder: function( signatures ){}, 
     
    10801201    criteria: function( filter ){ 
    10811202         
    1082                 if( isCal  = filter && filter.calendar ) 
    1083                         filter = filter.calendar; 
    1084                         return { 
    1085                                 filter: filter ? [  "=", ( isCal ? "calendar" : "id" ), filter ] : false, 
    1086                                 criteria: { format: 'iCal', deepness: 2 } 
    1087                         }; 
    1088                 } 
     1203        if( isCal  = filter && filter.calendar ) 
     1204            filter = filter.calendar; 
     1205        return { 
     1206            filter: filter ? [  "=", ( isCal ? "calendar" : "id" ), filter ] : false, 
     1207            criteria: { 
     1208                format: 'iCal',  
     1209                deepness: 2 
     1210            } 
     1211        }; 
     1212    } 
    10891213}); 
    10901214 
  • trunk/prototype/modules/calendar/js/calendar.shared.js

    r6052 r6066  
    22    var html = DataLayer.render('templates/shared_calendar.ejs', { 
    33        calendar: Calendar.calendars 
    4         });      
     4    });  
    55         
    66    //Variaval global para manipulação dos usuários 
     
    9292                var permission = DataLayer.get('calendarToPermission', { 
    9393                    filter: ['AND', ['=', 'calendar', calendarId], ['=', 'user', '0']] 
    94                     }, true); 
     94                }, true); 
    9595                if($.isArray(permission)) 
    9696                    permission = permission[0]; 
     
    186186                        name: currentUsers [id] .name,  
    187187                        mail: currentUsers [id] .mail 
    188                         }])) 
     188                    }])) 
    189189                    .scrollTo('max'); 
    190190                                                 
     
    300300        } 
    301301    }); 
    302 if(dataCurrent){ 
    303     for(var i = 0; i < dataCurrent.length; i++){ 
    304         if(dataCurrent[i].user == "0"){ 
    305             UI.dialogs.sharedCalendar.find('input[name="isPublic"]').attr('checked', 'checked') 
    306             .parent().find('.free-busy').toggleClass('hidden'); 
    307             if(dataCurrent[i].acl['busy']) 
    308                 UI.dialogs.sharedCalendar.find('input[name="busy"]').attr('checked', 'checked'); 
    309         }else{ 
    310             currentUsers[dataCurrent[i].user.id] = true; 
    311  
    312             UI.dialogs.sharedCalendar.find('dd.user-list ul.user-list') 
    313             .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [{ 
    314                 id: dataCurrent[i].user.id,  
    315                 name: dataCurrent[i].user.name,  
    316                 mail: dataCurrent[i].user.mail,  
    317                 acl:dataCurrent[i].acl,  
    318                 aclValue: dataCurrent[i].aclValues,  
    319                 current: true,  
    320                 idPermission: dataCurrent[i].id 
    321             }])) 
    322             .scrollTo('max'); 
    323             $('li.not-user').remove(); 
    324             callbackSharedCotactsAdd(); 
    325  
    326             for (var f in dataCurrent[i].acl){ 
    327                 if(dataCurrent[i].acl[f]){ 
    328                     UI.dialogs.sharedCalendar.find('.'+f+':last').toggleClass('attendee-permissions-change-button') 
    329                     .find('span:first').toggleClass('attendee-permissions-change').end();   
    330                 } 
    331             } 
    332         } 
    333     } 
    334 } 
    335 UI.dialogs.sharedCalendar.dialog('open'); 
     302    if(dataCurrent){ 
     303        for(var i = 0; i < dataCurrent.length; i++){ 
     304            if(dataCurrent[i].user == "0"){ 
     305                UI.dialogs.sharedCalendar.find('input[name="isPublic"]').attr('checked', 'checked') 
     306                .parent().find('.free-busy').toggleClass('hidden'); 
     307                if(dataCurrent[i].acl['busy']) 
     308                    UI.dialogs.sharedCalendar.find('input[name="busy"]').attr('checked', 'checked'); 
     309            }else{ 
     310                currentUsers[dataCurrent[i].user.id] = true; 
     311 
     312                UI.dialogs.sharedCalendar.find('dd.user-list ul.user-list') 
     313                .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [{ 
     314                    id: dataCurrent[i].user.id,  
     315                    name: dataCurrent[i].user.name,  
     316                    mail: dataCurrent[i].user.mail,  
     317                    acl:dataCurrent[i].acl,  
     318                    aclValue: dataCurrent[i].aclValues,  
     319                    current: true,  
     320                    idPermission: dataCurrent[i].id 
     321                }])) 
     322                .scrollTo('max'); 
     323                $('li.not-user').remove(); 
     324                callbackSharedCotactsAdd(); 
     325 
     326                for (var f in dataCurrent[i].acl){ 
     327                    if(dataCurrent[i].acl[f]){ 
     328                        UI.dialogs.sharedCalendar.find('.'+f+':last').toggleClass('attendee-permissions-change-button') 
     329                        .find('span:first').toggleClass('attendee-permissions-change').end();   
     330                    } 
     331                } 
     332            } 
     333        } 
     334    } 
     335    UI.dialogs.sharedCalendar.dialog('open'); 
    336336} 
    337337 
     
    378378                backgroundColor: (!!type ? 'fbec88' : '8c8c8c'),  
    379379                borderColor: (!!type ? 'fad24e' : '120d0d') 
    380                 }, !!idPermission ? { 
     380            }, !!idPermission ? { 
    381381                id: idPermission 
    382382            } : {} )); 
     
    405405                } 
    406406            }, true); 
    407         var resultPublic = DataLayer.get('calendarToPermission', { 
    408             filter: ['AND', ['=','type',1],   ['OR', ['i*','name',$(this).val()], ["i*", "description", $(this).val()]]]  ,  
    409             criteria: { 
    410                 deepness: 2 
    411             } 
    412         }, true); 
    413  
    414     /** 
     407            var resultPublic = DataLayer.get('calendarToPermission', { 
     408                filter: ['AND', ['=','type',1],   ['OR', ['i*','name',$(this).val()], ["i*", "description", $(this).val()]]]  ,  
     409                criteria: { 
     410                    deepness: 2 
     411                } 
     412            }, true); 
     413 
     414            /** 
    415415    * TODO: trocar por template 
    416416    */ 
    417     UI.dialogs.sharedCalendar.find('ul.search-result-list').empty().css('overflow', 'hidden'); 
    418         if (!result && !resultPublic) { 
    419             UI.dialogs.sharedCalendar.find('ul.search-result-list').append('<li><label class="empty">Nenhum resultado encontrado.</label></li>'); 
    420         } 
    421                                  
    422         if(resultPublic){ 
    423             var notConflict = []; 
    424             var conflit = false; 
    425             for(var i = 0; i < resultPublic.length; i++){ 
    426                 for(var j = 0; j < result.length; j++){ 
    427                     if(resultPublic[i].id == result[j].calendar.id) 
    428                         conflit = true; 
    429                 } 
    430                 if(!conflit){ 
    431                     notConflict.push(resultPublic[i]); 
    432                     conflit = false; 
    433                 } 
    434             } 
    435         } 
    436         resultPublic = notConflict; 
    437                                  
    438         var resultNormalize = []; 
    439         for(i=0; i<result.length; i++){ 
    440             resultNormalize.push({ 
    441                 id: result[i].calendar.id,  
    442                 name:result[i].calendar.name,  
    443                 mail: result[i].calendar.description,  
    444                 type: 0 
    445             }) 
    446             resultNormalize[i].enabled = currentCalendars[result[i].id] ? false : true; 
    447         } 
    448         if(resultPublic) 
    449             for(i=0; i<resultPublic.length; i++){ 
     417            UI.dialogs.sharedCalendar.find('ul.search-result-list').empty().css('overflow', 'hidden'); 
     418            if (!result && !resultPublic) { 
     419                UI.dialogs.sharedCalendar.find('ul.search-result-list').append('<li><label class="empty">Nenhum resultado encontrado.</label></li>'); 
     420            } 
     421                                 
     422            if(resultPublic){ 
     423                var notConflict = []; 
     424                var conflit = false; 
     425                for(var i = 0; i < resultPublic.length; i++){ 
     426                    for(var j = 0; j < result.length; j++){ 
     427                        if(resultPublic[i].id == result[j].calendar.id) 
     428                            conflit = true; 
     429                    } 
     430                    if(!conflit){ 
     431                        notConflict.push(resultPublic[i]); 
     432                        conflit = false; 
     433                    } 
     434                } 
     435            } 
     436            resultPublic = notConflict; 
     437                                 
     438            var resultNormalize = []; 
     439            for(i=0; i<result.length; i++){ 
    450440                resultNormalize.push({ 
    451                     id: resultPublic[i].calendar.id,  
    452                     name:resultPublic[i].calendar.name,  
    453                     mail: resultPublic[i].calendar.description, 
    454                     type: 1 
     441                    id: result[i].calendar.id,  
     442                    name:result[i].calendar.name,  
     443                    mail: result[i].calendar.description,  
     444                    type: 0 
    455445                }) 
    456                 resultNormalize[i].enabled = currentCalendars[resultPublic[i].id] ? false : true; 
    457             } 
    458                                  
    459         UI.dialogs.sharedCalendar.find('ul.search-result-list').append(DataLayer.render( 'templates/calendar_search_itemlist.ejs', resultNormalize)); 
    460  
    461         UI.dialogs.sharedCalendar.find('ul.search-result-list li').click(function(event, ui){ 
    462             if ($(event.target).is('input')) { 
    463                 old_item = $(event.target).parents('li'); 
    464                 var id = old_item.find('.id').html(); 
     446                resultNormalize[i].enabled = currentCalendars[result[i].id] ? false : true; 
     447            } 
     448            if(resultPublic) 
     449                for(i=0; i<resultPublic.length; i++){ 
     450                    resultNormalize.push({ 
     451                        id: resultPublic[i].calendar.id,  
     452                        name:resultPublic[i].calendar.name,  
     453                        mail: resultPublic[i].calendar.description, 
     454                        type: 1 
     455                    }) 
     456                    resultNormalize[i].enabled = currentCalendars[resultPublic[i].id] ? false : true; 
     457                } 
     458                                 
     459            UI.dialogs.sharedCalendar.find('ul.search-result-list').append(DataLayer.render( 'templates/calendar_search_itemlist.ejs', resultNormalize)); 
     460 
     461            UI.dialogs.sharedCalendar.find('ul.search-result-list li').click(function(event, ui){ 
     462                if ($(event.target).is('input')) { 
     463                    old_item = $(event.target).parents('li'); 
     464                    var id = old_item.find('.id').html(); 
    465465                                                 
    466                 for(var i = 0; i<resultNormalize.length; i++){ 
    467                     if(resultNormalize[i].id == id) 
    468                         currentCalendars[id] = { 
    469                             id: id,  
    470                             name: resultNormalize[i].name,  
    471                             description: resultNormalize[i].description,  
    472                             type: resultNormalize[i].type,  
    473                             isCalendar: true 
    474                         }; 
    475                 } 
    476  
    477                 UI.dialogs.sharedCalendar.find('dd.calendar-list ul.user-list') 
    478                 .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [currentCalendars[id]])) 
    479                 .scrollTo('max'); 
     466                    for(var i = 0; i<resultNormalize.length; i++){ 
     467                        if(resultNormalize[i].id == id) 
     468                            currentCalendars[id] = { 
     469                                id: id,  
     470                                name: resultNormalize[i].name,  
     471                                description: resultNormalize[i].description,  
     472                                type: resultNormalize[i].type,  
     473                                isCalendar: true 
     474                            }; 
     475                    } 
     476 
     477                    UI.dialogs.sharedCalendar.find('dd.calendar-list ul.user-list') 
     478                    .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [currentCalendars[id]])) 
     479                    .scrollTo('max'); 
    480480                                                 
    481                 $('li.not-user').remove(); 
    482                 callbackSharedCalendarAdd(); 
    483                 old_item.remove(); 
    484             } 
    485         }); 
    486         event.preventDefault(); 
    487     } 
    488 }); 
    489                  
    490 var callbackSharedCalendarAdd = function(event){ 
    491                  
    492     UI.dialogs.sharedCalendar.find('.button').filter(".close.new").button({ 
    493         icons: { 
    494             primary: "ui-icon-close" 
    495         }, 
    496         text: false 
    497     }).click(function () { 
    498         var id = $(this).parents('li').find('input[name="idPermission"]').val(); 
    499         currentCalendars[$(this).parents().find('input[name="calendar[]"]').val()] = false; 
    500         $(this).parents('li').remove(); 
    501         if(!!id) 
    502         DataLayer.remove('calendarSignature', id); 
    503     }) 
    504     .addClass('tiny disable ui-button-disabled ui-state-disabled') 
    505     .removeClass('new').end(); 
    506  
    507     UI.dialogs.sharedCalendar.find('.user-list li').hover( 
    508         function () { 
    509             $(this).addClass("hover-user"); 
    510             $(this).find('.button').removeClass('disable ui-button-disabled ui-state-disabled').end() 
    511             .find('.user-acls-shared-calendar').addClass('hover-user'); 
    512         }, 
    513         function () { 
    514             $(this).removeClass("hover-user"); 
    515             $(this).find('.button').addClass('disable ui-button-disabled ui-state-disabled').end() 
    516             .find('.user-acls-shared-calendar').removeClass('hover-user');; 
    517         } 
    518         );               
    519 } 
    520  
    521 //Carrega os dados já cadastrados 
    522 for (var i = 0; i < Calendar.signatures.length; i++) 
    523     if(Calendar.signatures[i].isOwner == "0"){ 
    524         var dataCurrent = Calendar.signatures[i].calendar; 
    525         currentCalendars[Calendar.signatures[i].permission.id] = { 
    526             id: dataCurrent.id,  
    527             idPermission:Calendar.signatures[i].id , 
    528             name: dataCurrent.name,  
    529             description: dataCurrent.description,  
    530             type: Calendar.signatures[i].permission.type,  
    531             isCalendar: true, 
    532             current: true 
    533         }; 
     481                    $('li.not-user').remove(); 
     482                    callbackSharedCalendarAdd(); 
     483                    old_item.remove(); 
     484                } 
     485            }); 
     486            event.preventDefault(); 
     487        } 
     488    }); 
     489                 
     490    var callbackSharedCalendarAdd = function(event){ 
     491                 
     492        UI.dialogs.sharedCalendar.find('.button').filter(".close.new").button({ 
     493            icons: { 
     494                primary: "ui-icon-close" 
     495            }, 
     496            text: false 
     497        }).click(function () { 
     498            var id = $(this).parents('li').find('input[name="idPermission"]').val(); 
     499            currentCalendars[$(this).parents().find('input[name="calendar[]"]').val()] = false; 
     500            $(this).parents('li').remove(); 
     501            if(!!id) 
     502                DataLayer.remove('calendarSignature', id); 
     503        }) 
     504        .addClass('tiny disable ui-button-disabled ui-state-disabled') 
     505        .removeClass('new').end(); 
     506 
     507        UI.dialogs.sharedCalendar.find('.user-list li').hover( 
     508            function () { 
     509                $(this).addClass("hover-user"); 
     510                $(this).find('.button').removeClass('disable ui-button-disabled ui-state-disabled').end() 
     511                .find('.user-acls-shared-calendar').addClass('hover-user'); 
     512            }, 
     513            function () { 
     514                $(this).removeClass("hover-user"); 
     515                $(this).find('.button').addClass('disable ui-button-disabled ui-state-disabled').end() 
     516                .find('.user-acls-shared-calendar').removeClass('hover-user');; 
     517            } 
     518            );           
     519    } 
     520 
     521    //Carrega os dados já cadastrados 
     522    for (var i = 0; i < Calendar.signatures.length; i++) 
     523        if(Calendar.signatures[i].isOwner == "0"){ 
     524            var dataCurrent = Calendar.signatures[i].calendar; 
     525            currentCalendars[Calendar.signatures[i].permission.id] = { 
     526                id: dataCurrent.id,  
     527                idPermission:Calendar.signatures[i].id , 
     528                name: dataCurrent.name,  
     529                description: dataCurrent.description,  
     530                type: Calendar.signatures[i].permission.type,  
     531                isCalendar: true, 
     532                current: true 
     533            }; 
    534534                         
    535         UI.dialogs.sharedCalendar.find('dd.calendar-list ul.user-list') 
    536         .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [currentCalendars[Calendar.signatures[i].permission.id]])) 
    537         .scrollTo('max'); 
    538                                  
    539         $('li.not-user').remove(); 
    540         callbackSharedCalendarAdd(); 
    541     } 
    542                  
    543 UI.dialogs.sharedCalendar.dialog('open'); 
     535            UI.dialogs.sharedCalendar.find('dd.calendar-list ul.user-list') 
     536            .append(DataLayer.render('templates/user_shared_add_itemlist.ejs', [currentCalendars[Calendar.signatures[i].permission.id]])) 
     537            .scrollTo('max'); 
     538                                 
     539            $('li.not-user').remove(); 
     540            callbackSharedCalendarAdd(); 
     541        } 
     542                 
     543    UI.dialogs.sharedCalendar.dialog('open'); 
    544544} 
    545545 
  • trunk/prototype/modules/calendar/templates/attendee_add.ejs

    r5592 r6066  
    55                <dt class="me"><%= data.event.me.name %></dt> 
    66                <dd class="me"> 
    7                         <select class="status" name="status"> 
     7                    <select class="status" name="status" <%= data.event.isAttendee ? '' : 'disabled' %>> 
    88                                <%if(!data.event.delegatedFrom[data.event.me.id]){%> 
    99                                        <option value="1" <%= data.event.status=='1' ? 'selected="selected"':'' %>>Eu vou</option> 
     
    1717                                <%}%> 
    1818                        </select> 
    19                         <% if (!data.event.acl.organization && !data.event.acl.write && !data.event.acl.inviteGuests && !data.event.acl.participationRequired && !data.event.delegatedFrom[data.event.me.id] ) { %> 
     19                        <% if ((!data.event.acl.organization && !data.event.acl.write && !data.event.acl.inviteGuests && !data.event.acl.participationRequired && !data.event.delegatedFrom[data.event.me.id]) && data.event.isAttendee) { %> 
    2020                                <fieldset class="add-attendee-options-read"> 
    2121                                        <a href="#" class="button participant-delegate add-attendee-options-button">Delegar participação a um novo participante</a> 
     
    3939                <dd class="attendee-list"> 
    4040                        <ul class="attendee-list"> 
    41                                 <li class="organizer <%= (data.event.acl.organization) ? "hidden" : "" %>">  
     41                                <li class="organizer <%= (data.event.acl.organization || !data.event.isAttendee) ? "hidden" : "" %>">  
    4242                                        <div style="overflow:hidden; width:100%; display:table;"> 
    4343                                                <span class="space-status ui-icon <%=iconStatus[data.event.organizer.status]%>" title="<%=legendStatus[data.event.organizer.status]%>"></span> 
     
    126126                        </ul> 
    127127                </dd> 
    128                 <dd class="attendee-list-add"> 
     128                <dd class="attendee-list-add <%= data.event.acl.write && data.event.isAttendee ? '' : 'hidden' %>"> 
    129129                        <fieldset class="add-attendee-input input-field-rounded ui-corner-all"> 
    130130                                <span class="ui-icon ui-icon-plus"></span> 
  • trunk/prototype/modules/calendar/templates/event_add.ejs

    r5916 r6066  
    2626                        </select> 
    2727                         
    28                         <a class="button suggestion-hours small <%=(data.event.acl.organization || data.event.acl.write) ? "hidden" : '' %>" href="#">Sugerir horário</a> 
     28                        <a class="button suggestion-hours small <%=(data.event.acl.organization || data.event.acl.write || !data.event.isAttendee) ? "hidden" : '' %>" href="#">Sugerir horário</a> 
    2929                         
    3030                </p> 
  • trunk/prototype/modules/calendar/templates/event_repeat.ejs

    r5715 r6066  
    55        <p class="input-group"> 
    66                <label for="frequency">Repetição:</label> 
    7                 <select name="frequency" class="frequency"> 
     7                <select name="frequency" class="frequency" <%= ((data.event.acl.write || data.event.acl.organization) && data.event.isAttendee) ? '' : 'disabled'%>> 
    88                        <option value="none">Sem repetição</option> 
    99                        <option value="daily">Diária</option> 
Note: See TracChangeset for help on using the changeset viewer.