[moodle] / moodle / lib / googleapi.php Repository:

Annotation of /moodle/lib/googleapi.php

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.8 - (view) (download)

1 : samhemelryk 1.7 <?php
2 : poltawski 1.1 /**
3 :     * Moodle - Modular Object-Oriented Dynamic Learning Environment
4 :     * http://moodle.org
5 :     * Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com
6 :     *
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.
11 :     *
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.
16 :     *
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/>.
19 :     *
20 : samhemelryk 1.7 * @package moodlecore
21 : poltawski 1.1 * @subpackage lib
22 : samhemelryk 1.7 * @copyright Dan Poltawski <talktodan@gmail.com>
23 :     * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 : poltawski 1.1 *
25 :     * Simple implementation of some Google API functions for Moodle.
26 :     */
27 :    
28 : samhemelryk 1.7 /** Include essential file */
29 : poltawski 1.1 require_once($CFG->libdir.'/filelib.php');
30 :    
31 :     /**
32 :     * Base class for google authenticated http requests
33 :     *
34 :     * Most Google API Calls required that requests are sent with an
35 :     * Authorization header + token. This class extends the curl class
36 :     * to aid this
37 : samhemelryk 1.7 *
38 :     * @package moodlecore
39 :     * @subpackage lib
40 :     * @copyright Dan Poltawski <talktodan@gmail.com>
41 :     * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42 : poltawski 1.1 */
43 :     abstract class google_auth_request extends curl{
44 :     protected $token = '';
45 :    
46 :     // Must be overriden with the authorization header name
47 :     public abstract static function get_auth_header_name();
48 :    
49 :     protected function request($url, $options = array()){
50 :     if($this->token){
51 :     // Adds authorisation head to a request so that it can be authentcated
52 :     $this->setHeader('Authorization: '. $this->get_auth_header_name().'"'.$this->token.'"');
53 :     }
54 :    
55 :     $ret = parent::request($url, $options);
56 :     // reset headers for next request
57 :     $this->header = array();
58 :     return $ret;
59 :     }
60 :    
61 : poltawski 1.6 protected function multi($requests, $options = array()) {
62 :     if($this->token){
63 :     // Adds authorisation head to a request so that it can be authentcated
64 :     $this->setHeader('Authorization: '. $this->get_auth_header_name().'"'.$this->token.'"');
65 :     }
66 :    
67 :     $ret = parent::multi($requests, $options);
68 :     // reset headers for next request
69 :     $this->header = array();
70 :     return $ret;
71 :     }
72 :    
73 : poltawski 1.1 public function get_sessiontoken(){
74 :     return $this->token;
75 :     }
76 :     }
77 :    
78 :     /*******
79 :     * The following two classes are usd to implement AuthSub google
80 :     * authtentication, as documented here:
81 :     * http://code.google.com/apis/accounts/docs/AuthSub.html
82 :     *******/
83 :    
84 :     /**
85 :     * Used to uprade a google AuthSubRequest one-time token into
86 :     * a session token which can be used long term.
87 : samhemelryk 1.7 *
88 :     * @package moodlecore
89 :     * @subpackage lib
90 :     * @copyright Dan Poltawski <talktodan@gmail.com>
91 :     * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92 : poltawski 1.1 */
93 :     class google_authsub_request extends google_auth_request {
94 :     const AUTHSESSION_URL = 'https://www.google.com/accounts/AuthSubSessionToken';
95 :    
96 :     /**
97 :     * Constructor. Calls constructor of its parents
98 :     *
99 :     * @param string $authtoken The token to upgrade to a session token
100 :     */
101 :     public function __construct($authtoken){
102 :     parent::__construct();
103 :     $this->token = $authtoken;
104 :     }
105 :    
106 :     /**
107 :     * Requests a long-term session token from google based on the
108 :     *
109 :     * @return string Sub-Auth token
110 :     */
111 :     public function get_session_token(){
112 :     $content = $this->get(google_authsub_request::AUTHSESSION_URL);
113 :    
114 :     if( preg_match('/token=(.*)/i', $content, $matches) ){
115 :     return $matches[1];
116 :     }else{
117 :     throw new moodle_exception('could not upgrade google authtoken to session token');
118 :     }
119 :     }
120 :    
121 :     public static function get_auth_header_name(){
122 :     return 'AuthSub token=';
123 :     }
124 :     }
125 :    
126 :     /**
127 :     * Allows http calls using google subauth authorisation
128 : samhemelryk 1.7 *
129 :     * @package moodlecore
130 :     * @subpackage lib
131 :     * @copyright Dan Poltawski <talktodan@gmail.com>
132 :     * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
133 : poltawski 1.1 */
134 :     class google_authsub extends google_auth_request {
135 :     const LOGINAUTH_URL = 'https://www.google.com/accounts/AuthSubRequest';
136 :     const VERIFY_TOKEN_URL = 'https://www.google.com/accounts/AuthSubTokenInfo';
137 :     const REVOKE_TOKEN_URL = 'https://www.google.com/accounts/AuthSubRevokeToken';
138 :    
139 :     /**
140 :     * Constructor, allows subauth requests using the response from an initial
141 :     * AuthSubRequest or with the subauth long-term token. Note that constructing
142 :     * this object without a valid token will cause an exception to be thrown.
143 :     *
144 :     * @param string $sessiontoken A long-term subauth session token
145 :     * @param string $authtoken A one-time auth token wich is used to upgrade to session token
146 :     * @param mixed @options Options to pass to the base curl object
147 :     */
148 :     public function __construct($sessiontoken = '', $authtoken = '', $options = array()){
149 :     parent::__construct($options);
150 :    
151 :     if( $authtoken ){
152 :     $gauth = new google_authsub_request($authtoken);
153 :     $sessiontoken = $gauth->get_session_token();
154 :     }
155 :    
156 :     $this->token = $sessiontoken;
157 :     if(! $this->valid_token() ){
158 :     throw new moodle_exception('Invalid subauth token');
159 :     }
160 :     }
161 :    
162 :     /**
163 :     * Tests if a subauth token used is valid
164 :     *
165 :     * @return boolean true if token valid
166 :     */
167 :     public function valid_token(){
168 :     $this->get(google_authsub::VERIFY_TOKEN_URL);
169 :    
170 :     if($this->info['http_code'] === 200){
171 :     return true;
172 :     }else{
173 :     return false;
174 :     }
175 :     }
176 :    
177 :     /**
178 :     * Calls googles api to revoke the subauth token
179 :     *
180 :     * @return boolean Returns true if token succesfully revoked
181 :     */
182 :     public function revoke_session_token(){
183 :     $this->get(google_authsub::REVOKE_TOKEN_URL);
184 :    
185 :     if($this->info['http_code'] === 200){
186 :     $this->token = '';
187 :     return true;
188 :     }else{
189 :     return false;
190 :     }
191 :     }
192 :    
193 :     /**
194 :     * Creates a login url for subauth request
195 :     *
196 :     * @param string $returnaddr The address which the user should be redirected to recieve the token
197 :     * @param string $realm The google realm which is access is being requested
198 :     * @return string URL to bounce the user to
199 :     */
200 :     public static function login_url($returnaddr, $realm){
201 :     $uri = google_authsub::LOGINAUTH_URL.'?next='
202 :     .urlencode($returnaddr)
203 :     .'&scope='
204 :     .urlencode($realm)
205 :     .'&session=1&secure=0';
206 :    
207 :     return $uri;
208 :     }
209 :    
210 :     public static function get_auth_header_name(){
211 :     return 'AuthSub token=';
212 :     }
213 :     }
214 :    
215 :     /**
216 :     * Class for manipulating google documents through the google data api
217 :     * Docs for this can be found here:
218 : samhemelryk 1.7 * {@link http://code.google.com/apis/documents/docs/2.0/developers_guide_protocol.html}
219 :     *
220 :     * @package moodlecore
221 :     * @subpackage lib
222 :     * @copyright Dan Poltawski <talktodan@gmail.com>
223 :     * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
224 : poltawski 1.1 */
225 :     class google_docs {
226 : poltawski 1.6 // need both docs and the spreadsheets realm
227 :     const REALM = 'http://docs.google.com/feeds/ http://spreadsheets.google.com/feeds/';
228 : poltawski 1.1 const DOCUMENTFEED_URL = 'http://docs.google.com/feeds/documents/private/full';
229 :     const USER_PREF_NAME = 'google_authsub_sesskey';
230 :    
231 :     private $google_curl = null;
232 :    
233 :     /**
234 :     * Constructor.
235 :     *
236 :     * @param object A google_auth_request object which can be used to do http requests
237 :     */
238 :     public function __construct($google_curl){
239 :     if(is_a($google_curl, 'google_auth_request')){
240 :     $this->google_curl = $google_curl;
241 :     }else{
242 :     throw new moodle_exception('Google Curl Request object not given');
243 :     }
244 :     }
245 :    
246 :     public static function get_sesskey($userid){
247 :     return get_user_preferences(google_docs::USER_PREF_NAME, false, $userid);
248 :     }
249 :    
250 :     public static function set_sesskey($value, $userid){
251 :     return set_user_preference(google_docs::USER_PREF_NAME, $value, $userid);
252 :     }
253 :    
254 :     public static function delete_sesskey($userid){
255 :     return unset_user_preference(google_docs::USER_PREF_NAME, $userid);
256 :     }
257 :    
258 :     /**
259 :     * Returns a list of files the user has formated for files api
260 :     *
261 :     * @param string $search A search string to do full text search on the documents
262 :     * @return mixed Array of files formated for fileapoi
263 :     */
264 :     #FIXME
265 :     public function get_file_list($search = ''){
266 : poltawski 1.6 global $CFG;
267 : poltawski 1.1 $url = google_docs::DOCUMENTFEED_URL;
268 :    
269 :     if($search){
270 :     $url.='?q='.urlencode($search);
271 :     }
272 :     $content = $this->google_curl->get($url);
273 :    
274 :     $xml = new SimpleXMLElement($content);
275 :    
276 : poltawski 1.6
277 :    
278 : poltawski 1.1 $files = array();
279 :     foreach($xml->entry as $gdoc){
280 :    
281 : poltawski 1.6 // there doesn't seem to to be cleaner way of getting the id/type
282 :     // than spliting this..
283 :     if (preg_match('/^http:\/\/docs.google.com\/feeds\/documents\/private\/full\/([^%]*)%3A(.*)$/', $gdoc->id, $matches)){
284 :     $docid = $matches[2];
285 :    
286 :     // FIXME: We're making hard-coded choices about format here.
287 :     // If the repo api can support it, we could let the user
288 :     // chose.
289 :     switch($matches[1]){
290 :     case 'document':
291 :     $title = $gdoc->title.'.rtf';
292 :     $source = 'http://docs.google.com/feeds/download/documents/Export?docID='.$docid.'&exportFormat=rtf';
293 :     break;
294 :     case 'presentation':
295 :     $title = $gdoc->title.'.ppt';
296 :     $source = 'http://docs.google.com/feeds/download/presentations/Export?docID='.$docid.'&exportFormat=ppt';
297 :     break;
298 :     case 'spreadsheet':
299 :     $title = $gdoc->title.'.xls';
300 :     $source = 'http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key='.$docid.'&fmcmd=4';
301 :     break;
302 :     }
303 :    
304 :     $files[] = array( 'title' => $title,
305 :     'url' => "{$gdoc->link[0]->attributes()->href}",
306 :     'source' => $source,
307 :     'date' => usertime(strtotime($gdoc->updated)),
308 : dongsheng 1.8 'thumbnail' => $CFG->wwwroot.'/pix/f/'.mimeinfo('icon32', $title)
309 : poltawski 1.6 );
310 :     }
311 : poltawski 1.1 }
312 :    
313 :     return $files;
314 :     }
315 :    
316 :     /**
317 :     * Sends a file object to google documents
318 :     *
319 :     * @param object $file File object
320 :     * @return boolean True on success
321 :     */
322 :     public function send_file($file){
323 :     $this->google_curl->setHeader("Content-Length: ". $file->get_filesize());
324 :     $this->google_curl->setHeader("Content-Type: ". $file->get_mimetype());
325 :     $this->google_curl->setHeader("Slug: ". $file->get_filename());
326 :    
327 :     $this->google_curl->post(google_docs::DOCUMENTFEED_URL, $file->get_content());
328 :    
329 :     if($this->google_curl->info['http_code'] === 201){
330 :     return true;
331 :     }else{
332 :     return false;
333 :     }
334 :     }
335 :    
336 :     public function download_file($url, $fp){
337 :     return $this->google_curl->download(array( array('url'=>$url, 'file' => $fp) ));
338 :     }
339 :     }
340 :    
341 :     /**
342 :     * Class for manipulating picasa through the google data api
343 :     * Docs for this can be found here:
344 : samhemelryk 1.7 * {@link http://code.google.com/apis/picasaweb/developers_guide_protocol.html}
345 :     *
346 :     * @package moodlecore
347 :     * @subpackage lib
348 :     * @copyright Dan Poltawski <talktodan@gmail.com>
349 :     * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
350 : poltawski 1.1 */
351 :     class google_picasa {
352 :     const REALM = 'http://picasaweb.google.com/data/';
353 :     const USER_PREF_NAME = 'google_authsub_sesskey_picasa';
354 :     const UPLOAD_LOCATION = 'http://picasaweb.google.com/data/feed/api/user/default/albumid/default';
355 : poltawski 1.2 const ALBUM_PHOTO_LIST = 'http://picasaweb.google.com/data/feed/api/user/default/albumid/';
356 :     const PHOTO_SEARCH_URL = 'http://picasaweb.google.com/data/feed/api/user/default?kind=photo&q=';
357 :     const LIST_ALBUMS_URL = 'http://picasaweb.google.com/data/feed/api/user/default';
358 : poltawski 1.1
359 :     private $google_curl = null;
360 :    
361 :     /**
362 :     * Constructor.
363 :     *
364 :     * @param object A google_auth_request object which can be used to do http requests
365 :     */
366 :     public function __construct($google_curl){
367 :     if(is_a($google_curl, 'google_auth_request')){
368 :     $this->google_curl = $google_curl;
369 :     }else{
370 :     throw new moodle_exception('Google Curl Request object not given');
371 :     }
372 :     }
373 :    
374 :     public static function get_sesskey($userid){
375 :     return get_user_preferences(google_picasa::USER_PREF_NAME, false, $userid);
376 :     }
377 :    
378 :     public static function set_sesskey($value, $userid){
379 :     return set_user_preference(google_picasa::USER_PREF_NAME, $value, $userid);
380 :     }
381 :    
382 :     public static function delete_sesskey($userid){
383 :     return unset_user_preference(google_picasa::USER_PREF_NAME, $userid);
384 :     }
385 :    
386 :     /**
387 :     * Sends a file object to picasaweb
388 :     *
389 :     * @param object $file File object
390 :     * @return boolean True on success
391 :     */
392 :     public function send_file($file){
393 :     $this->google_curl->setHeader("Content-Length: ". $file->get_filesize());
394 :     $this->google_curl->setHeader("Content-Type: ". $file->get_mimetype());
395 :     $this->google_curl->setHeader("Slug: ". $file->get_filename());
396 :    
397 :     $this->google_curl->post(google_picasa::UPLOAD_LOCATION, $file->get_content());
398 :    
399 :     if($this->google_curl->info['http_code'] === 201){
400 :     return true;
401 :     }else{
402 :     return false;
403 :     }
404 :     }
405 : poltawski 1.2
406 :     /**
407 :     * Returns list of photos for file picker.
408 :     * If top level then returns list of albums, otherwise
409 :     * photos within an album.
410 :     *
411 :     * @param string $path The path to files (assumed to be albumid)
412 :     * @return mixed $files A list of files for the file picker
413 :     */
414 :     public function get_file_list($path = ''){
415 :     if(!$path){
416 :     return $this->get_albums();
417 :     }else{
418 :     return $this->get_album_photos($path);
419 :     }
420 :     }
421 :    
422 :     /**
423 :     * Returns list of photos in album specified
424 :     *
425 :     * @param int $albumid Photo album to list photos from
426 :     * @return mixed $files A list of files for the file picker
427 :     */
428 :     public function get_album_photos($albumid){
429 :     $albumcontent = $this->google_curl->get(google_picasa::ALBUM_PHOTO_LIST.$albumid);
430 :    
431 :     return $this->get_photo_details($albumcontent);
432 :     }
433 :    
434 :     /**
435 :     * Does text search on the users photos and returns
436 :     * matches in format for picasa api
437 :     *
438 :     * @param string $query Search terms
439 :     * @return mixed $files A list of files for the file picker
440 :     */
441 :     public function do_photo_search($query){
442 :     $content = $this->google_curl->get(google_picasa::PHOTO_SEARCH_URL.htmlentities($query));
443 :    
444 :     return $this->get_photo_details($content);
445 :     }
446 :    
447 :     /**
448 :     * Gets all the users albums and returns them as a list of folders
449 :     * for the file picker
450 :     *
451 :     * @return mixes $files Array in the format get_listing uses for folders
452 :     */
453 :     public function get_albums(){
454 :     $content = $this->google_curl->get(google_picasa::LIST_ALBUMS_URL);
455 :     $xml = new SimpleXMLElement($content);
456 :    
457 :     $files = array();
458 :    
459 :     foreach($xml->entry as $album){
460 :     $gphoto = $album->children('http://schemas.google.com/photos/2007');
461 :    
462 :     $mediainfo = $album->children('http://search.yahoo.com/mrss/');
463 :     //hacky...
464 :     $thumbnailinfo = $mediainfo->group->thumbnail[0]->attributes();
465 :    
466 :     $files[] = array( 'title' => (string) $gphoto->name,
467 :     'date' => userdate($gphoto->timestamp),
468 :     'size' => (int) $gphoto->bytesUsed,
469 :     'path' => (string) $gphoto->id,
470 :     'thumbnail' => (string) $thumbnailinfo['url'],
471 : moodler 1.3 'thumbnail_width' => 160, // 160 is the native maximum dimension
472 :     'thumbnail_height' => 160,
473 : poltawski 1.2 'children' => array(),
474 :     );
475 :    
476 :     }
477 :    
478 :     return $files;
479 :     }
480 :    
481 :     /**
482 :     * Recieves XML from a picasa list of photos and returns
483 :     * array in format for file picker.
484 :     *
485 :     * @param string $rawxml XML from picasa api
486 :     * @return mixed $files A list of files for the file picker
487 :     */
488 :     public function get_photo_details($rawxml){
489 :    
490 :     $xml = new SimpleXMLElement($rawxml);
491 :    
492 :     $files = array();
493 :    
494 :     foreach($xml->entry as $photo){
495 :     $gphoto = $photo->children('http://schemas.google.com/photos/2007');
496 :    
497 :     $mediainfo = $photo->children('http://search.yahoo.com/mrss/');
498 :     $fullinfo = $mediainfo->group->content->attributes();
499 :     //hacky...
500 :     $thumbnailinfo = $mediainfo->group->thumbnail[0]->attributes();
501 :    
502 : moodler 1.4 // Derive the nicest file name we can
503 :     if (!empty($mediainfo->group->description)) {
504 :     $title = shorten_text((string)$mediainfo->group->description, 20, false, '');
505 :     $title = clean_filename($title).'.jpg';
506 :     } else {
507 :     $title = (string)$mediainfo->group->title;
508 :     }
509 :    
510 :     $files[] = array(
511 :     'title' => $title,
512 : poltawski 1.2 'date' => userdate($gphoto->timestamp),
513 :     'size' => (int) $gphoto->size,
514 :     'path' => $gphoto->albumid.'/'.$gphoto->id,
515 :     'thumbnail' => (string) $thumbnailinfo['url'],
516 : moodler 1.3 'thumbnail_width' => 72, // 72 is the native maximum dimension
517 :     'thumbnail_height' => 72,
518 : moodler 1.5 'source' => (string) $fullinfo['url'],
519 :     'url' => (string) $fullinfo['url']
520 : poltawski 1.2 );
521 :     }
522 :    
523 :     return $files;
524 :     }
525 :    
526 : poltawski 1.1 }
527 :    
528 :     /**
529 :     * Beginings of an implementation of Clientogin authenticaton for google
530 :     * accounts as documented here:
531 : samhemelryk 1.7 * {@link http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#ClientLogin}
532 : poltawski 1.1 *
533 :     * With this authentication we have to accept a username and password and to post
534 :     * it to google. Retrieving a token for use afterwards.
535 : samhemelryk 1.7 *
536 :     * @package moodlecore
537 :     * @subpackage lib
538 :     * @copyright Dan Poltawski <talktodan@gmail.com>
539 :     * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
540 : poltawski 1.1 */
541 :     class google_authclient extends google_auth_request {
542 :     const LOGIN_URL = 'https://www.google.com/accounts/ClientLogin';
543 :    
544 :     public function __construct($sessiontoken = '', $username = '', $password = '', $options = array() ){
545 :     parent::__construct($options);
546 :    
547 :     if($username and $password){
548 :     $param = array(
549 :     'accountType'=>'GOOGLE',
550 :     'Email'=>$username,
551 :     'Passwd'=>$password,
552 :     'service'=>'writely'
553 :     );
554 :    
555 :     $content = $this->post(google_authclient::LOGIN_URL, $param);
556 :    
557 :     if( preg_match('/auth=(.*)/i', $content, $matches) ){
558 :     $sessiontoken = $matches[1];
559 :     }else{
560 :     throw new moodle_exception('could not upgrade authtoken');
561 :     }
562 :    
563 :     }
564 :    
565 :     if($sessiontoken){
566 :     $this->token = $sessiontoken;
567 :     }else{
568 :     throw new moodle_exception('no session token specified');
569 :     }
570 :     }
571 :    
572 :     public static function get_auth_header_name(){
573 :     return 'GoogleLogin auth=';
574 :     }
575 :     }
576 :    
577 :     ?>

Moodle CVS Admin
ViewVC Help
Powered by ViewVC 1.0.7