Changeset 1435377
- Timestamp:
- 06/12/2016 02:23:02 PM (10 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
taghound-media-tagger/trunk/lib/class-clarifai-api.php
r1435376 r1435377 36 36 } 37 37 38 /** 39 * Determines if a token object is expired using a custom value we calculate 40 * @param array $token Token with 'expiration_date' 41 * @return boolean 42 */ 43 protected function is_token_expired( $token ) { 44 return time() > $token['expiration_date']; 45 } 46 47 /** 48 * Gets the API keys set on the object 49 * @return array 50 */ 38 51 protected function get_api_keys() { 39 52 return array( … … 43 56 } 44 57 58 /** 59 * Gets the auth token. Generates ones if it's invalid or expired. 60 * @return array Token object 61 */ 45 62 protected function get_auth_token() { 46 return get_option(IAT_TOKEN_SETTING); 63 $token = get_option(IAT_TOKEN_SETTING); 64 65 if ( !$token || $this->is_token_expired($token) ) { 66 return $this->renew_auth_token(); 67 } 68 69 return $token; 47 70 } 48 71 72 /** 73 * Get a new auth token 74 * @return array Auth token array 75 */ 49 76 protected function renew_auth_token() { 50 77 $keys = $this->get_api_keys(); … … 61 88 $results = $this->_make_request( $args, true ); 62 89 63 update_option(IAT_TOKEN_SETTING, $results['access_token']); 90 // Calculate the expiration date of this token 91 $results['expiration_date'] = time() + $results['expires_in']; 92 93 update_option(IAT_TOKEN_SETTING, $results); 94 95 return $results; 64 96 } 65 97 … … 67 99 * Get tags for an image 68 100 * @param string $image_path File path to image 69 * @return array Array of tags101 * @return array Array ( tags => array, doc_id => int ) 70 102 */ 71 public staticfunction get_tags_for_image( $image_path ) {103 public function get_tags_for_image( $image_path ) { 72 104 $args = array( 73 105 'endpoint' => 'tag', 74 106 'post' => array( 75 'encoded_data' => new CURLFile( $image_path ),107 'encoded_data' => new \CURLFile( $image_path ), 76 108 ), 77 109 ); 78 110 79 $results = $this->_make_request( $args ); 111 try { 112 $results = $this->_make_request( $args ); 80 113 81 $tags = $results['results'][0]['result']['tag']['classes']; 114 $tags = $results['results'][0]['result']['tag']['classes']; 115 $doc_id = $results['results'][0]['docid']; 82 116 83 return $tags; 117 return array( 118 'tags' => $tags, 119 'doc_id' => $doc_id, 120 ); 121 } catch ( \Exception $e ) { 122 return $e; 123 } 84 124 } 85 125 … … 89 129 protected function _make_request( $args, $authenticating = false ) { 90 130 if ( ! $authenticating ) { 131 $token = $this->get_auth_token(); 91 132 $args = wp_parse_args( $args, array( 92 133 'headers' => array( 93 "Authorization: Bearer {$t his->get_auth_token()}",134 "Authorization: Bearer {$token['access_token']}",