<?php
class ImportedFeedDataUpdateHandler {
	
	private $feed;
	private $debug;
	private $handler;
	private $errors = array();
	private $datafields;
	
	function ImportedFeedDataUpdateHandler($handler, $debug = true) {
		$this->debug = $debug;
		$this->handler = $handler;
		$this->datafields = array_keys((array)$this->handler->createImportedFeedData());
	}
	
	function updateFeed($id = 0, $forced_update = false) {
		GLOBAL $DatabaseBroker;
		if(empty($id) || !is_numeric($id)) return $this->setError('Imported Feed ID is not specified');
		$selected = $DatabaseBroker->SelectAny('SELECT id FROM importedfeed WHERE id = '.$id.' LIMIT 1');
		if(empty($selected)) return $this->setError('Imported Feed with such ID doesn\'t exist');
		$this->feed = $this->handler->_parseContent($this->handler->openImportedFeed(array('id' => $id, 'with_data' => true)));
		if(!empty($this->feed['_error'])) return $this->setError('Imported Feed init failed. '.$this->feed['_error']);
		$count = count($this->feed['feedsources']);
		for ($i = 0; $i < $count; $i++){
			if($forced_update) $this->updateData(&$this->feed['feedsources'][$i]);
			else {
				$datetime = explode('.', $this->feed['feedsources'][$i]['last_date_updated']);
				$datetime = explode(' ', $datetime[0]);
				$datetime[0] = explode('-', $datetime[0]);
				$datetime[1] = explode(':', $datetime[1]);
				$last_updated = mktime($datetime[1][0], $datetime[1][1], $datetime[1][2], $datetime[0][1], $datetime[0][2], $datetime[0][0]);
				$updating_period = empty($this->feed['feedsources'][$i]['updating_period']) ? $this->feed['updating_period'] : $this->feed['feedsources'][$i]['updating_period'];
				$term = time() - $updating_period;
				if($last_updated < $term) $this->updateData(&$this->feed['feedsources'][$i]);
			}
		}
		return $this->feed;
	}
	
	function updateData($source){
		if(!empty($source['_error'])) return $this->setError('Imported Feed Source init error. '.$source['_error']);
		$source['feeddata'] = array();
		$data = @file_get_contents($source['link']);
		if(empty($data)) return $this->setError($source['link'].'&nbsp;&nbsp;-&nbsp;&nbsp;No response from URL');
		$data = $this->transformCDATA($data);
		$xml = null;
		try {
			$xml = new SimpleXMLElement($data, LIBXML_NOERROR);
		}
		catch(Exception $e) {
			return $this->setError($source['link'].'&nbsp;&nbsp;-&nbsp;&nbsp;'.$e->getMessage());
		}
		$items = $xml->xpath('//item');
		$count = count($items);
		if($source['max_count'] < $count) $count = $source['max_count'];
		for ($i = 0; $i < $count; $i++){
			$item = (array)$items[$i];
			if(empty($item) || !is_array($item)) return $this->setError($source['link'].'&nbsp;&nbsp;-&nbsp;&nbsp;RSS item is not valid');
			$item = array_change_key_case($item, CASE_LOWER);
			if(!isset($item['description']) || !is_string($item['description'])) return $this->setError($source['link'].'&nbsp;&nbsp;-&nbsp;&nbsp;RSS item description is not valid');
			foreach($this->datafields as $value){
				if(isset($item[$value]) && is_string($item[$value])) $source['feeddata'][$i][$value] = $item[$value];
			}
			$source['feeddata'][$i]['id'] = '';
			$source['feeddata'][$i]['ownerid'] = $source['id'];
		}
		$source['last_date_updated'] = 'now';
		$this->handler->saveImportedFeedSource($source);
		return 1;
	}
	
	function transformCDATA($string) {
		$result = $string;
		$noncdata = array();
		preg_match_all("/\<\!\[CDATA\[.*?\]\]\>/s", $string, $cdata);
		$count = count($cdata[0]);
		for ($i = 0; $i < $count; $i++){
			$noncdata[$i] = str_replace(array("<![CDATA[", "]]>", "&", "<", ">", '"', "\r", "\n", "\t"), array("", "", "&amp;", "&lt;", "&gt;", "&quot;", "", "", ""), $cdata[0][$i]);
			$result = str_replace($cdata[0][$i], $noncdata[$i], $result);
		}
		return $result;
	}
	
	private function setError($error){
		if($this->debug) echo $error.'<br>';
		$this->errors[] = array(
			'datetime' => date('Y-m-d H:i:s', time()),
			'message' => $error,
			'type' => '0',
		);
		return 0;
	}
	
	public function getErrors() {
		return $this->errors;
	}
	
}
?>