Index: /trunk/expressoCalendar/setup/tables_current.inc.php
===================================================================
--- /trunk/expressoCalendar/setup/tables_current.inc.php	(revision 5341)
+++ /trunk/expressoCalendar/setup/tables_current.inc.php	(revision 5415)
@@ -122,4 +122,5 @@
                 'tzid' => array('type' => 'varchar', 'precision' => '50' ,'nullable' => True),
                 'transp' => array( 'type' => 'int', 'precision' => '2', 'nullable' => FALSE , 'default' => 0 ),
+                'sequence' => array( 'type' => 'int', 'precision' => '8', 'nullable' => FALSE , 'default' => 0 ),
             ),
             'pk' => array('id'),
Index: /trunk/prototype/services/iCal.php
===================================================================
--- /trunk/prototype/services/iCal.php	(revision 5399)
+++ /trunk/prototype/services/iCal.php	(revision 5415)
@@ -105,264 +105,94 @@
         $vcalendar = new icalCreator( ); 
         $vcalendar->parse(trim($data)); 
-        $vcalendar->sort();
-       
+        $vcalendar->sort();         
+        
         $return = array();
-        
         $method = $vcalendar->getProperty('method',FALSE , FALSE);
-               
+        $params['prodid'] =  $vcalendar->getProperty( 'prodid' , false , false );
+        
         while ($component = $vcalendar->getComponent())
-        {
-            
+        {     
             $interation = array();
+            $uid = $component->getProperty( 'uid' , false , false ); //Resgata o uid do componente
             
             switch (strtoupper($component->objName)) {
                 case 'VEVENT':
-                    $vevent = array();                    
-                    $vevent['uid'] = $component->getProperty( 'uid' , false , false );
-                    $vevent['type'] = EVENT_ID;
                     
-                    $exists =  Controller::find(array('concept' => 'schedulable') , null , array ( 'deepness' => '*' , 'filter' =>  array('=' , 'uid' , $vevent['uid'] )));
-                    $exists = ( is_array($exists) && count($exists) > 0 ) ? $exists[0] : false;
-
                     switch ($method) 
                     {
-                         case 'REPLY':
-                             
-                               if($exists !== false)
-                               {
-                                   while($property = $component->getProperty('attendee',FALSE , TRUE))                                 
-                                       if( $pID  = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $exists['participants']))
-                                            $interation['participant://'.$pID] = array( 'id' => $pID , 'status' => constant('STATUS_'.strtoupper($property['params']['PARTSTAT'])) );
-                               }
+                         case 'PUBLISH':            
+                             if( !$schedulable = self::_getSchedulable($uid))
+                                  $interation['schedulable://'.mt_rand().'(Formatter)'] = self::_makeCreateVEVENT($component);
                                break;
 
-                         case 'CANCEL':
-                               if($exists !== false)
-                                    $interation['schedulable://'.$exists['id']] = false;
-                               break;
-
-                         default:                             
-                               $veventID = mt_rand().'1(Formatter)';
-                               
-                               if($exists !== false)
-                               {
-                                  Config::regSet('noAlarm', False); //Reativa o envio de notificação
-                                  $existsCalendarToSchedulable = Controller::find( array( 'concept' => 'calendarToSchedulable' ) , array('id') ,array( 'filter' => array('AND' , array('=' , 'calendar' ,  $params['calendar'] ), array('=' , 'schedulable' ,  $exists['id'] ) )) ); 
-                                            
-                                    
-                                  if( !is_array($existsCalendarToSchedulable) || count($existsCalendarToSchedulable) < 1 )
-                                  {  
+                         case 'REQUEST':
+                             $schedulable = self::_getSchedulable($uid);
+                              
+                             if($schedulable) //Caso o evento exista
+                             {
+                                if(!self::_existInMyCalendars($schedulable['id']))
+                                {
                                       $calendarToSchedulable = array();
                                       $calendarToSchedulable['calendar'] = $params['calendar'];
-                                      $calendarToSchedulable['schedulable'] = $exists['id'];
+                                      $calendarToSchedulable['schedulable'] = $schedulable['id'];
                                       $interation['calendarToSchedulable://'.mt_rand().'(Formatter)'] = $calendarToSchedulable;
-                                      continue;
-                                  }
-// Codigo para atualizar status do importador. não nescessario pois sera enviado um email de configmação para o organizador.
-//                         foreach ($exists['participants'] as  $participant)
-//                           if($participant['user']['id'] == Config::me('uidNumber'))
-//                               $interation['participant://'.$participant['id']] = array( 'id' => $participant['id'], 'status' => STATUS_CONFIRMED);
-                                    
-                                 $veventID = $exists['id'];
-                                 $vevent = $exists;
-                               }
-                          
-                                /* Data de Inicio*/
-                                    $startTime = $component->getProperty( 'dtstart', false , true );
-
-                                /* Tiem zone do evento*/    
-                                   if(isset($startTime['params']['TZID']))
-                                      $vevent['timezone'] = self::nomalizeTZID ($startTime['params']['TZID']); 
-                                   else
-                                      $vevent['timezone'] = $params['calendar_timezone'] ? $params['calendar_timezone'] : 'America/Sao_Paulo'; 
-
-                                    if($startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone']) )
+                                      
+                                      if(isset($params['status']))
+                                      {
+                                        $pID = self::_getParticipantByMail( Config::me('mail') , $schedulable['participants'] );
+                                        $interation['participant://'.$pID]['status'] = $params['status'];
+                                      }
+                                }
+                                else
+                                {
+                                    if( self::_getTime($component , 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty( 'sequence' , false , false ) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
+                                       $interation = self::_makeVEVENT($schedulable , $component , $params);
+                                    else if ( $component->getProperty( 'sequence' , false , false ) === $schedulable['sequence']) 
                                     {
-                                        $vevent['allDay'] = 1;
-                                        $vevent['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC',$params['calendar_timezone']) . '000';
-                                    }
-                                    elseif(isset($startTime['params']['TZID']) && !isset($startTime['value']['tz']))/* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
-                                        $vevent['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC',$startTime['params']['TZID']) . '000';      
-                                    else
-                                        $vevent['startTime'] = self::date2timestamp($startTime['value']) . '000';                         
-
-                                 /* Data de Termino*/
-                                    $endTime = $component->getProperty( 'dtend', false , true ); 
-
-                                    if($endTime['params']['VALUE'] === 'DATE')
-                                        $vevent['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC',$params['calendar_timezone']) . '000';
-                                    else if(isset($endTime['params']['TZID']) && !isset($endTime['value']['tz'])) /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
-                                        $vevent['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC',$endTime['params']['TZID']) . '000';
-                                    else
-                                        $vevent['endTime'] = self::date2timestamp($endTime['value']) . '000';
-
-                                $vevent['summary'] = mb_convert_encoding ( $component->getProperty( 'summary' , false , false ) , 'UTF-8' , 'UTF-8,ISO-8859-1');
-
-                                /* Definindo Description */
-                                    if($desc = $component->getProperty( 'description' , false , false ))
-                                        $vevent['description'] = mb_convert_encoding (str_ireplace ('\n', "\n", $desc) ,'UTF-8' , 'UTF-8,ISO-8859-1');
-
-                                 /* Definindo location */
-                                    if($location = $component->getProperty( 'location' , false , false ))
-                                        $vevent['location'] = mb_convert_encoding ( $location , 'UTF-8' , 'UTF-8,ISO-8859-1') ;
-
-
-                                /* Definindo Class */
-                                    $class = $component->getProperty( 'class' , false , false );
-                                    if( $class && defined(constant(strtoupper('CLASS_'.$class))) )
-                                        $vevent['class'] = constant(strtoupper('CLASS_'.$class));
-                                    else if( !isset($exists['class']) )
-                                        $vevent['class'] = CLASS_PRIVATE ; // padrão classe private
-
-                                /* Definindo RRULE */
-                                    if(  $rrule = $component->getProperty( 'rrule' , false , false ))
-                                    {   
-                                        /* Gera um randon id para o contexto formater */
-                                            $repeatID = mt_rand().'3(Formatter)';
-
-                                        $repeat = array();
-                                        $repeat['schedulable'] = $veventID;
-                                        foreach($rrule as $i => $v)
-                                           $repeat[strtolower($i)] = $v;
-
-                                        $interation['repeat://'.$repeatID] = $repeat;
-                                    }
-
-
-                                $vevent['calendar'] = $params['calendar'];           
-
-                                $participantsInEvent = array();
-
-                                //TODO: Participants com delegated não estao sendo levados em conta
-                                while($property = $component->getProperty('attendee',FALSE , TRUE))
-                                {
-                                    $participant = array();
-
-                                    $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
-
-                                    $participantID = mt_rand().'2(Formatter)';
-                                    $participant['schedulable'] = $veventID;                                      
-                                    $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_'.$property['params']['PARTSTAT']) !== null ) ? constant('STATUS_'.$property['params']['PARTSTAT']) : STATUS_UNANSWERED;
-                                    $participant['isOrganizer'] = '0';
-
-                                    /* Verifica se este usuario é um usuario interno do ldap */     
-                                    $intUser = Controller::find( array( 'concept' => 'user', 'service' => 'OpenLDAP' ) , array('uidNumber') ,array( 'filter' => array('OR' , array('=' , 'mail' ,  $mailUser ), array('=' , 'mailAlternateAddress' ,  $mailUser ) )) ); 
-
-                                    if( !is_array($intUser) || count($intUser) < 1 )
-                                         $intUser = Controller::find( array( 'concept' => 'user' ,'service' => 'PostgreSQL') , array('uidNumber') ,array( 'filter' => array('=' , 'mail' ,  $mailUser )) ); 
-
-
-                                    $user = null;    
-                                    if( $intUser && count($intUser) > 0 )
-                                    {
-                                        $participant['isExternal']  = 0;
-                                        $participant['user'] = $intUser[0]['id'];
-                                    }
-                                    else
-                                    {
-                                        $participant['isExternal']  = 1;
-                                         /* Gera um randon id para o contexto formater */
-                                            $userID = mt_rand().'4(Formatter)';
-
-                                        $user['mail'] = $mailUser;
-                                        $user['isExternal'] = '1';
-                                        $user['name'] =  ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
-                                        $user['participants'] = array($participantID);
-                                        $participant['user'] = $userID;
-                                        $interation['user://'.$userID] = $user;
-                                    }
-
-                                    $interation['participant://'.$participantID] = $participant;
-                                    $vevent['participants'][] = $participantID;
-
-                                };
-
-                                if($property = $component->getProperty('organizer',FALSE , TRUE))
-                                {
-                                    $participant = array();
-                                    $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
-
-                                    $participantID = mt_rand().'2(Formatter)';
-
-                                    $participant['schedulable'] = $veventID;
-                                    $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_'.$property['params']['PARTSTAT']) !== null ) ? constant('STATUS_'.$property['params']['PARTSTAT']) : STATUS_UNANSWERED;
-                                    $participant['isOrganizer'] = '1';
-
-                                    /* Verifica se este usuario é um usuario interno do ldap */     
-                                    $intUser = Controller::find( array( 'concept' => 'user' ,'service' => 'OpenLDAP') , array('uidNumber') ,array( 'filter' => array('OR' , array('=' , 'mail' ,  $mailUser ), array('=' , 'mailAlternateAddress' ,  $mailUser ) )) ); 
-
-                                    if( !is_array($intUser) || count($intUser) < 1 )
-                                         $intUser = Controller::find( array( 'concept' => 'user' ,'service' => 'PostgreSQL') , array('uidNumber') ,array( 'filter' => array('=' , 'mail' ,  $mailUser )) ); 
-
-
-
-                                    $user = null;    
-                                    if( $intUser && count($intUser) > 0 )
-                                    {
-                                        $participant['isExternal']  = 0;
-                                        $participant['user'] = $intUser[0]['id'];
-                                    }
-                                    else
-                                    {
-                                        $participant['isExternal']  = 1;
-                                         /* Gera um randon id para o contexto formater */
-                                            $userID = mt_rand().'4(Formatter)';
-
-                                        $user['mail'] = $mailUser;
-                                        $user['name'] =  ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
-                                        $user['participants'] = array($participantID);
-                                        $user['isExternal'] = '1';
-                                        $participant['user'] = $userID;
-                                        $interation['user://'.$userID] = $user;
-                                    }
-
-                                    $interation['participant://'.$participantID] = $participant;
-                                    $vevent['participants'][] = $participantID;
-
+                                        //Ler melhor rfc sobre isto 3.2.2.2
+                                        //Aparentemente é para retornar um ical com o evento atualizado para o attende
+                                    } 
                                 }
-                                else //caso não tenha organizador o usuario se torna organizador
-                                {
-                                   $user = Controller::read( array( 'concept' => 'user', 'id' => $params['owner'] ) , array('mail')); 
-
-                                   if(!self::_getParticipantByMail($user['mail'] , $exists['participants']))
-                                   {
-                                        $participantID = mt_rand().'2(Formatter)';
-
-                                        $participant['schedulable'] = $veventID;
-                                        $participant['status'] = STATUS_CONFIRMED;
-                                        $participant['isOrganizer'] = '1';
-                                        $participant['isExternal']  = 0;
-                                        $participant['user'] =  $params['owner'];
-                                        $interation['participant://'.$participantID] = $participant;
-                                        $vevent['participants'][] = $participantID;
-                                   }
-                                }
-
-                                 /* Definindo DTSTAMP */
-                                if($dtstamp = $component->getProperty( 'dtstamp', false , true ))
-                                {
-                                    if(isset($dtstamp['params']['TZID']) && !isset($dtstamp['value']['tz']))
-                                        $vevent['dtstamp'] = self::date2timestamp($dtstamp['value']) - self::_getTzOffset('UTC',$dtstamp['params']['TZID']) . '000';
-                                    else
-                                        $vevent['dtstamp'] = self::date2timestamp($dtstamp['value']) . '000';
-                                }
-
-                                /* Definindo TRANSP */
-                                if(($tranp = $component->getProperty( 'transp', false , true )) && strtoupper($tranp) == 'OPAQUE')
-                                    $vevent['transparent'] = 1;
-
-                                 /* Definindo last_update */
-                                if($lastUpdate = $component->getProperty( 'LAST-MODIFIED', false , true ))
-                                {
-                                    if(isset($lastUpdate['params']['TZID']) && !isset($lastUpdate['value']['tz']))
-                                        $vevent['lasUpdate'] = self::date2timestamp($lastUpdate['value']) - self::_getTzOffset('UTC',$lastUpdate['params']['TZID']) . '000';
-                                    else
-                                        $vevent['lastUpdate'] = self::date2timestamp($lastUpdate['value']) . '000';
-                                }
-
-                                $interation['schedulable://'.$veventID] = $vevent;
-
+    
+                             }else // Importar evento
+                                $interation = self::_makeVEVENT( array() , $component , $params);
+                             
+                             break;  
+                           
+                         case 'REFRESH':
+                               break;  
+                         
+                         case 'CANCEL':
+                             if($schedulable = self::_getSchedulable($uid))                              
+                                $interation['schedulable://'.$schedulable['id']] = false;
                                break;
+                           
+                         case 'ADD':
+                               break;
+                         
+                         case 'REPLY':
+                             if(  $schedulable = self::_getSchedulable($uid) )
+                             {
+                                   while($property = $component->getProperty('attendee',FALSE , TRUE))                                 
+                                       if( $pID  = self::_getParticipantByMail(str_replace('MAILTO:', '', $property['value']), $schedulable['participants']))
+                                            $interation['participant://'.$pID] = array( 'id' => $pID , 'status' => constant('STATUS_'.strtoupper($property['params']['PARTSTAT'])) );                            
+                             }
+                               break;
+                         
+                         case 'COUNTER':
+                               break;
+                         
+                         case 'DECLINE-COUNTER':
+                               break;
+                           
+                         default:
+                             $schedulable = self::_getSchedulable($uid);
                              
+                             if($schedulable && ( self::_getTime($component , 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty( 'sequence' , false , false ) > $schedulable['sequence'])) //Caso o evento exista
+                                $interation = self::_makeVEVENT($schedulable , $component , $params);
+                             else // Importar evento
+                                 $interation = self::_makeVEVENT( array() , $component , $params);
+
+                             break;
                     }
                     
@@ -376,7 +206,96 @@
         
         }
-        
+                
          return $return;   
     }
+    
+        public function analize ( $data , $params = false)
+        {
+            $vcalendar = new icalCreator( ); 
+            $vcalendar->parse(trim($data)); 
+            $vcalendar->sort();         
+
+            $return = array();
+            $method = $vcalendar->getProperty('method',FALSE , FALSE);
+
+            while ($component = $vcalendar->getComponent())
+            {     
+                $interation = array();
+                $uid = $component->getProperty( 'uid' , false , false ); //Resgata o uid do componente
+
+                switch (strtoupper($component->objName)) {
+                    case 'VEVENT':
+
+                        switch ($method) 
+                        {
+                             case 'PUBLISH':            
+                                   $interation = ICAL_ACTION_IMPORT;
+                                   break;
+
+                             case 'REQUEST':
+                                 $schedulable = self::_getSchedulable($uid);
+
+                                 if($schedulable ) //Caso o evento exista
+                                 {
+                                    if(!self::_existInMyCalendars($schedulable['id']))
+                                          $interation = ICAL_ACTION_IMPORT;   
+                                    else
+                                    {
+                                        if( self::_getTime($component , 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty( 'sequence' , false , false ) > $schedulable['sequence']) //Organizador esta requisitando que você atualize o evento
+                                           $interation = ICAL_ACTION_UPDATE;   
+                                        else
+                                           $interation = ICAL_ACTION_NONE;    
+                                    }
+                                 }else
+                                   $interation =  ICAL_ACTION_IMPORT;
+
+                                 break;  
+
+                             case 'REFRESH':
+                                   break;  
+
+                             case 'CANCEL':
+                                    $interation = ICAL_ACTION_DELETE;
+                                   break;
+
+                             case 'ADD':
+                                   break;
+
+                             case 'REPLY':
+                                     $interation = ICAL_ACTION_REPLY;
+                                   break;
+
+                             case 'COUNTER':
+                                   break;
+
+                             case 'DECLINE-COUNTER':
+                                   break;
+
+                             default:
+                                 $schedulable = self::_getSchedulable($uid);
+
+                                 if($schedulable && ( self::_getTime($component , 'dtstamp') > $schedulable['dtstamp'] || $component->getProperty( 'sequence' , false , false ) > $schedulable['sequence'])) //Caso o evento exista
+                                      $interation = ICAL_ACTION_UPDATE;
+                                 else if($schedulable) 
+                                     $interation = ICAL_ACTION_NONE;
+                                 else // Importar evento
+                                      $interation = ICAL_ACTION_IMPORT;
+
+                                 break;
+                        }
+
+                        $return[$uid] = $interation;
+                        break;
+                   case 'VTIMEZONE':
+
+
+                        break;
+                }
+
+            }
+
+             return $return;   
+        }
+    
     
     /* Helpers */
@@ -410,6 +329,5 @@
         
         private static function _getParticipantByMail( $mail , &$participants )
-        {
-                    
+        {          
             foreach ($participants as $i => $v)
                 if($v['user']['mail'] == $mail  || (isset($v['user']['mailAlternateAddress']) && in_array($mail, $v['user']['mailAlternateAddress'])))
@@ -447,4 +365,258 @@
         }
 
+        static private function _makeVEVENT( $schedulable , $component ,$params)
+        {
+            $interation = array();                  
+            $eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand().'(Formatter)';
+            
+            /* Data de Inicio*/
+                $startTime = $component->getProperty( 'dtstart', false , true );
+         
+                   
+            /* Tiem zone do evento*/    
+               if(isset($startTime['params']['TZID']))
+                  $schedulable['timezone'] = self::nomalizeTZID ($startTime['params']['TZID']); 
+               else
+                  $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo'; 
+               
+                $objTimezone =  new DateTimeZone($schedulable['timezone']);  
+                
+                if($startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone']) )
+                {
+                    $schedulable['allDay'] = 1;
+                    $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC',$schedulable['timezone']) . '000';
+                }
+                elseif(isset($startTime['params']['TZID']) && !isset($startTime['value']['tz']))/* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
+                    $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC',$startTime['params']['TZID']) . '000';      
+                else
+                {
+                    $schedulable['startTime'] = self::date2timestamp($startTime['value']) . '000';
+                     if( strpos($params['prodid'], 'Outlook') !== false )
+                    {
+                        //Se o ics veio em utc não aplicar horario de verão
+                        $sTime = new DateTime( '@'.(int)($schedulable['startTime'] / 1000) , new DateTimeZone('UTC') ); 
+                        $sTime->setTimezone($objTimezone);
+                        if($sTime->format('I')) //Se o ics veio em utc não aplicar horario de verão
+                         $schedulable['startTime'] = $schedulable['startTime'] - 3600000;
+                    }
+                }
+                
+
+             /* Data de Termino*/
+                $endTime = $component->getProperty( 'dtend', false , true ); 
+
+                if($endTime['params']['VALUE'] === 'DATE')
+                    $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC',$schedulable['timezone']) . '000';
+                else if(isset($endTime['params']['TZID']) && !isset($endTime['value']['tz'])) /* Caso não tenha um tz na data mais exista um parametro TZID deve ser aplicado o timezone do TZID a data */
+                    $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC',$endTime['params']['TZID']) . '000';
+                else
+                {
+                    $schedulable['endTime'] = self::date2timestamp($endTime['value']) . '000';
+                    if( strpos($params['prodid'], 'Outlook') !== false )
+                    {
+                    //Se o ics veio em utc não aplicar horario de verão
+                        $eTime = new DateTime( '@'.(int)($schedulable['endTime'] / 1000)  ,new DateTimeZone('UTC')); 
+                        $eTime->setTimezone($objTimezone);
+                        if($eTime->format('I')) 
+                            $schedulable['endTime'] = $schedulable['endTime'] - 3600000;
+                    }
+                }
+        
+
+            $schedulable['summary'] = mb_convert_encoding ( $component->getProperty( 'summary' , false , false ) , 'UTF-8' , 'UTF-8,ISO-8859-1');
+
+            /* Definindo Description */
+                if($desc = $component->getProperty( 'description' , false , false ))
+                    $schedulable['description'] = mb_convert_encoding (str_ireplace ('\n', "\n", $desc) ,'UTF-8' , 'UTF-8,ISO-8859-1');
+
+             /* Definindo location */
+                if($location = $component->getProperty( 'location' , false , false ))
+                    $schedulable['location'] = mb_convert_encoding ( $location , 'UTF-8' , 'UTF-8,ISO-8859-1') ;
+
+
+            /* Definindo Class */
+                $class = $component->getProperty( 'class' , false , false );
+                if( $class && defined(constant(strtoupper('CLASS_'.$class))) )
+                    $schedulable['class'] = constant(strtoupper('CLASS_'.$class));
+                else if( !isset($exists['class']) )
+                    $schedulable['class'] = CLASS_PRIVATE ; // padrão classe private
+
+            /* Definindo RRULE */
+                if(  $rrule = $component->getProperty( 'rrule' , false , false ))
+                {   
+                    /* Gera um randon id para o contexto formater */
+                        $repeatID = mt_rand().'3(Formatter)';
+
+                    $repeat = array();
+                    $repeat['schedulable'] = $eventID;
+                    foreach($rrule as $i => $v)
+                       $repeat[strtolower($i)] = $v;
+
+                    //$interation['repeat://'.$repeatID] = $repeat;
+                }
+
+
+            $schedulable['calendar'] = $params['calendar'];           
+
+            $participantsInEvent = array();
+
+            //TODO: Participants com delegated não estao sendo levados em conta
+            while($property = $component->getProperty('attendee',FALSE , TRUE))
+            {
+                $participant = array();
+
+                $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
+
+                $participantID = mt_rand().'2(Formatter)';
+                $participant['schedulable'] = $eventID;                                      
+                
+                if(isset($params['status']) && $mailUser == Config::me('mail'))
+                    $participant['status'] = $params['status'];
+                else
+                    $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_'.$property['params']['PARTSTAT']) !== null ) ? constant('STATUS_'.$property['params']['PARTSTAT']) : STATUS_UNANSWERED;
+                 
+                
+                $participant['isOrganizer'] = '0';
+
+                /* Verifica se este usuario é um usuario interno do ldap */     
+                $intUser = Controller::find( array( 'concept' => 'user', 'service' => 'OpenLDAP' ) , array('uidNumber') ,array( 'filter' => array('OR' , array('=' , 'mail' ,  $mailUser ), array('=' , 'mailAlternateAddress' ,  $mailUser ) )) ); 
+
+                if( !is_array($intUser) || count($intUser) < 1 )
+                     $intUser = Controller::find( array( 'concept' => 'user' ,'service' => 'PostgreSQL') , array('uidNumber') ,array( 'filter' => array('=' , 'mail' ,  $mailUser )) ); 
+
+
+                $user = null;    
+                if( $intUser && count($intUser) > 0 )
+                {
+                    $participant['isExternal']  = 0;
+                    $participant['user'] = $intUser[0]['id'];
+                }
+                else
+                {
+                    $participant['isExternal']  = 1;
+                     /* Gera um randon id para o contexto formater */
+                        $userID = mt_rand().'4(Formatter)';
+
+                    $user['mail'] = $mailUser;
+                    $user['isExternal'] = '1';
+                    $user['name'] =  ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
+                    $user['participants'] = array($participantID);
+                    $participant['user'] = $userID;
+                    $interation['user://'.$userID] = $user;
+                }
+
+                $interation['participant://'.$participantID] = $participant;
+                $schedulable['participants'][] = $participantID;
+
+            };
+
+            if($property = $component->getProperty('organizer',FALSE , TRUE))
+            {
+                $participant = array();
+                $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
+
+                $participantID = mt_rand().'2(Formatter)';
+
+                $participant['schedulable'] = $eventID;
+                $participant['status'] = (isset($property['params']['PARTSTAT']) && constant('STATUS_'.$property['params']['PARTSTAT']) !== null ) ? constant('STATUS_'.$property['params']['PARTSTAT']) : STATUS_UNANSWERED;
+                $participant['isOrganizer'] = '1';
+
+                /* Verifica se este usuario é um usuario interno do ldap */     
+                $intUser = Controller::find( array( 'concept' => 'user' ,'service' => 'OpenLDAP') , array('uidNumber') ,array( 'filter' => array('OR' , array('=' , 'mail' ,  $mailUser ), array('=' , 'mailAlternateAddress' ,  $mailUser ) )) ); 
+
+                if( !is_array($intUser) || count($intUser) < 1 )
+                     $intUser = Controller::find( array( 'concept' => 'user' ,'service' => 'PostgreSQL') , array('uidNumber') ,array( 'filter' => array('=' , 'mail' ,  $mailUser )) ); 
+
+                $user = null;    
+                if( $intUser && count($intUser) > 0 )
+                {
+                    $participant['isExternal']  = 0;
+                    $participant['user'] = $intUser[0]['id'];
+                }
+                else
+                {
+                    $participant['isExternal']  = 1;
+                     /* Gera um randon id para o contexto formater */
+                        $userID = mt_rand().'4(Formatter)';
+
+                    $user['mail'] = $mailUser;
+                    $user['name'] =  ( isset($property['params']['CN']) ) ? $property['params']['CN'] : '';
+                    $user['participants'] = array($participantID);
+                    $user['isExternal'] = '1';
+                    $participant['user'] = $userID;
+                    $interation['user://'.$userID] = $user;
+                }
+
+                $interation['participant://'.$participantID] = $participant;
+                $schedulable['participants'][] = $participantID;
+
+            }
+            else if(!is_array($schedulable['participants']) || count($schedulable['participants']) < 1)//caso não tenha organizador o usuario se torna organizador
+            {
+               $user = Controller::read( array( 'concept' => 'user', 'id' => $params['owner'] ) , array('mail')); 
+
+               if(!self::_getParticipantByMail($user['mail'] , $exists['participants']))
+               {
+                    $participantID = mt_rand().'2(Formatter)';
+
+                    $participant['schedulable'] = $eventID;
+                    $participant['status'] = STATUS_CONFIRMED;
+                    $participant['isOrganizer'] = '1';
+                    $participant['isExternal']  = 0;
+                    $participant['user'] =  $params['owner'];
+                    $interation['participant://'.$participantID] = $participant;
+                    $schedulable['participants'][] = $participantID;
+               }
+            }
+
+             /* Definindo DTSTAMP */
+            if($dtstamp = self::_getTime($component , 'dtstamp') )
+                $schedulable['dtstamp'] = $dtstamp;
+      
+            /* Definindo TRANSP */
+            if(($tranp = $component->getProperty( 'transp', false , true )) && strtoupper($tranp) == 'OPAQUE')
+                $schedulable['transparent'] = 1;
+
+             /* Definindo last_update */
+            if($lastUpdate =  self::_getTime($component , 'LAST-MODIFIED'))
+                  $schedulable['lastUpdate'] = $lastUpdate;
+            
+            
+            if($sequence = $component->getProperty( 'SEQUENCE', false , false ))
+                  $schedulable['sequence'] = $sequence;
+              
+            if($uid = $component->getProperty( 'uid' , false , false ));
+                  $schedulable['uid'] = $uid;
+                
+             $interation['schedulable://'.$eventID] = $schedulable;
+                         
+             return $interation;
+        }
+        
+        static private function _getSchedulable( $uid )
+        {
+           $schedulable =  Controller::find( array( 'concept' => 'schedulable' ) , null , array ( 'deepness' => '2' , 'filter' => array( '=' , 'uid' , $uid )));
+           return (isset($schedulable[0])) ? $schedulable[0] : false;
+        }
+        
+        static private function _existInMyCalendars( $id )
+        {
+           $sig = Controller::find(array('concept' => 'calendarSignature'), array('user','calendar'), array('filter' => array( '=' , 'user' , Config::me('uidNumber'))));       
+           $calendars = array();
+           foreach ($sig as $val)
+               $calendars[] = $val['calendar'];
+           
+           $return =  Controller::find( array( 'concept' => 'calendarToSchedulable' ) , null , array ( 'filter' => array('AND' , array( 'IN' , 'calendar' , $calendars ),array( '=' , 'schedulable' , $id ))));
+           
+           return (isset($return[0])) ? true : false;
+        }
+        
+        static private function _getTime(&$component , $property)
+        {
+           if($date = $component->getProperty($property , false , true ))
+                return (isset($date['params']['TZID']) && !isset($date['value']['tz'])) ? (self::date2timestamp($date['value']) - self::_getTzOffset('UTC',$date['params']['TZID'])) . '000' : self::date2timestamp($date['value']) . '000';
+           
+           return false;
+        }
 }
 ?>
Index: /trunk/prototype/modules/calendar/interceptors/DBMapping.php
===================================================================
--- /trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 5399)
+++ /trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 5415)
@@ -24,4 +24,5 @@
                                          'lastUpdate' => 'last_update',
                                          'dtstamp' => 'dtstamp',
+                                         'sequence' => 'sequence',
                                          'timezone' => 'tzid');
       
@@ -287,7 +288,7 @@
 
     public function encodeUpdateSchedulable( &$uri , &$params , &$criteria , $original ){	
-        if(isset($params['rangeStart']))
+        if(isset($params['startTime']))
 	       	$params['rangeStart'] = gmdate( 'd-m-Y' , (int)($params['startTime'] / 1000) );
-	if(isset($params['rangeEnd']))
+	if(isset($params['endTime']))
    		$params['rangeEnd'] = gmdate( 'd-m-Y' , (int)($params['endTime'] / 1000) );       
         
@@ -679,5 +680,5 @@
         $newCriteria = $original['criteria'];
         $valid = true;
-        self::validExternalUserCriteria($newCriteria, self::$calendar_ex_participantMap, $valid);
+        self::validExternalUserCriteria($newCriteria['filter'], self::$calendar_ex_participantMap, $valid);
         if($valid == true)
         {
@@ -979,5 +980,5 @@
         if (!is_array($filter) || count($filter) <= 0)
             return null;
-
+        
         $op = array_shift($filter);
 
@@ -985,7 +986,7 @@
             foreach ($filter as $i => $f)
                 $filter[$i] = self::validExternalUserCriteria($f, $map ,$findCalendar );
-        }
-        else
-        {
+	}
+	else
+	{           
            if( isset($filter[0]) && !in_array($filter[0] , self::$calendar_ex_participantMap))
              $ref = false;
@@ -994,7 +995,5 @@
                 $filter[0] = isset($map[$filter[0]]) ? $map[$filter[0]] : $filter[0];
         }
-
-        array_unshift($filter, $op);
-
+        
         return( $filter );
     }
Index: /trunk/prototype/modules/calendar/constants.php
===================================================================
--- /trunk/prototype/modules/calendar/constants.php	(revision 5341)
+++ /trunk/prototype/modules/calendar/constants.php	(revision 5415)
@@ -23,3 +23,10 @@
 define('CLASS_CONFIDENTIAL', 3);
 
+
+define('ICAL_ACTION_IMPORT', 1);
+define('ICAL_ACTION_UPDATE', 2);
+define('ICAL_ACTION_DELETE', 3);
+define('ICAL_ACTION_NONE', 4);
+define('ICAL_ACTION_REPLY', 5);
+
 ?>
Index: /trunk/prototype/modules/calendar/js/calendar.codecs.js
===================================================================
--- /trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 5409)
+++ /trunk/prototype/modules/calendar/js/calendar.codecs.js	(revision 5415)
@@ -415,5 +415,5 @@
 					
 					if( attend.user.id ===  me.id ){
-					    participantInfo = {
+					    participantInfo.user = {
 							status : attend.status,
 							alarms : $.map(attend.alarms || [], function( alarm ){
@@ -422,4 +422,5 @@
 						};
 						me.id = attend.id;
+                                                return(null);
 					};
 					
@@ -433,5 +434,5 @@
 					if( !!parseInt(attend.isOrganizer )){
 						isOrganizer = ((attend.user.id == User.me.id) || (!!!attend.user)) ? 1 : 0;
-					    participantInfo.organizer = person;
+					    participantInfo.organizer = DataLayer.copy(person);
 						return(null);
 					};					
@@ -440,6 +441,6 @@
 				}),
 			    organizer: participantInfo.organizer || me,
-			    alarms: participantInfo.alarms || [],
-			    status: participantInfo.status || 1,
+			    alarms: !!participantInfo.user ?  participantInfo.user.alarms : [],
+			    status: !!participantInfo.user ? participantInfo.user.status :  1,
 			    me: me,
 				isOrganizer: isOrganizer,
Index: /trunk/prototype/api/controller.php
===================================================================
--- /trunk/prototype/api/controller.php	(revision 5399)
+++ /trunk/prototype/api/controller.php	(revision 5415)
@@ -597,4 +597,6 @@
 
 			case 'format': $return = $params['service']->format( $params['properties'], $params['criteria'] ); break;
+                        
+                        default:  $return = $params['service']->$method( $params['properties'], $params['criteria'] ); break;
 	    }
 
Index: /trunk/prototype/api/config.php
===================================================================
--- /trunk/prototype/api/config.php	(revision 5399)
+++ /trunk/prototype/api/config.php	(revision 5415)
@@ -29,6 +29,6 @@
         if( !isset( $_SESSION['wallet'][$service] ) || !isset( $_SESSION['wallet'][$service][$config] ))
             $_SESSION['wallet'][$service] = parse_ini_file( ROOTPATH."/config/$service.srv", true );
-        
-        return isset($_SESSION['wallet'][$service][$config]) ? $_SESSION['wallet'][$service][$config] : false;
+       
+        return (isset($_SESSION['wallet'][$service][$config])) ? $_SESSION['wallet'][$service][$config] : false;
     }
     
Index: /trunk/prototype/converter.php
===================================================================
--- /trunk/prototype/converter.php	(revision 5399)
+++ /trunk/prototype/converter.php	(revision 5415)
@@ -3,5 +3,7 @@
 require_once 'api/controller.php';
 
-$args = Controller::call( 'parse',
+$method =  $_REQUEST['analize'] ? 'analize' : 'parse';
+
+$args = Controller::call( $method,
 
 			  array( 'service' => $_REQUEST['type'] ),
Index: /trunk/expressoMail1_2/inc/class.db_functions.inc.php
===================================================================
--- /trunk/expressoMail1_2/inc/class.db_functions.inc.php	(revision 5409)
+++ /trunk/expressoMail1_2/inc/class.db_functions.inc.php	(revision 5415)
@@ -400,4 +400,5 @@
 				$_REQUEST['params']['calendar'] = $params['selected'];
 				$_REQUEST['readable'] = $params['readable'] ? true : false;
+                                $_REQUEST['analize'] = isset($params['readable']) ? true : false;
 				$_REQUEST['params']['status'] = $params['status'];
 				$_REQUEST['params']['owner'] = $_SESSION['phpgw_info']['expressomail']['user']['account_id'];
@@ -409,13 +410,7 @@
 					if(!$valid)
 					{
-						$return = false;
-						$output = unserialize($output);										
-						foreach($output[0] as $key => &$value){
-						
-							if(isset($value['user'])){							
-								if($user == $value['user'])
-									return  $value['schedulable'];
-							}
-						}
+						$output = unserialize($output);	
+                                                foreach($output as $key => $value)
+                                                    return $value;
 					}
 					return false;
Index: /trunk/expressoMail1_2/js/main.js
===================================================================
--- /trunk/expressoMail1_2/js/main.js	(revision 5409)
+++ /trunk/expressoMail1_2/js/main.js	(revision 5415)
@@ -3382,5 +3382,5 @@
 		});
                 $.ajax({
-                        url: "controller.php?action="+import_url+'&from_ajax=true&id_user='+User.me.id+'&readable=true&cirus_delimiter='+cyrus_delimiter,
+                        url: "controller.php?action="+import_url+'&from_ajax=true&id_user='+User.me.id+'&readable=true&cirus_delimiter='+cyrus_delimiter+'&analize=true',
                         async: false,
                         success: function(data){
@@ -3388,7 +3388,7 @@
 
 
-                                var createDialog = function(isCorrentEvent, propaget){
-
-                                        if(!(!!isCorrentEvent)){
+                                var createDialog = function(typeImport, propaget){
+
+                                        if(typeImport == '1'){
                                                 $("#select-agenda").html('');
                                                 for(var calendario in Calendar.calendarIds){
@@ -3420,5 +3420,25 @@
                                                  });					
 
-                                        }else{
+                                        }else if(data == '4'){
+                                            alert('Seu evento já se encontra atualizado');
+                                            return;
+                                        }else if(data == '3'){
+                                           $.ajax({
+							url: "controller.php?action="+import_url+'&from_ajax=true&selected=true',
+                                                	success: function(msg){
+                                                	alert( ( ( connector.unserialize(msg)) == "ok") ? "Seu evento foi removido " : "Ocorreu um erro ao remover o evento" );
+                                                        }
+                                                });
+                                                return;
+                                        }
+                                        else if(data == '5'){
+						$.ajax({
+							url: "controller.php?action="+import_url+'&from_ajax=true&selected=true',
+                                                	success: function(msg){
+                                                	alert( ( ( connector.unserialize(msg)) == "ok") ? "Atualizado com sucesso " : "Ocorreu um erro ao atualizar o evento" );
+                                                        }
+                                                });
+                                                return;
+					}else {
                                                 up = true;
                                                 $("#select-agenda").css("display", "none");
@@ -3432,18 +3452,13 @@
                                                             },
                                                            "Atualizar": function() {
-                                                           if ($(".ui-dialog-buttonpane").find(".ui-button:last").children().html() == 'Atualizar'){
-                                                               
-															   
-															   
-                                                               var isOk = propaget || DataLayer.put('participant', { id: ( DataLayer.get('participant', ['AND', ['=', 'user', User.me.id], ['=', 'schedulable', isCorrentEvent[0].schedulable]] ) )[0].id, 
-                                                                                                         status: $("#select-status option:selected").val() });
-
-                                                                DataLayer.commit();
-
-                                                                alert( !!isOk ? "Evento atualizado com sucesso ... " : "Ocorreu um erro ao atualizar o evento  ... ");
-
-                                                               $( this ).dialog( "close" );
-
-                                                           }
+                                                                
+                                                                $.ajax({
+                                                                     url: "controller.php?action="+import_url+'&from_ajax=true&selected='+$("#select-agenda option:selected").val()+'&status='+$("#select-status option:selected").val(),
+                                                                     success: function(msg){
+                                                                            alert( ( (msg = connector.unserialize(msg)) == "ok") ? "Atualizado com sucesso para " : "Ocorreu um erro ao atualizar o evento" );
+                                                                    }
+                                                                });
+                                                        
+                                                                $( this ).dialog( "close" );
                                                         }
                                                     }
@@ -3453,19 +3468,6 @@
                                         $( "#import-dialog" ).dialog( "open" );	
                                 };
-
-
-
-                                if(!!data){
-                                        var isCorrentEvent = false;
-                                        var count = 0;
-
-                                        $.getJSON("../prototype/request.php",
-                                        {
-                                                concept : "calendarToSchedulable",
-                                                filter : ['AND', ['IN', 'calendar', Calendar.calendarIds], ['=', 'schedulable', data]]
-                                        }, createDialog);
-                                }else{
-                                        createDialog(true, true);
-                                }
+                                createDialog(data, true);
+                                
                 }});
 			
