<?php

/**
 * Snippet to display a twitter feed.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS\module\social
 * @copyright Copyright (c) 2013 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/** @var $tplEngine cfTemplateEngine */
$params = array();
if(isset($id)) {
	$f = 'feedid';
	$params[] = $id;
}
else if(isset($name)) {
	$f = 'screenname';
	$params[] = $name;
}
else
	return;

$limit = isset($limit) ? $limit : 200;
$wrapperTpl = isset($wrapperTpl) ? $tplEngine->getChunk($wrapperTpl) : '<ul class="twitterfeed">[[+tweets]]</ul>';
$itemTpl = isset($itemTpl) ? $tplEngine->getChunk($itemTpl) : '<li>[[+text]] <span>[[+deltaTime]]</span></li>';

// Read the data
if($data = clearFusionCMS::getDb()->fetchOne("SELECT feedcache FROM cf_socialtwitter_default_site WHERE $f=?", $params)) {
	if(!empty($data)) {
		$tweets = json_decode($data);
		if(count($tweets)) {
			$html = '';
			foreach($tweets as $tweet) {
				// Age of tweet
				$date = new flDate();
				$date = $date->timeSpan(new flDate($tweet->created_at, clearFusionCMS::getSysTimezone()));

				// Make links links and link to names
				$html .= $tplEngine->parseString($itemTpl, array(
					'text' => preg_replace('#(@([a-z0-9_-]+))#i', '<a href="http://twitter.com/$2" rel="nofollow">$1</a>', preg_replace('#(https?)://([^\s]+)#', '<a href="$1://$2" rel="nofollow">$1://$2</a>', $tweet->text)),
					'deltaTime' => $date['string'],
					'createdAt' => $tweet->created_at,
					'source' => $tweet->source,
					'profileImg' => $tweet->user->profile_image_url_https,
					'name' => $tweet->user->name,
					'screenName' => $tweet->user->screen_name
				));

				if(!--$limit)
					break;
			}

			echo $tplEngine->parseString($wrapperTpl, array('tweets' => $html));
		}
	}
}
