PageRenderTime 39ms CodeModel.GetById 25ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/plugin/PBAPI/PBAPI/Request.php

https://bitbucket.org/chamilo/chamilo-ext-repo-photobucket-dev/
PHP | 398 lines | 175 code | 43 blank | 180 comment | 14 complexity | 17e211c1fd3c6ffd6b0efffe78ba1269 MD5 | raw file
  1<?php
  2use common\libraries\Path;
  3/**
  4 * Photobucket API 
  5 * Fluent interface for PHP5
  6 * Request parent class
  7 * 
  8 * @author jhart
  9 * @package PBAPI
 10 * 
 11 * @copyright Copyright (c) 2008, Photobucket, Inc.
 12 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
 13 */
 14
 15/**
 16 * Require OAuth Request Obj
 17 */
 18require_once Path :: get_plugin_path() . 'pear/OAuth/Request.php';
 19
 20/**
 21 * Request method parent class
 22 *
 23 * @package PBAPI
 24 */
 25abstract class PBAPI_Request
 26{
 27    
 28    /**
 29     * Oauth consumer object
 30     *
 31     * @var OAuth_Consumer
 32     */
 33    private $oauth_consumer;
 34    /**
 35     * Oauth token object
 36     *
 37     * @var OAuth_Token
 38     */
 39    private $oauth_token;
 40    
 41    /**
 42     * Current subdomain
 43     *
 44     * @var string
 45     */
 46    protected $subdomain;
 47    /**
 48     * Default format id
 49     *
 50     * @var string
 51     */
 52    protected $default_format;
 53    
 54    /**
 55     * Full request URL (for debugging)
 56     *
 57     * @var string
 58     */
 59    public $request_url;
 60    /**
 61     * Oauth Request object (for debugging)
 62     *
 63     * @var OAuthRequest
 64     */
 65    public $oauth_request;
 66    
 67    /**
 68     * Request strategy parameters
 69     * 
 70     * @var array
 71     */
 72    protected $request_params = array();
 73    
 74    /**
 75     * Photobucket Web Login url
 76     *
 77     * @static
 78     * @var string
 79     */
 80    public static $web_login_url = 'http://photobucket.com/apilogin/login';
 81
 82    /**
 83     * Class Constructor
 84     *
 85     * @param array $request_parameters parameters send to set in this object
 86     * @param string $subdomain default subdomain
 87     * @param string $default_format default format
 88     */
 89    public function __construct($subdomain = 'api', $default_format = 'xml', $request_params = array())
 90    {
 91        $this->setSubdomain($subdomain);
 92        $this->setDefaultFormat($default_format);
 93        $this->setRequestParams($request_params);
 94    }
 95
 96    /**
 97     * Set OAuth Consumer information
 98     *
 99     * @param string $consumer_key
100     * @param string $consumer_secret
101     */
102    public function setOAuthConsumer($consumer_key, $consumer_secret)
103    {
104        $this->oauth_consumer = new OAuth_Consumer($consumer_key, $consumer_secret);
105    }
106
107    /**
108     * Set OAuth Token info
109     *
110     * @param string $token
111     * @param string $token_secret
112     */
113    public function setOAuthToken($token, $token_secret)
114    {
115        $this->oauth_token = new OAuth_Token($token, $token_secret);
116    }
117
118    /**
119     * Set OAuth Token Object
120     *
121     * @param oAuth_Token $oauth_token
122     */
123    public function setOAuthTokenObject(OAuth_Token $oauth_token)
124    {
125        $this->oauth_token = $oauth_token;
126    }
127
128    /**
129     * Get OAuth Token info
130     *
131     * return OAuth_Token
132     */
133    public function getOAuthToken()
134    {
135        return $this->oauth_token;
136    }
137
138    /**
139     * clear oauth token
140     *
141     */
142    public function resetOAuthToken()
143    {
144        $this->oauth_token = null;
145    }
146
147    /**
148     * set subdomain value
149     *
150     * @param string $subdomain
151     */
152    public function setSubdomain($subdomain)
153    {
154        $subdomain = preg_replace('#\.photobucket\.com(/.*)?$#', '', $subdomain);
155        $this->subdomain = $subdomain;
156    }
157
158    /**
159     * get subdomain value
160     * 
161     * @return string subdomain
162     */
163    public function getSubdomain()
164    {
165        return $this->subdomain;
166    }
167
168    /**
169     * get whole subdomain url
170     *
171     * @param string $uri uri ending
172     * @return string http://...
173     */
174    public function getSubdomainUrl($uri)
175    {
176        return 'http://' . $this->subdomain . '.photobucket.com/' . trim($uri, '/');
177    }
178
179    /**
180     * set default response format
181     *
182     * @param string $format
183     */
184    public function setDefaultFormat($format)
185    {
186        //todo verify allowed formats
187        $this->default_format = $format;
188    }
189
190    /**
191     * Request params
192     * 
193     * @param array $params request params
194     */
195    public function setRequestParams($params)
196    {
197        $this->request_params = $params;
198    }
199
200    /**
201     * Get OAuthRequest for given items
202     *
203     * @param string $method HTTP method
204     * @param string $uri URI (no http/host)
205     * @param array $params key=>value parameters
206     * @return OAuthRequest
207     */
208    protected function getSignedOAuthRequest($method, $uri, array $params)
209    {
210        $req = OAuth_Request :: fromConsumerAndToken($this->oauth_consumer, $this->oauth_token, $method, 'http://api.photobucket.com/' . trim($uri, '/'), $params);
211        $req->signRequest('HMAC-SHA1', $this->oauth_consumer, $this->oauth_token);
212        return $req;
213    }
214
215    /**
216     * Pre-Request filter
217     *
218     * @param string $method (ref) HTTP method
219     * @param string $uri URI (no http://)
220     * @param array $params parameters
221     * @return string finished request url
222     */
223    protected function preRequest(&$method, &$uri, array &$params)
224    {
225        //cleanup method
226        $method = strtoupper($method);
227        
228        //cleanup/determine format
229        if ($this->default_format && ! array_key_exists('format', $params))
230        {
231            $params['format'] = $this->default_format;
232        }
233        
234        //block uploadfile from parameters
235        $uploadfile = null;
236        if (! empty($params['uploadfile']))
237        {
238            $uploadfile = $params['uploadfile'];
239            unset($params['uploadfile']);
240        }
241        
242        //get fullly signed request
243        $req = $this->getSignedOAuthRequest($method, $uri, $params);
244        
245        $url = '';
246        $params = array();
247        
248        //rebuild url and request with uploadfile
249        if ($method != 'POST')
250        {
251            $url = $this->getSubdomainUrl($uri) . '?' . $req->toPostdata();
252        }
253        else
254        {
255            $url = $this->getSubDomainUrl($uri);
256            if ($uploadfile)
257            {
258                $req->setParameter('uploadfile', $uploadfile);
259            }
260            $params = $req->getParameters();
261        }
262        
263        $this->request_url = $url;
264        $this->oauth_request = $req;
265        return $url;
266    }
267
268    /**
269     * Redirect to the login page (for given token)
270     *
271     * @param string $extra optional extra parameter to pass along (if you need to store a key without a cookie, for example)
272     */
273    public function redirectLogin($extra = null)
274    {
275        if (! $this->oauth_token || self :: getOAuthTokenType($this->oauth_token) != 'req')
276        {
277            throw new PBAPI_Exception('OAuth Token is not a request token');
278        }
279        $req = $this->oauth_token->getKey();
280        
281        $url = self :: $web_login_url . '?oauth_token=' . $req;
282        if ($extra)
283            $url .= '&extra=' . $extra;
284        
285        header('Location: ' . $url);
286        exit();
287    }
288
289    /**#@+
290     * Request function
291     *
292     * @param string $uri
293     * @param array $params
294     */
295    public function get($uri, $params = array())
296    {
297        return $this->request('GET', $uri, $params);
298    }
299
300    public function post($uri, $params = array())
301    {
302        return $this->request('POST', $uri, $params);
303    }
304
305    public function put($uri, $params = array())
306    {
307        return $this->request('PUT', $uri, $params);
308    }
309
310    public function delete($uri, $params = array())
311    {
312        return $this->request('DELETE', $uri, $params);
313    }
314
315    /**#@-*/
316    
317    /**
318     * Actual Request function
319     *
320     * @param string $method
321     * @param string $uri
322     * @param array $params
323     * @return string
324     */
325    abstract protected function request($method, $uri, $params = array());
326
327    /**
328     * Turn parameters into multipart encoded string
329     *
330     * @param array $params key value pairs of parameters
331     * @param string $bound boundary (should be relatively unique)
332     * @return string mime type multipart-form 
333     */
334    public static function multipartEncodeParams(array $params, $bound)
335    {
336        $bound = '--' . trim($bound) . "\n";
337        $result = '';
338        $paramStr = array();
339        
340        foreach ($params as $key => $val)
341        {
342            $file = false;
343            
344            if (strpos($val, '@') === 0)
345            {
346                $filepath = trim($val, '@');
347                $val = file_get_contents($filepath);
348                $disp = 'content-disposition: form-data; name="' . $key . '"; filename="' . basename($filepath) . '"' . "\n";
349                $mimetype = 'mimetype';
350                $disp .= 'content-type: ' . $mimetype . "\n";
351                $disp .= 'content-transfer-encoding: binary' . "\n";
352            }
353            else
354            {
355                $disp = 'content-disposition: form-data; name="' . $key . '"' . "\n";
356            }
357            
358            $paramStr[] = $disp . "\n" . $val . "\n";
359        }
360        
361        $result = $bound . implode($bound, $paramStr) . $bound;
362        return $result;
363    }
364
365    /**
366     * See if the given array has an upload filename as a parameter
367     *
368     * @param array $params parameters
369     * @return bool array has at least one upload filename parameter
370     */
371    public static function detectFileUploadParams($params = array())
372    {
373        foreach ($params as $p)
374        {
375            if (strpos($p, '@') === 0)
376                return true;
377        }
378        return false;
379    }
380
381    /**
382     * Determine an OAuth_Token's type
383     *
384     * @param OAuth_Token $token
385     * @return string type of token [req|user]
386     */
387    public static function getOAuthTokenType(OAuth_Token $token)
388    {
389        if (! $token)
390            return false;
391        if (strpos($token->getKey(), 'req_') === 0)
392            $type = 'req';
393        else
394            $type = 'user';
395        return $type;
396    }
397
398}