Index: admin/repository.php
===================================================================
RCS file: /cvsroot/moodle/moodle/admin/repository.php,v
retrieving revision 1.17
diff -u -a -r1.17 repository.php
--- admin/repository.php	9 Oct 2008 03:02:26 -0000	1.17
+++ admin/repository.php	13 Nov 2008 10:33:33 -0000
@@ -39,7 +39,7 @@

 if (!empty($edit) || !empty($new)) {
     if (!empty($edit)) {
-        $repositorytype = repository_get_type_by_typename($edit);
+        $repositorytype = repository::get_type_by_typename($edit);
         $classname = 'repository_' . $repositorytype->get_typename();
         $configs = call_user_func(array($classname,'get_type_option_names'));
         $plugin = $repositorytype->get_typename();
@@ -56,7 +56,7 @@
     //detect if we create a new type without config (in this case if don't want to display a setting page during creation)
     $createnewtype = false;
     if (!empty($new)) {
-        $adminconfignames = repository_static_function($new, 'get_type_option_names');
+        $adminconfignames = repository::static_function($new, 'get_type_option_names');
         $createnewtype = empty($adminconfignames);
     }
     // end setup, begin output
@@ -72,7 +72,7 @@
             foreach($configs as $config) {
                 $settings[$config] = $fromform->$config;
             }
-             $instanceoptionnames = repository_static_function($edit, 'get_instance_option_names');
+             $instanceoptionnames = repository::static_function($edit, 'get_instance_option_names');
             if (!empty($instanceoptionnames)) {
                     if (array_key_exists('enablecourseinstances', $fromform)) {
                         $settings['enablecourseinstances'] = $fromform->enablecourseinstances;
@@ -108,8 +108,8 @@
         print_heading(get_string('configplugin', 'repository_'.$plugin));
         $displaysettingform = true;
         if ($edit) {
-            $typeoptionnames = repository_static_function($edit, 'get_type_option_names');
-            $instanceoptionnames = repository_static_function($edit, 'get_instance_option_names');
+            $typeoptionnames = repository::static_function($edit, 'get_type_option_names');
+            $instanceoptionnames = repository::static_function($edit, 'get_instance_option_names');
             if (empty($typeoptionnames) && empty($instanceoptionnames)) {
                 $displaysettingform = false;
             }
@@ -123,9 +123,9 @@

         //display instances list and creation form
         if ($edit){
-             $instanceoptionnames = repository_static_function($edit, 'get_instance_option_names');
+             $instanceoptionnames = repository::static_function($edit, 'get_instance_option_names');
              if (!empty($instanceoptionnames)){
-                repository_display_instances_list(get_context_instance(CONTEXT_SYSTEM), $edit);
+                repository::display_instances_list(get_context_instance(CONTEXT_SYSTEM), $edit);
            }
         }

@@ -134,12 +134,12 @@
     if (!confirm_sesskey()) {
         print_error('confirmsesskeybad', '', $baseurl);
     }
-    $repositorytype = repository_get_type_by_typename($hide);
+    $repositorytype = repository::get_type_by_typename($hide);
     $repositorytype->switch_and_update_visibility();
     $return = true;
 } else if (!empty($delete)) {
     admin_externalpage_print_header();
-    $repositorytype = repository_get_type_by_typename($delete);
+    $repositorytype = repository::get_type_by_typename($delete);
     if ($sure) {
         if (!confirm_sesskey()) {
             print_error('confirmsesskeybad', '', $baseurl);
@@ -157,7 +157,7 @@
     $return = false;
 }
 else if (!empty($move) && !empty($type)) {
-    $repositorytype = repository_get_type_by_typename($type);
+    $repositorytype = repository::get_type_by_typename($type);
     $repositorytype->move_order($move);
 }

Index: admin/repositoryinstance.php
===================================================================
RCS file: /cvsroot/moodle/moodle/admin/repositoryinstance.php,v
retrieving revision 1.5
diff -u -a -r1.5 repositoryinstance.php
--- admin/repositoryinstance.php	19 Sep 2008 06:43:06 -0000	1.5
+++ admin/repositoryinstance.php	13 Nov 2008 10:33:33 -0000
@@ -42,8 +42,8 @@

 if (!empty($edit) || !empty($new)) {
     if (!empty($edit)) {
-        $instance = repository_get_instance($edit);
-        $instancetype = repository_get_type_by_id($instance->typeid);
+        $instance = repository::get_instance($edit);
+        $instancetype = repository::get_type_by_id($instance->typeid);
         $classname = 'repository_' . $instancetype->get_typename();
         $configs  = $instance->get_instance_option_names();
         $plugin = $instancetype->get_typename();
@@ -75,7 +75,7 @@
             }
             $success = $instance->set_option($settings);
         } else {
-            $success = repository_static_function($plugin, 'create', $plugin, 0, get_system_context(), $fromform);
+            $success = repository::static_function($plugin, 'create', $plugin, 0, get_system_context(), $fromform);
             $data = data_submitted();
         }
         if ($success) {
@@ -99,14 +99,14 @@
     if (!confirm_sesskey()) {
         print_error('confirmsesskeybad', '', $baseurl);
     }
-    $instance = repository_get_type_by_typename($hide);
+    $instance = repository::get_type_by_typename($hide);
     var_dump($instance);
     var_dump($hide);
     $instance->hide();
     $return = true;
-} else if (!empty($delete)) {
+} else if (!empty($delete)) {
     admin_externalpage_print_header();
-    $instance = repository_get_instance($delete);
+    $instance = repository::get_instance($delete);
     //if you try to delete an instance set as readonly, display an error message
     if ($instance->readonly) {
             throw new repository_exception('readonlyinstance', 'repository');
Index: admin/mnet/adminlib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/admin/mnet/adminlib.php,v
retrieving revision 1.9
diff -u -a -r1.9 adminlib.php
--- admin/mnet/adminlib.php	23 Oct 2008 08:14:24 -0000	1.9
+++ admin/mnet/adminlib.php	13 Nov 2008 10:33:34 -0000
@@ -46,7 +46,7 @@
         $relname = '/repository/' . $parentname . '/'. $docname;
         $filename = $CFG->dirroot . $relname;
         require_once($CFG->dirroot . '/repository/lib.php');
-        $publishes = (array)repository_static_function($parentname, 'mnet_publishes');
+        $publishes = (array)repository::static_function($parentname, 'mnet_publishes');
     } else {
         // auth or enrol
         $relname  = '/'.$type.'/'.$parentname.'/'.$docname;
Index: admin/settings/plugins.php
===================================================================
RCS file: /cvsroot/moodle/moodle/admin/settings/plugins.php,v
retrieving revision 1.30
diff -u -a -r1.30 plugins.php
--- admin/settings/plugins.php	18 Sep 2008 05:21:52 -0000	1.30
+++ admin/settings/plugins.php	13 Nov 2008 10:33:34 -0000
@@ -228,12 +228,12 @@
     $ADMIN->add('repositorysettings', new admin_externalpage('repositoryinstanceedit',
         get_string('editrepositoryinstance', 'repository'), $url, 'moodle/site:config', true),
         '', $url);
-    foreach (repository_get_types()
+    foreach (repository::get_types()
         as $repositorytype)
     {
       //display setup page for plugins with: general options or multiple instances (e.g. has instance config)
-      $typeoptionnames = repository_static_function($repositorytype->get_typename(), 'get_type_option_names');
-      $instanceoptionnames = repository_static_function($repositorytype->get_typename(), 'get_instance_option_names');
+      $typeoptionnames = repository::static_function($repositorytype->get_typename(), 'get_type_option_names');
+      $instanceoptionnames = repository::static_function($repositorytype->get_typename(), 'get_instance_option_names');
       if (!empty($typeoptionnames) || !empty($instanceoptionnames)) {
             $ADMIN->add('repositorysettings',
                 new admin_externalpage('repositorysettings'.$repositorytype->get_typename(),
Index: blocks/admin/block_admin.php
===================================================================
RCS file: /cvsroot/moodle/moodle/blocks/admin/block_admin.php,v
retrieving revision 1.118
diff -u -a -r1.118 block_admin.php
--- blocks/admin/block_admin.php	30 Oct 2008 06:26:18 -0000	1.118
+++ blocks/admin/block_admin.php	13 Nov 2008 10:33:40 -0000
@@ -188,7 +188,7 @@

     /// Repository Instances
         require_once($CFG->dirroot.'/repository/lib.php');
-        $editabletypes = repository_get_editable_types($context);
+        $editabletypes = repository::get_editable_types($context);
         if ($course->id !== SITEID && has_capability('moodle/course:update', $context) && !empty($editabletypes)) {
             $this->content->items[]='<a href="'.$CFG->wwwroot.'/repository/manage_instances.php?contextid='.$context->id.'">'.get_string('repositories').'</a>';
             $this->content->icons[]='<img src="'.$CFG->pixpath.'/i/repository.png" alt=""/>';
Index: lib/adminlib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/lib/adminlib.php,v
retrieving revision 1.285
diff -u -a -r1.285 adminlib.php
--- lib/adminlib.php	13 Nov 2008 08:41:00 -0000	1.285
+++ lib/adminlib.php	13 Nov 2008 10:34:01 -0000
@@ -6012,7 +6012,7 @@
                 return true;
             }
         }
-        foreach (repository_get_types() as $instance) {
+        foreach (repository::get_types() as $instance) {
             $title = $instance->get_typename();
             if (strpos($textlib->strtolower($title), $query) !== false) {
                 return true;
@@ -6030,7 +6030,7 @@
         $hiddenstr = get_string('hiddenshow', 'repository');
         $deletestr = get_string('delete');
         $plugins = get_list_of_plugins('repository');
-        $instances = repository_get_types();
+        $instances = repository::get_types();
         $instancesnumber = count($instances);
         $alreadyplugins = array();
         $table = new StdClass;
@@ -6041,8 +6041,8 @@
         foreach ($instances as $i) {
             $settings = '';
             //display edit link only if you can config the type or if it has multiple instances (e.g. has instance config)
-            $typeoptionnames = repository_static_function($i->get_typename(), 'get_type_option_names');
-            $instanceoptionnames = repository_static_function($i->get_typename(), 'get_instance_option_names');
+            $typeoptionnames = repository::static_function($i->get_typename(), 'get_type_option_names');
+            $instanceoptionnames = repository::static_function($i->get_typename(), 'get_instance_option_names');
             if ( !empty($typeoptionnames) || !empty($instanceoptionnames)) {
                 $settings .= '<a href="' . $this->baseurl . '&amp;edit=' . $i->get_typename() . '">'
                               . $settingsstr .'</a>' . "\n";
Index: repository/javascript.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/javascript.php,v
retrieving revision 1.24
diff -u -a -r1.24 javascript.php
--- repository/javascript.php	3 Nov 2008 04:44:53 -0000	1.24
+++ repository/javascript.php	13 Nov 2008 10:36:37 -0000
@@ -956,7 +965,7 @@
 EOD;

 $user_context = get_context_instance(CONTEXT_USER, $USER->id);
-$repos = repository_get_instances(array($user_context, $context, get_system_context()));
+$repos = repository::get_instances(array($user_context, $context, get_system_context()));
 foreach ($repos as $repo) {
     $js .= "\r\n";
     $js .= 'repository_client_'.$suffix.'.repos.push('.json_encode($repo->ajax_info()).');'."\n";
Index: repository/lib.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/lib.php,v
retrieving revision 1.141
diff -u -a -r1.141 lib.php
--- repository/lib.php	3 Nov 2008 04:44:53 -0000	1.141
+++ repository/lib.php	13 Nov 2008 10:36:37 -0000
@@ -103,7 +103,7 @@
      * @return boolean
      */
     public function get_contextvisibility($contextlevel) {
-
+
         if ($contextlevel == CONTEXT_COURSE) {
             return $this->_options['enablecourseinstances'];
         }
@@ -115,7 +115,7 @@
         //the context is SITE
         return true;
     }
-
+


     /**
@@ -136,7 +136,7 @@

         //set options attribut
         $this->_options = array();
-        $options = repository_static_function($typename,'get_type_option_names');
+        $options = repository::static_function($typename,'get_type_option_names');
         //check that the type can be setup
         if (!empty($options)) {
             //set the type options
@@ -153,13 +153,13 @@
         } else {
              $this->_options['enablecourseinstances'] = 0;
         }
-
+
         if (array_key_exists('enableuserinstances',$typeoptions)) {
             $this->_options['enableuserinstances'] = $typeoptions['enableuserinstances'];
         } else {
              $this->_options['enableuserinstances'] = 0;
         }
-
+
     }

     /**
@@ -238,15 +238,15 @@
             //if the plugin type has no multiple instance (e.g. has no instance option name) so it wont
             //be possible for the administrator to create a instance
             //in this case we need to create an instance
-            $instanceoptionnames = repository_static_function($this->_typename, 'get_instance_option_names');
+            $instanceoptionnames = repository::static_function($this->_typename, 'get_instance_option_names');
             if (empty($instanceoptionnames)) {
                 $instanceoptions = array();
                 $instanceoptions['name'] = $this->_typename;
-                repository_static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
+                repository::static_function($this->_typename, 'create', $this->_typename, 0, get_system_context(), $instanceoptions);
             }

             //run init function
-            if (!repository_static_function($this->_typename, 'plugin_init')) {
+            if (!repository::static_function($this->_typename, 'plugin_init')) {
                 throw new repository_exception('cannotcreatetype', 'repository');
             }

@@ -332,7 +332,7 @@
     public function move_order($move) {
         global $DB;

-        $types = repository_get_types();    // retrieve all types
+        $types = repository::get_types();    // retrieve all types

     /// retrieve this type into the returned array
         $i = 0;
@@ -386,7 +386,7 @@
         global $DB;

         //delete all instances of this type
-        $instances = repository_get_instances(array(),null,false,$this->_typename);
+        $instances = repository::get_instances(array(),null,false,$this->_typename);
         foreach ($instances as $instance) {
             $instance->delete();
         }
@@ -401,94 +401,642 @@
 }

 /**
- * Return a type for a given type name.
- * @global object $DB
- * @param string $typename the type name
- * @return integer
+ * This is the base class of the repository class
+ *
+ * To use repository plugin, see:
+ * http://docs.moodle.org/en/Development:Repository_How_to_Create_Plugin
+ *
+ * class repository is an abstract class, some functions must be implemented in subclass.
+ *
+ * See an example: repository/boxnet/repository.class.php
+ *
+ * A few notes:
+ *   // for ajax file picker, this will print a json string to tell file picker
+ *   // how to build a login form
+ *   $repo->print_login();
+ *   // for ajax file picker, this will return a files list.
+ *   $repo->get_listing();
+ *   // this function will be used for non-javascript version.
+ *   $repo->print_listing();
+ *   // print a search box
+ *   $repo->print_search();
+ *
+ * @package repository
+ * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  */
-function repository_get_type_by_typename($typename) {
-    global $DB;
+abstract class repository {
+    // $disabled can be set to true to disable a plugin by force
+    // example: self::$disabled = true
+    public $disabled = false;
+    public $id;
+    public $context;
+    public $options;
+    public $readonly;

-    if (!$record = $DB->get_record('repository',array('type' => $typename))) {
-        return false;
+    /**
+     * Return a type for a given type name.
+     * @global object $DB
+     * @param string $typename the type name
+     * @return integer
+     */
+    public static function get_type_by_typename($typename) {
+        global $DB;
+
+        if (!$record = $DB->get_record('repository',array('type' => $typename))) {
+            return false;
+        }
+
+        return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
     }

-    return new repository_type($typename, (array)get_config($typename), $record->visible, $record->sortorder);
-}
+    /**
+     * Return a type for a given type id.
+     * @global object $DB
+     * @param string $typename the type name
+     * @return integer
+     */
+    public static function get_type_by_id($id) {
+        global $DB;

-/**
- * Return a type for a given type id.
- * @global object $DB
- * @param string $typename the type name
- * @return integer
- */
-function repository_get_type_by_id($id) {
-    global $DB;
+        if (!$record = $DB->get_record('repository',array('id' => $id))) {
+            return false;
+        }
+
+        return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
+    }
+
+    /**
+     * Return all repository types ordered by sortorder
+     * first type in returnedarray[0], second type in returnedarray[1], ...
+     * @global object $DB
+     * @param boolean $visible can return types by visiblity, return all types if null
+     * @return array Repository types
+     */
+    public static function get_types($visible=null) {
+        global $DB;
+
+        $types = array();
+        $params = null;
+        if (!empty($visible)) {
+            $params = array('visible' => $visible);
+        }
+        if ($records = $DB->get_records('repository',$params,'sortorder')) {
+            foreach($records as $type) {
+                $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
+            }
+        }
+
+        return $types;
+    }
+
+    /**
+     * Check context
+     * @param int $ctx_id
+     * @return boolean
+     */
+    public static function check_context($ctx_id) {
+        global $USER;
+
+        $context = get_context_instance_by_id($ctx_id);
+        $level = $context->contextlevel;

-    if (!$record = $DB->get_record('repository',array('id' => $id))) {
+        if ($level == CONTEXT_COURSE) {
+            if (!has_capability('moodle/course:view', $context)) {
+                return false;
+            } else {
+                return true;
+            }
+        } else if ($level == CONTEXT_USER) {
+            $c = get_context_instance(CONTEXT_USER, $USER->id);
+            if ($c->id == $ctx_id) {
+                return true;
+            } else {
+                return false;
+            }
+        } else if ($level == CONTEXT_SYSTEM) {
+            // it is always ok in system level
+            return true;
+        }
         return false;
     }

-    return new repository_type($record->type, (array)get_config($record->type), $record->visible, $record->sortorder);
-}
+    /**
+     * Return all types that you a user can create/edit and which are also visible
+     * Note: Mostly used in order to know if at least one editable type can be set
+     * @param object $context the context for which we want the editable types
+     * @return array types
+     */
+    public static function get_editable_types($context = null) {

-/**
- * Return all repository types ordered by sortorder
- * first type in returnedarray[0], second type in returnedarray[1], ...
- * @global object $DB
- * @param boolean $visible can return types by visiblity, return all types if null
- * @return array Repository types
- */
-function repository_get_types($visible=null) {
-    global $DB;
+        if (empty($context)) {
+            $context = get_system_context();
+        }
+
+        $types= repository::get_types(true);
+        $editabletypes = array();
+        foreach ($types as $type) {
+            $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
+            if (!empty($instanceoptionnames)) {
+                if ($type->get_contextvisibility($context->contextlevel)) {
+                    $editabletypes[]=$type;
+                }
+             }
+        }
+        return $editabletypes;
+    }
+
+    /**
+     * Return repository instances
+     * @global object $DB
+     * @global object $CFG
+     * @global object $USER
+     * @param object $contexts contexts for which the instances are set
+     * @param integer $userid
+     * @param boolean $onlyvisible if visible == true, return visible instances only,
+     *                otherwise, return all instances
+     * @param string $type a type name to retrieve
+     * @return array repository instances
+     */
+    public static function get_instances($contexts=array(), $userid = null, $onlyvisible = true, $type=null) {
+        global $DB, $CFG, $USER;
+
+        $params = array();
+        $sql = 'SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible FROM {repository} r, {repository_instances} i WHERE ';
+        $sql .= 'i.typeid = r.id ';
+
+        if (!empty($userid) && is_numeric($userid)) {
+            $sql .= ' AND (i.userid = 0 or i.userid = ?)';
+            $params[] = $userid;
+        }
+
+        foreach ($contexts as $context) {
+            if (empty($firstcontext)) {
+                $firstcontext = true;
+                $sql .= ' AND ((i.contextid = ?)';
+            } else {
+                $sql .= ' OR (i.contextid = ?)';
+            }
+            $params[] = $context->id;
+        }
+
+        if (!empty($firstcontext)) {
+           $sql .=')';
+        }
+
+        if ($onlyvisible == true) {
+            $sql .= ' AND (r.visible = 1)';
+        }
+
+        if (isset($type)) {
+            $sql .= ' AND (r.type = ?)';
+            $params[] = $type;
+        }
+        $sql .= ' order by r.sortorder, i.name';
+
+        if (!$repos = $DB->get_records_sql($sql, $params)) {
+            $repos = array();
+        }
+
+        $ret = array();
+        foreach ($repos as $repo) {
+            require_once($CFG->dirroot . '/repository/'. $repo->repositorytype.'/repository.class.php');
+            $options['visible'] = $repo->visible;
+            $options['name']    = $repo->name;
+            $options['type']    = $repo->repositorytype;
+            $options['typeid']  = $repo->typeid;
+            $classname = 'repository_' . $repo->repositorytype;//
+
+            $repository = new $classname($repo->id, $repo->contextid, $options, $repo->readonly);
+            if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
+                $ret[] = $repository;
+            }
+        }
+        return $ret;
+    }
+
+    /**
+     * Get single repository instance
+     * @global object $DB
+     * @global object $CFG
+     * @param integer $id repository id
+     * @return object repository instance
+     */
+    public static function get_instance($id) {
+        global $DB, $CFG;
+        $sql = 'SELECT i.*, r.type AS repositorytype, r.visible FROM {repository} r, {repository_instances} i WHERE ';
+        $sql .= 'i.typeid = r.id AND ';
+        $sql .= 'i.id = '.$id;
+
+        if(!$instance = $DB->get_record_sql($sql)) {
+            return false;
+        }
+        require_once($CFG->dirroot . '/repository/'. $instance->repositorytype
+                . '/repository.class.php');
+        $classname = 'repository_' . $instance->repositorytype;
+        $options['typeid'] = $instance->typeid;
+        $options['type']   = $instance->repositorytype;
+        $options['name']   = $instance->name;
+        return new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
+    }
+
+    /**
+     * call a static function
+     * @global <type> $CFG
+     * @param <type> $plugin
+     * @param <type> $function
+     * @param type $nocallablereturnvalue default value if function not found
+     *             it's mostly used when you don't want to display an error but
+     *             return a boolean
+     * @return <type>
+     */
+    public static function static_function($plugin, $function) {
+        global $CFG;
+
+        //check that the plugin exists
+        $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/repository.class.php';
+        if (!file_exists($typedirectory)) {
+            throw new repository_exception('invalidplugin', 'repository');
+        }
+
+        $pname = null;
+        if (is_object($plugin) || is_array($plugin)) {
+            $plugin = (object)$plugin;
+            $pname = $plugin->name;
+        } else {
+            $pname = $plugin;
+        }
+
+        $args = func_get_args();
+        if (count($args) <= 2) {
+            $args = array();
+        }
+        else {
+            array_shift($args);
+            array_shift($args);
+        }
+
+        require_once($typedirectory);
+        return call_user_func_array(array('repository_' . $plugin, $function), $args);
+    }
+
+    /**
+     * Move file from download folder to file pool using FILE API
+     * @global object $DB
+     * @global object $CFG
+     * @global object $USER
+     * @param string $path file path in download folder
+     * @param string $name file name
+     * @param integer $itemid item id to identify a file in filepool
+     * @param string $filearea file area
+     * @return array information of file in file pool
+     */
+    public static function move_to_filepool($path, $name, $itemid, $filearea = 'user_draft') {
+        global $DB, $CFG, $USER;
+        $context = get_context_instance(CONTEXT_USER, $USER->id);
+        $now = time();
+        $entry = new object();
+        $entry->filearea  = $filearea;
+        $entry->contextid = $context->id;
+        $entry->filename  = $name;
+        $entry->filepath  = '/'.uniqid().'/';
+        $entry->timecreated  = $now;
+        $entry->timemodified = $now;
+        if(is_numeric($itemid)) {
+            $entry->itemid = $itemid;
+        } else {
+            $entry->itemid = 0;
+        }
+        $entry->mimetype     = mimeinfo('type', $path);
+        $entry->userid       = $USER->id;
+        $fs = get_file_storage();
+        $browser = get_file_browser();
+        if ($file = $fs->create_file_from_pathname($entry, $path)) {
+            $delete = unlink($path);
+            $ret = $browser->get_file_info($context, $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename());
+            if(!empty($ret)) {
+                return array('url'=>$ret->get_url(),'id'=>$file->get_itemid(), 'file'=>$file->get_filename());
+            } else {
+                return null;
+            }
+        } else {
+            return null;
+        }
+    }
+
+    public static function download_btn($repo_id, $ctx_id, $sesskey, $title, $src, $returnurl = '') {
+        global $CFG;
+        if (empty($returnurl)) {
+            $returnurl = get_referer();
+        }
+        $str  = '<form action="'.$CFG->httpswwwroot.'/repository/ws.php">';
+        $str .= '  <input type="hidden" name="sesskey" value="'.$sesskey.'" />';
+        $str .= '  <input type="hidden" name="ctx_id" value="'.$ctx_id.'" />';
+        $str .= '  <input type="hidden" name="repo_id" value="'.$repo_id.'" />';
+        $str .= '  <input type="hidden" name="file" value="'.$src.'" />';
+        $str .= '  <input type="hidden" name="action" value="download" />';
+        $str .= '  <input type="hidden" name="returnurl" value="'.$returnurl.'" />';
+        $str .= '  <input type="text" name="title" value="'.$title.'" />';
+        $str .= '  <input type="submit" value="Select it!" />';
+        $str .= '</form>';
+        return $str;
+    }
+
+    /**
+     * Save file to local filesystem pool
+     * @param string $elname name of element
+     * @param string $filearea
+     * @param string $filepath
+     * @param string $filename - use specified filename, if not specified name of uploaded file used
+     * @param bool $override override file if exists
+     * @return mixed stored_file object or false if error; may throw exception if duplicate found
+     */
+    public static function store_to_filepool($elname, $filearea='user_draft', $filepath='/', $filename = '', $override = false) {
+        global $USER;
+        if (!isset($_FILES[$elname])) {
+            return false;
+        }
+
+        if (!$filename) {
+            $filename = $_FILES[$elname]['name'];
+        }
+        $context = get_context_instance(CONTEXT_USER, $USER->id);
+        $itemid = (int)substr(hexdec(uniqid()), 0, 9)+rand(1,100);
+        $fs = get_file_storage();
+        $browser = get_file_browser();
+
+        if ($file = $fs->get_file($context->id, $filearea, $itemid, $filepath, $filename)) {
+            if ($override) {
+                $file->delete();
+            } else {
+                return false;
+            }
+        }
+
+        $file_record = new object();
+        $file_record->contextid = $context->id;
+        $file_record->filearea  = $filearea;
+        $file_record->itemid    = $itemid;
+        $file_record->filepath  = $filepath;
+        $file_record->filename  = $filename;
+        $file_record->userid    = $USER->id;
+
+        $file = $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
+        $info = $browser->get_file_info($context, $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename());
+        $ret = array('url'=>$info->get_url(),'id'=>$itemid, 'file'=>$file->get_filename());
+        return $ret;
+    }
+
+    /**
+     * Return the user arborescence in a format to be returned by the function get_listing
+     * @global <type> $CFG
+     * @param <type> $search
+     * @return <type>
+     */
+    public static function get_user_file_tree($search = ""){
+        global $CFG;
+     $ret = array();
+            $ret['nologin'] = true;
+            $ret['manage'] = $CFG->wwwroot .'/files/index.php'; // temporary
+            $browser = get_file_browser();
+            $itemid = null;
+            $filename = null;
+            $filearea = null;
+            $path = '/';
+            $ret['dynload'] = false;
+
+            if ($fileinfo = $browser->get_file_info(get_system_context(), $filearea, $itemid, $path, $filename)) {
+
+                $ret['path'] = array();
+                $params = $fileinfo->get_params();
+                $filearea = $params['filearea'];
+                $ret['path'][] = repository::encode_path($filearea, $path, $fileinfo->get_visible_name());
+                if ($fileinfo->is_directory()) {
+                    $level = $fileinfo->get_parent();
+                    while ($level) {
+                        $params = $level->get_params();
+                        $ret['path'][] = repository::encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
+                        $level = $level->get_parent();
+                    }
+                }
+                $filecount = repository::build_tree($fileinfo, $search, $ret['dynload'], $ret['list']);
+                $ret['path'] = array_reverse($ret['path']);
+            }
+
+            if (empty($ret['list'])) {
+                //exit(mnet_server_fault(9016, get_string('emptyfilelist', 'repository_local')));
+                throw new Exception('emptyfilelist');
+            } else {
+                return $ret;
+            }
+
+    }
+
+    /**
+     *
+     * @param <type> $filearea
+     * @param <type> $path
+     * @param <type> $visiblename
+     * @return <type>
+     */
+    public static function encode_path($filearea, $path, $visiblename) {
+        return array('path'=>serialize(array($filearea, $path)), 'name'=>$visiblename);
+    }
+
+    /**
+     * Builds a tree of files This function is
+     * then called recursively.
+     *
+     * @param $fileinfo an object returned by file_browser::get_file_info()
+     * @param $search searched string
+     * @param $dynamicmode bool no recursive call is done when in dynamic mode
+     * @param $list - the array containing the files under the passed $fileinfo
+     * @returns int the number of files found
+     *
+     * todo: take $search into account, and respect a threshold for dynamic loading
+     */
+    public static function build_tree($fileinfo, $search, $dynamicmode, &$list) {
+        global $CFG;
+
+        $filecount = 0;
+        $children = $fileinfo->get_children();
+
+        foreach ($children as $child) {
+            $filename = $child->get_visible_name();
+            $filesize = $child->get_filesize();
+            $filesize = $filesize ? display_size($filesize) : '';
+            $filedate = $child->get_timemodified();
+            $filedate = $filedate ? userdate($filedate) : '';
+            $filetype = $child->get_mimetype();
+
+            if ($child->is_directory()) {
+                $path = array();
+                $level = $child->get_parent();
+                while ($level) {
+                    $params = $level->get_params();
+                    $path[] = repository::encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
+                    $level = $level->get_parent();
+                }
+
+                $tmp = array(
+                    'title' => $child->get_visible_name(),
+                    'size' => 0,
+                    'date' => $filedate,
+                    'path' => array_reverse($path),
+                    'thumbnail' => $CFG->pixpath .'/f/folder.gif'
+                );
+
+                //if ($dynamicmode && $child->is_writable()) {
+                //    $tmp['children'] = array();
+                //} else {
+                    // if folder name matches search, we send back all files contained.
+                $_search = $search;
+                if ($search && stristr($tmp['title'], $search) !== false) {
+                    $_search = false;
+                }
+                $tmp['children'] = array();
+                $_filecount = repository::build_tree($child, $_search, $dynamicmode, $tmp['children']);
+                if ($search && $_filecount) {
+                    $tmp['expanded'] = 1;
+                }
+
+                //}
+
+                //Uncomment this following line if you wanna display all directory ()even empty
+                //if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
+                if ($_filecount) {
+                    $filecount += $_filecount;
+                    $list[] = $tmp;
+                }
+
+            } else { // not a directory
+                // skip the file, if we're in search mode and it's not a match
+                if ($search && (stristr($filename, $search) === false)) {
+                    continue;
+                }
+                $params = $child->get_params();
+                $source = serialize(array($params['contextid'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
+                $list[] = array(
+                    'title' => $filename,
+                    'size' => $filesize,
+                    'date' => $filedate,
+                    //'source' => $child->get_url(),
+                    'source' => base64_encode($source),
+                    'thumbnail' => $CFG->pixpath .'/f/'. mimeinfo_from_type("icon", $filetype)
+                );
+                $filecount++;
+            }
+        }
+
+        return $filecount;
+    }
+
+
+    /**
+     * Display a repository instance list (with edit/delete/create links)
+     * @global object $CFG
+     * @global object $USER
+     * @param object $context the context for which we display the instance
+     * @param string $typename if set, we display only one type of instance
+     */
+    public static function display_instances_list($context, $typename = null) {
+        global $CFG, $USER;
+
+        $output = print_box_start('generalbox','',true);
+        //if the context is SYSTEM, so we call it from administration page
+        $admin = ($context->id == SYSCONTEXTID) ? true : false;
+        if ($admin) {
+            $baseurl = $CFG->httpswwwroot . '/admin/repositoryinstance.php?sesskey=' . sesskey();
+            $output .= "<div ><h2 style='text-align: center'>" . get_string('siteinstances', 'repository') . " ";
+            $output .= "</h2></div>";
+        } else {
+            $baseurl = $CFG->httpswwwroot . '/repository/manage_instances.php?contextid=' . $context->id . '&amp;sesskey=' . sesskey();
+        }
+
+        $namestr = get_string('name');
+        $pluginstr = get_string('plugin', 'repository');
+        $settingsstr = get_string('settings');
+        $deletestr = get_string('delete');
+        $updown = get_string('updown', 'repository');
+        //retrieve list of instances. In administration context we want to display all
+        //instances of a type, even if this type is not visible. In course/user context we
+        //want to display only visible instances, but for every type types. The repository_get_instances()
+        //third parameter displays only visible type.
+        $instances = repository::get_instances(array($context),null,!$admin,$typename);
+        $instancesnumber = count($instances);
+        $alreadyplugins = array();
+
+        $table = new StdClass;
+        $table->head = array($namestr, $pluginstr, $deletestr, $settingsstr);
+        $table->align = array('left', 'left', 'center','center');
+        $table->data = array();
+
+        $updowncount = 1;
+
+        foreach ($instances as $i) {
+            $settings = '';
+            $delete = '';
+            $settings .= '<a href="' . $baseurl . '&amp;type='.$typename.'&amp;edit=' . $i->id . '">' . $settingsstr . '</a>' . "\n";
+            if (!$i->readonly) {
+                $delete .= '<a href="' . $baseurl . '&amp;type='.$typename.'&amp;delete=' .  $i->id . '">' . $deletestr . '</a>' . "\n";
+            }
+
+            $type = repository::get_type_by_id($i->typeid);
+            $table->data[] = array($i->name, $type->get_readablename(), $delete, $settings);
+
+            //display a grey row if the type is defined as not visible
+            if (isset($type) && !$type->get_visible()) {
+                $table->rowclass[] = 'dimmed_text';
+            } else {
+                $table->rowclass[] = '';
+            }
+
+            if (!in_array($i->name, $alreadyplugins)) {
+                $alreadyplugins[] = $i->name;
+            }
+        }
+        $output .= print_table($table, true);
+        $instancehtml = '<div>';
+        $addable = 0;
+
+        //if no type is set, we can create all type of instance
+        if (!$typename) {
+            $instancehtml .= '<h3>';
+            $instancehtml .= get_string('createrepository', 'repository');
+            $instancehtml .= '</h3><ul>';
+            $types = repository::get_editable_types($context);
+            foreach ($types as $type) {
+                if (!empty($type) && $type->get_visible()) {
+                    $instanceoptionnames = repository::static_function($type->get_typename(), 'get_instance_option_names');
+                    if (!empty($instanceoptionnames)) {
+                        $instancehtml .= '<li><a href="'.$baseurl.'&amp;new='.$type->get_typename().'">'.get_string('create', 'repository')
+                            .' "'.get_string('repositoryname', 'repository_'.$type->get_typename()).'" '
+                            .get_string('instance', 'repository').'</a></li>';
+                        $addable++;
+                    }
+                }
+            }
+            $instancehtml .= '</ul>';

-    $types = array();
-    $params = null;
-    if (!empty($visible)) {
-        $params = array('visible' => $visible);
-    }
-    if ($records = $DB->get_records('repository',$params,'sortorder')) {
-        foreach($records as $type) {
-            $types[] = new repository_type($type->type, (array)get_config($type->type), $type->visible, $type->sortorder);
+        } else {
+            $instanceoptionnames = repository::static_function($typename, 'get_instance_option_names');
+            if (!empty($instanceoptionnames)) {   //create a unique type of instance
+                $addable = 1;
+                $instancehtml .= "<form action='".$baseurl."&amp;new=".$typename."' method='post'>
+                    <p style='text-align:center'><input type='submit' value='".get_string('createinstance', 'repository')."'/></p>
+                    </form>";
+            }
         }
-    }

-    return $types;
-}
+        if ($addable) {
+            $instancehtml .= '</div>';
+            $output .= $instancehtml;
+        }

-/**
- * This is the base class of the repository class
- *
- * To use repository plugin, see:
- * http://docs.moodle.org/en/Development:Repository_How_to_Create_Plugin
- *
- * class repository is an abstract class, some functions must be implemented in subclass.
- *
- * See an example: repository/boxnet/repository.class.php
- *
- * A few notes:
- *   // for ajax file picker, this will print a json string to tell file picker
- *   // how to build a login form
- *   $repo->print_login();
- *   // for ajax file picker, this will return a files list.
- *   $repo->get_listing();
- *   // this function will be used for non-javascript version.
- *   $repo->print_listing();
- *   // print a search box
- *   $repo->print_search();
- *
- * @package repository
- * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
- */
-abstract class repository {
-    // $disabled can be set to true to disable a plugin by force
-    // example: self::$disabled = true
-    public $disabled = false;
-    public $id;
-    public $context;
-    public $options;
-    public $readonly;
+        $output .= print_box_end(true);

+        //print the list + creation links
+        print($output);
+    }
     /**
      * 1. Initialize context and options
      * 2. Accept necessary parameters
@@ -627,9 +1175,9 @@
      * (is the type visible ? is the context enable ?)
      * @return boolean
      */
-    public function is_visible() {
-        $type = repository_get_type_by_id($this->typeid);
-        $instanceoptions = repository_static_function($type->get_typename(), 'get_instance_option_names');
+    public function is_visible() {
+        $type = repository::get_type_by_id($this->typeid);
+        $instanceoptions = repository::static_function($type->get_typename(), 'get_instance_option_names');

         if ($type->get_visible()) {
             //if the instance is unique so it's visible, otherwise check if the instance has a enabled context
@@ -713,7 +1261,7 @@

             if (!empty($id)) {
                 unset($options['name']);
-                $instance = repository_get_instance($id);
+                $instance = repository::get_instance($id);
                 $instance->set_option($options);
                 return $id;
             } else {
@@ -900,7 +1448,7 @@
     /**
      * Search files in repository
      * When doing global search, $search_text will be used as
-     * keyword.
+     * keyword.
      *
      * @return mixed, see get_listing()
      */
@@ -980,7 +1528,7 @@
      */
      public function type_config_form(&$mform) {
     }
-
+
       /**
      * Edit/Create Instance Settings Moodle form
      * @param object $ Moodle form (passed by reference)
@@ -1022,447 +1570,6 @@
 class repository_exception extends moodle_exception {
 }

-/**
- * Check context
- * @param int $ctx_id
- * @return boolean
- */
-function repository_check_context($ctx_id) {
-    global $USER;
-
-    $context = get_context_instance_by_id($ctx_id);
-    $level = $context->contextlevel;
-
-    if ($level == CONTEXT_COURSE) {
-        if (!has_capability('moodle/course:view', $context)) {
-            return false;
-        } else {
-            return true;
-        }
-    } else if ($level == CONTEXT_USER) {
-        $c = get_context_instance(CONTEXT_USER, $USER->id);
-        if ($c->id == $ctx_id) {
-            return true;
-        } else {
-            return false;
-        }
-    } else if ($level == CONTEXT_SYSTEM) {
-        // it is always ok in system level
-        return true;
-    }
-    return false;
-}
-
-/**
- * Return all types that you a user can create/edit and which are also visible
- * Note: Mostly used in order to know if at least one editable type can be set
- * @param object $context the context for which we want the editable types
- * @return array types
- */
-function repository_get_editable_types($context = null) {
-
-    if (empty($context)) {
-        $context = get_system_context();
-    }
-
-    $types= repository_get_types(true);
-    $editabletypes = array();
-    foreach ($types as $type) {
-        $instanceoptionnames = repository_static_function($type->get_typename(), 'get_instance_option_names');
-        if (!empty($instanceoptionnames)) {
-            if ($type->get_contextvisibility($context->contextlevel)) {
-                $editabletypes[]=$type;
-            }
-         }
-    }
-    return $editabletypes;
-}
-
-/**
- * Return repository instances
- * @global object $DB
- * @global object $CFG
- * @global object $USER
- * @param object $contexts contexts for which the instances are set
- * @param integer $userid
- * @param boolean $onlyvisible if visible == true, return visible instances only,
- *                otherwise, return all instances
- * @param string $type a type name to retrieve
- * @return array repository instances
- */
-function repository_get_instances($contexts=array(), $userid = null, $onlyvisible = true, $type=null) {
-    global $DB, $CFG, $USER;
-
-    $params = array();
-    $sql = 'SELECT i.*, r.type AS repositorytype, r.sortorder, r.visible FROM {repository} r, {repository_instances} i WHERE ';
-    $sql .= 'i.typeid = r.id ';
-
-    if (!empty($userid) && is_numeric($userid)) {
-        $sql .= ' AND (i.userid = 0 or i.userid = ?)';
-        $params[] = $userid;
-    }
-
-    foreach ($contexts as $context) {
-        if (empty($firstcontext)) {
-            $firstcontext = true;
-            $sql .= ' AND ((i.contextid = ?)';
-        } else {
-            $sql .= ' OR (i.contextid = ?)';
-        }
-        $params[] = $context->id;
-    }
-
-    if (!empty($firstcontext)) {
-       $sql .=')';
-    }
-
-    if ($onlyvisible == true) {
-        $sql .= ' AND (r.visible = 1)';
-    }
-
-    if (isset($type)) {
-        $sql .= ' AND (r.type = ?)';
-        $params[] = $type;
-    }
-    $sql .= ' order by r.sortorder, i.name';
-
-    if (!$repos = $DB->get_records_sql($sql, $params)) {
-        $repos = array();
-    }
-
-    $ret = array();
-    foreach ($repos as $repo) {
-        require_once($CFG->dirroot . '/repository/'. $repo->repositorytype.'/repository.class.php');
-        $options['visible'] = $repo->visible;
-        $options['name']    = $repo->name;
-        $options['type']    = $repo->repositorytype;
-        $options['typeid']  = $repo->typeid;
-        $classname = 'repository_' . $repo->repositorytype;//
-
-        $repository = new $classname($repo->id, $repo->contextid, $options, $repo->readonly);
-        if (!$onlyvisible || ($repository->is_visible() && !$repository->disabled)) {
-            $ret[] = $repository;
-        }
-    }
-    return $ret;
-}
-
-/**
- * Get single repository instance
- * @global object $DB
- * @global object $CFG
- * @param integer $id repository id
- * @return object repository instance
- */
-function repository_get_instance($id) {
-    global $DB, $CFG;
-    $sql = 'SELECT i.*, r.type AS repositorytype, r.visible FROM {repository} r, {repository_instances} i WHERE ';
-    $sql .= 'i.typeid = r.id AND ';
-    $sql .= 'i.id = '.$id;
-
-    if(!$instance = $DB->get_record_sql($sql)) {
-        return false;
-    }
-    require_once($CFG->dirroot . '/repository/'. $instance->repositorytype
-            . '/repository.class.php');
-    $classname = 'repository_' . $instance->repositorytype;
-    $options['typeid'] = $instance->typeid;
-    $options['type']   = $instance->repositorytype;
-    $options['name']   = $instance->name;
-    return new $classname($instance->id, $instance->contextid, $options, $instance->readonly);
-}
-
-/**
- * call a static function
- * @global <type> $CFG
- * @param <type> $plugin
- * @param <type> $function
- * @param type $nocallablereturnvalue default value if function not found
- *             it's mostly used when you don't want to display an error but
- *             return a boolean
- * @return <type>
- */
-function repository_static_function($plugin, $function) {
-    global $CFG;
-
-    //check that the plugin exists
-    $typedirectory = $CFG->dirroot . '/repository/'. $plugin . '/repository.class.php';
-    if (!file_exists($typedirectory)) {
-        throw new repository_exception('invalidplugin', 'repository');
-    }
-
-    $pname = null;
-    if (is_object($plugin) || is_array($plugin)) {
-        $plugin = (object)$plugin;
-        $pname = $plugin->name;
-    } else {
-        $pname = $plugin;
-    }
-
-    $args = func_get_args();
-    if (count($args) <= 2) {
-        $args = array();
-    }
-    else {
-        array_shift($args);
-        array_shift($args);
-    }
-
-    require_once($typedirectory);
-    return call_user_func_array(array('repository_' . $plugin, $function), $args);
-}
-
-/**
- * Move file from download folder to file pool using FILE API
- * @global object $DB
- * @global object $CFG
- * @global object $USER
- * @param string $path file path in download folder
- * @param string $name file name
- * @param integer $itemid item id to identify a file in filepool
- * @param string $filearea file area
- * @return array information of file in file pool
- */
-function repository_move_to_filepool($path, $name, $itemid, $filearea = 'user_draft') {
-    global $DB, $CFG, $USER;
-    $context = get_context_instance(CONTEXT_USER, $USER->id);
-    $now = time();
-    $entry = new object();
-    $entry->filearea  = $filearea;
-    $entry->contextid = $context->id;
-    $entry->filename  = $name;
-    $entry->filepath  = '/'.uniqid().'/';
-    $entry->timecreated  = $now;
-    $entry->timemodified = $now;
-    if(is_numeric($itemid)) {
-        $entry->itemid = $itemid;
-    } else {
-        $entry->itemid = 0;
-    }
-    $entry->mimetype     = mimeinfo('type', $path);
-    $entry->userid       = $USER->id;
-    $fs = get_file_storage();
-    $browser = get_file_browser();
-    if ($file = $fs->create_file_from_pathname($entry, $path)) {
-        $delete = unlink($path);
-        $ret = $browser->get_file_info($context, $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename());
-        if(!empty($ret)) {
-            return array('url'=>$ret->get_url(),'id'=>$file->get_itemid(), 'file'=>$file->get_filename());
-        } else {
-            return null;
-        }
-    } else {
-        return null;
-    }
-}
-
-function repository_download_btn($repo_id, $ctx_id, $sesskey, $title, $src, $returnurl = '') {
-    global $CFG;
-    if (empty($returnurl)) {
-        $returnurl = get_referer();
-    }
-    $str  = '<form action="'.$CFG->httpswwwroot.'/repository/ws.php">';
-    $str .= '  <input type="hidden" name="sesskey" value="'.$sesskey.'" />';
-    $str .= '  <input type="hidden" name="ctx_id" value="'.$ctx_id.'" />';
-    $str .= '  <input type="hidden" name="repo_id" value="'.$repo_id.'" />';
-    $str .= '  <input type="hidden" name="file" value="'.$src.'" />';
-    $str .= '  <input type="hidden" name="action" value="download" />';
-    $str .= '  <input type="hidden" name="returnurl" value="'.$returnurl.'" />';
-    $str .= '  <input type="text" name="title" value="'.$title.'" />';
-    $str .= '  <input type="submit" value="Select it!" />';
-    $str .= '</form>';
-    return $str;
-}
-
-/**
- * Save file to local filesystem pool
- * @param string $elname name of element
- * @param string $filearea
- * @param string $filepath
- * @param string $filename - use specified filename, if not specified name of uploaded file used
- * @param bool $override override file if exists
- * @return mixed stored_file object or false if error; may throw exception if duplicate found
- */
-function repository_store_to_filepool($elname, $filearea='user_draft', $filepath='/', $filename = '', $override = false) {
-    global $USER;
-    if (!isset($_FILES[$elname])) {
-        return false;
-    }
-
-    if (!$filename) {
-        $filename = $_FILES[$elname]['name'];
-    }
-    $context = get_context_instance(CONTEXT_USER, $USER->id);
-    $itemid = (int)substr(hexdec(uniqid()), 0, 9)+rand(1,100);
-    $fs = get_file_storage();
-    $browser = get_file_browser();
-
-    if ($file = $fs->get_file($context->id, $filearea, $itemid, $filepath, $filename)) {
-        if ($override) {
-            $file->delete();
-        } else {
-            return false;
-        }
-    }
-
-    $file_record = new object();
-    $file_record->contextid = $context->id;
-    $file_record->filearea  = $filearea;
-    $file_record->itemid    = $itemid;
-    $file_record->filepath  = $filepath;
-    $file_record->filename  = $filename;
-    $file_record->userid    = $USER->id;
-
-    $file = $fs->create_file_from_pathname($file_record, $_FILES[$elname]['tmp_name']);
-    $info = $browser->get_file_info($context, $file->get_filearea(), $file->get_itemid(), $file->get_filepath(), $file->get_filename());
-    $ret = array('url'=>$info->get_url(),'id'=>$itemid, 'file'=>$file->get_filename());
-    return $ret;
-}
-
-/**
- * Return the user arborescence in a format to be returned by the function get_listing
- * @global <type> $CFG
- * @param <type> $search
- * @return <type>
- */
-function repository_get_user_file_tree($search = ""){
-    global $CFG;
- $ret = array();
-        $ret['nologin'] = true;
-        $ret['manage'] = $CFG->wwwroot .'/files/index.php'; // temporary
-        $browser = get_file_browser();
-        $itemid = null;
-        $filename = null;
-        $filearea = null;
-        $path = '/';
-        $ret['dynload'] = false;
-
-        if ($fileinfo = $browser->get_file_info(get_system_context(), $filearea, $itemid, $path, $filename)) {
-
-            $ret['path'] = array();
-            $params = $fileinfo->get_params();
-            $filearea = $params['filearea'];
-            $ret['path'][] = repository_encode_path($filearea, $path, $fileinfo->get_visible_name());
-            if ($fileinfo->is_directory()) {
-                $level = $fileinfo->get_parent();
-                while ($level) {
-                    $params = $level->get_params();
-                    $ret['path'][] = repository_encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
-                    $level = $level->get_parent();
-                }
-            }
-            $filecount = repository_build_tree($fileinfo, $search, $ret['dynload'], $ret['list']);
-            $ret['path'] = array_reverse($ret['path']);
-        }
-
-        if (empty($ret['list'])) {
-            //exit(mnet_server_fault(9016, get_string('emptyfilelist', 'repository_local')));
-            throw new Exception('emptyfilelist');
-        } else {
-            return $ret;
-        }
-
-}
-
- /**
-     *
-     * @param <type> $filearea
-     * @param <type> $path
-     * @param <type> $visiblename
-     * @return <type>
-     */
-    function repository_encode_path($filearea, $path, $visiblename) {
-        return array('path'=>serialize(array($filearea, $path)), 'name'=>$visiblename);
-    }
-
- /**
-     * Builds a tree of files This function is
-     * then called recursively.
-     *
-     * @param $fileinfo an object returned by file_browser::get_file_info()
-     * @param $search searched string
-     * @param $dynamicmode bool no recursive call is done when in dynamic mode
-     * @param $list - the array containing the files under the passed $fileinfo
-     * @returns int the number of files found
-     *
-     * todo: take $search into account, and respect a threshold for dynamic loading
-     */
-    function repository_build_tree($fileinfo, $search, $dynamicmode, &$list) {
-        global $CFG;
-
-        $filecount = 0;
-        $children = $fileinfo->get_children();
-
-        foreach ($children as $child) {
-            $filename = $child->get_visible_name();
-            $filesize = $child->get_filesize();
-            $filesize = $filesize ? display_size($filesize) : '';
-            $filedate = $child->get_timemodified();
-            $filedate = $filedate ? userdate($filedate) : '';
-            $filetype = $child->get_mimetype();
-
-            if ($child->is_directory()) {
-                $path = array();
-                $level = $child->get_parent();
-                while ($level) {
-                    $params = $level->get_params();
-                    $path[] = repository_encode_path($params['filearea'], $params['filepath'], $level->get_visible_name());
-                    $level = $level->get_parent();
-                }
-
-                $tmp = array(
-                    'title' => $child->get_visible_name(),
-                    'size' => 0,
-                    'date' => $filedate,
-                    'path' => array_reverse($path),
-                    'thumbnail' => $CFG->pixpath .'/f/folder.gif'
-                );
-
-                //if ($dynamicmode && $child->is_writable()) {
-                //    $tmp['children'] = array();
-                //} else {
-                    // if folder name matches search, we send back all files contained.
-                $_search = $search;
-                if ($search && stristr($tmp['title'], $search) !== false) {
-                    $_search = false;
-                }
-                $tmp['children'] = array();
-                $_filecount = repository_build_tree($child, $_search, $dynamicmode, $tmp['children']);
-                if ($search && $_filecount) {
-                    $tmp['expanded'] = 1;
-                }
-
-                //}
-
-                //Uncomment this following line if you wanna display all directory ()even empty
-                //if (!$search || $_filecount || (stristr($tmp['title'], $search) !== false)) {
-                if ($_filecount) {
-                    $filecount += $_filecount;
-                    $list[] = $tmp;
-                }
-
-            } else { // not a directory
-                // skip the file, if we're in search mode and it's not a match
-                if ($search && (stristr($filename, $search) === false)) {
-                    continue;
-                }
-                $params = $child->get_params();
-                $source = serialize(array($params['contextid'], $params['filearea'], $params['itemid'], $params['filepath'], $params['filename']));
-                $list[] = array(
-                    'title' => $filename,
-                    'size' => $filesize,
-                    'date' => $filedate,
-                    //'source' => $child->get_url(),
-                    'source' => base64_encode($source),
-                    'thumbnail' => $CFG->pixpath .'/f/'. mimeinfo_from_type("icon", $filetype)
-                );
-                $filecount++;
-            }
-        }
-
-        return $filecount;
-    }
-

 /**
  * TODO: write comment
@@ -1500,7 +1607,7 @@

         //add fields
         if (!$this->instance) {
-            $result = repository_static_function($this->plugin, 'instance_config_form', $mform);
+            $result = repository::static_function($this->plugin, 'instance_config_form', $mform);
         }
         else {
             $data = array();
@@ -1569,14 +1676,14 @@

         // let the plugin add its specific fields
         if (!$this->instance) {
-                $result = repository_static_function($this->plugin, 'type_config_form', $mform);
+                $result = repository::static_function($this->plugin, 'type_config_form', $mform);
             } else {
                 $classname = 'repository_' . $this->instance->get_typename();
                 $result = call_user_func(array($classname,'type_config_form'),$mform);
         }

         //add "enable course/user instances" checkboxes if multiple instances are allowed
-        $instanceoptionnames = repository_static_function($this->plugin, 'get_instance_option_names');
+        $instanceoptionnames = repository::static_function($this->plugin, 'get_instance_option_names');
         if (!empty($instanceoptionnames)){
             $mform->addElement('checkbox', 'enablecourseinstances', get_string('enablecourseinstances', 'repository'));
             $mform->addElement('checkbox', 'enableuserinstances', get_string('enableuserinstances', 'repository'));
@@ -1601,115 +1708,9 @@
             }
             $this->set_data($data);
         }
-
+
         $this->add_action_buttons(true, get_string('save','repository'));
     }
 }


-/**
- * Display a repository instance list (with edit/delete/create links)
- * @global object $CFG
- * @global object $USER
- * @param object $context the context for which we display the instance
- * @param string $typename if set, we display only one type of instance
- */
-function repository_display_instances_list($context, $typename = null) {
-    global $CFG, $USER;
-
-    $output = print_box_start('generalbox','',true);
-    //if the context is SYSTEM, so we call it from administration page
-    $admin = ($context->id == SYSCONTEXTID) ? true : false;
-    if ($admin) {
-        $baseurl = $CFG->httpswwwroot . '/admin/repositoryinstance.php?sesskey=' . sesskey();
-        $output .= "<div ><h2 style='text-align: center'>" . get_string('siteinstances', 'repository') . " ";
-        $output .= "</h2></div>";
-    } else {
-        $baseurl = $CFG->httpswwwroot . '/repository/manage_instances.php?contextid=' . $context->id . '&amp;sesskey=' . sesskey();
-    }
-
-    $namestr = get_string('name');
-    $pluginstr = get_string('plugin', 'repository');
-    $settingsstr = get_string('settings');
-    $deletestr = get_string('delete');
-    $updown = get_string('updown', 'repository');
-    //retrieve list of instances. In administration context we want to display all
-    //instances of a type, even if this type is not visible. In course/user context we
-    //want to display only visible instances, but for every type types. The repository_get_instances()
-    //third parameter displays only visible type.
-    $instances = repository_get_instances(array($context),null,!$admin,$typename);
-    $instancesnumber = count($instances);
-    $alreadyplugins = array();
-
-    $table = new StdClass;
-    $table->head = array($namestr, $pluginstr, $deletestr, $settingsstr);
-    $table->align = array('left', 'left', 'center','center');
-    $table->data = array();
-
-    $updowncount = 1;
-
-    foreach ($instances as $i) {
-        $settings = '';
-        $delete = '';
-        $settings .= '<a href="' . $baseurl . '&amp;type='.$typename.'&amp;edit=' . $i->id . '">' . $settingsstr . '</a>' . "\n";
-        if (!$i->readonly) {
-            $delete .= '<a href="' . $baseurl . '&amp;type='.$typename.'&amp;delete=' .  $i->id . '">' . $deletestr . '</a>' . "\n";
-        }
-
-        $type = repository_get_type_by_id($i->typeid);
-        $table->data[] = array($i->name, $type->get_readablename(), $delete, $settings);
-
-        //display a grey row if the type is defined as not visible
-        if (isset($type) && !$type->get_visible()) {
-            $table->rowclass[] = 'dimmed_text';
-        } else {
-            $table->rowclass[] = '';
-        }
-
-        if (!in_array($i->name, $alreadyplugins)) {
-            $alreadyplugins[] = $i->name;
-        }
-    }
-    $output .= print_table($table, true);
-    $instancehtml = '<div>';
-    $addable = 0;
-
-    //if no type is set, we can create all type of instance
-    if (!$typename) {
-        $instancehtml .= '<h3>';
-        $instancehtml .= get_string('createrepository', 'repository');
-        $instancehtml .= '</h3><ul>';
-        $types = repository_get_editable_types($context);
-        foreach ($types as $type) {
-            if (!empty($type) && $type->get_visible()) {
-                $instanceoptionnames = repository_static_function($type->get_typename(), 'get_instance_option_names');
-                if (!empty($instanceoptionnames)) {
-                    $instancehtml .= '<li><a href="'.$baseurl.'&amp;new='.$type->get_typename().'">'.get_string('create', 'repository')
-                        .' "'.get_string('repositoryname', 'repository_'.$type->get_typename()).'" '
-                        .get_string('instance', 'repository').'</a></li>';
-                    $addable++;
-                }
-            }
-        }
-        $instancehtml .= '</ul>';
-
-    } else {
-        $instanceoptionnames = repository_static_function($typename, 'get_instance_option_names');
-        if (!empty($instanceoptionnames)) {   //create a unique type of instance
-            $addable = 1;
-            $instancehtml .= "<form action='".$baseurl."&amp;new=".$typename."' method='post'>
-                <p style='text-align:center'><input type='submit' value='".get_string('createinstance', 'repository')."'/></p>
-                </form>";
-        }
-    }
-
-    if ($addable) {
-        $instancehtml .= '</div>';
-        $output .= $instancehtml;
-    }
-
-    $output .= print_box_end(true);
-
-    //print the list + creation links
-    print($output);
-}
Index: repository/manage_instances.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/manage_instances.php,v
retrieving revision 1.7
diff -u -a -r1.7 manage_instances.php
--- repository/manage_instances.php	9 Oct 2008 03:02:26 -0000	1.7
+++ repository/manage_instances.php	13 Nov 2008 10:36:37 -0000
@@ -55,13 +55,13 @@

 /// Security: we cannot perform any action if the type is not visible or if the context has been disabled
     if (!empty($new)){
-        $type = repository_get_type_by_typename($new);
+        $type = repository::get_type_by_typename($new);
     } else if (!empty($edit)){
-        $instance = repository_get_instance($edit);
-        $type = repository_get_type_by_id($instance->typeid);
+        $instance = repository::get_instance($edit);
+        $type = repository::get_type_by_id($instance->typeid);
     } else if (!empty($delete)){
-        $instance = repository_get_instance($delete);
-        $type = repository_get_type_by_id($instance->typeid);
+        $instance = repository::get_instance($delete);
+        $type = repository::get_type_by_id($instance->typeid);
     }
     if (isset($type) && ( !$type->get_visible() || (!$type->get_contextvisibility($context->contextlevel)) ) ) {
         print_error('typenotvisible', 'repository', $baseurl);
@@ -76,7 +76,7 @@
                 'type' => 'misc');
         $navlinks[] = array('name' => $pagename,
                 'link' => null,
-                'type' => 'misc');
+                'type' => 'misc');
         $fullname = $course->fullname;
     } else {
         $fullname = fullname($user);
@@ -106,12 +106,12 @@

     if (!empty($edit) || !empty($new)) {
         if (!empty($edit)) {
-            $instance = repository_get_instance($edit);
+            $instance = repository::get_instance($edit);
             //if you try to edit an instance set as readonly, display an error message
             if ($instance->readonly) {
                 throw new repository_exception('readonlyinstance', 'repository');
             }
-            $instancetype = repository_get_type_by_id($instance->typeid);
+            $instancetype = repository::get_type_by_id($instance->typeid);
             $classname = 'repository_' . $instancetype->get_typename();
             $configs  = $instance->get_instance_option_names();
             $plugin = $instancetype->get_typename();
@@ -142,7 +142,7 @@
                 }
                 $success = $instance->set_option($settings);
             } else {
-                $success = repository_static_function($plugin, 'create', $plugin, 0, get_context_instance_by_id($contextid), $fromform);
+                $success = repository::static_function($plugin, 'create', $plugin, 0, get_context_instance_by_id($contextid), $fromform);
                 $data = data_submitted();
             }
             if ($success) {
@@ -164,7 +164,7 @@
         }
     } else if (!empty($delete)) {
         // admin_externalpage_print_header();
-        $instance = repository_get_instance($delete);
+        $instance = repository::get_instance($delete);
          //if you try to delete an instance set as readonly, display an error message
         if ($instance->readonly) {
             throw new repository_exception('readonlyinstance', 'repository');
@@ -185,7 +185,7 @@
         notice_yesno(get_string('confirmdelete', 'repository', $instance->name), $baseurl . '&amp;delete=' . $delete . '&amp;sure=yes', $baseurl);
         $return = false;
     } else {
-        repository_display_instances_list($context);
+        repository::display_instances_list($context);
         $return = false;
     }

Index: repository/ws.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/ws.php,v
retrieving revision 1.45
diff -u -a -r1.45 ws.php
--- repository/ws.php	23 Oct 2008 04:26:48 -0000	1.45
+++ repository/ws.php	13 Nov 2008 10:36:37 -0000
@@ -23,7 +23,7 @@
     header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");

 /// Check permissions
-    if (! (isloggedin() && repository_check_context($ctx_id)) ) {
+    if (! (isloggedin() && repository::check_context($ctx_id)) ) {
         $err = new stdclass;
         $err->e = get_string('nopermissiontoaccess', 'repository');
         die(json_encode($err));
@@ -36,7 +36,7 @@
     switch ($action) {

         case 'gsearch':     //  Global Search
-            $repos = repository_get_instances(array(get_context_instance_by_id($ctx_id), get_system_context()));
+            $repos = repository::get_instances(array(get_context_instance_by_id($ctx_id), get_system_context()));
             $list = array();
             foreach($repos as $repo){
                 if ($repo->global_search()) {
@@ -158,7 +158,7 @@
                 if (preg_match('#(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)#', $path)) {
                     echo json_encode(array('url'=>$path, 'id'=>$path, 'file'=>$path));
                 } else {
-                    $info = repository_move_to_filepool($path, $title, $itemid);
+                    $info = repository::move_to_filepool($path, $title, $itemid);
                     if ($env == 'form'){
                         echo json_encode($info);
                     } else if ($env == 'editor') {
Index: repository/flickr/repository.class.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/flickr/repository.class.php,v
retrieving revision 1.51
diff -u -a -r1.51 repository.class.php
--- repository/flickr/repository.class.php	18 Sep 2008 05:43:38 -0000	1.51
+++ repository/flickr/repository.class.php	13 Nov 2008 10:36:37 -0000
@@ -271,7 +271,7 @@
         $mform->addElement('text', 'secret', get_string('secret', 'repository_flickr'), array('value'=>$secret,'size' => '40'));

         //retrieve the flickr instances
-        $instances = repository_get_instances(array(),null,false,"flickr");
+        $instances = repository::get_instances(array(),null,false,"flickr");
         if (empty($instances)) {
             $callbackurl = get_string("callbackwarning","repository_flickr");
              $mform->addElement('static', null, '',  $callbackurl);
Index: repository/flickr_public/repository.class.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/flickr_public/repository.class.php,v
retrieving revision 1.25
diff -u -a -r1.25 repository.class.php
--- repository/flickr_public/repository.class.php	24 Sep 2008 06:25:22 -0000	1.25
+++ repository/flickr_public/repository.class.php	13 Nov 2008 10:36:37 -0000
@@ -318,7 +318,7 @@
      */
     public static function plugin_init() {
         //here we create a default instance for this type
-        repository_static_function('flickr_public','create', 'flickr_public', 0, get_system_context(), array('name' => get_string('repositoryname', 'repository_flickr_public'),'email_address' => null),1);
+        repository::static_function('flickr_public','create', 'flickr_public', 0, get_system_context(), array('name' => get_string('repositoryname', 'repository_flickr_public'),'email_address' => null),1);
     }

 }
Index: repository/local/repository.class.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/local/repository.class.php,v
retrieving revision 1.23
diff -u -a -r1.23 repository.class.php
--- repository/local/repository.class.php	30 Oct 2008 02:30:26 -0000	1.23
+++ repository/local/repository.class.php	13 Nov 2008 10:36:37 -0000
@@ -77,15 +77,15 @@
      */
     public function get_listing($encodedpath = '', $search = '') {
         global $CFG;

         try {
-            return repository_get_user_file_tree($search);
+            return repository::get_user_file_tree($search);
         }
         catch (Exception $e) {
             throw new repository_exception('emptyfilelist', 'repository_local');
         }
     }

Index: repository/remotemoodle/repository.class.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/remotemoodle/repository.class.php,v
retrieving revision 1.15
diff -u -a -r1.15 repository.class.php
--- repository/remotemoodle/repository.class.php	30 Oct 2008 04:24:46 -0000	1.15
+++ repository/remotemoodle/repository.class.php	13 Nov 2008 10:36:38 -0000
@@ -100,9 +100,9 @@
         if (empty($USER)) {
             exit(mnet_server_fault(9016, get_string('usernotfound', 'repository_remotemoodle',  $username)));
         }

         try {
-            return repository_get_user_file_tree($search);
+            return repository::get_user_file_tree($search);
         }
         catch (Exception $e) {
             exit(mnet_server_fault(9016, get_string('failtoretrievelist', 'repository_remotemoodle')));
Index: repository/upload/repository.class.php
===================================================================
RCS file: /cvsroot/moodle/moodle/repository/upload/repository.class.php,v
retrieving revision 1.8
diff -u -a -r1.8 repository.class.php
--- repository/upload/repository.class.php	18 Sep 2008 05:43:38 -0000	1.8
+++ repository/upload/repository.class.php	13 Nov 2008 10:36:38 -0000
@@ -26,7 +26,7 @@
         parent::__construct($repositoryid, $context, $options);
         if($action=='upload'){
             $filepath = '/'.uniqid().'/';
-            $this->info = repository_store_to_filepool('repo_upload_file', 'user_draft', $filepath);
+            $this->info = repository::store_to_filepool('repo_upload_file', 'user_draft', $filepath);
         }
     }

Index: user/repository.php
===================================================================
RCS file: /cvsroot/moodle/moodle/user/repository.php,v
retrieving revision 1.4
diff -u -a -r1.4 repository.php
--- user/repository.php	28 Aug 2008 05:30:19 -0000	1.4
+++ user/repository.php	13 Nov 2008 10:36:48 -0000
@@ -35,7 +35,7 @@
 print_heading($configstr);
 print_simple_box_start();

-if (!$instances = repository_get_instances($COURSE->context, $USER->id)) {
+if (!$instances = repository::get_instances($COURSE->context, $USER->id)) {
     print_error('noinstances', 'repository', $CFG->wwwroot . '/user/view.php');
 }

Index: user/tabs.php
===================================================================
RCS file: /cvsroot/moodle/moodle/user/tabs.php,v
retrieving revision 1.69
diff -u -a -r1.69 tabs.php
--- user/tabs.php	9 Oct 2008 03:02:26 -0000	1.69
+++ user/tabs.php	13 Nov 2008 10:36:48 -0000
@@ -259,7 +259,7 @@
     if (!empty($user) and $user->id == $USER->id) {
         require_once($CFG->dirroot . '/repository/lib.php');
         $usercontext = get_context_instance(CONTEXT_USER,$user->id);
-        $editabletypes = repository_get_editable_types($usercontext);
+        $editabletypes = repository::get_editable_types($usercontext);
         if (!empty($usercontext) && $usercontext->contextlevel == CONTEXT_USER && !empty($editabletypes)) {
             $toprow[] = new tabobject('repositories', $CFG->wwwroot .'/repository/manage_instances.php?contextid='.$usercontext->id, get_string('repositories', 'repository'));
         }
