Advertisement
annukaka

ymClient.php

Aug 19th, 2016
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 35.43 KB | None | 0 0
  1. <?php
  2. /**
  3.  * YahooMessenger Api Client.
  4.  *
  5.  * @author    Bogdan Constantinescu <bog_con@yahoo.com>
  6.  * @copyright Copyright (c) 2013-2015 Bogdan Constantinescu
  7.  * @link      GitHub https://github.com/bogcon/yahoo-messenger-api
  8.  * @license   New BSD License (http://opensource.org/licenses/BSD-3-Clause);
  9.  *            see LICENSE.txt file that came along with this package.
  10.  */
  11. namespace app\libs;
  12.  
  13. class ymClient
  14. {
  15.     /**
  16.      * @var const string    Constants for APIs urls.
  17.      */
  18.  
  19.  
  20.     const URL_OAUTH_REQUEST_TOKEN    = 'https://login.yahoo.com/WSLogin/V1/get_auth_token';
  21.     const URL_OAUTH_ACCESS_TOKEN     = 'https://api.login.yahoo.com/oauth/v2/get_token';
  22.     const URL_YM_CREATE_SESSION      = 'http://developer.messenger.yahooapis.com/v1/session';
  23.     const URL_YM_DESTROY_SESSION     = 'http://%SERVER%/v1/session';
  24.     const URL_YM_KEEPALIVE_SESSION   = 'http://%SERVER%/v1/session/keepalive';
  25.     const URL_YM_CUSTOM_AVATARS      = 'http://displayimage.messenger.yahooapis.com/v1/displayImage/custom/%NETWORK%/%USERID%';
  26.     const URL_YM_GROUPS              = 'http://%SERVER%/v1/groups';
  27.     const URL_YM_NOTIFICATIONS       = 'http://%SERVER%/v1/notifications';
  28.     const URL_YM_SEND_MESSAGE        = 'http://%SERVER%/v1/message/%NETWORK%/%TARGETID%';
  29.     const URL_YM_PRESENCE            = 'http://%SERVER%/v1/presence';
  30.     const URL_YM_BUDDY_AUTHORIZATION = 'http://%SERVER%/v1/buddyrequest/%NETWORK%/%CONTACTID%';
  31.    
  32.     /**
  33.      *  @var const int      Constants for user presence statuses.
  34.      */
  35.     const USER_IS_OFFLINE = -1;
  36.     const USER_IS_ONLINE  = 0;
  37.     const USER_IS_BUSY    = 2;
  38.     const USER_IS_IDLE    = 999;
  39.    
  40.     /**
  41.      * @var const int       Accept / decline buddy invitation.
  42.      */
  43.     const BUDDY_ACCEPT  = 1;
  44.     const BUDDY_DECLINE = 0;
  45.    
  46.     /**
  47.      * @var static array    Presence states for buddyStatus|buddyInfo notifications.
  48.      */
  49.     public static $notificationsPresenceStatuses = array(
  50.         0   => 'Online',
  51.         1   => 'Be Right Back',
  52.         2   => 'Busy',
  53.         3   => 'Not At Home',
  54.         4   => 'Not At My Desk',
  55.         5   => 'Not In The Office',
  56.         6   => 'On The Phone',
  57.         7   => 'On Vacation',
  58.         8   => 'Out To Lunch',
  59.         9   => 'Stepped Out',
  60.         10  => 'Away',
  61.         99  => 'Custom',
  62.         999 => 'Idle',
  63.     );
  64.  
  65.     /**
  66.     * @var static array    Set the trace.
  67.     */
  68.     public static $__ERROR__ = NULL;
  69.     public static $__TRACE__ = NULL;
  70.    
  71.     /**
  72.      * @var const int       Curl connect timeout.
  73.      */
  74.     const TIMEOUT = 20;
  75.    
  76.     /**
  77.      * @var const string    Client 's version. Should be 4-part string, such as 1.0.1.0
  78.      */
  79.     const VERSION = '1.0.0.0';
  80.    
  81.     /**
  82.      * @var string          User 's username.
  83.      */
  84.     private $userName;
  85.    
  86.     /**
  87.      * @var string          User 's password.
  88.      */
  89.     private $password;
  90.    
  91.     /**
  92.      * @var string          Application 's key.
  93.      */
  94.     private $appKey;
  95.    
  96.     /**
  97.      * @var string          Application 's secret.
  98.      */
  99.     private $appSecret;
  100.    
  101.     /**
  102.      * @var resource        The curl resource.
  103.      */
  104.     protected $curl;
  105.    
  106.     /**
  107.      * @var array           Array with token info
  108.      */
  109.     protected $tokens;
  110.    
  111.     /**
  112.      * @var array           Array with session info.
  113.      */
  114.     protected $session;
  115.    
  116.     /**
  117.      * @var boolean         Keep track if token was renewed.
  118.      */
  119.     protected $tokenRenewed;
  120.    
  121.     static public function __TROW__($message='',$exit = true)
  122.     {
  123.         self::$__ERROR__ = $message;
  124.         if($exit == true)
  125.             return false;
  126.     }
  127.    
  128.     /**
  129.      * Constructor; initializes stuffs...
  130.      * @param   string     $strUserName     YahooMessenger username.
  131.      * @param   string     $strPassword     YahooMessenger password.
  132.      * @param   string     $strAppKey       API application key.
  133.      * @param   string     $strAppSecret    API application secret.
  134.      * @throws  \BogCon\YahooMessengerApi\Exception  If params are not ok / curl could not be initialized.
  135.      */
  136.     public function __construct($strUserName, $strPassword, $strAppKey, $strAppSecret)
  137.     {
  138.         // include './Exception.php';
  139.         /* verify username and password */
  140.         if (!is_string($strUserName)) {
  141.             return self::__TROW__('Invalid param username. Must be a string.');
  142.         }
  143.         $arrUser = explode('@', $strUserName);
  144.         if (count($arrUser) > 2) {
  145.             return self::__TROW__('Invalid param username. Must contain at most one @.');
  146.         }
  147.         if (!preg_match('/^[a-z0-9_\.\+]{1,32}$/i', $arrUser[0])) {
  148.             return self::__TROW__('Invalid param username. ID must match [a-z0-9_.+] and must have at most 32 chars.');
  149.         }
  150.         if (isset($arrUser[1]) && !preg_match('/^[a-z0-9_\.\+]{3,64}$/i', $arrUser[1])) {
  151.             return self::__TROW__('Invalid param username. DNS must match [a-z0-9_.+] and must have at most 64 chars.');
  152.         }
  153.         if (!is_string($strPassword) || mb_strlen($strPassword) > 32) {
  154.             return self::__TROW__('Invalid param password.');
  155.         }
  156.         if (!is_string($strAppKey) || !mb_strlen($strAppKey)) {
  157.             return self::__TROW__('Invalid param app key.');
  158.         }
  159.         if (!is_string($strAppSecret) || !mb_strlen($strAppSecret)) {
  160.             return self::__TROW__('Invalid param app secret.');
  161.         }
  162.         $this->userName  = $strUserName;
  163.         $this->password  = $strPassword;
  164.         $this->appKey    = $strAppKey;
  165.         $this->appSecret = $strAppSecret;
  166.  
  167.         if (!extension_loaded('curl')) {
  168.             // @codeCoverageIgnoreStart
  169.             return self::__TROW__('cURL extension is not enabled.');
  170.             // @codeCoverageIgnoreEnd
  171.         }
  172.         $this->curl = curl_init();
  173.         if (false === $this->curl) {
  174.             // @codeCoverageIgnoreStart
  175.             return self::__TROW__('cURL could not be initialized.');
  176.             // @codeCoverageIgnoreEnd
  177.         }
  178.  
  179.         $this->setTokens(array());
  180.         $this->setSession(array());
  181.         $this->setTokenRenewed(false);
  182.     }
  183.    
  184.    
  185.    
  186.     /**
  187.      * Makes YM api call.
  188.      * @param   string     $strUrl                      Api call url.
  189.      * @param   string     $strMethod                   Request method (POST|GET|DELETE|PUT...)
  190.      * @param   array      $arrHeaders                  Optional request headers.
  191.      * @param   string     $strPostData                 Request body.
  192.      * @param   boolean    $blnSuprimeResponseHeader    Whether to suprime response 's headers or not.
  193.      * @return  string                                  Api call response.
  194.      * @throws \BogCon\YahooMessengerApi\Exception               If smth went wrong.
  195.      * @codeCoverageIgnore
  196.      */
  197.     protected function makeApiCall(
  198.         $strUrl,
  199.         $strMethod = 'GET',
  200.         array $arrHeaders = array(),
  201.         $strPostData = '',
  202.         $blnSuprimeResponseHeader = false,
  203.         &$intStatus = null
  204.     ) {
  205.         curl_setopt($this->curl, CURLOPT_URL, $strUrl);
  206.         curl_setopt($this->curl, CURLOPT_HTTPHEADER, $arrHeaders);
  207.         curl_setopt($this->curl, CURLOPT_TIMEOUT, self::TIMEOUT);
  208.         curl_setopt($this->curl, CURLOPT_CONNECTTIMEOUT, self::TIMEOUT);
  209.         curl_setopt($this->curl, CURLOPT_MAXREDIRS, 3);
  210.         curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
  211.         curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, 1);
  212.         curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, $strMethod);
  213.         curl_setopt($this->curl, CURLOPT_POSTFIELDS, $strPostData);
  214.         curl_setopt($this->curl, CURLOPT_HEADER, !$blnSuprimeResponseHeader);
  215.         curl_setopt(
  216.             $this->curl,
  217.             CURLOPT_USERAGENT,
  218.             'YahooMessenger/1.0 (PHP bogcon/yahoo-messenger-api; ' . self::VERSION . ')'
  219.         );
  220.         curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, 0);
  221.        
  222.         $mxdResponse = curl_exec($this->curl);
  223.         self::$__TRACE__ = $mxdResponse; # changes by andri
  224.        if (false === $mxdResponse) {
  225.             return self::__TROW__(curl_error($this->curl), curl_errno($this->curl));
  226.         }
  227.         $intStatus = curl_getinfo($this->curl, CURLINFO_HTTP_CODE);
  228.  
  229.         return $mxdResponse;
  230.     }
  231.    
  232.    
  233.    
  234.     /**
  235.      * Checks if request token was set.
  236.      * @return boolean
  237.      */
  238.     public function hasRequestToken()
  239.     {
  240.         return array_key_exists('request', $this->getTokens());
  241.     }
  242.    
  243.    
  244.    
  245.     /**
  246.      * Checks if access token was set.
  247.      * @return boolean
  248.      */
  249.     public function hasAccessToken()
  250.     {
  251.         $arrTokens = $this->getTokens();
  252.         return array_key_exists('access', $arrTokens) && is_array($arrTokens['access'])
  253.                && array_key_exists('oauth_token', $arrTokens['access'])
  254.                && array_key_exists('oauth_token_secret', $arrTokens['access'])
  255.                && array_key_exists('oauth_session_handle', $arrTokens['access']);
  256.     }
  257.    
  258.    
  259.    
  260.     /**
  261.      * Checks if access token was set.
  262.      * @return boolean
  263.      */
  264.     public function hasSession()
  265.     {
  266.         return array_key_exists('sessionId', $this->getSession())
  267.                && array_key_exists('server', $this->getSession());
  268.     }
  269.    
  270.    
  271.    
  272.     /**
  273.      * Getter method for request token; implements lazy instantiation.
  274.      * @return  string  The request token.
  275.      * @throws  \BogCon\YahooMessengerApi\Exception  If could not fetch request token from Yahoo API.
  276.      */
  277.     public function getRequestToken()
  278.     {
  279.         if (!$this->hasRequestToken()) {
  280.             $strUrl = self::URL_OAUTH_REQUEST_TOKEN
  281.                 . '?login=' . urlencode($this->userName)
  282.                 . '&passwd=' . urlencode($this->password)
  283.                 . '&oauth_consumer_key=' . urldecode($this->appKey);
  284.  
  285.             $strResponse = $this->makeApiCall($strUrl, 'GET', array(), '', true);
  286.             $arrBody = explode('=', $strResponse);
  287.             if (2 != count($arrBody) || mb_strtolower($arrBody[0]) != 'requesttoken') {
  288.                 return self::__TROW__('Could not fetch request token. Api response: ' . $strResponse);
  289.             }
  290.             $this->tokens['request'] = $arrBody[1];
  291.         }
  292.        
  293.         return $this->tokens['request'];
  294.     }
  295.    
  296.    
  297.    
  298.     /**
  299.      * Getter method for access token; implements lazy instantiation.
  300.      * @param   boolean     $force   Whether to renew the access token even if it is already set.
  301.      * @return  array                Array with access token info.
  302.      * @throws  \BogCon\YahooMessengerApi\Exception  If could not fetch access token from Yahoo API.
  303.      */
  304.     public function getAccessToken($force = false)
  305.     {
  306.         if (!$this->hasAccessToken() || $force) {
  307.             $arrQuery = array(
  308.                 'oauth_nonce' => uniqid(mt_rand(1, 1000)),
  309.                 'oauth_consumer_key' => $this->appKey,
  310.                 'oauth_signature_method' => 'PLAINTEXT',
  311.                 'oauth_timestamp' => time(),
  312.                 'oauth_version' => '1.0',
  313.             );
  314.            
  315.             if ($force && $this->hasAccessToken()) {
  316.                 // renew acces token
  317.                 $arrQuery['oauth_token'] = $this->tokens['access']['oauth_token'];
  318.                 $arrQuery['oauth_signature'] = $this->appSecret . '&' . $this->tokens['access']['oauth_token_secret'];
  319.                 $arrQuery['oauth_session_handle'] = $this->tokens['access']['oauth_session_handle'];
  320.             } else {
  321.                 // new acces token
  322.                 $arrQuery['oauth_token'] = $this->getRequestToken();
  323.                 $arrQuery['oauth_signature'] = $this->appSecret . '&';
  324.             }
  325.            
  326.             $strUrl = self::URL_OAUTH_ACCESS_TOKEN . '?' . http_build_query($arrQuery);
  327.             $strResponse = $this->makeApiCall($strUrl, 'GET', array(), '', true);
  328.             $arrBody = array();
  329.             parse_str($strResponse, $arrBody);
  330.             if (count($arrBody) < 4
  331.                 || !array_key_exists('oauth_token', $arrBody)
  332.                 || !array_key_exists('oauth_token_secret', $arrBody)) {
  333.                 return self::__TROW__('Could not fetch access token. Api response: ' . $strResponse);
  334.             }
  335.             $this->tokens['access'] = $arrBody;
  336.             $this->setTokenRenewed(true);
  337.         }
  338.        
  339.         return $this->tokens['access'];
  340.     }
  341.  
  342.    
  343.    
  344.     /**
  345.      * Creates session.
  346.      * @param  int $intState The state to log user in; one of the constants
  347.      *                       \BogCon\YahooMessengerApi\Client::USER_IS_* (optional)
  348.      * @param  string $strStatusMessage The presence message of the user. (optional)
  349.      * @return \BogCon\YahooMessengerApi\Client
  350.      * @throws \BogCon\YahooMessengerApi\Exception
  351.      */
  352.     public function logIn($intState = self::USER_IS_ONLINE, $strStatusMessage = '')
  353.     {
  354.         // check state param
  355.         if (!in_array(
  356.             $intState,
  357.             array(
  358.                 self::USER_IS_ONLINE,
  359.                 self::USER_IS_OFFLINE,
  360.                 self::USER_IS_BUSY,
  361.                 self::USER_IS_IDLE
  362.             )
  363.         )) {
  364.             $intState = self::USER_IS_ONLINE; // set default value
  365.         }
  366.         $arrPostData = array(
  367.             'presenceState' => $intState,
  368.         );
  369.         if (mb_strlen($strStatusMessage)) {
  370.             $arrPostData['presenceMessage'] = $strStatusMessage;
  371.         }
  372.        
  373.         $strPostData = json_encode($arrPostData);
  374.         $intHttpStatus = 0;
  375.         $strResponse = $this->makeApiCall(
  376.             self::URL_YM_CREATE_SESSION,
  377.             'POST',
  378.             $this->getHeadersForCurlCall($strPostData),
  379.             $strPostData,
  380.             true,
  381.             $intHttpStatus
  382.         );
  383.  
  384.         if (200 != $intHttpStatus) {
  385.             if (403 == $intHttpStatus)
  386.                 return self::__TROW__('Could not create session. 403[forbidden]. Api response: ' . $strResponse);
  387.             return self::__TROW__('Could not create session. Api response: ' . $strResponse);
  388.         }
  389.        
  390.         $arrBody = json_decode($strResponse, true);
  391.         if (JSON_ERROR_NONE != json_last_error()) {
  392.             return self::__TROW__(
  393.                 'Could not create session. '
  394.                 . 'Json error code: ' . json_last_error() . '. '
  395.                 . 'Api response: ' . $strResponse
  396.             );
  397.         }
  398.         $this->setSession($arrBody);
  399.         return $this;
  400.     }
  401.    
  402.    
  403.    
  404.     /**
  405.      * Check session.
  406.      * @return array
  407.      * @throws \BogCon\YahooMessengerApi\Exception
  408.      */
  409.     public function checkSession()
  410.     {
  411.         $intHttpStatus = 0;
  412.         $strResponse = $this->makeApiCall(
  413.             self::URL_YM_CREATE_SESSION,
  414.             'GET',
  415.             $this->getHeadersForCurlCall(),
  416.             '',
  417.             true,
  418.             $intHttpStatus
  419.         );
  420.        
  421.         /* renew access token if expired and redo the call */
  422.         if (401 == $intHttpStatus && false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  423.             $this->getAccessToken(true);
  424.             $strResponse = $this->makeApiCall(
  425.                 self::URL_YM_CREATE_SESSION,
  426.                 'GET',
  427.                 $this->getHeadersForCurlCall(),
  428.                 '',
  429.                 true,
  430.                 $intHttpStatus
  431.             );
  432.         }
  433.        
  434.         if (200 != $intHttpStatus) {
  435.             return self::__TROW__('Could not check session. Api response: ' . $strResponse);
  436.         }
  437.         $arrReturnValue = json_decode($strResponse, true);
  438.         if (JSON_ERROR_NONE != json_last_error()) {
  439.             return self::__TROW__(
  440.                 'Could not check session. '
  441.                 . 'Json error code: ' . json_last_error() . '. '
  442.                 . 'Api response: ' . $strResponse
  443.             );
  444.         }
  445.         return $arrReturnValue;
  446.     }
  447.    
  448.    
  449.    
  450.     /**
  451.      * Keeps alive user session on Yahoo 's servers.
  452.      * @return \BogCon\YahooMessengerApi\Client
  453.      * @throws \BogCon\YahooMessengerApi\Exception   If not previously logged in, if could not keep alive session.
  454.      */
  455.     public function keepAliveSession()
  456.     {
  457.         if (!$this->hasSession()) {
  458.             return self::__TROW__('You have to be logged in in order to perform this action.');
  459.         }
  460.        
  461.         $strUrl = str_replace('%SERVER%', $this->session['server'], self::URL_YM_KEEPALIVE_SESSION)
  462.             . '?sid=' . urlencode($this->session['sessionId'])
  463.             . '&notifyServerToken=1';
  464.  
  465.         $intHttpStatus = 0;
  466.         $strResponse = $this->makeApiCall($strUrl, 'PUT', $this->getHeadersForCurlCall(), '', true, $intHttpStatus);
  467.  
  468.         /* renew access token if expired and redo the call */
  469.         if (401 == $intHttpStatus && false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  470.             $this->getAccessToken(true);
  471.             $strResponse = $this->makeApiCall($strUrl, 'PUT', $this->getHeadersForCurlCall(), '', true, $intHttpStatus);
  472.         }
  473.  
  474.         if (200 != $intHttpStatus || trim($strResponse) != '') {
  475.             return self::__TROW__('Could not keepalive session. Api response: ' . $strResponse);
  476.         }
  477.  
  478.         return $this;
  479.     }
  480.    
  481.    
  482.    
  483.     /**
  484.      * Destroys session.
  485.      * @return  \BogCon\YahooMessengerApi\Client
  486.      * @throws  \BogCon\YahooMessengerApi\Exception
  487.      */
  488.     public function logOut()
  489.     {
  490.         if (!$this->hasSession()) {
  491.             return $this;
  492.         }
  493.        
  494.         $strUrl = str_replace('%SERVER%', $this->session['server'], self::URL_YM_DESTROY_SESSION)
  495.             . '?sid=' . urlencode($this->session['sessionId']);
  496.  
  497.         $intHttpStatus = 0;
  498.         $strResponse = $this->makeApiCall(
  499.             $strUrl,
  500.             'DELETE',
  501.             $this->getHeadersForCurlCall(),
  502.             '',
  503.             true,
  504.             $intHttpStatus
  505.         );
  506.  
  507.         /* renew access token if expired and redo the call */
  508.         if (401 == $intHttpStatus && false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  509.             $this->getAccessToken(true);
  510.             $strResponse = $this->makeApiCall(
  511.                 $strUrl,
  512.                 'DELETE',
  513.                 $this->getHeadersForCurlCall(),
  514.                 '',
  515.                 true,
  516.                 $intHttpStatus
  517.             );
  518.         }
  519.  
  520.         if (200 != $intHttpStatus || trim($strResponse) != '') {
  521.             return self::__TROW__('Could not log out. Api response: ' . $strResponse);
  522.         }
  523.  
  524.         return $this;
  525.     }
  526.    
  527.    
  528.    
  529.     /**
  530.      * Retrieve user 's custom avatar.
  531.      * @param  string  $strUserId         User 's id.
  532.      * @param  string  $strNetwork        User 's network.
  533.      * @param  string  $strImgSize        Can take 'small', 'medium', 'full' values.
  534.      * @param  string  $strImgFormat      Can take 'gif', 'jpg', 'png' values.
  535.      * @return string  User 's avatar url.
  536.      * @throws \BogCon\YahooMessengerApi\Exception If could not fetch avatar.
  537.      */
  538.     public function fetchCustomAvatar($strUserId, $strNetwork = 'yahoo', $strImgSize = 'small', $strImgFormat = 'png')
  539.     {
  540.         $strReturnValue = '';
  541.  
  542.         $strUrl = str_replace(
  543.             array('%USERID%', '%NETWORK%'),
  544.             array($strUserId, $strNetwork),
  545.             self::URL_YM_CUSTOM_AVATARS
  546.         ) . '?size=' . urlencode($strImgSize)
  547.           . '&format=' . urlencode($strImgFormat);
  548.  
  549.         $intHttpStatus = 0;
  550.         $strResponse = $this->makeApiCall($strUrl, 'HEAD', $this->getHeadersForCurlCall(), '', false, $intHttpStatus);
  551.  
  552.         /* renew access token if expired and redo the call */
  553.         if (401 == $intHttpStatus && false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  554.             $this->getAccessToken(true);
  555.             $strResponse = $this->makeApiCall(
  556.                 $strUrl,
  557.                 'HEAD',
  558.                 $this->getHeadersForCurlCall(),
  559.                 '',
  560.                 false,
  561.                 $intHttpStatus
  562.             );
  563.         }
  564.  
  565.         if (200 != $intHttpStatus) {
  566.             return self::__TROW__('Could not get user avatar. Api response: ' . $strResponse);
  567.         }
  568.  
  569.         $arrHeaders = $this->getHeadersFromCurlResponse($strResponse);
  570.         if (array_key_exists('x-yahoo-msgr-imageurl', $arrHeaders)
  571.             && mb_strlen($arrHeaders['x-yahoo-msgr-imageurl'])) {
  572.             $strReturnValue = $arrHeaders['x-yahoo-msgr-imageurl'];
  573.         } else {
  574.             return self::__TROW__('Could not get user avatar. Api response: ' . $strResponse);
  575.         }
  576.        
  577.         return $strReturnValue;
  578.     }
  579.    
  580.    
  581.    
  582.     /**
  583.      * Retrieve list of groups and users.
  584.      * @return array
  585.      * @throws \BogCon\YahooMessengerApi\Exception   If not previously logged in, or could not fetch groups.
  586.      */
  587.     public function fetchGroups()
  588.     {
  589.         if (!$this->hasSession()) {
  590.             return self::__TROW__('You have to be logged in in order to perform this action.');
  591.         }
  592.        
  593.         $strUrl = str_replace('%SERVER%', $this->session['server'], self::URL_YM_GROUPS)
  594.             . '?sid=' . urlencode($this->session['sessionId'])
  595.             . '&fields=' . urlencode('+presence')
  596.             . '&fields=' . urlencode('+contacts')
  597.             . '&fields=' . urlencode('+clientcap')
  598.             . '&fields=' . urlencode('+addressbook');
  599.        
  600.         $intHttpStatus = 0;
  601.         $strResponse = $this->makeApiCall($strUrl, 'GET', $this->getHeadersForCurlCall(), '', true, $intHttpStatus);
  602.  
  603.         /* renew access token if expired and redo the call */
  604.         if (401 == $intHttpStatus && false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  605.             $this->getAccessToken(true);
  606.             $strResponse = $this->makeApiCall($strUrl, 'GET', $this->getHeadersForCurlCall(), '', true, $intHttpStatus);
  607.         }
  608.  
  609.         if (200 != $intHttpStatus) {
  610.             return self::__TROW__('Could not fetch groups. Api response: ' . $strResponse);
  611.         }
  612.        
  613.         $arrReturnValue = json_decode($strResponse, true);
  614.         if (JSON_ERROR_NONE != json_last_error()) {
  615.             return self::__TROW__(
  616.                 'Could not fetch groups. '
  617.                 . 'Json error code: ' . json_last_error() . '. '
  618.                 . 'Api response: ' . $strResponse
  619.             );
  620.         }
  621.         return $arrReturnValue;
  622.     }
  623.    
  624.    
  625.    
  626.     /**
  627.      * Fetch notifications (messages from other users, other users status changes, etc...)
  628.      *
  629.      * @param  integer  $intSequence    Unique sequence 's number.
  630.      * @return array
  631.      * @throws \BogCon\YahooMessengerApi\Exception If not previously logged in,
  632.      *                                             or could not fetch notifications.
  633.      */
  634.     public function fetchNotifications($intSequence)
  635.     {
  636.         if (!$this->hasSession()) {
  637.             return self::__TROW__('You have to be logged in in order to perform this action.');
  638.         }
  639.        
  640.         $strUrl = str_replace('%SERVER%', $this->session['server'], self::URL_YM_NOTIFICATIONS)
  641.             . '?sid=' . urlencode($this->session['sessionId'])
  642.             . '&seq=' . intval($intSequence)
  643.             . '&count=100'
  644.             . '&rand=' . uniqid(time() + mt_rand(1, 1000));
  645.        
  646.         $intHttpStatus = 0;
  647.         $strResponse = $this->makeApiCall($strUrl, 'GET', $this->getHeadersForCurlCall(), '', true, $intHttpStatus);
  648.  
  649.         /* renew access token / session if expired and redo the call */
  650.         if (401 == $intHttpStatus) {
  651.             if (false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  652.                 $this->getAccessToken(true);
  653.                 $strResponse = $this->makeApiCall(
  654.                     $strUrl,
  655.                     'GET',
  656.                     $this->getHeadersForCurlCall(),
  657.                     '',
  658.                     true,
  659.                     $intHttpStatus
  660.                 );
  661.             }
  662.         }
  663.  
  664.         if (200 != $intHttpStatus) {
  665.             return self::__TROW__('Could not fetch notifications. Api response: ' . $strResponse);
  666.         }
  667.        
  668.         $arrReturnValue = json_decode($strResponse, true);
  669.         if (JSON_ERROR_NONE != json_last_error()) {
  670.             return self::__TROW__(
  671.                 'Could not fetch notifications. '
  672.                 . 'Json error code: ' . json_last_error() . '. '
  673.                 . 'Api response: ' . $strResponse
  674.             );
  675.         }
  676.         return $arrReturnValue;
  677.     }
  678.    
  679.    
  680.    
  681.     /**
  682.      * Send a message to another user.
  683.      * @param  string   $strMsg         The message to send.
  684.      * @param  string   $strUserId      The user 's id to send message to.
  685.      * @param  string   $strNetwork     The user 's network. (optional, default 'yahoo')
  686.      * @return \BogCon\YahooMessengerApi\Client
  687.      * @throws \BogCon\YahooMessengerApi\Exception   If not previously logged in, or could not fetch notifications.
  688.      */
  689.     public function sendMessage($strMsg, $strUserId, $sendAsAnonymous = false, $strNetwork = 'yahoo')
  690.     {
  691.         if (!$this->hasSession()) {
  692.             return self::__TROW__('You have to be logged in in order to perform this action.');
  693.         }
  694.        
  695.         $strUrl = str_replace(
  696.             array('%SERVER%', '%NETWORK%', '%TARGETID%'),
  697.             array($this->session['server'], $strNetwork, $strUserId),
  698.             self::URL_YM_SEND_MESSAGE
  699.         ) . '?sid=' . urlencode($this->session['sessionId']);
  700.         /* [START] changes by andri */
  701.         if ($sendAsAnonymous === true) {
  702.             $sendAs = $this->session['primaryLoginId'];
  703.         }
  704.         elseif($sendAsAnonymous === false){
  705.             $sendAs = $this->userName;
  706.         }
  707.         else{
  708.             $sendAs = $sendAsAnonymous;
  709.         }
  710.         /* [END] changes by andri */
  711.         $strPostData = json_encode(
  712.             array(
  713.                 'sendAs'  => $sendAs,
  714.                 'message' => $strMsg,
  715.             )
  716.         );
  717.         $intHttpStatus = 0;
  718.         $strResponse = $this->makeApiCall(
  719.             $strUrl,
  720.             'POST',
  721.             $this->getHeadersForCurlCall($strPostData),
  722.             $strPostData,
  723.             true,
  724.             $intHttpStatus
  725.         );
  726.        
  727.         /* renew access token if expired and redo the call */
  728.         if (401 == $intHttpStatus && false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  729.             $this->getAccessToken(true);
  730.             $strResponse = $this->makeApiCall(
  731.                 $strUrl,
  732.                 'POST',
  733.                 $this->getHeadersForCurlCall($strPostData),
  734.                 $strPostData,
  735.                 true,
  736.                 $intHttpStatus
  737.             );
  738.         }
  739.  
  740.         if (200 != $intHttpStatus || trim($strResponse) != '') {
  741.             return self::__TROW__('Could not send message. Api response: ' . $strResponse);
  742.         }
  743.         return $this;
  744.     }
  745.    
  746.    
  747.    
  748.     /**
  749.      * Updates user 's presence information.
  750.      * @param   int             $intState         Presence state.
  751.      * @param   string          $strMessage       Presence message.
  752.      * @return \BogCon\YahooMessengerApi\Client
  753.      * @throws \BogCon\YahooMessengerApi\Exception   If not previously logged in, if could not change presence state.
  754.      */
  755.     public function changePresenceState($intState, $strMessage)
  756.     {
  757.         if (!$this->hasSession()) {
  758.             return self::__TROW__('You have to be logged in in order to perform this action.');
  759.         }
  760.        
  761.         $strUrl = str_replace('%SERVER%', $this->session['server'], self::URL_YM_PRESENCE)
  762.             . '?sid=' . urlencode($this->session['sessionId']);
  763.         $strPostData = json_encode(
  764.             array(
  765.                 'presenceState' => $intState,
  766.                 'presenceMessage' => $strMessage,
  767.             )
  768.         );
  769.         $intHttpStatus = 0;
  770.         $strResponse = $this->makeApiCall(
  771.             $strUrl,
  772.             'PUT',
  773.             $this->getHeadersForCurlCall($strPostData),
  774.             $strPostData,
  775.             true,
  776.             $intHttpStatus
  777.         );
  778.        
  779.         /* renew access token if expired and redo the call */
  780.         if (401 == $intHttpStatus && false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  781.             $this->getAccessToken(true);
  782.             $strResponse = $this->makeApiCall(
  783.                 $strUrl,
  784.                 'PUT',
  785.                 $this->getHeadersForCurlCall($strPostData),
  786.                 $strPostData,
  787.                 true,
  788.                 $intHttpStatus
  789.             );
  790.         }
  791.  
  792.         if (200 != $intHttpStatus || trim($strResponse) != '') {
  793.             return self::__TROW__('Could not change presence. Api response: ' . $strResponse);
  794.         }
  795.         return $this;
  796.     }
  797.    
  798.    
  799.    
  800.     /**
  801.      * Buddylist authorization management.
  802.      * @param   string              $strContactId       Contact 's id.
  803.      * @param   int                 $intOperation       Authorization operation; one of the constants BUDDY_*.
  804.      * @param   string              $strNetwork         Contact 's network.
  805.      * @param   string              $strAuthReason      Authorization reason; max (2000 chars).
  806.      * @return  \BogCon\YahooMessengerApi\Client
  807.      * @throws  \BogCon\YahooMessengerApi\Exception  If not previously logged in, if could not change presence state.
  808.      */
  809.     public function authorizeBuddy(
  810.         $strContactId,
  811.         $intOperation = self::BUDDY_ACCEPT,
  812.         $strNetwork = 'yahoo',
  813.         $strAuthReason = ''
  814.     ) {
  815.         if (!$this->hasSession()) {
  816.             return self::__TROW__('You have to be logged in in order to perform this action.');
  817.         }
  818.         $strUrl = str_replace(
  819.             array('%SERVER%', '%NETWORK%', '%CONTACTID%'),
  820.             array($this->session['server'], $strNetwork, $strContactId),
  821.             self::URL_YM_BUDDY_AUTHORIZATION
  822.         ) . '?sid=' . urlencode($this->session['sessionId']);
  823.  
  824.         if (mb_strlen($strAuthReason)) {
  825.             $strPostData = json_encode(array('authReason' => mb_substr(trim($strAuthReason), 0, 2000)));
  826.         } else {
  827.             $strPostData = json_encode(array());
  828.         }
  829.         $intHttpStatus = 0;
  830.         $strMethod = $intOperation == self::BUDDY_ACCEPT ? 'POST' : 'DELETE';
  831.         $strResponse = $this->makeApiCall(
  832.             $strUrl,
  833.             $strMethod,
  834.             $this->getHeadersForCurlCall($strPostData),
  835.             $strPostData,
  836.             true,
  837.             $intHttpStatus
  838.         );
  839.  
  840.         /* renew access token if expired and redo the call */
  841.         if (401 == $intHttpStatus && false !== mb_strpos($strResponse, 'oauth_problem="token_expired"')) {
  842.             $this->getAccessToken(true);
  843.             $strResponse = $this->makeApiCall(
  844.                 $strUrl,
  845.                 $strMethod,
  846.                 $this->getHeadersForCurlCall($strPostData),
  847.                 $strPostData,
  848.                 true,
  849.                 $intHttpStatus
  850.             );
  851.         }
  852.  
  853.         if (200 != $intHttpStatus || trim($strResponse) != '') {
  854.             return self::__TROW__('Could not authorize buddy. Api response: ' . $strResponse);
  855.         }
  856.        
  857.         return $this;
  858.     }
  859.    
  860.    
  861.    
  862.     /**
  863.      * Builds an array with headers.
  864.      * @param   string  $strResponse    HTTP response text.
  865.      * @return  array                   An array with headers,
  866.      *                                  first item in the array is the http_code,
  867.      *                                  the other headers, key is header name lowercased
  868.      */
  869.     protected function getHeadersFromCurlResponse($strResponse)
  870.     {
  871.         $arrReturnValue = array();
  872.         $strHeaderText = mb_substr($strResponse, 0, mb_strpos($strResponse, "\r\n\r\n"));
  873.         foreach (explode("\r\n", $strHeaderText) as $intKey => $strLine) {
  874.             if (0 === $intKey) {
  875.                 $arrReturnValue['http_code'] = $strLine;
  876.             } else {
  877.                 $arrLine = explode(': ', $strLine);
  878.                 $arrReturnValue[mb_strtolower($arrLine[0])] = $arrLine[1];
  879.             }
  880.         }
  881.         return $arrReturnValue;
  882.     }
  883.    
  884.    
  885.    
  886.     /**
  887.      * Retrieve authorization header.
  888.      * @return  string                  The OAuth authorization header.
  889.      */
  890.     protected function getAuthorizationHeader()
  891.     {
  892.         $accessToken = $this->getAccessToken();
  893.         return 'Authorization: OAuth realm="yahooapis.com",'
  894.             . 'oauth_nonce="' . uniqid(mt_rand(1, 1000)) . '",'
  895.             . 'oauth_consumer_key="' . $this->appKey . '",'
  896.             . 'oauth_signature_method="PLAINTEXT",'
  897.             . 'oauth_signature="' . urlencode($this->appSecret . '&' . $accessToken['oauth_token_secret']) . '",'
  898.             . 'oauth_timestamp="' . time() . '",'
  899.             . 'oauth_version="1.0",'
  900.             . 'oauth_token="' . urlencode($accessToken['oauth_token']) . '"';
  901.     }
  902.    
  903.    
  904.    
  905.     /**
  906.      * Retrieve headers for curl call.
  907.      * @param   string|null  $mxdPostData    If set adds extra content type json and content length headers.
  908.      * @return  array                        An array with headers.
  909.      */
  910.     protected function getHeadersForCurlCall($mxdPostData = null)
  911.     {
  912.         $arrReturnValue = array(
  913.             $this->getAuthorizationHeader(),
  914.         );
  915.         if (is_string($mxdPostData)) {
  916.             $arrReturnValue[] = 'Content-Type: application/json;charset=utf-8';
  917.             $arrReturnValue[] = 'Content-Length: ' . mb_strlen($mxdPostData);
  918.         }
  919.         return $arrReturnValue;
  920.     }
  921.    
  922.    
  923.    
  924.     /**
  925.      * Getter method for $tokens.
  926.      * @return array    Array that could have two keys 'request' & 'access'.
  927.      */
  928.     public function getTokens()
  929.     {
  930.         return $this->tokens;
  931.     }
  932.    
  933.    
  934.    
  935.     /**
  936.      * Setter method for $tokens.
  937.      * @param   array       $arrTokens
  938.      * @return  \BogCon\YahooMessengerApi\Client
  939.      */
  940.     public function setTokens(array $arrTokens)
  941.     {
  942.         $this->tokens = $arrTokens;
  943.         return $this;
  944.     }
  945.    
  946.    
  947.    
  948.     /**
  949.      * Getter method for $session.
  950.      * @return array
  951.      */
  952.     public function getSession()
  953.     {
  954.         return $this->session;
  955.     }
  956.    
  957.    
  958.    
  959.     /**
  960.      * Setter method for $session.
  961.      * @param   array       $arrSession
  962.      * @return  \BogCon\YahooMessengerApi\Client
  963.      */
  964.     public function setSession(array $arrSession)
  965.     {
  966.         $this->session = $arrSession;
  967.         return $this;
  968.     }
  969.    
  970.    
  971.    
  972.     /**
  973.      * Setter method for $tokenRenewed.
  974.      * @param   boolean     $blnTokenRenewed
  975.      * @return  \BogCon\YahooMessengerApi\Client
  976.      */
  977.     public function setTokenRenewed($blnTokenRenewed)
  978.     {
  979.         $this->tokenRenewed = (boolean) $blnTokenRenewed;
  980.         return $this;
  981.     }
  982.  
  983.    
  984.    
  985.     /**
  986.      * Getter method for $tokenRenewed.
  987.      * If it is true, this method also will reset the flag, so a second call to irl will return false.
  988.      * @return array
  989.      */
  990.     public function isTokenRenewed()
  991.     {
  992.         if ($this->tokenRenewed) {
  993.             $this->setTokenRenewed(false);
  994.             return true;
  995.         }
  996.         return $this->tokenRenewed;
  997.     }
  998.  
  999.    
  1000.    
  1001.     /**
  1002.      * Destructor; frees resources, memory, closes connections, etc....
  1003.      */
  1004.     public function __destruct()
  1005.     {
  1006.         if (is_resource($this->curl)) {
  1007.             curl_close($this->curl);
  1008.         }
  1009.     }
  1010. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement