Browse Source

Add new jquery upload see BT#10893

jmontoya 9 years ago
parent
commit
3d311507cd

+ 1 - 1
main/document/showinframes.php

@@ -86,7 +86,7 @@ if (is_dir($file_url_sys)) {
 
 $is_allowed_to_edit = api_is_allowed_to_edit();
 //fix the screen when you try to access a protected course through the url
-$is_allowed_in_course = $_SESSION['is_allowed_in_course'] || $is_allowed_to_edit;
+$is_allowed_in_course = api_is_allowed_in_course() || $is_allowed_to_edit;
 if ($is_allowed_in_course == false) {
     api_not_allowed(true);
 }

+ 143 - 62
main/document/upload.php

@@ -40,47 +40,6 @@ require_once api_get_path(LIBRARY_PATH).'specific_fields_manager.lib.php';
 
 // Adding extra javascript to the form
 $htmlHeadXtra[] = api_get_jquery_libraries_js(array('jquery-ui', 'jquery-upload'));
-$htmlHeadXtra[] = '<script>
-
-function check_unzip() {
-    if (document.upload.unzip.checked){
-        document.upload.if_exists[0].disabled=true;
-        document.upload.if_exists[1].checked=true;
-        document.upload.if_exists[2].disabled=true;
-    } else {
-        document.upload.if_exists[0].checked=true;
-        document.upload.if_exists[0].disabled=false;
-        document.upload.if_exists[2].disabled=false;
-    }
-}
-
-function setFocus(){
-    $("#title_file").focus();
-}
-</script>';
-
-$htmlHeadXtra[] = "
-<script>
-$(function () {
-    setFocus();
-    $('#file_upload').fileUploadUI({
-        uploadTable:   $('.files'),
-        downloadTable: $('.files'),
-        buildUploadRow: function (files, index) {
-            $('.files').show();
-            return $('<tr><td>' + files[index].name + '<\/td>' +
-                    '<td class=\"file_upload_progress\"><div><\/div><\/td>' +
-                    '<td class=\"file_upload_cancel\">' +
-                    '<button class=\"ui-state-default ui-corner-all\" title=\"".get_lang('Cancel')."\">' + '<span class=\"ui-icon ui-icon-cancel\">".get_lang('Cancel')."<\/span>' +'<\/button>'+
-                    '<\/td><\/tr>');
-        },
-        buildDownloadRow: function (file) {
-            return $('<tr><td>' + file.name + '<\/td> <td> ' + file.size + ' <\/td>  <td>&nbsp;' + file.result + ' <\/td> <\/tr>');
-        }
-    });
-});
-
-</script>";
 
 // Variables
 
@@ -122,6 +81,131 @@ if (empty($document_data)) {
 }
 $group_properties = array();
 
+$url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file&curdirpath='.$path;
+
+$htmlHeadXtra[] = '<script>
+
+function check_unzip() {
+    if (document.upload.unzip.checked){
+        document.upload.if_exists[0].disabled=true;
+        document.upload.if_exists[1].checked=true;
+        document.upload.if_exists[2].disabled=true;
+    } else {
+        document.upload.if_exists[0].checked=true;
+        document.upload.if_exists[0].disabled=false;
+        document.upload.if_exists[2].disabled=false;
+    }
+}
+
+function setFocus(){
+    $("#title_file").focus();
+}
+</script>';
+
+$htmlHeadXtra[] = "
+<script>
+$(function () {
+    'use strict';
+    var url = '".$url."';
+    var uploadButton = $('<button/>')
+        .addClass('btn btn-primary')
+        .prop('disabled', true)
+        .text('".get_lang('Loading')."')
+        .on('click', function () {
+            var \$this = $(this),
+            data = \$this.data();
+
+            \$this
+                .off('click')
+                .text('".get_lang('Cancel')."')
+                .on('click', function () {
+                    \$this.remove();
+                    data.abort();
+                });
+            data.submit().always(function () {
+                \$this.remove();
+            });
+        });
+
+    $('#file_upload').fileupload({
+        url: url,
+        dataType: 'json',
+        autoUpload: false,
+        // Enable image resizing, except for Android and Opera,
+        // which actually support image resizing, but fail to
+        // send Blob objects via XHR requests:
+        disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
+        previewMaxWidth: 100,
+        previewMaxHeight: 100,
+        previewCrop: true
+     }).on('fileuploadadd', function (e, data) {
+        data.context = $('<div/>').appendTo('#files');
+
+        $.each(data.files, function (index, file) {
+            var node = $('<p/>').append($('<span/>').text(file.name));
+            if (!index) {
+                node
+                    .append('<br>')
+                    .append(uploadButton.clone(true).data(data));
+            }
+            node.appendTo(data.context);
+        });
+    }).on('fileuploadprocessalways', function (e, data) {
+        var index = data.index,
+            file = data.files[index],
+            node = $(data.context.children()[index]);
+        if (file.preview) {
+            node
+                .prepend('<br>')
+                .prepend(file.preview);
+        }
+        if (file.error) {
+            node
+                .append('<br>')
+                .append($('<span class=\"text-danger\"/>').text(file.error));
+        }
+        if (index + 1 === data.files.length) {
+            data.context.find('button')
+                .text('Upload')
+                .prop('disabled', !!data.files.error);
+        }
+    }).on('fileuploadprogressall', function (e, data) {
+        var progress = parseInt(data.loaded / data.total * 100, 10);
+        $('#progress .progress-bar').css(
+            'width',
+            progress + '%'
+        );
+    }).on('fileuploaddone', function (e, data) {
+
+        $.each(data.result.files, function (index, file) {
+            if (file.url) {
+                var link = $('<a>')
+                    .attr('target', '_blank')
+                    .prop('href', file.url);
+
+                $(data.context.children()[index]).wrap(link);
+            } else if (file.error) {
+                var error = $('<span class=\"text-danger\"/>').text(file.error);
+                $(data.context.children()[index])
+                    .append('<br>')
+                    .append(error);
+            }
+        });
+    }).on('fileuploadfail', function (e, data) {
+        $.each(data.files, function (index) {
+            var error = $('<span class=\"text-danger\"/>').text('File upload failed.');
+            $(data.context.children()[index])
+                .append('<br>')
+                .append(error);
+        });
+    }).prop('disabled', !$.support.fileInput)
+        .parent().addClass($.support.fileInput ? undefined : 'disabled');
+
+});
+
+</script>";
+
+
 // This needs cleaning!
 if (!empty($groupId)) {
     // If the group id is set, check if the user has the right to be here
@@ -174,7 +258,7 @@ if (isset($_REQUEST['certificate'])) {
 // Breadcrumbs
 if ($is_certificate_mode) {
     $interbreadcrumb[] = array(
-        'url' => '../gradebook/'.$_SESSION['gradebook_dest'],
+        'url' => '../gradebook/index.php?'.api_get_cidreq(),
         'name' => get_lang('Gradebook'),
     );
 } else {
@@ -225,10 +309,10 @@ if (!empty($_FILES)) {
 // Link back to the documents overview
 if ($is_certificate_mode) {
     $actions = '<a href="document.php?id='.$document_id.'&selectcat=' . $selectcat.'&'.api_get_cidreq().'">'.
-            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('CertificateOverview'),'',ICON_SIZE_MEDIUM).'</a>';
+        Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('CertificateOverview'),'',ICON_SIZE_MEDIUM).'</a>';
 } else {
     $actions = '<a href="document.php?id='.$document_id.'&'.api_get_cidreq().'">'.
-            Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('DocumentsOverview'),'',ICON_SIZE_MEDIUM).'</a>';
+        Display::return_icon('back.png',get_lang('BackTo').' '.get_lang('DocumentsOverview'),'',ICON_SIZE_MEDIUM).'</a>';
 }
 
 // Link to create a folder
@@ -317,26 +401,23 @@ $form->setDefaults($defaults);
 
 $simple_form = $form->returnForm();
 
-$url = api_get_path(WEB_AJAX_PATH).'document.ajax.php?'.api_get_cidreq().'&a=upload_file';
 $multiple_form = '<div class="description-upload">'.get_lang('ClickToSelectOrDragAndDropMultipleFilesOnTheUploadField').'</div>';
 $multiple_form .=  '
-    <div class="form-ajax">
-    <form id="file_upload" action="'.$url.'" method="POST" enctype="multipart/form-data">
-        <input type="hidden" name="curdirpath" value="'.$path.'" />
-        <input type="file" name="file" multiple>
-        <button type="submit">Upload</button>
-        <div class="button-load">
-        '.get_lang('UploadFiles').'
-        </div>
-    </form>
-    </div>
-    <table style="display:none; width:50%" class="files data_table">
-        <tr>
-            <th>'.get_lang('FileName').'</th>
-            <th>'.get_lang('Size').'</th>
-            <th>'.get_lang('Status').'</th>
-        </tr>
-    </table>';
+<span class="btn btn-success fileinput-button">
+    <i class="glyphicon glyphicon-plus"></i>
+    <span>'.get_lang('AddFiles').'</span>
+    <!-- The file input field used as target for the file upload widget -->
+    <input id="file_upload" type="file" name="files[]" multiple>
+</span>
+
+<br />
+<br />
+<!-- The global progress bar -->
+<div id="progress" class="progress">
+    <div class="progress-bar progress-bar-success"></div>
+</div>
+<div id="files" class="files"></div>
+';
 
 $nav_info = api_get_navigator();
 if ($nav_info ['name'] == 'Internet Explorer') {

+ 67 - 68
main/forum/forumfunction.inc.php

@@ -48,8 +48,7 @@ function setFocus() {
 }
 </script>';
 // The next javascript script is to manage ajax upload file
-$htmlHeadXtra[] = "
-<script>
+$htmlHeadXtra[] = "<script>
 $(function () {
     setFocus();
     $('#file_upload').fileUploadUI({
@@ -998,8 +997,8 @@ function return_visible_invisible_icon($content, $id, $current_visibility_status
                 $html .= $key . '=' . $value . '&';
             }
         }
-       $html.='action=invisible&content='.$content.'&id='.$id.'">'.
-           Display::return_icon('visible.png', get_lang('MakeInvisible'), array(), ICON_SIZE_SMALL).'</a>';
+        $html.='action=invisible&content='.$content.'&id='.$id.'">'.
+            Display::return_icon('visible.png', get_lang('MakeInvisible'), array(), ICON_SIZE_SMALL).'</a>';
     }
     if ($current_visibility_status == '0') {
         $html .= '<a href="' . api_get_self() . '?' . api_get_cidreq() . '&';
@@ -1008,8 +1007,8 @@ function return_visible_invisible_icon($content, $id, $current_visibility_status
                 $html .= $key . '=' . $value . '&';
             }
         }
-       $html .= 'action=visible&content=' . $content . '&id=' . $id . '">' .
-           Display::return_icon('invisible.png', get_lang('MakeVisible'), array(), ICON_SIZE_SMALL) . '</a>';
+        $html .= 'action=visible&content=' . $content . '&id=' . $id . '">' .
+            Display::return_icon('invisible.png', get_lang('MakeVisible'), array(), ICON_SIZE_SMALL) . '</a>';
     }
     return $html;
 }
@@ -1843,9 +1842,9 @@ function getThreadInfo($threadId, $cId)
 {
     $em = Database::getManager();
     $forumThread = $em->getRepository('ChamiloCourseBundle:CForumThread')->findOneBy(['threadId' => $threadId, 'cId' => $cId]);
-    
+
     $thread = [];
-    
+
     if ($forumThread) {
         $thread['threadId'] = $forumThread->getThreadId();
         $thread['threadTitle'] = $forumThread->getThreadTitle();
@@ -2298,62 +2297,62 @@ function updateThread($values)
 {
     $threadTable = Database :: get_course_table(TABLE_FORUM_THREAD);
     $courseId = api_get_course_int_id();
-        
+
     $params = [
-            'thread_title' => $values['thread_title'],
-            'thread_sticky' => isset($values['thread_sticky']) ? $values['thread_sticky'] : null,
-            'thread_title_qualify' => $values['calification_notebook_title'],
-            'thread_qualify_max' => $values['numeric_calification'],
-            'thread_weight' => $values['weight_calification'],
-            'thread_peer_qualify' => $values['thread_peer_qualify'],
-        ];
-        $where = ['c_id = ? AND thread_id = ?' => [$courseId, $values['thread_id']]];
-        Database::update($threadTable, $params, $where);
-        
-        if (api_is_course_admin() == true) {
-            $option_chek = isset($values['thread_qualify_gradebook']) ? $values['thread_qualify_gradebook'] : false; // values 1 or 0
-            if ($option_chek) {
-                $id = $values['thread_id'];
-                $titleGradebook = Security::remove_XSS(stripslashes($values['calification_notebook_title']));
-                $valueCalification = isset($values['numeric_calification']) ? intval($values['numeric_calification']) : 0;
-                $weightCalification = isset($values['weight_calification']) ? floatval($values['weight_calification']) : 0;
-                $description = '';
-                $sessionId = api_get_session_id();
-                $courseId = api_get_course_id();
-
-                $linkInfo = GradebookUtils::is_resource_in_course_gradebook(
+        'thread_title' => $values['thread_title'],
+        'thread_sticky' => isset($values['thread_sticky']) ? $values['thread_sticky'] : null,
+        'thread_title_qualify' => $values['calification_notebook_title'],
+        'thread_qualify_max' => $values['numeric_calification'],
+        'thread_weight' => $values['weight_calification'],
+        'thread_peer_qualify' => $values['thread_peer_qualify'],
+    ];
+    $where = ['c_id = ? AND thread_id = ?' => [$courseId, $values['thread_id']]];
+    Database::update($threadTable, $params, $where);
+
+    if (api_is_course_admin() == true) {
+        $option_chek = isset($values['thread_qualify_gradebook']) ? $values['thread_qualify_gradebook'] : false; // values 1 or 0
+        if ($option_chek) {
+            $id = $values['thread_id'];
+            $titleGradebook = Security::remove_XSS(stripslashes($values['calification_notebook_title']));
+            $valueCalification = isset($values['numeric_calification']) ? intval($values['numeric_calification']) : 0;
+            $weightCalification = isset($values['weight_calification']) ? floatval($values['weight_calification']) : 0;
+            $description = '';
+            $sessionId = api_get_session_id();
+            $courseId = api_get_course_id();
+
+            $linkInfo = GradebookUtils::is_resource_in_course_gradebook(
+                $courseId,
+                LINK_FORUM_THREAD,
+                $id,
+                $sessionId
+            );
+            $linkId = $linkInfo['id'];
+
+            if (!$linkInfo) {
+                GradebookUtils::add_resource_to_course_gradebook(
+                    $values['category_id'],
                     $courseId,
                     LINK_FORUM_THREAD,
                     $id,
+                    $titleGradebook,
+                    $weightCalification,
+                    $valueCalification,
+                    $description,
+                    1,
                     $sessionId
                 );
-                $linkId = $linkInfo['id'];
-
-                if (!$linkInfo) {
-                    GradebookUtils::add_resource_to_course_gradebook(
-                        $values['category_id'],
-                        $courseId,
-                        LINK_FORUM_THREAD,
-                        $id,
-                        $titleGradebook,
-                        $weightCalification,
-                        $valueCalification,
-                        $description,
-                        1,
-                        $sessionId
-                    );
-                } else {
-                    $em = Database::getManager();
-                    $gradebookLink = $em->getRepository('ChamiloCoreBundle:GradebookLink')->find($linkId);
-                    $gradebookLink->setWeight($weightCalification);
-                    $em->persist($gradebookLink);
-                    $em->flush();
-                }
+            } else {
+                $em = Database::getManager();
+                $gradebookLink = $em->getRepository('ChamiloCoreBundle:GradebookLink')->find($linkId);
+                $gradebookLink->setWeight($weightCalification);
+                $em->persist($gradebookLink);
+                $em->flush();
             }
         }
-        
-        $message = get_lang('EditPostStored').'<br />';
-        Display :: display_confirmation_message($message, false);
+    }
+
+    $message = get_lang('EditPostStored').'<br />';
+    Display :: display_confirmation_message($message, false);
 }
 
 /**
@@ -2608,7 +2607,7 @@ function store_thread($current_forum, $values, $courseInfo = array(), $showMessa
 function showUpdateThreadForm($currentForum, $forumSetting, $formValues = '')
 {
     $userInfo = api_get_user_info();
-    
+
     $myThread = isset($_GET['thread']) ? intval($_GET['thread']) : '';
     $myForum = isset($_GET['forum']) ? intval($_GET['forum']) : '';
     $myGradebook = isset($_GET['gradebook']) ? Security::remove_XSS($_GET['gradebook']) : '';
@@ -2621,7 +2620,7 @@ function showUpdateThreadForm($currentForum, $forumSetting, $formValues = '')
             'thread' => $myThread,
         ]) . '&' . api_get_cidreq()
     );
-    
+
     $form->addElement('header', get_lang('EditThread'));
     $form->setConstants(array('forum' => '5'));
     $form->addElement('hidden', 'forum_id', $myForum);
@@ -2647,7 +2646,7 @@ function showUpdateThreadForm($currentForum, $forumSetting, $formValues = '')
         } else {
             $form->addElement('hidden', 'thread_qualify_gradebook', false);
         }
-        
+
         $form->addElement('html', '<div id="options_field" style="display:none">');
         $form->addElement('text', 'numeric_calification', get_lang('QualificationNumeric'));
         $form->applyFilter('numeric_calification', 'html_filter');
@@ -2680,9 +2679,9 @@ function showUpdateThreadForm($currentForum, $forumSetting, $formValues = '')
     if ($forumSetting['allow_sticky'] && api_is_allowed_to_edit(null, true)) {
         $form->addElement('checkbox', 'thread_sticky', '', get_lang('StickyPost'));
     }
-    
+
     $form->addElement('html', '</div>');
-    
+
     if (!empty($formValues)) {
         $defaults['thread_qualify_gradebook'] = ($formValues['threadQualifyMax'] > 0 && empty($_POST)) ? 1 : 0 ;
         $defaults['thread_title'] = prepare4display($formValues['threadTitle']);
@@ -2699,9 +2698,9 @@ function showUpdateThreadForm($currentForum, $forumSetting, $formValues = '')
         $defaults['thread_peer_qualify'] = 0;
     }
     $form->setDefaults(isset($defaults) ? $defaults : null);
-    
+
     $form->addButtonUpdate(get_lang('ModifyThread'), 'SubmitPost');
-    
+
     if ($form->validate()) {
         $check = Security::check_token('post');
         if ($check) {
@@ -2724,8 +2723,8 @@ function showUpdateThreadForm($currentForum, $forumSetting, $formValues = '')
         $token = Security::get_token();
         $form->addElement('hidden', 'sec_token');
         $form->setConstants(array('sec_token' => $token));
-        
-        
+
+
         $form->display();
     }
 }
@@ -3639,7 +3638,7 @@ function store_edit_post($values)
             $values['id_attach']
         );
     }
-    
+
     // Storing the attachments if any.
     //update_added_resources('forum_post', $values['post_id']);
 
@@ -3688,9 +3687,9 @@ function display_user_link($user_id, $name, $origin = '', $in_title = '')
 function display_user_image($user_id, $name, $origin = '')
 {
     $userInfo = api_get_user_info($user_id);
-    
+
     $link = '<a href="'.(!empty($origin) ? '#' : $userInfo['profile_url']).'" '.(!empty($origin) ? 'target="_self"' : '').'>';
-    
+
     if ($user_id != 0) {
         return $link.'<img src="'.$userInfo['avatar'].'"  alt="'.$name.'"  title="'.$name.'" /></a>';
     } else {

+ 57 - 25
main/inc/ajax/document.ajax.php

@@ -1,5 +1,6 @@
 <?php
 /* For licensing terms, see /license.txt */
+
 /**
  * Responses to AJAX calls for the document upload
  */
@@ -18,7 +19,11 @@ switch ($action) {
             } else {
                 exit;
             }
-        } elseif ($is_allowed_to_edit || DocumentManager::is_my_shared_folder(api_get_user_id(), $_POST['curdirpath'], api_get_session_id())) {
+        } elseif (
+            $is_allowed_to_edit ||
+            DocumentManager::is_my_shared_folder(api_get_user_id(), $_POST['curdirpath'], api_get_session_id())
+        ) {
+            // ??
         } else {
             // No course admin and no group member...
             exit;
@@ -33,34 +38,61 @@ switch ($action) {
         //$ifExists = isset($_POST['if_exists']) ? $_POST['if_exists'] : $defaultFileExistsOption;
 
         if (!empty($_FILES)) {
-            $file = $_FILES['file'];
-            $result = DocumentManager::upload_document(
-                $_FILES,
-                $_POST['curdirpath'],
-                $file['name'],
-                '', // comment
-                0,
-                $defaultFileExistsOption,
-                false,
-                false
-            );
+            $files = $_FILES['files'];
+            $fileList = [];
+            foreach ($files as $name => $array) {
+                $counter = 0;
+                foreach ($array as $data) {
+                    $fileList[$counter][$name] = $data;
+                    $counter++;
+                }
+            }
 
-            $json = array();
-            $json['name'] = Display::url(
-                api_htmlentities($result['title']),
-                api_htmlentities($result['url']),
-                array('target'=>'_blank')
-            );
+            $resultList = [];
+            foreach ($fileList as $file) {
+                $globalFile = [];
+                $globalFile['files'] = $file;
+                $result = DocumentManager::upload_document(
+                    $globalFile,
+                    $_REQUEST['curdirpath'],
+                    $file['name'],
+                    '', // comment
+                    0,
+                    $defaultFileExistsOption,
+                    false,
+                    false,
+                    'files'
+                );
 
-            $json['type'] = api_htmlentities($file['type']);
-            $json['size'] = format_file_size($file['size']);
-            if (!empty($result) && is_array($result)) {
-                $json['result'] = Display::return_icon('accept.png', get_lang('Uploaded'));
-            } else {
-                $json['result'] = Display::return_icon('exclamation.png', get_lang('Error'));
+                $json = array();
+                $json['name'] = Display::url(
+                    api_htmlentities($result['title']),
+                    api_htmlentities($result['url']),
+                    array('target'=>'_blank')
+                );
+
+                $json['url'] = $result['url'];
+
+                $json['size'] = format_file_size($file['size']);
+                $json['type'] = api_htmlentities($file['type']);
+
+                if (!empty($result) && is_array($result)) {
+                    $json['result'] = Display::return_icon(
+                        'accept.png',
+                        get_lang('Uploaded')
+                    );
+                } else {
+                    $json['result'] = Display::return_icon(
+                        'exclamation.png',
+                        get_lang('Error')
+                    );
+                }
+                $resultList[] = $json;
             }
-            echo json_encode($json);
+
+            echo json_encode(['files' => $resultList]);
         }
+        exit;
         break;
     case 'document_preview':
         $course_info = api_get_course_info_by_id($_REQUEST['course_id']);

+ 13 - 3
main/inc/lib/api.lib.php

@@ -6518,9 +6518,19 @@ function api_get_jquery_libraries_js($libraries) {
 
     //Document multiple upload funcionality
     if (in_array('jquery-upload', $libraries)) {
-        $js .= api_get_js('jquery-upload/jquery.fileupload.js');
-        $js .= api_get_js('jquery-upload/jquery.fileupload-ui.js');
-        $js .= api_get_css($js_path.'jquery-upload/jquery.fileupload-ui.css');
+
+        $js .= api_get_asset('blueimp-load-image/js/load-image.all.min.js');
+        $js .= api_get_asset('blueimp-canvas-to-blob/js/canvas-to-blob.min.js');
+        $js .= api_get_asset('jquery-file-upload/js/jquery.iframe-transport.js');
+        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload.js');
+        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-process.js');
+        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-image.js');
+        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-audio.js');
+        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-video.js');
+        $js .= api_get_asset('jquery-file-upload/js/jquery.fileupload-validate.js');
+
+        $js .= api_get_css(api_get_path(WEB_PATH).'web/assets/jquery-file-upload/css/jquery.fileupload.css');
+        $js .= api_get_css(api_get_path(WEB_PATH).'web/assets/jquery-file-upload/css/jquery.fileupload-ui.css');
     }
 
     // jquery datepicker