14aec630e30c70c9ac28227b11b0aff345450fd4
[moodle.git] / lib / boxlib.php
1 <?php
2 /**
3  * Box REST Client Library for PHP5 Developers
4  *
5  *
6  * @author James Levy <james@box.net>
7  * @link http://enabled.box.net
8  * @access public
9  * @version 1.0
10  * copyright Box.net 2007
11  * Available for use and distribution under GPL-license
12  * Go to http://www.gnu.org/licenses/gpl-3.0.txt for full text
13  */
15 /**
16  * Modified by Dongsheng Cai <dongsheng@cvs.moodle.org>
17  *
18  */
20 class boxclient {
21     public $auth_token = '';
23     private $_box_api_url = 'http://box.net/api/1.0/rest';
24     private $_box_api_upload_url = 'http://upload.box.net/api/1.0/upload';
25     private $_error_code = '';
26     private $_error_msg = '';
27     private $debug = false;
29     public function __construct($api_key, $auth_token = '', $debug = false) {
30         $this->api_key    = $api_key;
31         $this->auth_token = $auth_token;
32         $this->debug = $debug;
33     }
34     // Setup for Functions
35     function makeRequest($method, $params = array()) {
36         $this->_clearErrors();
37         if($this->debug){
38             $c = new curl(array('debug'=>true, 'cache'=>true));
39         } else {
40             $c = new curl(array('debug'=>false, 'cache'=>true));
41         }
42         try {
43             if ($method == 'upload'){
44                 $request = $this->_box_api_upload_url.'/'.
45                     $this->auth_token.'/'.$params['folder_id'];
46                 $xml = $c->post($request, $params);
47             }else{
48                 $args = array();
49                 $xml = $c->get($this->_box_api_url, $params);
50             }
51             $xml_parser = xml_parser_create();
52             // set $data here
53             xml_parse_into_struct($xml_parser, $xml, $data);
54             xml_parser_free($xml_parser);
55         } catch (moodle_exception $e) {
56             $this->setError(0, 'connection time-out or invalid url');
57             return false;
58         }
59         return $data;
60     }
61     function getTicket($params = array()) {
62         $params['api_key'] = $this->api_key;
63         $params['action']  = 'get_ticket';
64         $ret_array = array();
65         $data = $this->makeRequest('action=get_ticket', $params);
66         if ($this->_checkForError($data)) {
67             return false;
68         }
69         foreach ($data as $a) {
70             switch ($a['tag']) {
71             case 'STATUS':
72                 $ret_array['status'] = $a['value'];
73                 break;
74             case 'TICKET':
75                 $ret_array['ticket'] = $a['value'];
76                 break;
77             }
78         }
79         return $ret_array;
80     }
82     // $options['username'] and $options['password'] must be
83     // given, we  will use them to obtain a valid auth_token
84     // To get a token, you should use following code:
85     //
86     // $box = new boxclient('dmls97d8j3i9tn7av8y71m9eb55vrtj4');
87     // Get a ticket
88     // $t = $box->getTicket();
89     // $box->getAuthToken($t['ticket'], array(
90     //              'username'=>'dongsheng@moodle.com',
91     //              'password'=>'xxx'));
92     //
93     function getAuthToken($ticket, $username, $password) {
94         if($this->debug){
95             $c = new curl(array('debug'=>true));
96         } else {
97             $c = new curl(array('debug'=>false));
98         }
99         $c->setopt(array('CURLOPT_FOLLOWLOCATION'=>0));
100         $param =  array(
101             'login_form1'=>'',
102             'login'=>$username,
103             'password'=>$password,
104             'dologin'=>1,
105             '__login'=>1
106             );
107         try {
108             $ret = $c->post('http://www.box.net/api/1.0/auth/'.$ticket, $param);
109         } catch (moodle_exception $e) {
110             $this->setError(0, 'connection time-out or invalid url');
111             return false;
112         }
113         $header = $c->getResponse();
114         if(empty($header['location'])) {
115             throw new repository_exception('invalidpassword', 'repository_boxnet');
116         }
117         $location = $header['location'];
118         preg_match('#auth_token=(.*)$#i', $location, $matches);
119         $auth_token = $matches[1];
120         if(!empty($auth_token)) {
121             $this->auth_token = $auth_token;
122             return $auth_token;
123         } else {
124             throw new repository_exception('invalidtoken', 'repository_boxnet');
125         }
126     }
127     //
128     function getfiletree($path, $params = array()) {
129         $this->_clearErrors();
130         $params['auth_token'] = $this->auth_token;
131         $params['folder_id']  = 0;
132         $params['api_key']    = $this->api_key;
133         $params['action']     = 'get_account_tree';
134         $params['onelevel']   = 1;
135         $params['params[]']   = 'nozip';
136         if($this->debug){
137             $c = new curl(array('debug'=>true, 'cache'=>true));
138         } else {
139             $c = new curl(array('debug'=>false, 'cache'=>true));
140         }
141         try {
142             $args = array();
143             $xml = $c->get($this->_box_api_url, $params);
144         } catch (Exception $e){
145         }
146         $ret = array();
147         $o = simplexml_load_string(trim($xml));
148         if($o->status == 'listing_ok') {
149             $tree = $o->tree->folder;
150             $this->buildtree($tree, $ret);
151         }
152         return $ret;
153     }
155     function buildtree($sax, &$tree){
156         $sax = (array)$sax;
157         $count = 0;
158         foreach($sax as $k=>$v){
159             if($k == 'folders'){
160                 $o = $sax[$k];
161                 foreach($o->folder as $z){
162                     $tmp = array('title'=>(string)$z->attributes()->name,
163                         'size'=>0, 'date'=>userdate(time()),
164                         'thumbnail'=>'http://www.box.net/img/small_folder_icon.gif',
165                         'path'=>array('name'=>(string)$z->attributes()->name, 'path'=>(int)$z->attributes()->id));
166                     $tmp['children'] = array();
167                     $this->buildtree($z, $tmp['children']);
168                     $tree[] = $tmp;
169                 }
170             } elseif ($k == 'files') {
171                 $val = $sax[$k]->file;
172                 foreach($val as $file){
173                     $thumbnail = (string)$file->attributes()->thumbnail;
174                     if (!preg_match('#^(?:http://)?([^/]+)#i', $thumbnail)) {
175                         $thumbnail =  'http://www.box.net'.$thumbnail;
176                     }
177                     $tmp = array('title'=>(string)$file->attributes()->file_name,
178                         'size'=>display_size((int)$file->attributes()->size),
179                         'thumbnail'=>$thumbnail,
180                         'date'=>userdate((int)$file->attributes()->updated), 
181                         'source'=>'http://box.net/api/1.0/download/'
182                             .$this->auth_token.'/'.(string)$file->attributes()->id,
183                         'url'=>(string)$file->attributes()->shared_link);
184                     $tree[] = $tmp;
185                 }
186             }
187             $count++;
188         }
189     }
190     // Get the file list
191     function getAccountTree($params = array()) {
192         $params['auth_token'] = $this->auth_token;
193         $params['folder_id']  = 0;
194         $params['api_key']    = $this->api_key;
195         $params['action']     = 'get_account_tree';
196         $params['onelevel']   = 1;
197         $params['params[]']   = 'nozip';
198         $ret_array = array();
199         $data = $this->makeRequest('action=get_account_tree', $params);
200         if ($this->_checkForError($data)) {
201             return false;
202         }
203         $tree_count=count($data);
204         $entry_count = 0;
205         for ($i=0; $i<$tree_count; $i++) {
206             $a = $data[$i];
207             switch ($a['tag'])
208             {
209             case 'FOLDER':
210                 if (@is_array($a['attributes'])) {
211                     $ret_array['folder_id'][$i] = $a['attributes']['ID'];
212                     $ret_array['folder_name'][$i] = $a['attributes']['NAME'];
213                     $ret_array['shared'][$i] = $a['attributes']['SHARED'];
214                 }
215                 break;
217             case 'FILE':
218                 if (@is_array($a['attributes'])) {
219                     $ret_array['file_id'][$i] = $a['attributes']['ID'];
220                     @$ret_array['file_name'][$i] = $a['attributes']['FILE_NAME'];
221                     @$ret_array['file_keyword'][$i] = $a['attributes']['KEYWORD'];
222                     @$ret_array['file_size'][$i] = display_size($a['attributes']['SIZE']);
223                     @$ret_array['file_date'][$i] = userdate($a['attributes']['UPDATED']);
224                     if (preg_match('#^(?:http://)?([^/]+)#i', $a['attributes']['THUMBNAIL'])) {
225                         @$ret_array['thumbnail'][$i] =  $a['attributes']['THUMBNAIL'];
226                     } else {
227                         @$ret_array['thumbnail'][$i] =  'http://www.box.net'.$a['attributes']['THUMBNAIL'];
228                     }
229                     $entry_count++;
230                 }
231                 break;
232             }
233         }
234         return $ret_array;
235     }
237     // Create New Folder
238     function CreateFolder($new_folder_name, $params = array()) {
239         $params['auth_token'] =  $this->auth_token;
240         $params['api_key']    = $this->api_key;
241         $params['action']     = 'create_folder';
242         $params['name']       = $new_folder_name;
243         $defaults = array(
244             'parent_id'  => 0, //Set to '0' by default. Change to create within sub-folder.
245             'share'     => 1, //Set to '1' by default. Set to '0' to make folder private.
246         );
247         foreach ($defaults as $key => $value) {
248             if (!array_key_exists($key, $params)) {
249                 $params[$key] = $value;
250             }
251         }
253         $ret_array = array();
254         $data = $this->makeRequest('action=create_folder', $params);
255         if ($this->_checkForError($data)) {
256             return false;
257         }
258         foreach ($data as $a) {
259             switch ($a['tag']) {
260             case 'FOLDER_ID':
261                 $ret_array['folder_id'] = $a['value'];
262                 break;
264             case 'FOLDER_NAME':
265                 $ret_array['folder_name'] = $a['value'];
266                 break;
268             case 'FOLDER_TYPE_ID':
269                 $ret_array['folder_type_id'] = $a['value'];
270                 break;
272             case 'SHARED':
273                 if(!empty($a['value'])){
274                     $ret_array['shared'] = $a['value'];
275                 }else{
276                     $ret_array['shared'] = false;
277                 }
278                 break;
279             case 'PASSWORD':
280                 $ret_array['password'] = $a['value'];
281                 break;
282             }
283         }
284         return $ret_array;
285     }
287     /** Upload a File
288     * @param array $params the file MUST be present in key 'file' and be a moodle stored_file object.
289     */
290     function UploadFile ($params = array()) {
291         $params['auth_token'] = $this->auth_token;
292         // this param should be the full path of the file
293         $params['new_file1']  = $params['file'];
294         unset($params['file']);
295         $defaults = array(
296             'folder_id' => 0, //Set to '0' by default. Change to create within sub-folder.
297             'share'     => 1, //Set to '1' by default. Set to '0' to make folder private.
298         );
299         foreach ($defaults as $key => $value) {
300             if (!array_key_exists($key, $params)) {
301                 $params[$key] = $value;
302             }
303         }
304         $ret_array = array();
305         $entry_count = 0;
306         $data = $this->makeRequest('upload', $params);
307         if ($this->_checkForError($data)) {
308             return false;
309         }
310         for ($i=0, $tree_count=count($data); $i<$tree_count; $i++) {
311             $a = $data[$i];
312             switch ($a['tag']) {
313             case 'STATUS':
314                 $ret_array['status'] = $a['value'];
315                 break;
317             case 'FILE':
318                 if (is_array($a['attributes'])) {
319                     @$ret_array['file_name'][$i] = $a['attributes']['FILE_NAME'];
320                     @$ret_array['id'][$i] = $a['attributes']['ID'];
321                     @$ret_array['folder_name'][$i] = $a['attributes']['FOLDER_NAME'];
322                     @$ret_array['error'][$i] = $a['attributes']['ERROR'];
323                     @$ret_array['public_name'][$i] = $a['attributes']['PUBLIC_NAME'];
324                     $entry_count++;
325                 }
326                 break;
327             }
328         }
330         return $ret_array;
331     }
333     function RenameFile($fileid, $newname) {
334         $params = array(
335             'api_key'    => $this->api_key,
336             'auth_token' => $this->auth_token,
337             'action'     => 'rename',
338             'target'     => 'file',
339             'target_id'  => $fileid,
340             'new_name'   => $newname,
341         );
342         $data = $this->makeRequest('action=rename', $params);
343         if ($this->_checkForError($data)) {
344             return false;
345         }
346         foreach ($data as $a) {
347             switch ($a['tag']) {
348                 case 'STATUS':
349                     if ($a['value'] == 'e_rename_node') {
350                         return true;
351                     }
352             }
353         }
354         return false;
355     }
357     // Register New User
358     function RegisterUser($params = array()) {
359         $params['api_key'] = $this->api_key;
360         $params['action']  = 'register_new_user';
361         $params['login']   = $_REQUEST['login'];
362         $params['password'] = $_REQUEST['password'];
363         $ret_array = array();
364         $data = $this->makeRequest('action=register_new_user', $params);
365         if ($this->_checkForError($data)) {
366             return false;
367         }
368         foreach ($data as $a) {
369             switch ($a['tag']) {
370             case 'STATUS':
371                 $ret_array['status'] = $a['value'];
372                 break;
374             case 'AUTH_TOKEN':
375                 $ret_array['auth_token'] = $a['value'];
376                 break;
378             case 'LOGIN':
379                 $ret_array['login'] = $a['value'];
380                 break;
381             case 'SPACE_AMOUNT':
382                 $ret_array['space_amount'] = $a['value'];
383                 break;
384             case 'SPACE_USED':
385                 $ret_array['space_used'] = $a['value'];
386                 break;
387             }
388         }
390         return $ret_array;
391     }
393     // Add Tags  (http://enabled.box.net/docs/rest#add_to_tag)
395     function AddTag($tag, $id, $target_type, $params = array()) {
396         $params['auth_token'] = $this->auth_token;
397         $params['api_key']    = $this->api_key;
398         $params['action']     = 'add_to_tag';
399         $params['target']     = $target_type; // File or folder
400         $params['target_id']  = $id; // Set to ID of file or folder
401         $params['tags[]']     = $tag;
402         $ret_array = array();
403         $data = $this->makeRequest('action=add_to_tag', $params);
404         if ($this->_checkForError($data)) {
405             return false;
406         }
407         foreach ($data as $a) {
408             switch ($a['tag']) {
409             case 'STATUS':
410                 $ret_array['status'] = $a['value'];
412                 break;
413             }
414         }
415         return $ret_array;
416     }
418     // Public Share  (http://enabled.box.net/docs/rest#public_share)
419     function PublicShare($message, $emails, $id, $target_type, $password, $params = array()) {
420         $params['auth_token'] = $this->auth_token;
421         $params['api_key']    = $this->api_key;
422         $params['action']     = 'public_share';
423         $params['target']     = $target_type;
424         $params['target_id']  = $id;
425         $params['password']   =  $password;
426         $params['message']    = $message;
427         $params['emails']     = $emails;
428         $ret_array = array();
429         $data = $this->makeRequest('action=public_share', $params);
430         if ($this->_checkForError($data)) {
431             return false;
432         }
433         foreach ($data as $a) {
434             switch ($a['tag']) {
435             case 'STATUS':
436                 $ret_array['status'] = $a['value'];
437                 break;
438             case 'PUBLIC_NAME':
439                 $ret_array['public_name'] = $a['value'];
440                 break;
441             }
442         }
444         return $ret_array;
445     }
446     // Get Friends  (http://enabled.box.net/docs/rest#get_friends)
447     function GetFriends ($params = array()) {
448         $params['auth_token'] = $this->auth_token;
449         $params['action']     = 'get_friends';
450         $params['api_key']    = $this->api_key;
451         $params['params[]']   = 'nozip';
452         $ret_array = array();
453         $data = $this->makeRequest('action=get_friends', $params);
454         if ($this->_checkForError($data)) {
455             return false;
456         }
457         foreach ($data as $a) {
458             switch ($a['tag']) {
459             case 'NAME':
460                 $ret_array['name'] = $a['value'];
461                 break;
462             case 'EMAIL':
463                 $ret_array['email'] = $a['value'];
464                 break;
465             case 'ACCEPTED':
466                 $ret_array['accepted'] = $a['value'];
467                 break;
468             case 'AVATAR_URL':
469                 $ret_array['avatar_url'] = $a['value'];
470                 break;
471             case 'ID':
472                 $ret_array['id'] = $a['value'];
473                 break;
474             case 'URL':
475                 $ret_array['url'] = $a['value'];
476                 break;
477             case 'STATUS':
478                 $ret_array['status'] = $a['value'];
479                 break;
480             }
481         }
482         return $ret_array;
483     }
485     // Logout User
486     function Logout($params = array()) {
487         $params['auth_token'] = $this->auth_token;
488         $params['api_key']    = $this->api_key;
489         $params['action']     = 'logout';
490         $ret_array = array();
491         $data = $this->makeRequest('action=logout', $params);
492         if ($this->_checkForError($data)) {
493             return false;
494         }
495         foreach ($data as $a) {
496             switch ($a['tag']) {
497             case 'ACTION':
498                 $ret_array['logout'] = $a['value'];
500                 break;
501             }
502             return $ret_array;
503         }
504     }
505     function _checkForError($data) {
506         if ($this->_error_msg != '') {
507             return true;
508         }
509         if (@$data[0]['attributes']['STAT'] == 'fail') {
510             $this->_error_code = $data[1]['attributes']['CODE'];
511             $this->_error_msg = $data[1]['attributes']['MSG'];
512             return true;
513         }
514         return false;
515     }
517     public function isError() {
518         if  ($this->_error_msg != '') {
519             return true;
520         }
521         return false;
522     }
523     public function setError($code = 0, $msg){
524         $this->_error_code = $code;
525         $this->_error_msg  = $msg;
526     }
528     function getErrorMsg() {
529         return '<p>Error: (' . $this->_error_code . ') ' . $this->_error_msg . '</p>';
530     }
532     function getErrorCode() {
533         return $this->_error_code;
534     }
536     function _clearErrors() {
537         $this->_error_code = '';
538         $this->_error_msg = '';
539     }
542 ?>