<?php
/**
* @version		1.0
* @license		GNU/GPL 2.1
* @author		David Jonas
*/

// no direct access to this file
defined( '_JEXEC' ) or die( 'Restricted access' );

//Import JPlugin
jimport( 'joomla.plugin.plugin' );
require_once (JPATH_ROOT . DS . 'plugins' . DS . 'system' . DS . 'facebook-platform' . DS . 'php' . DS . 'facebook.php');
require_once (JPATH_ROOT . DS . 'components' . DS . 'com_content' . DS . 'helpers' . DS . 'route.php');

/**
 * AutoFacebook is a plugin that automatically posts new content on a Joomla! site to a facebook
 * account. 
 */
class plgSystemAutofacebook extends JPlugin
{
	protected $api_key = '';
	protected $secret  = '';
	protected $static_text	= '';
	protected $static_text_pos	= 0;
	protected $limit = 255;
	protected $post_modified = 0;
	protected $uid = '';

	/**
	 * Constructor
	 *
	 * @access	protected
	 * @param	object	$subject The object to observe
	 * @param 	array   $config  An array that holds the plugin configuration
	 * @since	1.0
	 */
	 
	 private function getSection($id)
	{
		$row =& JTable::getInstance('section');
		$row->load($id);

		return $row;
	}
	
	private function getCategory($id)
	{
		$row =& JTable::getInstance('category');
		$row->load($id);

		return $row;
	}
	
	// Helps with the Joomla url hell and creates corect url safeley.
	// Different cases for routing: frontend, backend, joomla not installed in route
	// Courtesy of AutoTweet
	 function fm_create_url($site_url)
	{
		// remove administrator string from path, if post is from backend (this is hell, why is joomla 1.5 routing and 				        basepath different in front- and backend?)
		$base_uri = JURI::base();
		$del_pos = JString::strrpos($base_uri, '/administrator/');
		if (FALSE === $del_pos) {
			// if access is form front end get only domain by this function, because routing returns roor foolder
			// [TODO]	make this more failsave for later joomla version (if they correct this, i will have trouble here!	
			$baseurl = JURI::getInstance()->toString(array ('scheme', 'host', 'port'));
		}
		else {
			$baseurl = substr_replace($base_uri, '', $del_pos);
		}
	
		// Joomla bug: different value for backend and frontend post (one with slash): correct this safely
		if ('/' != substr($site_url, 0, 1)) {
			// remove slash at the beginning                   
			$site_url = '/' . $site_url;
		}
	
		$url = $baseurl . $site_url;
		
		return $url;
	}

	function getURL($article)
	{
			$sec =& $this->getSection($article->sectionid);
			$cat =& $this->getCategory($article->catid);
			
			$sec_name	= '';
			$cat_name	= '';
			$sec_slug	= 0;
			$cat_slug	= 0;
			$id_slug	= $article->id . ':' . JFilterOutput::stringURLSafe($article->alias);			

			// post also correct url for article without section/category!
			if ($sec && $cat && (0 < $sec->id) && (0 < $cat->id)) {
				$sec_name = $sec->title;
				$cat_name = $cat->title;
				$sec_slug = $sec->id . ':' . JFilterOutput::stringURLSafe($sec->alias);
				$cat_slug = $cat->id . ':' . JFilterOutput::stringURLSafe($cat->alias);
			}
			
			// create url savely
			$article_url = JRoute::_(ContentHelperRoute::getArticleRoute($id_slug, $cat_slug, $sec_slug));
			$del_pos = JString::strrpos($article_url, '&amp;Itemid=');
			if (('' ==  $cat_name) && $del_pos) {
				// corrections for uncategorized articles (remove itemid from url)
				$article_url = substr_replace($article_url, '', $del_pos);
				$article_url = urldecode($article_url);
			}			
			$url = $this->fm_create_url($article_url);
			
			return $url;
	}		
	 
	function plgSystemAutofacebook( &$subject, $params  )
	{
		global $mainframe;
		parent::__construct( $subject, $params  );

		// Get Plugin info
		$plugin			=& JPluginHelper::getPlugin('system', 'autofacebook');
		$pluginParams	= new JParameter($plugin->params);

		//populate this class
		$this->api_key = $pluginParams->get('api_key', '');
		$this->secret = $pluginParams->get('secret', '');
		$this->post_modified = (int)$pluginParams->get('post_modified', 0);
		$this->uid = $pluginParams->get('uid', '');
		$this->static_text = $pluginParams->get('static_text', '');
		$this->static_text_pos = (int)$pluginParams->get('static_text_pos', 0);
		$this->include_link = (int)$pluginParams->get('include_link', 0);
	}

	function postMessage($article, $facebook)
	{
		global $mainframe;
		
		//Prepare the text
		$doPost = true;
		$title = $article->title;
		$msg = '';
		$url = $this->getURL($article);
		
		if($this->static_text != '')
		{
			switch($this->static_text_pos)
			{
				case 0:
					$msg = $title;
					break;
				case 1:
					$msg = $this->static_text.' '.$title;
					break;
				case 2:
					$msg = $title.' '.$this->static_text;
					break;
			}
		}
		else
		{
			$msg = $title;
		}
		
		if($this->include_link == 1)
		{
			$msg .= ' - '.$url;
		}
		
		try
		{
			if($facebook->api_client->users_hasAppPermission("publish_stream", $this->uid))
			{
				$facebook->api_client->stream_publish($msg, null, null, null, $this->uid);
				$mainframe->enqueueMessage('AutoFacebook - Facebook status has been updated!');
			}
			else
			{
				JError::raiseWarning('1', "You have no permission to set the status of this user");
				JError::raiseWarning('1', "To grant permition to the application login to facebook and visit:");
				JError::raiseWarning('1', "http://www.facebook.com/connect/prompt_permissions.php?api_key=".$this->api_key."&v=1.0&next=http://www.facebook.com/connect/login_success.html?xxRESULTTOKENxx&display=popup&ext_perm=read_stream,publish_stream,offline_access&enable_profile_selector=1&profile_selector_ids=".$this->uid);
			}
		}
		catch(Exception $e)
		{
			JError::raiseWarning('1', ' - AutoFacebook error - ' . $e->getMessage());
		}
	}

	/**
	 * Run the plugin when onAfterContentSave is triggered 
	 */
	function onAfterContentSave( &$article, $isNew )
	{
	    global $mainframe;
		//Check if AutoFacebook is configured
		if($this->api_key == '' || $this->secret == '' || $this->uid == '')
		{
			JError::raiseWarning('1', ' - AutoFacebook error - AutoFacebook is not configured properly. Please go to Plugin Manager and add your facebook API key, API secret and User ID');
			return false;
		}
		
		//Check if content is published
		if(($isNew	|| $this->post_modified) && ($article->state == 1))
		{
			$facebook = new Facebook($this->api_key, $this->secret);			
			$this->postMessage($article, $facebook);
		}
		
		return true;
	}
}
?>