<?php

class PublishHandler extends Handler{

	function __construct(){
		parent::__construct('PublishHandler');
	}
	
	function getGuideGroup(){
		$selected = $this->DB->SelectAny('SELECT id, name, access_flag, date_locked FROM presetgroup ORDER BY id');
		$array = array();
		foreach($selected as $value){
			$presets_access = $this->DB->SelectAny('SELECT id, name, access_flag, date_locked FROM preset WHERE ownerid = '.$value['id'].' ORDER BY id');
			$ar = array();
			foreach($presets_access as $v)
				$ar[$v['id']] = array('name' => $v['name'], 'access_flag' => $v['access_flag'], 'date_locked' => $v['date_locked'],);
			$array[$value['id']] = array('name' => $value['name'], 'access_flag' => $value['access_flag'], 'date_locked' => $value['date_locked'], 'presets' => $ar);
		}
		return $array;
	}
	
	function getGuide(){
		$selected = $this->DB->SelectGuide(array('preset g'), '*', array());
		return $selected;
	}
	
	function getGuides(){
		$guides['groupslist'] =  $this->getGuideGroup();
		$guides['presetslist'] = $this->getGuide();
		return $guides;
	}
	
	function getUser($request = array()){
		if(is_array($request)){
			if(isset($request['access_flag']) && !empty($request['access_flag'])){
				$selected = $this->DB->SelectAny('SELECT username FROM member WHERE id = '.$request['access_flag']);
				if(empty($selected))
					$request['username'] = '|Unknown User|';
				else
					$request['username'] = $selected[0]['username'];
			}
			foreach($request as $key => $value)
				if(is_array($value))
					$request[$key] = $this->getUser($value);
		}
		return $request;
	}
	
	function makeGroupLocked($request = array()){
		$this->DB->begin();
		$this->DB->update('presetgroup', array('access_flag' => $request['member'], 'date_locked' => 'now'), array('id' => $request['id']));
		$this->setLogEvent(4, 13, 3, 'Lock PreSet Group ['.$request['id'].']',$request['id']);
		$this->DB->commit();
		return $request;
	}
	
	function makeLocked($request = array()){
		$this->DB->begin();
		$this->DB->update('preset', array('access_flag' => $request['member'], 'date_locked' => 'now'), array('id' => $request['id']));
		$this->setLogEvent(4, 5, 3, 'Lock PreSet ['.$request['id'].']',$request['id']);
		$this->DB->commit();
		return $request;
	}
	
	function makeGroupUnLocked($request = array()){
		$this->DB->begin();
		$this->DB->update('presetgroup', array('access_flag' => '0'), array('id' => $request['id']));
		$this->setLogEvent(4, 13, 4, 'UnLock PreSet Group ['.$request['id'].']',$request['id']);
		$this->DB->commit();
		return $request;
	}
	
	function makeUnLocked($request = array()){
		$this->DB->begin();
		$this->DB->update('preset', array('access_flag' => '0'), array('id' => $request['id']));
		$this->setLogEvent(4, 5, 4, 'UnLock PreSet ['.$request['id'].']',$request['id']);
		$this->DB->commit();
		return $request;
	}
	
	function createPreSetGroup(){
		$presetgroup = new PreSetGroup();
		$presetgroup->presets = new ObjectsList();
		$presetgroup->presets->type = new PreSet();
		return $presetgroup;
	}
	
	function createPreSet(){
		$preset = new PreSet();
		return $preset;
	}
	
	function createPackage(){
		$package = new Package();
		$package->items = new ObjectsList();
		$package->items->type = $this->createPackageItem();
		$package->publish = new ObjectsList();
		$package->publish->type = $this->createPackagePublish();
		return $package;
	}
	
	function createPackageItem(){
		$packageitem = new PackageItem();
		return $packageitem;
	}
	
	function createPackagePublish(){
		$packagepublish = new PackagePublish();
		$packagepublish->flush_pathes = new ObjectsList();
		$packagepublish->flush_pathes->type = $this->createPackagePublishFlush();
		$packagepublish->error = new ObjectsList();
		$packagepublish->error->type = $this->createPackagePublishError();
		$packagepublish->report = new ObjectsList();
		$packagepublish->report->type = $this->createPackagePublishReport();
		return $packagepublish;
	}
	
	function createPackagePublishFlush(){
		$packagepublishflush = new PackagePublishFlush();
		return $packagepublishflush;
	}
	
	function createPackagePublishError(){
		$packagepublisherror = new PackagePublishError();
		return $packagepublisherror;
	}
	
	function createPackagePublishReport(){
		$packagepublishreport = new PackagePublishReport();
		return $packagepublishreport;
	}
	
	function selectPreSetGroup($request = array()) {
		if(!isset($request['changed_urls_check'])) $request['changed_urls_check'] = false;
		$selected = $this->getGuideGroup();
		$result = array();
		foreach($selected as $key => $value){
			$presetgroup = $this->createPreSetGroup();
			$presetgroup->id = $key;
			$this->DB->initObject($presetgroup);
			if($request['changed_urls_check'] && $presetgroup->canceled) continue;
			$result[$key] = $presetgroup;
			if($request['changed_urls_check']){
				$count = count($result[$key]->presets->data);
				for ($i = 0; $i < $count; $i++){
					if($result[$key]->presets->data[$i]->canceled){
						unset($result[$key]->presets->data[$i]);
						continue;
					}
					$result[$key]->presets->data[$i]->deleted_objects = $this->DB->SelectAny('SELECT id, uid FROM deleted WHERE type = 3 AND preset = '.$result[$key]->presets->data[$i]->id);
					$result[$key]->presets->data[$i]->changed_urls = $this->DB->SelectAny('SELECT changedurl.id, changedurl.ownerid AS module_id, module.name AS module_name FROM changedurl, module WHERE changedurl.preset = '.$result[$key]->presets->data[$i]->id.' AND module.id = changedurl.ownerid');
				}
			}
			$result[$key]->presets->data = array_values($result[$key]->presets->data);
		}
		return $result;
	}
	
	function openPreSetGroup($request = array('id' => 0)) {
		$presetgroup = $this->createPreSetGroup();
		$presetgroup->id = $request['id'];
		$this->DB->initObject($presetgroup);
		return $presetgroup;
	}
	
	function selectPreSet($request = array()) {
		$selected = $this->DB->SelectGuide(array('preset g'),'*',array());
		return $selected;
	}

	function openPreSet($request = array('id' => 1)) {
		$preset = $this->createPreSet();
		$preset->id = $request['id'];
		$this->DB->initObject($preset);
		$preset->groupslist = $this->getGuideGroup();
		return $preset;
	}
	
	function savePreSetGroup($request = array()) {
		$presetgroup = new PreSetGroup();
		$this->parseRequest($request, $presetgroup);
		$guides = $this->getGuides();
		$same_name_flag = false;
		foreach($guides['groupslist'] as $key => $value)
			if ($presetgroup->name == $value['name'] && $presetgroup->id != $key)
				$same_name_flag = true;
		if($same_name_flag) {
			$this->DB->good = FALSE;
			$presetgroup->_error = 'PreSet Group with such name already exists';
			return $presetgroup;
		}
		if(in_array($presetgroup->name, $guides['presetslist'])) {
			$this->DB->good = FALSE;
			$presetgroup->_error = 'PreSet with such name already exists';
			return $presetgroup;
		}
		if(empty($presetgroup->id)) $this->setLogEvent(4, 13, 11, 'Add prepublishing group of presets "'.$presetgroup->name.'" ['.$presetgroup->id.']', $presetgroup->id);
		else $this->setLogEvent(4, 13, 12, 'Edit prepublishing group of presets "'.$presetgroup->name.'" ['.$presetgroup->id.']', $presetgroup->id);
		$this->DB->processObject($presetgroup);
		$this->DB->commit();
		return $presetgroup;
	}

	function savePreSet($request = array()) {
		$preset = $this->createPreSet();
		$this->parseRequest($request, $preset);
		$guides = $this->getGuides();
		if(!isset($guides['groupslist'][$preset->ownerid])){
			$preset->_error = 'No such PreSet Group';
			$preset->groupslist = $guides['groupslist'];
			return $preset;
		}
		if(in_array($preset->name, $guides['presetslist']) && array_search($preset->name, $guides['presetslist']) != $preset->id) {
			$this->DB->good = FALSE;
			$preset->_error = 'PreSet with such name already exists';
			$preset->groupslist = $guides['groupslist'];
			return $preset;
		}
		$same_name_flag = false;
		foreach($guides['groupslist'] as $key => $value)
			if ($preset->name == $value['name'])
				$same_name_flag = true;
		if($same_name_flag) {
			$this->DB->good = FALSE;
			$preset->_error = 'PreSet Group with such name already exists';
			$preset->groupslist = $guides['groupslist'];
			return $preset;
		}
		if(!empty($preset->id)) $this->setLogEvent(4, 5, 12, 'Edit prepublishing preset "'.$preset->name.'" ['.$preset->id.']', $preset->id);
		else $this->setLogEvent(4, 5, 11, 'Add prepublishing preset "'.$preset->name.'" ['.$preset->id.']', $preset->id);
		$this->DB->processObject($preset);
		$this->DB->commit();
		$preset->groupslist = $guides['groupslist'];
		return $preset;
	}
	
	function deletePreSetGroup($request = array()){
		$presetgroup = $this->createPreSetGroup();
		$this->parseRequest($request, $presetgroup);
		$this->DB->begin();
		$this->DB->initObject($presetgroup);
		$this->DB->processObject($presetgroup, 'delete', array(), array(), true);
		$this->setLogEvent(4, 13, 13, 'Delete prepublishing group of presets "'.$presetgroup->name.'" ['.$presetgroup->id.']',$presetgroup->id);
		$this->DB->commit();
		return $presetgroup;
	}

	function deletePreSet($request = array()) {
		$preset = $this->createPreSet();
		$this->parseRequest($request, $preset);
		$this->DB->begin();
		$this->setLogEvent(4, 5, 13, 'Delete prepublishing preset "'.$preset->name.'" ['.$preset->id.']',$preset->id);
		$this->DB->processObject($preset, 'delete', array(), array(), true);
		$this->DB->commit();
		return $preset;
	}
	
	function selectPackage($request = array()){
		if(!empty($request['all_addable'])){
			$selected = $this->DB->SelectAny('SELECT id, name, comment FROM package WHERE actioned = 0 AND (access_flag = 0 OR access_flag = '.$request['user'].') ORDER BY date_changed DESC');
			return $selected;
		}
		if(empty($request['curPageNumber'])) $request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty'] = 50;
		$selected = $this->DB->SelectAny('SELECT id, name, actioned, uid, access_flag, date_locked, date_changed, engine_version FROM package ORDER BY date_changed DESC LIMIT '.$request['pageRecordsQty'].' OFFSET '.(($request['curPageNumber'] - 1) * $request['pageRecordsQty']));
		$count = count($selected);
		for ($i = 0; $i < $count; $i++){
			$date_locked = explode('.', $selected[$i]['date_locked']);
			$selected[$i]['date_locked'] = $date_locked[0];
			$selected[$i]['username'] = $this->getUserName(array('type' => 1, 'userid' => $selected[$i]['access_flag'],));
			$last_date_published = $this->DB->SelectAny('SELECT max((\'now\'::date - date_published::date)) AS last_date_published FROM packagepublish WHERE ownerid = '.$selected[$i]['id']);
			$selected[$i]['last_date_published'] = empty($last_date_published) ? 0 : $last_date_published[0]['last_date_published'];
			$selected[$i]['publish'] = $this->DB->SelectAny('SELECT id, type, successful, host, date_published, userid, final FROM packagepublish WHERE ownerid = '.$selected[$i]['id'].' ORDER BY date_published DESC');
			$final = false;
			$c = count($selected[$i]['publish']);
			for ($j = 0; $j < $c; $j++){
				if($selected[$i]['publish'][$j]['final'] == 1 && $selected[$i]['publish'][$j]['successful'] == 1) $final = true;
				$date_published = explode('.', $selected[$i]['publish'][$j]['date_published']);
				$selected[$i]['publish'][$j]['date_published'] = $date_published[0];
				$selected[$i]['publish'][$j]['hostpath'] = $this->getHostPath(array('type' => $selected[$i]['publish'][$j]['type'], 'host' => $selected[$i]['publish'][$j]['host'],));
				$selected[$i]['publish'][$j]['username'] = $this->getUserName(array('type' => $selected[$i]['publish'][$j]['type'], 'userid' => $selected[$i]['publish'][$j]['userid'],));
			}
			$selected[$i]['final'] = $final;
		}
		$count = $this->DB->SelectAny('SELECT count(id) AS count FROM package');
		$request['recordsTotal'] = $count[0]['count'];
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = $selected;
		return $request;
	}
	
	function openPackage($request = array()){
		if(empty($request['nopublish'])) $package = $this->createPackage();
		else{
			$package = new Package();
			$package->items = new ObjectsList();
			$package->items->type = $this->createPackageItem();
		}
		$package->id = $request['id'];
		$this->DB->initObject($package); 
		return $package;
	}
	
	function savePackage($request = array()){
		if(!$request['actioned']){
			$package = $this->createPackage();
			$this->parseRequest($request, $package);
			if(!empty($package->id))
				$this->setLogEvent(4, 14, 12, 'Edit publishing package "'.$package->name.'" ['.$package->id.']',$package->id);
			else{
				$this->setLogEvent(4, 14, 11, 'Add publishing package "'.$package->name.'"');
				$package->date_created = 'now';
				$package->uid = str_replace(array('.', ' '), '', microtime());
			}
			$this->DB->commit();
			$package->date_changed = 'now';
			$this->DB->begin();
			$this->DB->processObject($package);
			$this->DB->commit();
		}
		else{
			$packagearray = $request;
			$itemsarray = $packagearray['items'];
			$packagearray['items'] = array();
			$package = $this->createPackage();
			$this->parseRequest($packagearray, $package);
			$package->date_changed = 'now';
			$this->DB->begin();
			$this->DB->processObject($package);
			$this->DB->commit();
			foreach ($itemsarray as $value){
				if (!empty($value['parent'])) continue;
				$oldid = $value['id'];
				$value['id'] = '';
				$value['ownerid'] = $package->id;
				$packageitem = $this->savePackageItem($value);
				foreach ($itemsarray as $val){
					if($val['parent'] != $oldid) continue;
					$val['id'] = '';
					$val['ownerid'] = $package->id;
					$val['parent'] = $packageitem->id;
					$this->savePackageItem($val);
				}
			}
			$package = $this->getPackage(array('id' => $package->id));
		}
		return $package;
	}
	
	function savePackageItem($request = array()){
		$packageitem = $this->createPackageItem();
		$this->parseRequest($request, $packageitem);
		$this->DB->begin();
		$this->DB->processObject($packageitem);
		$this->DB->commit();
		return $packageitem;
	}
	
	function savePackagePublish($request = array()){
		$packagepublish = $this->createPackagePublish();
		$this->parseRequest($request, $packagepublish);
		$this->DB->begin();
		$this->DB->processObject($packagepublish);
		$this->DB->commit();
		$this->DB->initObject($packagepublish);
		$packagepublish->hostpath = $this->getHostPath(array('type' => $packagepublish->type, 'host' => $packagepublish->host));
		$packagepublish->username = $this->getUserName(array('type' => $packagepublish->type, 'userid' => $packagepublish->userid));
		return $packagepublish;
	}
	
	function deletePackage($request = array()){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$package = $this->createPackage();
		$this->parseRequest($request, $package);
		$this->DB->begin();
		$this->DB->initObject($package);
		$package_path = $ROOT_PATH.'/'.$COMMON_VARS['package_dir'].'/'.$package->uid.'.tar.gz';
		$actioned = $package->actioned ? true : false;
		$this->setLogEvent(4, 14, 13, 'Delete publishing package "'.$package->name.'" ['.$package->id.']', $package->id);
		$this->DB->processObject($package, 'delete', array(), array(), true);
		$this->DB->commit();
		if($actioned) mysystem('rm -rf '.$package_path);
		return $package;
	}
	
	function getPackageAccess($request = array()){
		$selected = $this->DB->SelectAny('SELECT id, name, comment, access_flag, actioned, date_locked, date_changed FROM package WHERE id = '.$request['id'].' LIMIT 1');
		if(!empty($selected)){
			$date_locked = explode('.', $selected[0]['date_locked']);
			$selected[0]['date_locked'] = $date_locked[0];
			$date_changed = explode('.', $selected[0]['date_changed']);
			$selected[0]['date_locked'] = $date_changed[0];
			$last_date_published = $this->DB->SelectAny('SELECT max((\'now\'::date - date_published::date)) AS last_date_published FROM packagepublish WHERE ownerid = '.$selected[0]['id']);
			$selected[0]['last_date_published'] = empty($last_date_published) ? 0 : $last_date_published[0]['last_date_published'];
		}
		return $this->getUser($selected[0]);
	}
	
	function makePackageLocked($request = array()){
		$this->setLogEvent(4, 14, 3, 'Lock Package ['.$request['id'].']', $request['id']);
		$this->DB->begin();
		$this->DB->update('package', array('access_flag' => $request['member'], 'date_locked' => 'now',), array('id' => $request['id']));
		$this->DB->commit();
		return $request;
	}
	
	function makePackageUnlocked($request = array()){
		$this->setLogEvent(4, 14, 4, 'Unlock Package ['.$request['id'].']', $request['id']);
		$this->DB->begin();
		$this->DB->update('package', array('access_flag' => '0'), array('id' => $request['id']));
		$this->DB->commit();
		return $request;
	}
	
	function getPublisherHostID($request = array()){
		$selected = $this->DB->SelectAny('SELECT id FROM publisher WHERE host = \''.$request['host'].'\' LIMIT 1');
		if(empty($selected)){
			$this->DB->insert('publisher', array('host' => $request['host']));
			$selected = $this->DB->SelectAny('SELECT id FROM publisher WHERE oid = '.$this->DB->Last_ID);
		}
		return $selected[0]['id'];
	}
	
	function getPublisherUserID($request = array()){
		$selected = $this->DB->SelectAny('SELECT id FROM publisher_user WHERE username = \''.$request['user'].'\' LIMIT 1');
		if(empty($selected)){
			$this->DB->insert('publisher_user', array('username' => $request['user']));
			$selected = $this->DB->SelectAny('SELECT id FROM publisher_user WHERE oid = '.$this->DB->Last_ID);
		}
		return $selected[0]['id'];
	}
	
	function getHostPath($request = array()){
		$selected = $this->DB->SelectAny('SELECT '.($request['type'] == 1 ? 'name' : 'host').' AS hostpath FROM '.($request['type'] == 1 ? 'preset' : 'publisher').' WHERE id = '.$request['host'].' LIMIT 1');
		$hostpath = empty($selected) ? '[undefined]' : $selected[0]['hostpath'];
		return $hostpath;
	}
	
	function getUserName($request = array()){
		$selected = $this->DB->SelectAny('SELECT username FROM '.($request['type'] == 1 ? 'member' : 'publisher_user').' WHERE id = '.$request['userid'].' LIMIT 1');
		$username = empty($selected) ? '[undefined]' : $selected[0]['username'];
		return $username;
	}
	
	function getActionedPackage($request = array()){
		GLOBAL $ROOT_PATH, $COMMON_VARS, $REGISTRY;
		$package = $this->createPackage();
		$package->id = $request['id'];
		$this->DB->initObject($package);
		$pack_eng_v = explode('.', $package->engine_version);
		$eng_v = explode('.', $REGISTRY['Core']['EngineVersion']);
		if($pack_eng_v[0] != $eng_v[0] || $pack_eng_v[1] != $eng_v[1]) $package->_error = 'Package was created by the different engine version';
		$last_date_published = $this->DB->SelectAny('SELECT max((\'now\'::date - date_published::date)) AS last_date_published FROM packagepublish WHERE ownerid = '.$request['id']);
		$package->last_date_published = empty($last_date_published) ? 0 : $last_date_published[0]['last_date_published'];
		$count = count($package->publish->data);
		for($i = 0; $i < $count; $i++){
			$package->publish->data[$i]->hostpath = $this->getHostPath(array('type' => $package->publish->data[$i]->type, 'host' => $package->publish->data[$i]->host));
			$package->publish->data[$i]->username = $this->getUserName(array('type' => $package->publish->data[$i]->type, 'userid' => $package->publish->data[$i]->userid));
		}
		$package_path = $ROOT_PATH.'/'.$COMMON_VARS['package_dir'].'/'.$package->uid.'.tar.gz';
		$ext_package_path = $ROOT_PATH.'/'.$COMMON_VARS['temp_package_dir'].'/'.$package->uid;
		if(!file_exists($package_path)) $package->_error = 'Dumped package archived file "'.$package_path.'" doesn\'t exist';
		else if(!is_readable($package_path)) $package->_error = 'Dumped package archived file "'.$package_path.'" is not readable';
		else{
			$Archive  = new Archive(dirname($package_path).'/', $ROOT_PATH.'/'.$COMMON_VARS['temp_package_dir'].'/', basename($package_path), true);
			$Archive->setTarPath($COMMON_VARS['tar_dir']);
			$Archive->extractArchive();
			if(!empty($Archive->errors)) $package->_error = $Archive->errors[0];
			else if(!file_exists($ext_package_path)) $package->_error = 'Extracted package folder "'.$ext_package_path.'" doesn\'t exist';
			else if(!is_readable($ext_package_path)) $package->_error = 'Extracted package folder "'.$ext_package_path.'" is not readable';
		}
		$types = $this->selectPublishTypes();
		$count = count($package->items->data);
		for ($i = 0; $i < $count; $i++){
			$package->items->data[$i]->objectfields = array(
				'id' => '',
				'name' => '',
				'access_flag' => 0,
				'username' => '',
				'date_locked' => '',
				'date_changed' => '',
				'_error' => '',
				'message' => '',
			);
			switch($package->items->data[$i]->type){
				case 0: case 4: case 8: {
					switch($package->items->data[$i]->type){
						case 0: $filename = $COMMON_VARS['css_file']; $filedir = empty($COMMON_VARS['css_dir']) ? '' : $COMMON_VARS['css_dir'].'/'; break;
						case 4: $filename = $COMMON_VARS['sitemap_file']; $filedir = empty($COMMON_VARS['sitemap_dir']) ? '' : $COMMON_VARS['sitemap_dir'].'/'; break;
						case 8: $filename = $COMMON_VARS['redirects_file']; $filedir = empty($COMMON_VARS['redirects_dir']) ? '' : $COMMON_VARS['redirects_dir'].'/'; break;
					}
					$package->items->data[$i]->objectfields['name'] = $filename;
					$object_path = $ext_package_path.'/'.$filename;
					if(!file_exists($object_path)){
						$package->items->data[$i]->objectfields['_error'] = 'Package error! Doesn\'t exist';
						break;
					}
					$package->items->data[$i]->objectfields['date_changed'] = date("Y-m-d H:i:s", filemtime($object_path));
					if(md5_file($object_path) != md5_file($ROOT_PATH.'/'.$filedir.$filename)) $package->items->data[$i]->objectfields['message'] = 'Has been changed';
					break;
				}
				case 1: case 2: case 3: case 6: case 9: case 10: case 11: case 12: case 13: case 14: case 15: {
					switch($package->items->data[$i]->type){
						case 9: {
							if(!file_exists($ext_package_path.'/RegistryAdd.inc')){
								$package->items->data[$i]->objectfields['_error'] = 'Package error! Doesn\'t exist';
								break 2;
							}
							$currentHomeTarget = $REGISTRY['HomeTarget'];
							include($ext_package_path.'/RegistryAdd.inc');
							if($currentHomeTarget != $REGISTRY['HomeTarget']) $package->items->data[$i]->objectfields['message'] = 'Other page is appointed home page';
							$types[$package->items->data[$i]->type]['name'] = 'module';
							$package->items->data[$i]->object = $REGISTRY['HomeTarget'];
							$REGISTRY['HomeTarget'] = $currentHomeTarget;
							break;
						}
						case 10: case 11: {
							$id = $this->DB->SelectAny('SELECT id FROM module WHERE type = (SELECT id FROM moduletype WHERE name = \''.($package->items->data[$i]->type == 10 ? '404Page' : 'Script Editor').'\' LIMIT 1) LIMIT 1');
							$types[$package->items->data[$i]->type]['name'] = 'module';
							$package->items->data[$i]->object = $id[0]['id'];
							break;
						}
					}
					$package->items->data[$i]->objectfields['id'] = $package->items->data[$i]->object;
					$object_path = $ext_package_path.'/'.$package->items->data[$i]->type.'_'.$package->items->data[$i]->object.'.inc';
					if(!file_exists($object_path)){
						$package->items->data[$i]->objectfields['_error'] = 'Package error! Doesn\'t exist';
						break;
					}
					include($object_path);
					$package->items->data[$i]->objectfields['name'] = $object['name'];
					$package->items->data[$i]->objectfields['uid'] = isset($object['uid']) ? $object['uid'] : '';
					$pack_date_changed = explode('.', $object['date_changed']);
					$package->items->data[$i]->objectfields['date_changed'] = $pack_date_changed[0];
					$selected = $this->DB->SelectAny('SELECT date_changed FROM '.$types[$package->items->data[$i]->type]['name'].' WHERE id = '.$package->items->data[$i]->object);
					if(empty($selected)){
						$package->items->data[$i]->objectfields['message'] = 'Doesn\'t exist anymore';
						break;
					}
					$pack_date_changed = explode(' ', $pack_date_changed[0]);
					$pack_date = explode('-', $pack_date_changed[0]);
					$pack_time = explode(':', $pack_date_changed[1]);
					$curr_date_changed = explode('.', $selected[0]['date_changed']);
					$curr_date_changed = explode(' ', $curr_date_changed[0]);
					$curr_date = explode('-', $curr_date_changed[0]);
					$curr_time = explode(':', $curr_date_changed[1]);
					if(mktime($curr_time[0], $curr_time[1], $curr_time[2], $curr_date[1], $curr_date[2], $curr_date[0]) != mktime($pack_time[0], $pack_time[1], $pack_time[2], $pack_date[1], $pack_date[2], $pack_date[0]))
						$package->items->data[$i]->objectfields['message'] = 'Has been changed';
					break;
				}
				case 5: {
					$package->items->data[$i]->objectfields['name'] = $package->items->data[$i]->object;
					if(!file_exists($ext_package_path.$package->items->data[$i]->object)) $package->items->data[$i]->objectfields['_error'] = 'Package error! Doesn\'t exist';
					else{
						$package->items->data[$i]->objectfields['date_changed'] = date("Y-m-d H:i:s", filemtime($ext_package_path.$package->items->data[$i]->object));
						if(file_exists($ROOT_PATH.$package->items->data[$i]->object)){
							if(is_dir($ext_package_path.$package->items->data[$i]->object)){
								if(!is_dir($ROOT_PATH.$package->items->data[$i]->object)) $package->items->data[$i]->objectfields['message'] = 'Doesn\'t exist anymore';
							}
							else{
								if(is_dir($ROOT_PATH.$package->items->data[$i]->object)) $package->items->data[$i]->objectfields['message'] = 'Doesn\'t exist anymore';
								else if(md5_file($ext_package_path.$package->items->data[$i]->object) != md5_file($ROOT_PATH.$package->items->data[$i]->object)) $package->items->data[$i]->objectfields['message'] = 'Has been changed';
							}
						}
						else $package->items->data[$i]->objectfields['message'] = 'Doesn\'t exist anymore';
					}
					break;
				}
			}
		}
		mysystem('rm -rf '.$ext_package_path);
		return $package;
	}
	
	function getPackage($request = array()){
		GLOBAL $REGISTRY;//echo 'Begin time: '.date("H:i:s", time()).'<br>';
		if(empty($request['requested'])){
			$package = $this->createPackage();
			$package->id = $request['id'];
			$this->DB->initObject($package);
		}
		else{
			$package = $this->createPackage();
			$this->parseRequest($request['requested'], $package);
		}
		$package->last_date_published = 0;
		foreach($package->publish->data as $key => $value){
			$package->publish->data[$key]->hostpath = $this->getHostPath(array('type' => $value->type, 'host' => $value->host));
			$package->publish->data[$key]->username = $this->getUserName(array('type' => $value->type, 'userid' => $value->userid));
		}
		if(@$request['action'] == 'Duplicate'){
			$count = count($package->items->data);
			for ($i = 0; $i < $count; $i++)
				if(!empty($package->items->data[$i]->parent))
					unset($package->items->data[$i]);
			$package->items->data = array_values($package->items->data);
			$package->actioned = 0;
		}
		$count = count($package->items->data);
		for ($i = 0; $i < $count; $i++){
			switch($package->items->data[$i]->type){
				case 0: $this->getCSSIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 1: $this->getLayoutIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 2: $this->getMenuIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 3: $this->getPageIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 4: $this->getSitemapIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 5: $this->getFFIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 6: $this->getTemplateIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 8: $this->getRedirectsIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 9:
					$temp = $package->items->data[$i]->object;
					$package->items->data[$i]->object = $REGISTRY['HomeTarget'];
					$this->getPageIncludes(&$package, $i, $package->items->data[$i]->id);
					$package->items->data[$i]->object = $temp;
					break;
				case 10:
					$temp = $package->items->data[$i]->object;
					$id = $this->DB->SelectAny('SELECT id FROM module WHERE type = (SELECT id FROM moduletype WHERE name = \'404Page\' LIMIT 1) LIMIT 1');
					$package->items->data[$i]->object = $id[0]['id'];
					$this->getPageIncludes(&$package, $i, $package->items->data[$i]->id);
					$package->items->data[$i]->object = $temp;
					break;
				case 11:
					$temp = $package->items->data[$i]->object;
					$id = $this->DB->SelectAny('SELECT id FROM module WHERE type = (SELECT id FROM moduletype WHERE name = \'Script Editor\' LIMIT 1) LIMIT 1');
					$package->items->data[$i]->object = $id[0]['id'];
					$this->getPageIncludes(&$package, $i, $package->items->data[$i]->id);
					$package->items->data[$i]->object = $temp;
					break;
				case 12: $this->getSubdomainIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 13: $this->getImportedFeedIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 14: $this->getCityIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 15: $this->getFeedIncludes(&$package, $i, $package->items->data[$i]->id); break;
				case 16: $this->getCategoryIncludes(&$package, $i, $package->items->data[$i]->id); break;
			}
		}//echo 'End time: '.date("H:i:s", time()).'<br>';
		return $package;
	}
	
	function getPageIncludes(&$package, $number, $parent){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$handler = new ContentHandler();
		$page = $handler->openSection(array('id' => $package->items->data[$number]->object,));
		$user = $this->getUser(array('access_flag' => $page->access_flag));
		$date_locked = explode('.', $page->date_locked);
		$page->date_changed = explode('.', $page->date_changed);
		$package->items->data[$number]->objectfields = array(
			'id' => $page->id,
			'name' => $page->name,
			'access_flag' => $page->access_flag,
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $page->date_changed[0],
			'_error' => ($page->name === NULL ? 'Page doesn\'t exist' : ''),
		);
		if($package->actioned) return;
		if ($page->is_describe){
			$newitemarray = array('ownerid' => $package->id, 'type' => 1, 'object' => $page->layout->id, 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getLayoutIncludes($package, key($package->items->data), $parent);
		}
		$selected = $this->DB->SelectAny('SELECT DISTINCT template FROM moduletemplate WHERE ownerid = '.$page->id);
		foreach ($selected as $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 6, 'object' => $value['template'], 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getTemplateIncludes($package, key($package->items->data), $parent);
		}
		$selected = $this->DB->SelectAny('SELECT DISTINCT importedfeed FROM moduleimportedfeed WHERE ownerid = '.$page->id);
		foreach ($selected as $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 13, 'object' => $value['importedfeed'], 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getImportedFeedIncludes($package, key($package->items->data), $parent);
		}
		$selected = $this->DB->SelectAny('SELECT DISTINCT feed FROM modulefeed WHERE ownerid = '.$page->id);
		foreach ($selected as $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 15, 'object' => $value['feed'], 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getFeedIncludes($package, key($package->items->data), $parent);
		}
		$selected = $this->DB->SelectAny('SELECT DISTINCT menu FROM modulemenulineitem WHERE ownerid = '.$page->id);
		foreach ($selected as $key => $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 2, 'object' => $value['menu'], 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getMenuIncludes(&$package, key($package->items->data), $parent);
		}
		$files = array();
		$count = count($page->modulejszones->data);
		for($i = 0; $i < $count; $i++) $files = array_merge($files, $this->GetIncludedFiles($page->modulejszones->data[$i]->value, $COMMON_VARS['file_includes_condition']));
		$count = count($page->contents->data);
		for($i = 0; $i < $count; $i++) $files = array_merge($files, $this->GetIncludedFiles($page->contents->data[$i]->value, $COMMON_VARS['file_includes_condition']));
		$files = array_unique($files);
		foreach($files as $key => $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 5, 'object' => $value, 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getFFIncludes(&$package, key($package->items->data), $parent);
		}
		if(!empty($page->parent->id)){
			$newitemarray = array('ownerid' => $package->id, 'type' => 3, 'object' => $page->parent->id, 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getPageIncludes(&$package, key($package->items->data), $parent);
		}
	}

	function getCategoryIncludes(&$package, $number, $parent){
		GLOBAL $CORE_PATH, $COMMON_VARS;
		$handler = $this->Server->getHandler(22);
		$category = $handler->openCategory(array('id' => $package->items->data[$number]->object));
		$user = $this->getUser(array('access_flag' => $category->access_flag));
		$date_locked = explode('.', $category->date_locked);
		$date_changed = explode('.', $category->date_changed);
		$package->items->data[$number]->objectfields = array(
			'id' => $category->id,
			'name' => $category->name,
			'access_flag' => $category->access_flag,
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $date_changed[0],
			'_error' => ($category->name === NULL ? 'Layout doesn\'t exist' : ''),
		);
		if($package->actioned) return;
	}
	
	function getLayoutIncludes(&$package, $number, $parent){
		GLOBAL $CORE_PATH, $COMMON_VARS;
		$handler = new LayoutHandler();
		$layout = $handler->openLayout(array('id' => $package->items->data[$number]->object));
		$user = $this->getUser(array('access_flag' => $layout->access_flag));
		$date_locked = explode('.', $layout->date_locked);
		$date_changed = explode('.', $layout->date_changed);
		$package->items->data[$number]->objectfields = array(
			'id' => $layout->id,
			'name' => $layout->name,
			'access_flag' => $layout->access_flag,
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $date_changed[0],
			'_error' => ($layout->name === NULL ? 'Layout doesn\'t exist' : ''),
		);
		if($package->actioned) return;
		$files = $this->GetIncludedFiles($layout->value, $COMMON_VARS['file_includes_condition']);
		$files = array_unique($files);
		foreach ($files as $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 5, 'object' => $value, 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getFFIncludes(&$package, key($package->items->data), $parent);
		}
	}
	
	function getTemplateIncludes(&$package, $number, $parent){
		GLOBAL $COMMON_VARS;
		$handler = new TemplateHandler();
		$template = $handler->openTemplate(array('id' => $package->items->data[$number]->object));
		$user = $this->getUser(array('access_flag' => $template->access_flag));
		$date_locked = explode('.', $template->date_locked);
		$date_changed = explode('.', $template->date_changed);
		$package->items->data[$number]->objectfields = array(
			'id' => $template->id,
			'name' => $template->name,
			'access_flag' => $template->access_flag,
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $date_changed[0],
			'_error' => ($template->name === NULL ? 'Template doesn\'t exist' : ''),
		);
		if($package->actioned) return;
		$files = array();
		foreach ($template->items->data as $value)
			$files = array_merge($files, $this->GetIncludedFiles($value->value, $COMMON_VARS['file_includes_condition']));
		$files = array_unique($files);
		foreach ($files as $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 5, 'object' => $value, 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getFFIncludes(&$package, key($package->items->data), $parent);
		}
	}
	
	function getFFIncludes(&$package, $number, $parent){
		GLOBAL $ROOT_PATH, $TOOLS_PATH, $COMMON_VARS;
		$ffpath = $package->items->data[$number]->object;
		include_once($TOOLS_PATH.'/File.functions.inc');
		$package->items->data[$number]->objectfields = array(
			'id' => '',
			'name' => $ffpath,
			'access_flag' => 0,
			'username' => '',
			'date_locked' => '',
			'date_changed' => '',
			'_error' => '',
		);
		if($package->actioned) return;
		if(!file_exists($ROOT_PATH.$ffpath)){
			$package->items->data[$number]->objectfields['_error'] = 'Doesn\'t exist';
			return;
		}
		$package->items->data[$number]->objectfields['date_changed'] = date("Y-m-d H:i:s", filemtime($ROOT_PATH.$ffpath));
		if(!is_writable($ROOT_PATH.$ffpath)){
			$package->items->data[$number]->objectfields['_error'] = 'Permission denied';
			return;
		}
		foreach ($COMMON_VARS['publish_path_denied'] as $value)
			if($ROOT_PATH.$ffpath == $ROOT_PATH.'/'.$value){
				$package->items->data[$number]->objectfields['_error'] = 'Access denied';
				return;
			}
		if(is_dir($ROOT_PATH.$ffpath)){
			foreach ($COMMON_VARS['publish_path_denied'] as $value)
				if($ROOT_PATH.$ffpath == $ROOT_PATH.'/'.$value){
					return;
			}
			$result = array();
			getPathesArray($result, $ROOT_PATH.$ffpath, false, false, false, $COMMON_VARS['publish_file_types']);
			foreach($result as $key => $value)
				$result[$key] = substr($value, strlen($ROOT_PATH));
			natsort($result);
			foreach ($result as $value){
				$newitemarray = array('ownerid' => $package->id, 'type' => 5, 'object' => $value, 'parent' => $parent);
				$newitem = $this->createPackageItem();
				$this->parseRequest($newitemarray, $newitem);
				$package->items->data[] = $newitem;
				end($package->items->data);
				$this->getFFIncludes(&$package, key($package->items->data), $parent);
			}
		}
	}
	
	function getCSSIncludes(&$package, $number, $parent){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$csspath = '/'.$COMMON_VARS['css_dir'].(empty($COMMON_VARS['css_dir']) ? '' : '/').$COMMON_VARS['css_file'];
		$package->items->data[$number]->objectfields = array(
			'id' => '',
			'name' => $COMMON_VARS['css_file'],
			'access_flag' => 0,
			'username' => '',
			'date_locked' => '',
			'date_changed' => '',
			'_error' => '',
		);
		if($package->actioned) return;
		if(!file_exists($ROOT_PATH.$csspath)){
			$package->items->data[$number]->objectfields['_error'] = 'Doesn\'t exist';
			return;
		}
		$package->items->data[$number]->objectfields['date_changed'] = date("Y-m-d H:i:s", filemtime($ROOT_PATH.$csspath));
		if(!is_writable($ROOT_PATH.$csspath)){
			$package->items->data[$number]->objectfields['_error'] = 'Permission denied';
			return;
		}
		$files = array();
		$files = $this->GetIncludedFiles(@file_get_contents($ROOT_PATH.$csspath), $COMMON_VARS['file_includes_condition']);
		$files = array_unique($files);
		foreach($files as $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 5, 'object' => $value, 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getFFIncludes(&$package, key($package->items->data), $newitem, $parent);
		}
	}
	
	function getMenuIncludes(&$package, $number, $parent){
		$menu = $this->DB->SelectAny('SELECT * FROM menu WHERE id = '.$package->items->data[$number]->object);
		if(empty($menu))
			$menu = array(
				'id' => $package->items->data[$number]->object,
				'name' => NULL,
				'access_flag' => '0',
				'date_locked' => '',
				'date_changed' => '',
			);
		else
			$menu = $menu[0];
		$user = $this->getUser(array('access_flag' => $menu['access_flag']));
		$date_locked = explode('.', $menu['date_locked']);
		$date_changed = explode('.', $menu['date_changed']);
		$package->items->data[$number]->objectfields = array(
			'id' => $menu['id'],
			'name' => $menu['name'],
			'access_flag' => $menu['access_flag'],
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $date_changed[0],
			'_error' => ($menu['name'] === NULL ? 'Menu doesn\'t exist' : ''),
		);
	}
	
	function getRedirectsIncludes(&$package, $number, $parent){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$redirectspath = '/'.$COMMON_VARS['redirects_dir'].(empty($COMMON_VARS['redirects_dir']) ? '' : '/').$COMMON_VARS['redirects_file'];
		$package->items->data[$number]->objectfields = array(
			'id' => '',
			'name' => $redirectspath,
			'access_flag' => 0,
			'username' => '',
			'date_locked' => '',
			'date_changed' => '',
			'_error' => '',
		);
		if(!file_exists($ROOT_PATH.$redirectspath)){
			$package->items->data[$number]->objectfields['_error'] = 'Doesn\'t exist';
			return;
		}
		$package->items->data[$number]->objectfields['date_changed'] = date("Y-m-d H:i:s", filemtime($ROOT_PATH.$redirectspath));
		if(!is_writable($ROOT_PATH.$redirectspath))
			$package->items->data[$number]->objectfields['_error'] = 'Permission denied';
	}
	
	function getSitemapIncludes(&$package, $number, $parent){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$sitemappath = '/'.$COMMON_VARS['sitemap_dir'].(empty($COMMON_VARS['sitemap_dir']) ? '' : '/').$COMMON_VARS['sitemap_file'];
		$package->items->data[$number]->objectfields = array(
			'id' => '',
			'name' => $sitemappath,
			'access_flag' => 0,
			'username' => '',
			'date_locked' => '',
			'date_changed' => '',
			'_error' => '',
		);
		if(!file_exists($ROOT_PATH.$sitemappath)){
			$package->items->data[$number]->objectfields['_error'] = 'Doesn\'t exist';
			return;
		}
		$package->items->data[$number]->objectfields['date_changed'] = date("Y-m-d H:i:s", filemtime($ROOT_PATH.$sitemappath));
		if(!is_writable($ROOT_PATH.$sitemappath)) $package->items->data[$number]->objectfields['_error'] = 'Permission denied';
	}
	
	function getSubdomainIncludes (&$package, $number, $parent) {
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$handler = new SubdomainHandler();
		$subdomain = $handler->openSubdomain(array('id' => $package->items->data[$number]->object,));
		$user = $this->getUser(array('access_flag' => $subdomain->access_flag));
		$date_locked = explode('.', $subdomain->date_locked);
		$subdomain->date_changed = explode('.', $subdomain->date_changed);
		$package->items->data[$number]->objectfields = array(
			'id' => $subdomain->id,
			'name' => $subdomain->name,
			'access_flag' => $subdomain->access_flag,
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $subdomain->date_changed[0],
			'_error' => ($subdomain->name === NULL ? 'Subdomain doesn\'t exist' : ''),
		);
		if($package->actioned) return;
		$selected = $this->DB->SelectAny('SELECT id FROM module WHERE type = 8 LIMIT 1');
		$page = $this->DB->SelectAny('SELECT id FROM module WHERE parent = '.$selected[0]['id'].' AND lower(path) = \''.strtolower($subdomain->domain).'\' LIMIT 1');
		if(!empty($page[0]['id'])){
			$newitemarray = array('ownerid' => $package->id, 'type' => 3, 'object' => $page[0]['id'], 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getPageIncludes(&$package, key($package->items->data), $parent);
		}
	}
	
	function getImportedFeedIncludes (&$package, $number, $parent) {
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$handler = new FeedHandler();
		$importedfeed = $handler->openImportedFeed(array('id' => $package->items->data[$number]->object,));
		$user = $this->getUser(array('access_flag' => $importedfeed->access_flag));
		$date_locked = explode('.', $importedfeed->date_locked);
		$importedfeed->date_changed = explode('.', $importedfeed->date_changed);
		$package->items->data[$number]->objectfields = array(
			'id' => $importedfeed->id,
			'name' => $importedfeed->name,
			'access_flag' => $importedfeed->access_flag,
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $importedfeed->date_changed[0],
			'_error' => ($importedfeed->name === NULL ? 'Imported Feed doesn\'t exist' : ''),
		);
	}
	
	function getCityIncludes(&$package, $number, $parent) {
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$handler = new CitiesHandler();
		$city = $handler->openCity(array('id' => $package->items->data[$number]->object,));
		$user = $this->getUser(array('access_flag' => $city->access_flag));
		$date_locked = explode('.', $city->date_locked);
		$city->date_changed = explode('.', $city->date_changed);
		$package->items->data[$number]->objectfields = array(
			'id' => $city->id,
			'name' => $city->name,
			'access_flag' => $city->access_flag,
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $city->date_changed[0],
			'_error' => ($city->name === NULL ? 'City doesn\'t exist' : ''),
		);
		if($package->actioned) return;
		$files = $this->GetIncludedFiles($city->description, $COMMON_VARS['file_includes_condition']);
		$files = array_unique($files);
		foreach ($files as $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 5, 'object' => $value, 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getFFIncludes(&$package, key($package->items->data), $parent);
		}
	}
	
	function getFeedIncludes (&$package, $number, $parent) {
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$handler = new FeedHandler();
		$feed = $handler->openFeed(array('id' => $package->items->data[$number]->object,));
		$user = $this->getUser(array('access_flag' => $feed->access_flag));
		$date_locked = explode('.', $feed->date_locked);
		$feed->date_changed = explode('.', $feed->date_changed);
		$package->items->data[$number]->objectfields = array(
			'id' => $feed->id,
			'name' => $feed->name,
			'access_flag' => $feed->access_flag,
			'username' => empty($user['username']) ? '' : $user['username'],
			'date_locked' => $date_locked[0],
			'date_changed' => $feed->date_changed[0],
			'_error' => ($feed->name === NULL ? 'Feed doesn\'t exist' : ''),
		);
		if($package->actioned) return;
		$files = array();
		foreach ($feed->items->data as $value) $files = array_merge($files, $this->GetIncludedFiles($value->description, $COMMON_VARS['file_includes_condition']));
		$files = array_unique($files);
		foreach ($files as $value){
			$newitemarray = array('ownerid' => $package->id, 'type' => 5, 'object' => $value, 'parent' => $parent);
			$newitem = $this->createPackageItem();
			$this->parseRequest($newitemarray, $newitem);
			$package->items->data[] = $newitem;
			end($package->items->data);
			$this->getFFIncludes(&$package, key($package->items->data), $parent);
		}
	}
	
	function GetIncludedFiles($text, $condition){
		global $REGISTRY;
		$files = array();
		$text = preg_replace("~'~", "\"", $text);
		$text = preg_replace("~&#39;~", "\"", $text);
		$text = preg_replace("~&quot;~", "\"", $text);
		$text = preg_replace("/%20/", " ", $text);
		$text = preg_replace("/<!--.*?-->/s", " ", $text);
		foreach($REGISTRY['Globals']['static'] as $key => $value)
			if(!is_array($value)) $text = str_replace('{'.$key.':static}', $value, $text);
		foreach($condition as $key => $value){
			$content = explode($key, $text);
			$content_c = count($content);
			for($i = 0; $i < $content_c; $i++){
				foreach ($value as $ind => $val){
					if(preg_match_all($ind, $content[$i], $matches)){//echo $ind.'<br>';echo 'MATCHES<br>';printArray($matches[0]);
						foreach($matches[0] as $v){
							if(!preg_match('/:\/\//', $v) && preg_match('/[[:alpha:][:alnum:]._-]*(\/[[:alpha:][:alnum:]._-]+)+\.[[:alpha:]]{2,4}/', $v, $path)){//echo 'PATH<br>';printArray($path);
								$path = $path[0];
								if(substr($path, 0, 1) != '/') $path = '/'.$path;
								if (empty($val)) $files[] = $path;
								else{
									$extension = explode('.', $path);
									if(in_array(strtolower($extension[count($extension) - 1]), $val))
										$files[] = $path;
								}
							}
						}
					}
				}
			}
		}
		//echo '<br><hr>';
		//preg_match_all('/(\/[[:alpha:][:alnum:]_]+)+\.[[:alpha:]]{2,4}/', $text, $array);
		//echo 'Files<br>'; printArray($files);
		//echo 'Matches<br>'; printArray($array);
		return $files;
	}
	
	function searchPackages($request = array()){
		$result = array();
		$packages = array();
		$query = 'SELECT id, name FROM package';
		$conditions = array();
		if(!empty($request['not_older'])) $conditions[] = 'date_created > \''.date("Y-m-d", time() - $request['not_older']).'\'';
		if(!empty($request['published'])) $conditions[] = 'id IN (SELECT ownerid FROM packagepublish WHERE type = 1 AND date_published > \''.date("Y-m-d", time() - $request['published']).'\')';
		if(!empty($request['inpublished'])) $conditions[] = 'id IN (SELECT ownerid FROM packagepublish WHERE type = 2 AND date_published > \''.date("Y-m-d", time() - $request['inpublished']).'\')';
		if(!empty($conditions)) $query .= ' WHERE '.implode(' AND ', $conditions);
		$query .= ' ORDER BY id DESC';
		$packages = $this->DB->SelectAny($query);
		if(empty($request['contained'])) return $packages;
		else{
			$conditions = array();
			foreach($request['contained'] as $type => $objects){
				$count = count($objects);
				for($i = 0; $i < $count; $i++) $conditions[] = 'type = '.$type.' AND object = \''.$request['contained'][$type][$i].'\'';
			}
			$count = count($packages);
			for($i = 0; $i < $count; $i++){
				$contain = true;
				$cond_count = count($conditions);
				for ($j = 0; $j < $cond_count; $j++){
					$selected = $this->DB->SelectAny('SELECT id FROM packageitem WHERE ownerid = '.$packages[$i]['id'].' AND '.$conditions[$j]);
					if(empty($selected)){
						$contain = false;
						break;
					}
				}
				if($contain) $result[] = $packages[$i];
			}
		}
		return $result;
	}
	
	function getFlushPathes($request = array(), $ToolsHandler = ''){
		GLOBAL $REGISTRY, $ROOT_PATH, $COMMON_VARS;
		$prepath = 'http://'.strtolower($REGISTRY['Core']['SiteName']);
		$result = array();
		$included = array(1 => array(), 2 => array(), 3 => array(), 5 => array(), 6 => array(),);
		$count = count($request);
		for ($i = 0; $i < $count; $i++)
			switch($request[$i]['type']){
				case '0': {
					$path = $prepath.'/'.$COMMON_VARS['css_dir'].(empty($COMMON_VARS['css_dir']) ? '' : '/').$COMMON_VARS['css_file'];
					if(!in_array($path, $result)) $result[] = $path;
					break;
				}
				case '1': {
					if(isset($included[1][$request[$i]['object']])) break;
					$included[1][$request[$i]['object']] = true;
					$selected = $this->DB->SelectAny('SELECT id FROM module WHERE layout = '.$request[$i]['object']);
					$c = count($selected);
					for($j = 0; $j < $c; $j++){
						if(isset($included[3][$selected[$j]['id']])) continue;
						$included[3][$selected[$j]['id']] = true;
						if(($pagepath = $this->getPagePath($selected[$j]['id'])) !== false) $result[] = $pagepath;
					}
					break;
				}
				case '2': {
					if(isset($included[2][$request[$i]['object']])) break;
					$included[2][$request[$i]['object']] = true;
					$selected = $this->DB->SelectAny('SELECT ownerid AS id FROM modulemenulineitem WHERE menu = '.$request[$i]['object']);
					$c = count($selected);
					for($j = 0; $j < $c; $j++){
						if(isset($included[3][$selected[$j]['id']])) continue;
						$included[3][$selected[$j]['id']] = true;
						if(($pagepath = $this->getPagePath($selected[$j]['id'])) !== false) $result[] = $pagepath;
					}
					break;
				}
				case '3': {
					if(isset($included[3][$request[$i]['object']])) break;
					$included[3][$request[$i]['object']] = true;
					$selected = $this->DB->SelectAny('SELECT is_describe, default_page FROM module WHERE id = '.$request[$i]['object'].' LIMIT 1');
					if(empty($selected) || (empty($selected[0]['is_describe']) && empty($selected[0]['default_page']))) continue;
					if(($pagepath = $this->getPagePath($request[$i]['object'])) !== false) $result[] = $pagepath;
					break;
				}
				case '4': {
					$path = $prepath.'/'.$COMMON_VARS['sitemap_dir'].(empty($COMMON_VARS['sitemap_dir']) ? '' : '/').$COMMON_VARS['sitemap_file'];
					if(!in_array($path, $result)) $result[] = $path;
					break;
				}
				case '5': {
					if(isset($included[5][$request[$i]['object']])) break;
					$included[5][$request[$i]['object']] = true;
					if(!file_exists($ROOT_PATH.$request[$i]['object']) || is_dir($ROOT_PATH.$request[$i]['object']) || preg_match("/sitemap\.xml\.gz$/i", $request[$i]['object']) || preg_match("/.+\/robots\.txt$/i", $request[$i]['object'])) break;
					$result[] = $prepath.$request[$i]['object'];
					// No subdomains flush
					//if(($subdomain_prepath = $this->getFileSubdomainsPrePath($request[$i]['object'])) !== false) $result[] = $subdomain_prepath.$request[$i]['object'];
					break;
				}
				case '6': {
					if(isset($included[6][$request[$i]['object']])) break;
					$included[6][$request[$i]['object']] = true;
					$templateitems_count = $this->DB->SelectAny('SELECT count(id) AS count FROM templateitem WHERE ownerid = '.$request[$i]['object']);
					if(empty($templateitems_count) || empty($templateitems_count[0]['count'])) break;
					if ($templateitems_count[0]['count'] == 1){
						$selected = $this->DB->SelectAny('SELECT DISTINCT ownerid AS id FROM moduletemplate WHERE template = '.$request[$i]['object']);
						$c = count($selected);
						for($j = 0; $j < $c; $j++){
							if(isset($included[3][$selected[$j]['id']])) continue;
							$included[3][$selected[$j]['id']] = true;
							if(($pagepath = $this->getPagePath($selected[$j]['id'])) !== false) $result[] = $pagepath;
						}
					}
					else {
						$selected = $this->DB->SelectAny('SELECT uid FROM templateitem WHERE ownerid = '.$request[$i]['object']);
						// No subdomains flush
						//$subdomain_prepaths = $this->getTemplateSubdomainsPrePaths($request[$i]['object']);
						//$subd_count = count($subdomain_prepaths);
						$c = count($selected);
						for($j = 0; $j < $c; $j++) {
							$result[] = $prepath.'/TemplateItem/'.$selected[$j]['uid'];
							//for ($k = 0 ; $k < $subd_count; $k++) $result[] = $subdomain_prepaths[$k].'/TemplateItem/'.$selected[$j]['uid'];
						}
					}
					break;
				}
				case '8': {
					if(!is_object($ToolsHandler)) $ToolsHandler = new ToolsHandler();
					$redirects = $ToolsHandler->getRedirects();
					$c = count($redirects['from']);
					for($j = 0; $j < $c; $j++){
						$path = $prepath.'/'.$redirects['from'][$j];
						if(!in_array($path, $result)) $result[] = $path;
					}
					break;
				}
				case '9': {
					if(!in_array($prepath, $result)) $result[] = $prepath.'/';
					if(isset($included[3][$request[$i]['objectfields']['id']])) break;
					$included[3][$request[$i]['objectfields']['id']] = true;
					if(($pagepath = $this->getPagePath($request[$i]['objectfields']['id'])) !== false) $result[] = $prepath.$pagepath;
					break;
				}
				case '13': {
					if(isset($included[13][$request[$i]['object']])) break;
					$included[13][$request[$i]['object']] = true;
					$selected = $this->DB->SelectAny('SELECT link FROM importedfeed WHERE id = '.$request[$i]['object']);
					if(!empty($selected)) $result[] = $prepath.'/'.$selected[0]['link'];
					$selected = $this->DB->SelectAny('SELECT DISTINCT ownerid AS id FROM moduleimportedfeed WHERE importedfeed = '.$request[$i]['object']);
					$c = count($selected);
					for($j = 0; $j < $c; $j++){
						if(isset($included[3][$selected[$j]['id']])) continue;
						$included[3][$selected[$j]['id']] = true;
						if(($pagepath = $this->getPagePath($selected[$j]['id'])) !== false) $result[] = $pagepath;
					}
					break;
				}
				case '14': {
					if(isset($included[14][$request[$i]['object']])) break;
					$included[14][$request[$i]['object']] = true;
					$selected = $this->DB->SelectAny('SELECT name_in_url FROM city WHERE id = '.$request[$i]['object'].' LIMIT 1');
					if(!empty($selected)) $result[] = $prepath.'/'.$COMMON_VARS['cities_path'].'/'.$selected[0]['name_in_url'];
					break;
				}
				case '15': {
					if(isset($included[15][$request[$i]['object']])) break;
					$included[15][$request[$i]['object']] = true;
					$selected = $this->DB->SelectAny('SELECT link FROM feed WHERE id = '.$request[$i]['object']);
					if(!empty($selected)) $result[] = $prepath.'/'.$selected[0]['link'];
					$selected = $this->DB->SelectAny('SELECT DISTINCT ownerid AS id FROM modulefeed WHERE feed = '.$request[$i]['object']);
					$c = count($selected);
					for($j = 0; $j < $c; $j++){
						if(isset($included[3][$selected[$j]['id']])) continue;
						$included[3][$selected[$j]['id']] = true;
						if(($pagepath = $this->getPagePath($selected[$j]['id'])) !== false) $result[] = $pagepath;
					}
					break;
				}
			}
		return $result;
	}
	
	function getPagePath($id){
		GLOBAL $signature, $REGISTRY;
		$selected = $this->DB->SelectAny('SELECT path, parent FROM module WHERE id = '.$id.' LIMIT 1');
		if(empty($selected)) return false;
		$path = '/'.$selected[0]['path'];
		$parent[0] = $selected[0]['parent'];
		while(end($parent)){
			$selected = $this->DB->SelectAny('SELECT path, parent FROM module WHERE id = '.end($parent).' LIMIT 1');
			if(empty($selected)) break;
			$path = '/'.$selected[0]['path'].$path;
			$parent[] = $selected[0]['parent'];
		}
		$count = count($parent);
		if($count > 1 && $parent[$count - 2] == 60){
			// no subdomains flush
			return false;
			$exploded = explode('/', $path);
			$selected = $this->DB->SelectAny('SELECT domain FROM subdomain WHERE lower(domain) = \''.strtolower($exploded[2]).'\' LIMIT 1');
			if(empty($selected)) return false;
			$prepath = 'http://'.$selected[0]['domain'].'.'.$signature['domain'][0];
			unset($exploded[0], $exploded[1], $exploded[2]);
			$path = '/'.implode('/', $exploded);
		}
		else $prepath = 'http://'.strtolower($REGISTRY['Core']['SiteName']);
		$path = $prepath.$path;
		return $path;
	}
	
	function getTemplateSubdomainsPrePaths($id) {
		GLOBAL $signature;
		$result = array();
		$selected = $this->DB->SelectAny('SELECT DISTINCT ownerid FROM moduletemplate WHERE template = '.$id);
		$count = count($selected);
		for ($i = 0; $i < $count; $i++)
			if(($subdomain = $this->getPageSubdomain($selected[$i]['ownerid'])) !== false) $result['http://'.$subdomain.'.'.$signature['domain'][0]] = true;
		return array_keys($result);
	}
	
	function getPageSubdomain($id) {
		$subdomain = false;
		$selected = $this->DB->SelectAny('SELECT path, parent FROM module WHERE id = '.$id.' LIMIT 1');
		if(empty($selected)) return false;
		$path[0] = $selected[0]['path'];
		$parent[0] = $selected[0]['parent'];
		while(end($parent)){
			$selected = $this->DB->SelectAny('SELECT path, parent FROM module WHERE id = '.end($parent).' LIMIT 1');
			if(empty($selected)) break;
			$path[] = $selected[0]['path'];
			$parent[] = $selected[0]['parent'];
		}
		$count = count($parent);
		if($count > 1 && $parent[$count - 2] == 60){
			$selected = $this->DB->SelectAny('SELECT domain FROM subdomain WHERE lower(domain) = \''.strtolower($path[count($path) - 2]).'\' LIMIT 1');
			if(!empty($selected)) $subdomain = $selected[0]['domain'];
		}
		return $subdomain;
	}
	
	function getFileSubdomainsPrePath($path) {
		GLOBAL $signature;
		$result = false;
		$exploded = explode('/', $path);
		if(count($exploded) > 2 && $exploded[1] == 'subdomains') {
			$selected = $this->DB->SelectAny('SELECT domain FROM subdomain WHERE lower(domain) = \''.strtolower($exploded[2]).'\' LIMIT 1');
			if(!empty($selected)) $result = 'http://'.$selected[0]['domain'].'.'.$signature['domain'][0];
		}
		return $result;
	}
	
	function selectPublishTypes($request = array()){
		$selected = $this->DB->SelectAny('SELECT number, name, title FROM publish_type');
		$types = array();
		foreach ($selected as $value)
			$types[$value['number']] = array('name' => $value['name'], 'title' => $value['title']);
		return $types;
	}
	
	function selectReportTypes($request = array()){
		$selected = $this->DB->SelectAny('SELECT number, name FROM reporttype');
		$types = array();
		foreach($selected as $value)
			$types[$value['number']] = $value['name'];
		return $types;
	}
	
	function selectPages($request = array()){
		$handler = new ContentHandler();
		$pages = $handler->selectPages();
		return $pages;
	}
	
	function selectFiles($request = array()){
		global $ROOT_PATH, $TOOLS_PATH, $COMMON_VARS;
		include_once($TOOLS_PATH.'/File.functions.inc');
		$result = array();
		$array = array();
		$excluded_pathes = array();
		foreach ($COMMON_VARS['publish_path_denied'] as $value) $excluded_pathes[] = $ROOT_PATH.'/'.$value;
		getPathesArray($array, $ROOT_PATH, $excluded_pathes, false, false, $COMMON_VARS['publish_file_types']);
		if(empty($request['md5'])){
			foreach ($array as $value) $result[substr($value, strlen($ROOT_PATH))] = substr($value, strlen($ROOT_PATH));
			natsort($result);
		}
		else{
			natsort($array);
			foreach($array as $value)
				$result[substr($value, strlen($ROOT_PATH))] = is_dir($value) ? '' : md5_file($value);
		}
		return $result;
	}
	
	function selectReportReceivers($request = array()){
		$selected = $this->DB->SelectAny('SELECT id, email FROM reportreceiver');
		$result = array();
		foreach($selected as $key => $value)
			$result[$value['id']] = $value['email'];
		return $result;
	}
	
	function createDeletedProcessing(){
		$deletedprocessing = new DeletedProcessing();
		$deletedprocessing->report = new ObjectsList();
		$deletedprocessing->report->type = new DeletedProcessingReport();
		return $deletedprocessing;
	}
	
	function openDeletedObjectsProcessing($request = array()){
		$deletedprocessing = $this->createDeletedProcessing();
		$deletedprocessing->id = $request['id'];
		$this->DB->initObject($deletedprocessing);
		if(!empty($deletedprocessing->host)) $deletedprocessing->hostpath = $this->getHostPath(array('type' => $deletedprocessing->type, 'host' => $deletedprocessing->host,));
		if(!empty($deletedprocessing->userid)) $deletedprocessing->username = $this->getUserName(array('type' => $deletedprocessing->type, 'userid' => $deletedprocessing->userid,));
		$datetime = explode('.', $deletedprocessing->date_processed);
		$deletedprocessing->date_processed = $datetime[0];
		return $deletedprocessing;
	}
	
	function saveDeletedObjectsProcessing($request = array()){
		$deletedprocessing = $this->createDeletedProcessing();
		$this->parseRequest($request, $deletedprocessing);
		$this->DB->begin();
		$this->DB->processObject($deletedprocessing);
		$this->DB->commit();
		$deletedprocessing = $this->openDeletedObjectsProcessing(array('id' => $deletedprocessing->id));
		$this->setLogEvent(4, 15, 16, 'Deleted objects processed on  "'.$deletedprocessing->hostpath.'" ['.$deletedprocessing->host.']', $deletedprocessing->id);
		$this->DB->commit();
		return $deletedprocessing;
	}
	
	function getDeletedObjects($request = array()){
		$selected = $this->DB->SelectAny('SELECT * FROM deleted WHERE preset = '.$request['id']);
		return $selected;
	}
	
	function cleanDeletedObjects($request = array()){
		$query = 'DELETE FROM deleted WHERE preset = '.$request['id'];
		if(!empty($request['exception'])) $query .= ' AND uid NOT IN (\''.implode('\', \'', $request['exception']).'\')';
		if($this->DB->query($query)) return array();
		else return array('_error' => 'Can not clean deleted. Query: "'.$query.'"');
	}
	
	function selectEngineFiles($request = array()){
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$Handler = new ToolsHandler();
		$result = $Handler->selectEnginePacketAdds($request);
		foreach($result as $key => $value)
			if(file_exists($ROOT_PATH.$key)) $result[$key] = is_dir($ROOT_PATH.$key) ? '' : md5_file($ROOT_PATH.$key);
		return $result;
	}
	
	function deleteFromChangedURL($request = array()){
		if(empty($request['preset'])) return array('_error' => 'PreSet is not specified');
		if(!isset($request['objects']) || !is_array($request['objects'])) $request['objects'] = array();
		$count = count($request['objects']);
		$result = array();
		for ($i = 0; $i < $count; $i++){
			if(($request['objects'][$i]['type'] == '3' || $request['objects'][$i]['type'] == '9') && !isset($result[$request['objects'][$i]['object']])){
				$this->DB->delete('changedurl', array('ownerid' => $request['objects'][$i]['type'] == '3' ? $request['objects'][$i]['object'] : $request['objects'][$i]['objectfields']['id'], 'preset' => $request['preset']));
				$result[$request['objects'][$i]['object']] = true;
			}
		}
		return array_keys($result);
	}
	
	function addToDeletedObjects($request = array()){
		if(empty($request['preset'])) return array('_error' => 'PreSet is not specified');
		if(!isset($request['objects']) || !is_array($request['objects'])) $request['objects'] = array();
		$result = array();
		$types_names = array(1 => 'layout', 2 => 'menu', 3 => 'module', 6 => 'template', 12 => 'subdomain', 13 => 'importedfeed', 14 => 'city', 15 => 'feed',);
		$types_numbers = array_keys($types_names);
		$count = count($request['objects']);
		for ($i = 0; $i < $count; $i++){
			if($request['objects'][$i]['type'] == 9){
				$request['objects'][$i]['type'] = 3;
				$request['objects'][$i]['object'] = $request['objects'][$i]['objectfields']['id'];
			}
			if(in_array($request['objects'][$i]['type'], $types_numbers) && !isset($result[$request['objects'][$i]['type']][$request['objects'][$i]['object']])){
				if(!isset($result[$request['objects'][$i]['type']])) $result[$request['objects'][$i]['type']] = array();
				$selected = $this->DB->SelectAny('SELECT id FROM '.$types_names[$request['objects'][$i]['type']].' WHERE id = '.$request['objects'][$i]['object'].' LIMIT 1');
				if(empty($selected)){
					$already = $this->DB->SelectAny('SELECT id FROM deleted WHERE type = '.$request['objects'][$i]['type'].' AND uid = \''.$request['objects'][$i]['objectfields']['uid'].'\' AND preset = '.$request['preset'].' LIMIT 1');
					if(empty($already)) $this->DB->insert('deleted', array('type' => $request['objects'][$i]['type'], 'uid' => $request['objects'][$i]['objectfields']['uid'], 'preset' => $request['preset']));
					$result[$request['objects'][$i]['type']][$request['objects'][$i]['object']] = true;
				}
			}
		}
		$count = count($types_numbers);
		for ($i = 0; $i < $count; $i++)
			if(isset($result[$types_numbers[$i]])) $result[$types_numbers[$i]] = array_keys($result[$types_numbers[$i]]);
		return $result;
	}
	
	function deleteOldPackages($request = array()){
		$result = array();
		$last_pub_packages = array();
		$objects['1'] = $this->DB->SelectAny('SELECT id, date_changed FROM layout');
		$objects['2'] = $this->DB->SelectAny('SELECT id, date_changed FROM menu');
		$objects['3'] = $this->DB->SelectAny('SELECT id, date_changed FROM module WHERE type IN (1, 3, 6, 8)');
		$objects['6'] = $this->DB->SelectAny('SELECT id, date_changed FROM template');
		$objects['12'] = $this->DB->SelectAny('SELECT id, date_changed FROM subdomain');
		$objects['13'] = $this->DB->SelectAny('SELECT id, date_changed FROM importedfeed');
		$objects['14'] = $this->DB->SelectAny('SELECT id, date_changed FROM city');
		$objects['15'] = $this->DB->SelectAny('SELECT id, date_changed FROM feed');
		$types = array_keys($objects);
		$count = count($types);
		for ($i = 0; $i < $count; $i++) {
			$c = count($objects[$types[$i]]);
			for ($j = 0; $j < $c; $j++) {
				$selected = $this->DB->SelectAny('SELECT packagepublish.ownerid FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.date_published > \''.$objects[$types[$i]][$j]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type = '.$types[$i].' AND packageitem.object = \''.$objects[$types[$i]][$j]['id'].'\') ORDER BY packagepublish.date_published DESC');
				$sel_count = count($selected);
				for ($k = 0; $k < $sel_count; $k++) $last_pub_packages[$selected[$k]['ownerid']] = true;
			}
		}
		$selected = $this->DB->SelectAny('SELECT ownerid, max((\'now\'::date - date_published::date)) AS elapsed_time FROM packagepublish GROUP BY ownerid HAVING max((\'now\'::date - date_published::date)) > '.$request['life_time'].' ORDER BY ownerid');
		$count = count($selected);
		$index = 0;
		for ($i = 0; $i < $count; $i++){
			$package = $this->DB->SelectAny('SELECT id, name, access_flag, date_locked FROM package WHERE id = '.$selected[$i]['ownerid'].' LIMIT 1');
			if(empty($package)) continue;
			$date_locked = explode('.', $package[0]['date_locked']);
			$result[$index] = array(
				'id' => $package[0]['id'],
				'name' => $package[0]['name'],
				'elapsed_time' => $selected[$i]['elapsed_time'],
				'message' => empty($package[0]['access_flag']) || $package[0]['access_flag'] == $this->Security->currentuser->id ? (isset($last_pub_packages[$selected[$i]['ownerid']]) ? 'Not deleted. Package contains important information for CMS publication reports' : '') : 'Not deleted. Locked by '.$this->getUserName(array('type' => 1, 'userid' => $package[0]['access_flag'])).' [ '.$date_locked[0].' ]',
				'error' => '',
			);
			if(empty($result[$index]['message'])){
				$deleted = $this->deletePackage($package[0]);
				if(!empty($deleted->_error)) $result[$index]['error'] = $deleted->_error;
			}
			$index++;
		}
		return $result;
	}

}
?>