Index: trunk/prototype/modules/calendar/interceptors/DBMapping.php
===================================================================
--- trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 6849)
+++ trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 6996)
@@ -10,27 +10,29 @@
 class DBMapping extends Helpers {
 
-    static function encodeCreateSchedulable(&$uri, &$params, &$criteria, $original) {
-	$params['type_id'] = EVENT_ID;
-
-	if (!is_numeric($params['startTime']))
-	    $params['startTime'] = self::parseTimeDate($params['startTime'], $params['timezone']);
-
-	if (!is_numeric($params['endTime'])) {
-	    $params['endTime'] = self::parseTimeDate($params['endTime'], $params['timezone']);
-
-	    if ($params['allDay'])
-		$params['endTime'] = $params['endTime'] + 86400000;
-	}
-
-	$params['rangeEnd'] = $params['endTime'];
-	$params['rangeStart'] = $params['startTime'];
-
-	///////////////////////////////////////////////////////////////////
-
-	$params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] : time() . '000';
-	$params['lastUpdate'] = (isset($params['lastUpdate'])) ? $params['lastUpdate'] : time() . '000';
-	$params['type'] = EVENT_ID;
-	$params['uid'] = isset($params['uid']) ? $params['uid'] : self::_makeUid();
-    }
+    static function encodeCreateSchedulable(&$uri, &$params, &$criteria, $original) 
+    {
+
+    	if (isset($params['startTime']) && !is_numeric($params['startTime'])){
+    	    $params['startTime'] = self::parseTimeDate($params['startTime'], $params['timezone']);
+	    $params['rangeStart'] = $params['startTime'];
+	}
+    	if (isset($params['endTime']) && !is_numeric($params['endTime'])) {
+    	    $params['endTime'] = self::parseTimeDate($params['endTime'], $params['timezone']);
+
+    	    if ($params['allDay'])
+    		$params['endTime'] = $params['endTime'] + 86400000;
+	    
+	    $params['rangeEnd'] = $params['endTime'];
+    	}
+
+        if (isset($params['due']) && $params['due'] != '' && !is_numeric($params['due']))
+            $params['due'] = self::parseTimeDate($params['due'], $params['timezone']);
+
+    	///////////////////////////////////////////////////////////////////
+
+    	$params['dtstamp'] = (isset($params['dtstamp'])) ? $params['dtstamp'] : time() . '000';
+    	$params['lastUpdate'] = (isset($params['lastUpdate'])) ? $params['lastUpdate'] : time() . '000';
+    	$params['uid'] = isset($params['uid']) ? $params['uid'] : self::_makeUid();
+        }
 
     static function parseTimeDate($time, $timezone) {
@@ -66,4 +68,19 @@
 	if (isset($params['type']))
 	    $params['type'] = self::codeAlarmType($params['type']);
+	else{
+	    $alarm = Controller::read( array('concept' => 'alarm' , 'id' => $params['id'] ));
+
+	    $params['unit'] = $alarm['unit'];
+	}
+	$params['offset'] = $params['time'] * 1000;
+
+
+	switch( strtolower($params['unit']) )
+	{
+	    case 'd': $params['offset'] *= 24;
+	    case 'h': $params['offset'] *= 60;
+	    case 'm': $params['offset'] *= 60;
+	}
+	
     }
 
@@ -119,4 +136,6 @@
 		.'calendar_object.dtstart as "startTime", calendar_object.summary as "summary", '
 		.'calendar_object.description as "description", calendar_object.dtend as "endTime" , '
+        .'calendar_object.priority as "priority", calendar_object.due as "due", '
+        .'calendar_object.percentage as "percentage", calendar_object.status as "status", '
 		.'calendar_object.location as "location", calendar_object.allday as "allDay", '
 		.'calendar_object.transp as "transparent", calendar_object.class_id as "class", '
@@ -127,5 +146,6 @@
 		.'calendar FROM calendar_to_calendar_object , calendar_object '
 		.'WHERE ( calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $criteria['filter'][2][2]) . '\')) '
-		.'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id ';	
+		.'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id '
+        .'AND calendar_object.id NOT IN(select calendar_object_task_id from calendar_task_to_activity_object where owner = \'' . Config::me('uidNumber') . '\') ';	
 	    
 	    if(isset($criteria['searchEvent']) && $criteria['searchEvent']){
@@ -157,4 +177,36 @@
 		$params = array_merge($params, $occ);		
 	    }
+	    $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
+	    return false;
+	}
+    }
+
+    public function findTask(&$uri, &$params, &$criteria, $original) {
+
+	if (isset($criteria['filterTasks']) && $criteria['filterTasks']) {
+
+	    $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.priority as "priority", calendar_object.due as "due", '
+	    .'calendar_object.percentage as "percentage", calendar_object.status as "status", '
+	    .'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 ( calendar_to_calendar_object.calendar_id IN (\'' . implode('\',\'', $criteria['filter'][3][2]) . '\')) '
+	    .'AND calendar_to_calendar_object.calendar_object_id = calendar_object.id '
+        .'AND calendar_to_calendar_object.calendar_object_id NOT IN (select calendar_object_activity_id from calendar_task_to_activity_object where owner =  \'' . Config::me("uidNumber") . '\' ) '    
+        .'AND calendar_to_calendar_object.calendar_object_id NOT IN (select calendar_object_task_id from calendar_task_to_activity_object where owner =  \'' . Config::me("uidNumber") . '\' ) ';    
+
+        if(isset($criteria['filter'][4]))
+            $sql .= 'AND (((upper("summary") like upper(\'%'.$criteria['filter'][4][1][2].'%\') OR upper("description") like upper(\'%'.$criteria['filter'][4][1][2].'%\'))))';
+
+	    $sql .= 'AND (range_start >= \'' . $criteria['filter'][2][2] . '\' AND type_id <= \'' .  $criteria['filter'][1][2] . '\')';
+
+	    $params = Controller::service('PostgreSQL')->execResultSql($sql);
 	    $params = self::deepnessFindEvent($uri, $params, $criteria, $original);
 	    return false;
@@ -405,22 +457,79 @@
     public function encodeUpdateSchedulable(&$uri, &$params, &$criteria, $original) {
 
-	$event = Controller::read(array('concept' => 'schedulable', 'id' => $params['id']));
-	
-	if (isset($params['startTime'])) {
-
-	    if (!is_numeric($params['startTime']))
-		$params['startTime'] = self::parseTimeDate($params['startTime'], $event['timezone']);
-
-	    $params['rangeStart'] = $params['startTime'];
-	}if (isset($params['endTime'])) {
-
-	    if (!is_numeric($params['endTime'])) {
-		$params['endTime'] = self::parseTimeDate($params['endTime'], $event['timezone']);
-
-	    if ((isset($params['allDay']) && $params['allDay']) || ( !isset($params['allDay']) && $event['allDay']))
-		$params['endTime'] = $params['endTime'] + 86400000;
-	    }
-	    $params['rangeEnd'] = $params['endTime'];
-	}
+    	$event = Controller::read(array('concept' => 'schedulable', 'id' => $params['id']));
+    	            
+    	if (isset($params['startTime'])) {
+
+    	    if (!is_numeric($params['startTime']))
+    		$params['startTime'] = self::parseTimeDate($params['startTime'], $event['timezone']);
+
+    	    $params['rangeStart'] = $params['startTime'];
+    	}
+
+        if (isset($params['endTime'])) {
+
+    	    if (!is_numeric($params['endTime'])) {
+        		$params['endTime'] = self::parseTimeDate($params['endTime'], $event['timezone']);
+
+        	    if ((isset($params['allDay']) && $params['allDay']) || ( !isset($params['allDay']) && $event['allDay']))
+        		$params['endTime'] = $params['endTime'] + 86400000;
+    	    }
+    	    $params['rangeEnd'] = $params['endTime'];
+    	}
+
+
+        if (isset($params['due']) && $params['due'] != '' && !is_numeric($params['due']))
+            $params['due'] = self::parseTimeDate($params['due'], $event['timezone']);
+
+
+        if($event['type'] == '2'){
+
+            $criteria['historic'] = $params;
+            $criteria['beforeValue'] = $event;
+
+            if(isset($params['startTime']) && $params['startTime'] == $event['startTime'])
+                unset($criteria['historic']['startTime']);
+
+            if(isset($params['endTime']) && $params['endTime'] == $event['endTime'])
+                unset($criteria['historic']['endTime']);
+
+            if(isset($params['due']) && $params['due'] == $event['due'])
+                unset($criteria['historic']['due']);
+
+	    //necessário para atulizar a atividade de composta pela tarefa aqui sendo atualizada
+	    if(isset($criteria['historic']['startTime']) || isset($criteria['historic']['endTime'])){
+		$taskToActivity = Controller::find(array('concept' => 'taskToActivity'), false, array('filter' => array('AND', array('=', 'schedulable', $event['id']), array('=', 'owner', Config::me('uidNumber'))), 'deepness' => 2));
+
+		if(!empty($taskToActivity)){
+		    $activity = Controller::read(array('concept' => 'schedulable', 'id' => $taskToActivity[0]['activity']), array('startTime', 'endTime', 'rangeStart', 'rangeEnd'));
+		    $start = $params['startTime'];
+		    $end = $params['endTime'];
+		    foreach($taskToActivity as $t){
+			 if($t['task']['id'] != $params['id']){
+			    $start = $t['task']['startTime'] < $start ? $t['task']['startTime'] : $start;
+			    $end = $t['task']['endTime'] < $end ? $t['task']['endTime'] : $end;
+			 }
+		    }
+
+		    $toUpdate = array();
+		    
+		    if($start != $activity['startTime'])
+			$toUpdate['starTime'] = $start;
+		    
+		    if($end != $activity['endTime'])
+			$toUpdate['endTime'] = $end;
+		     
+		    if(!empty($toUpdate))
+			Controller::update(array('concept' => 'schedulable', 'id' => $activity['id']), $toUpdate);		  
+		}
+	    }
+
+            unset($criteria['historic']['rangeEnd']);
+            unset($criteria['historic']['rangeStart']);
+	    unset($criteria['historic']['class']);
+	    unset($criteria['historic']['type']);
+	    unset($criteria['historic']['allDay']);
+            unset($criteria['historic']['id']);            
+        }
     }
 
@@ -453,4 +562,75 @@
     }
 
+
+    static function prepareParticipantHistoric(&$uri, &$params, &$criteria, $original){
+       $participant = Controller::read(array('concept' => 'participant', 'id' => $uri['id']));
+       $schedulable = Controller::read(array('concept' => 'schedulable', 'id' => $participant['schedulable']));
+
+
+       if($schedulable['type'] == '2')
+            $criteria['historic']['participant']  = $participant;
+    } 
+
+    static function removeParticipantHistoric(&$uri, &$params, &$criteria, $original){
+        if(isset($criteria['historic'])){
+
+            $participant = $criteria['historic']['participant'];
+
+             Controller::create(array('concept' => 'calendarHistoric'), 
+                array('schedulable' => $participant['schedulable'], 
+                    'user' => Config::me('uidNumber'),
+                    'time' => time() . '000',
+                    'attribute' => 'participant',
+                    'beforeValue' => $participant['user'],
+                    'afterValue' => ''
+                    )
+                );
+
+        }
+
+    }
+
+    static function createParticipantHistoric(&$uri, &$params, &$criteria, $original){
+
+	if(isset($original['properties']) && $original['properties']['isOrganizer'] != '1'){
+	    if(!isset($criteria['event'])){
+		$event = Controller::read(array('concept' => 'schedulable', 'id' => $original['properties']['schedulable']));
+		$criteria['event'] = $event;
+	    }else
+		$event = $criteria['event'];
+
+	    if($event['type'] == '2'){
+		Controller::create(array('concept' => 'calendarHistoric'), 
+		    array('schedulable' => $original['properties']['schedulable'], 
+			'user' => Config::me('uidNumber'),
+			'time' => time() . '000',
+			'attribute' => 'participant',
+			'beforeValue' => '',
+			'afterValue' => $original['properties']['user']
+			)
+		    );
+	    }
+	}
+    }
+
+    static function createHistoric(&$uri, &$result, &$criteria, $original) {
+
+        if(isset($criteria['historic']) && count($criteria['historic'])){
+            $time =  time() . '000';
+
+            foreach($criteria['historic'] as $k => $v){
+                Controller::create(array('concept' => 'calendarHistoric'), 
+                    array('schedulable' => $uri['id'], 
+                        'user' => Config::me('uidNumber'),
+                        'time' => $time,
+                        'attribute' => $k,
+                        'beforeValue' => $criteria['beforeValue'][$k],
+                        'afterValue' => $v
+                        )
+                    );
+            }
+        }    
+    }
+
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
 
@@ -466,10 +646,53 @@
     }
 
-    public function createCreateSchedulableToAttachment(&$uri, &$params, &$criteria, $original) {
-	if (array_key_exists('attachments', $original['properties']))
-	    foreach ($original['properties']['attachments'] as $key => $value) {
-		if (isset($params['id']))
-		    Controller::create(array('concept' => 'schedulableToAttachment'), array('attachment' => $value['attachment'], 'schedulable' => $params['id']));
-	    }
+    //TODO: Remover apos suporte a ManytoMany na api 
+    public function createTasksToActivity(&$uri, &$result, &$criteria, $original) {
+
+        if(isset($original['properties']['taskToActivity']) && $original['properties']['taskToActivity']){
+
+            foreach($original['properties']['taskToActivity'] as $relational)
+
+                Controller::create(array('concept' => 'taskToActivity'), array('task' => $relational['task'], 'owner' => $relational['owner'], 'activity' => $result['id']));
+
+        }
+    }
+
+    public function removeAttachmentHistoric(&$uri, &$params, &$criteria, $original) {
+
+        if(isset($criteria['historic'])){
+            $attachment = $criteria['historic']['attachment'];
+
+            $attachment['attachment'] = Controller::read(array('concept' => 'attachment', 'id' => $attachment['attachment']), array('name'));
+            Controller::create(array('concept' => 'calendarHistoric'), 
+                    array('schedulable' => $attachment['schedulable'], 
+                        'user' => Config::me('uidNumber'),
+                        'time' => time() . '000',
+                        'attribute' => 'attachment',
+                        'beforeValue' => $attachment['attachment']['name'],
+                        'afterValue' => ''
+                        )
+                    );
+
+        }
+    
+    }
+
+    public function createAttachmentHistoric(&$uri, &$params, &$criteria, $original) {
+        $event = Controller::read(array('concept' => 'schedulable', 'id' => $original['properties']['schedulable']));
+
+        if($event['type'] == '2'){
+            $attachment = Controller::read(array('concept' => 'attachment', 'id' => $original['properties']['attachment']), array('name'));
+
+            Controller::create(array('concept' => 'calendarHistoric'), 
+                array('schedulable' => $original['properties']['schedulable'], 
+                    'user' => Config::me('uidNumber'),
+                    'time' => time() . '000',
+                    'attribute' => 'attachment',
+                    'beforeValue' => '',
+                    'afterValue' => $attachment['name']
+                    )
+                );
+
+        }
     }
 
@@ -512,4 +735,31 @@
 
     //TODO: Remover apos suporte a deepness na api 
+    public function deepnessFindTask(&$uri, &$result, &$criteria, $original) {
+        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) 
+           foreach($result as &$value)
+                $value['task'] = Controller::read(array('concept' => 'schedulable', 'id' => $value['task']));
+           
+        
+        return $result;
+    }
+
+    //TODO: Remover apos suporte a deepness na api 
+    public function deepnessFindHistoric(&$uri, &$result, &$criteria, $original) {
+        if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
+            foreach($result as &$v){
+                $v['user'] = Controller::read(array('concept' => 'user', 'id' => $v['user']));
+
+                if($v['attribute'] == 'participant'){
+                    if($v['beforeValue'] != '')
+                        $v['beforeValue'] = Controller::read(array('concept' => 'user', 'id' => $v['beforeValue']));
+
+                    if($v['afterValue'] != '')
+                        $v['afterValue'] = Controller::read(array('concept' => 'user', 'id' => $v['afterValue']));
+                }
+            }
+        }
+    }
+
+    //TODO: Remover apos suporte a deepness na api 
     public function deepnessFindEvent(&$uri, &$result, &$criteria, $original) {
 	if (isset($original['criteria']['deepness']) && $original['criteria']['deepness'] != 0) {
@@ -543,4 +793,15 @@
 
 		$result[$i]['DayLigth'] = $DayLigth;
+
+        if(((int)$v['type']) == 2){
+
+            $taskToActivity = Controller::find(array('concept' => 'taskToActivity'), false, array('filter' => array('AND', array('=', 'activity', $v['id']), array('=','owner', Config::me('uidNumber'))) , 'deepness' => 2));
+
+            if($taskToActivity)
+                $result[$i]['taskToActivity'] = $taskToActivity;
+
+            $result[$i]['historic'] = Controller::find(array('concept' => 'calendarHistoric'), false, array('filter' => array('=', 'schedulable', $v['id']) , 'deepness' => 2));
+
+        }
 
 		if (isset($v['id'])) {
@@ -608,4 +869,8 @@
 	    } 
 	    
+       }
+       
+       if(isset($result['id']) && $result['type'] == '2'){
+	   $result['historic'] =  Controller::find( array( 'concept' => 'calendarHistoric' ), false, array( 'filter' => array( '=', 'schedulable', $result['id'] ) ) );
        }
    } 
@@ -791,5 +1056,5 @@
     
     static private function countMyCalendarsEvent($id, $owner) {
-		$sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'user', $owner), array('=', 'isOwner', '1'))));
+		$sig = Controller::find(array('concept' => 'calendarSignature'), array('user', 'calendar', 'isOwner'), array('filter' => array('AND', array('=', 'isOwner', '1'), array('=', 'user', $owner))));
 		$calendars = array();
 		foreach ($sig as $val)
@@ -807,5 +1072,5 @@
         if(isset($criteria['filter']) && $criteria['filter'] && isset($criteria['filter'][1][2])){
             $idSchedulable = $criteria['filter'][1][2];
-			$idCalendar = $criteria['filter'][2][2];
+	    $idCalendar = $criteria['filter'][2][2];
             $owner = $criteria['filter'][3][2];
 
@@ -844,4 +1109,8 @@
 
             $uri['id'] = $idSchedulable;
+	    
+	    if(isset($criteria['filter']) && isset($criteria['filter'][4]) && isset($criteria['filter'][4][2])){
+		Controller::deleteALL(array('concept' => 'taskToActivity'), null, array('filter' => array('=', 'activity', $idSchedulable)));
+	    }
         }
         
@@ -894,9 +1163,16 @@
             $schedulableAttachment = Controller::read(array('concept' => 'schedulableToAttachment'), false, array('filter' => array( '=', 'attachment' , $original['URI']['id'] )));
             $uri['id'] = $schedulableAttachment[0]['id'];
+
+            $params = $schedulableAttachment[0];
+
+            $event = Controller::read(array('concept' => 'schedulable', 'id' => $params['schedulable']));
+            if($event['type'] == '2')
+                $criteria['historic']['attachment'] = $schedulableAttachment[0];
+
         }
     }
 
     public function deleteAttachmentDependences(&$uri, &$params, &$criteria, $original) {
-        Controller::delete(array('concept' => 'attachment', 'id' => $original['URI']['id']));
+        Controller::delete(array('concept' => 'attachment', 'id' => (isset($params['attachment']) ? $params['attachment'] : $original['URI']['id'])));
     }
     
@@ -908,5 +1184,54 @@
     }
 
+
+     public function createDefaultGroup(&$uri, &$result, &$criteria, $original) {
+        if( $original['criteria']['filter'][1][0] == '=' &&
+        $original['criteria']['filter'][1][1] == 'user' &&
+        $original['criteria']['filter'][1][2] == $_SESSION['phpgw_session']['account_id']){
+
+            $existDefaultGroup = false;
+
+            foreach($result as $v){
+                if($v['type'] == 1 && $v['calendar']['type'] == 1)
+                    $existDefaultGroup = true;
+            }
+
+            if(!$existDefaultGroup){
+
+                $cal = array('name' => 'Sem grupo',
+                    'description' => 'Sem grupo',
+                    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
+                    'dtstamp' => time() . '000',
+                    'type' => '1'
+                );
+
+                $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
+
+                $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
+                    'calendar' => $calCreated['id'],
+                    'isOwner' => '1',
+                    'dtstamp' => time() . '000',
+                    'fontColor' => 'FFFFFF',
+                    'backgroundColor' => '3366CC',
+                    'borderColor' => '3366CC',
+                    'type' => '1'
+                );
+
+                $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
+                $sigCreated = Controller::read(array('concept' => 'calendarSignature', 'id' => $sigCreated['id']), false, array('deepness' => 2 ));
+
+                array_push($result, $sigCreated);
+            }
+
+        }
+
+     }
+
     public function createDefaultSignature(&$uri, &$result, &$criteria, $original) {
+
+    if(count($result) == 0 && isset($criteria['filter'][3]) && isset($criteria['filter'][3]['isRecursion'])){
+        throw new Exception('It was not possible to find to calendar!');
+        return false;
+    }
 
 	//Caso uma busca não retorne nenhum resultado e foi buscado pelas assinaturas do usuario logado apenas
@@ -916,6 +1241,6 @@
 	if (count($result) > 0) {
 	    foreach ($result as $value) {
-		if (isset($value['isOwner']) && $value['isOwner'] != 0)
-		    $isValidSignature = true;
+    		if (isset($value['isOwner']) && $value['isOwner'] != 0 && isset($value['type']) && $value['type'] == 0)
+    		    $isValidSignature = true;
 	    }
 	}
@@ -928,64 +1253,71 @@
 
 	    if (Config::module('useCaldav', 'expressoCalendar')) {
-		require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
-
-		$calendario = DAViCalAdapter::findCalendars();
+    		require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+    		$calendario = DAViCalAdapter::findCalendars();
 	    }
 
 	    if (Config::module('useCaldav', 'expressoCalendar') && is_array($calendario) && count($calendario) > 0) {
-		foreach ($calendario as $i => $v) {
-
-		    $urlA = explode('/', $v->url);
-		    $name = isset($v->displayname) ? $v->displayname : $urlA[(count($urlA) - 2)];
-		    $cal = array('name' => $name,
-			'description' => isset($v->description) ? $v->description : $name,
-			'timezone' => isset($v->timezone) ? $v->timezone : (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
-			'dtstamp' => time() . '000',
-			'location' => $urlA[(count($urlA) - 3)] . '/' . $urlA[(count($urlA) - 2)]
-		    );
-
-		    $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
-
-
-
-		    $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
-			'calendar' => $calCreated['id'],
-			'isOwner' => '1',
-			'dtstamp' => time() . '000',
-			'fontColor' => 'FFFFFF',
-			'backgroundColor' => '3366CC',
-			'borderColor' => '3366CC',
-		    );
-
-		    $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
-
-
-		    DAViCalAdapter::importCollection($v->url, $calCreated['id']);
-		}
+    		foreach ($calendario as $i => $v) {
+
+    		    $urlA = explode('/', $v->url);
+    		    $name = isset($v->displayname) ? $v->displayname : $urlA[(count($urlA) - 2)];
+    		    $cal = array('name' => $name,
+    			'description' => isset($v->description) ? $v->description : $name,
+    			'timezone' => isset($v->timezone) ? $v->timezone : (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
+    			'dtstamp' => time() . '000',
+    			'location' => $urlA[(count($urlA) - 3)] . '/' . $urlA[(count($urlA) - 2)]
+    		    );
+
+    		    $calCreated = Controller::create(array('concept' => 'calendar'), $cal);
+
+                if(!$calCreated){
+                    throw new Exception('Error to create calendar');
+                    return false;
+                }
+
+    		    $sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
+    			'calendar' => $calCreated['id'],
+    			'isOwner' => '1',
+    			'dtstamp' => time() . '000',
+    			'fontColor' => 'FFFFFF',
+    			'backgroundColor' => '3366CC',
+    			'borderColor' => '3366CC',
+    		    );
+
+    		    $sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
+
+                if(!$sigCreated){
+                    throw new Exception('Error to create signature');
+                    return false;
+                }
+
+    		    DAViCalAdapter::importCollection($v->url, $calCreated['id']);
+    		}
 	    } else {
-		//Criaremos uma agenda padrão
-		$cal = array('name' => 'Calendario',
-		    'description' => 'Calendario Padrão',
-		    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
-		    'dtstamp' => time() . '000'
-		);
-
-		$calCreated = Controller::create(array('concept' => 'calendar'), $cal);
-
-		$sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
-		    'calendar' => $calCreated['id'],
-		    'isOwner' => '1',
-		    'dtstamp' => time() . '000',
-		    'fontColor' => 'FFFFFF',
-		    'backgroundColor' => '3366CC',
-		    'borderColor' => '3366CC',
-		);
-
-		$sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
-	    }
-
-	    $result = Controller::find($original['URI'], $original['properties'] ? $original['properties'] : null, $original['criteria']);
+    		//Criaremos uma agenda padrão
+    		$cal = array('name' => 'Calendario',
+    		    'description' => 'Calendario Padrão',
+    		    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
+    		    'dtstamp' => time() . '000'
+    		);
+
+    		$calCreated = Controller::create(array('concept' => 'calendar'), $cal);
+
+    		$sig = array('user' => $_SESSION['wallet']['user']['uidNumber'],
+    		    'calendar' => $calCreated['id'],
+    		    'isOwner' => '1',
+    		    'dtstamp' => time() . '000',
+    		    'fontColor' => 'FFFFFF',
+    		    'backgroundColor' => '3366CC',
+    		    'borderColor' => '3366CC',
+    		);
+
+    		$sigCreated = Controller::create(array('concept' => 'calendarSignature'), $sig);
+        }
+    
+        $original['criteria']['filter'][] = array('isRecursion' => true);
+        $result = Controller::find($original['URI'], $original['properties'] ? $original['properties'] : null, $original['criteria']);
 	    return false;
-	}
+    	}
     }
 
@@ -1017,27 +1349,27 @@
 
     public function davcalCreateCollection(&$uri, &$params, &$criteria, $original) {
-	if (Config::module('useCaldav', 'expressoCalendar')) {
-	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
-	    DAViCalAdapter::mkcalendar($params['location'], $params['name'], isset($params['description']) ? $params['description'] : '' );
-	}
+    	if (Config::module('useCaldav', 'expressoCalendar')) {
+    	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+    	    DAViCalAdapter::mkcalendar($params['location'], $params['name'], isset($params['description']) ? $params['description'] : '' );
+	   }
     }
 
     public function davcalDeleteCollection(&$uri, &$params, &$criteria, $original) {
-	if (Config::module('useCaldav', 'expressoCalendar') && Config::module('onRemoveCascadeCalDav')) {
-	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
-	    $calendar = Controller::read($uri);
-	    DAViCalAdapter::rmCalendar($calendar['location']);
-	}
+    	if (Config::module('useCaldav', 'expressoCalendar') && Config::module('onRemoveCascadeCalDav')) {
+    	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+    	    $calendar = Controller::read($uri);
+    	    DAViCalAdapter::rmCalendar($calendar['location']);
+    	}
     }
 
     public function davcalUpdateCollection(&$uri, &$params, &$criteria, $original) {
-	if (Config::module('useCaldav', 'expressoCalendar')) {
-	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
-	    if (isset($params['location'])) {
-		$calendar = Controller::read($uri);
-		if ($calendar['location'] !== $params['location'])
-		    DAViCalAdapter::mvcalendar($calendar['location'], $params['location']);
-	    }
-	}
+    	if (Config::module('useCaldav', 'expressoCalendar')) {
+    	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
+    	    if (isset($params['location'])) {
+    		$calendar = Controller::read($uri);
+    		if ($calendar['location'] !== $params['location'])
+    		    DAViCalAdapter::mvcalendar($calendar['location'], $params['location']);
+    	    }
+    	}
     }
 
