Index: sandbox/2.4.2-expresso1/prototype/services/iCal.php
===================================================================
--- sandbox/2.4.2-expresso1/prototype/services/iCal.php	(revision 6891)
+++ sandbox/2.4.2-expresso1/prototype/services/iCal.php	(revision 6951)
@@ -184,5 +184,4 @@
                 
                 }
-            
 
             if (isset($v['participants']) && is_array($v['participants']) && count($v['participants']) > 0)
@@ -617,7 +616,7 @@
         switch ($method) {
             case 'PUBLISH':
-                //Caso a tarefa nÃ£o exista o mesmo cria um novo evento, se jÃ¡ existir o mesmo referencia o evento com agenda
+                //Caso a tarefa não exista o mesmo cria um novo evento, se já existir o mesmo referencia o evento com agenda
                 if (!$schedulable = self::_getSchedulable($uid))
-                    $interation = self::_makeVEVENT($schedulable, $component, $params);
+                    $interation = self::_makeVTODO($schedulable, $component, $params);
                 else{
                     $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
@@ -1291,5 +1290,5 @@
     }
 
-    static private function _makeVEVENT($schedulable, $component, $params) {
+        static private function _makeVEVENT($schedulable, $component, $params) {
 	$interation = array();
 	$eventID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
@@ -1312,5 +1311,5 @@
 	    $schedulable['allDay'] = 1;
 	    $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
-	} elseif ($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 */
+	} elseif ($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', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
 	    $schedulable['allDay'] = 0;
@@ -1392,5 +1391,5 @@
 	$participantsInEvent = array();
 
-	//TODO: Participants com delegated nÃ£o estao sendo levados em conta
+	//TODO: Participants com delegated nao estao sendo levados em conta
 	while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
 	    $participant = array();
@@ -1570,4 +1569,262 @@
 
 	$interation['schedulable://' . $eventID] = $schedulable;
+
+	return $interation;
+    }
+    
+    static private function _makeVTODO($schedulable, $component, $params) {
+	$interation = array();
+	$todoID = isset($schedulable['id']) ? $schedulable['id'] : mt_rand() . '(Formatter)';
+
+	/* Data de Inicio */
+	$startTime = $component->getProperty('dtstart', false, true);
+
+	$tzid = (isset($startTime['params']['TZID']) ? $startTime['params']['TZID'] : $params['X-WR-TIMEZONE']);
+
+	/* Tiem zone do evento */
+	if ($tzid){
+	    $tzid = self::nomalizeTZID($tzid);
+	    $schedulable['timezone'] = $tzid;
+	}else
+	    $schedulable['timezone'] = isset($params['calendar_timezone']) ? $params['calendar_timezone'] : 'America/Sao_Paulo';
+
+	$objTimezone = new DateTimeZone($schedulable['timezone']);
+
+	if (isset($startTime['params']['VALUE']) && $startTime['params']['VALUE'] === 'DATE' && isset($params['calendar_timezone'])) {
+	    $schedulable['allDay'] = 1;
+	    $schedulable['startTime'] = self::date2timestamp($startTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($startTime['value'])) . '000';
+	} elseif ($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', $tzid, '@' . self::date2timestamp($startTime['value'])) . '000';
+	    $schedulable['allDay'] = 0;
+	} 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);
+
+	$tzid = isset($endTime['params']['TZID']) ? $endTime['params']['TZID'] : $params['X-WR-TIMEZONE'];
+	
+	if($tzid)
+	    $tzid = self::nomalizeTZID($tzid);
+
+	if (isset($endTime['params']['VALUE']) && $endTime['params']['VALUE'] === 'DATE')
+	    $schedulable['endTime'] = self::date2timestamp($endTime['value']) - self::_getTzOffset('UTC', $schedulable['timezone'], '@' . self::date2timestamp($endTime['value'])) . '000';
+	else if ($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', $tzid, '@' . self::date2timestamp($endTime['value'])) . '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['type'] = '2'; //type schedulable
+	$schedulable['summary'] = mb_convert_encoding($component->getProperty('summary', false, false), 'ISO-8859-1', 'UTF-8,ISO-8859-1');
+
+	/* Definindo Description */
+	if ($desc = $component->getProperty('description', false, false))
+	    $schedulable['description'] = mb_convert_encoding(str_ireplace(array('\n', '\t'), array("\n", "\t"), $desc), 'ISO-8859-1', '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($schedulable['class']))
+	    $schedulable['class'] = CLASS_PRIVATE; // padrão classe private
+
+	$schedulable['calendar'] = $params['calendar'];
+
+	$participantsInTodo = array();
+
+	//TODO: Participants com delegated nao estao sendo levados em conta
+	while ($property = $component->getProperty('attendee', FALSE, TRUE)) {
+	    $participant = array();
+
+	    $mailUser = trim(str_replace('MAILTO:', '', $property['value']));
+
+	    $participantID = ($tpID = self::_getParticipantByMail($mailUser, $schedulable['participants'])) ? $tpID : 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'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
+
+	    $user = null;
+	    if ($intUser && count($intUser) > 0) {
+		$participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['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';
+	    $participant['acl'] = 'rowi';
+
+	    /* Verifica se este usuario Ã© um usuario interno do ldap */
+	    $intUser = Controller::find(array('concept' => 'user'), array('id', 'isExternal'), array('filter' => array('OR', array('=', 'mail', $mailUser), array('=', 'mailAlternateAddress', $mailUser))));
+
+	    $user = null;
+	    if ($intUser && count($intUser) > 0) {
+		$participant['isExternal'] = isset($intUser[0]['isExternal']) ? $intUser[0]['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 (!isset($schedulable['participants']) || !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'], $schedulable['participants'])) {
+		$participantID = mt_rand() . '2(Formatter)';
+
+		$participant['schedulable'] = $todoID;
+		$participant['status'] = STATUS_CONFIRMED;
+		$participant['isOrganizer'] = '1';
+		$participant['acl'] = 'rowi';
+		$participant['isExternal'] = 0;
+		$participant['user'] = $params['owner'];
+		$interation['participant://' . $participantID] = $participant;
+		$schedulable['participants'][] = $participantID;
+	    }
+	}
+	
+	$alarms = array();
+	
+	/* Definindo ALARMES */
+	while ($alarmComp = $component->getComponent('valarm'))
+	{
+		$alarm = array();
+		$alarmID = mt_rand() . '6(Formatter)';
+		$action =  $alarmComp->getProperty('action', false, true);
+		$trygger = $alarmComp->getProperty('trigger', false, true);
+		$alarm['type'] = self::decodeAlarmAction($action['value']);
+
+		 if(isset($trygger['value']['day']))
+		{
+			$alarm['time'] = $trygger['value']['day'];
+			$alarm['unit'] = 'd';
+		}
+		else if(isset($trygger['value']['hour']))
+		{
+			$alarm['time'] = $trygger['value']['hour'];
+			$alarm['unit'] = 'h';
+ 		}
+		else if(isset($trygger['value']['min']))
+		{
+			$alarm['time'] = $trygger['value']['min'];
+			$alarm['unit'] = 'm';
+		}
+		
+		foreach ($interation as $iint => &$vint)
+		{
+			if(isset($vint['user']) && $vint['user'] == Config::me('uidNumber'))
+			{
+				$alarm['participant'] = str_replace('participant://', '', $iint);	
+				$vint['alarms'][] = $alarmID;
+			}
+		}
+		$alarm['schedulable'] = $eventID;
+				
+		$interation['alarm://' . $alarmID ] = $alarm;
+		
+	}
+	
+	
+	/* Definindo DTSTAMP */
+	if ($dtstamp = self::_getTime($component, 'dtstamp'))
+	    $schedulable['dtstamp'] = $dtstamp;
+
+	/* Definindo TRANSP */
+	if (($tranp = $component->getProperty('transp', false, true)) && $tranp && is_string($tranp) && 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;
+
+	while ($attach = $component->getProperty('ATTACH', FALSE, TRUE)) {
+
+	    $attachCurrent = array('name' => $attach['params']['X-FILENAME'],
+		'size' => strlen($attach['value']),
+		'type' => self::_getContentType($attach['params']['X-FILENAME'])
+	    );
+
+	    $ids = Controller::find(array('concept' => 'attachment'), array('id'), array('filter' => array('AND', array('=', 'name', $attachCurrent['name']), array('=', 'size', $attachCurrent['size']), array('=', 'type', $attachCurrent['type']))));
+
+	    if (!is_array($ids)) {
+		$attachCurrent['source'] = $attach['value'];
+		//insere o anexo no banco e pega id para colcar no relacionamento				
+		$idAttachment = Controller::create(array('concept' => 'attachment'), $attachCurrent);
+	    }else
+		$idAttachment = array('id' => $ids[0]['id']);
+
+	    $calendarToAttachmentId = mt_rand() . '2(Formatter)';
+	    $calendarToAttachment['attachment'] = $idAttachment['id'];
+	    $calendarToAttachment['schedulable'] = $eventID;
+	    $interation['schedulableToAttachment://' . $calendarToAttachmentId] = $calendarToAttachment;
+
+	    $schedulable['attachments'][] = $calendarToAttachmentId;
+	}
+
+	$interation['schedulable://' . $todoID] = $schedulable;
 
 	return $interation;
