2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Provides {@link flickr_client} class.
21 * @copyright 2017 David Mudrák <david@moodle.com>
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') ||
die();
27 require_once($CFG->libdir
.'/oauthlib.php');
30 * Simple Flickr API client implementing the features needed by Moodle
32 * @copyright 2017 David Mudrak <david@moodle.com>
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class flickr_client
extends oauth_helper
{
38 * Base URL for Flickr OAuth 1.0 API calls.
40 const OAUTH_ROOT
= 'https://www.flickr.com/services/oauth';
43 * Base URL for Flickr REST API calls.
45 const REST_ROOT
= 'https://api.flickr.com/services/rest';
48 * Base URL for Flickr Upload API call.
50 const UPLOAD_ROOT
= 'https://up.flickr.com/services/upload/';
53 * Set up OAuth and initialize the client.
55 * The callback URL specified here will override the one specified in the
56 * auth flow defined at Flickr Services.
58 * @param string $consumerkey
59 * @param string $consumersecret
60 * @param moodle_url|string $callbackurl
62 public function __construct($consumerkey, $consumersecret, $callbackurl = '') {
65 'api_root' => self
::OAUTH_ROOT
,
66 'oauth_consumer_key' => $consumerkey,
67 'oauth_consumer_secret' => $consumersecret,
68 'oauth_callback' => $callbackurl,
73 * Temporarily store the request token secret in the session.
75 * The request token secret is returned by the oauth request_token method.
76 * It needs to be stored in the session before the user is redirected to
77 * the Flickr to authorize the client. After redirecting back, this secret
78 * is used for exchanging the request token with the access token.
80 * The identifiers help to avoid collisions between multiple calls to this
81 * method from different plugins in the same session. They are used as the
82 * session cache identifiers. Provide an associative array identifying the
83 * particular method call. At least, the array must contain the 'caller'
84 * with the caller's component name. Use additional items if needed.
86 * @param array $identifiers Identification of the call
87 * @param string $secret
89 public function set_request_token_secret(array $identifiers, $secret) {
91 if (empty($identifiers) ||
empty($identifiers['caller'])) {
92 throw new coding_exception('Invalid call identification');
95 $cache = cache
::make_from_params(cache_store
::MODE_SESSION
, 'core', 'flickrclient', $identifiers);
96 $cache->set('request_token_secret', $secret);
100 * Returns previously stored request token secret.
102 * See {@link self::set_request_token_secret()} for more details on the
103 * $identifiers argument.
105 * @param array $identifiers Identification of the call
106 * @return string|bool False on error, string secret otherwise.
108 public function get_request_token_secret(array $identifiers) {
110 if (empty($identifiers) ||
empty($identifiers['caller'])) {
111 throw new coding_exception('Invalid call identification');
114 $cache = cache
::make_from_params(cache_store
::MODE_SESSION
, 'core', 'flickrclient', $identifiers);
116 return $cache->get('request_token_secret');
120 * Call a Flickr API method.
122 * @param string $function API function name like 'flickr.photos.getSizes' or just 'photos.getSizes'
123 * @param array $params Additional API call arguments.
124 * @param string $method HTTP method to use (GET or POST).
125 * @return object|bool Response as returned by the Flickr or false on invalid authentication
127 public function call($function, array $params = [], $method = 'GET') {
129 if (strpos($function, 'flickr.') !== 0) {
130 $function = 'flickr.'.$function;
133 $params['method'] = $function;
134 $params['format'] = 'json';
135 $params['nojsoncallback'] = 1;
137 $rawresponse = $this->request($method, self
::REST_ROOT
, $params);
138 $response = json_decode($rawresponse);
140 if (!is_object($response) ||
!isset($response->stat
)) {
141 throw new moodle_exception('flickr_api_call_failed', 'core_error', '', $rawresponse);
144 if ($response->stat
=== 'ok') {
147 } else if ($response->stat
=== 'fail' && $response->code
== 98) {
148 // Authentication failure, give the caller a chance to re-authenticate.
152 throw new moodle_exception('flickr_api_call_failed', 'core_error', '', $response);
159 * Return the URL to fetch the given photo from.
161 * Flickr photos are distributed via farm servers staticflickr.com in
162 * various sizes (resolutions). The method tries to find the source URL of
163 * the photo in the highest possible resolution. Results are cached so that
164 * we do not need to query the Flickr API over and over again.
166 * @param string $photoid Flickr photo identifier
169 public function get_photo_url($photoid) {
171 $cache = cache
::make_from_params(cache_store
::MODE_APPLICATION
, 'core', 'flickrclient');
173 $url = $cache->get('photourl_'.$photoid);
175 if ($url === false) {
176 $response = $this->call('photos.getSizes', ['photo_id' => $photoid]);
177 // Sizes are returned from smallest to greatest.
178 if (!empty($response->sizes
->size
) && is_array($response->sizes
->size
)) {
179 while ($bestsize = array_pop($response->sizes
->size
)) {
180 if (isset($bestsize->source
)) {
181 $url = $bestsize->source
;
188 if ($url === false) {
189 throw new repository_exception('cannotdownload', 'repository');
192 $cache->set('photourl_'.$photoid, $url);
199 * Upload a photo from Moodle file pool to Flickr.
201 * Optional meta information are title, description, tags, is_public,
202 * is_friend, is_family, safety_level, content_type and hidden.
203 * See {@link https://www.flickr.com/services/api/upload.api.html}.
205 * Upload can't be asynchronous because then the query would not return the
206 * photo ID which we need to add the photo to a photoset (album)
209 * @param stored_file $photo stored in Moodle file pool
210 * @param array $meta optional meta information
211 * @return int|bool photo id, false on authentication failure
213 public function upload(stored_file
$photo, array $meta = []) {
216 'title' => isset($meta['title']) ?
$meta['title'] : null,
217 'description' => isset($meta['description']) ?
$meta['description'] : null,
218 'tags' => isset($meta['tags']) ?
$meta['tags'] : null,
219 'is_public' => isset($meta['is_public']) ?
$meta['is_public'] : 0,
220 'is_friend' => isset($meta['is_friend']) ?
$meta['is_friend'] : 0,
221 'is_family' => isset($meta['is_family']) ?
$meta['is_family'] : 0,
222 'safety_level' => isset($meta['safety_level']) ?
$meta['safety_level'] : 1,
223 'content_type' => isset($meta['content_type']) ?
$meta['content_type'] : 1,
224 'hidden' => isset($meta['hidden']) ?
$meta['hidden'] : 2,
227 $this->sign_secret
= $this->consumer_secret
.'&'.$this->access_token_secret
;
228 $params = $this->prepare_oauth_parameters(self
::UPLOAD_ROOT
, ['oauth_token' => $this->access_token
] +
$args, 'POST');
230 $params['photo'] = $photo;
232 $response = $this->http
->post(self
::UPLOAD_ROOT
, $params);
235 $xml = simplexml_load_string($response);
237 if ((string)$xml['stat'] === 'ok') {
238 return (int)$xml->photoid
;
240 } else if ((string)$xml['stat'] === 'fail' && (int)$xml->err
['code'] == 98) {
241 // Authentication failure.
245 throw new moodle_exception('flickr_upload_failed', 'core_error', '',
246 ['code' => (int)$xml->err
['code'], 'message' => (string)$xml->err
['msg']]);
250 throw new moodle_exception('flickr_upload_error', 'core_error', '', null, $response);