]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-15488
authordongsheng <dongsheng>
Mon, 7 Jul 2008 06:34:39 +0000 (06:34 +0000)
committerdongsheng <dongsheng>
Mon, 7 Jul 2008 06:34:39 +0000 (06:34 +0000)
1. Create a ajax file picker, which can switch views(list and thumbnail now), transfer json data between server and client side
2. Improve curl.class.php
3. Improve boxnet plugin, which won't need to redirect box.net to authenticate from now on
4. Improve flickr plugin

repository/ajax.php [new file with mode: 0644]
repository/boxnet/boxlibphp5.php
repository/boxnet/repository.class.php
repository/boxnet/version.php
repository/curl.class.php
repository/flickr/phpFlickr.php
repository/flickr/repository.class.php
repository/ibrowse.php [deleted file]
repository/ws.php [new file with mode: 0644]

diff --git a/repository/ajax.php b/repository/ajax.php
new file mode 100644 (file)
index 0000000..b95291e
--- /dev/null
@@ -0,0 +1,257 @@
+<?php
+/*******************************************************\
+  This file is a demo page for ajax repository file 
+  picker,
+
+
+\*******************************************************/
+require_once('../config.php');
+?>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+<title>Ajax picker demo page</title>
+<style type="text/css">
+body {
+       margin:0;
+       padding:0;
+}
+#demo .yui-resize-handle-br {
+    height: 11px;
+    width: 11px;
+    background-position: -20px -60px;
+    background-color: transparent;
+}
+#panel{padding:0;margin:0; text-align:left;}
+#list{}
+.t{width:80px; float:left;text-align:center;}
+img{margin:0;padding:0;border:0}
+</style>
+<link rel="stylesheet" type="text/css" href="../lib/yui/reset-fonts-grids/reset-fonts-grids.css" />
+<link rel="stylesheet" type="text/css" href="../lib/yui/reset/reset-min.css" />
+<link rel="stylesheet" type="text/css" href="../lib/yui/resize/assets/skins/sam/resize.css" />
+<link rel="stylesheet" type="text/css" href="../lib/yui/container/assets/skins/sam/container.css" />
+<link rel="stylesheet" type="text/css" href="../lib/yui/layout/assets/skins/sam/layout.css" />
+<link rel="stylesheet" type="text/css" href="../lib/yui/button/assets/skins/sam/button.css" />
+<link rel="stylesheet" type="text/css" href="../lib/yui/menu/assets/skins/sam/menu.css" />
+<script type="text/javascript" src="../lib/yui/yahoo/yahoo-min.js"></script>
+<script type="text/javascript" src="../lib/yui/event/event-min.js"></script>
+<script type="text/javascript" src="../lib/yui/dom/dom-min.js"></script>
+<script type="text/javascript" src="../lib/yui/element/element-beta-min.js"></script>
+<script type="text/javascript" src="../lib/yui/dragdrop/dragdrop-min.js"></script>
+<script type="text/javascript" src="../lib/yui/container/container-min.js"></script>
+<script type="text/javascript" src="../lib/yui/resize/resize-beta-min.js"></script>
+<script type="text/javascript" src="../lib/yui/animation/animation-min.js"></script>
+<script type="text/javascript" src="../lib/yui/layout/layout-beta-min.js"></script>
+<script type="text/javascript" src="../lib/yui/connection/connection.js"></script>
+<script type="text/javascript" src="../lib/yui/json/json-min.js"></script>
+<script type="text/javascript" src="../lib/yui/menu/menu-min.js"></script>
+<script type="text/javascript" src="../lib/yui/button/button-min.js"></script>
+</head>
+<body class=" yui-skin-sam">
+<div id="file-picker"></div>
+<script type="text/javascript">
+var repositoryid = 0;
+var datasource;
+(function() {
+    var Dom = YAHOO.util.Dom,
+        Event = YAHOO.util.Event,
+        layout = null,
+        resize = null;
+
+    Event.onDOMReady(function() {
+               // QUIRKS FLAG, FOR BOX MODEL
+               var IE_QUIRKS = (YAHOO.env.ua.ie && document.compatMode == "BackCompat");
+               // UNDERLAY/IFRAME SYNC REQUIRED
+               var IE_SYNC = (YAHOO.env.ua.ie == 6 || (YAHOO.env.ua.ie == 7 && IE_QUIRKS));
+               // PADDING USED FOR BODY ELEMENT (Hardcoded for example)
+               var PANEL_BODY_PADDING = (10*2);
+        // 10px top/bottom padding applied to Panel body element. The top/bottom border width is 0
+    
+        var panel = new YAHOO.widget.Panel('file-picker', {
+            draggable: true,
+            modal: true,
+            close: true,
+            underlay: 'none',
+            width: '510px',
+            xy: [100, 100]
+        });
+        panel.setHeader('Moodle Repository Picker');
+        panel.setBody('<div id="layout"></div>');
+        panel.beforeRenderEvent.subscribe(function() {
+            Event.onAvailable('layout', function() {
+                layout = new YAHOO.widget.Layout('layout', {
+                    height: 400,
+                    width: 490,
+                    units: [
+                        { position: 'top', height: 32, resize: false, body: '<div class="yui-buttongroup" id="viewbar">'
+                        +'<input type="radio" value="List" id="listview" checked />'
+                        +'<input type="radio" value="Thumbnail" id="thumbview" />'
+                        +'</div>', gutter: '2' },
+                        { position: 'left', width: 150, resize: true, body: '<ul id="list"></ul>', gutter: '0 5 0 2', minWidth: 150, maxWidth: 300 },
+                        { position: 'bottom', 
+                        height: 30, 
+                        body: '<div id="toolbar">'+
+                        '<input type="button" value="Select" />'+
+                        '<input type="button" id="search" value="Search" />'+
+                        '<input type="button" id="logout" value="Logout" />'+
+                        '</div>', 
+                        gutter: '2'},
+                        { position: 'center', body: '<div id="panel"></div>', scroll: true, gutter: '0 2 0 0' }
+                    ]
+                });
+
+                layout.render();
+                var btns = new YAHOO.widget.ButtonGroup('viewbar');
+            });
+        });
+        panel.render();
+        resize = new YAHOO.util.Resize('file-picker', {
+            handles: ['br'],
+            autoRatio: true,
+            status: true,
+            minWidth: 380,
+            minHeight: 400
+        });
+        resize.on('resize', function(args) {
+            var panelHeight = args.height;
+                       var headerHeight = this.header.offsetHeight; // Content + Padding + Border
+                       var bodyHeight = (panelHeight - headerHeight);
+                       var bodyContentHeight = (IE_QUIRKS) ? bodyHeight : bodyHeight - PANEL_BODY_PADDING;
+                       YAHOO.util.Dom.setStyle(this.body, 'height', bodyContentHeight + 'px');
+                       if (IE_SYNC) {
+                               // Keep the underlay and iframe size in sync.
+                               // You could also set the width property, to achieve the 
+                               // same results, if you wanted to keep the panel's internal
+                               // width property in sync with the DOM width. 
+                               this.sizeUnderlay();
+                               // Syncing the iframe can be expensive. Disable iframe if you
+                               // don't need it.
+                               this.syncIframe();
+                       }
+            layout.set('height', bodyContentHeight);
+            layout.set('width', (args.width - PANEL_BODY_PADDING));
+            layout.resize();
+            
+        }, panel, true);
+        var list = new YAHOO.util.Element('list');
+        list.on('contentReady', function(e){
+                var li = document.createElement('li');
+                li.innerHTML = '<a href="###">Box.net</a>';
+                li.id = 'repo-1';
+                this.appendChild(li);
+                var i = new YAHOO.util.Element('repo-1');
+                i.on('click', function(e){
+                    cr(1, 1, 0);
+                    });
+                li = document.createElement('li');
+                li.innerHTML = '<a href="###">Flickr</a>';
+                li.id = 'repo-2';
+                this.appendChild(li);
+                i = new YAHOO.util.Element('repo-2');
+                i.on('click', function(e){
+                    cr(2, 1, 0);
+                    });
+            });
+        var listview = new YAHOO.util.Element('listview');
+        listview.on('click', function(e){
+                viewlist();
+                })
+        var thumbview = new YAHOO.util.Element('thumbview');
+        thumbview.on('click', function(e){
+                viewthumb();
+                })
+        var search = new YAHOO.util.Element('search');
+        search.on('click', function(e){
+                })
+    });
+})();
+YAHOO.util.Event.addListener('logout', 'click', function(e){
+        cr(repositoryid, 1, 1);
+        });
+
+function postdata(obj) {
+    var str = '';
+    for(k in obj) {
+        if(str == ''){
+            str += '?';
+        } else {
+            str += '&';
+        }
+        str += encodeURIComponent(k) +'='+encodeURIComponent(obj[k]);
+    }
+    return str;
+}
+
+function loading(){
+    var panel = new YAHOO.util.Element('panel');
+    panel.get('element').innerHTML = '<img src="<?php echo $CFG->pixpath.'/i/loading.gif'?>" alt="loading..." />';
+}
+
+function viewthumb(){
+    obj = datasource.list;
+    if(!obj){
+        return;
+    }
+    var panel = new YAHOO.util.Element('panel');
+    var str = '';
+    for(k in obj){
+        str += '<div class="t">';
+        str += '<img title="'+obj[k].title+'" src="'+obj[k].thumbnail+'" />';
+        str += '<div style="text-align:center">'+obj[k].title+'</div>';
+        str += '</div>';
+    }
+    panel.get('element').innerHTML = str;
+    return str;
+}
+function viewlist(){
+    obj = datasource.list;
+    if(!obj){
+        return;
+    }
+    var panel = new YAHOO.util.Element('panel');
+    var str = '';
+    for(k in obj){
+        str += '<input type="checkbox" value="'+obj[k].url+'" />';
+        str += obj[k].title;
+        str += '<br/>';
+    }
+    panel.get('element').innerHTML = str;
+    return str;
+}
+function print_login(){
+    var panel = new YAHOO.util.Element('panel');
+    var data = datasource.l;
+    panel.get('element').innerHTML = data;
+}
+
+var callback = {
+success: function(o) {
+    var ret = YAHOO.lang.JSON.parse(o.responseText);
+    datasource = ret;
+    if(datasource.l){
+        print_login();
+    } else if(datasource.list) {
+        viewlist();
+    }
+  }
+}
+
+function cr(id, page, reset){
+    if(id == 0) {
+        repositoryid = id;
+    }
+    loading();
+    var trans = YAHOO.util.Connect.asyncRequest('GET', 'ws.php?id='+id+'&p='+page+'&reset='+reset, callback);
+}
+
+function dologin(){
+    YAHOO.util.Connect.setForm('moodle-repo-login');
+    loading();
+    var trans = YAHOO.util.Connect.asyncRequest('POST', 'ws.php', callback);
+}
+</script>
+</body>
+</html>
index 78d6de934ad9032dd76788eadc67fa5f765f2bd3..01711f80cd432b903b0159a50a8fa344a57e54e3 100755 (executable)
@@ -17,7 +17,7 @@
  *
  */
 
-require_once 'class.curl.php';
+require_once($CFG->dirroot.'/repository/'.'curl.class.php');
 
 class boxclient {
 
@@ -58,18 +58,21 @@ class boxclient {
                 $query_str = implode('&', $args);
             }
             $request = $this->_box_api_url .'?'. $method . '&' . $query_str;
-            if ($this->_debug){ echo "Request: ".$request; }
+            if ($this->_debug){
+                echo "Request: ".$request;
+            }
         }
         if ($useCURL) {
-            $c = &new curl($request );
-            $c->setopt(CURLOPT_FOLLOWLOCATION, true);
-            $xml = $c->exec();
+            $c = new curl($request);
+            $c->setopt(array('CURLOPT_FOLLOWLOCATION'=>true));
+            $xml = $c->get($request);
+            /*
             $error = $c->hasError();
             if ($error) {
                 $this->_error_msg = $error;
                 return false;
             }
-            $c->close() ;
+            */
         } else {
             $url_parsed = parse_url($request);
             $host       = $url_parsed["host"];
@@ -155,9 +158,10 @@ class boxclient {
         if ($ret_array['status'] == 'get_auth_token_ok'){
             $this->auth_token = $ret_array['auth_token'];
             $auth_token = $ret_array['auth_token'];
-            global $auth_token;
+            return $auth_token;
         }else{
             echo '<a href="http://www.box.net/api/1.0/auth/'.$ticket.'">Login</a>';
+            return false;
             //header ('location: http://www.box.net/api/1.0/auth/'.$ticket) ; 
         }   
     }
index 1477dd697353af68035039ea75cd9aa8e9504acd..c61f6fb86cd07dfd7ee39299678ace95f40803b0 100755 (executable)
@@ -8,6 +8,7 @@
  * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  */
 require_once($CFG->dirroot.'/repository/'.'lib.php');
+require_once($CFG->dirroot.'/repository/'.'curl.class.php');
 require_once($CFG->dirroot.'/repository/boxnet/'.'boxlibphp5.php');
 
 class repository_boxnet extends repository{
@@ -16,39 +17,66 @@ class repository_boxnet extends repository{
     var $ticket;
 
     public function __construct($repositoryid, $context = SITEID, $options = array()){
-        global $SESSION;
-        $op = repository_get_option($repositoryid, 1);
-        $options['api_key']    = $op['api_key'];
-        $options['auth_token'] = optional_param('auth_token', '', PARAM_RAW);
-        if(!empty($options['auth_token'])) {
-            $SESSION->box_token = $options['auth_token'];
-        } else {
-            $options['auth_token'] = $SESSION->box_token;
+        global $SESSION, $action;
+        $options['username']   = optional_param('username', '', PARAM_RAW);
+        $options['password']   = optional_param('password', '', PARAM_RAW);
+        $options['ticket']     = optional_param('ticket', '', PARAM_RAW);
+        $options['api_key']    = 'dmls97d8j3i9tn7av8y71m9eb55vrtj4';
+        // reset session
+        $reset = optional_param('reset', 0, PARAM_INT);
+        if(!empty($reset)) {
+            unset($SESSION->box_token);
         }
-        $options['api_key'] = 'dmls97d8j3i9tn7av8y71m9eb55vrtj4';
-        parent::__construct($repositoryid, $context, $options);
-        if(!empty($options['api_key'])){
-            $this->api_key = $options['api_key'];
+        // do login 
+        if(!empty($options['username'])
+                    && !empty($options['password']) 
+                    && !empty($options['ticket']) ) 
+        {
+            $c = new curl;
+            $str = '';
+            $c->setopt(array('CURLOPT_FOLLOWLOCATION'=>0));
+            $param =  array(
+                'login_form1'=>'',
+                'login'=>$options['username'],
+                'password'=>$options['password'],
+                'dologin'=>1,
+                '__login'=>1
+                );
+            $ret = $c->post('http://www.box.net/api/1.0/auth/'.$options['ticket'], $param);
+            $header = $c->getResponse();
+            $location = $header['location'];
+            preg_match('#auth_token=(.*)$#i', $location, $matches);
+            $auth_token = $matches[1];
+            $SESSION->box_token = $auth_token;
         }
-        if(empty($this->options['auth_token'])) {
-            $this->box = new boxclient($this->api_key, '');
+        // already logged
+        if(!empty($SESSION->box_token)) {
+            $this->box = new boxclient($options['api_key'], $SESSION->box_token);
+            $this->options['auth_token'] = $SESSION->box_token;
+            $action = 'list';
         } else {
-            $this->box = new boxclient($this->api_key, $this->options['auth_token']);
+            $this->box = new boxclient($options['api_key'], '');
+            $action = '';
         }
+        parent::__construct($repositoryid, $context, $options);
     }
 
     public function get_listing($path = '0', $search = ''){
-        $ret = array();
+        global $CFG;
+        $list = array();
+        $ret  = array();
         if($this->box){
-            $tree  = $this->box->getAccountTree();
+            $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]);
+                    $list[] = array('title'=>$v, 'size'=>0, 'date'=>'',
+                            'url'=>'http://box.net/api/1.0/download/'.$this->options['auth_token'].'/'.$fileids[$n],
+                            'thumbnail'=>$CFG->pixpath.'/i/files.gif');
                 }
-                $this->listing = $ret;
+                $this->listing = $list;
+                $ret['list']   = $list;
                 return $ret;
             } else {
                 return null;
@@ -58,13 +86,18 @@ class repository_boxnet extends repository{
 
     public function print_login(){
         if(!empty($this->box) && !empty($this->options['auth_token'])) {
-            echo '<a href="picker.php?id='.$this->repositoryid.'&action=list">View File list</a>';
-            return true;
+            if($this->options['ajax']){
+                return $this->get_listing();
+            } else {
+                echo $this->get_listing();
+            }
         } else if(!empty($this->box)){
             // get a ticket from box.net
             $ticket_return = $this->box->getTicket();
             if($this->box->isError()) {
-                echo $this->box->getErrorMsg();
+                if(!$this->options['ajax']){
+                    echo $this->box->getErrorMsg();
+                }
             } else {
                 $this->ticket = $ticket_return['ticket'];
             }
@@ -83,11 +116,27 @@ class repository_boxnet extends repository{
             // function instead a login screen.
 
             if($this->ticket && ($this->options['auth_token'] == '')){
-                $this->box->getAuthToken($this->ticket);
-                return false;
+                $str = '';
+                $str .= '<form id="moodle-repo-login">';
+                $str .= '<input type="hidden" name="ticket" value="'.$this->ticket.'" />';
+                $str .= '<input type="hidden" name="id" value="'.$this->repositoryid.'" />';
+                $str .= '<label for="box_username">Username: <label>';
+                $str .= '<input type="text" id="box_username" name="username" />';
+                $str .= '<br/>';
+                $str .= '<label for="box_password">Password: <label>';
+                $str .= '<input type="password" id="box_password" name="password" />';
+                $str .= '<input type="button" onclick="dologin()" value="Go" />';
+                $str .= '</form>';
+                if($this->options['ajax']){
+                    $ret = array();
+                    $ret['l'] = $str;
+                    return $ret;
+                } else {
+                    echo $str;
+                }
+                //$this->box->getAuthToken($this->ticket);
             }
         } else {
-            return false;
         }
     }
 
index 0afc879c5ce6b2230115a66faf628d80c656c976..6799f15dfce3bf9809a5781f77bb68f311866204 100755 (executable)
@@ -1,9 +1,10 @@
-<?PHP // $Id$
+<?php // $Id$
 
 /////////////////////////////////////////////////////////////////////////////////
 ///  Code fragment to define the version of repository plug-in (box.net)
 /////////////////////////////////////////////////////////////////////////////////
 
+$plugin->name     = "Box.net Repository";
 $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)
index 4937555a1a73d42bae3291b79b2ada20875ac43a..30c207eacb23d7e61a0bff1d0b43b10850926176 100644 (file)
@@ -1,36 +1,88 @@
 <?php
 /**
- * curl class
+ * RESTful cURL class
+ *
+ * This is a wrapper class for curl, it is quite easy to use:
  *
- * This is a wrapper class for curl, it is easy to use:
  * $c = new curl();
  * // HTTP GET Method
- * $html = $c->get('http://moodle.org');
+ * $html = $c->get('http://example.com');
  * // HTTP POST Method
- * $html = $c->post('http://moodle.org/', array('q'=>'words', 'name'=>'moodle'));
+ * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
+ * // HTTP PUT Method
+ * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
  *
  * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
- * @version 0.1 dev
+ * @version 0.2 dev
  * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  */
 
 class curl {
-    private $header;
     private $options;
-    private $error;
-    private $debug = false;
-
+    private $debug    = false;
+    private $cookie   = false;
+    public  $version  = '0.2 dev';
+    public  $response = array();
+    public  $header   = array();
+    public  $info;
+    public  $error;
     public function __construct($options = array()){
-
         if(!function_exists('curl_init')) {
             $this->error = 'cURL module must be enabled!';
             trigger_error($this->error, E_USER_ERROR);
             return false;
         }
-
-        $this->header  = array();
+        if(!empty($options['debug'])) {
+            $this->debug = true;
+        }
+        $this->debug = false;
+        if(!empty($options['cookie'])) {
+            if(is_file($options['cookie'])) {
+                $this->cookie = $options['cookie'];
+            }
+        }
+        $this->resetopt();
+    }
+    public function resetopt(){
         $this->options = array();
-        $this->setopt();
+        $this->options['CURLOPT_USERAGENT']         = 'MoodleBot/1.0';
+        // True to include the header in the output 
+        $this->options['CURLOPT_HEADER']            = 0;
+        // True to Exclude the body from the output 
+        $this->options['CURLOPT_NOBODY']            = 0;
+        // TRUE to follow any "Location: " header that the server 
+        // sends as part of the HTTP header (note this is recursive, 
+        // PHP will follow as many "Location: " headers that it is sent, 
+        // unless CURLOPT_MAXREDIRS is set).  
+        $this->options['CURLOPT_FOLLOWLOCATION']    = 1;
+        $this->options['CURLOPT_MAXREDIRS']         = 10;
+        $this->options['CURLOPT_ENCODING']          = '';
+        // TRUE to return the transfer as a string of the return 
+        // value of curl_exec() instead of outputting it out directly.  
+        $this->options['CURLOPT_RETURNTRANSFER']    = 1;
+        $this->options['CURLOPT_BINARYTRANSFER']    = 0;
+        $this->options['CURLOPT_SSL_VERIFYPEER']    = 0;
+        $this->options['CURLOPT_SSL_VERIFYHOST']    = 2;
+        $this->options['CURLOPT_TIMEOUT']           = 120;
+    }
+
+    /**
+     * Reset Cookie
+     * 
+     * @param array $options If array is null, this function will
+     * reset the options to default value.
+     *
+     */
+    public function resetcookie() {
+        if(!empty($this->cookie)) {
+            if(is_file($this->cookie)) {
+                $fp = fopen($this->cookie, 'w');
+                if(!empty($fp)) {
+                    fwrite($fp, '');
+                    fclose($fp);
+                }
+            }
+        }
     }
 
     /**
@@ -41,26 +93,20 @@ class curl {
      *
      */
     public function setopt($options = array()) {
-        $this->options['CURLOPT_HEADER']            = 0;
-        $this->options['CURLOPT_NOBODY']            = 0;
-        $this->options['CURLOPT_USERAGENT']         = 'MoodleBot/1.0';
-        $this->options['CURLOPT_FOLLOWLOCATION']    = 1;
-        $this->options['CURLOPT_MAXREDIRS']         = 10;
-        $this->options['CURLOPT_TIMEOUT']           = 120;
-        $this->options['CURLOPT_ENCODING']          = '';
-        $this->options['CURLOPT_RETURNTRANSFER']    = 1;
-        $this->options['CURLOPT_BINARYTRANSFER']    = 0;
-        $this->options['CURLOPT_SSL_VERIFYPEER']    = 0;
-
         if (is_array($options)) {
-            foreach($options as $name => $val) 
+            foreach($options as $name => $val){
+                if(stripos($name, 'CURLOPT_') === false) {
+                    $name = strtoupper('CURLOPT_'.$name);
+                }
                 $this->options[$name] = $val;
+            } 
         }
-
     }
-
-    private function resetopt() 
-    {
+    /**
+     * Reset http method
+     *
+     */
+    public function cleanopt(){
         unset($this->options['CURLOPT_HTTPGET']);
         unset($this->options['CURLOPT_POST']);
         unset($this->options['CURLOPT_POSTFIELDS']);
@@ -69,29 +115,88 @@ class curl {
         unset($this->options['CURLOPT_INFILESIZE']);
         unset($this->options['CURLOPT_CUSTOMREQUEST']);
     }
+
     /**
-     * Set HTTP Header
+     * Set HTTP Request Header
      * 
      * @param array $headers 
      *
      */
-    public function setheader($header) {
+    public function setHeader($header) {
         if (is_array($header)){
             foreach ($header as $v) {
-                $this->setheader($v);
+                $this->setHeader($v);
             }
         } else {
-            $this->header[] = $val;
+            $this->header[] = $header;
+        }
+    }
+    /**
+     * Set HTTP Response Header
+     * 
+     */
+    public function getResponse(){
+        return $this->response;
+    }
+    /**
+     * private callback function
+     * Formatting HTTP Response Header
+     * 
+     */
+    private function formatHeader($ch, $header) 
+    {
+        $this->count++;
+        if (strlen($header) > 2) {
+            list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
+            $key = rtrim($key, ':');
+            if(!empty($this->response[$key])) {
+                if(is_array($this->response[$key])){
+                    $this->response[$key][] = $value;
+                } else {
+                    $tmp = $this->response[$key];
+                    $this->response[$key] = array();
+                    $this->response[$key][] = $tmp;
+                    $this->response[$key][] = $value;
+
+                }
+            } else {
+                $this->response[$key] = $value;
+            }
         }
+        return strlen($header);
     }
 
+    /**
+     * Formatting HTTP Response Header
+     * 
+     */
     protected function request($url, $options = array()){
-
+        // Clean up
+        $this->cleanopt();
         // create curl instance
         $curl = curl_init($url);
         // reset before set options
+        curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
+
         $this->setopt($options);
 
+        // set headers
+        if(empty($this->header)){
+            $this->setHeader(array(
+                'User-Agent: MoodleBot/1.0',
+                'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
+                'Connection: keep-alive'
+                ));
+        }
+        curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
+
+        // set cookie
+        if(!empty($this->cookie)) {
+            $this->setopt(array('cookiejar'=>$this->cookie,
+                            'cookiefile'=>$this->cookie
+                             ));
+        }
+
         // set options
         foreach($this->options as $name => $val) {
             if (is_string($name)) {
@@ -101,22 +206,26 @@ class curl {
         }
 
         if($this->debug){
+            echo '<h1>Options</h1>';
             var_dump($this->options);
+            echo '<h1>Header</h1>';
+            var_dump($this->header);
         }
 
-        // set headers
-        if(!empty($this->header)){
-            curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
-        }
 
         $ret  = curl_exec($curl);
+        $this->info  = curl_getinfo($curl);
+        $this->error = curl_error($curl);
 
         if($this->debug){
+            echo '<h1>Return Data</h1>';
             var_dump($ret);
+            echo '<h1>Info</h1>';
+            var_dump($this->info);
+            echo '<h1>Error</h1>';
+            var_dump($this->error);
         }
 
-        $info = curl_getinfo($curl);
-
         curl_close($curl);
 
         if(!empty($ret)){
@@ -130,9 +239,9 @@ class curl {
      * HTTP HEAD method
      */
     public function head($url, $options = array()){
-        $this->setopt(array('CURLOPT_HTTPGET'=>1));
-        $this->setopt(array('CURLOPT_HEADER' =>1));
-        $this->setopt(array('CURLOPT_NOBODY' =>1));
+        $options['CURLOPT_HTTPGET'] = 0;
+        $options['CURLOPT_HEADER']  = 1;
+        $options['CURLOPT_NOBODY']  = 1;
         return $this->request($url, $options);
     }
 
@@ -140,8 +249,8 @@ class curl {
      * HTTP POST method
      */
     public function post($url, $params = array(), $options = array()){
-        $this->setopt(array('CURLOPT_POST'=>1));
-        $this->setopt(array('CURLOPT_POSTFIELDS'=>$params));
+        $options['CURLOPT_POST']       = 1;
+        $options['CURLOPT_POSTFIELDS'] = $params;
         return $this->request($url, $options);
     }
 
@@ -149,11 +258,13 @@ class curl {
      * HTTP GET method
      */
     public function get($url, $params = array(), $options = array()){
+        $options['CURLOPT_HTTPGET'] = 1;
+
         if(!empty($params)){
             $url .= (stripos($url, '?') !== false) ? '&' : '?';
             $url .= http_build_query($params);
         }
-        $this->setopt(array('CURLOPT_HTTPGET'=>1));
+
         return $this->request($url, $options);
     }
 
@@ -165,37 +276,44 @@ class curl {
         if(!is_file($file)){
             return null;
         }
-        $fp = fopen($file, 'rw');
-        $this->setopt(array('CURLOPT_PUT'=>1));
-        $this->setopt(array('CURLOPT_INFILE'=>$fp));
-        $this->setopt(array('CURLOPT_INFILESIZE'=>-1));
+        $fp   = fopen($file, 'r');
+        $size = filesize($file);
+        $options['CURLOPT_PUT']        = 1;
+        $options['CURLOPT_INFILESIZE'] = $size;
+        $options['CURLOPT_INFILE']     = $fp;
         if (!isset($this->options['CURLOPT_USERPWD'])){
             $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
         }
         $ret = $this->request($url, $options);
+        fclose($fp);
         return $ret;
     }
 
     /**
      * HTTP DELETE method
      */
-    public function delete($url, $options = array()){
-        $this->setopt(array('CURLOPT_CUSTOMREQUEST'=>'DELETE'));
-        if (!isset($this->options['CURLOPT_USERPWD'])) {
-            $this->options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
+    public function delete($url, $param = array(), $options = array()){
+        $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
+        if (!isset($options['CURLOPT_USERPWD'])) {
+            $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
         }
         $ret = $this->request($url, $options);
         return $ret;
     }
+    /**
+     * HTTP TRACE method
+     */
+    public function trace($url){
+        $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
+        $ret = $this->request($url, $options);
+        return $ret;
+    }
+    /**
+     * HTTP OPTIONS method
+     */
+    public function options($url){
+        $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
+        $ret = $this->request($url, $options);
+        return $ret;
+    }
 }
-/*
-$c = new curl();
-
-echo '<div style="clear:both">---------------------This is a line---------------------</a>';
-
-$z = $c->get('http://foleo.appspot.com/');
-
-echo '<div><textarea rows="29" cols="99">';
-echo htmlentities($z);
-echo '</textarea></div>';
-*/
index 7facdeb7caeedee1031e1918e19d74e39c333ac5..0dd926c3e71ada46961a7d3f9f173fdefd35276e 100755 (executable)
@@ -78,13 +78,6 @@ class phpFlickr {
 
        function enableCache($type, $connection, $cache_expire = 600, $table = 'flickr_cache')
        {
-               // Turns on caching.  $type must be either "db" (for database caching) or "fs" (for filesystem).
-               // When using db, $connection must be a PEAR::DB connection string. Example:
-               //        "mysql://user:password@server/database"
-               // If the $table, doesn't exist, it will attempt to create it.
-               // When using file system, caching, the $connection is the folder that the web server has write
-               // access to. Use absolute paths for best results.  Relative paths may have unexpected behavior
-               // when you include this.  They'll usually work, you'll just want to test them.
         $this->cache = 'fs';
         $connection = realpath($connection);
         $this->cache_dir = $connection;
index 1cc0c3a287349a6422e961fda3dad2e62fde713d..1e2e0242e6b616dfa486080a13817b540d2e8eea 100755 (executable)
@@ -50,63 +50,77 @@ class repository_flickr extends repository{
             }
         }
     }
-    public function print_login(){
+    public function print_login($ajax = true){
         global $SESSION;
         if(empty($SESSION->flickrmail)) {
-        echo <<<EOD
-            <form action="picker.php">
-            <label for="account">Flickr Account (Email)</lable>
+        $str =<<<EOD
+            <form id="moodle-repo-login">
+            <label for="account">Flickr Account (Email)</label>
             <input type='text' name='flickrmail' id='account' />
-            <input type='hidden' name='id' value='$this->repositoryid' />
+            <input type='hidden' name='id' value='$this->repositoryid' /><br/>
             <input type='checkbox' name='remember' value='true' /> Remember <br/>
-            <input type='submit' value='Go' />
+            <a href="###" onclick="dologin()">Go</a>
             </form>
 EOD;
+            if($ajax){
+                $ret = array();
+                $ret['l'] = $str;
+                return $ret;
+            }else{
+                echo $str;
+            }
         } else {
-            $this->print_listing();
+            return $this->get_listing();
         }
-        //echo '<a href="?id='.$this->repositoryid.'&action=list">See flickr photos list</a>';
-        return true;
     }
     public function get_listing($path = '0', $search = ''){
         global $SESSION;
         $people = $this->flickr->people_findByEmail($SESSION->flickrmail);
         $photos_url = $this->flickr->urls_getUserPhotos($people['nsid']);
         $photos = $this->flickr->people_getPublicPhotos($people['nsid'], null, 36, $this->page);
-        $this->photos = array('a'=>$SESSION->flickrmail, 'u'=>$photos_url, 'p'=>$photos);
-        return $this->photos;
+        $ret = new stdclass;
+        $ret->url   = $photos_url;
+        $ret->list  = array();
+        $ret->page  = $photos['page'];
+        $ret->pages = $photos['pages'];
+        foreach ($photos['photo'] as $p) {
+            $ret->list[] = array('title'=>$p['title'],'thumbnail'=>$this->flickr->buildPhotoURL($p, "Square"));
+        }
+        return $ret;
     }
     public function print_listing(){
         if(empty($this->photos)){
             $this->get_listing();
         }
-        echo '<h2>Account: <span>'.$this->photos['a'].'</span></h2>';
-        echo '<a href="picker.php?id='.$this->repositoryid.'&reset=1">Change user</a>';
-        echo '<hr/>';
-        foreach ((array)$this->photos['p']['photo'] as $photo) {
-            echo "<a href='".$this->photos['u'].$photo[id]."'>";
-            echo "<img border='0' alt='$photo[title]' ".
-                "src=" . $this->flickr->buildPhotoURL($photo, "Square") . ">";
-            echo "</a>";
+        $str = '';
+        $str .= '<h2>Account: <span>'.$this->photos['a'].'</span></h2>';
+        $str .= '<a href="###" onclick="callrepo('.$this->repositoryid.', 1, 1)">Change user</a>';
+        $str .= '<hr/>';
+        foreach ((array)$this->photos['photo'] as $photo) {
+            $str .= "<a href='".$this->photos['url'].$photo[id]."'>";
+            $str .= "<img border='0' alt='$photo[title]' ".
+                "src=" . $photo['thumbnail'] . ">";
+            $str .= "</a>";
             $i++;
-            // If it reaches the sixth photo, insert a line break
-            if ($i % 6 == 0) {
-                echo "<br/>";
+            
+            if ($i % 4 == 0) {
+                $str .= "<br/>";
             }
         }
-        echo <<<EOD
+        $str .= <<<EOD
 <style type='text/css'>
 #paging{margin-top: 10px; clear:both}
 #paging a{padding: 4px; border: 1px solid gray}
 </style>
 EOD;
-        echo '<div id="paging">';
-        for($i=1; $i <= $this->photos['p']['pages']; $i++) {
-            echo '<a href="picker.php?id='.$this->repositoryid.'&action=list&p='.$i.'">';
-            echo $i;
-            echo '</a> ';
+        $str .= '<div id="paging">';
+        for($i=1; $i <= $this->photos['pages']; $i++) {
+            $str .= '<a href="###" onclick="cr('.$this->repositoryid.', '.$i.', 0)">';
+            $str .= $i;
+            $str .= '</a> ';
         }
-        echo '</div>';
+        $str .= '</div>';
+        echo $str;
     }
     public function print_search(){
         echo '<input type="text" name="Search" value="search terms..." size="40" class="right"/>';
diff --git a/repository/ibrowse.php b/repository/ibrowse.php
deleted file mode 100644 (file)
index 6618a22..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-<?php
-require_once('../config.php');
-require_once('lib.php');
-?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
-<html>
-<head>
-    <meta content="text/html; charset=UTF-8" http-equiv="content-type">
-    <title>File Picker</title>
-    <link href="style.css" rel="stylesheet" type="text/css">
-</head>
-<body class="frame">
-    <div id='nav'>
-        <a href="###">Root</a> &gt; <a href="###">&nbsp;Folder 1</a> &gt; <a href="###">&nbsp;Sub-folder 1_1</a>
-    </div>
-<table border="0">
-<tbody>
-    <tr>
-    <td class="content" colspan="4"><img src="<?php echo $CFG->pixpath.'/f/folder.gif';?>" alt="folder"/> ..</td>
-    </tr>
-
-    <tr>
-    <td class="content"><input type="radio" name="file" value="" /></td>
-    <td class="content">basket_readme.avi</td>
-    <td class="content">8 Kb</td>
-    <td class="content">22/05/2008 4:45PM</td>
-    </tr>
-
-    <tr>
-    <td class="content"><input type="radio" name="file" value="" /></td>
-    <td class="content">readme.doc</td>
-    <td class="content">2 Kb</td>
-    <td class="content">22/05/2008 4:45PM</td>
-    </tr>
-
-    <tr>
-    <td class="content"><input type="radio" name="file" value="" /></td>
-    <td class="content">moodle_readme.txt</td>
-    <td class="content">2 Kb</td>
-    <td class="content">22/05/2008 4:45PM</td>
-    </tr>
-</tbody>
-</table>
-</body>
-</html>
diff --git a/repository/ws.php b/repository/ws.php
new file mode 100644 (file)
index 0000000..3537bdd
--- /dev/null
@@ -0,0 +1,27 @@
+<?php
+require_once('../config.php');
+require_once('lib.php');
+$id        = optional_param('id', PARAM_INT);
+$action    = optional_param('action', '', PARAM_RAW);
+if(!$repository = $DB->get_record('repository', array('id'=>$id))) {
+    echo json_encode('wrong');
+    die;
+}
+
+if(is_file($CFG->dirroot.'/repository/'.$repository->repositorytype.'/repository.class.php')) {
+    require_once($CFG->dirroot.'/repository/'.$repository->repositorytype.'/repository.class.php');
+    $classname = 'repository_' . $repository->repositorytype;
+    $repo = new $classname($id, SITEID, array('ajax'=>true));
+} else {
+    print_error('invalidplugin', 'repository');
+    echo json_encode('invalidplugin');
+    die;
+}
+
+if($action == 'list') {
+    echo json_encode($repo->get_listing());
+} else {
+    echo json_encode($repo->print_login());
+}
+
+?>