<?php

/******************************************************************************
 *
 *	PROJECT: Flynax Classifieds Software
 *	VERSION: 4.X
 *	LICENSE: FL4HLD2A8696 - http://www.flynax.com/license-agreement.html
 *	PRODUCT: Real Estate Agency
 *	DOMAIN: gevimmo.com
 *	FILE: RLBOOKMARKS.CLASS.PHP
 *
 *	The software is a commercial product delivered under single, non-exclusive,
 *	non-transferable license for one domain or IP address. Therefore distribution,
 *	sale or transfer of the file in whole or in part without permission of Flynax
 *	respective owners is considered to be illegal and breach of Flynax License End
 *	User Agreement.
 *
 *	You are not allowed to remove this information from the file without permission
 *	of Flynax respective owners.
 *
 *	Flynax Classifieds Software 2017 |  All copyrights reserved.
 *
 *	http://www.flynax.com/
 *
 ******************************************************************************/

class rlBookmarks extends reefless
{
	/**
	* @var services - addone services list
	**/
	var $services = array(
		'google_plusone' => 'Google Plus',
		'facebook_like' => 'Facebook Like',
		'tweet' => 'Tweet',
		'counter' => 'AddThis Counter',
		
		'compact' => 'AddThis Button',
		'facebook' => 'Facebook',
		'twitter' => 'Twitter',
		'email' => 'Email',
		'print' => 'Print',
		'google' => 'Google',
		'myspace' => 'MySpace',
		'stumbleupon' => 'StumbleUpon',
		'favorites' => 'Favorites',
		'live' => 'Messenger',
		'delicious' => 'Delicious',
		'digg' => 'Digg',
		'orkut' => 'orkut',
		'blogger' => 'Blogger',
		'gmail' => 'Gmail',
		'yahoomail' => 'Y! Mail',
		'reddit' => 'Reddit',
		'vk' => 'vk.com',
		'aim' => 'Aol Lifestream',
		'meneame' => 'Meneame',
		'mailto' => 'Email App',
		'googlebuzz' => 'Google Buzz',
		'hotmail' => 'Hotmail',
		'linkedin' => 'LinkedIn',
		'yahoobkm' => 'Y! Buzz',
		'viadeo' => 'Viadeo',
		'aolmail' => 'AOL Mail',
		'friendfeed' => 'FriendFeed',
		'tumblr' => 'tumblr',
		'friendster' => 'Friendster',
		'baidu' => 'Baidu',
		'wordpress' => 'Wordpress',
		'yahoobkm' => 'Y! Bookmarks',
		'100zakladok' => '100zakladok',
		'misterwong_de' => 'Mister Wong DE',
		'hyves' => 'Hyves',
		'sonico' => 'Sonico',
		'amazonwishlist' => 'Amazon',
		'bebo' => 'Bebo',
		'bitly' => 'Bit.ly',
		'addio' => 'Add.io',
		'bobrdobr' => 'Bobrdobr',
		'adifni' => 'Adifni',
		'dotnetshoutout' => 'DotNetShoutout',
		'2tag' => '2 Tag',
		'googlereader' => 'Google Reader',
		'studivz' => 'studiVZ',
		'fark' => 'Fark',
		'livejournal' => 'LiveJournal',
		'allmyfaves' => 'All My Faves',
		'oyyla' => 'Oyyla'
	);
	
	/**
	* @var bookmarks - bookmark types
	**/
	var $bookmarks = array(
		'googleplus_like_tweet' => array(
			'Key' => 'googleplus_like_tweet',
			'Name' => 'bsh_googleplus_like_tweet',
			'Align' => true,
			'Services' => array(
				'counter',
				'google_plusone',
				'facebook_like',
				'tweet'
			)
		),
		'floating_bar' => array(
			'Key' => 'floating_bar',
			'Name' => 'bsh_floating_bar',
			'Align' => true,
			'Services' => true,
			'Color' => true
		),
		'vertical_share_counter' => array(
			'Key' => 'vertical_share_counter',
			'Name' => 'bsh_vertical_share_counter',
			'Align' => true
		),
		'horizontal_share_counter' => array(
			'Key' => 'horizontal_share_counter',
			'Name' => 'bsh_horizontal_share_counter',
			'Align' => true
		),
		'tweet_like_share' => array(
			'Key' => 'tweet_like_share',
			'Name' => 'bsh_tweet_like_share',
			'Align' => true
		),
		'toolbox_facebook_like' => array(
			'Key' => 'toolbox_facebook_like',
			'Name' => 'bsh_toolbox_facebook_like',
			'Align' => true,
			'Services' => true
		),
		'32x32_icons_addthis' => array(
			'Key' => '32x32_icons_addthis',
			'Name' => 'bsh_32x32_icons_addthis',
			'Align' => true,
			'Services' => true
		),
		'64x64_icons_aquaticus' => array(
			'Key' => '64x64_icons_aquaticus',
			'Name' => 'bsh_64x64_icons_aquaticus',
			'Align' => true,
			'Services' => array(
				'compact',
				'facebook',
				'twitter',
				'myspace',
				'stumbleupon',
				'delicious',
				'reddit'
			)
		),
		'css3_share_buttons' => array(
			'Key' => 'css3_share_buttons',
			'Name' => 'bsh_css3_share_buttons',
			'Align' => true,
			'Color' => true
		),
		'32x32_vertical_icons' => array(
			'Key' => '32x32_vertical_icons',
			'Name' => 'bsh_32x32_vertical_icons',
			'Align' => true,
			'Services' => true
		),
		'share_button' => array(
			'Key' => 'share_button',
			'Name' => 'bsh_share_button',
			'Align' => true
		),
		'vertical_layout_menu' => array(
			'Key' => 'vertical_layout_menu',
			'Name' => 'bsh_vertical_layout_menu',
			'Align' => true,
			'Color' => true,
			'Services' => true
		)/*,
		'wibiya_bar' => array(
			'Key' => 'wibiya_bar',
			'Name' => 'bsh_wibiya_bar'
		)*/
	);
	
	/**
	* delete bookmark block
	*
	* @package ajax
	*
	* @param string $ID - bookmark block ID
	*
	**/
	function ajaxDeleteBookmark( $id )
	{
		global $_response, $lang;

		// check admin session expire
		if ( $this -> checkSessionExpire() === false )
		{
			$redirect_url = RL_URL_HOME . ADMIN ."/index.php";
			$redirect_url .= empty($_SERVER['QUERY_STRING']) ? '?session_expired' : '?'. $_SERVER['QUERY_STRING'] .'&session_expired';
			$_response -> redirect( $redirect_url );
		}
		
		$id = (int)$id;
		
		$key = $this -> getOne('Key', "`ID` = {$id}", 'bookmarks');
		
		/* remove bookmark entry */
		$sql = "DELETE FROM `". RL_DBPREFIX ."bookmarks` WHERE `Key` = '{$key}' LIMIT 1";
		$this -> query($sql);
		
		/* remove block entry */
		$sql = "DELETE FROM `". RL_DBPREFIX ."blocks` WHERE `Key` = 'bookmark_{$key}' LIMIT 1";
		$this -> query($sql);
		
		/* remove block entry */
		$sql = "DELETE FROM `". RL_DBPREFIX ."lang_keys` WHERE `Key` = 'blocks+name+bookmark_{$key}'";
		$this -> query($sql);
		
		$_response -> script("
			bookmarkGrid.reload();
			printMessage('notice', '{$lang['block_deleted']}');
		");

		return $_response;
	}


	/*** Twitter ***/


    /**
     * @hook afterListingDone
     */
    public function hookAfterListingDone()
    {
        global $listing_id, $listing_title, $listing_data, $update_status, $pages, $category, $listing_type;

        $this->preparePost2twitter(array(
            'status'        => $update_status['fields']['Status'],
            'page_path'     => $pages[$listing_type['Page_key']],
            'photo'         => $listing_data['Main_photo'],
            'category_path' => $category['Path'],
            'title'         => $listing_title,
            'listing_id'    => $listing_id,
        ));
    }

    /**
     * @hook postPaymentComplete
     */
    public function hookPostPaymentComplete($data)
    {
        $listing_id = (int) $data['item_id'];
        $listing = $this->fetch('*', array('ID' => $listing_id), null, null, 'listings', 'row');

        $_fetch = array('fields' => array('Path', 'Type'), 'where' => array('ID' => $listing['Category_ID']));
        $category = $this->fetch($_fetch['fields'], $_fetch['where'], null, null, 'categories', 'row');

        $l_type = $GLOBALS['rlListingTypes']->types[$category['Type']];
        $listing_title = $GLOBALS['rlListings']->getListingTitle($listing['Category_ID'], $listing, $l_type['Key']);

        $this->preparePost2twitter(array(
            'status'        => 'active',
            'page_path'     => $GLOBALS['pages'][$l_type['Page_key']],
            'photo'         => $listing['Main_photo'],
            'category_path' => $category['Path'],
            'title'         => $listing_title,
            'listing_id'    => $listing_id,
        ));
    }

    /**
     * @hook apPhpListingsAfterAdd
     */
    public function hookApPhpListingsAfterAdd()
    {
        global $listing_id, $status, $data, $listing_type, $category, $pages;

        $listing_title = $GLOBALS['rlListings']->getListingTitle($category['ID'], $data, $listing_type['Key']);
        $main_photo = $this->getOne('Main_photo', "`ID` = {$listing_id}", 'listings');

        $this->preparePost2twitter(array(
            'status'        => $status,
            'page_path'     => $pages[$listing_type['Page_key']],
            'photo'         => $main_photo,
            'category_path' => $category['Path'],
            'title'         => $listing_title,
            'listing_id'    => $listing_id,
        ));
    }

    /**
     * Prepare Twitter post to publishing
     * 
     * @since 3.1.5
     * 
     * @see self::hookAfterListingDone
     * @see self::hookPostPaymentComplete
     * @see self::hookApPhpListingsAfterAdd
     * 
     * @param array $data - Required data to prepare the Twitter post
     */
    private function preparePost2twitter($data)
    {
        if ($data['status'] != 'active') {
            return;
        }
        $thumbnail = false;

        if (!empty($data['photo']) && file_exists(RL_FILES . $data['photo'])) {
            $thumbnail = RL_FILES . $data['photo'];
        }

        $listing_id = (int) $data['listing_id'];
        $link = RL_URL_HOME;

        if ($GLOBALS['config']['mod_rewrite']) {
            $link .= sprintf(
                '%s/%s/%s-%d.html',
                $data['page_path'],
                $data['category_path'],
                $GLOBALS['rlSmarty']->str2path($data['title']),
                $listing_id
            );
        } else {
            $link .= 'index.php?page=' . $pages[$listing_type['Page_key']] . '&id=' . $listing_id;
        }

        $this->post2twitter($data['title'], $link, $thumbnail);
    }

	/**
	 * Post to Twitter Timeline
	 *
	 * @param string $message
	 * @param string $link
	 * @param string $image
	 */
	function post2twitter($message = false, $link = false, $image = false) {
		global $config;

		if (empty($config['bookmarks_twitter_api_key'])    || 
			empty($config['bookmarks_twitter_api_secret']) || 
			empty($config['bookmarks_twitter_token'])      || 
			empty($config['bookmarks_twitter_token_secret'])
		) {
			return $this->twitLogger('API keys doesn\'t configured properly', true);
		}

		if (empty($message))
			return $this->twitLogger('Message is empty');


		$twitter_src = RL_PLUGINS . 'bookmarks' . RL_DS . 'libs' . RL_DS;

		if (!file_exists($twitter_src . 'tmhOAuth.php'))
			return $this->twitLogger('tmhOAuth lib doesn\'t exists.', true);

		else if (!file_exists($twitter_src . 'cacert.pem'))
			return $this->twitLogger('cacert.pem doesn\'t exists.', true);


		require_once($twitter_src . 'tmhOAuth.php');

		$tmhOAuth = new tmhOAuth(array(
		    'consumer_key'    => $config['bookmarks_twitter_api_key'],
		    'consumer_secret' => $config['bookmarks_twitter_api_secret'],
		    'token'           => $config['bookmarks_twitter_token'],
		    'secret'          => $config['bookmarks_twitter_token_secret']
		));

		$command['status'] = "{$message}\n{$link}";
		$command_url = $tmhOAuth->url('1.1/statuses/update');

		if ($image !== false) {
			list($img_width, $img_height) = @getimagesize($image);

			if (is_int($img_width) && $img_width > 0) {
				$command['media[]'] = file_get_contents($image);
				$command_url = $tmhOAuth->url('1.1/statuses/update_with_media');
			}
		}

		$code = $tmhOAuth->request('POST', $command_url, $command, true, true);

		if ($code !== 200)
			return $this->twitLogger('Post to twitter failed! error_code: '. $code);

		return true;
	}

	/**
	 * Logger for Twitter API purposes
	 * 
	 * @since v3.1.1
	 * @param string $message - some message for logging
	 * @param bool $turnOffAPI - trigger
	 */
	function twitLogger($message = null, $turnOffAPI = false) {
		$GLOBALS['rlDebug']->logger('post2twitter: ' . $message);

		if ($turnOffAPI === true)
			$GLOBALS['rlConfig']->setConfig('bookmarks_twitter_api_use_module', 0);

		return false;
	}
}
