Merge branch 'MDL-33818' of git://github.com/timhunt/moodle
authorDan Poltawski <dan@moodle.com>
Mon, 18 Jun 2012 13:33:26 +0000 (21:33 +0800)
committerDan Poltawski <dan@moodle.com>
Mon, 18 Jun 2012 13:33:26 +0000 (21:33 +0800)
15 files changed:
files/renderer.php
lang/en/moodle.php
lang/en/repository.php
lib/form/dndupload.js
lib/form/filemanager.js
lib/outputrequirementslib.php
lib/portfolio/forms.php
lib/portfolio/plugin.php
portfolio/boxnet/lib.php
portfolio/flickr/lib.php
portfolio/googledocs/lib.php
portfolio/mahara/lib.php
portfolio/picasa/lib.php
portfolio/upgrade.txt [new file with mode: 0644]
repository/upload/lib.php

index 2f5f5d4..f1b629e 100644 (file)
@@ -802,7 +802,8 @@ class core_files_renderer extends plugin_renderer_base {
      * Must have one top element, CSS for this element must define width and height of the window;
      *
      * content of element with class 'fp-dlg-text' will be replaced with dialog text;
-     * elements with classes 'fp-dlg-butoverwrite', 'fp-dlg-butrename' and 'fp-dlg-butcancel' will
+     * elements with classes 'fp-dlg-butoverwrite', 'fp-dlg-butrename',
+     * 'fp-dlg-butoverwriteall', 'fp-dlg-butrenameall' and 'fp-dlg-butcancel' will
      * hold onclick events;
      *
      * content of element with class 'fp-dlg-butrename' will be substituted with appropriate string
@@ -821,6 +822,34 @@ class core_files_renderer extends plugin_renderer_base {
         return preg_replace('/\{\!\}/', '', $rv);
     }
 
+    /**
+     * FilePicker JS template for popup dialogue window asking for action when file with the same name already exists (multiple-file version).
+     *
+     * Must have one top element, CSS for this element must define width and height of the window;
+     *
+     * content of element with class 'fp-dlg-text' will be replaced with dialog text;
+     * elements with classes 'fp-dlg-butoverwrite', 'fp-dlg-butrename' and 'fp-dlg-butcancel' will
+     * hold onclick events;
+     *
+     * content of element with class 'fp-dlg-butrename' will be substituted with appropriate string
+     * (Note that it may have long text)
+     *
+     * @return string
+     */
+    private function fp_js_template_processexistingfilemultiple() {
+        $rv = '
+<div class="file-picker fp-dlg">
+    <p class="{!}fp-dlg-text"></p>
+    <a class="{!}fp-dlg-butoverwrite fp-panel-button" href="#">'.get_string('overwrite', 'repository').'</a>
+    <a class="{!}fp-dlg-butcancel fp-panel-button" href="#">'.get_string('cancel').'</a>
+    <a class="{!}fp-dlg-butrename fp-panel-button" href="#"></a>
+    <br/>
+    <a class="{!}fp-dlg-butoverwriteall fp-panel-button" href="#">'.get_string('overwriteall', 'repository').'</a>
+    <a class="{!}fp-dlg-butrenameall fp-panel-button" href="#">'.get_string('renameall', 'repository').'</a>
+</div>';
+        return preg_replace('/\{\!\}/', '', $rv);
+    }
+
     /**
      * FilePicker JS template for repository login form including templates for each element type
      *
index ba5553c..d0b5f9d 100644 (file)
@@ -684,6 +684,7 @@ $string['failedloginattempts'] = '{$a->attempts} failed logins since your last l
 $string['failedloginattemptsall'] = '{$a->attempts} failed logins for {$a->accounts} accounts';
 $string['feedback'] = 'Feedback';
 $string['file'] = 'File';
+$string['fileexists'] = 'There is already a file called {$a}';
 $string['filemissing'] = '{$a} is missing';
 $string['filetoolarge'] = 'is too large to upload';
 $string['files'] = 'Files';
@@ -1714,7 +1715,7 @@ $string['uploadedfiletoobig'] = 'Sorry, but that file is too big (limit is {$a}
 $string['uploadextension'] = 'File upload stopped by extension';
 $string['uploadfailednotrecovering'] = 'Your file upload has failed because there was a problem with one of the files, {$a->name}.<br /> Here is a log of the problems:<br />{$a->problem}<br />Not recovering.';
 $string['uploadfilelog'] = 'Upload log for file {$a}';
-$string['uploadformlimit'] = 'Uploaded file exceeded the maximum size limit set by the form';
+$string['uploadformlimit'] = 'Uploaded file {$a} exceeded the maximum size limit set by the form';
 $string['uploadlabel'] = 'Title:';
 $string['uploadnewfile'] = 'Upload new file';
 $string['uploadnofilefound'] = 'No file was found - are you sure you selected one to upload?';
index d8d90f0..1245426 100644 (file)
@@ -163,6 +163,7 @@ $string['openpicker'] = 'Choose a file...';
 $string['operation'] = 'Operation';
 $string['on'] = 'Enabled and visible';
 $string['overwrite'] = 'Overwrite';
+$string['overwriteall'] = 'Overwrite all';
 $string['personalrepositories'] = 'Available repository instances';
 $string['plugin'] = 'Repository plug-ins';
 $string['pluginerror'] = 'Errors in repository plugin.';
@@ -176,6 +177,7 @@ $string['referenceslist'] = 'Aliases/Shortcuts';
 $string['refresh'] = 'Refresh';
 $string['refreshnonjsfilepicker'] = 'Please close this window and refresh non-javascript file picker';
 $string['removed'] = 'Repository removed';
+$string['renameall'] = 'Rename all';
 $string['renameto'] = 'Rename to "{$a}"';
 $string['repositories'] = 'Repositories';
 $string['repository'] = 'Repository';
index 2e1514c..103d316 100644 (file)
@@ -30,12 +30,12 @@ M.form_dndupload.init = function(Y, options) {
         Y: null,
         // URL for upload requests
         url: M.cfg.wwwroot + '/repository/repository_ajax.php?action=upload',
+        // options may include: itemid, acceptedtypes, maxfiles, maxbytes, clientid, repositoryid, author
+        options: {},
         // itemid used for repository upload
         itemid: null,
         // accepted filetypes accepted by this form passed to repository
         acceptedtypes: [],
-        // maximum number of files this form allows
-        maxfiles: 0,
         // maximum size of files allowed in this form
         maxbytes: 0,
         // unqiue id of this form field used for html elements
@@ -86,9 +86,9 @@ M.form_dndupload.init = function(Y, options) {
                 return; // no upload repository is enabled to upload to
             }
 
+            this.options = options;
             this.acceptedtypes = options.acceptedtypes;
             this.clientid = options.clientid;
-            this.maxfiles = options.maxfiles;
             this.maxbytes = options.maxbytes;
             this.itemid = options.itemid;
             this.author = options.author;
@@ -170,7 +170,7 @@ M.form_dndupload.init = function(Y, options) {
          * onto the page
          */
         drag_enter_page: function(e) {
-            if (!this.has_files(e) || this.reached_maxfiles()) {
+            if (!this.has_files(e)) {
                 return false;
             }
 
@@ -209,7 +209,7 @@ M.form_dndupload.init = function(Y, options) {
          * @param e event object
          * @return boolean true if a valid file drag event
          */
-        check_drag: function(e, maxfilesalert) {
+        check_drag: function(e) {
             if (!this.has_files(e)) {
                 return false;
             }
@@ -217,13 +217,6 @@ M.form_dndupload.init = function(Y, options) {
             e.preventDefault();
             e.stopPropagation();
 
-            if (this.reached_maxfiles()) {
-                if (typeof(maxfilesalert) != 'undefined' && maxfilesalert) {
-                    alert(M.util.get_string('maxfilesreached', 'moodle', this.maxfiles));
-                }
-                return false;
-            }
-
             return true;
         },
 
@@ -299,21 +292,28 @@ M.form_dndupload.init = function(Y, options) {
 
             var files = e._event.dataTransfer.files;
             if (this.filemanager) {
-                var currentfilecount = this.filemanager.filecount;
-                if (((currentfilecount + files.length) > this.maxfiles) && (this.maxfiles != -1)) {
-                    alert(M.util.get_string('maxfilesreached', 'moodle', this.maxfiles));
-                    return false;
-                }
-                this.show_progress_spinner();
-                for (var i=0, f; f=files[i]; i++) {
-                    if (this.upload_file(f)) {
-                        currentfilecount++;
-                    }
-                }
+                var options = {
+                    files: files,
+                    options: this.options,
+                    repositoryid: this.repositoryid,
+                    currentfilecount: this.filemanager.filecount, // All files uploaded.
+                    currentfiles: this.filemanager.options.list, // Only the current folder.
+                    callback: Y.bind('update_filemanager', this)
+                };
+                var uploader = new dnduploader(options);
+                uploader.start_upload();
             } else {
-                this.show_progress_spinner();
                 if (files.length >= 1) {
-                    this.upload_file(files[0]);
+                    options = {
+                        files:[files[0]],
+                        options: this.options,
+                        repositoryid: this.repositoryid,
+                        currentfilecount: 0,
+                        currentfiles: [],
+                        callback: Y.bind('callback', this)
+                    };
+                    uploader = new dnduploader(options);
+                    uploader.start_upload();
                 }
             }
 
@@ -336,20 +336,6 @@ M.form_dndupload.init = function(Y, options) {
             return false;
         },
 
-        /**
-         * Check if reached the maximumum number of allowed files
-         *
-         * @return boolean true if reached maximum number of files
-         */
-        reached_maxfiles: function() {
-            if (this.filemanager) {
-                if (this.filemanager.filecount >= this.maxfiles && this.maxfiles != -1) {
-                    return true;
-                }
-            }
-            return false;
-        },
-
         /**
          * Highlight the area where files could be dropped
          */
@@ -376,40 +362,377 @@ M.form_dndupload.init = function(Y, options) {
         },
 
         /**
-         * Display a progress spinner in the destination node
+         * Tell the attached filemanager element (if any) to refresh on file
+         * upload
+         */
+        update_filemanager: function() {
+            if (this.filemanager) {
+                // update the filemanager that we've uploaded the files
+                this.filemanager.filepicker_callback();
+            }
+        }
+    };
+
+    var dnduploader = function(options) {
+        dnduploader.superclass.constructor.apply(this, arguments);
+    };
+
+    Y.extend(dnduploader, Y.Base, {
+        // The URL to send the upload data to.
+        api: M.cfg.wwwroot+'/repository/repository_ajax.php',
+        // Options passed into the filemanager/filepicker element.
+        options: {},
+        // The function to call when all uploads complete.
+        callback: null,
+        // The list of files dropped onto the element.
+        files: null,
+        // The ID of the 'upload' repository.
+        repositoryid: 0,
+        // Array of files already in the current folder (to check for name clashes).
+        currentfiles: null,
+        // Total number of files already uploaded (to check for exceeding limits).
+        currentfilecount: 0,
+        // The list of files to upload.
+        uploadqueue: [],
+        // This list of files with name clashes.
+        renamequeue: [],
+        // Set to true if the user has clicked on 'overwrite all'.
+        overwriteall: false,
+        // Set to true if the user has clicked on 'rename all'.
+        renameall: false,
+
+        /**
+         * Initialise the settings for the dnduploader
+         * @param object params - includes:
+         *                     options (copied from the filepicker / filemanager)
+         *                     repositoryid - ID of the upload repository
+         *                     callback - the function to call when uploads are complete
+         *                     currentfiles - the list of files already in the current folder in the filemanager
+         *                     currentfilecount - the total files already in the filemanager
+         *                     files - the list of files to upload
+         * @return void
+         */
+        initializer: function(params) {
+            this.options = params.options;
+            this.repositoryid = params.repositoryid;
+            this.callback = params.callback;
+            this.currentfiles = params.currentfiles;
+            this.currentfilecount = params.currentfilecount;
+
+            this.initialise_queue(params.files);
+        },
+
+        /**
+         * Entry point for starting the upload process (starts by processing any
+         * renames needed)
          */
-        show_progress_spinner: function() {
-            this.container.addClass('dndupload-uploading');
+        start_upload: function() {
+            this.process_renames(); // Automatically calls 'do_upload' once renames complete.
         },
 
         /**
-         * Remove progress spinner in the destination node
+         * Display a message in a popup
+         * @param string msg - the message to display
+         * @param string type - 'error' or 'info'
          */
-        hide_progress_spinner: function() {
-            this.container.removeClass('dndupload-uploading');
+        print_msg: function(msg, type) {
+            var header = M.str.moodle.error;
+            if (type != 'error') {
+                type = 'info'; // one of only two types excepted
+                header = M.str.moodle.info;
+            }
+            if (!this.msg_dlg) {
+                this.msg_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.message);
+                this.msg_dlg_node.generateID();
+
+                this.msg_dlg = new Y.Panel({
+                    srcNode      : this.msg_dlg_node,
+                    zIndex       : 800000,
+                    centered     : true,
+                    modal        : true,
+                    visible      : false,
+                    render       : true
+                });
+                this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
+                this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
+                    e.preventDefault();
+                    this.msg_dlg.hide();
+                }, this);
+            }
+
+            this.msg_dlg.set('headerContent', header);
+            this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
+            this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
+            this.msg_dlg.show();
         },
 
         /**
-         * Tell the attached filemanager element (if any) to refresh on file
-         * upload
+         * Check the size of each file and add to either the uploadqueue or, if there
+         * is a name clash, the renamequeue
+         * @param FileList files - the files to upload
+         * @return void
          */
-        update_filemanager: function() {
-            if (this.filemanager) {
-                // update the filemanager that we've uploaded the files
-                this.filemanager.filepicker_callback();
+        initialise_queue: function(files) {
+            this.uploadqueue = [];
+            this.renamequeue = [];
+
+            // Loop through the files and find any name clashes with existing files
+            var i;
+            for (i=0; i<files.length; i++) {
+                if (this.options.maxbytes > 0 && files[i].size > this.options.maxbytes) {
+                    // Check filesize before attempting to upload
+                    this.print_msg(M.util.get_string('uploadformlimit', 'moodle', files[i].name), 'error');
+                    this.uploadqueue = []; // No uploads if one file is too big.
+                    return;
+                }
+
+                if (this.has_name_clash(files[i].name)) {
+                    this.renamequeue.push(files[i]);
+                } else {
+                    if (!this.add_to_upload_queue(files[i], files[i].name, false)) {
+                        return;
+                    }
+                }
             }
         },
 
         /**
-         * Upload a single file via an AJAX call to the 'upload' repository
+         * Add a single file to the uploadqueue, whilst checking the maxfiles limit
+         * @param File file - the file to add
+         * @param string filename - the name to give the file on upload
+         * @param bool overwrite - true to overwrite the existing file
+         * @return bool true if added successfully
          */
-        upload_file: function(file) {
-            if (file.size > this.maxbytes && this.maxbytes > 0) {
-                // Check filesize before attempting to upload
-                this.hide_progress_spinner();
-                alert(M.util.get_string('uploadformlimit', 'moodle')+"\n'"+file.name+"'");
+        add_to_upload_queue: function(file, filename, overwrite) {
+            if (!overwrite) {
+                this.currentfilecount++;
+            }
+            if (this.options.maxfiles > 0 && this.currentfilecount > this.options.maxfiles) {
+                // Too many files - abort entire upload.
+                this.uploadqueue = [];
+                this.renamequeue = [];
+                this.print_msg(M.util.get_string('maxfilesreached', 'moodle', this.options.maxfiles), 'error');
                 return false;
             }
+            this.uploadqueue.push({file:file, filename:filename, overwrite:overwrite});
+            return true;
+        },
+
+        /**
+         * Take the next file from the renamequeue and ask the user what to do with
+         * it. Called recursively until the queue is empty, then calls do_upload.
+         * @return void
+         */
+        process_renames: function() {
+            if (this.renamequeue.length == 0) {
+                // All rename processing complete - start the actual upload.
+                this.do_upload();
+                return;
+            }
+            var multiplefiles = (this.renamequeue.length > 1);
+
+            // Get the next file from the rename queue.
+            var file = this.renamequeue.shift();
+            // Generate a non-conflicting name for it.
+            var newname = this.generate_unique_name(file.name);
+
+            // If the user has clicked on overwrite/rename ALL then process
+            // this file, as appropriate, then process the rest of the queue.
+            if (this.overwriteall) {
+                this.add_to_upload_queue(file, file.name, true);
+                this.process_renames();
+                return;
+            }
+            if (this.renameall) {
+                this.add_to_upload_queue(file, newname, false);
+                this.process_renames();
+                return;
+            }
+
+            // Ask the user what to do with this file.
+            var self = this;
+
+            var process_dlg_node;
+            if (multiplefiles) {
+                process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfilemultiple);
+            } else {
+                process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
+            }
+            var node = process_dlg_node;
+            node.generateID();
+            var process_dlg = new Y.Panel({
+                srcNode      : node,
+                headerContent: M.str.repository.fileexistsdialogheader,
+                zIndex       : 800000,
+                centered     : true,
+                modal        : true,
+                visible      : false,
+                render       : true,
+                buttons      : {}
+            });
+            process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
+
+            // Overwrite original.
+            node.one('.fp-dlg-butoverwrite').on('click', function(e) {
+                e.preventDefault();
+                process_dlg.hide();
+                self.add_to_upload_queue(file, file.name, true);
+                self.process_renames();
+            }, this);
+
+            // Rename uploaded file.
+            node.one('.fp-dlg-butrename').on('click', function(e) {
+                e.preventDefault();
+                process_dlg.hide();
+                self.add_to_upload_queue(file, newname, false);
+                self.process_renames();
+            }, this);
+
+            // Cancel all uploads.
+            node.one('.fp-dlg-butcancel').on('click', function(e) {
+                e.preventDefault();
+                process_dlg.hide();
+            }, this);
+
+            // When we are at the file limit, only allow 'overwrite', not rename.
+            if (this.currentfilecount == this.options.maxfiles) {
+                node.one('.fp-dlg-butrename').setStyle('display', 'none');
+                if (multiplefiles) {
+                    node.one('.fp-dlg-butrenameall').setStyle('display', 'none');
+                }
+            }
+
+            // If there are more files still to go, offer the 'overwrite/rename all' options.
+            if (multiplefiles) {
+                // Overwrite all original files.
+                node.one('.fp-dlg-butoverwriteall').on('click', function(e) {
+                    e.preventDefault();
+                    process_dlg.hide();
+                    this.overwriteall = true;
+                    self.add_to_upload_queue(file, file.name, true);
+                    self.process_renames();
+                }, this);
+
+                // Rename all new files.
+                node.one('.fp-dlg-butrenameall').on('click', function(e) {
+                    e.preventDefault();
+                    process_dlg.hide();
+                    this.renameall = true;
+                    self.add_to_upload_queue(file, newname, false);
+                    self.process_renames();
+                }, this);
+            }
+            node.one('.fp-dlg-text').setContent(M.util.get_string('fileexists', 'moodle', file.name));
+            process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', newname));
+
+            // Destroy the dialog once it has been hidden.
+            process_dlg.after('visibleChange', function(e) {
+                if (!process_dlg.get('visible')) {
+                    process_dlg.destroy(true);
+                }
+            });
+
+            process_dlg.show();
+        },
+
+        /**
+         * Checks if there is already a file with the given name in the current folder
+         * or in the list of already uploading files
+         * @param string filename - the name to test
+         * @return bool true if the name already exists
+         */
+        has_name_clash: function(filename) {
+            // Check against the already uploaded files
+            var i;
+            for (i=0; i<this.currentfiles.length; i++) {
+                if (filename == this.currentfiles[i].filename) {
+                    return true;
+                }
+            }
+            // Check against the uploading files that have already been processed
+            for (i=0; i<this.uploadqueue.length; i++) {
+                if (filename == this.uploadqueue[i].filename) {
+                    return true;
+                }
+            }
+            return false;
+        },
+
+        /**
+         * Adds _NUMBER to the end of the filename and increments this number until
+         * a unique name is found
+         * @param string filename
+         * @return string the unique filename generated
+         */
+        generate_unique_name: function(filename) {
+            // Split the filename into the basename + extension.
+            var extension;
+            var basename;
+            var dotpos = filename.lastIndexOf('.');
+            if (dotpos == -1) {
+                basename = filename;
+                extension = '';
+            } else {
+                basename = filename.substr(0, dotpos);
+                extension = filename.substr(dotpos, filename.length);
+            }
+
+            // Look to see if the name already has _NN at the end of it.
+            var number = 0;
+            var hasnumber = basename.match(/^(.*)_(\d+)$/);
+            if (hasnumber != null) {
+                // Note the current number & remove it from the basename.
+                number = parseInt(hasnumber[2]);
+                basename = hasnumber[1];
+            }
+
+            // Loop through increating numbers until a unique name is found.
+            var newname;
+            do {
+                number++;
+                newname = basename + '_' + number + extension;
+            } while (this.has_name_clash(newname));
+
+            return newname;
+        },
+
+        /**
+         * Upload the next file from the uploadqueue - called recursively after each
+         * upload is complete, then handles the callback to the filemanager/filepicker
+         * @param lastresult - the last result from the server
+         */
+        do_upload: function(lastresult) {
+            if (this.uploadqueue.length > 0) {
+                var filedetails = this.uploadqueue.shift();
+                this.upload_file(filedetails.file, filedetails.filename, filedetails.overwrite);
+            } else {
+                this.uploadfinished(lastresult);
+            }
+        },
+
+        /**
+         * Run the callback to the filemanager/filepicker
+         */
+        uploadfinished: function(lastresult) {
+            this.callback(lastresult);
+        },
+
+        /**
+         * Log any errors generated
+         */
+        add_error: function(text, errorlevel) {
+            // TODO
+            console.log(text);
+        },
+
+        /**
+         * Upload a single file via an AJAX call to the 'upload' repository. Automatically
+         * calls do_upload as each upload completes.
+         * @param File file - the file to upload
+         * @param string filename - the name to give the file
+         * @param bool overwrite - true if the existing file should be overwritten
+         */
+        upload_file: function(file, filename, overwrite) {
 
             // This would be an ideal place to use the Y.io function
             // however, this does not support data encoded using the
@@ -421,13 +744,12 @@ M.form_dndupload.init = function(Y, options) {
             var self = this;
             xhr.onreadystatechange = function() { // Process the server response
                 if (xhr.readyState == 4) {
-                    self.hide_progress_spinner();
                     if (xhr.status == 200) {
                         var result = JSON.parse(xhr.responseText);
                         if (result) {
                             if (result.error) {
-                                alert(result.error);
-                            } else if (self.callback) {
+                                self.add_error(result.error); // TODO add filename?
+                            } else {
                                 // Only update the filepicker if there were no errors
                                 if (result.event == 'fileexists') {
                                     // Do not worry about this, as we only care about the last
@@ -435,45 +757,52 @@ M.form_dndupload.init = function(Y, options) {
                                     result.file = result.newfile.filename;
                                     result.url = result.newfile.url;
                                 }
-                                result.client_id = self.clientid;
-                                self.callback(result);
-                            } else {
-                                self.update_filemanager();
+                                result.client_id = self.options.clientid;
                             }
                         }
+                        self.processedfiles++;
+                        self.do_upload(result); // continue uploading
                     } else {
-                        alert(M.util.get_string('serverconnection', 'error'));
+                        self.add_error(M.util.get_string('serverconnection', 'error'));
+                        this.uploadfinished();
                     }
                 }
             };
 
             // Prepare the data to send
             var formdata = new FormData();
+            formdata.append('action', 'upload');
             formdata.append('repo_upload_file', file); // The FormData class allows us to attach a file
             formdata.append('sesskey', M.cfg.sesskey);
             formdata.append('repo_id', this.repositoryid);
-            formdata.append('itemid', this.itemid);
-            if (this.author) {
-                formdata.append('author', this.author);
+            formdata.append('itemid', this.options.itemid);
+            if (this.options.author) {
+                formdata.append('author', this.options.author);
+            }
+            if (this.options.filemanager) { // Filepickers do not have folders
+                formdata.append('savepath', this.options.filemanager.currentpath);
             }
-            if (this.filemanager) { // Filepickers do not have folders
-                formdata.append('savepath', this.filemanager.currentpath);
+            formdata.append('title', filename);
+            if (overwrite) {
+                formdata.append('overwrite', 1);
             }
 
-            if (this.acceptedtypes.constructor == Array) {
-                for (var i=0; i<this.acceptedtypes.length; i++) {
-                    formdata.append('accepted_types[]', this.acceptedtypes[i]);
+            // Accepted types can be either a string or an array, but an array is
+            // expected in the processing script, so make sure we are sending an array
+            if (this.options.acceptedtypes.constructor == Array) {
+                for (var i=0; i<this.options.acceptedtypes.length; i++) {
+                    formdata.append('accepted_types[]', this.options.acceptedtypes[i]);
                 }
             } else {
-                formdata.append('accepted_types[]', this.acceptedtypes);
+                formdata.append('accepted_types[]', this.options.acceptedtypes);
             }
 
             // Send the file & required details
-            xhr.open("POST", this.url, true);
+            xhr.open("POST", this.api, true);
             xhr.send(formdata);
             return true;
         }
-    };
+    });
 
     dnduploadhelper.init(Y, options);
 };
index e433d35..eafe284 100644 (file)
@@ -262,16 +262,12 @@ M.form_filemanager.init = function(Y, options) {
             var button_addfile  = this.filemanager.one('.fp-btn-add');
 
             // setup 'add file' button
-            // if maxfiles == -1, the no limit
-            button_addfile.on('click', function(e) {
-                e.preventDefault();
-                var options = this.filepicker_options;
-                options.formcallback = this.filepicker_callback;
-                // XXX: magic here, to let filepicker use filemanager scope
-                options.magicscope = this;
-                options.savepath = this.currentpath;
-                M.core_filepicker.show(Y, options);
-            }, this);
+            button_addfile.on('click', this.show_filepicker, this);
+
+            var dndarrow = this.filemanager.one('.dndupload-arrow');
+            if (dndarrow) {
+                dndarrow.on('click', this.show_filepicker, this);
+            }
 
             // setup 'make a folder' button
             if (this.options.subdirs) {
@@ -370,6 +366,18 @@ M.form_filemanager.init = function(Y, options) {
                     }
                 }, this);
         },
+
+        show_filepicker: function (e) {
+            // if maxfiles == -1, the no limit
+            e.preventDefault();
+            var options = this.filepicker_options;
+            options.formcallback = this.filepicker_callback;
+            // XXX: magic here, to let filepicker use filemanager scope
+            options.magicscope = this;
+            options.savepath = this.currentpath;
+            M.core_filepicker.show(Y, options);
+        },
+
         print_path: function() {
             var p = this.options.path;
             this.pathbar.setContent('').addClass('empty');
index c4fdd8f..8f95fe5 100644 (file)
@@ -500,8 +500,8 @@ class page_requirements_manager {
                 case 'core_dndupload':
                     $module = array('name'     => 'core_dndupload',
                                     'fullpath' => '/lib/form/dndupload.js',
-                                    'requires' => array('node', 'event', 'json'),
-                                    'strings'  => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'), array('dndenabled_inbox', 'moodle')));
+                                    'requires' => array('node', 'event', 'json', 'core_filepicker'),
+                                    'strings'  => array(array('uploadformlimit', 'moodle'), array('droptoupload', 'moodle'), array('maxfilesreached', 'moodle'), array('dndenabled_inbox', 'moodle'), array('fileexists', 'moodle')));
                     break;
             }
 
index 7b7c669..2e95777 100644 (file)
@@ -199,13 +199,9 @@ final class portfolio_admin_form extends moodleform {
 
         // let the plugin add the fields they want (either statically or not)
         if (portfolio_static_function($this->plugin, 'has_admin_config')) {
-            if (!$this->instance) {
-                require_once($CFG->libdir . '/portfolio/plugin.php');
-                require_once($CFG->dirroot . '/portfolio/' . $this->plugin .  '/lib.php');
-                call_user_func(array('portfolio_plugin_' . $this->plugin, 'admin_config_form'), $mform);
-            } else {
-                $this->instance->admin_config_form($mform);
-            }
+            require_once($CFG->libdir . '/portfolio/plugin.php');
+            require_once($CFG->dirroot . '/portfolio/' . $this->plugin .  '/lib.php');
+            call_user_func(array('portfolio_plugin_' . $this->plugin, 'admin_config_form'), $mform);
         }
 
         // and set the data if we have some.
@@ -237,12 +233,7 @@ final class portfolio_admin_form extends moodleform {
         }
 
         $pluginerrors = array();
-        if ($this->instance) {
-            $pluginerrors = $this->instance->admin_config_validation($data);
-        }
-        else {
-            $pluginerrors = portfolio_static_function($this->plugin, 'admin_config_validation', $data);
-        }
+        $pluginerrors = portfolio_static_function($this->plugin, 'admin_config_validation', $data);
         if (is_array($pluginerrors)) {
             $errors = array_merge($errors, $pluginerrors);
         }
index 6c32ffc..34c40c8 100644 (file)
@@ -347,7 +347,7 @@ abstract class portfolio_plugin_base {
      *
      * @param moodleform $mform passed by reference, add elements to it.
      */
-    public function admin_config_form(&$mform) {}
+    public static function admin_config_form(&$mform) {}
 
     /**
      * Just like the moodle form validation function,
@@ -356,7 +356,7 @@ abstract class portfolio_plugin_base {
      *
      * @param array $data data from form.
      */
-    public function admin_config_validation($data) {}
+    public static function admin_config_validation($data) {}
 
     /**
      * mform to display to the user exporting data using this plugin.
index 99c42ba..120f61e 100644 (file)
@@ -106,7 +106,7 @@ class portfolio_plugin_boxnet extends portfolio_plugin_push_base {
         }
     }
 
-    public function admin_config_form(&$mform) {
+    public static function admin_config_form(&$mform) {
         global $CFG;
 
         $mform->addElement('text', 'apikey', get_string('apikey', 'portfolio_boxnet'));
index fe63d9d..2815a0f 100644 (file)
@@ -96,7 +96,7 @@ class portfolio_plugin_flickr extends portfolio_plugin_push_base {
         return true;
     }
 
-    public function admin_config_form(&$mform) {
+    public static function admin_config_form(&$mform) {
         global $CFG;
 
         $strrequired = get_string('required');
index 02ce159..9695bc2 100644 (file)
@@ -100,7 +100,7 @@ class portfolio_plugin_googledocs extends portfolio_plugin_push_base {
         return array('clientid', 'secret');
     }
 
-    public function admin_config_form(&$mform) {
+    public static function admin_config_form(&$mform) {
         $a = new stdClass;
         $a->docsurl = get_docs_url('Google_OAuth2_Setup');
         $a->callbackurl = google_oauth::callback_url()->out(false);
index beb43b1..77c40d6 100644 (file)
@@ -84,7 +84,7 @@ class portfolio_plugin_mahara extends portfolio_plugin_pull_base {
         return true;
     }
 
-    public function admin_config_form(&$mform) {
+    public static function admin_config_form(&$mform) {
         $strrequired = get_string('required');
         $hosts = self::get_mnet_hosts(); // this is called by sanity check but it's ok because it's cached
         foreach ($hosts as $host) {
index 70200c1..cb72e85 100644 (file)
@@ -100,7 +100,7 @@ class portfolio_plugin_picasa extends portfolio_plugin_push_base {
         return array('clientid', 'secret');
     }
 
-    public function admin_config_form(&$mform) {
+    public static function admin_config_form(&$mform) {
         $a = new stdClass;
         $a->docsurl = get_docs_url('Google_OAuth2_Setup');
         $a->callbackurl = google_oauth::callback_url()->out(false);
diff --git a/portfolio/upgrade.txt b/portfolio/upgrade.txt
new file mode 100644 (file)
index 0000000..efc88ea
--- /dev/null
@@ -0,0 +1,9 @@
+This files describes API changes in /portfolio/ portfolio system,
+information provided here is intended especially for developers.
+
+=== 2.3 ===
+
+required changes:
+* The following methods must now be declared static for php5 compatibility:
+    - admin_config_form
+    - admin_config_validation
index cf023dd..d1a2512 100644 (file)
@@ -57,8 +57,9 @@ class repository_upload extends repository {
         $itemid   = optional_param('itemid', 0, PARAM_INT);
         $license  = optional_param('license', $CFG->sitedefaultlicense, PARAM_TEXT);
         $author   = optional_param('author', '', PARAM_TEXT);
+        $overwriteexisting = optional_param('overwrite', false, PARAM_BOOL);
 
-        return $this->process_upload($saveas_filename, $maxbytes, $types, $savepath, $itemid, $license, $author);
+        return $this->process_upload($saveas_filename, $maxbytes, $types, $savepath, $itemid, $license, $author, $overwriteexisting);
     }
 
     /**
@@ -70,9 +71,10 @@ class repository_upload extends repository {
      * @param int $itemid optional the ID for this item within the file area
      * @param string $license optional the license to use for this file
      * @param string $author optional the name of the author of this file
+     * @param bool $overwriteexisting optional user has asked to overwrite the existing file
      * @return object containing details of the file uploaded
      */
-    public function process_upload($saveas_filename, $maxbytes, $types = '*', $savepath = '/', $itemid = 0, $license = null, $author = '') {
+    public function process_upload($saveas_filename, $maxbytes, $types = '*', $savepath = '/', $itemid = 0, $license = null, $author = '', $overwriteexisting = false) {
         global $USER, $CFG;
 
         if ((is_array($types) and in_array('*', $types)) or $types == '*') {
@@ -191,32 +193,37 @@ class repository_upload extends repository {
         $record->userid    = $USER->id;
 
         if (repository::draftfile_exists($record->itemid, $record->filepath, $record->filename)) {
-            $existingfilename = $record->filename;
-            $unused_filename = repository::get_unused_filename($record->itemid, $record->filepath, $record->filename);
-            $record->filename = $unused_filename;
-            $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
-            $event = array();
-            $event['event'] = 'fileexists';
-            $event['newfile'] = new stdClass;
-            $event['newfile']->filepath = $record->filepath;
-            $event['newfile']->filename = $unused_filename;
-            $event['newfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $unused_filename)->out(false);
-
-            $event['existingfile'] = new stdClass;
-            $event['existingfile']->filepath = $record->filepath;
-            $event['existingfile']->filename = $existingfilename;
-            $event['existingfile']->url      = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $existingfilename)->out(false);
-            return $event;
-        } else {
-            $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
+            if ($overwriteexisting) {
+                repository::delete_tempfile_from_draft($record->itemid, $record->filepath, $record->filename);
+            } else {
+                $existingfilename = $record->filename;
+                $unused_filename = repository::get_unused_filename($record->itemid, $record->filepath, $record->filename);
+                $record->filename = $unused_filename;
+                $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
+                $event = array();
+                $event['event'] = 'fileexists';
+                $event['newfile'] = new stdClass;
+                $event['newfile']->filepath = $record->filepath;
+                $event['newfile']->filename = $unused_filename;
+                $event['newfile']->url = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $unused_filename)->out(false);
 
-            return array(
-                'url'=>moodle_url::make_draftfile_url($record->itemid, $record->filepath, $record->filename)->out(false),
-                'id'=>$record->itemid,
-                'file'=>$record->filename);
+                $event['existingfile'] = new stdClass;
+                $event['existingfile']->filepath = $record->filepath;
+                $event['existingfile']->filename = $existingfilename;
+                $event['existingfile']->url      = moodle_url::make_draftfile_url($record->itemid, $record->filepath, $existingfilename)->out(false);
+                return $event;
+            }
         }
+
+        $stored_file = $fs->create_file_from_pathname($record, $_FILES[$elname]['tmp_name']);
+
+        return array(
+            'url'=>moodle_url::make_draftfile_url($record->itemid, $record->filepath, $record->filename)->out(false),
+            'id'=>$record->itemid,
+            'file'=>$record->filename);
     }
 
+
     /**
      * Checks the contents of the given file is not completely NULL - this can happen if a
      * user drags & drops a folder onto a filemanager / filepicker element