3 * Moodle - Modular Object-Oriented Dynamic Learning Environment
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/>.
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');
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
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()){
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){
64 $ret = parent
::request($url, $options);
65 // reset headers for next request
66 $this->header
= array();
70 protected function multi($requests, $options = array()) {
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){
80 $ret = parent
::multi($requests, $options);
81 // reset headers for next request
82 $this->header
= array();
86 public function get_sessiontoken(){
90 public function add_persistant_header($header){
91 $this->persistantheaders
[] = $header;
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
102 * Used to uprade a google AuthSubRequest one-time token into
103 * a session token which can be used long term.
105 * @package moodlecore
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) ){
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
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);
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){
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){
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)
222 .'&session=1&secure=0';
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
239 * @copyright Dan Poltawski <talktodan@gmail.com>
240 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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;
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');
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
283 public function get_file_list($search = ''){
284 global $CFG, $OUTPUT;
285 $url = google_docs
::DOCUMENTFEED_URL
;
288 $url.='?q='.urlencode($search);
290 $content = $this->google_curl
->get($url);
292 $xml = new SimpleXMLElement($content);
296 foreach($xml->entry
as $gdoc){
297 $docid = (string) $gdoc->children('http://schemas.google.com/g/2005')->resourceId
;
298 list($type, $docid) = explode(':', $docid);
302 // FIXME: We're making hard-coded choices about format here.
303 // If the repo api can support it, we could let the user
307 $title = $gdoc->title
.'.rtf';
308 $source = 'https://docs.google.com/feeds/download/documents/Export?id='.$docid.'&exportFormat=rtf';
311 $title = $gdoc->title
.'.ppt';
312 $source = 'https://docs.google.com/feeds/download/presentations/Export?id='.$docid.'&exportFormat=ppt';
315 $title = $gdoc->title
.'.xls';
316 $source = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key='.$docid.'&exportFormat=xls';
319 $title = (string)$gdoc->title
;
320 $source = (string)$gdoc->content
[0]->attributes()->src
;
325 $files[] = array( 'title' => $title,
326 'url' => "{$gdoc->link[0]->attributes()->href}",
328 'date' => usertime(strtotime($gdoc->updated
)),
329 'thumbnail' => (string) $OUTPUT->pix_url(file_extension_icon($title, 32))
338 * Sends a file object to google documents
340 * @param object $file File object
341 * @return boolean True on success
343 public function send_file($file){
344 $this->google_curl
->setHeader("Content-Length: ". $file->get_filesize());
345 $this->google_curl
->setHeader("Content-Type: ". $file->get_mimetype());
346 $this->google_curl
->setHeader("Slug: ". $file->get_filename());
348 $this->google_curl
->post(google_docs
::DOCUMENTFEED_URL
, $file->get_content());
350 if($this->google_curl
->info
['http_code'] === 201){
357 public function download_file($url, $fp){
358 return $this->google_curl
->download(array( array('url'=>$url, 'file' => $fp) ));
363 * Class for manipulating picasa through the google data api
364 * Docs for this can be found here:
365 * {@link http://code.google.com/apis/picasaweb/developers_guide_protocol.html}
367 * @package moodlecore
369 * @copyright Dan Poltawski <talktodan@gmail.com>
370 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
372 class google_picasa
{
373 const REALM
= 'http://picasaweb.google.com/data/';
374 const USER_PREF_NAME
= 'google_authsub_sesskey_picasa';
375 const UPLOAD_LOCATION
= 'https://picasaweb.google.com/data/feed/api/user/default/albumid/default';
376 const ALBUM_PHOTO_LIST
= 'https://picasaweb.google.com/data/feed/api/user/default/albumid/';
377 const PHOTO_SEARCH_URL
= 'https://picasaweb.google.com/data/feed/api/user/default?kind=photo&q=';
378 const LIST_ALBUMS_URL
= 'https://picasaweb.google.com/data/feed/api/user/default';
379 const MANAGE_URL
= 'http://picasaweb.google.com/';
381 private $google_curl = null;
386 * @param object A google_auth_request object which can be used to do http requests
388 public function __construct($google_curl){
389 if(is_a($google_curl, 'google_auth_request')){
390 $this->google_curl
= $google_curl;
391 $this->google_curl
->add_persistant_header('GData-Version: 2');
393 throw new moodle_exception('Google Curl Request object not given');
397 public static function get_sesskey($userid){
398 return get_user_preferences(google_picasa
::USER_PREF_NAME
, false, $userid);
401 public static function set_sesskey($value, $userid){
402 return set_user_preference(google_picasa
::USER_PREF_NAME
, $value, $userid);
405 public static function delete_sesskey($userid){
406 return unset_user_preference(google_picasa
::USER_PREF_NAME
, $userid);
410 * Sends a file object to picasaweb
412 * @param object $file File object
413 * @return boolean True on success
415 public function send_file($file){
416 $this->google_curl
->setHeader("Content-Length: ". $file->get_filesize());
417 $this->google_curl
->setHeader("Content-Type: ". $file->get_mimetype());
418 $this->google_curl
->setHeader("Slug: ". $file->get_filename());
420 $this->google_curl
->post(google_picasa
::UPLOAD_LOCATION
, $file->get_content());
422 if($this->google_curl
->info
['http_code'] === 201){
430 * Returns list of photos for file picker.
431 * If top level then returns list of albums, otherwise
432 * photos within an album.
434 * @param string $path The path to files (assumed to be albumid)
435 * @return mixed $files A list of files for the file picker
437 public function get_file_list($path = ''){
439 return $this->get_albums();
441 return $this->get_album_photos($path);
446 * Returns list of photos in album specified
448 * @param int $albumid Photo album to list photos from
449 * @return mixed $files A list of files for the file picker
451 public function get_album_photos($albumid){
452 $albumcontent = $this->google_curl
->get(google_picasa
::ALBUM_PHOTO_LIST
.$albumid);
454 return $this->get_photo_details($albumcontent);
458 * Does text search on the users photos and returns
459 * matches in format for picasa api
461 * @param string $query Search terms
462 * @return mixed $files A list of files for the file picker
464 public function do_photo_search($query){
465 $content = $this->google_curl
->get(google_picasa
::PHOTO_SEARCH_URL
.htmlentities($query));
467 return $this->get_photo_details($content);
471 * Gets all the users albums and returns them as a list of folders
472 * for the file picker
474 * @return mixes $files Array in the format get_listing uses for folders
476 public function get_albums(){
477 $content = $this->google_curl
->get(google_picasa
::LIST_ALBUMS_URL
);
478 $xml = new SimpleXMLElement($content);
482 foreach($xml->entry
as $album){
483 $gphoto = $album->children('http://schemas.google.com/photos/2007');
485 $mediainfo = $album->children('http://search.yahoo.com/mrss/');
487 $thumbnailinfo = $mediainfo->group
->thumbnail
[0]->attributes();
489 $files[] = array( 'title' => (string) $gphoto->name
,
490 'date' => userdate($gphoto->timestamp
),
491 'size' => (int) $gphoto->bytesUsed
,
492 'path' => (string) $gphoto->id
,
493 'thumbnail' => (string) $thumbnailinfo['url'],
494 'thumbnail_width' => 160, // 160 is the native maximum dimension
495 'thumbnail_height' => 160,
496 'children' => array(),
505 * Recieves XML from a picasa list of photos and returns
506 * array in format for file picker.
508 * @param string $rawxml XML from picasa api
509 * @return mixed $files A list of files for the file picker
511 public function get_photo_details($rawxml){
513 $xml = new SimpleXMLElement($rawxml);
517 foreach($xml->entry
as $photo){
518 $gphoto = $photo->children('http://schemas.google.com/photos/2007');
520 $mediainfo = $photo->children('http://search.yahoo.com/mrss/');
521 $fullinfo = $mediainfo->group
->content
->attributes();
523 $thumbnailinfo = $mediainfo->group
->thumbnail
[0]->attributes();
525 // Derive the nicest file name we can
526 if (!empty($mediainfo->group
->description
)) {
527 $title = shorten_text((string)$mediainfo->group
->description
, 20, false, '');
528 $title = clean_filename($title).'.jpg';
530 $title = (string)$mediainfo->group
->title
;
535 'date' => userdate($gphoto->timestamp
),
536 'size' => (int) $gphoto->size
,
537 'path' => $gphoto->albumid
.'/'.$gphoto->id
,
538 'thumbnail' => (string) $thumbnailinfo['url'],
539 'thumbnail_width' => 72, // 72 is the native maximum dimension
540 'thumbnail_height' => 72,
541 'source' => (string) $fullinfo['url'],
542 'url' => (string) $fullinfo['url']
552 * Beginings of an implementation of Clientogin authenticaton for google
553 * accounts as documented here:
554 * {@link http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#ClientLogin}
556 * With this authentication we have to accept a username and password and to post
557 * it to google. Retrieving a token for use afterwards.
559 * @package moodlecore
561 * @copyright Dan Poltawski <talktodan@gmail.com>
562 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
564 class google_authclient
extends google_auth_request
{
565 const LOGIN_URL
= 'https://www.google.com/accounts/ClientLogin';
567 public function __construct($sessiontoken = '', $username = '', $password = '', $options = array() ){
568 parent
::__construct($options);
570 if($username and $password){
572 'accountType'=>'GOOGLE',
578 $content = $this->post(google_authclient
::LOGIN_URL
, $param);
580 if( preg_match('/auth=(.*)/i', $content, $matches) ){
581 $sessiontoken = $matches[1];
583 throw new moodle_exception('could not upgrade authtoken');
589 $this->token
= $sessiontoken;
591 throw new moodle_exception('no session token specified');
595 public static function get_auth_header_name(){
596 return 'GoogleLogin auth=';