MDL-35669 gravatar Fix secure image urls.
[moodle.git] / lib / googleapi.php
blob75d697cafb5b0e9d52e1b86cd92e4702fa74c11d
1 <?php
2 /**
3 * Moodle - Modular Object-Oriented Dynamic Learning Environment
4 * http://moodle.org
5 * Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * @package core
21 * @subpackage lib
22 * @copyright Dan Poltawski <talktodan@gmail.com>
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 * Simple implementation of some Google API functions for Moodle.
28 defined('MOODLE_INTERNAL') || die();
30 /** Include essential file */
31 require_once($CFG->libdir.'/filelib.php');
33 /**
34 * Base class for google authenticated http requests
36 * Most Google API Calls required that requests are sent with an
37 * Authorization header + token. This class extends the curl class
38 * to aid this
40 * @package moodlecore
41 * @subpackage lib
42 * @copyright Dan Poltawski <talktodan@gmail.com>
43 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 abstract class google_auth_request extends curl {
46 protected $token = '';
47 private $persistantheaders = array();
49 // Must be overridden with the authorization header name
50 public static function get_auth_header_name() {
51 throw new coding_exception('get_auth_header_name() method needs to be overridden in each subclass of google_auth_request');
54 protected function request($url, $options = array()){
55 if($this->token){
56 // Adds authorisation head to a request so that it can be authentcated
57 $this->setHeader('Authorization: '. $this->get_auth_header_name().'"'.$this->token.'"');
60 foreach($this->persistantheaders as $h){
61 $this->setHeader($h);
64 $ret = parent::request($url, $options);
65 // reset headers for next request
66 $this->header = array();
67 return $ret;
70 protected function multi($requests, $options = array()) {
71 if($this->token){
72 // Adds authorisation head to a request so that it can be authentcated
73 $this->setHeader('Authorization: '. $this->get_auth_header_name().'"'.$this->token.'"');
76 foreach($this->persistantheaders as $h){
77 $this->setHeader($h);
80 $ret = parent::multi($requests, $options);
81 // reset headers for next request
82 $this->header = array();
83 return $ret;
86 public function get_sessiontoken(){
87 return $this->token;
90 public function add_persistant_header($header){
91 $this->persistantheaders[] = $header;
95 /*******
96 * The following two classes are usd to implement AuthSub google
97 * authtentication, as documented here:
98 * http://code.google.com/apis/accounts/docs/AuthSub.html
99 *******/
102 * Used to uprade a google AuthSubRequest one-time token into
103 * a session token which can be used long term.
105 * @package moodlecore
106 * @subpackage lib
107 * @copyright Dan Poltawski <talktodan@gmail.com>
108 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
110 class google_authsub_request extends google_auth_request {
111 const AUTHSESSION_URL = 'https://www.google.com/accounts/AuthSubSessionToken';
114 * Constructor. Calls constructor of its parents
116 * @param string $authtoken The token to upgrade to a session token
118 public function __construct($authtoken){
119 parent::__construct();
120 $this->token = $authtoken;
124 * Requests a long-term session token from google based on the
126 * @return string Sub-Auth token
128 public function get_session_token(){
129 $content = $this->get(google_authsub_request::AUTHSESSION_URL);
131 if( preg_match('/token=(.*)/i', $content, $matches) ){
132 return $matches[1];
133 }else{
134 throw new moodle_exception('could not upgrade google authtoken to session token');
138 public static function get_auth_header_name(){
139 return 'AuthSub token=';
144 * Allows http calls using google subauth authorisation
146 * @package moodlecore
147 * @subpackage lib
148 * @copyright Dan Poltawski <talktodan@gmail.com>
149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
151 class google_authsub extends google_auth_request {
152 const LOGINAUTH_URL = 'https://www.google.com/accounts/AuthSubRequest';
153 const VERIFY_TOKEN_URL = 'https://www.google.com/accounts/AuthSubTokenInfo';
154 const REVOKE_TOKEN_URL = 'https://www.google.com/accounts/AuthSubRevokeToken';
157 * Constructor, allows subauth requests using the response from an initial
158 * AuthSubRequest or with the subauth long-term token. Note that constructing
159 * this object without a valid token will cause an exception to be thrown.
161 * @param string $sessiontoken A long-term subauth session token
162 * @param string $authtoken A one-time auth token wich is used to upgrade to session token
163 * @param mixed @options Options to pass to the base curl object
165 public function __construct($sessiontoken = '', $authtoken = '', $options = array()){
166 parent::__construct($options);
168 if( $authtoken ){
169 $gauth = new google_authsub_request($authtoken);
170 $sessiontoken = $gauth->get_session_token();
173 $this->token = $sessiontoken;
174 if(! $this->valid_token() ){
175 throw new moodle_exception('Invalid subauth token');
180 * Tests if a subauth token used is valid
182 * @return boolean true if token valid
184 public function valid_token(){
185 $this->get(google_authsub::VERIFY_TOKEN_URL);
187 if($this->info['http_code'] === 200){
188 return true;
189 }else{
190 return false;
195 * Calls googles api to revoke the subauth token
197 * @return boolean Returns true if token succesfully revoked
199 public function revoke_session_token(){
200 $this->get(google_authsub::REVOKE_TOKEN_URL);
202 if($this->info['http_code'] === 200){
203 $this->token = '';
204 return true;
205 }else{
206 return false;
211 * Creates a login url for subauth request
213 * @param string $returnaddr The address which the user should be redirected to recieve the token
214 * @param string $realm The google realm which is access is being requested
215 * @return string URL to bounce the user to
217 public static function login_url($returnaddr, $realm){
218 $uri = google_authsub::LOGINAUTH_URL.'?next='
219 .urlencode($returnaddr)
220 .'&scope='
221 .urlencode($realm)
222 .'&session=1&secure=0';
224 return $uri;
227 public static function get_auth_header_name(){
228 return 'AuthSub token=';
233 * Class for manipulating google documents through the google data api
234 * Docs for this can be found here:
235 * {@link http://code.google.com/apis/documents/docs/2.0/developers_guide_protocol.html}
237 * @package moodlecore
238 * @subpackage lib
239 * @copyright Dan Poltawski <talktodan@gmail.com>
240 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
242 class google_docs {
243 // need both docs and the spreadsheets realm
244 const REALM = 'https://docs.google.com/feeds/ https://spreadsheets.google.com/feeds/ https://docs.googleusercontent.com/';
245 const DOCUMENTFEED_URL = 'https://docs.google.com/feeds/default/private/full';
246 const USER_PREF_NAME = 'google_authsub_sesskey';
248 private $google_curl = null;
251 * Constructor.
253 * @param object A google_auth_request object which can be used to do http requests
255 public function __construct($google_curl){
256 if(is_a($google_curl, 'google_auth_request')){
257 $this->google_curl = $google_curl;
258 $this->google_curl->add_persistant_header('GData-Version: 3.0');
259 }else{
260 throw new moodle_exception('Google Curl Request object not given');
264 public static function get_sesskey($userid){
265 return get_user_preferences(google_docs::USER_PREF_NAME, false, $userid);
268 public static function set_sesskey($value, $userid){
269 return set_user_preference(google_docs::USER_PREF_NAME, $value, $userid);
272 public static function delete_sesskey($userid){
273 return unset_user_preference(google_docs::USER_PREF_NAME, $userid);
277 * Returns a list of files the user has formated for files api
279 * @param string $search A search string to do full text search on the documents
280 * @return mixed Array of files formated for fileapoi
282 #FIXME
283 public function get_file_list($search = ''){
284 global $CFG, $OUTPUT;
285 $url = google_docs::DOCUMENTFEED_URL;
287 if($search){
288 $url.='?q='.urlencode($search);
290 $content = $this->google_curl->get($url);
292 $xml = new SimpleXMLElement($content);
295 $files = array();
296 foreach($xml->entry as $gdoc){
297 $docid = (string) $gdoc->children('http://schemas.google.com/g/2005')->resourceId;
298 list($type, $docid) = explode(':', $docid);
300 $title = '';
301 $source = '';
302 // FIXME: We're making hard-coded choices about format here.
303 // If the repo api can support it, we could let the user
304 // chose.
305 switch($type){
306 case 'document':
307 $title = $gdoc->title.'.rtf';
308 $source = 'https://docs.google.com/feeds/download/documents/Export?id='.$docid.'&exportFormat=rtf';
309 break;
310 case 'presentation':
311 $title = $gdoc->title.'.ppt';
312 $source = 'https://docs.google.com/feeds/download/presentations/Export?id='.$docid.'&exportFormat=ppt';
313 break;
314 case 'spreadsheet':
315 $title = $gdoc->title.'.xls';
316 $source = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key='.$docid.'&exportFormat=xls';
317 break;
318 case 'pdf':
319 case 'file':
320 $title = (string)$gdoc->title;
321 // Some files don't have a content probably because the download has been restricted.
322 if (isset($gdoc->content)) {
323 $source = (string)$gdoc->content[0]->attributes()->src;
325 break;
328 $files[] = array( 'title' => $title,
329 'url' => "{$gdoc->link[0]->attributes()->href}",
330 'source' => $source,
331 'date' => usertime(strtotime($gdoc->updated)),
332 'thumbnail' => (string) $OUTPUT->pix_url(file_extension_icon($title, 32))
336 return $files;
340 * Sends a file object to google documents
342 * @param object $file File object
343 * @return boolean True on success
345 public function send_file($file){
346 $this->google_curl->setHeader("Content-Length: ". $file->get_filesize());
347 $this->google_curl->setHeader("Content-Type: ". $file->get_mimetype());
348 $this->google_curl->setHeader("Slug: ". $file->get_filename());
350 $this->google_curl->post(google_docs::DOCUMENTFEED_URL, $file->get_content());
352 if($this->google_curl->info['http_code'] === 201){
353 return true;
354 }else{
355 return false;
359 public function download_file($url, $fp){
360 return $this->google_curl->download(array( array('url'=>$url, 'file' => $fp) ));
365 * Class for manipulating picasa through the google data api
366 * Docs for this can be found here:
367 * {@link http://code.google.com/apis/picasaweb/developers_guide_protocol.html}
369 * @package moodlecore
370 * @subpackage lib
371 * @copyright Dan Poltawski <talktodan@gmail.com>
372 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
374 class google_picasa {
375 const REALM = 'http://picasaweb.google.com/data/';
376 const USER_PREF_NAME = 'google_authsub_sesskey_picasa';
377 const UPLOAD_LOCATION = 'https://picasaweb.google.com/data/feed/api/user/default/albumid/default';
378 const ALBUM_PHOTO_LIST = 'https://picasaweb.google.com/data/feed/api/user/default/albumid/';
379 const PHOTO_SEARCH_URL = 'https://picasaweb.google.com/data/feed/api/user/default?kind=photo&q=';
380 const LIST_ALBUMS_URL = 'https://picasaweb.google.com/data/feed/api/user/default';
381 const MANAGE_URL = 'http://picasaweb.google.com/';
383 private $google_curl = null;
384 private $lastalbumname = null;
387 * Constructor.
389 * @param object A google_auth_request object which can be used to do http requests
391 public function __construct($google_curl){
392 if(is_a($google_curl, 'google_auth_request')){
393 $this->google_curl = $google_curl;
394 $this->google_curl->add_persistant_header('GData-Version: 2');
395 }else{
396 throw new moodle_exception('Google Curl Request object not given');
400 public static function get_sesskey($userid){
401 return get_user_preferences(google_picasa::USER_PREF_NAME, false, $userid);
404 public static function set_sesskey($value, $userid){
405 return set_user_preference(google_picasa::USER_PREF_NAME, $value, $userid);
408 public static function delete_sesskey($userid){
409 return unset_user_preference(google_picasa::USER_PREF_NAME, $userid);
413 * Sends a file object to picasaweb
415 * @param object $file File object
416 * @return boolean True on success
418 public function send_file($file){
419 $this->google_curl->setHeader("Content-Length: ". $file->get_filesize());
420 $this->google_curl->setHeader("Content-Type: ". $file->get_mimetype());
421 $this->google_curl->setHeader("Slug: ". $file->get_filename());
423 $this->google_curl->post(google_picasa::UPLOAD_LOCATION, $file->get_content());
425 if($this->google_curl->info['http_code'] === 201){
426 return true;
427 }else{
428 return false;
433 * Returns list of photos for file picker.
434 * If top level then returns list of albums, otherwise
435 * photos within an album.
437 * @param string $path The path to files (assumed to be albumid)
438 * @return mixed $files A list of files for the file picker
440 public function get_file_list($path = ''){
441 if(!$path){
442 return $this->get_albums();
443 }else{
444 return $this->get_album_photos($path);
449 * Returns list of photos in album specified
451 * @param int $albumid Photo album to list photos from
452 * @return mixed $files A list of files for the file picker
454 public function get_album_photos($albumid){
455 $albumcontent = $this->google_curl->get(google_picasa::ALBUM_PHOTO_LIST.$albumid);
457 return $this->get_photo_details($albumcontent);
461 * Returns the name of the album for which get_photo_details was called last time.
463 * @return string
465 public function get_last_album_name() {
466 return $this->lastalbumname;
470 * Does text search on the users photos and returns
471 * matches in format for picasa api
473 * @param string $query Search terms
474 * @return mixed $files A list of files for the file picker
476 public function do_photo_search($query){
477 $content = $this->google_curl->get(google_picasa::PHOTO_SEARCH_URL.htmlentities($query));
479 return $this->get_photo_details($content);
483 * Gets all the users albums and returns them as a list of folders
484 * for the file picker
486 * @return mixes $files Array in the format get_listing uses for folders
488 public function get_albums(){
489 $content = $this->google_curl->get(google_picasa::LIST_ALBUMS_URL);
490 $xml = new SimpleXMLElement($content);
492 $files = array();
494 foreach($xml->entry as $album){
495 $gphoto = $album->children('http://schemas.google.com/photos/2007');
497 $mediainfo = $album->children('http://search.yahoo.com/mrss/');
498 //hacky...
499 $thumbnailinfo = $mediainfo->group->thumbnail[0]->attributes();
501 $files[] = array( 'title' => (string) $album->title,
502 'date' => userdate($gphoto->timestamp),
503 'size' => (int) $gphoto->bytesUsed,
504 'path' => (string) $gphoto->id,
505 'thumbnail' => (string) $thumbnailinfo['url'],
506 'thumbnail_width' => 160, // 160 is the native maximum dimension
507 'thumbnail_height' => 160,
508 'children' => array(),
513 return $files;
517 * Recieves XML from a picasa list of photos and returns
518 * array in format for file picker.
520 * @param string $rawxml XML from picasa api
521 * @return mixed $files A list of files for the file picker
523 public function get_photo_details($rawxml){
525 $xml = new SimpleXMLElement($rawxml);
526 $this->lastalbumname = (string)$xml->title;
528 $files = array();
530 foreach($xml->entry as $photo){
531 $gphoto = $photo->children('http://schemas.google.com/photos/2007');
533 $mediainfo = $photo->children('http://search.yahoo.com/mrss/');
534 $fullinfo = $mediainfo->group->content->attributes();
535 //hacky...
536 $thumbnailinfo = $mediainfo->group->thumbnail[0]->attributes();
538 // Derive the nicest file name we can
539 if (!empty($mediainfo->group->description)) {
540 $title = shorten_text((string)$mediainfo->group->description, 20, false, '');
541 $title = clean_filename($title).'.jpg';
542 } else {
543 $title = (string)$mediainfo->group->title;
546 $files[] = array(
547 'title' => $title,
548 'date' => userdate($gphoto->timestamp),
549 'size' => (int) $gphoto->size,
550 'path' => $gphoto->albumid.'/'.$gphoto->id,
551 'thumbnail' => (string) $thumbnailinfo['url'],
552 'thumbnail_width' => 72, // 72 is the native maximum dimension
553 'thumbnail_height' => 72,
554 'source' => (string) $fullinfo['url'],
555 'url' => (string) $fullinfo['url']
559 return $files;
565 * Beginings of an implementation of Clientogin authenticaton for google
566 * accounts as documented here:
567 * {@link http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#ClientLogin}
569 * With this authentication we have to accept a username and password and to post
570 * it to google. Retrieving a token for use afterwards.
572 * @package moodlecore
573 * @subpackage lib
574 * @copyright Dan Poltawski <talktodan@gmail.com>
575 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
577 class google_authclient extends google_auth_request {
578 const LOGIN_URL = 'https://www.google.com/accounts/ClientLogin';
580 public function __construct($sessiontoken = '', $username = '', $password = '', $options = array() ){
581 parent::__construct($options);
583 if($username and $password){
584 $param = array(
585 'accountType'=>'GOOGLE',
586 'Email'=>$username,
587 'Passwd'=>$password,
588 'service'=>'writely'
591 $content = $this->post(google_authclient::LOGIN_URL, $param);
593 if( preg_match('/auth=(.*)/i', $content, $matches) ){
594 $sessiontoken = $matches[1];
595 }else{
596 throw new moodle_exception('could not upgrade authtoken');
601 if($sessiontoken){
602 $this->token = $sessiontoken;
603 }else{
604 throw new moodle_exception('no session token specified');
608 public static function get_auth_header_name(){
609 return 'GoogleLogin auth=';