<?php
/**
 * @copyright (C) 2013 iJoomla, Inc. - All rights reserved.
 * @license GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html)
 * @author iJoomla.com <webmaster@ijoomla.com>
 * @url https://www.jomsocial.com/license-agreement
 * The PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript *are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0
 * More info at https://www.jomsocial.com/license-agreement
 */
// no direct access
defined('_JEXEC') or die('Restricted access');

require_once( JPATH_ROOT . '/components/com_community/libraries/core.php');

if (!class_exists('plgCommunityTwitter')) {

    class plgCommunityTwitter extends CApplications {

        public $name = "Twitter";
        public $_name = 'twitter';
        public $_path = '';
        public $timelines = array(
            'public' => '1.1/statuses/public_timeline.json',
            'friends' => '1.1/statuses/friends_timeline.json',
            'home' => '1.1/statuses/home_timeline.json',
            'user' => '1.1/statuses/user_timeline.json',
            'update' => '1.1/statuses/update.json'
        );
        public $users = array(
            'show' => '1.1/users/show.json'
        );

        static public function getConsumer() {
            static $consumer = null;

            if (is_null($consumer)) {
                $my = CFactory::getUser();
                //$consumer = new Zend_Oauth_Consumer(self::getConfiguration());
                $configuration = self::getConfiguration();
                //$consumer = new TwitterOAuth( $configuration['consumerKey'],$configuration['consumerSecret'] );
                $consumer = new tmhOAuth(self::getConfiguration());
            }

            return $consumer;
        }

        static public function getConfiguration($userid = '') {
            static $configuration = null;

            if (is_null($configuration)) {
                $plugin = JPluginHelper::getPlugin('community', 'twitter');
                $params = new CParameter($plugin->params);
                $my = CFactory::getUser($userid);

                $oauth = JTable::getInstance('Oauth', 'CTable');
                $loaded = $oauth->load($my->id, 'twitter');
                $accesstoken = unserialize($oauth->accesstoken);

                $consumer_key = $params->get('consumerKey');
                $consumer_secret = $params->get('consumerSecret');

                $configuration = array(
                    'consumer_key' => $consumer_key,
                    'consumer_secret' => $consumer_secret,
                    'user_token' => $accesstoken['oauth_token'],
                    'user_secret' => $accesstoken['oauth_token_secret'],
                    'bearer'          => base64_encode($consumer_key.':'.$consumer_secret),
                    'curl_ssl_verifypeer' => true
                );
            }
            return $configuration;
        }

        public function onProfileDisplay() {
            JPlugin::loadLanguage('plg_community_twitter', JPATH_ADMINISTRATOR);

            $user = CFactory::getRequestUser();

            $document = JFactory::getDocument();
            $css = JURI::base() . 'plugins/community/twitter/twitter/style.css';
            $document->addStyleSheet($css);

            $my = CFactory::getUser();
            $oauth = JTable::getInstance('Oauth', 'CTable');

            if (!$oauth->load($user->id, 'twitter')) {
                return JText::_('PLG_TWITTER_NOT_SET');
            }

            return $this->_getTwitterHTML($user->id);
        }

        protected function _getTwitterHTML($userId) {
            $this->loadUserParams();

            $my = CFactory::getUser($userId);
            $this->userparams = $my->getAppParams($this->_name);

            $showFriends = $this->userparams->get('showFriends', false);
            $oauth = JTable::getInstance('Oauth', 'CTable');
            $loaded = $oauth->load($my->id, 'twitter');
            $accesstoken = unserialize($oauth->accesstoken);

            ob_start();

            $accountId = $this->userparams->get('accountid');
            $client = new tmhOAuth(self::getConfiguration($my->id));

            if(!empty($accountId) && ($accountId || $accountId != '')){
            ?>
                <div class="content-nopost">
                    <a class="twitter-timeline" style="text-decoration: none; cursor: default; color: black" data-height="470" data-theme="light"  href="https://twitter.com/<?php echo $accountId ?>?ref_src=twsrc%5Etfw">Twitter by <?php echo $accountId ?></a> 
                    <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> 
                </div>
            <?php }else{ ?>
                <div class="content-nopost">
                    <?php echo JText::_('PLG_TWITTER_NOT_UPDATES'); ?>
                </div>
            <?php } ?>

            <?php
            $html = ob_get_contents();
            ob_end_clean();

            return $html;
        }

        static public function replaceAliasURL($message) {
            $pattern = '/@(("(.*)")|([A-Z0-9][A-Z0-9_-]+)([A-Z0-9][A-Z0-9_-]+))/i';

            preg_match_all($pattern, $message, $matches);

            if (isset($matches[0]) && !empty($matches[0])) {
                //CFactory::load('helpers', 'user');
                //CFactory::load('helpers', 'linkgenerator');

                $usernames = $matches[0];

                for ($i = 0; $i < count($usernames); $i++) {
                    $username = $usernames[$i];
                    $username = JString::str_ireplace('"', '', $username);
                    $username = explode('@', $username);
                    $username = $username[1];

                    $message = JString::str_ireplace($username, '<a href="http://twitter.com/' . $username . '" target="_blank" rel="nofollow">' . $username . '</a>', $message);
                }
            }

            return $message;
        }

        function onProfileStatusUpdate($userid, $old_status, $new_status) {
            $my = CFactory::getUser($userid);
            $this->userparams = $my->getAppParams($this->_name);
            $updateTwitter = $this->userparams->get('updateTwitter', 0);
            if ($updateTwitter) {
                $plugin = JPluginHelper::getPlugin('community', 'twitter');
                $params = new CParameter($plugin->params);
                $my = CFactory::getUser($userid);
                $oauth = JTable::getInstance('Oauth', 'CTable');
                $loaded = $oauth->load($my->id, 'twitter');
                $accesstoken = unserialize($oauth->accesstoken);
                if ($loaded && !is_null($accesstoken) && !empty($accesstoken)) {
                    $client = new tmhOAuth(self::getConfiguration());

                    $code = $client->request('POST', $client->url($this->timelines['update']), array(
                        'status' => $new_status
                    ));
                }
            }
        }

    }

}

