<?php

class SubdomainHandler extends ContentHandler{

	function __construct(){
		parent::__construct('SubdomainHandler');
	}

	function createSubdomain () {
		return new Subdomain();
	}

	function selectSubdomains ($request = array()) {
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		$parent = $this->getSubdomainsParent();
		$presets = array();
		$selected = $this->DB->SelectAny('SELECT id, name FROM preset');
		$presets_count = count($selected);
		for ($i = 0; $i < $presets_count; $i++) $presets[$selected[$i]['id']] = $selected[$i]['name'];
		$packages = array();
		$hostpaths = array();
		$usernames = array();
		$result = $this->DB->SelectAny('SELECT id, name, domain, date_changed, (\'now\'::date - date_changed::date) AS unmodified, access_flag, date_locked FROM subdomain ORDER BY id');
		$count = count($result);
		for ($i = 0; $i < $count; $i++) {
			$result[$i]['user_name'] = $this->getUsername($result[$i]['access_flag']);
			$result[$i]['_error'] = '';
			$page = $this->DB->SelectAny('SELECT id, is_describe FROM module WHERE parent = '.$parent.' AND lower(path) = \''.$result[$i]['domain'].'\' LIMIT 1');
			if(empty($page)) $result[$i]['_error'] = 'Subdomain Main Page doesn\'t exist';
			else if(empty($page[0]['is_describe'])) $result[$i]['_error'] = 'Subdomain Main Page is set to subcategory';
			if(!file_exists($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir'].'/'.$result[$i]['domain'])) $result[$i]['_error'] = 'Subdomain folder doesn\'t exist';
			$result[$i]['publish'] = array();
			$query = 'SELECT packagepublish.id, packagepublish.ownerid as package_id, packagepublish.host, packagepublish.userid, packagepublish.date_published FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.date_published > \''.$result[$i]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type = 12 AND packageitem.object = \''.$result[$i]['id'].'\') ORDER BY packagepublish.date_published DESC';
			$packagepublish = $this->DB->SelectAny($query);
			$presets_unique = array();
			$c = count($packagepublish);
			$index = 0;
			for ($j = 0; $j < $c; $j++){
				if(isset($presets_unique[$packagepublish[$j]['host']])) continue;
				$presets_unique[$packagepublish[$j]['host']] = true;
				$result[$i]['publish'][$index] = $packagepublish[$j];
				$date_published = explode ('.', $packagepublish[$j]['date_published']);
				$result[$i]['publish'][$index]['date_published'] = $date_published[0];
				if(!isset($packages[$packagepublish[$j]['package_id']])){
					$sel = $this->DB->SelectAny('SELECT name FROM package WHERE id = '.$packagepublish[$j]['package_id'].' LIMIT 1');
					$packages[$packagepublish[$j]['package_id']] = empty($sel) ? '[deleted]' : $sel[0]['name'];
				}
				$result[$i]['publish'][$index]['package_name'] = $packages[$packagepublish[$j]['package_id']];
				if(!isset($hostpaths[$packagepublish[$j]['host']])){
					$sel = $this->DB->SelectAny('SELECT name FROM preset WHERE id = '.$packagepublish[$j]['host'].' LIMIT 1');
					$hostpaths[$packagepublish[$j]['host']] = empty($sel) ? '[unknown]' : $sel[0]['name'];
				}
				$result[$i]['publish'][$index]['hostpath'] = $hostpaths[$packagepublish[$j]['host']];
				if(!isset($usernames[$packagepublish[$j]['userid']])){
					$sel = $this->DB->SelectAny('SELECT username FROM member WHERE id = '.$packagepublish[$j]['userid'].' LIMIT 1');
					$usernames[$packagepublish[$j]['userid']] = empty($sel) ? '[unknown]' : $sel[0]['username'];
				}
				$result[$i]['publish'][$index]['username'] = $usernames[$packagepublish[$j]['userid']];
				$index++;
			}
			$result[$i]['published_count'] = count($result[$i]['publish']).'/'.$presets_count;
		}
		return $result;
	}

	function getSubdomainLock ($request = array()) {
		$result = array('access_flag' => 0, 'user_name' => '', 'date_locked' => '');
		$selected = $this->DB->SelectAny('SELECT access_flag, date_locked FROM subdomain WHERE id = '.$request['id'].' LIMIT 1');
		if(!empty($selected)) {
			$selected[0]['user_name'] = $this->getUsername($selected[0]['access_flag']);
			$result = $selected[0];
		}
		return $result;
	}

	function lockSubdomain ($request = array()) {
		$this->setLogEvent(3, 18, 3, 'Lock Subdomain ['.$request['id'].']', $request['id']);
		$this->DB->update('subdomain', array('access_flag' => $this->Security->currentuser->id, 'date_locked' => 'now'), array('id' => $request['id']));
		$this->DB->commit();
		return array();
	}

	function unlockSubdomain ($request = array()) {
		$this->setLogEvent(3, 18, 4, 'UnLock Subdomain ['.$request['id'].']', $request['id']);
		$this->DB->update('subdomain', array('access_flag' => 0), array('id' => $request['id']));
		$this->DB->commit();
		return array();
	}

	function openSubdomain ($request = array()) {
		GLOBAL $ROOT_PATH, $COMMON_VARS, $TOOLS_PATH;
		$subdomain = $this->createSubdomain();
		if(empty($request['undo'])) {
			$subdomain->id = $request['id'];
			$this->DB->initObject($subdomain);
		}
		else {
			$Undo_field = array('type' => 12, 'id' => $request['id'], 'undo' => 0, 'version' => $request['undo']);
			include ($TOOLS_PATH.'/undo.php');
			$subdomain = $print_arr;
		}
		$parent = $this->getSubdomainsParent();
		$page = $this->DB->SelectAny('SELECT id, is_describe FROM module WHERE parent = '.$parent.' AND lower(path) = \''.$subdomain->domain.'\' LIMIT 1');
		if(empty($page)) $subdomain->_error = 'Subdomain Main Page doesn\'t exist.<br>Resave subdomain to create that page automatically or create it manual.';
		else if(empty($page[0]['is_describe'])) $subdomain->_error = 'Subdomain Main Page\'s type is set to "subcategory".<br>Resave subdomain to update main page\'s type automatically or fix it manual.';
		if(!file_exists($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir'].'/'.$subdomain->domain)) $subdomain->_error = 'Subdomain folder "/'.$COMMON_VARS['subdomains_dir'].'/'.$subdomain->domain.'" doesn\'t exist.<br>Resave subdomain to create that folder automatically or create it manual.';
		$subdomain->comments = $this->DB->SelectAny('SELECT sdc.*, m.username AS member FROM subdomaincomment sdc, member m WHERE m.id = sdc.member AND sdc.ownerid = '.$request['id'].' ORDER BY sdc.version DESC LIMIT 10 OFFSET 0');
		$count = count($subdomain->comments);
		for ($i = 0; $i < $count; $i++) $subdomain->comments[$i]['file'] = file_exists($ROOT_PATH.'/undo/subdomain/'.$request['id'].'/'.$subdomain->comments[$i]['version'].'.inc') ? true : false;
		return $subdomain;
	}

	function saveSubdomain ($request = array()) {
		GLOBAL $ROOT_PATH, $COMMON_VARS, $TOOLS_PATH;
		$this->undo = 0;
		$parent = $this->getSubdomainsParent();
		$subdomain = $this->createSubdomain();
		$this->parseRequest($request, $subdomain);
		$subdomain->domain = strtolower($subdomain->domain);
		$selected = $this->DB->SelectAny('SELECT id, domain FROM subdomain WHERE domain = \''.$subdomain->domain.'\' LIMIT 1');
		if(!empty($selected) && $selected[0]['id'] != $subdomain->id) {
			$subdomain->_error = 'Such subdomain already exists';
			return $subdomain;
		}
		if (empty($subdomain->id)) {
			/*$selected = $this->DB->SelectAny('SELECT id FROM module WHERE parent = '.$parent.' AND lower(path) = \''.$subdomain->domain.'\'');
			if(!empty($selected)) {
				$subdomain->_error = 'Page with such path already exists and it\'s not main subdomain page';
				return $subdomain;
			}*/
			$subdomain->date_created = 'now';
			$this->setLogEvent(3, 18, 11, 'Add Subdomain "'.$subdomain->name.'"');
		}
		else {
			$this->setLogEvent(3, 18, 12, 'Edit Subdomain "'.$subdomain->name.'" ['.$subdomain->id.']', $subdomain->id);
			$Undo_field = array('type' => 12, 'id' => $subdomain->id, 'undo' => 1);
			include($TOOLS_PATH.'/undo.php');
			$this->undo = $undo_handler->arr_obj;
		}
		$subdomain->date_changed = 'now';
		if(empty($subdomain->uid)) $subdomain->uid = getUnique32();
		$this->DB->processObject($subdomain, 'save', array(), array(), TRUE);
		$this->DB->commit();
		$this->DB->delete('deleted', array('uid' => $subdomain->uid, 'type' => 12));
		$this->DB->begin();
		$subdomaincomment = new SubdomainComment();
		$subdomaincomment->version = 1;
		$subdomaincomment->value = 'Subdomain has been created';
		$selected = $this->DB->SelectAny('SELECT version FROM subdomaincomment WHERE ownerid = '.$subdomain->id.' ORDER BY date DESC LIMIT 1 OFFSET 0');
		if(!empty($selected[0]['version'])) {
			$subdomaincomment->version = ++$selected[0]['version'];
			$subdomaincomment->value = (!empty($request['undo']) ? 'Subdomain has been undone up to '.$request['undo'].' version<br>'."\r\n" : '').htmlspecialchars($request['comment']);
		}
		$subdomaincomment->ownerid = $subdomain->id;
		$subdomaincomment->member = empty($request['id_user']) ? $this->Security->currentuser->id : $request['id_user'];
		$subdomaincomment->date = 'now';
		$this->DB->processObject($subdomaincomment, 'save', array(), array(), TRUE);
		if(!empty($request['undo'])) $this->setLogEvent(3, 18, 10, 'Subdomain "'.$subdomain->name.'" ['.$subdomain->id.'] has been undone up to '.$request['undo'].' version', $subdomain->id);
		$this->DB->commit();
		if($this->DB->good && !empty($this->undo)) 	$undo_handler->GetArrayInFile($this->undo, 'Undo_object', $ROOT_PATH.'/undo/'.$pub_type[0]['name'].'/'.$Undo_field['id'].'/'.($subdomaincomment->version > 1 ? $subdomaincomment->version - 1 : 1).'.inc');
		if(empty($request['publish']) || !$request['publish']){
			$page = $this->DB->SelectAny('SELECT id, is_describe, name, sys_name, sort_order FROM module WHERE parent = '.$parent.' AND lower(path) = \''.$subdomain->domain.'\' LIMIT 1');
			$layout = $this->DB->SelectAny('SELECT id FROM layout ORDER BY id LIMIT 1');
			if(empty($page)) {
				$module = $this->createModule();
				$module = $this->_parseContent($module);
				$module['name'] = $subdomain->name;
				$module['sys_name'] = $subdomain->name;
				$module['path'] = $subdomain->domain;
				$module['parent']['id'] = $parent;
				$module['is_describe'] = 1;
				if(!empty($layout)) $module['layout']['id'] = $layout[0]['id'];
				$module = $this->saveSection($module);
				if(empty($module->id)) $subdomain->_error = 'Unexpected error. Can not save subdomain main page';
			}
			else if(empty($page[0]['is_describe'])) {
				$module = $this->createModule();
				$this->parseRequest($page[0], $module);
				$module = $this->_parseContent($module);
				$module['parent']['id'] = $parent;
				$module['is_describe'] = 1;
				if(!empty($layout)) $module['layout']['id'] = $layout[0]['id'];
				$module['comment'] = 'Autochanged Page\'s type by the Subdomain Manager';
				$module = $this->saveSection($module);
				if(empty($module->id) || empty($module->is_describe)) $subdomain->_error = 'Unexpected error. Can not save subdomain main page';
			}
		}
		if(!file_exists($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir'].'/'.$subdomain->domain)){
			if(!file_exists($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir'])) {
				mkdir($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir']);
				chmod($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir'], 0664);
			}
			mkdir($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir'].'/'.$subdomain->domain);
			if(file_exists($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir'].'/'.$subdomain->domain)) chmod($ROOT_PATH.'/'.$COMMON_VARS['subdomains_dir'].'/'.$subdomain->domain, 0664);
			else $subdomain->_error = 'Unexpected error. Can not create subdomain folder';
		}
		return $subdomain;
	}

	function deleteSubdomain($request = array()){
		GLOBAL $REGISTRY, $Server;
		$subdomain = $this->createSubdomain();
		$this->parseRequest($request, $subdomain);
		$this->DB->initObject($subdomain);
		$presets = $this->DB->SelectGuide(array('preset g'), '*', array());
		$this->setLogEvent(3, 18, 13, 'Delete Subdomain "'.$subdomain->name.'" ['.$subdomain->id.']',$subdomain->id);
		foreach($presets as $prekey => $prevalue) {
			$selected = $this->DB->SelectAny('SELECT id FROM deleted WHERE uid = \''.$subdomain->uid.'\' AND preset = '.$prekey.' AND type = 12 LIMIT 1');
			if(empty($selected)) $this->DB->insert('deleted', array('uid' => $subdomain->uid, 'preset' => $prekey, 'type' => 12));
		}
		$this->DB->processObject($subdomain, 'delete', array(), array(), TRUE);
		$this->DB->delete('subdomaincomment', array('ownerid' => $subdomain->id));
		$this->DB->commit();
		return $subdomain;
	}

	function getUsername ($id) {
		if(!is_numeric($id)) $id = 0;
		$selected = $this->DB->SelectAny('SELECT username FROM member WHERE id = '.$id.' LIMIT 1');
		return empty($selected) ? '' : $selected[0]['username'];
	}

	function getSubdomainsParent() {
		$parent = $this->DB->SelectAny('SELECT id FROM module WHERE type = 8 LIMIT 1');
		$parent = isset($parent[0]['id']) ? $parent[0]['id'] : 0;
		return $parent;
	}

	function selectSubdomainComments ($request = array()) {
		GLOBAL $ROOT_PATH;
		if(empty($request['curPageNumber'])) $request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty'] = 20;
		$subdomain = $this->DB->SelectAny('SELECT name FROM subdomain WHERE id = '.$request['id'].' LIMIT 1');
		$request['name'] = $subdomain[0]['name'];
		$selected = $this->DB->SelectAny('SELECT sdc.*, m.username AS member FROM subdomaincomment sdc, member m WHERE m.id = sdc.member AND sdc.ownerid = '.$request['id'].' ORDER BY sdc.version DESC LIMIT '.$request['pageRecordsQty'].' OFFSET '.(($request['curPageNumber'] - 1) * $request['pageRecordsQty']));
		$count = count($selected);
		for ($i = 0; $i < $count; $i++) $selected[$i]['file'] = file_exists($ROOT_PATH.'/undo/subdomain/'.$request['id'].'/'.$selected[$i]['version'].'.inc') ? true : false;
		$count = $this->DB->SelectAny('SELECT count(id) AS count FROM subdomaincomment WHERE ownerid = '.$request['id']);
		$request['recordsTotal'] = $count[0]['count'];
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = $selected;
		return $request;
	}
}
?>