source: extensions/instagram2piwigo/include/Instagram/Core/Proxy.php @ 19561

Last change on this file since 19561 was 19561, checked in by mistic100, 11 years ago

first commit

File size: 17.7 KB
Line 
1<?php
2
3/**
4* Instagram PHP
5* @author Galen Grover <galenjr@gmail.com>
6* @license http://opensource.org/licenses/mit-license.php The MIT License
7*/
8
9
10include_once(INSTAGRAM_ROOT.'/Core/ApiException.php');
11include_once(INSTAGRAM_ROOT.'/Core/ApiAuthException.php');
12include_once(INSTAGRAM_ROOT.'/Net/ClientInterface.php');
13include_once(INSTAGRAM_ROOT.'/Net/ApiResponse.php');
14
15
16/**
17 * Proxy
18 *
19 * This class performs all the API calls
20 *
21 * It uses the supplied HTTP client as a default (cURL)
22 *
23 */
24class Instagram_Core_Proxy {
25
26    /**
27     * HTTP Client
28     *
29     * @var Instagram_Net_ClientInterface
30     * @access protected
31     */
32    protected $client;
33
34    /**
35     * Instagram access token
36     *
37     * @var string
38     * @access protected
39     */
40    protected $access_token = null;
41
42    /**
43     * Client ID
44     *
45     * @var string
46     * @access protected
47     */
48    protected $client_id = null;
49
50    /**
51     * API URL
52     *
53     * @var string
54     * @access protected
55     */
56    protected $api_url = 'https://api.instagram.com/v1';
57   
58    /**
59     * Cache directory
60     * @var string
61     * @access protected
62     */
63    protected $cache_dir = null;
64   
65    /**
66     * Cache expiration time
67     * @var int
68     * @access protected
69     */
70    protected $cache_expire = 600;
71
72    /**
73     * Constructor
74     *
75     * @param Instagram_Net_ClientInterface $client HTTP Client
76     * @param string $access_token The access token from authentication
77     * @access public
78     */
79    public function __construct( Instagram_Net_ClientInterface $client, $access_token = null ) {
80        $this->client = $client;
81        $this->access_token = $access_token;
82    }
83
84    /**
85     * Enable cache system
86     * @param string $directory where cache is stored
87     * @param int $cache_expire in seconds
88     * @throws Exception
89     * @access public
90     */
91    public function enableCache( $directory, $cache_expire = 600 ) {
92        $directory = realpath($directory);
93       
94        if ($dir = opendir($directory)) {
95            $this->cache_dir = $directory;
96            $this->cache_expire = $cache_expire;
97           
98            while ($file = readdir($dir)) {
99                if (substr($file, -6) == '.cache' && ((filemtime($this->cache_dir . '/' . $file) + $this->cache_expire) < time()) ) {
100                    unlink($this->cache_dir . '/' . $file);
101                }
102            }
103        }
104        else {
105            throw new Exception( "Unable to read cache directory." );
106        }
107    }
108
109    /**
110     * Get cached request, returns false if nothing found
111     * @param string $url
112     * @param array $params
113     * @return string or false
114     * @access private
115     */
116    private function getCached( $url, $params ) {
117        $reqhash = $this->access_token.$url;
118        if ( !empty($params) ) {
119          ksort( $params );
120          $reqhash.= serialize( $params );
121        }
122        $reqhash = sha1( $reqhash );
123       
124        $file = $this->cache_dir . '/' . $reqhash . '.cache';
125        if ( file_exists($file) ) {
126            return file_get_contents( $file );
127        }
128       
129        return false;
130    }
131
132    /**
133     * Cache the unparsed response of a request
134     * @param string $url
135     * @param array $params
136     * @param string $raw_data
137     * @return bool
138     * @access private
139     */
140                private function cache( $url, $params, $raw_data ) {
141        $reqhash = $this->access_token.$url;
142        if ( !empty($params) ) {
143          ksort( $params );
144          $reqhash.= serialize( $params );
145        }
146        $reqhash = sha1( $reqhash );
147     
148        $file = $this->cache_dir . "/" . $reqhash . ".cache";
149        $fstream = fopen( $file, "w" );
150        $result = fwrite( $fstream, $raw_data );
151        fclose( $fstream );
152       
153        return $result;
154    }
155
156    /**
157     * Get the access token
158     * @param array $data Instagram_Auth data
159     * @return string Returns the access token
160     */
161    public function getAccessToken( array $data ) {
162        $response = $this->apiCall(
163            'post',
164            'https://api.instagram.com/oauth/access_token',
165            $data
166        );
167        return $response;
168    }
169
170    /**
171     * Set the access token
172     *
173     * @param string $access_token The access token
174     * @access public
175     */
176    public function setAccessToken( $access_token ) {
177        $this->access_token = $access_token;
178    }
179
180    /**
181     * Set the client ID
182     *
183     * @param string $client_id the client ID
184     * @access public
185     */
186    public function setClientID( $client_id ) {
187        $this->client_id = $client_id;
188    }
189
190    /**
191     * Logout of instagram
192     *
193     * This hasn't been implemented by instagram yet
194     *
195     * @access public
196     */
197    public function logout() {
198        $this->client->get( 'https://instagram.com/accounts/logout/', array() );
199    }
200
201    /**
202     * Get the media associated with an object
203     *
204     * This function is used by the individual object functions
205     * getLocationMedia, getTagMedia, atc...
206     *
207     * @param  string $api_endpoint API endpoint for the object type
208     * @param  string $id Id of the object to get the media for
209     * @param  array $params Extra parameters for the API call
210     * @return StdClass Returns the raw response
211     * @access protected
212     */
213    protected function getObjectMedia( $api_endpoint, $id, array $params = null ) {
214        $response = $this->apiCall(
215            'get',
216            sprintf( '%s/%s/%s/media/recent', $this->api_url, strtolower( $api_endpoint ), $id  ),
217            $params
218        );
219        return $response->getRawData();
220    }
221
222    /**
223     * Get location media
224     *
225     * @param string $id Instagram_Location ID
226     * @param array $params Extra params to pass to the API
227     * @return StdClass Returns the location media
228     * @access public
229     */
230    public function getLocationMedia( $id, array $params = null ) {
231        return $this->getObjectMedia( 'Locations', $id, $params );
232    }
233
234    /**
235     * Get tag media
236     *
237     * @param string $id Instagram_Location ID
238     * @param array $params Extra params to pass to the API
239     * @return StdClass Returns the location media
240     * @access public
241     */
242    public function getTagMedia( $id, array $params = null ) {
243        return $this->getObjectMedia( 'Tags', $id, $params );
244    }
245
246    /**
247     * Get user media
248     *
249     * @param string $id Instagram_Location ID
250     * @param array $params Extra params to pass to the API
251     * @return StdClass Returns the location media
252     * @access public
253     */
254    public function getUserMedia( $id, array $params = null ) {
255        return $this->getObjectMedia( 'Users', $id, $params );
256    }
257
258    /**
259     * Get user
260     *
261     * @param string $id Instagram_User ID
262     * @return StdClass Returns the user data
263     * @access public
264     */
265    public function getUser( $id ) {
266        $response = $this->apiCall(
267            'get',
268            sprintf( '%s/users/%s', $this->api_url, $id )
269        );
270        return $response->getData();
271    }
272
273    /**
274     * Get a user's follows
275     *
276     * @param string $id Instagram_User's ID
277     * @param array $params Extra params to pass to the API
278     * @return StdClass Returns the user's followers
279     * @access public
280     */
281    public function getUserFollows( $id, array $params = null ) {
282        $response = $this->apiCall(
283            'get',
284            sprintf( '%s/users/%s/follows', $this->api_url, $id ),
285            $params
286        );
287        return $response->getRawData();
288    }
289
290    /**
291     * Get a user's followers
292     *
293     * @param string $id Instagram_User's ID
294     * @param array $params Extra params to pass to the API
295     * @return StdClass Returns the user's followers
296     * @access public
297     */
298    public function getUserFollowers( $id, array $params = null ) {
299        $response = $this->apiCall(
300            'get',
301            sprintf( '%s/users/%s/followed-by', $this->api_url, $id ),
302            $params
303        );
304        return $response->getRawData();
305    }
306
307    /**
308     * Get media comments
309     *
310     * @param string $id Instagram_Media ID
311     * @return StdClass Returns the media data
312     * @access public
313     */
314    public function getMediaComments( $id ) {
315        $response = $this->apiCall(
316            'get',
317            sprintf( '%s/media/%s/comments', $this->api_url, $id )
318        );
319        return $response->getRawData();
320    }
321
322    /**
323     * Get media likes
324     *
325     * @param string $id Instagram_Media ID
326     * @return StdClass Returns the media likes
327     * @access public
328     */
329    public function getMediaLikes( $id ) {
330        $response = $this->apiCall(
331            'get',
332            sprintf( '%s/media/%s/likes', $this->api_url, $id )
333        );
334        return $response->getRawData();
335    }
336
337    /**
338     * Get media comments
339     *
340     * @return StdClass Returns the current user data
341     * @access public
342     */
343    public function getCurrentUser() {
344        $response = $this->apiCall(
345            'get',
346            sprintf( '%s/users/self', $this->api_url )
347        );
348        return $response->getData();
349    }
350
351    /**
352     * Get media
353     *
354     * @param string $id Instagram_Media ID
355     * @return StdClass Returns the media data
356     * @access public
357     */
358    public function getMedia( $id ) {
359        $response = $this->apiCall(
360            'get',
361            sprintf( '%s/media/%s', $this->api_url, $id )
362        );
363        return $response->getData();
364    }
365
366    /**
367     * Get tag
368     *
369     * @param string $id Instagram_Tag ID
370     * @return StdClass Returns the tag data
371     * @access public
372     */
373    public function getTag( $tag ) {
374        $response = $this->apiCall(
375            'get',
376            sprintf( '%s/tags/%s', $this->api_url, $tag )
377        );
378        return $response->getData();
379    }
380
381    /**
382     * Get location
383     *
384     * @param string $id Instagram_Location ID
385     * @return StdClass Returns the location data
386     * @access public
387     */
388    public function getLocation( $id ) {
389        $response = $this->apiCall(
390            'get',
391            sprintf( '%s/locations/%s', $this->api_url, $id )
392        );
393        return $response->getData();
394    }
395
396    /**
397     * Search users
398     *
399     * @param array $params Search params
400     * @return array Returns an array of user data
401     * @access public
402     */
403    public function searchUsers( array $params = null ) {
404        $response = $this->apiCall(
405            'get',
406            $this->api_url . '/users/search',
407            $params
408        );
409        return $response->getRawData();
410    }
411
412    /**
413     * Search tags
414     *
415     * @param array $params Search params
416     * @return array Returns an array of tag data
417     * @access public
418     */
419    public function searchTags( array $params = null ) {
420        $response = $this->apiCall(
421            'get',
422            $this->api_url . '/tags/search',
423            $params
424        );
425        return $response->getRawData();
426    }
427
428    /**
429     * Search media
430     *
431     * @param array $params Search params
432     * @return array Returns an array of media data
433     * @access public
434     */
435    public function searchMedia( array $params = null ) {
436        $response = $this->apiCall(
437            'get',
438            $this->api_url . '/media/search',
439            $params
440        );
441        return $response->getRawData();
442    }
443
444    /**
445     * Search locations
446     *
447     * @param array $params Search params
448     * @return array Returns an array of location data
449     * @access public
450     */
451    public function searchLocations( array $params = null ) {
452        $response = $this->apiCall(
453            'get',
454            $this->api_url . '/locations/search',
455            $params
456        );
457        return $response->getRawData();
458    }
459
460    /**
461     * Get popular media
462     *
463     * @param array $params Extra params
464     * @return array Returns an array of popular media data
465     * @access public
466     */
467    public function getPopularMedia( array $params = null ) {
468        $response = $this->apiCall(
469            'get',
470            $this->api_url . '/media/popular',
471            $params
472        );
473        return $response->getRawData();
474    }
475
476    /**
477     * Get the current user's feed
478     *
479     * @param array $params Extra params
480     * @return array Returns an array of media data
481     * @access public
482     */
483    public function getFeed( array $params = null ) {
484        $response = $this->apiCall(
485            'get',
486            $this->api_url . '/users/self/feed',
487            $params
488        );
489        return $response->getRawData();
490    }
491
492    /**
493     * Get the current users follow requests
494     *
495     * @param $params Extra params (not used in API, here in case it's added)
496     * @return array Returns an array of user data
497     * @access public
498     */
499    public function getFollowRequests( array $params = null ) {
500        $response = $this->apiCall(
501            'get',
502            $this->api_url . '/users/self/requested-by',
503            $params
504        );
505        return $response->getRawData();
506    }
507
508    /**
509     * Get the current user's liked media
510     *
511     * @param array $params Extra params
512     * @return array Returns an array of media data
513     * @access public
514     */
515    public function getLikedMedia( array $params = null ) {
516        $response = $this->apiCall(
517            'get',
518            $this->api_url . '/users/self/media/liked',
519            $params
520        );
521        return $response->getRawData();
522    }
523
524    /**
525     * Get a user's relationship to the current user
526     *
527     * @param string $user_id Instagram_User to check relationship for
528     * @return StdClass Returns the relationship
529     * @access public
530     */
531    public function getRelationshipToCurrentUser( $user_id ) {
532        $response = $this->apiCall(
533            'get',
534            $this->api_url . sprintf( '/users/%s/relationship', $user_id )
535        );
536        return $response->getData();
537    }
538
539    /**
540     * Modify a relationship with the current user
541     * @param string $user_id Instagram_User ID of the user to change the relationship for
542     * @param string $relationship New relationship {@link http://instagram.com/developer/endpoints/relationships/#post_relationship}
543     * @return StdClass Returns the status
544     * @access public
545     */
546    public function modifyRelationship( $user_id, $relationship ) {
547        $response = $this->apiCall(
548            'post',
549            $this->api_url . sprintf( '/users/%s/relationship', $user_id ),
550            array( 'action' => $relationship )
551        );
552        return $response->getData();
553    }
554
555    /**
556     * Add a like form the current user on a media
557     *
558     * @param string $media_id Instagram_Media ID to like
559     * @return StdClass Returns the status
560     * @access public
561     */
562    public function like( $media_id ) {
563        $this->apiCall(
564            'post',
565            $this->api_url . sprintf( '/media/%s/likes', $media_id )
566        );
567    }
568
569    /**
570     * Delete a like form the current user on a media
571     *
572     * @param string $media_id Instagram_Media ID to unlike
573     * @return StdClass Returns the status
574     * @access public
575     */
576    public function unLike( $media_id ) {
577        $this->apiCall(
578            'delete',
579            $this->api_url . sprintf( '/media/%s/likes', $media_id )
580        );
581    }
582
583    /**
584     * Add a comment to a media
585     *
586     * @param string $media_id Instagram_Media ID
587     * @param string $text Instagram_Comment text
588     * @return StdClass Returns the status
589     * @access public
590     */
591    public function addMediaComment( $media_id, $text ) {
592        $this->apiCall(
593            'post',
594            $this->api_url . sprintf( '/media/%s/comments', $media_id ),
595            array( 'text' => $text )
596        );
597    }
598
599    /**
600     * Delete a comment from a media
601     *
602     * @param string $media_id Instagram_Media ID
603     * @param string $comment_id Instagram_Comment ID to delete
604     * @return StdClass
605     * @access public
606     */
607    public function deleteMediaComment( $media_id, $comment_id ) {
608        $this->apiCall(
609            'delete',
610            $this->api_url . sprintf( '/media/%s/comments/%s', $media_id, $comment_id )
611        );
612    }
613
614    /**
615     * Make a call to the API
616     *
617     * @param string $method HTTP method to use
618     * @param string $url URL
619     * @param array $params API parameters
620     * @param boolean $throw_exception True to throw exceptoins
621     * @throws Instagram_Core_ApiException, Instagram_Core_ApiAuthException
622     * @return Instagram_Net_ApiResponse Returns teh API response
623     * @access private
624     */
625    private function apiCall( $method, $url, array $params = null, $throw_exception = true ) {
626        if ( $method != 'get' || empty($this->cache_dir) || ($raw_response = $this->getCached($url, $params)) === false ) {
627            $raw_response = $this->client->$method(
628                $url,
629                array(
630                    'access_token'  => $this->access_token,
631                    'client_id'     => isset( $params['client_id'] ) ? $params['client_id'] : $this->client_id
632                ) + (array) $params
633            );
634           
635            if ($method == 'get') {
636                $this->cache($url, $params, $raw_response);
637            }
638        }
639
640        $response = new Instagram_Net_ApiResponse( $raw_response );
641
642        if ( !$response->isValid() ) {
643            if ( $throw_exception ) {
644                if ( $response->getErrorType() == 'OAuthAccessTokenException' ) {
645                    throw new Instagram_Core_ApiAuthException( $response->getErrorMessage(), $response->getErrorCode(), $response->getErrorType() );
646                }
647                else {
648                    throw new Instagram_Core_ApiException( $response->getErrorMessage(), $response->getErrorCode(), $response->getErrorType() );
649                }
650            }
651            else {
652                return false;
653            }
654        }
655        return $response;
656    }
657
658
659}
660?>
Note: See TracBrowser for help on using the repository browser.