MDL-15350, Initial Revision of boxnet plugin

This commit is contained in:
dongsheng 2008-06-27 06:19:40 +00:00
parent fca079c514
commit d710e1001c
4 changed files with 978 additions and 0 deletions

519
repository/boxnet/boxlibphp5.php Executable file
View file

@ -0,0 +1,519 @@
<?php
/**
* Box REST Client Library for PHP5 Developers
*
*
* @author James Levy <james@box.net>
* @link http://enabled.box.net
* @access public
* @version 1.0
* copyright Box.net 2007
* Available for use and distribution under GPL-license
* Go to http://www.gnu.org/licenses/gpl-3.0.txt for full text
*/
/**
* Modified by Dongsheng Cai <dongsheng@cvs.moodle.org>
*
*/
require_once 'class.curl.php';
class boxclient {
var $_debug = false;
var $_box_api_url = 'http://www.box.net/api/1.0/rest';
var $_box_api_upload_url = 'http://upload.box.net/api/1.0/upload';
var $_error_code = '';
var $_error_msg = '';
var $auth_token = '';
public function setAuth($str){
$this->auth_token = $str;
}
public function __construct($api_key, $auth_token) {
$this->api_key = $api_key;
$this->auth_token = $auth_token;
}
// Setup for Functions
function makeRequest($method, $params = array()) {
$this->_clearErrors();
$useCURL = in_array('curl', get_loaded_extensions());
if ($method == 'upload'){
$args = array();
foreach($params as $k => $v){
array_push($args, urlencode($v));
$query_str = implode('/', $args);
}
$request = $this->_box_api_upload_url .'/'. $query_str;
if ($this->_debug){
echo "Upload Request: ".$request;
}
}else{
$args = array();
foreach($params as $k => $v){
array_push($args, urlencode($k).'='.urlencode($v));
$query_str = implode('&', $args);
}
$request = $this->_box_api_url .'?'. $method . '&' . $query_str;
if ($this->_debug){ echo "Request: ".$request; }
}
if ($useCURL) {
$c = &new curl($request );
$c->setopt(CURLOPT_FOLLOWLOCATION, true);
$xml = $c->exec();
$error = $c->hasError();
if ($error) {
$this->_error_msg = $error;
return false;
}
$c->close() ;
} else {
$url_parsed = parse_url($request);
$host = $url_parsed["host"];
$port = ($url_parsed['port'] == 0) ? 80 : $url_parsed['port'];
$path = $url_parsed["path"] . (($url_parsed['query'] != '') ? $path .= "?{$url_parsed[query]}" : '');
$headers = "GET $path HTTP/1.0\r\n";
$headers .= "Host: $host\r\n\r\n";
$fp = fsockopen($host, $port, $errno, $errstr, 30);
if (!$fp) {
$this->_error_msg = $errstr;
$this->_error_code = $errno;
return false;
} else {
fwrite($fp, $headers);
while (!feof($fp)) {
$xml .= fgets($fp, 1024);
}
fclose($fp);
$xml_start = strpos($xml, '<?xml');
$xml = substr($xml, $xml_start, strlen($xml));
}
}
if ($this->_debug) {
echo '<h2>XML Response</h2>';
echo '<pre class="xml">';
echo htmlspecialchars($xml);
echo '</pre>';
}
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $xml, $data);
xml_parser_free($xml_parser);
return $data;
}
function getTicket($params = array()) {
$params['api_key'] = $this->api_key;
$ret_array = array();
$data = $this->makeRequest('action=get_ticket', $params);
if ($this->_checkForError($data)) {
return false;
}
foreach ($data as $a) {
switch ($a['tag']) {
case 'STATUS':
$ret_array['status'] = $a['value'];
break;
case 'TICKET':
$ret_array['ticket'] = $a['value'];
break;
}
}
if ($this->_debug) {
echo '<h2>Ticket Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
// Get Auth Token
function getAuthToken($ticket) {
$params['api_key'] = $this->api_key;
$params['ticket'] = $ticket;
$ret_array = array();
$data = $this->makeRequest('action=get_auth_token', $params);
if ($this->_checkForError($data)) {
return false;
}
foreach ($data as $a) {
switch ($a['tag'])
{
case 'STATUS':
$ret_array['status'] = $a['value'];
break;
case 'AUTH_TOKEN':
$ret_array['auth_token'] = $a['value'];
break;
}
}
if ($ret_array['status'] == 'get_auth_token_ok'){
$this->auth_token = $ret_array['auth_token'];
$auth_token = $ret_array['auth_token'];
global $auth_token;
}else{
echo '<a href="http://www.box.net/api/1.0/auth/'.$ticket.'">Login</a>';
//header ('location: http://www.box.net/api/1.0/auth/'.$ticket) ;
}
}
// Retrieve Account Tree (http://enabled.box.net/docs/rest#get_account_tree)
function getAccountTree($params = array()) {
$params['api_key'] = $this->api_key;
$params['auth_token'] = $this->auth_token;
$params['folder_id'] = 0;
$params['onelevel'] = 1;
$params['params[]'] = 'nozip';
$ret_array = array();
$data = $this->makeRequest('action=get_account_tree', $params);
if ($this->_checkForError($data)) {
return false;
}
$tree_count=count($data);
global $tree_count;
$entry_count = 0;
for ($i=0, $tree_count=count($data); $i<$tree_count; $i++) {
$a = $data[$i];
switch ($a['tag'])
{
case 'FOLDER':
if (@is_array($a['attributes'])) {
$ret_array['folder_id'][$i] = $a['attributes']['ID'];
$ret_array['folder_name'][$i] = $a['attributes']['NAME'];
$ret_array['shared'][$i] = $a['attributes']['SHARED'];
}
break;
case 'FILE':
if (@is_array($a['attributes'])) {
$ret_array['file_id'][$i] = $a['attributes']['ID'];
@$ret_array['file_name'][$i] = $a['attributes']['FILE_NAME'];
@$ret_array['file_keyword'][$i] = $a['attributes']['KEYWORD'];
$entry_count++;
}
break;
}
}
if ($this->_debug) {
echo '<h2>Account Tree Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
// Create New Folder
function CreateFolder($new_folder_name, $params = array()) {
$params['api_key'] = $this->api_key;
$params['auth_token'] = $this->auth_token;
$params['parent_id'] = 0; //Set to '0' by default. Change to create within sub-folder.
$params['name'] = $new_folder_name;
$params['share'] = 1; //Set to '1' by default. Set to '0' to make folder private.
$ret_array = array();
$data = $this->makeRequest('action=create_folder', $params);
if ($this->_checkForError($data)) {
return false;
}
foreach ($data as $a) {
switch ($a['tag']) {
case 'FOLDER_ID':
$ret_array['folder_id'] = $a['value'];
break;
case 'FOLDER_NAME':
$ret_array['folder_type'] = $a['value'];
break;
case 'SHARED':
$ret_array['shared'] = $a['value'];
break;
case 'PASSWORD':
$ret_array['password'] = $a['value'];
break;
}
}
if ($this->_debug) {
echo '<h2>Account Tree Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
// Upload File
function UploadFile ($params = array()) {
$params['auth_token'] = $this->auth_token;
$params['new_file1'] = $_FILES['new_file1'];
$params['folder id'] = 0; //Set to '0' by default. Change to create within sub-folder.
$params['share'] = 1; //Set to '1' by default. Set to '0' to make folder private.
$ret_array = array();
$data = $this->makeUploadRequst($params);
if ($this->_checkForError($data)) {
return false;
}
for ($i=0, $tree_count=count($data); $i<$tree_count; $i++) {
$a = $data[$i];
switch ($a['tag']) {
case 'STATUS':
$ret_array['status'] = $a['value'];
break;
case 'FILE':
if (is_array($a['attributes'])) {
$ret_array['file_name'][$i] = $a['attributes']['FILE_NAME'];
$ret_array['id'][$i] = $a['attributes']['ID'];
$ret_array['folder_name'][$i] = $a['attributes']['FOLDER_NAME'];
$ret_array['error'][$i] = $a['attributes']['ERROR'];
$ret_array['public_name'][$i] = $a['attributes']['PUBLIC_NAME'];
$entry_count++;
}
break;
}
}
if ($this->_debug) {
echo '<h2>Account Tree Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
// Set Description of File or Folder
// Register New User
function RegisterUser($params = array()) {
$params['api_key'] = $this->api_key;
$params['login'] = $_REQUEST['login'];
$params['password'] = $_REQUEST['password'];
$ret_array = array();
$data = $this->makeRequest('action=register_new_user', $params);
if ($this->_checkForError($data)) {
return false;
}
foreach ($data as $a) {
switch ($a['tag']) {
case 'STATUS':
$ret_array['status'] = $a['value'];
break;
case 'AUTH_TOKEN':
$ret_array['auth_token'] = $a['value'];
break;
case 'LOGIN':
$ret_array['login'] = $a['value'];
break;
case 'SPACE_AMOUNT':
$ret_array['space_amount'] = $a['value'];
break;
case 'SPACE_USED':
$ret_array['space_used'] = $a['value'];
break;
}
}
if ($this->_debug) {
echo '<h2>Registration Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
// Add Tags (http://enabled.box.net/docs/rest#add_to_tag)
function AddTag($tag, $id, $target_type, $params = array()) {
$params['api_key'] = $this->api_key;
$params['auth_token'] = $this->auth_token;
$params['target'] = $target_type; // File or folder
$params['target_id'] = $id; // Set to ID of file or folder
$params['tags[]'] = $tag;
$ret_array = array();
$data = $this->makeRequest('action=add_to_tag', $params);
if ($this->_checkForError($data)) {
return false;
}
foreach ($data as $a) {
switch ($a['tag']) {
case 'STATUS':
$ret_array['status'] = $a['value'];
break;
}
}
if ($this->_debug) {
echo '<h2>Tag Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
// Public Share (http://enabled.box.net/docs/rest#public_share)
function PublicShare($message, $emails, $id, $target_type, $password, $params = array()) {
$params['api_key'] = $this->api_key;
$params['auth_token'] = $this->auth_token;
$params['target'] = $target_type; // File or folder
$params['target_id'] = $id; // Set to ID of file or folder
$params['password'] = $password; //optional
$params['message'] = $message;
$params['emails'] = $emails;
$ret_array = array();
$data = $this->makeRequest('action=public_share', $params);
if ($this->_checkForError($data)) {
return false;
}
foreach ($data as $a) {
switch ($a['tag']) {
case 'STATUS':
$ret_array['status'] = $a['value'];
break;
case 'PUBLIC_NAME':
$ret_array['public_name'] = $a['value'];
break;
}
}
if ($this->_debug) {
echo '<h2>Public Share Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
// Get Friends (http://enabled.box.net/docs/rest#get_friends)
function GetFriends ($params = array()) {
$params['api_key'] = $this->api_key;
$params['auth_token'] = $this->auth_token;
$params['params[]'] = 'nozip';
$ret_array = array();
$data = $this->makeRequest('action=get_friends', $params);
if ($this->_checkForError($data)) {
return false;
}
foreach ($data as $a) {
switch ($a['tag']) {
case 'NAME':
$ret_array['name'] = $a['value'];
break;
case 'EMAIL':
$ret_array['email'] = $a['value'];
break;
case 'ACCEPTED':
$ret_array['accepted'] = $a['value'];
break;
case 'AVATAR_URL':
$ret_array['avatar_url'] = $a['value'];
break;
case 'ID':
$ret_array['id'] = $a['value'];
break;
case 'URL':
$ret_array['url'] = $a['value'];
break;
case 'STATUS':
$ret_array['status'] = $a['value'];
break;
}
}
if ($this->_debug) {
echo '<h2>Get Friend Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
// Logout User
function Logout($params = array()) {
$params['api_key'] = $this->api_key;
$params['auth_token'] = $this->auth_token;
$ret_array = array();
$data = $this->makeRequest('action=logout', $params);
if ($this->_checkForError($data)) {
return false;
}
foreach ($data as $a) {
switch ($a['tag']) {
case 'ACTION':
$ret_array['logout'] = $a['value'];
break;
}
if ($this->_debug) {
echo '<h2>Logout Return</h2>';
$this->_a($ret_array);
var_dump ($a);
}
return $ret_array;
}
}
function _checkForError($data) {
if (@$data[0]['attributes']['STAT'] == 'fail') {
$this->_error_code = $data[1]['attributes']['CODE'];
$this->_error_msg = $data[1]['attributes']['MSG'];
return true;
}
return false;
}
public function isError() {
if ($this->_error_msg != '') {
return true;
}
return false;
}
function getErrorMsg() {
return '<p>Error: (' . $this->_error_code . ') ' . $this->_error_msg . '</p>';
}
function getErrorCode() {
return $this->_error_code;
}
function _clearErrors() {
$this->_error_code = '';
$this->_error_msg = '';
}
public function setDebug($debug) {
$this->_debug = $debug;
}
private function _a($array) {
var_dump($array);
}
}
?>

358
repository/boxnet/class.curl.php Executable file
View file

@ -0,0 +1,358 @@
<?php
/**
* @author Dick Munroe (munroe@csworks.com)
* @copyright copyright @ 2004, Dick Munroe, released under the GPL.
*
* The cURL class is a thin wrapper around the procedural interface
* to cURL provided by PHP. I use it mostly as a base class for
* web services whose low level interface is, literally, web pages.
*
* There are a few differences (value added, I guess) between the interface
* provided by this class and the procedural cURL interface. Most
* noticable are:
*
* 1. The curl::exec function (when returning data to the caller rather
* than simply outputing it) always parses the HTTP header and returns
* only the body portion of the reqeust. The header is available via
* the curl::getHeader method.
* 2. The status of the last curl::exec is always maintained. It is
* available via the curl::getStatus method. In addition to the information
* returned by curl_getinfo, that of curl_error and curl_errno is folded
* in as well.
*
* @example ./example.class.curl.php
*/
//
// Edit History:
//
// Dick Munroe munroe@csworks.com 30-Nov-2004
// Initial Version Created.
//
// Dick Munroe munroe@csworks.com 01-Dec-2004
// Forgot to check for cURL actually being in this instance of PHP.
//
class curl
{
/**
* The mapping to caseless header names.
*
* @access private
* @var array
*/
var $m_caseless ;
/**
* The handle for the current curl session.
*
* @access private
* @var resource
*/
var $m_handle ;
/**
* The parsed contents of the HTTP header if one happened in the
* message. All repeated elements appear as arrays.
*
* The headers are stored as an associative array, the key of which
* is the name of the header, e.g., Set-Cookie, and the values of which
* are the bodies of the header in the order in which they occurred.
*
* Some headers can be repeated in a single header, e.g., Set-Cookie and
* pragma, so each type of header has an array containing one or more
* headers of the same type.
*
* The names of the headers can, potentially, vary in spelling from
* server to server and client to client. No attempt to regulate this
* is made, i.e., the curl class does not force all headers to lower
* or upper class, but it DOES collect all headers of the same type
* under the spelling of the type of header used by the FIRST header
* of that type.
*
* For example, two headers:
*
* 1. Set-Cookie: ...
* 2. set-cookie: ...
*
* Would appear as $this->m_header['Set-Cookie'][0] and ...[1]
*
* @access private
* @var mixed
*/
var $m_header ;
/**
* Current setting of the curl options.
*
* @access private
* @var mixed
*/
var $m_options ;
/**
* Status information for the last executed http request. Includes the errno and error
* in addition to the information returned by curl_getinfo.
*
* The keys defined are those returned by curl_getinfo with two additional
* ones specified, 'error' which is the value of curl_error and 'errno' which
* is the value of curl_errno.
*
* @link http://www.php.net/curl_getinfo
* @link http://www.php.net/curl_errno
* @link http://www.php.net/curl_error
* @access private
* @var mixed
*/
var $m_status ;
/**
* curl class constructor
*
* Initializes the curl class for it's default behavior:
* o no HTTP headers.
* o return the transfer as a string.
* o URL to access.
* By default, the curl class will simply read the URL provided
* in the constructor.
*
* @link http://www.php.net/curl_init
* @param string $theURL [optional] the URL to be accessed by this instance of the class.
*/
function curl($theURL=null)
{
if (!function_exists('curl_init'))
{
trigger_error('PHP was not built with --with-curl, rebuild PHP to use the curl class.', E_USER_ERROR) ;
}
$this->m_handle = curl_init() ;
$this->m_caseless = null ;
$this->m_header = null ;
$this->m_options = null ;
$this->m_status = null ;
if (!empty($theURL))
{
$this->setopt(CURLOPT_URL, $theURL) ;
}
$this->setopt(CURLOPT_HEADER, false) ;
$this->setopt(CURLOPT_RETURNTRANSFER, true) ;
}
/**
* Free the resources associated with the curl session.
*
* @link http://www.php.net/curl_close
*/
function close()
{
curl_close($this->m_handle) ;
$this->m_handle = null ;
}
/**
* Execute the curl request and return the result.
*
* @link http://www.php.net/curl_exec
* @link http://www.php.net/curl_getinfo
* @link http://www.php.net/curl_errno
* @link http://www.php.net/curl_error
* @return string The contents of the page (or other interaction as defined by the
* settings of the various curl options).
*/
function exec()
{
$theReturnValue = curl_exec($this->m_handle) ;
$this->m_status = curl_getinfo($this->m_handle) ;
$this->m_status['errno'] = curl_errno($this->m_handle) ;
$this->m_status['error'] = curl_error($this->m_handle) ;
//
// Parse out the http header (if any).
//
$this->m_header = null ;
if ($this->getOption(CURLOPT_HEADER))
{
$theArray = preg_split("/(\r\n){2,2}/", $theReturnValue, 2) ;
$this->parseHeader($theArray[0]) ;
return $theArray[1] ;
}
return $theReturnValue ;
}
/**
* Returns the parsed http header.
*
* @param string $theHeader [optional] the name of the header to be returned.
* The name of the header is case insensitive. If
* the header name is omitted the parsed header is
* returned. If the requested header doesn't exist
* false is returned.
* @returns mixed
*/
function getHeader($theHeader=null)
{
if (empty($theHeader))
{
return $this->m_header ;
}
else
{
$theHeader = strtoupper($theHeader) ;
if (isset($this->m_caseless[$theHeader]))
{
return $this->m_header[$this->m_caseless[$theHeader]] ;
}
else
{
return false ;
}
}
}
/**
* Returns the current setting of the request option. If no
* option has been set, it return null.
*
* @param integer the requested CURLOPT.
* @returns mixed
*/
function getOption($theOption)
{
if (isset($this->m_options[$theOption]))
{
return $this->m_options[$theOption] ;
}
return null ;
}
/**
* Did the last curl exec operation have an error?
*
* @return mixed The error message associated with the error if an error
* occurred, false otherwise.
*/
function hasError()
{
if (isset($this->m_status['error']))
{
return (empty($this->m_status['error']) ? false : $this->m_status['error']) ;
}
else
{
return false ;
}
}
/**
* Parse an HTTP header.
*
* As a side effect it stores the parsed header in the
* m_header instance variable. The header is stored as
* an associative array and the case of the headers
* as provided by the server is preserved and all
* repeated headers (pragma, set-cookie, etc) are grouped
* with the first spelling for that header
* that is seen.
*
* All headers are stored as if they COULD be repeated, so
* the headers are really stored as an array of arrays.
*
* @param string $theHeader The HTTP data header.
*/
function parseHeader($theHeader)
{
$this->m_caseless = array() ;
$theArray = preg_split("/(\r\n)+/", $theHeader) ;
//
// Ditch the HTTP status line.
//
if (preg_match('/^HTTP/', $theArray[0]))
{
$theArray = array_slice($theArray, 1) ;
}
foreach ($theArray as $theHeaderString)
{
$theHeaderStringArray = preg_split("/\s*:\s*/", $theHeaderString, 2) ;
$theCaselessTag = strtoupper($theHeaderStringArray[0]) ;
if (!isset($this->m_caseless[$theCaselessTag]))
{
$this->m_caseless[$theCaselessTag] = $theHeaderStringArray[0] ;
}
$this->m_header[$this->m_caseless[$theCaselessTag]][] = $theHeaderStringArray[1] ;
}
}
/**
* Return the status information of the last curl request.
*
* @param string $theField [optional] the particular portion
* of the status information desired.
* If omitted the array of status
* information is returned. If a non-existant
* status field is requested, false is returned.
* @returns mixed
*/
function getStatus($theField=null)
{
if (empty($theField))
{
return $this->m_status ;
}
else
{
if (isset($this->m_status[$theField]))
{
return $this->m_status[$theField] ;
}
else
{
return false ;
}
}
}
/**
* Set a curl option.
*
* @link http://www.php.net/curl_setopt
* @param mixed $theOption One of the valid CURLOPT defines.
* @param mixed $theValue the value of the curl option.
*/
function setopt($theOption, $theValue)
{
curl_setopt($this->m_handle, $theOption, $theValue) ;
$this->m_options[$theOption] = $theValue ;
}
}
?>

View file

@ -0,0 +1,90 @@
<?php
/**
* repository_box class
* This is a subclass of repository class
*
* @author Dongsheng Cai
* @version 0.1 dev
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License
*/
require_once($CFG->dirroot.'/repository/'.'lib.php');
require_once($CFG->dirroot.'/repository/box/'.'boxlibphp5.php');
class repository_box extends repository{
var $api_key = 'dmls97d8j3i9tn7av8y71m9eb55vrtj4';
var $box;
var $ticket;
public function __construct($repositoryid, $context = SITEID, $options = array()){
$repositoryid = -1;
parent::__construct($repositoryid, $context, $options);
if(!empty($options['api_key'])){
$this->api_key = $options['api_key'];
}
if(empty($this->options['auth_token'])) {
$this->box = new boxclient($this->api_key, '');
} else {
$this->box = new boxclient($this->api_key, $this->options['auth_token']);
}
}
public function get_listing($path = '0', $search = ''){
$ret = array();
if($this->box){
$tree = $this->box->getAccountTree();
if($tree) {
$filenames = $tree['file_name'];
$fileids = $tree['file_id'];
foreach ($filenames as $n=>$v){
$ret[] = array('name'=>$v, 'size'=>0, 'date'=>'',
'url'=>'http://box.net/api/1.0/download/'.$this->options['auth_token'].'/'.$fileids[$n]);
}
return $ret;
} else {
return null;
}
}
}
public function print_login(){
if($this->box){
// get a ticket from box.net
$ticket_return = $this->box->getTicket();
if($this->box->isError()) {
echo $this->box->getErrorMsg();
} else {
$this->ticket = $ticket_return['ticket'];
}
// use the ticket to get a auth_token
// auth_token is the key to access the resources
// of box.net
// WARNING: this function won't return a auth_token
// if auth_token is not existed, this function will
// direct user to authentication page of box.net
// If the user has been authenticated, box.net will
// direct to a callback page (can be set in box.net)
// the call back page will obtain the auth_token
// ===============================================
// Because the authentication process will be done
// in box.net, so we need print a login link in this
// function instead a login screen.
if($this->ticket && ($this->options['auth_token'] == '')){
$this->box->getAuthToken($this->ticket);
return false;
} else {
echo 'Logged';
return true;
}
} else {
return false;
}
}
public function print_search(){
return false;
}
}
?>

11
repository/boxnet/version.php Executable file
View file

@ -0,0 +1,11 @@
<?PHP // $Id$
/////////////////////////////////////////////////////////////////////////////////
/// Code fragment to define the version of repository plug-in (box.net)
/////////////////////////////////////////////////////////////////////////////////
$plugin->version = 2008062701; // The current plug-in version (Date: YYYYMMDDXX)
$plugin->requires = 2007101509; // The current plug-in version (Date: YYYYMMDDXX)
$plugin->cron = 3600; // Period for cron to check this plug-in (secs)
?>