<?php

class ImportedFeedManagerView extends Slot {

	var $SectionID = 44;
	var $ModuleID = 15;
	var $colors = array('red' => '#DC143C', 'yellow' => '#FF8C00', 'green' => '#006400', 'black' => '#000000', 'blue' => '#4169E1',);
	var $action;
	var $importedfeeds = array();
	var $importedfeed = array();
	var $terminated = false;
	var $undo = 0;
	var $default_updating_period = 43200;
	var $feed_updating_periods = array(3600 => '1 Hour', 10800 => '3 Hours', 21600 => '6 Hours', 43200 => '12 Hours', 86400 => '24 Hours', 172800 => '2 Days', 345600 => '4 Days', 604800 => '1 Week');
	var $updating_periods = array();
	var $max_count = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5,);

	function __construct($pquery) {
		parent::__construct($pquery);
		$this->updating_periods = $this->feed_updating_periods;
		$this->updating_periods[0] = 'Feed';
		ksort($this->updating_periods);
	}

	function init() {
		GLOBAL $TOOLS_PATH;
		$this->action = isset($this->LocalTarget[0]) ? $this->LocalTarget[0] : '';
		$this->importedfeeds = $this->Action->Server->getGuide('importedfeed');
		if(!empty($this->action) && !is_numeric($this->action) && (($this->action != 'Add' && $this->action != 'FeedSourceData' && !array_key_exists(@$this->LocalTarget[1], $this->importedfeeds)) || ($this->server_type != 'dev' && $this->action != 'View' && $this->action != 'FeedSourceData'))) return $this->terminateAction();
		switch($this->action){
			case 'Add': {
				$this->importedfeed = $this->Action->Handler->_parseContent($this->Action->Handler->createImportedFeed());
				$this->importedfeed['feedsources'][0] = $this->Action->Handler->_parseContent(new ImportedFeedSource());
				$this->importedfeed['updating_period'] = $this->default_updating_period;
				$this->Scheme = 'action';
				break;
			}
			case 'Update': case 'View': case 'Duplicate': case 'Delete': {
				if($this->action != 'View'){
					$this->Action->processEvent($this->SectionID, 'get_lock', array('id' => $this->LocalTarget[1]), $this);
					if(empty($this->PreparedTemplates)) {
						if($this->action != 'Duplicate') $this->Action->processEvent($this->SectionID, 'lock', array('id' => $this->LocalTarget[1], 'member' => $this->Action->Security->currentuser->id), $this);
					}
					else if($this->PreparedTemplates['access_flag'] != $this->Action->Security->currentuser->id) return $this->terminateAction();
				}
				if($this->action == 'Update' && @$this->LocalTarget[2] == 'Undo' && @$this->LocalTarget[3] && is_numeric($this->LocalTarget[3])) $this->undo = $this->LocalTarget[3];
				$this->Action->processEvent($this->SectionID, 'open', array('id' => $this->LocalTarget[1], 'undo' => $this->undo), $this);
				$this->importedfeed = $this->PreparedTemplates;
				if($this->action == 'Duplicate') $this->importedfeed['id'] = '';
				if(empty($this->importedfeed['feedsources'])) $this->importedfeed['feedsources'][0] = $this->Action->Handler->_parseContent(new ImportedFeedSource());
				$this->Scheme = 'action';
				break;
			}
			case 'Unlock': {
				$this->Action->processEvent($this->SectionID, 'get_lock', array('id' => $this->LocalTarget[1]), $this);
				if(@$this->PreparedTemplates['access_flag'] == $this->Action->Security->currentuser->id) $this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->LocalTarget[1], 'member' => $this->Action->Security->currentuser->id), $this);
				return $this->terminateAction();
				break;
			}
			case 'FullHistory': {
				$this->Action->processEvent($this->SectionID, 'select_comments', array('id' => $this->LocalTarget[1]), $this);
				$this->Scheme = 'fullhistory';
				break;
			}
			case 'FeedSourceData': {
				$this->Scheme = 'feedsourcedata';
				$this->Action->processEvent($this->SectionID, 'open_feedsource', array('id' => $this->LocalTarget[1], 'with_data' => true), $this);
				break;
			}
			default: {
				$this->Scheme = 'default';
				$this->Action->processEvent($this->SectionID, 'select', array(), $this);
				break;
			}
		}
		if(empty($this->Request)){
			$this->setSchemeTemplate($this->Scheme);
			return;
		}
		switch($this->action) {
			case 'Update': case 'Duplicate': case 'Add': {
				foreach ($this->Request['form'] as $key => $value) $this->importedfeed[$key] = is_array($value) ? array_values($value) : $value;
				if($this->validateImportedFeed()){
					$this->importedfeed['action'] = $this->action;
					$this->importedfeed['id_user'] = $this->Action->Security->currentuser->id;
					if ($this->Action->processEvent($this->SectionID, 'save', $this->importedfeed, $this)) {
						if(!empty($this->importedfeed['id'])) $this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->importedfeed['id'], 'member' => $this->Action->Security->currentuser->id), $this);
						return $this->terminateAction();
					}
					else $this->errors['validate'] = $this->PreparedTemplates['_error'];
				}
				break;
			}
			case 'Delete': {
				include($TOOLS_PATH.'/checker.php');
				$this->check = check_to_delete($this->importedfeed['id'], 'Imported Feed');
				if (empty($this->check)){
					$this->Action->processEvent($this->SectionID, 'delete', $this->importedfeed, $this)
					and $this->clearUndo($this->importedfeed['id'])
					and $this->terminateAction();
				}
				else {
					$this->Scheme = 'nodelete';
					$this->Action->processEvent($this->SectionID, 'unlock', array('id' => $this->importedfeed['id'], 'member' => $this->Action->Security->currentuser->id), $this);
				}
				break;
			}
		}
		$this->setSchemeTemplate($this->Scheme);
	}

	function fillElements() {
		switch($this->Scheme) {
			case 'action': $this->fillAction(); break;
			case 'fullhistory': $this->fillFullHistory(); break;
			case 'nodelete': $this->fillNoDelete(); break;
			case 'feedsourcedata': $this->fillFeedSourceData(); break;
			default: $this->fillDefault(); break;
		}
	}
	

	function fillDefault() {
		if($this->terminated) return false;
		$edit_vis = $this->server_type == 'dev' ? 'visible' : 'hidden';
		$pub_vis = $this->server_type == 'pro' ? 'hidden' : 'visible';
		$this->TempFillEls['pub_vis'] = $pub_vis;
		$this->TempFillEls['btnEdit_vis'] = $edit_vis;
		$count = count($this->PreparedTemplates);
		for ($i = 0; $i < $count; $i++) {
			$this->TempFillEls['importedfeeds'][$i] = $this->PreparedTemplates[$i];
			$date_locked = explode('.', $this->PreparedTemplates[$i]['date_locked']);
			$this->TempFillEls['importedfeeds'][$i]['date_locked'] = $date_locked[0];
			if(empty($this->PreparedTemplates[$i]['_error'])) $this->TempFillEls['importedfeeds'][$i]['img'] = 'bullet';
			else {
				$this->TempFillEls['importedfeeds'][$i]['img'] = 'bullet2';
				$this->TempFillEls['importedfeeds'][$i]['chbAdds_disabled'] = 'disabled';
			}
			$this->TempFillEls['importedfeeds'][$i]['btnEdit_vis'] = $edit_vis;
			$this->TempFillEls['importedfeeds'][$i]['chbAdds_vis'] = $pub_vis;
			if(!empty($this->PreparedTemplates[$i]['access_flag']) && $this->PreparedTemplates[$i]['access_flag'] != $this->Action->Security->currentuser->id) {
				$this->TempFillEls['importedfeeds'][$i]['btnUnlock_disp'] = 'none';
				$this->TempFillEls['importedfeeds'][$i]['btnEdit_disp'] = 'none';
				$this->TempFillEls['importedfeeds'][$i]['btnDelete_disp'] = 'none';
			}
			else {
				$this->TempFillEls['importedfeeds'][$i]['locked_message_disp'] = 'none';
				if($this->PreparedTemplates[$i]['access_flag'] != $this->Action->Security->currentuser->id) $this->TempFillEls['importedfeeds'][$i]['btnUnlock_disp'] = 'none';
			}
			$presets_count = explode('/', $this->PreparedTemplates[$i]['published_count']);
			$c = count($this->PreparedTemplates[$i]['publish']);
			$this->TempFillEls['importedfeeds'][$i]['published_count_cursor'] = $c ? 'pointer' : 'auto';
			$this->TempFillEls['importedfeeds'][$i]['published_count_color'] = $this->colors[($presets_count[0] >= $presets_count[1] ? 'green' : (empty($presets_count[0]) ? 'red' : 'blue'))];
			$this->TempFillEls['importedfeeds'][$i]['publish'][]['variable'] = 'importedfeeds['.$this->PreparedTemplates[$i]['id'].']=[];';
			$this->TempFillEls['importedfeeds'][$i]['publish'][]['variable'] = 'importedfeeds['.$this->PreparedTemplates[$i]['id'].']["publish"]=[];';
			for($j = 0; $j < $c; $j++){
				$this->TempFillEls['importedfeeds'][$i]['publish'][]['variable'] = 'importedfeeds['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']=[];';
				$this->TempFillEls['importedfeeds'][$i]['publish'][]['variable'] = 'importedfeeds['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["package_id"]='.$this->PreparedTemplates[$i]['publish'][$j]['package_id'].';';
				$this->TempFillEls['importedfeeds'][$i]['publish'][]['variable'] = 'importedfeeds['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["package_name"]="'.$this->PreparedTemplates[$i]['publish'][$j]['package_name'].'";';
				$this->TempFillEls['importedfeeds'][$i]['publish'][]['variable'] = 'importedfeeds['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["username"]="'.$this->PreparedTemplates[$i]['publish'][$j]['username'].'";';
				$this->TempFillEls['importedfeeds'][$i]['publish'][]['variable'] = 'importedfeeds['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["hostpath"]="'.$this->PreparedTemplates[$i]['publish'][$j]['hostpath'].'";';
				$this->TempFillEls['importedfeeds'][$i]['publish'][]['variable'] = 'importedfeeds['.$this->PreparedTemplates[$i]['id'].']["publish"]['.$j.']["date_published"]="'.$this->PreparedTemplates[$i]['publish'][$j]['date_published'].'";';
			}
		}
		$this->clearAllTemplates();
	}

	function fillAction() {
		if($this->terminated) return false;
		if($this->undo) $this->TempFillEls['undo'] = 'Undo up to '.$this->undo.' version';
		$this->TempFillEls['action'] = $this->action;
		$this->TempFillEls['name'] = $this->importedfeed['name'];
		$this->TempFillEls['id'] = $this->importedfeed['id'];
		$this->TempFillEls['link'] = '<a href="/'.$this->importedfeed['link'].'">'.$this->importedfeed['link'].'</a>';
		$this->TempFillEls['uid'] = $this->importedfeed['uid'];
		$date_created = explode('.', $this->importedfeed['date_created']);
		$this->TempFillEls['date_created'] = $date_created[0];
		$this->TempFillEls['form_name'] = inputText('form[name]', $this->importedfeed['name'], 80, '', 128);
		$this->TempFillEls['form_title'] = inputText('form[title]', $this->importedfeed['title'], 80, '', 256);
		$this->TempFillEls['form_description'] = inputTextArea('form[description]', $this->importedfeed['description'], '', 5, 'style="width: 500px;"');
		$this->TempFillEls['form_updating_period'] = inputSelect ('form[updating_period]', $this->feed_updating_periods, $this->importedfeed['updating_period'], 'style="width: 150px;"');
		$count = count($this->importedfeed['feedsources']);
		for ($i = 0; $i < $count; $i++) {
			$last_date_updated = explode('.', @$this->importedfeed['feedsources'][$i]['last_date_updated']);
			$this->TempFillEls['feedsources'][$i] = array(
				'feedsource_ident' => $i,
				'id' => @$this->importedfeed['feedsources'][$i]['id'],
				'form_name' => inputText('form[feedsources]['.$i.'][name]', $this->importedfeed['feedsources'][$i]['name'], 35, '', 256),
				'form_link' => inputText('form[feedsources]['.$i.'][link]', $this->importedfeed['feedsources'][$i]['link'], 60, '', 512),
				'form_updating_period' => inputSelect ('form[feedsources]['.$i.'][updating_period]', $this->updating_periods, $this->importedfeed['feedsources'][$i]['updating_period'], 'style="width: 100px;"'),
				'form_max_count' => inputSelect ('form[feedsources]['.$i.'][max_count]', $this->max_count, $this->importedfeed['feedsources'][$i]['max_count'], 'style="width: 40px;"'),
				'last_date_updated' => $last_date_updated[0].inputHidden('form[feedsources]['.$i.'][last_date_updated]', @$this->importedfeed['feedsources'][$i]['last_date_updated']),
				'btnMagn_vis' => $this->action == 'View' ? 'visible' : 'hidden',
			);
		}
		$this->TempFillEls['max_feedsource_ident'] = $count - 1;
		if(empty($this->importedfeed['id'])) {
			$this->TempFillEls['header_info_disp'] = 'none';
			$this->TempFillEls['link_disp'] = 'none';
			$this->TempFillEls['date_created_disp'] = 'none';
			$this->TempFillEls['uid_disp'] = 'none';
		}
		$this->TempFillEls['form_comment'] = inputTextarea('form[comment]', (isset($this->importedfeed['comment']) ? $this->importedfeed['comment'] : ''), '', 5, 'id="form[comment]" style="width: 500px;"');
		if(!empty($this->importedfeed['comments'])) $this->fillFullHistory(false);
		if(!empty($this->importedfeed['_error'])) $this->errors['model'] = $this->importedfeed['_error'];
		if(count($this->errors) > 0) $this->errors['header'] = 'There were some errors.<br>Please see below for details';
		foreach ($this->errors as $k => $v) $this->TempFillEls[$k.'_error'] = $this->printError($v).($k == 'header' ? '<p>' : '');
		$this->clearAllTemplates();
	}

	function fillFullHistory($main = true) {
		if($this->terminated) return false;
		if($main) $history = &$this->PreparedTemplates['curPage'];
		else $history = &$this->importedfeed['comments'];
		$count = count($history);
		for ($i = 0; $i < $count; $i++){
			$date = explode('.', $history[$i]['date']);
			$this->TempFillEls['comments'][$i] = array(
				'number' => $main ? ($this->PreparedTemplates['pageRecordsQty'] * ($this->PreparedTemplates['curPageNumber'] - 1) + $i + 1) : ($i + 1),
				'date' => $date[0],
				'member' => $history[$i]['member'],
				'version' => $history[$i]['version'],
				'value' => wordwrap($history[$i]['value'], 30, '<br>', 1),
				'id' => $this->LocalTarget[1],
				'undo_vis' => $history[$i]['file'] ? 'visible' : 'hidden',
			);
		}
		if($main) {
			$this->TempFillEls['id'] = $this->PreparedTemplates['id'];
			$this->TempFillEls['name'] = $this->PreparedTemplates['name'];
			$this->clearAllTemplates();
		}
	}
	
	function fillNoDelete() {
		if($this->terminated) return false;
		$this->TempFillEls['id'] = $this->importedfeed['id'];
		$this->TempFillEls['name'] = $this->importedfeed['name'];
		$count = count($this->check);
		for ($i = 0; $i < $count; $i++)
			$this->TempFillEls['Pages'][0]['pitems'][$i] = array(
				'item' => makeLink($this->Home.$this->check[$i]['path'], $this->check[$i]['name']),
				'id' => $this->check[$i]['id'],
			);
		$this->clearAllTemplates();
	}
	
	function fillFeedSourceData() {
		if($this->terminated) return false;
		$this->TempFillEls['name'] = $this->PreparedTemplates['name'];
		$this->TempFillEls['link'] = $this->PreparedTemplates['link'];
		$last_date_updated = explode('.', $this->PreparedTemplates['last_date_updated']);
		$this->TempFillEls['last_date_updated'] = $last_date_updated[0];
		$count = count($this->PreparedTemplates['feeddata']);
		for ($i = 0; $i < $count; $i++) {
			$this->TempFillEls['feeddata'][$i] = $this->PreparedTemplates['feeddata'][$i];
			$this->TempFillEls['feeddata'][$i]['short_link'] = strlen($this->PreparedTemplates['feeddata'][$i]['link']) > 70 ? substr($this->PreparedTemplates['feeddata'][$i]['link'], 0, 70).'...' : $this->PreparedTemplates['feeddata'][$i]['link'];
			if(strlen($this->TempFillEls['feeddata'][$i]['title']) > 80) $this->TempFillEls['feeddata'][$i]['title'] = substr($this->TempFillEls['feeddata'][$i]['title'], 0, 80).'...';
		}
		if(!empty($this->PreparedTemplates['_error'])) $this->TempFillEls['script'] = 'window.close();';
		$this->clearAllTemplates();
	}
	
	function validateImportedFeed() {
		if(($id = array_search($this->importedfeed['name'], $this->importedfeeds)) !== false && $id != $this->importedfeed['id']) $this->errors['name'] = 'Imported Feed with such name already exists';
		if(!is_AlphaNumUnderDefis($this->importedfeed['name'], 3, 128)) $this->errors['name'] = 'Imported Feed name is not valid';
		if(!is_FullText($this->importedfeed['description'], 6, 256)) $this->errors['description'] = 'Imported Feed description is not valid';
		if(!is_numeric($this->importedfeed['updating_period']) || $this->importedfeed['updating_period'] < 1) $this->errors['updating_period'] = 'Imported Feed updating period is not valid';
		$count = count($this->importedfeed['feedsources']);
		for ($i = 0; $i < $count; $i++) {
			$link = checkURL($this->importedfeed['feedsources'][$i]['link']);
			if(empty($this->importedfeed['feedsources'][$i]['link']) || $link != $this->importedfeed['feedsources'][$i]['link'] || strlen($this->importedfeed['feedsources'][$i]['link']) > 512) {
				$this->errors['feedsource'] = 'Some Source Link URL is not valid';
				break;
			}
		}
		if(!$count) {
			$this->errors['feedsource'] = 'Imported Feed must contain at least 1 source link';
			$this->importedfeed['feedsources'][0] = $this->Action->Handler->_parseContent(new ImportedFeedSource());
		}
		return empty($this->errors) ? true : false;
	}

	function clearUndo($id) {
		GLOBAL $ROOT_PATH, $TOOLS_PATH;
		include_once($TOOLS_PATH.'/func.php');
		$path = $ROOT_PATH.'/undo/importedfeed/'.$id;
		if(file_exists($path)) mysystem('rm -rf '.$path);
		return true;
	}
	
	function terminateAction(){
		$this->terminated = true;
		$this->clearAllTemplates();
		header('Location: '.$this->Home.'/Registar/ImportedFeedManager'.$this->SID);
		return true;
	}
	
	function clearAllTemplates(){
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'get_lock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'lock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'unlock');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'open');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'save');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'delete');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'select_comments');
		$this->PreparedTemplates = $this->Action->clearTemplate($this->SectionID, 'open_feedsource');
	}

}
?>