Index: trunk/prototype/modules/calendar/interceptors/DBMapping.php
===================================================================
--- trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 6331)
+++ trunk/prototype/modules/calendar/interceptors/DBMapping.php	(revision 6344)
@@ -202,5 +202,5 @@
 	$lastExceptions = Controller::find(array('concept' => 'repeatOccurrence'), array("occurrence"), array('filter' => array('AND', array('=', 'repeat', $id), array('=', 'exception', 1))));
 
-	//Recurepa as execeções anteriores caso exista
+	//Recurepa as execeÃ§Ãµes anteriores caso exista
 	if (isset($lastExceptions) && count($lastExceptions) && $lastExceptions)
 	    foreach ($lastExceptions as $key => $value)
@@ -323,6 +323,6 @@
 	    return( array() );
 
-	//Nao deve ser usando o horário da repeticao pois nela contem apenas o dias,
-	//deve se recuperar o horário do evento para um correto calculo.
+	//Nao deve ser usando o horÃ¡rio da repeticao pois nela contem apenas o dias,
+	//deve se recuperar o horÃ¡rio do evento para um correto calculo.
 	if (max($start, $repeat['startTime']) != $repeat['startTime']) {
 	    $time = new DateTime('@' . (int) ( $repeat['startTime'] / 1000 ), new DateTimeZone('UTC'));
@@ -362,5 +362,5 @@
 	    $u = $result->format('U') * 1000;
 
-	    if ($u > $end) //data da repetição atual maior que a data final da busca do usuario ?
+	    if ($u > $end) //data da repetiÃ§Ã£o atual maior que a data final da busca do usuario ?
 		break;
 
@@ -628,5 +628,5 @@
 		    $result[$i]['calendar'] = Controller::read(array('concept' => 'calendar', 'id' => $v['calendar']), false, false);
 		    $result[$i]['defaultAlarms'] = Controller::find(array('concept' => 'calendarSignatureAlarm'), false, array('filter' => array('=', 'calendarSignature', $v['id'])));
-		    //Caso não seja o dono da agenda retorna o objeto permission com as acls
+		    //Caso nï¿œo seja o dono da agenda retorna o objeto permission com as acls
 		    if ($result[$i]['isOwner'] == 0) {
 			$permission = Controller::find(array('concept' => 'calendarToPermission'), false, array('filter' => array('AND', array('=', 'calendar', $v['calendar']), array('=', 'user', Config::me('uidNumber')))));
@@ -712,69 +712,61 @@
         }
     } 
-
+    
+    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'))));
+		$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])) ? count($return) : 0;
+    }
+    
     public function deleteSchedulable(&$uri, &$params, &$criteria, $original) {
-
-	if (Config::module('useCaldav', 'expressoCalendar'))
+        if (Config::module('useCaldav', 'expressoCalendar'))
 	    require_once ROOTPATH . '/modules/calendar/interceptors/DAViCalAdapter.php';
-	
-	if(isset($criteria['filter']) && $criteria['filter'] && isset($criteria['filter'][1][2])){
-	    $idSchedulable = $criteria['filter'][1][2];
-	    $idCalendar = $criteria['filter'][2][2];
-	    
-	    if(!self::ownerSchedulable($idSchedulable, $criteria['filter'][3][2])){
-		$isPermissionFromOwner = self::permissionFromCalendarSignature($idCalendar, $idSchedulable);
-		
-		if($isPermissionFromOwner){
-		    Controller::delete(array('concept' => 'schedulable', 'id' => $idSchedulable));
-
-		}else{
-		    $calendarsToSchedulable = self::schedulable2calendarToObject($idSchedulable);
-
-		    foreach($calendarsToSchedulable as $value)
-			if($value['calendar_id'] == $idCalendar){    
-
-			    $participant = Controller::read(array('concept' => 'participant'), array('id'), array('filter' =>
-				array('AND',
-				    array('=', 'user', $criteria['filter'][3][2]),
-				    array('=', 'schedulable', $idSchedulable)
-				)));
-
-			    Controller::call(('update'), array('concept' => 'participant', 'id' => $participant[0]['id']), array('status' => STATUS_CANCELLED));
-			    Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $value['calendar_to_calendar_object']));
-			    break;
-			}
-		}
-		return false;
-	    }
-
-	    $uri['id'] = $idSchedulable;
-	}
-
-	$calendarsToSchedulable = self::schedulable2calendarToObject($uri['id']);
-
-	if (!self::ownerSchedulable($uri['id'], Config::me('uidNumber')) && !self::isAllowDeleteInCalendar($calendarsToSchedulable[0]['calendar_id'])) {
-
-	    foreach ($calendarsToSchedulable as $i => $v) {
-		Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $v['calendar_to_calendar_object']));
-
-		if (Config::module('useCaldav', 'expressoCalendar'))
-		    DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location']));
-	    }
-
-	    /* Seta o participante como rejeitado */
-	    $participant = Controller::read(array('concept' => 'participant'), array('id'), array('filter' =>
-		array('AND',
-		    array('=', 'user', Config::me('uidNumber')),
-		    array('=', 'schedulable', $idSchedulable)
-		)));
-
-	    Controller::call(('update'), array('concept' => 'participant', 'id' => $participant[0]['id']), array('status' => STATUS_CANCELLED));
-
-	    return false; /* Mata o restante da execução */
-	}
-
-	if (Config::module('useCaldav', 'expressoCalendar'))
-	    foreach ($calendarsToSchedulable as $i => $v)
-		DAViCalAdapter::deleteEvent($uri['id'], array('location' => $v['calendar_location']));
+        
+        if(isset($criteria['filter']) && $criteria['filter'] && isset($criteria['filter'][1][2])){
+            $idSchedulable = $criteria['filter'][1][2];
+			$idCalendar = $criteria['filter'][2][2];
+            $owner = $criteria['filter'][3][2];
+
+            $qtdMyCalendars = self::countMyCalendarsEvent($idSchedulable, $owner);
+
+            $link = Controller::read(array('concept' => 'calendarToSchedulable'), false, array('filter' => array('AND', array('=','calendar',$idCalendar), array('=','schedulable',$idSchedulable))));
+            $link = (is_array($link) && isset($link[0])) ? $link[0] : $link;
+            
+            $calendar = Controller::read(array('concept' => 'calendar'), false, array('filter' => array('=','id',$idCalendar)));
+            $calendar = (is_array($calendar) && isset($calendar[0])) ? $calendar[0] : $calendar;
+
+            if($isAttende = !self::ownerSchedulable($idSchedulable, $owner)){
+                Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $link['id']));
+                
+                if($qtdMyCalendars <= 1){
+
+                    $participant = Controller::read(array('concept' => 'participant'), array('id'), array('filter' =>
+                        array('AND',
+                            array('=', 'user', $owner),
+                            array('=', 'schedulable', $idSchedulable)
+                        )));
+
+                    Controller::call(('update'), array('concept' => 'participant', 'id' => $participant[0]['id']), array('status' => STATUS_CANCELLED));
+                }
+
+            }else{
+                if($qtdMyCalendars > 1 )
+                    Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $link['id']));
+            }
+
+            if (Config::module('useCaldav', 'expressoCalendar'))
+		    DAViCalAdapter::deleteEvent($idSchedulable, array('location' => $calendar['location']));
+
+            if($isAttende || ($qtdMyCalendars > 1))
+                return false;
+
+            $uri['id'] = $idSchedulable;
+        }
+        
     }
 
@@ -829,8 +821,8 @@
     public function createDefaultSignature(&$uri, &$result, &$criteria, $original) {
 
-	//Caso uma busca não retorne nenhum resultado e foi buscado pelas assinaturas do usuario logado apenas
+	//Caso uma busca nÃ£o retorne nenhum resultado e foi buscado pelas assinaturas do usuario logado apenas
 	$isValidSignature = false;
 
-	//Veirifica pois o usuário pode ter varias assinaturas mas não ser dona de nenhuma
+	//Veirifica pois o usuÃ¡rio pode ter varias assinaturas mas nÃ£o ser dona de nenhuma
 	if (count($result) > 0) {
 	    foreach ($result as $value) {
@@ -883,7 +875,7 @@
 		}
 	    } else {
-		//Criaremos uma agenda padrão
+		//Criaremos uma agenda padrï¿œo
 		$cal = array('name' => 'Calendario',
-		    'description' => 'Calendario Padrão',
+		    'description' => 'Calendario Padrï¿œo',
 		    'timezone' => (date_default_timezone_get()) ? date_default_timezone_get() : 'America/Sao_Paulo',
 		    'dtstamp' => time() . '000'
@@ -1012,24 +1004,4 @@
     }
 
-    private static function permissionFromCalendarSignature($idCalendar, $idEvent) {
-	$signature = Controller::find(array('concept' => 'calendarSignature'), false, array( 'filter' => array('AND', array('=', 'calendar', $idCalendar), array('=', 'isOwner', '1')), 'deepness' => 2));
-	
-	$signature = is_array($signature) ? $signature[0] : $signature;
-
-	if($signature['user']['id'] == Config::me('uidNumber')){
-	    return false;
-	}else{
-	   $isOwner = Controller::find(array('concept' => 'participant'), array('id'), array('filter' =>
-		    array('AND',
-			array('=', 'isOrganizer', '1'),
-			array('=', 'user', $signature['user']['id']),
-			array('=', 'schedulable', $idEvent)
-			)));
-
-	return ( isset($isOwner[0]['id']) ) ? true : false;
-	}
-    }
-    
-    
     private static function ownerSchedulable($id, $me) {
 
