<?php
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );

class plgContentAllarticleannounce extends JPlugin
{

	function plgContentAllarticleannounce( &$subject, $config )
	{
		parent::__construct( $subject, $config );

		// Do some extra initialisation in this constructor if required
	}

	/**
	 * Do something onAfterInitialise 
	 */
	function onAfterContentSave( &$article, $isNew )
	{
		global $mainframe;
		$this->publish_article( $article, $isNew );
		return true;
	}
	function onBeforeDisplayContent( &$article, &$params, $limitstart )
	{
		global $mainframe;
		return '';
	}
	
	function publish_article($article, $isNew)
	{
		global $mainframe;
		$plugin	=& JPluginHelper::getPlugin('content', 'allArticleAnnounce');
		$params=new JParameter( $plugin->params );
		$db		=& JFactory::getDBO();
		$query="select count(content_id) from #__content_allarticleannounce where content_id='".$article->id."'";
		$db->setQuery($query);
		$result=$db->loadResult();
		if($isNew || $result=='0')
		{
			$query=" INSERT INTO `#__content_allarticleannounce` (`content_id`,`published_f`,`published_t`)  VALUES ('".$article->id."','0','0') ";
			$db->setQuery($query);
			$db->query();
		}
		// on/off switch //
		$query='select * from #__content_allarticleannounce_switch limit 1';
		$db->setQuery($query);
		$result=$db->loadObject();
		$content_type=$result->content_type;
		$query="update `#__content_allarticleannounce` set `facebook_on`='".$result->facebook."',`twitter_on`='".$result->twitter."' where content_id='".$article->id."'";
		$db->setQuery($query);
		$db->query();
		// on/off switch//
		// config //
		$query="select * from #__content_allarticleannounce_config";
		$db->setQuery($query);
		// config //
		$config=$db->loadObject();
		if($content_type=='0')
		{
			// use global setting
			$content_type=($config->content_type=='0')?1:2;
		}
		if($content_type=='1')
		{
			// 80 chars
			$body=$article->introtext;
		}
		else
		{
			// metadesc
			$body=$article->metadesc;
		}
		$body=strip_tags($body);
		$body=substr($body,0,70);
		/*
		*  if the article has not been publish to websithe then publish the article to the website.
		*/
		$query="select * from #__content_allarticleannounce where content_id='".$article->id."'";
		$db->setQuery($query);
		$result= $db->loadObjectList();
		$msg='';
		if($article->state=='1')
		{
			$host=JURI::root().'index.php?option=com_allarticleannounce&format=raw&task=get_url&id='.$article->id;
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $host);
			curl_setopt($ch, CURLOPT_VERBOSE, 1);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT, 2 );
			curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
			curl_setopt($ch, CURLOPT_POST, 1);
			$url = curl_exec($ch);
			curl_close($ch);
			/* for debug */
			/*
			global $mainframe;
			$mainframe->enqueueMessage($url);
			*/
			// twitter 
			if($result[0]->published_t=='0'&&$result[0]->twitter_on=='1')
			{
				// check category //
				if($config->all_categories_t!='1')
				{
					$categories=explode(',',$config->category_option_t);
					$true=true;
					foreach($categories as $cat)
					{
						if($cat==$article->catid)
						{
							$true=false;
						}
					}
					if($true)
					{
						return true;
					}
				}
				// check category //
				if($config->publish_twitter=='1')
				{
					$num=$this->twitter_published($article,$config,$body,$url);
					if($num=='200')
					{
						$msg.=' Twitter status updated successfully. ';
						$query="update `#__content_allarticleannounce` set `published_t`='1',`published_t_date`='".date('Y-m-d')."' where content_id='".$article->id."'";
						$db->setQuery($query);
						$db->query();
					}
					else
					{
						$msg.='Error code:'.$num.'. Twitter status updated error. ';
					}
				}
			}
			// facebook
			if($result[0]->published_f=='0'&&$result[0]->facebook_on=='1')
			{
				// check category //
				if($config->all_categories_f!='1')
				{
					$categories=explode(',',$config->category_option_f);
					$true=true;
					foreach($categories as $cat)
					{
						if($cat==$article->catid)
						{
							$true=false;
						}
					}
					if($true)
					{
						return true;
					}
				}
				// check category //
				if($config->publish_facebook=='1')
				{
					$num=$this->facebook_published($article,$config,$body,$url);
					if($num=='0')
					{
						$msg.='Facebook updated successfully. ';
						$query="update `#__content_allarticleannounce` set `published_f`='1',`published_f_date`='".date('Y-m-d')."' where content_id='".$article->id."'";
						$db->setQuery($query);
						$db->query();
					}
					else
					{
						$msg.='Error code:'.$num.'. Facebook updated error. ';
					}
				}
			}
			
		}
		if($config->update_message=='1')
		{
			$mainframe->enqueueMessage($msg);
		}
	}
	
	function facebook_published($article,$config,$body,$url)
	{
		$website=JURI::root();
		$login_email=$config->username_f;
		$login_pass=$config->ps_f;
		$page_type=$config->page_type;//1 personal wall, 0 business page
		$page_id=$config->page_id;
		$message=$article->title.': ';
		$message.=$body.'...';
		//$url=$this->CompressURL($website.'index.php?option=com_content&view=article&id='.$article->id);
		$url=$website.$url;
		$message.='    '.$url;
		$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://login.facebook.com/login.php?m&amp;next=http%3A%2F%2Fm.facebook.com%2Fhome.php');
        curl_setopt($ch, CURLOPT_POSTFIELDS, 'email=' . urlencode($login_email) . '&pass=' . urlencode($login_pass) . '&login=' . urlencode("Log in"));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
		curl_setopt($ch, CURLOPT_TIMEOUT, $config->timeout ); 
	    curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");
        curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.12) Gecko/2009070611 Firefox/3.0.12");
        curl_exec($ch);
		$error= curl_error($ch);
		$error_num=curl_errno($ch);
		if($error_num != '0')
		{
			curl_close($ch);
			return $error;
		}
		if($page_type=='1') // publish to personal wall
		{
			curl_setopt($ch, CURLOPT_POST, 0);
			curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com/home.php');
			$page = curl_exec($ch);
			$error= curl_error($ch);
			$error_num=curl_errno($ch);
			if($error_num != '0')
			{
				curl_close($ch);
				return $error;
			}
			curl_setopt($ch, CURLOPT_POST, 1);
			preg_match("/input type=\"hidden\" name=\"post_form_id\" value=\"(.*?)\"/", $page, $form_id);
			preg_match("/form action=\"(.*?)\"/", $page, $form_num);
			curl_setopt($ch, CURLOPT_POSTFIELDS, 'post_form_id=' . $form_id[1] . '&status=' . urlencode($message) . '&update=' . urlencode("Update status"));
			curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com' . str_replace("amp;","",$form_num[1]));
			curl_exec($ch);
			$error= curl_error($ch);
			$error_num=curl_errno($ch);
			if($error_num != '0')
			{
				curl_close($ch);
				return $error;
			}
		}
		else if($page_type=='0') // publish to buiness page
		{
			$url='http://m.facebook.com/profile.php?id='.$page_id.'&refid=17&v=feed';
			curl_setopt($ch, CURLOPT_POST, 0);
			curl_setopt($ch, CURLOPT_URL,$url);
			$page = curl_exec($ch);
			$error= curl_error($ch);
			$error_num=curl_errno($ch);
			if($error_num != '0')
			{
				curl_close($ch);
				return $error;
			}
			curl_setopt($ch, CURLOPT_POST, 1);
			preg_match("/input type=\"hidden\" name=\"post_form_id\" value=\"(.*?)\"/", $page, $form_id);
			preg_match("/form action=\"(.*?)\"/", $page, $form_num);
			curl_setopt($ch, CURLOPT_POSTFIELDS, 'post_form_id=' . $form_id[1] . '&comment=' . urlencode($message) . '&post=' . urlencode("Post").'&fb_dtsg=9GZSy');
			curl_setopt($ch, CURLOPT_URL, 'http://m.facebook.com' .str_replace("amp;","",$form_num[1]));
			$page = curl_exec($ch);
			$error= curl_error($ch);
			$error_num=curl_errno($ch);
			if($error_num != '0')
			{
				curl_close($ch);
				return $error;
			}
		}
        curl_close($ch);
		$db		=& JFactory::getDBO();
		$query="update `#__content_allarticleannounce` set published_f_text='".$message."' where content_id='".$article->id."'";
		$db->setQuery($query);
		$db->query();
		return 0;
		
		
	}
	function twitter_published($article,$config,$body,$url)
	{
		$website=JURI::root();
		$username=$config->username_t;
		$password=$config->ps_t;
		$message=$article->title.': ';
		$message.=$body.'...';
		$url=$this->CompressURL($website.$url);
		$message.=' '.$url;
		$host = "http://twitter.com/statuses/update.xml?status=".urlencode(stripslashes(urldecode($message)));
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $host);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, $config->timeout ); 
		curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($ch, CURLOPT_POST, 1);
		$result = curl_exec($ch);
		// Look at the returned header
		$resultArray = curl_getinfo($ch);
		curl_close($ch);
		$db		=& JFactory::getDBO();
		$query="update `#__content_allarticleannounce` set published_t_text='".$message."' where content_id='".$article->id."'";
		$db->setQuery($query);
		$db->query();
		return $resultArray['http_code'];
	}
	function CompressURL($url) {

	  $ch = curl_init();

	  curl_setopt($ch, CURLOPT_URL, "http://to.ly/api.php?longurl=".urlencode($url));
	  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	  curl_setopt($ch, CURLOPT_HEADER, 0);

	  $shorturl = curl_exec ($ch);
	  curl_close ($ch);

	  return $shorturl;

	}
}