<?php

require_once 'globals.php';


class Migrate_old_dbCommand extends CConsoleCommand
{
	public function cleanBadAuthorizationDatas()
	{
		echo "\n delete Plate authorization with no user..";
		Yii::app()->db->createCommand('delete w from whitelisttable w left join usertable u on UserID = u.ID where u.id is null')->execute();
		echo "\n done";
		
		echo "\n delete Plate authorization with no validity period..";
		Yii::app()->db->createCommand('delete w from whitelisttable w left join abbonamentotable a on AbbonamentoID = a.ID where a.id is null')->execute();
		echo "\n done";
		
		echo "\n delete Plate authorization with no vehicle..";
		Yii::app()->db->createCommand('delete w from whitelisttable w left join vehicletable v on VehicleID = v.ID where v.id is null')->execute();
		echo "\n done";
		
		echo "\n delete Plate authorization with wrong datetime";
		Yii::app()->db->createCommand("delete from abbonamentotable where (DATE(DATE_FORMAT(DataInizio, '%Y-%m-%d')) is null)")->execute();
		Yii::app()->db->createCommand("delete from abbonamentotable where (DATE(DATE_FORMAT(DataFine,   '%Y-%m-%d')) is null)")->execute();
		echo "\n done";
		
	}

	function createPath($path)
	{
		if (is_dir($path))
			 return true;
		
		$prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
		$return = self::createPath($prev_path);
		
		return ($return && is_writable($prev_path)) ? mkdir($path) : false;
	}
	
	public function exportImagesOnFileSystem()
	{
		$offset = 0;
		
		$curdb  = explode('=', Yii::app()->db->connectionString);
		$dbName =  $curdb[2];
		
		echo "\ndb=$dbName";

		echo "\nd -> Export STORICOTABLE";
		
		
		do
		{
			$resEv = Event::model()->findAll(array('condition'=>"Image !='' and Image is not null",  'order' => 't.StartTime', 'limit' => '1000' ));
				
			$count = count($resEv);
				
			if($count <= 0)
				break;
				
			$offset += $count;
	
			echo "\n export Images: ".$count." / ".$offset;
			echo "\n";
	
			foreach($resEv as $ev)
			{
				echo '.';
				
				$filename = $dbName."/images/StoricoTable/".$ev->StartTime->format('Ymd').'/'.$ev->StartTime->format('H').'/'.sprintf('%020d', $ev->ID).'/';
				
				$filenamedb = $filename;

				$path = pathCombine(Yii::app()->params['photoBasePath'], $filename);
				
				if(!file_exists($path))
					mkdir($path, 0777, true);
				
				$filename = $filename ."00000000000000000000_". $ev->ID.".jpg";
				$filenamedb = $filenamedb ."00000000000000000000_". $ev->ID.".jpg";
				
				if(file_exists($path + $filename))
					unlink($diskFileName);
				
				
				$diskFileName = pathCombine(Yii::app()->params['photoBasePath'], $filename);
				
				
				$file = fopen( $diskFileName, "w" );
								
				if( $file == false )
				{
					echo ( "Error in opening file $diskFileName" );
					continue;
				}
				
				$writeB = fwrite( $file, $ev->Image);

				fclose( $file );
				
				
				if($writeB > 0)
					Yii::app()->db->createCommand("update storicotable set blobfilename = '".$filenamedb."', Image = null where ID=".$ev->ID)->execute();
				else 
					echo "\nno images";
			
			}
			
			
		}
		while($count >= 0);
		
		
		
		echo "\nd -> Export TEB_TABLE";
		
		$offset = 0;
		
		
		do
		{
			$resMa = MediaAttachment::model()->findAll(array('condition'=>"BlobData !='' and BlobData is not null",  'order' => 't.EventID, t.BlobID', 'limit' => '1000' ));
		
			$count = count($resMa);
		
			if($count <= 0)
				break;
		
			$offset += $count;
		
			echo "\n export Blob: ".$count." / ".$offset;
			echo "\n";
		
			foreach($resMa as $ma)
			{
				echo ".";
		
				$blobTime = new DateTime();
				
				$ev = Event::model()->findByAttributes(array('ExtraInfoID'=> $ma->EventID));
				
				if($ev != null)
					$blobTime = $ev->StartTime;
				
				$filename = $dbName."/images/Teb_Table/".$blobTime->format('Ymd').'/'.$blobTime->format('H').'/'.sprintf('%020d', $ma->EventID).'/';
		
				$filenamedb = $filename;
		
				$path = pathCombine(Yii::app()->params['photoBasePath'], $filename);
		
				if(!file_exists($path))
					mkdir($path, 0777, true);
		
				$ext = '.jpg';
				if(stripos($ma->type, 'mp4') !== FALSE)
					$ext = '.mp4';
				else if(stripos($ma->type, 'avi') !== FALSE)
					$ext = '.avi';
				
				$filename = $filename ."00000000000000000000_". $ma->ID.$ext;
				$filenamedb = $filenamedb ."00000000000000000000_". $ma->ID.$ext;
		
				if(file_exists($path + $filename))
					unlink($diskFileName);
		
		
				$diskFileName = pathCombine(Yii::app()->params['photoBasePath'], $filename);
		
		
				$file = fopen( $diskFileName, "w" );
		
				if( $file == false )
				{
					echo ( "Error in opening file $diskFileName" );
					continue;
				}
		
				$writeB = fwrite( $file, $ma->BlobData);
		
				fclose( $file );
		
		
				if($writeB > 0)
				{
					Yii::app()->db->createCommand("update teb_table set blobfilename = '".$filenamedb."', BlobData = null where ID=".$ma->ID)->execute();
				}
				else
					echo "\nno images";
					
			}
				
				
		}
		while($count >= 0);
	}
	
	
	public function updateEventBehaviors()
	{
//		Event::model()->deleteAll(" validatedby != '' and validatedby != 'STANDBY'");
		
//		echo "\n delete events already validated..";
//		Yii::app()->db->createCommand("delete s, te, tb from storicotable s left join transitextrainfotable te on s.extrainfoid = te.id left join teb_table tb on tb.eventid = te.id where validatedby != '' and validatedby != 'STANDBY'")->execute();
//		echo "\n done";
	
//		Event::model()->updateAll(array('validation_result'=>''));
			
		ViolationDocument::model()->deleteAll();
		
		EventBehavior::model()->deleteAll();
		
		$offset = 0;
			
		do 
		{
			$resEv = Event::model()->findAll(array('order' => 't.ID asc', 'limit' => '1000', 'offset' => $offset ));
			
			$count = count($resEv);
			
			if($count <= 0)
				break;
			
			$offset += $count;
				
			echo "\n Update Event Behaviors: ".$count." / ".$offset;
				
			foreach($resEv as $ev)
			{
				$eb = new EventBehavior();
				$eb->id_event 			= $ev->ID;
				$eb->epoch 				= $ev->epoch;
				$ev->validation_result = '';
				
				
				
				$eb->validation_result = '';
				
				if($ev->Protocol == 'NO_MULTA')
				{
					$eb->validation_result = EventBehavior::STATUS_INVALID;
					$ev->validation_result = Event::VALIDATION_RESULT_INVALID;
					$ev->ext_code = '-';

					
					
				}
				else if($ev->ValidatedBy != '' and $ev->ValidatedBy != 'STANDBY')
				{
					$eb->validation_result = EventBehavior::STATUS_APPROVED;
					$ev->validation_result = Event::VALIDATION_RESULT_APPROVED;
					
					if($ev->Protocol != '')
						$ev->ext_code = $ev->Protocol;
						

				}
				
				$ev->update();

				$vdoc = new ViolationDocument();
				$vdoc->status = ViolationDocument::STATUS_MISSING;
				$vdoc->epoch = $ev->epoch;
				$vdoc->last_update = $ev->epoch;
			
				$gt = Gate::model()->findByAttributes(array('Gate'=>$ev->Gate));
			
				if($gt>GateType == Gate::GT_T_ID || $gt->GateType == 'T-ID')
				{
					$eb->setIsNewRecord(true);
					$be = Behavior::model()->findByAttributes(array('tag'=>Behavior::WHITELIST_VIOLATION));
					$eb->id_behavior = $be->ID;
					$eb->save(false);
						
					$vdoc->id_event_behavior = $eb->ID;
					$vdoc->save(false);
						
				}
				else if($gt->GateType == Gate::GT_T_RED)
				{
					$eb->setIsNewRecord(true);
					$be = Behavior::model()->findByAttributes(array('tag'=>Behavior::RED_VIOLATION));
					$eb->id_behavior = $be->ID;
					$eb->save(false);
			
					$vdoc->id_event_behavior = $eb->ID;
					$vdoc->save(false);
				}
				else if($gt->GateType == Gate::GT_T_EXSPEED)
				{
					$eb->setIsNewRecord(true);
					$be = Behavior::model()->findByAttributes(array('tag'=>Behavior::ILLEGAL_SPOT_SPEED));
					$eb->id_behavior = $be->ID;
					$eb->save(false);
						
					$vdoc->id_event_behavior = $eb->ID;
					$vdoc->save(false);
				}
			
			}
		}
		while($count >= 0);
	}
		
	
	public function run($args)
	{
		echo hello;

		var_dump($args);
		
		echo "\n######################################################################";
		echo "\n##                                                                  ##";
		echo "\n##                     EVENTSERVER DB UPDATE                        ##";
		echo "\n##                                                                  ##";
		echo "\n######################################################################";
		echo "\n";
		echo "\n";
		

		echo count($args) ;
		echo array_search('/?', $args) ;
		
		if(count($args) <= 0 || array_search('/?', $args) != FALSE || array_search('-?', $args) != FALSE)
		{
			
			if(count($args) <= 0)
				echo "\n Please specify one or more arguments!";
			
			echo "\n";
			echo "\n -all                               all actions";
			echo "\n -addlists                          add plate list based on type";
			echo "\n -uvpc                              update Validity periods codes";
			echo "\n -uwlc                              update White List codes";
			echo "\n -uwoc                              update vehicles and vehicle owners codes";
			echo "\n -addBehaviors                      add Behaviors";
			echo "\n -setBehaviors                      set behaviors for gates based on gate time";
			echo "\n -dbpa                              delete all bad authorizations";
			echo "\n -seb                               set event behaviors";
			echo "\n -dea                               delete expired autorization";
			echo "\n -agg                               add gate group";
			echo "\n -asr                               add services";
			echo "\n -eim                               export images";
			echo "\n -bid                               update old blobid and types";
				
				
			echo "\n";
			echo "\n";
				
			
			return 0;
		}
	
		echo (array_search('-addBehaviors', $args));
		
		
		$doAll 								=  (array_search('-all', $args) !== false);
		
		$enables['addLists'] 							= $doAll || (array_search('-addlists', $args) 			!==  false);
		$enables['updateWlListCode']	 				= $doAll || (array_search('-uwlc', $args)     			!==  false);
		$enables['updateVPeriodsCode']	 				= $doAll || (array_search('-uvpc', $args)     			!==  false);
		$enables['updateVehcileAndOwnerListCode']	 	= $doAll || (array_search('-uwoc', $args)     			!==  false);
		$enables['addBehaviors']	 					= 			(array_search('-addBehaviors', $args) 		!==  false);
		$enables['setBehaviors']	 					= $doAll || (array_search('-setBehaviors', $args) 		!==  false);
		$enables['delBadAuthorizations']	 			=           (array_search('-dbpa', $args) 				!==  false);
		$enables['setEventBehaviors']	 				= $doAll || (array_search('-seb', $args) 				!==  false);
		$enables['delExpiredAuthorizations']	 		= $doAll || (array_search('-dea', $args) 				!==  false);
		$enables['addGateGroup']	 					= $doAll || (array_search('-agg', $args) 				!==  false);
		$enables['addServices']					 		= $doAll || (array_search('-asr',  $args) 				!==  false);
		$enables['exportImages']					 	= $doAll || (array_search('-eim',  $args) 				!==  false);
		$enables['UpdateBlobIdsAndTypes']				= $doAll || (array_search('-bid',  $args) 				!==  false);

		
		var_dump($enables);
		
		Yii::app()->db->schema->refresh();
		
		
		if($enables['delBadAuthorizations'])
		{
			echo "\n##################################################################";
			echo "\n clean bad plate authorizations";
			echo "\n##################################################################";
			
			self::cleanBadAuthorizationDatas();
			
			echo "\n done";
		}

		if($enables['delExpiredAuthorizations'])
		{
			echo "\n##################################################################";
			echo "\n clean expired plate authorizations and validity periods";
			echo "\n##################################################################";
				
			echo "\n delete expired Plate authorization..";
			Yii::app()->db->createCommand('delete a, w from abbonamentotable a left join whitelisttable w on a.id = w.abbonamentoid where a.DataFine < ((NOW() - INTERVAL 30 DAY))')->execute();
			echo "\n done";
		
				
			echo "\n done";
		}
		
		
		
		if($enables['addLists'])
		{
			// Aggiunta liste per fissi e temporanei da PHP GUI e da import maggioli
			PlateList::model()->deleteAll(array('condition'=>'code >= 10 and code <= 13'));
			
			$pListPhpTemp = new PlateList;
			
			
			$pListPhpTemp->name						= 'Gui Temporanei';
			$pListPhpTemp->source					= 'GUI';
			$pListPhpTemp->code						= 10;
			$pListPhpTemp->auto_import				= false;
			$pListPhpTemp->import_folder			= '';
			$pListPhpTemp->epoch					= new DateTime();
			$pListPhpTemp->editable					= 0;
			$pListPhpTemp->visible					= 1;
			$pListPhpTemp->title					= 'Gui Tmp';
			$pListPhpTemp->mode						= '';
			$pListPhpTemp->last_change				= $pListPhpTemp->epoch; 
			$pListPhpTemp->autoconfirm				= 0;
			$pListPhpTemp->autoconfirm_wait			= 0;
			$pListPhpTemp->mode						= PlateList::MODE_WHITE_LIST;
	
			
			if(!$pListPhpTemp->save())
			{
				echo var_export($pListPhpTemp->getErrors());
			}
			
			
			$pListPhpFissi = new PlateList;
			
			$pListPhpFissi->name					= 'Gui Fissi';
			$pListPhpFissi->source					= 'GUI';
			$pListPhpFissi->code					= 11;
			$pListPhpFissi->auto_import				= false;
			$pListPhpFissi->import_folder			= '';
			$pListPhpFissi->epoch					= new DateTime();
			$pListPhpFissi->editable				= 0;
			$pListPhpFissi->visible					= 1;
			$pListPhpFissi->title					= 'Gui Fissi';
			$pListPhpFissi->mode					= '';
			$pListPhpFissi->last_change				= $pListPhpTemp->epoch;
			$pListPhpFissi->autoconfirm				= 0;
			$pListPhpFissi->autoconfirm_wait		= 0;
			$pListPhpFissi->mode					= PlateList::MODE_WHITE_LIST;
			
			if(!$pListPhpFissi->save())
			{
				echo var_export($pListPhpFissi->getErrors());
			}
	
			$pListImpTemp = new PlateList;		
			
			$pListImpTemp->name						= 'Import';
			$pListImpTemp->source					= 'IMPORT';
			$pListImpTemp->code						= 12;
			$pListImpTemp->auto_import				= false;
			$pListImpTemp->import_folder			= '';
			$pListImpTemp->epoch					= new DateTime();
			$pListImpTemp->editable					= 0;
			$pListImpTemp->visible					= 1;
			$pListImpTemp->title					= 'Import';
			$pListImpTemp->mode						= '';
			$pListImpTemp->last_change				= $pListPhpTemp->epoch;
			$pListImpTemp->autoconfirm				= 0;
			$pListImpTemp->autoconfirm_wait			= 0;
			$pListImpTemp->mode						= PlateList::MODE_WHITE_LIST;		
	
			
			if(!$pListImpTemp->save())
			{
				echo var_export($pListImpTemp->getErrors());
			}
	
		}
		
		
		if($enables['updateVPeriodsCode'])
		{
			echo "\n##################################################################";
			echo "\n Update Validity periods";
			echo "\n##################################################################";
			

			
			ValidityPeriod::model()->updateAll(array('list_code'=>'10'), array('condition'=>"Tipo='tempphp'"));
			ValidityPeriod::model()->updateAll(array('list_code'=>'11'), array('condition'=>"Tipo='fissophp'"));
			ValidityPeriod::model()->updateAll(array('list_code'=>'12'), array('condition'=>"Tipo='Temporaneo'"));
			ValidityPeriod::model()->updateAll(array('list_code'=>'12'), array('condition'=>"Tipo='Fisso'"));
			
			echo "\n Done";
		}
		
		////////////////////////////////////////////////////////////////////////////////////
		
		if($enables['updateWlListCode'])
		{
			echo "\n##################################################################";
			echo "\n Update WhiteList List Codes";
			echo "\n##################################################################";
			
			echo "\n Update WL List codes from PA..";
			Yii::app()->db->createCommand('update  abbonamentotable a left join whitelisttable w on a.id = w.abbonamentoid set w.list_code = a.list_code')->execute();
			echo "\n done";
		}
		
		////////////////////////////////////////////////////////////////////////////////////
		
		if($enables['updateVehcileAndOwnerListCode'])
		{
			
			echo "\n##################################################################";
			echo "\n Update Vehicles and Vehicle Owners List Codes";
			echo "\n##################################################################";
				
			echo "\n Update Vehicles and Vehicle Owner codes from PA..";
			Yii::app()->db->createCommand('update abbonamentotable a left join usertable u on a.UserID = u.id left join vehicletable v on v.userid= u.id  set u.list_code = a.list_code, v.list_code = a.list_code')->execute();
			echo "\n done";
		}

		////////////////////////////////////////////////////////////////////////////////////
		
		if($enables['addBehaviors'])
		{
			echo "\n##################################################################";
			echo "\n Update Behaviors";
			echo "\n##################################################################";
			
			Behavior::model()->deleteAll();
	
			$WlBehavior = new Behavior();
			
			$WlBehavior->name 			 = "white list";
			$WlBehavior->description    = "white list";	
			$WlBehavior->tag 			 = Behavior::WHITELIST_VIOLATION;
			$WlBehavior->confirmable    = 1;
			$WlBehavior->epoch			 = new DateTime();
			$WlBehavior->priority		 = 1;
			$WlBehavior->alarm_tag_name = "white list violation";
			
			$WlBehavior->save();
			
			$RedBehavior = new Behavior();
			
			$RedBehavior->name 			 = "red violation";
			$RedBehavior->description    = "red violation";
			$RedBehavior->tag 			 = Behavior::RED_VIOLATION;
			$RedBehavior->confirmable    = 1;
			$RedBehavior->epoch			 = new DateTime();
			$RedBehavior->priority		 = 1;
			$RedBehavior->alarm_tag_name = "red violation";
			
			$RedBehavior->save();		
			
			
			$SpeedBehavior = new Behavior();
			
			$SpeedBehavior->name 			 = "spot speed";
			$SpeedBehavior->description    = "spot speed";
			$SpeedBehavior->tag 			 = Behavior::ILLEGAL_SPOT_SPEED;
			$SpeedBehavior->confirmable    = 1;
			$SpeedBehavior->epoch			 = new DateTime();
			$SpeedBehavior->priority		 = 1;
			$SpeedBehavior->alarm_tag_name = "spot speed violation";
			
			$SpeedBehavior->save();
			
			echo "\n Done";
			echo "\n";
		}

			////////////////////////////////////////////////////////////////////////////////////
		
		if($enables['setBehaviors'])
		{
			echo "\n##################################################################";
			echo "\n Update Behaviors";
			echo "\n##################################################################";
			
			GateBehavior::model()->deleteAll();
	
			$gates = Gate::model()->findAll();
			
			foreach($gates as $gt)
			{
				echo "\n update for gate ".$gt->Gate."		type=".$gt->GateType;
				$gb = new GateBehavior();
				$gb->validate 					= 1;
				$gb->generate_alarm 			= 2;
				$gb->to_ignore 					= 0;
				$gb->epoch 						= new Datetime();
				$gb->transfer_from_vt 			= 0;
				$gb->transfer_from_event 		= 0;
				$gb->transfer_empty_plates 		= 0;
				$gb->is_whitelist 				= 0;
				$gb->id_gate = 					$gt->Gate;
				
				if($gt->GateType == Gate::GT_T_ID || $gt->GateType == 'T-ID')
				{
					echo "\nT-ID";
					
					$gb->setIsNewRecord(true);
					$gb->id_behavior = Behavior::model()->findByAttributes(array('tag'=>Behavior::WHITELIST_VIOLATION))->ID;
					if(!$gb->save(false))
						echo " - saveError";
				}
				else if($gt->GateType == Gate::GT_T_RED)
				{
					$gb->setIsNewRecord(true);
					$gb->id_behavior = Behavior::model()->findByAttributes(array('tag'=>Behavior::RED_VIOLATION))->ID;
					$gb->save(false);
				}
				else if($gt->GateType == Gate::GT_T_EXSPEED)
				{
					$gb->setIsNewRecord(true);
					$gb->id_behavior = Behavior::model()->findByAttributes(array('tag'=>Behavior::WHITELIST_VIOLATION))->ID;
					$gb->save(false);
					
					$gb->setIsNewRecord(true);
					$gb->id_behavior = Behavior::model()->findByAttributes(array('tag'=>Behavior::RED_VIOLATION))->ID;
					$gb->save(false);
					
					$gb->setIsNewRecord(true);
					$gb->id_behavior = Behavior::model()->findByAttributes(array('tag'=>Behavior::ILLEGAL_SPOT_SPEED))->DI;
					$gb->save(false);					
				}
			}
			
			echo "\n Done";
			echo "\n";
		}
		
		if($enables['setEventBehaviors'])
		{
			echo "\n##################################################################";
			echo "\n Update Event Behaviors";
			echo "\n##################################################################";

			self::updateEventBehaviors();
					
			
			echo "\n done";
		}
		
		////////////////////////////////////////////////////////////////////////////////////
		
		if($enables['addGateGroup'])
		{
			echo "\n##################################################################";
			echo "\n Update Gate Group";
			echo "\n##################################################################";
			
			GateGroup::model()->deleteAll();
			
			$gg = new GateGroup();
			
			$gg->name = "Gates";
			$gg->epoch = new DateTime();
			$gg->save(false);
			
			Gate::model()->updateAll(array('id_group' => $gg->ID));
			
			echo "\n done";
		}
		
		if($enables['addServices'])
		{
			echo "\n##################################################################";
			echo "\n Update Services";
			echo "\n##################################################################";
				
			Service::model()->deleteAll();
			
			$gg = GateGroup::model()->findAll();
			
					
			$fe = Event::model()->first(1)->find();
			
			var_dump($fe);
			
			$startTime = $fe->StartTime;
			
			
			$le = Event::model()->last(1)->find();
			
			$startTime = $fe->StartTime;
			$EndTime = $le->EndTime;
			
			$startDateTime = $startTime;
			$endDateTime = $EndTime;
			
			echo "\n start time =".$startDateTime->format('Y-m-d H:i:s');
			echo "\n end time    =".$endDateTime->format('Y-m-d H:i:s');
			
			$startDateTime->setTime(0,0);


			$endDateTime->setTime(23,59,59);
			


			$startTmpTime = $startDateTime;
			
			while($startTmpTime < $endDateTime)
			{
				
				$sr = new Service();
				
				$endTmpTime = clone $startTmpTime;
				
				echo "\n".$startTmpTime->format('Y-m-d H:i:s');
				
				
				$endTmpTime = $endTmpTime->add(new DateInterval('P10D'));

				echo "\n".$startTmpTime->format('Y-m-d H:i:s');
				
				echo "\n service: ".$startTmpTime->format('Y-m-d H:i:s')." <-> ".$endTmpTime->format('Y-m-d H:i:s');
				

				$sr->origin_type = Service::MANUAL_SERVICE;
				$sr->status = Service::STATUS_TERMINATED;
				$sr->confirmation_required = 0;
				$sr->expected_start_time = $startTmpTime;
				$sr->expected_end_time = $endTmpTime;
				$sr->start_time = $startTmpTime;
				$sr->termination_type = Service::MANUAL_SERVICE;
				$sr->termination_time = $endTmpTime;
				$sr->termination_confirmed_time = $endTmpTime;
				//sleep(3);
				$sr->epoch = $startTmpTime;
				$sr->name = $startTmpTime->format('d-m-Y H:M')."-".$endTmpTime->format('d-m-Y H:M');
				
				
				foreach ($gg as $group)
				{
					$srTmp = clone $sr;
					
					$srTmp->id_gategroup = $group->ID;

					$srTmp->save(false);
					
					
					$gates = $group->gates;
					
					
					foreach ($gates as $gate)
					{
						$condition = "Gate=".$gate->Gate." and  StartTime >='".$startTmpTime->format('Y-m-d H:i:s')."' AND StartTime < '".$endTmpTime->format('Y-m-d H:i:s')."'";
						echo " -- $condition";
				
						Event::model()->updateAll(array('id_run' => $srTmp->ID), "Gate=".$gate->Gate." and  StartTime >='".$startTmpTime->format('Y-m-d H:i:s')."' AND StartTime < '".$endTmpTime->format('Y-m-d H:i:s')."'");
					}

				}
					
			
				Yii::app()->db->createCommand("update run set epoch = expected_start_time")->execute();
					
				$startTmpTime = $endTmpTime;
			}

			echo "\n done";
		}
		
		if($enables['UpdateBlobIdsAndTypes'])
		{
			echo "\n##################################################################";
			echo "\n Update BlobIds And Types";
			echo "\n##################################################################";
				
			echo "\n Update Types and Video.";
			Yii::app()->db->createCommand("update teb_table set type = 'image/jpeg' where type='JPEG' or type=''")->execute();
			Yii::app()->db->createCommand("update teb_table set BlobID = 10000 where BlobId = 4000")->execute();
			Yii::app()->db->createCommand("update teb_table set BlobID = 10001 where BlobId = 3000")->execute();
			echo "\n done";
				
			echo "\n Update BlobIds and Types.";
			Yii::app()->db->createCommand("update teb_table set BlobID = (BlobID + 1000) where BlobId >= 2000 AND BlobId < 3000")->execute();
			echo "\n done";
		
			echo "\n Update BlobIdsSelectes and Types";
			Yii::app()->db->createCommand("update teb_table set BlobIDSelected = (BlobIDSelected + 1000) where BlobIDSelected >= 2000 AND BlobIDSelected < 3000")->execute();
			echo "\n done";
		}		
		
		
		if($enables['exportImages'])
		{
			echo "\n##################################################################";
			echo "\n Export Images";
			echo "\n##################################################################";
		
			self::exportImagesOnFileSystem();
				
			Yii::app()->db->createCommand("optimize table storicotable")->execute();
			Yii::app()->db->createCommand("optimize table teb_table")->execute();
				
			echo "\n done";
		}
		
		return 0;
		
	}
	
}
?>