Merge branch 'MDL-34171_22' of git://github.com/timhunt/moodle into MOODLE_22_STABLE
[moodle.git] / lib / boxlib.php
blob37e27a7400555dd86d9105358e958303ed3ca3ec
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * Box REST Client Library for PHP5 Developers
21 * @package moodlecore
22 * @author James Levy <james@box.net>
23 * @link http://enabled.box.net
24 * @access public
25 * @version 1.0
26 * @copyright copyright Box.net 2007
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 /**
31 * @package moodlecore
32 * @copyright copyright Box.net 2007
33 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 class boxclient {
36 /** @var string */
37 public $auth_token = '';
38 /** @var string */
39 private $_box_api_url = 'https://www.box.com/api/1.0/rest';
40 private $_box_api_upload_url = 'http://upload.box.com/api/1.0/upload';
41 private $_box_api_download_url = 'http://www.box.com/api/1.0/download';
42 private $_box_api_auth_url = 'http://www.box.com/api/1.0/auth';
43 private $_error_code = '';
44 private $_error_msg = '';
45 /** @var bool */
46 private $debug = false;
48 /**
49 * @param string $api_key
50 * @param string $auth_token
51 * @param bool $debug
53 public function __construct($api_key, $auth_token = '', $debug = false) {
54 $this->api_key = $api_key;
55 $this->auth_token = $auth_token;
56 if (!empty($debug)) {
57 $this->debug = true;
58 } else {
59 $this->debug = false;
62 /**
63 * Setup for Functions
65 * @param string $method
66 * @param array $params
67 * @return array
69 function makeRequest($method, $params = array()) {
70 $this->_clearErrors();
71 $c = new curl(array('debug'=>$this->debug, 'cache'=>true, 'module_cache'=>'repository'));
72 $c->setopt(array('CURLOPT_FOLLOWLOCATION'=>1));
73 try {
74 if ($method == 'upload'){
75 $request = $this->_box_api_upload_url.'/'.
76 $this->auth_token.'/'.$params['folder_id'];
77 $xml = $c->post($request, $params);
78 }else{
79 $args = array();
80 $xml = $c->get($this->_box_api_url, $params);
82 $xml_parser = xml_parser_create();
83 // set $data here
84 xml_parse_into_struct($xml_parser, $xml, $data);
85 xml_parser_free($xml_parser);
86 } catch (moodle_exception $e) {
87 $this->setError(0, 'connection time-out or invalid url');
88 return false;
90 return $data;
92 /**
93 * @param array $params
94 * @return array
96 function getTicket($params = array()) {
97 $params['api_key'] = $this->api_key;
98 $params['action'] = 'get_ticket';
99 $ret_array = array();
100 $data = $this->makeRequest('action=get_ticket', $params);
101 if ($this->_checkForError($data)) {
102 return false;
104 foreach ($data as $a) {
105 switch ($a['tag']) {
106 case 'STATUS':
107 $ret_array['status'] = $a['value'];
108 break;
109 case 'TICKET':
110 $ret_array['ticket'] = $a['value'];
111 break;
114 return $ret_array;
118 * $options['username'] and $options['password'] must be
119 * given, we will use them to obtain a valid auth_token
120 * To get a token, you should use following code:
122 * <code>
123 * $box = new boxclient('dmls97d8j3i9tn7av8y71m9eb55vrtj4');
124 * Get a ticket
125 * $t = $box->getTicket();
126 * $box->getAuthToken($t['ticket'], array(
127 * 'username'=>'dongsheng@moodle.com',
128 * 'password'=>'xxx'));
129 * </code>
131 * @param string $ticket
132 * @param string $username
133 * @param string $password
134 * @return mixed
136 function getAuthToken($ticket, $username, $password) {
137 $c = new curl(array('debug'=>$this->debug));
138 $c->setopt(array('CURLOPT_FOLLOWLOCATION'=>0));
139 $param = array(
140 'login_form1'=>'',
141 'login'=>$username,
142 'password'=>$password,
143 'dologin'=>1,
144 '__login'=>1
146 try {
147 $ret = $c->post($this->_box_api_auth_url.'/'.$ticket, $param);
148 } catch (moodle_exception $e) {
149 $this->setError(0, 'connection time-out or invalid url');
150 return false;
152 $header = $c->getResponse();
153 if(empty($header['location'])) {
154 throw new repository_exception('invalidpassword', 'repository_boxnet');
156 $location = $header['location'];
157 preg_match('#auth_token=(.*)$#i', $location, $matches);
158 $auth_token = $matches[1];
159 if(!empty($auth_token)) {
160 $this->auth_token = $auth_token;
161 return $auth_token;
162 } else {
163 throw new repository_exception('invalidtoken', 'repository_boxnet');
167 * @param string $path Unused
168 * @param array $params
169 * @return array
171 function getfiletree($path, $params = array()) {
172 $this->_clearErrors();
173 $params['auth_token'] = $this->auth_token;
174 $params['folder_id'] = 0;
175 $params['api_key'] = $this->api_key;
176 $params['action'] = 'get_account_tree';
177 $params['onelevel'] = 1;
178 $params['params[]'] = 'nozip';
179 $c = new curl(array('debug'=>$this->debug, 'cache'=>true, 'module_cache'=>'repository'));
180 $c->setopt(array('CURLOPT_FOLLOWLOCATION'=>1));
181 try {
182 $args = array();
183 $xml = $c->get($this->_box_api_url, $params);
184 } catch (Exception $e){
186 $ret = array();
187 $o = simplexml_load_string(trim($xml));
188 if($o->status == 'listing_ok') {
189 $tree = $o->tree->folder;
190 $this->buildtree($tree, $ret);
192 return $ret;
196 * @param array $sax
197 * @param array $tree Passed by reference
199 function buildtree($sax, &$tree){
200 $sax = (array)$sax;
201 $count = 0;
202 foreach($sax as $k=>$v){
203 if($k == 'folders'){
204 $o = $sax[$k];
205 foreach($o->folder as $z){
206 $tmp = array('title'=>(string)$z->attributes()->name,
207 'size'=>0, 'date'=>userdate(time()),
208 'thumbnail'=>'https://www.box.com/img/small_folder_icon.gif',
209 'path'=>array('name'=>(string)$z->attributes()->name, 'path'=>(int)$z->attributes()->id));
210 $tmp['children'] = array();
211 $this->buildtree($z, $tmp['children']);
212 $tree[] = $tmp;
214 } elseif ($k == 'files') {
215 $val = $sax[$k]->file;
216 foreach($val as $file){
217 $thumbnail = (string)$file->attributes()->thumbnail;
218 if (!preg_match('#^(?:http://)?([^/]+)#i', $thumbnail)) {
219 $thumbnail = 'http://www.box.com'.$thumbnail;
221 $tmp = array('title'=>(string)$file->attributes()->file_name,
222 'size'=>display_size((int)$file->attributes()->size),
223 'thumbnail'=>$thumbnail,
224 'date'=>userdate((int)$file->attributes()->updated),
225 'source'=> $this->_box_api_download_url .'/'
226 .$this->auth_token.'/'.(string)$file->attributes()->id,
227 'url'=>(string)$file->attributes()->shared_link);
228 $tree[] = $tmp;
231 $count++;
235 * @param array $params
236 * @return bool|array Array or false
238 function getAccountTree($params = array()) {
239 $params['auth_token'] = $this->auth_token;
240 $params['folder_id'] = 0;
241 $params['api_key'] = $this->api_key;
242 $params['action'] = 'get_account_tree';
243 $params['onelevel'] = 1;
244 $params['params[]'] = 'nozip';
245 $ret_array = array();
246 $data = $this->makeRequest('action=get_account_tree', $params);
247 if ($this->_checkForError($data)) {
248 return false;
250 $tree_count=count($data);
251 $entry_count = 0;
252 for ($i=0; $i<$tree_count; $i++) {
253 $a = $data[$i];
254 switch ($a['tag'])
256 case 'FOLDER':
257 if (@is_array($a['attributes'])) {
258 $ret_array['folder_id'][$i] = $a['attributes']['ID'];
259 $ret_array['folder_name'][$i] = $a['attributes']['NAME'];
260 $ret_array['shared'][$i] = $a['attributes']['SHARED'];
262 break;
264 case 'FILE':
265 if (@is_array($a['attributes'])) {
266 $ret_array['file_id'][$i] = $a['attributes']['ID'];
267 @$ret_array['file_name'][$i] = $a['attributes']['FILE_NAME'];
268 @$ret_array['file_keyword'][$i] = $a['attributes']['KEYWORD'];
269 @$ret_array['file_size'][$i] = display_size($a['attributes']['SIZE']);
270 @$ret_array['file_date'][$i] = userdate($a['attributes']['UPDATED']);
271 if (preg_match('#^(?:http://)?([^/]+)#i', $a['attributes']['THUMBNAIL'])) {
272 @$ret_array['thumbnail'][$i] = $a['attributes']['THUMBNAIL'];
273 } else {
274 @$ret_array['thumbnail'][$i] = 'http://www.box.com'.$a['attributes']['THUMBNAIL'];
276 $entry_count++;
278 break;
281 return $ret_array;
285 * @param string $new_folder_name
286 * @param array $params
287 * @return bool|array Array or false
289 function CreateFolder($new_folder_name, $params = array()) {
290 $params['auth_token'] = $this->auth_token;
291 $params['api_key'] = $this->api_key;
292 $params['action'] = 'create_folder';
293 $params['name'] = $new_folder_name;
294 $defaults = array(
295 'parent_id' => 0, //Set to '0' by default. Change to create within sub-folder.
296 'share' => 1, //Set to '1' by default. Set to '0' to make folder private.
298 foreach ($defaults as $key => $value) {
299 if (!array_key_exists($key, $params)) {
300 $params[$key] = $value;
304 $ret_array = array();
305 $data = $this->makeRequest('action=create_folder', $params);
306 if ($this->_checkForError($data)) {
307 return false;
309 foreach ($data as $a) {
310 if (!empty($a['value'])) {
311 switch ($a['tag']) {
313 case 'FOLDER_ID':
314 $ret_array['folder_id'] = $a['value'];
315 break;
317 case 'FOLDER_NAME':
318 $ret_array['folder_name'] = $a['value'];
319 break;
321 case 'FOLDER_TYPE_ID':
322 $ret_array['folder_type_id'] = $a['value'];
323 break;
325 case 'SHARED':
326 $ret_array['shared'] = $a['value'];
327 break;
329 case 'PASSWORD':
330 $ret_array['password'] = $a['value'];
331 break;
333 } else {
334 $ret_array[strtolower($a['tag'])] = null;
337 return $ret_array;
341 * Upload a File
342 * @param array $params the file MUST be present in key 'file' and be a moodle stored_file object.
343 * @return array|bool Array or false
345 function UploadFile ($params = array()) {
346 $params['auth_token'] = $this->auth_token;
347 // this param should be the full path of the file
348 $params['new_file1'] = $params['file'];
349 unset($params['file']);
350 $defaults = array(
351 'folder_id' => 0, //Set to '0' by default. Change to create within sub-folder.
352 'share' => 1, //Set to '1' by default. Set to '0' to make folder private.
354 foreach ($defaults as $key => $value) {
355 if (!array_key_exists($key, $params)) {
356 $params[$key] = $value;
359 $ret_array = array();
360 $entry_count = 0;
361 $data = $this->makeRequest('upload', $params);
362 if ($this->_checkForError($data)) {
363 return false;
365 for ($i=0, $tree_count=count($data); $i<$tree_count; $i++) {
366 $a = $data[$i];
367 switch ($a['tag']) {
368 case 'STATUS':
369 $ret_array['status'] = $a['value'];
370 break;
372 case 'FILE':
373 if (is_array($a['attributes'])) {
374 @$ret_array['file_name'][$i] = $a['attributes']['FILE_NAME'];
375 @$ret_array['id'][$i] = $a['attributes']['ID'];
376 @$ret_array['folder_name'][$i] = $a['attributes']['FOLDER_NAME'];
377 @$ret_array['error'][$i] = $a['attributes']['ERROR'];
378 @$ret_array['public_name'][$i] = $a['attributes']['PUBLIC_NAME'];
379 $entry_count++;
381 break;
385 return $ret_array;
388 * @param string $fileid
389 * @param string $newname
390 * @return bool
392 function RenameFile($fileid, $newname) {
393 $params = array(
394 'api_key' => $this->api_key,
395 'auth_token' => $this->auth_token,
396 'action' => 'rename',
397 'target' => 'file',
398 'target_id' => $fileid,
399 'new_name' => $newname,
401 $data = $this->makeRequest('action=rename', $params);
402 if ($this->_checkForError($data)) {
403 return false;
405 foreach ($data as $a) {
406 switch ($a['tag']) {
407 case 'STATUS':
408 if ($a['value'] == 's_rename_node') {
409 return true;
413 return false;
417 * Register New User
419 * @param array $params
420 * @return array|bool Outcome Array or false
422 function RegisterUser($params = array()) {
423 $params['api_key'] = $this->api_key;
424 $params['action'] = 'register_new_user';
425 $params['login'] = $_REQUEST['login'];
426 $params['password'] = $_REQUEST['password'];
427 $ret_array = array();
428 $data = $this->makeRequest('action=register_new_user', $params);
429 if ($this->_checkForError($data)) {
430 return false;
432 foreach ($data as $a) {
433 switch ($a['tag']) {
434 case 'STATUS':
435 $ret_array['status'] = $a['value'];
436 break;
438 case 'AUTH_TOKEN':
439 $ret_array['auth_token'] = $a['value'];
440 break;
442 case 'LOGIN':
443 $ret_array['login'] = $a['value'];
444 break;
445 case 'SPACE_AMOUNT':
446 $ret_array['space_amount'] = $a['value'];
447 break;
448 case 'SPACE_USED':
449 $ret_array['space_used'] = $a['value'];
450 break;
454 return $ret_array;
458 * Add Tags (http://enabled.box.net/docs/rest#add_to_tag)
460 * @param string $tag
461 * @param string $id Set to ID of file or folder
462 * @param string $target_type File or folder
463 * @param array $params
464 * @return array|bool Outcome Array or false
466 function AddTag($tag, $id, $target_type, $params = array()) {
467 $params['auth_token'] = $this->auth_token;
468 $params['api_key'] = $this->api_key;
469 $params['action'] = 'add_to_tag';
470 $params['target'] = $target_type; // File or folder
471 $params['target_id'] = $id; // Set to ID of file or folder
472 $params['tags[]'] = $tag;
473 $ret_array = array();
474 $data = $this->makeRequest('action=add_to_tag', $params);
475 if ($this->_checkForError($data)) {
476 return false;
478 foreach ($data as $a) {
479 switch ($a['tag']) {
480 case 'STATUS':
481 $ret_array['status'] = $a['value'];
483 break;
486 return $ret_array;
490 * Public Share (http://enabled.box.net/docs/rest#public_share)
492 * @param string $message
493 * @param string $emails
494 * @param string $id Set to ID of file or folder
495 * @param string $target_type File or folder
496 * @param string $password
497 * @param array $params
498 * @return array|bool Outcome Array or false
500 function PublicShare($message, $emails, $id, $target_type, $password, $params = array()) {
501 $params['auth_token'] = $this->auth_token;
502 $params['api_key'] = $this->api_key;
503 $params['action'] = 'public_share';
504 $params['target'] = $target_type;
505 $params['target_id'] = $id;
506 $params['password'] = $password;
507 $params['message'] = $message;
508 $params['emails'] = $emails;
509 $ret_array = array();
510 $data = $this->makeRequest('action=public_share', $params);
511 if ($this->_checkForError($data)) {
512 return false;
514 foreach ($data as $a) {
515 switch ($a['tag']) {
516 case 'STATUS':
517 $ret_array['status'] = $a['value'];
518 break;
519 case 'PUBLIC_NAME':
520 $ret_array['public_name'] = $a['value'];
521 break;
525 return $ret_array;
528 * Get Friends (http://enabled.box.net/docs/rest#get_friends)
530 * @param array $params
531 * @return array|bool Outcome Array or false
533 function GetFriends ($params = array()) {
534 $params['auth_token'] = $this->auth_token;
535 $params['action'] = 'get_friends';
536 $params['api_key'] = $this->api_key;
537 $params['params[]'] = 'nozip';
538 $ret_array = array();
539 $data = $this->makeRequest('action=get_friends', $params);
540 if ($this->_checkForError($data)) {
541 return false;
543 foreach ($data as $a) {
544 switch ($a['tag']) {
545 case 'NAME':
546 $ret_array['name'] = $a['value'];
547 break;
548 case 'EMAIL':
549 $ret_array['email'] = $a['value'];
550 break;
551 case 'ACCEPTED':
552 $ret_array['accepted'] = $a['value'];
553 break;
554 case 'AVATAR_URL':
555 $ret_array['avatar_url'] = $a['value'];
556 break;
557 case 'ID':
558 $ret_array['id'] = $a['value'];
559 break;
560 case 'URL':
561 $ret_array['url'] = $a['value'];
562 break;
563 case 'STATUS':
564 $ret_array['status'] = $a['value'];
565 break;
568 return $ret_array;
572 * Logout User (http://enabled.box.net/docs/rest#get_friends)
574 * @param array $params
575 * @return array|bool Outcome Array or false
577 function Logout($params = array()) {
578 $params['auth_token'] = $this->auth_token;
579 $params['api_key'] = $this->api_key;
580 $params['action'] = 'logout';
581 $ret_array = array();
582 $data = $this->makeRequest('action=logout', $params);
583 if ($this->_checkForError($data)) {
584 return false;
586 foreach ($data as $a) {
587 switch ($a['tag']) {
588 case 'ACTION':
589 $ret_array['logout'] = $a['value'];
591 break;
593 return $ret_array;
597 * @param array $data
598 * @return bool
600 function _checkForError($data) {
601 if ($this->_error_msg != '') {
602 return true;
604 if (@$data[0]['attributes']['STAT'] == 'fail') {
605 $this->_error_code = $data[1]['attributes']['CODE'];
606 $this->_error_msg = $data[1]['attributes']['MSG'];
607 return true;
609 return false;
613 * @return bool
615 public function isError() {
616 if ($this->_error_msg != '') {
617 return true;
619 return false;
624 public function setError($code = 0, $msg){
625 $this->_error_code = $code;
626 $this->_error_msg = $msg;
629 * @return string
631 function getErrorMsg() {
632 return '<p>Error: (' . $this->_error_code . ') ' . $this->_error_msg . '</p>';
635 * @return string
637 function getErrorCode() {
638 return $this->_error_code;
643 function _clearErrors() {
644 $this->_error_code = '';
645 $this->_error_msg = '';