Location: PHPKode > projects > Zzap > zzap/app/plugins/twitter/twitterFetch.php
<?php
/**
 * zzap group messaging / microblogging
 * 
 * Copyright (C) 2008 Dirk Ollmetzer
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @package Zzap
 * @subpackage Plugins
 * @author Dirk Ollmetzer <hide@address.com>
 * @copyright 2008 Dirk Ollmetzer
 * @version $Id: twitterFetch.php 148 2008-10-27 20:37:34Z dollmetzer $
 * @license GPLv3 http://www.gnu.org/copyleft/gpl.html
 */

require_once PATH_APP.'models/userModel.php';
require_once PATH_APP.'models/userDetailModel.php';
require_once PATH_APP.'models/userContactModel.php';
require_once PATH_APP.'models/companionModel.php';
require_once PATH_APP.'models/messageModel.php';
require_once PATH_APP.'plugins/twitter/twitterModel.php';
require_once PATH_APP.'plugins/twitter/twitterLib.php';


/**
 * Class for fetching contacts and messages from a twitter account.
 * It uses teh twitterapi to fetch the 20 most recent tweets from
 * a friend timeline.
 *
 * @package Zzap
 * @subpackage Plugins
 * @author Dirk Ollmetzer <hide@address.com>
 * @copyright 2008 Dirk Ollmetzer
 * @version $Id: twitterFetch.php 148 2008-10-27 20:37:34Z dollmetzer $
 */
class twitterFetch {
	
	/**
	 * Constructor
	 */
	//public function __construct($name, $password, $lastupdate=0) {
	public function __construct() {
	}

	
	
	/**
	 * Gets friends timeline from twitter an processes it.
	 * Checks, if all friends are already remoteusers of zzap.
	 * Inserts the missing friends and inserts the messages.
	 * 
	 * @param array $user data of the user, whose twitter friends timeline should be checked
	 */
	public function refresh($user) {
				
		$twitterModel = new twitterModel();
		$twitterData = $twitterModel->getTwitterByUser($user['id']);
		
		// skip, if user has no twitteraccount
		if(sizeof($twitterData) == 0) {
			return;
		}
		
		// skip, if pulling twitter is unwanted
		if($twitterData['pull'] == 0) {
			return;
		}
		
		// skip, if last refresh is not long enough ago 
		$refreshEvery = $GLOBALS['application']->setup['external']['twitter']['refreshEvery'] * 60;
		$distance = time() - $twitterData['twitterfetch'];
		if($distance < $refreshEvery) {
			return;
		}
		
		// Okay, let's go...
		// First update 'last checked' timestamp for the user
		$twitterModel->updateLastChecked($user['id'], time());

		// fetch the list as XML
		$twitterLib = new TwitterLib($twitterData['twittername'], $twitterData['twitterpass']);
		$list = $twitterLib->getFriendsTimeline($twitterData['twittername']);
		if($list == NULL) {
			return;
		}
		$xml = simplexml_load_string($list);

		// create List of authors
		$authors = array();
		foreach($xml->status as $status) {
			$screenName = strval($status->user->screen_name);
			if($screenName != $twitterData['twittername']) {
				$authors[$screenName] = array(
					'id'          => 0,
					'name'        => strval($status->user->name),
					'location'    => strval($status->user->location),
					'description' => strval($status->user->description),
					'picture'     => strval($status->user->profile_image_url),
					'url'         => strval($status->user->url)
				);
			}
		}
		/*
		echo "<pre>\n";
		print_r($authors);
		//var_dump($xml);
		echo "</pre>\n<hr />\n";
		*/
		
		// check, if every author is in DB and add the userid in the autorlist
		$userModel = new userModel();
		$userDetailModel = new userDetailModel();
		$userContactModel = new userContactModel();
		foreach($authors as $handle=>$data) {
			$user = $userModel->getUser($handle.'@twitter', true);
			if(isset($user['id'])) {
				// known user - take id only, if user is not blocked
				if($user['status'] == 1) {
					$authors[$handle]['id'] = $user['id'];
					$dbSet = "fullname='".$data['name']."', city='".$data['location']."'";
					$userDetailModel->updateUserDetail($user['id'], $dbSet);
					$userDetailModel->updatePicture($user['id'], $data['picture']);
					$url = preg_replace('/^https:\/\//', '', $data['url']);
					$url = preg_replace('/^http:\/\//', '', $url);
					$userContactModel->updateUserContact($user['id'], "web='$url'");
				} else {
					$authors[$handle]['id'] = 0;
				}
			} else {
				// unknown user - create
				$newUserId = $userModel->createUser($handle.'@twitter', '');
				$authors[$handle]['id'] = $newUserId;
				$dbSet = "fullname='".$data['name']."', city='".$data['location']."'";
				$userDetailModel->updateUserDetail($newUserId, $dbSet);
				$userDetailModel->updatePicture($newUserId, $data['picture']);
				$url = preg_replace('/^https:\/\//', '', $data['url']);
				$url = preg_replace('/^http:\/\//', '', $url);
				$userContactModel->updateUserContact($newUserId, "web='$url'");
			}
		}


		// check, if author marked as companion
		$companionModel = new companionModel();
		foreach($authors as $handle=>$data) {
			if(!$companionModel->isCompanion($GLOBALS['session']->get('user_id'), $data['id'], true)) {
				$companionModel->follow($GLOBALS['session']->get('user_id'), $data['id']);
			}
		}

		$month = array(
			'Jan'=>1,
			'Feb'=>2,
			'Mar'=>3,
			'Apr'=>4,
			'May'=>5,
			'Jun'=>6,
			'Jul'=>7,
			'Aug'=>8,
			'Sep'=>9,
			'Oct'=>10,
			'Nov'=>11,
			'Dec'=>12,
		);		
		$messageModel = new messageModel();
		foreach($xml->status as $status) {
			$screenName = strval($status->user->screen_name);
			if($screenName != $twitterData['twittername']) {
				/*
				echo "\n<br />\nINSERT:<br />\n";
				echo "Datum : ".$status->created_at."<br />\n";
				echo "User ID :".$authors[$screenName]['id']."<br />";
				echo "Foreign ID : ".$status->id."<br />\n";
				echo "Text : ".$status->text."<br />\n";
				*/
				
				$GLOBALS['application']->writeLog('Twitter Plugin :: Original timestamp'.$status->created_at, 'messageProcess');
				
				$temp = explode(' ', $status->created_at);
				$time = explode(':', $temp[3]);
				$timestamp = gmmktime($time[0], $time[1], $time[2], $month[$temp[1]], $temp[2], $temp[5] );
				
				// now correct the timecorrection... *phew*
				// timecorrection in timestamp ($temp[4] as '+0000')
				$tc_hours = (int) substr($temp[4], 1, 2);
				if(substr($temp[4], 0, 1) == '+') {
					$timeDiff += 3600 * $tc_hours;
					$GLOBALS['application']->writeLog('Twitter Plugin :: timestamp correction + '.$tc_hours.' hours', 'messageProcess');
				} else if(substr($temp[4], 0, 1) == '-') {
					$timeDiff -= 3600 * $tc_hours;
					$GLOBALS['application']->writeLog('Twitter Plugin :: timestamp correction - '.$tc_hours.' hours', 'messageProcess');
				}
				
				$messageModel->setMessage($status->text, $authors[$screenName]['id'], $status->id, 0, 0, $timestamp);
				//echo $status->created_at." -> $timestamp<br />\n";
			}
		}
	} /* refresh($user) */
	

	
	/**
	 * Get the difference in seconds to a given timezone
	 * 
	 * @param string $timeZone   e.g. 'cet' for central european time
	 * @param string $timeZoneId e.g. 'Europe/Berlin'
	 * 
	 * @return integer Difference in seconds. If negative, an error occured:
	 *                 -1 = Timezone not foundd
	 *                 -2 = Timezone ID not found
	 *                 -3 = Timezone and timezone id don't match
	 */
	protected function getTimeDiff($timeZone, $timeZoneId) {
		$timediff = -3; // default: timezone and timezoneid don't match
		$tzlist = timezone_abbreviations_list();
		$timezone_identifiers = DateTimeZone::listIdentifiers();
		
		if(!in_array($timeZone, array_keys($tzlist))) {
			$timediff = -1; // Timezone not found
		}
		if(!in_array($timeZoneId, $timezone_identifiers)) {
			$timediff = -2; // Timezone Id not found
		}
		
		for($i=0; $i<sizeof($tzlist[$timeZone]); $i++) {
			if($tzlist[$timeZone][$i]['timezone_id'] == $timeZoneId) {
				$timediff = $tzlist[$timeZone][$i]['offset'];
			}
		}
		
		return $timediff;
	} /* getTimeDiff($timeZone, $timeZoneId) */
	
}
?>
Return current item: Zzap