Automatic installer lang files (20110214)
[moodle.git] / lib / googleapi.php
blobcb09710cb2a6f2d30085aee0ec8198bc2a9d09c3
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 = 'http://docs.google.com/feeds/ http://spreadsheets.google.com/feeds/ http://docs.googleusercontent.com/';
245 const DOCUMENTFEED_URL = 'http://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);
297 $files = array();
298 foreach($xml->entry as $gdoc){
299 $docid = (string) $gdoc->children('http://schemas.google.com/g/2005')->resourceId;
300 list($type, $docid) = explode(':', $docid);
302 $title = '';
303 $source = '';
304 // FIXME: We're making hard-coded choices about format here.
305 // If the repo api can support it, we could let the user
306 // chose.
307 switch($type){
308 case 'document':
309 $title = $gdoc->title.'.rtf';
310 $source = 'http://docs.google.com/feeds/download/documents/Export?id='.$docid.'&exportFormat=rtf';
311 break;
312 case 'presentation':
313 $title = $gdoc->title.'.ppt';
314 $source = 'http://docs.google.com/feeds/download/presentations/Export?id='.$docid.'&exportFormat=ppt';
315 break;
316 case 'spreadsheet':
317 $title = $gdoc->title.'.xls';
318 $source = 'http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key='.$docid.'&exportFormat=xls';
319 break;
320 case 'pdf':
321 $title = (string)$gdoc->title;
322 $source = (string)$gdoc->content[0]->attributes()->src;
323 break;
326 if(!empty($source)){
327 $files[] = array( 'title' => $title,
328 'url' => "{$gdoc->link[0]->attributes()->href}",
329 'source' => $source,
330 'date' => usertime(strtotime($gdoc->updated)),
331 '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 = 'http://picasaweb.google.com/data/feed/api/user/default/albumid/default';
378 const ALBUM_PHOTO_LIST = 'http://picasaweb.google.com/data/feed/api/user/default/albumid/';
379 const PHOTO_SEARCH_URL = 'http://picasaweb.google.com/data/feed/api/user/default?kind=photo&q=';
380 const LIST_ALBUMS_URL = 'http://picasaweb.google.com/data/feed/api/user/default';
382 private $google_curl = null;
385 * Constructor.
387 * @param object A google_auth_request object which can be used to do http requests
389 public function __construct($google_curl){
390 if(is_a($google_curl, 'google_auth_request')){
391 $this->google_curl = $google_curl;
392 $this->google_curl->add_persistant_header('GData-Version: 2');
393 }else{
394 throw new moodle_exception('Google Curl Request object not given');
398 public static function get_sesskey($userid){
399 return get_user_preferences(google_picasa::USER_PREF_NAME, false, $userid);
402 public static function set_sesskey($value, $userid){
403 return set_user_preference(google_picasa::USER_PREF_NAME, $value, $userid);
406 public static function delete_sesskey($userid){
407 return unset_user_preference(google_picasa::USER_PREF_NAME, $userid);
411 * Sends a file object to picasaweb
413 * @param object $file File object
414 * @return boolean True on success
416 public function send_file($file){
417 $this->google_curl->setHeader("Content-Length: ". $file->get_filesize());
418 $this->google_curl->setHeader("Content-Type: ". $file->get_mimetype());
419 $this->google_curl->setHeader("Slug: ". $file->get_filename());
421 $this->google_curl->post(google_picasa::UPLOAD_LOCATION, $file->get_content());
423 if($this->google_curl->info['http_code'] === 201){
424 return true;
425 }else{
426 return false;
431 * Returns list of photos for file picker.
432 * If top level then returns list of albums, otherwise
433 * photos within an album.
435 * @param string $path The path to files (assumed to be albumid)
436 * @return mixed $files A list of files for the file picker
438 public function get_file_list($path = ''){
439 if(!$path){
440 return $this->get_albums();
441 }else{
442 return $this->get_album_photos($path);
447 * Returns list of photos in album specified
449 * @param int $albumid Photo album to list photos from
450 * @return mixed $files A list of files for the file picker
452 public function get_album_photos($albumid){
453 $albumcontent = $this->google_curl->get(google_picasa::ALBUM_PHOTO_LIST.$albumid);
455 return $this->get_photo_details($albumcontent);
459 * Does text search on the users photos and returns
460 * matches in format for picasa api
462 * @param string $query Search terms
463 * @return mixed $files A list of files for the file picker
465 public function do_photo_search($query){
466 $content = $this->google_curl->get(google_picasa::PHOTO_SEARCH_URL.htmlentities($query));
468 return $this->get_photo_details($content);
472 * Gets all the users albums and returns them as a list of folders
473 * for the file picker
475 * @return mixes $files Array in the format get_listing uses for folders
477 public function get_albums(){
478 $content = $this->google_curl->get(google_picasa::LIST_ALBUMS_URL);
479 $xml = new SimpleXMLElement($content);
481 $files = array();
483 foreach($xml->entry as $album){
484 $gphoto = $album->children('http://schemas.google.com/photos/2007');
486 $mediainfo = $album->children('http://search.yahoo.com/mrss/');
487 //hacky...
488 $thumbnailinfo = $mediainfo->group->thumbnail[0]->attributes();
490 $files[] = array( 'title' => (string) $gphoto->name,
491 'date' => userdate($gphoto->timestamp),
492 'size' => (int) $gphoto->bytesUsed,
493 'path' => (string) $gphoto->id,
494 'thumbnail' => (string) $thumbnailinfo['url'],
495 'thumbnail_width' => 160, // 160 is the native maximum dimension
496 'thumbnail_height' => 160,
497 'children' => array(),
502 return $files;
506 * Recieves XML from a picasa list of photos and returns
507 * array in format for file picker.
509 * @param string $rawxml XML from picasa api
510 * @return mixed $files A list of files for the file picker
512 public function get_photo_details($rawxml){
514 $xml = new SimpleXMLElement($rawxml);
516 $files = array();
518 foreach($xml->entry as $photo){
519 $gphoto = $photo->children('http://schemas.google.com/photos/2007');
521 $mediainfo = $photo->children('http://search.yahoo.com/mrss/');
522 $fullinfo = $mediainfo->group->content->attributes();
523 //hacky...
524 $thumbnailinfo = $mediainfo->group->thumbnail[0]->attributes();
526 // Derive the nicest file name we can
527 if (!empty($mediainfo->group->description)) {
528 $title = shorten_text((string)$mediainfo->group->description, 20, false, '');
529 $title = clean_filename($title).'.jpg';
530 } else {
531 $title = (string)$mediainfo->group->title;
534 $files[] = array(
535 'title' => $title,
536 'date' => userdate($gphoto->timestamp),
537 'size' => (int) $gphoto->size,
538 'path' => $gphoto->albumid.'/'.$gphoto->id,
539 'thumbnail' => (string) $thumbnailinfo['url'],
540 'thumbnail_width' => 72, // 72 is the native maximum dimension
541 'thumbnail_height' => 72,
542 'source' => (string) $fullinfo['url'],
543 'url' => (string) $fullinfo['url']
547 return $files;
553 * Beginings of an implementation of Clientogin authenticaton for google
554 * accounts as documented here:
555 * {@link http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#ClientLogin}
557 * With this authentication we have to accept a username and password and to post
558 * it to google. Retrieving a token for use afterwards.
560 * @package moodlecore
561 * @subpackage lib
562 * @copyright Dan Poltawski <talktodan@gmail.com>
563 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
565 class google_authclient extends google_auth_request {
566 const LOGIN_URL = 'https://www.google.com/accounts/ClientLogin';
568 public function __construct($sessiontoken = '', $username = '', $password = '', $options = array() ){
569 parent::__construct($options);
571 if($username and $password){
572 $param = array(
573 'accountType'=>'GOOGLE',
574 'Email'=>$username,
575 'Passwd'=>$password,
576 'service'=>'writely'
579 $content = $this->post(google_authclient::LOGIN_URL, $param);
581 if( preg_match('/auth=(.*)/i', $content, $matches) ){
582 $sessiontoken = $matches[1];
583 }else{
584 throw new moodle_exception('could not upgrade authtoken');
589 if($sessiontoken){
590 $this->token = $sessiontoken;
591 }else{
592 throw new moodle_exception('no session token specified');
596 public static function get_auth_header_name(){
597 return 'GoogleLogin auth=';