<?php
require_once(WCF_DIR.'lib/util/TwitterUtil.class.php');

/**
 * 
 * 
 * @author	Torben Brodt
 * @url		http://trac.easy-coding.de/trac/wcf/wiki/twitter
 * @license	GNU General Public License <http://opensource.org/licenses/gpl-3.0.html>
 */
class TwitterRetweetListener implements EventListener {

	/**
	 * @see EventListener::execute()
	 */
	public function execute($eventObj, $className, $eventName) {
	
		//TODO: display retweets
	
		foreach($eventObj->links as $link) {
		
	
			$link = $this->rdfAutoDiscover($link);
		
			if($this->isHomeLink($link)) {
				$query = parse_url($link, PHP_URL_QUERY);
				parse_str($query, $output);
				
				$this->link($eventObj, $output['action'], $output['objectID'], $output['objectType'], $output['packageID']);
			}
		}
	}

	/**
	 *
	 */
	protected function isHomeLink($link) {
		if(empty($link)) {
			return false;
		}

		// TODO: does this link point to PAGE_URL ?

		return true;
	}

	protected function link() {
		// TODO: insert wcf1_twitter_message_retweet
	}
	
	/**
	 * @return string
	 */
	protected function rdfAutoDiscover($trackbackURL) {
		// fetch page content
		$pageContent = @file_get_contents($trackbackURL);
		$didDiscover = false;
		
		if ($pageContent !== false) {
			// search for RDF instructions
			if (preg_match_all('/(<rdf:RDF.*?<\/rdf:RDF>)/sm', $pageContent, $matches)) {
				foreach($matches[0] as $rdfInstructions) {
					if (preg_match('|dc\:identifier\=\"'.preg_quote($trackbackURL).'\"|isU', $rdfInstructions)) {
						// get pingback URL
						if (preg_match('/trackback\:ping\=\"([^"]+)\"/isU', $rdfInstructions, $pingbackURL)) {
							
							return $pingbackURL[1];
						}
					}
				}
			}
		}
		return '';
	}
}
?>
