<?php

/**
 * 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 - 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * socialEvents Class
 *
 * Class to process social module events.
 *
 * @package clearFusionCMS\module\social
 */
class socialEvents {

	/**
	 * Event handler for cron to fetch feed updates.
	 *
	 * @param flEvent $evt The event object.
	 */
	function onCron($evt) {
		$siteMgr = new cfSiteManager($db = clearFusionCMS::getDb());
		$sites = $siteMgr->listSites();
		foreach($sites as $site => $n) {
			$bearer = null;

			// Get a list of feeds to update
			$feedRes = $db->query("SELECT screenname,tweetcount,exreplies FROM cf_socialtwitter_{$site}");
			if($feedRes->numRows()) {

				// Get Bearer key
				if($bearer === null) {
					$consumer = cfGetApiKey::twitterConsumerKey();
					$secret = cfGetApiKey::twitterSecret();

					if($consumer && $secret) {
						$http = new flHttpClient('https://api.twitter.com/oauth2/token');
						$http->setAuth($consumer, $secret);
						$http->setPostData(array('grant_type' => 'client_credentials'));
						if($http->sendRequest('POST') && $http->getResponseCode() == 200)
							$bearer = json_decode($http->getBody());
					}
				}

				// If have a bearer key then collect the data for each feed
				if($bearer !== null) {
					$http = new flHttpClient();
					$http->addHeader('Authorization', 'Bearer ' . $bearer->access_token);

					// For each feed collect the data
					while($feed = $feedRes->fetch()) {
						// Fetch all feeds
						$http->setUri('https://api.twitter.com/1.1/statuses/user_timeline.json?' . http_build_query(array(
							'screen_name' => $feed['screenname'],
							'count' => $feed['tweetcount'],
							'exclude_replies' => $feed['exreplies'],
							'include_rts' => '1')));
						if($http->sendRequest('GET') && $http->getResponseCode() == 200)
							$db->update("cf_socialtwitter_{$site}", array('feedcache' => $http->getBody()), 'screenname=?', $feed['screenname']);
					}
				}
			}
		}
	}
}
