コード例 #1
0
ファイル: document_quota.php プロジェクト: KRCM13/chamilo-lms
    foreach ($document_list as $document_data) {
        if ($document_data['insert_user_id'] == api_get_user_id() && $document_data['filetype'] == 'file') {
            $quota_bytes += $document_data['size'];
        }
    }
    if ($quota_bytes != 0) {
        $quota_percentage = round($quota_bytes / $total_quota_bytes, 2) * 100;
    }
    $session[] = array(addslashes(get_lang('Teacher') . ': ' . $user_name) . ' (' . format_file_size($quota_bytes) . ')', $quota_percentage);
    //if a sesson is active
    if ($session_id != 0) {
        if (!empty($course_list)) {
            $total_courses_quota = 0;
            $total_quota_bytes = 0;
            foreach ($course_list as $course_data) {
                $total_quota_bytes += DocumentManager::get_course_quota($course_data['id']);
            }
            if ($quota_bytes != 0) {
                $quota_percentage = round($quota_bytes / $total_quota_bytes, 2) * 100;
            }
        }
        $session[] = array(addslashes(sprintf(get_lang('TeacherXInSession'), $user_name)), $quota_percentage);
    }
}
$quota_percentage = round(($total_quota_bytes - $used_quota_bytes) / $total_quota_bytes, 2) * 100;
$session[] = array(addslashes(get_lang('ShowCourseQuotaUse')) . ' (' . format_file_size($total_quota_bytes - $used_quota_bytes) . ') ', $quota_percentage);
$quota_data = json_encode($session);
$htmlHeadXtra[] = "\n<script>\n\$(document).ready(function(){\n  var data = " . $quota_data . ";\n  var plot1 = jQuery.jqplot ('chart1', [data], {\n      seriesDefaults: {\n        // Make this a pie chart\n        renderer: jQuery.jqplot.PieRenderer,\n        rendererOptions: {\n          // Put data labels on the pie slices.\n          // By default, labels show the percentage of the slice.\n          showDataLabels: true\n        }\n      },\n      legend: { show:true, location: 'e' }\n    }\n  );\n});\n</script>";
$tpl = new Template($tool_name);
$content = Display::page_subheader(get_lang('ShowCourseQuotaUse')) . '<div id="chart1"></div>';
$tpl->assign('content', $content);
コード例 #2
0
ファイル: document.php プロジェクト: omaoibrahim/chamilo-lms
if (!empty($groupId)) {
    Display::display_introduction_section(TOOL_DOCUMENT . $groupId);
} else {
    Display::display_introduction_section(TOOL_DOCUMENT);
}
$toolbar = Display::toolbarAction('toolbar-document', array(0 => $actionsLeft, 1 => $actionsRight));
echo $toolbar;
echo $templateForm;
echo $moveForm;
echo $dirForm;
echo $selector;
$table->display();
if (count($documentAndFolders) > 1) {
    if ($is_allowed_to_edit || $group_member_with_upload_rights) {
        // Getting the course quota
        $course_quota = DocumentManager::get_course_quota();
        // Calculating the total space
        $already_consumed_space_course = DocumentManager::documents_total_space(api_get_course_int_id());
        // Displaying the quota
        DocumentManager::display_simple_quota($course_quota, $already_consumed_space_course);
    }
}
if (!empty($table_footer)) {
    Display::display_warning_message($table_footer);
}
echo '
    <div id="convertModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header" style="text-align: center;">
                <button type="button" class="close" data-dismiss="modal" aria-label="' . get_lang('Close') . '">
コード例 #3
0
$form->addGroup($group, '', get_lang('Unsubscription'), '<br />');
$form->addElement('text', 'disk_quota', array(get_lang('CourseQuota'), null, get_lang('MB')));
$form->addRule('disk_quota', get_lang('ThisFieldIsRequired'), 'required');
$form->addRule('disk_quota', get_lang('ThisFieldShouldBeNumeric'), 'numeric');
//Extra fields
$extra_field = new ExtraField('course');
$extra = $extra_field->addElements($form, $courseId);
$htmlHeadXtra[] = '
<script>
$(function() {
    ' . $extra['jquery_ready_content'] . '
});
</script>';
$form->addButtonUpdate(get_lang('ModifyCourseInfo'));
// Set some default values
$courseInfo['disk_quota'] = round(DocumentManager::get_course_quota($courseInfo['code']) / 1024 / 1024, 1);
$courseInfo['real_code'] = $courseInfo['code'];
$courseInfo['add_teachers_to_sessions_courses'] = isset($courseInfo['add_teachers_to_sessions_courses']) ? $courseInfo['add_teachers_to_sessions_courses'] : 0;
$form->setDefaults($courseInfo);
// Validate form
if ($form->validate()) {
    $course = $form->getSubmitValues();
    $visibility = $course['visibility'];
    $visual_code = $course['visual_code'];
    $visual_code = CourseManager::generate_course_code($visual_code);
    // Check if the visual code is already used by *another* course
    $visual_code_is_used = false;
    $warn = get_lang('TheFollowingCoursesAlreadyUseThisVisualCode');
    if (!empty($visual_code)) {
        $list = CourseManager::get_courses_info_from_visual_code($visual_code);
        foreach ($list as $course_temp) {
コード例 #4
0
ファイル: index.php プロジェクト: ragebat/chamilo-lms
//require_once '../inc/global.inc.php';
$htmlHeadXtra[] = "<script type=\"text/javascript\">\n<!-- //\nfunction check_unzip() {\n\tif(document.upload.unzip.checked){\n\tdocument.upload.if_exists[0].disabled=true;\n\tdocument.upload.if_exists[1].checked=true;\n\tdocument.upload.if_exists[2].disabled=true;\n\t}\n\telse {\n\tdocument.upload.if_exists[0].checked=true;\n\tdocument.upload.if_exists[0].disabled=false;\n\tdocument.upload.if_exists[2].disabled=false;\n\t}\n}\n// -->\n</script>";
//$is_allowed_to_edit = api_is_allowed_to_edit();
$is_allowed_to_edit = api_is_allowed_to_edit(null, true);
if (!$is_allowed_to_edit) {
    api_not_allowed(true);
}
/*
	Variables
	- some need defining before inclusion of libraries
*/
$courseDir = $_course['path'] . "/document";
$sys_course_path = api_get_path(SYS_COURSE_PATH);
$base_work_dir = $sys_course_path . $courseDir;
$noPHP_SELF = true;
$max_filled_space = DocumentManager::get_course_quota();
//what's the current path?
if (isset($_REQUEST['curdirpath'])) {
    $path = $_REQUEST['curdirpath'];
} else {
    $path = '/';
}
// set calling tool
if (isset($_REQUEST['tool'])) {
    $my_tool = $_REQUEST['tool'];
    $_SESSION['my_tool'] = $_REQUEST['tool'];
} elseif (!empty($_SESSION['my_tool'])) {
    $my_tool = $_SESSION['my_tool'];
} else {
    $my_tool = 'document';
    $_SESSION['my_tool'] = $my_tool;
コード例 #5
0
ファイル: upload.php プロジェクト: jloguercio/chamilo-lms
    $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>';
} 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>';
}
// Link to create a folder
echo $toolbar = Display::toolbarAction('toolbar-upload', array(0 => $actions), 1);
// Form to select directory
$folders = DocumentManager::get_all_document_folders($_course, $groupId, $is_allowed_to_edit);
if (!$is_certificate_mode) {
    echo DocumentManager::build_directory_selector($folders, $document_id, isset($group_properties['directory']) ? $group_properties['directory'] : array());
}
$action = api_get_self() . '?' . api_get_cidreq() . '&id=' . $document_id;
$form = new FormValidator('upload', 'POST', $action . '#tabs-2', '', array('enctype' => 'multipart/form-data'));
$form->addElement('hidden', 'id', $document_id);
$form->addElement('hidden', 'curdirpath', $path);
$course_quota = format_file_size(DocumentManager::get_course_quota() - DocumentManager::documents_total_space());
$label = get_lang('MaxFileSize') . ': ' . ini_get('upload_max_filesize') . '<br/>' . get_lang('DocumentQuota') . ': ' . $course_quota;
$form->addElement('file', 'file', array(get_lang('File'), $label), 'style="width: 250px" id="user_upload"');
$form->addElement('text', 'title', get_lang('Title'), array('id' => 'title_file'));
$form->addElement('textarea', 'comment', get_lang('Comment'));
// Advanced parameters
$form->addButtonAdvancedSettings('advanced_params');
$form->addElement('html', '<div id="advanced_params_options" style="display:none">');
// Check box options
$form->addElement('checkbox', 'unzip', get_lang('Options'), get_lang('Uncompress'), 'onclick="javascript: check_unzip();" value="1"');
if (api_get_setting('search.search_enabled') == 'true') {
    //TODO: include language file
    $supported_formats = get_lang('SupportedFormatsForIndex') . ': HTML, PDF, TXT, PDF, Postscript, MS Word, RTF, MS Power Point';
    $form->addElement('checkbox', 'index_document', '', get_lang('SearchFeatureDoIndexDocument') . '<div style="font-size: 80%" >' . $supported_formats . '</div>');
    $form->addElement('html', '<br /><div class="sub-form">');
    $form->addElement('html', '<div class="label">' . get_lang('SearchFeatureDocumentLanguage') . '</div>');
コード例 #6
0
 function verify_document_size($s)
 {
     $post_max = ini_get('post_max_size');
     $upl_max = ini_get('upload_max_filesize');
     $documents_total_space = DocumentManager::documents_total_space();
     $course_max_space = DocumentManager::get_course_quota();
     $total_size = filesize($s) + $documents_total_space;
     if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
         return true;
     } else {
         return false;
     }
 }
コード例 #7
0
$filename = Database::escape_string($filename);
$filename = api_replace_dangerous_char($filename, $strict = 'loose');
// or strict
$filename = FileManager::disable_dangerous_file($filename);
$title = trim(str_replace('_chnano_.', '.', $filename));
//hide nanogong wav tag at title
$title = str_replace('_', ' ', $title);
//
$documentPath = $filepath . $filename;
if ($nano_user_id != api_get_user_id() || api_get_user_id() == 0 || $nano_user_id == 0) {
    echo 'Not allowed';
    exit;
}
//Do not use here check Fileinfo method because return: text/plain
// Check if there is enough space in the course to save the file
if (!DocumentManager::enough_space(filesize($_FILES['voicefile']['tmp_name']), DocumentManager::get_course_quota())) {
    die(get_lang('UplNotEnoughSpace'));
}
if (!file_exists($documentPath)) {
    //add document to disk
    move_uploaded_file($_FILES['voicefile']['tmp_name'], $documentPath);
    //add document to database
    $current_session_id = $nano_session_id;
    $groupId = $nano_group_id;
    $file_size = filesize($documentPath);
    $relativeUrlPath = $dir;
    $doc_id = FileManager::add_document($_course, $relativeUrlPath . $filename, 'file', filesize($documentPath), $title);
    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $nano_user_id, $groupId, null, null, null, $current_session_id);
} else {
    return get_lang('FileExistRename');
}
コード例 #8
0
ファイル: nanogong.lib.php プロジェクト: ragebat/chamilo-lms
 /**
  * Uploads the nanogong wav file
  * @param bool
  */
 public function upload_file($is_nano = false)
 {
     if (!empty($_FILES)) {
         $upload_ok = FileManager::process_uploaded_file($_FILES['file'], false);
         if (!is_uploaded_file($_FILES['file']['tmp_name'])) {
             return 0;
         }
         if ($upload_ok) {
             // Check if there is enough space to save the file
             if (!DocumentManager::enough_space($_FILES['file']['size'], DocumentManager::get_course_quota())) {
                 return 0;
             }
             //first we delete everything before uploading the file
             $this->delete_files();
             //Reload the filename variable
             $file_name = FileManager::add_ext_on_mime($_FILES['file']['name'], $_FILES['file']['type']);
             $file_name = strtolower($file_name);
             $file_info = pathinfo($file_name);
             if ($is_nano == true) {
                 $file_info['extension'] = 'wav';
             }
             $file_name = $this->filename . '.' . $file_info['extension'];
             if (in_array($file_info['extension'], $this->available_extensions)) {
                 if (move_uploaded_file($_FILES['file']['tmp_name'], $this->store_path . $file_name)) {
                     $this->store_filename = $this->store_path . $file_name;
                     return 1;
                 }
             }
         }
     }
     return 0;
 }
コード例 #9
0
$form->addRule('disk_quota', get_lang('ThisFieldShouldBeNumeric'), 'numeric');
$list_course_extra_field = CourseManager::get_course_extra_field_list($course_code);
//@todo this is wrong
foreach ($list_course_extra_field as $extra_field) {
    switch ($extra_field['field_type']) {
        case CourseManager::COURSE_FIELD_TYPE_CHECKBOX:
            $checked = array_key_exists('extra_field_value', $extra_field) && $extra_field['extra_field_value'] == 1 ? array('checked' => 'checked') : '';
            $form->addElement('hidden', '_extra_' . $extra_field['field_variable'], 0);
            $field_display_text = $extra_field['field_display_text'];
            $form->addElement('checkbox', 'extra_' . $extra_field['field_variable'], array(null, get_lang('AllUsersAreAutomaticallyRegistered')), get_lang('SpecialCourse'), $checked);
            break;
    }
}
$form->addElement('style_submit_button', 'button', get_lang('ModifyCourseInfo'), 'onclick="valide()"; class="save"');
// Set some default values
$course['disk_quota'] = round(DocumentManager::get_course_quota($course_code) / 1024 / 1024, 1);
$course['title'] = api_html_entity_decode($course['title'], ENT_QUOTES, $charset);
$course['real_code'] = $course['code'];
$course['add_teachers_to_sessions_courses'] = isset($course['add_teachers_to_sessions_courses']) ? $course['add_teachers_to_sessions_courses'] : 0;
$form->setDefaults($course);
// Validate form
if ($form->validate()) {
    $course = $form->getSubmitValues();
    $visibility = $course['visibility'];
    global $_configuration;
    $urlId = api_get_current_access_url_id();
    if (isset($_configuration[$urlId]) && isset($_configuration[$urlId]['hosting_limit_active_courses']) && $_configuration[$urlId]['hosting_limit_active_courses'] > 0) {
        // Check if
        if ($course_info['visibility'] == COURSE_VISIBILITY_HIDDEN && $visibility != $course_info['visibility']) {
            $num = CourseManager::countActiveCourses($urlId);
            if ($num >= $_configuration[$urlId]['hosting_limit_active_courses']) {
コード例 #10
0
 /**
  * This function does the save-work for the documents.
  * It handles the uploaded file and adds the properties to the database
  * If unzip=1 and the file is a zipfile, it is extracted
  * If we decide to save ALL kinds of documents in one database,
  * we could extend this with a $type='document', 'scormdocument',...
  *
  * @param array $_course
  * @param array $uploaded_file ($_FILES)
  * @param string $base_work_dir
  * @param string $upload_path
  * @param int $user_id
  * @param int $to_group_id, 0 for everybody
  * @param int $to_user_id, NULL for everybody
  * @param int $unzip 1/0
  * @param string $what_if_file_exists overwrite, rename or warn if exists (default)
  * @param boolean Optional output parameter. So far only use for unzip_uploaded_document function. If no output wanted on success, set to false.
  * @return path of the saved file
  */
 static function handle_uploaded_document($_course, $uploaded_file, $base_work_dir, $upload_path, $user_id, $to_group_id = 0, $to_user_id = null, $unzip = 0, $what_if_file_exists = '', $output = true)
 {
     if (!$user_id) {
         die('Not a valid user.');
     }
     // Strip slashes
     $uploaded_file['name'] = stripslashes($uploaded_file['name']);
     // Add extension to files without one (if possible)
     $uploaded_file['name'] = self::add_ext_on_mime($uploaded_file['name'], $uploaded_file['type']);
     $current_session_id = api_get_session_id();
     //Just in case process_uploaded_file is not called
     $max_filled_space = DocumentManager::get_course_quota();
     // Check if there is enough space to save the file
     if (!DocumentManager::enough_space($uploaded_file['size'], $max_filled_space)) {
         if ($output) {
             Display::display_error_message(get_lang('UplNotEnoughSpace'));
         }
         return false;
     }
     // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
     if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
         return self::unzip_uploaded_document($uploaded_file, $upload_path, $base_work_dir, $max_filled_space, $output, $to_group_id);
         //display_message('Unzipping file');
     } elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
         // We can only unzip ZIP files (no gz, tar,...)
         if ($output) {
             Display::display_error_message(get_lang('UplNotAZip') . " " . get_lang('PleaseTryAgain'));
         }
         return false;
     } else {
         // Clean up the name, only ASCII characters should stay. (and strict)
         $clean_name = api_replace_dangerous_char($uploaded_file['name'], 'strict');
         // No "dangerous" files
         $clean_name = self::disable_dangerous_file($clean_name);
         if (!self::filter_extension($clean_name)) {
             if ($output) {
                 Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
             }
             return false;
         } else {
             // Extension is good
             //echo '<br />clean name = '.$clean_name;
             //echo '<br />upload_path = '.$upload_path;
             // If the upload path differs from / (= root) it will need a slash at the end
             if ($upload_path != '/') {
                 $upload_path = $upload_path . '/';
             }
             //echo '<br />upload_path = '.$upload_path;
             $file_path = $upload_path . $clean_name;
             //echo '<br />file path = '.$file_path;
             // Full path to where we want to store the file with trailing slash
             $where_to_save = $base_work_dir . $upload_path;
             // At least if the directory doesn't exist, tell so
             if (!is_dir($where_to_save)) {
                 if ($output) {
                     Display::display_error_message(get_lang('DestDirectoryDoesntExist') . ' (' . $upload_path . ')');
                 }
                 return false;
             }
             //echo '<br />where to save = '.$where_to_save;
             // Full path of the destination
             $store_path = $where_to_save . $clean_name;
             //echo '<br />store path = '.$store_path;
             // Name of the document without the extension (for the title)
             $document_name = self::get_document_title($uploaded_file['name']);
             // Size of the uploaded file (in bytes)
             $file_size = $uploaded_file['size'];
             $files_perm = api_get_permissions_for_new_files();
             // What to do if the target file exists
             switch ($what_if_file_exists) {
                 // Overwrite the file if it exists
                 case 'overwrite':
                     // Check if the target file exists, so we can give another message
                     $file_exists = file_exists($store_path);
                     if (self::moveUploadedFile($uploaded_file, $store_path)) {
                         chmod($store_path, $files_perm);
                         if ($file_exists) {
                             // UPDATE DATABASE
                             $document_id = DocumentManager::get_document_id($_course, $file_path);
                             if (is_numeric($document_id)) {
                                 // Update filesize
                                 self::update_existing_document($_course, $document_id, $uploaded_file['size']);
                                 // Update document item_property
                                 api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentUpdated', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
                                 //Redo visibility
                                 api_set_default_visibility($_course, TOOL_DOCUMENT, $document_id);
                             }
                             // If the file is in a folder, we need to update all parent folders
                             self::item_property_update_on_folder($_course, $upload_path, $user_id);
                             // Display success message with extra info to user
                             if ($output) {
                                 Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . $file_path . ' ' . get_lang('UplFileOverwritten'), false);
                             }
                             return $file_path;
                         } else {
                             // Put the document data in the database
                             $document_id = self::add_document($_course, $file_path, 'file', $file_size, $document_name, null, 0, true);
                             if ($document_id) {
                                 // Put the document in item_property update
                                 api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
                             }
                             // If the file is in a folder, we need to update all parent folders
                             self::item_property_update_on_folder($_course, $upload_path, $user_id);
                             // Display success message to user
                             if ($output) {
                                 Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . $file_path, false);
                             }
                             return $file_path;
                         }
                     } else {
                         if ($output) {
                             Display::display_error_message(get_lang('UplUnableToSaveFile'));
                         }
                         return false;
                     }
                     break;
                     // Rename the file if it exists
                 // Rename the file if it exists
                 case 'rename':
                     $new_name = self::unique_name($where_to_save, $clean_name);
                     $store_path = $where_to_save . $new_name;
                     $new_file_path = $upload_path . $new_name;
                     if (self::moveUploadedFile($uploaded_file, $store_path)) {
                         chmod($store_path, $files_perm);
                         // Put the document data in the database
                         $document_id = self::add_document($_course, $new_file_path, 'file', $file_size, $document_name, null, 0, true);
                         if ($document_id) {
                             // Update document item_property
                             api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
                         }
                         // If the file is in a folder, we need to update all parent folders
                         self::item_property_update_on_folder($_course, $upload_path, $user_id);
                         // Display success message to user
                         if ($output) {
                             Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . get_lang('UplFileSavedAs') . $new_file_path, false);
                         }
                         return $new_file_path;
                     } else {
                         if ($output) {
                             Display::display_error_message(get_lang('UplUnableToSaveFile'));
                         }
                         return false;
                     }
                     break;
                     // Only save the file if it doesn't exist or warn user if it does exist
                 // Only save the file if it doesn't exist or warn user if it does exist
                 default:
                     if (file_exists($store_path)) {
                         if ($output) {
                             Display::display_error_message($clean_name . ' ' . get_lang('UplAlreadyExists'));
                         }
                     } else {
                         if (self::moveUploadedFile($uploaded_file, $store_path)) {
                             chmod($store_path, $files_perm);
                             // Put the document data in the database
                             $document_id = self::add_document($_course, $file_path, 'file', $file_size, $document_name, null, 0, true);
                             if ($document_id) {
                                 // Update document item_property
                                 api_item_property_update($_course, TOOL_DOCUMENT, $document_id, 'DocumentAdded', $user_id, $to_group_id, $to_user_id, null, null, $current_session_id);
                             }
                             // If the file is in a folder, we need to update all parent folders
                             self::item_property_update_on_folder($_course, $upload_path, $user_id);
                             // Display success message to user
                             if ($output) {
                                 Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . $file_path, false);
                             }
                             return $file_path;
                         } else {
                             if ($output) {
                                 Display::display_error_message(get_lang('UplUnableToSaveFile'));
                             }
                             return false;
                         }
                     }
                     break;
             }
         }
     }
 }
コード例 #11
0
$form->addElement('hidden', 'id', $workId);
$form->addButtonUpload(get_lang('Upload'));
$error_message = null;
$succeed = false;
if ($form->validate()) {
    $values = $form->getSubmitValues();
    $upload = process_uploaded_file($_FILES['file'], false);
    if ($upload) {
        $zip = new PclZip($_FILES['file']['tmp_name']);
        // Check the zip content (real size and file extension)
        $zipFileList = (array) $zip->listContent();
        $realSize = 0;
        foreach ($zipFileList as &$this_content) {
            $realSize += $this_content['size'];
        }
        $maxSpace = DocumentManager::get_course_quota();
        if (!DocumentManager::enough_space($realSize, $maxSpace)) {
            Display::addFlash(Display::return_message(get_lang('UplNotEnoughSpace'), 'warning'));
        }
        $folder = api_get_unique_id();
        $destinationDir = api_get_path(SYS_ARCHIVE_PATH) . $folder;
        mkdir($destinationDir, api_get_permissions_for_new_directories(), true);
        /*	Uncompress zip file*/
        // We extract using a callback function that "cleans" the path
        $zip->extract(PCLZIP_OPT_PATH, $destinationDir, PCLZIP_CB_PRE_EXTRACT, 'clean_up_files_in_zip', PCLZIP_OPT_REPLACE_NEWER);
        $result = get_work_user_list(null, null, null, null, $workId);
        if (empty($result)) {
            Display::addFlash(Display::return_message(get_lang('NoDataAvailable'), 'warning'));
        }
        $finalResult = [];
        foreach ($result as $item) {
コード例 #12
0
ファイル: create_audio.php プロジェクト: ragebat/chamilo-lms
/**
 * This function save a post into a file mp3 from pediaphon services
 *
 * @param $filepath
 * @param $dir
 * @author Juan Carlos Raña Trabado <*****@*****.**>
 * @version january 2011, chamilo 1.8.8
 */
function downloadMP3_pediaphon($filepath, $dir)
{
    $location = 'create_audio.php?' . api_get_cidreq() . '&id=' . Security::remove_XSS($_POST['document_id']) . '&dt2a=pediaphon';
    //security
    if (!isset($_POST['lang']) && !isset($_POST['text']) && !isset($_POST['title']) && !isset($filepath) && !isset($dir)) {
        echo '<script>window.location.href="' . $location . '"</script>';
        return;
    }
    global $_user;
    $_course = api_get_course_info();
    $clean_title = trim($_POST['title']);
    $clean_title = Database::escape_string($clean_title);
    $clean_text = trim($_POST['text']);
    $clean_voices = Security::remove_XSS($_POST['voices']);
    if (empty($clean_title) || empty($clean_text) || empty($clean_voices)) {
        echo '<script>window.location.href="' . $location . '"</script>';
        return;
    }
    $clean_title = Security::remove_XSS($clean_title);
    $clean_title = Database::escape_string($clean_title);
    $clean_title = str_replace(' ', '_', $clean_title);
    //compound file names
    $clean_text = Security::remove_XSS($clean_text);
    $clean_lang = Security::remove_XSS($_POST['lang']);
    $clean_speed = Security::remove_XSS($_POST['speed']);
    $extension = 'mp3';
    $audio_filename = $clean_title . '.' . $extension;
    $audio_title = str_replace('_', ' ', $clean_title);
    //prevent duplicates
    if (file_exists($filepath . '/' . $clean_title . '.' . $extension)) {
        $i = 1;
        while (file_exists($filepath . '/' . $clean_title . '_' . $i . '.' . $extension)) {
            $i++;
        }
        $audio_filename = $clean_title . '_' . $i . '.' . $extension;
        $audio_title = $clean_title . '_' . $i . '.' . $extension;
        $audio_title = str_replace('_', ' ', $audio_title);
    }
    $documentPath = $filepath . '/' . $audio_filename;
    //prev for a fine unicode, borrowed from main api TODO:clean
    // Safe replacements for some non-letter characters (whitout blank spaces)
    $search = array("", "\t", "\n", "\r", "\v", '/', "\\", '"', "'", '?', '*', '>', '<', '|', ':', '$', '(', ')', '^', '[', ']', '#', '+', '&', '%');
    $replace = array('', '_', '_', '_', '_', '-', '-', '-', '_', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-');
    $filename = $clean_text;
    // Encoding detection.
    $encoding = api_detect_encoding($filename);
    // Converting html-entities into encoded characters.
    $filename = api_html_entity_decode($filename, ENT_QUOTES, $encoding);
    // Transliteration to ASCII letters, they are not dangerous for filesystems.
    $filename = api_transliterate($filename, 'x', $encoding);
    // Replacing remaining dangerous non-letter characters.
    $clean_text = str_replace($search, $replace, $filename);
    //adding the file
    if ($clean_lang == 'de') {
        $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice.cgi';
        $find_t2v = '/http\\:\\/\\/www\\.pediaphon\\.org\\/\\~bischoff\\/radiopedia\\/mp3\\/(.*)\\.mp3\\"/';
    } else {
        $url_pediaphon = 'http://www.pediaphon.org/~bischoff/radiopedia/sprich_multivoice_' . $clean_lang . '.cgi';
        //en, es, fr
        $find_t2v = '/http\\:\\/\\/www\\.pediaphon\\.org\\/\\~bischoff\\/radiopedia\\/mp3\\/' . $clean_lang . '\\/(.*)\\.mp3\\"/';
    }
    $data = "stimme=" . $clean_voices . "&inputtext=" . $clean_text . "&speed=" . $clean_speed . "&go=go";
    $opts = array('http' => array('method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n", "Content-Length: " . strlen($data) . "\r\n", 'content' => $data));
    $context = stream_context_create($opts);
    $previous_returntext2voice = file_get_contents($url_pediaphon, false, $context);
    //clean file contents
    $search_source = preg_match($find_t2v, $previous_returntext2voice, $hits);
    $souce_end = substr($hits[0], 0, -1);
    $returntext2voice = file_get_contents($souce_end);
    //make a temporal file for get the file size
    $tmpfname = tempnam("/tmp", "CTF");
    $handle = fopen($tmpfname, "w");
    fwrite($handle, $returntext2voice);
    fclose($handle);
    // Check if there is enough space in the course to save the file
    if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
        unlink($tmpfname);
        die(get_lang('UplNotEnoughSpace'));
    }
    //erase temporal file
    unlink($tmpfname);
    //save file
    file_put_contents($documentPath, $returntext2voice);
    //add document to database
    $current_session_id = api_get_session_id();
    $groupId = $_SESSION['_gid'];
    $file_size = filesize($documentPath);
    $relativeUrlPath = $dir;
    $doc_id = FileManager::add_document($_course, $relativeUrlPath . $audio_filename, 'file', filesize($documentPath), $audio_title);
    api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
    Display::display_confirmation_message(get_lang('DocumentCreated'));
    //return to location
    echo '<script>window.location.href="' . $location . '"</script>';
}
コード例 #13
0
ファイル: infocours.php プロジェクト: daffef/chamilo-lms
if (api_get_setting('document.pdf_export_watermark_by_course') == 'true') {
    $url = PDF::get_watermark($course_code);
    $form->addText('pdf_export_watermark_text', get_lang('PDFExportWatermarkTextTitle'), false, array('size' => '60'));
    $form->addElement('file', 'pdf_export_watermark_path', get_lang('AddWaterMark'));
    if ($url != false) {
        $delete_url = '<a href="?delete_watermark">' . Display::return_icon('delete.png', get_lang('DelImage')) . '</a>';
        $form->addElement('html', '<div class="row"><div class="formw"><a href="' . $url . '">' . $url . ' ' . $delete_url . '</a></div></div>');
    }
    $form->addRule('pdf_export_watermark_path', get_lang('OnlyImagesAllowed') . ' (' . implode(',', $allowed_picture_types) . ')', 'filetype', $allowed_picture_types);
}
if (api_get_setting('course.allow_course_theme') == 'true') {
    $group = array();
    $group[] = $form->createElement('SelectTheme', 'course_theme', null, array('id' => 'course_theme_id'));
    $form->addGroup($group, '', array(get_lang("Stylesheets")), '');
}
$form->addElement('label', get_lang('DocumentQuota'), format_file_size(DocumentManager::get_course_quota()));
$form->addButtonSave(get_lang('SaveSettings'), 'submit_save');
$form->addElement('html', '</div></div>');
// COURSE ACCESS
$form->addElement('html', '<div> <h3>' . Display::return_icon('course.png', Security::remove_XSS(get_lang('CourseAccess')), '', ICON_SIZE_SMALL) . ' ' . Security::remove_XSS(get_lang('CourseAccess')) . '</h3><div>');
$group = array();
$group[] = $form->createElement('radio', 'visibility', get_lang("CourseAccess"), get_lang('OpenToTheWorld'), COURSE_VISIBILITY_OPEN_WORLD);
$group[] = $form->createElement('radio', 'visibility', null, get_lang('OpenToThePlatform'), COURSE_VISIBILITY_OPEN_PLATFORM);
$group[] = $form->createElement('radio', 'visibility', null, get_lang('Private'), COURSE_VISIBILITY_REGISTERED);
$group[] = $form->createElement('radio', 'visibility', null, get_lang('CourseVisibilityClosed'), COURSE_VISIBILITY_CLOSED);
// The "hidden" visibility is only available to portal admins
if (api_is_platform_admin()) {
    $group[] = $form->createElement('radio', 'visibility', null, get_lang('CourseVisibilityHidden'), COURSE_VISIBILITY_HIDDEN);
}
$form->addGroup($group, '', array(get_lang("CourseAccess"), get_lang("CourseAccessConfigTip")), '');
$url = api_get_path(WEB_CODE_PATH) . "auth/inscription.php?c={$course_code}&e=1";
コード例 #14
0
 public function verify_document_size($s)
 {
     $post_max = ini_get('post_max_size');
     if (substr($post_max, -1, 1) == 'M') {
         $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
     } elseif (substr($post_max, -1, 1) == 'G') {
         $post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
     }
     $upl_max = ini_get('upload_max_filesize');
     if (substr($upl_max, -1, 1) == 'M') {
         $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
     } elseif (substr($upl_max, -1, 1) == 'G') {
         $upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
     }
     $documents_total_space = DocumentManager::documents_total_space();
     $course_max_space = DocumentManager::get_course_quota();
     $total_size = filesize($s) + $documents_total_space;
     if (filesize($s) > $post_max || filesize($s) > $upl_max || $total_size > $course_max_space) {
         return true;
     } else {
         return false;
     }
 }
コード例 #15
0
    $title_to_save = str_replace('_', ' ', $title_to_save);
}
$documentPath = $saveDir . '/' . $webcamname_to_save;
//read content
$content = file_get_contents('php://input');
if (!$content) {
    print "ERROR: Failed to read data\n";
    exit;
}
//make a temporal file for get the file size
$tmpfname = tempnam("/tmp", "CTF");
$handle = fopen($tmpfname, "w");
fwrite($handle, $content);
fclose($handle);
// Check if there is enough space in the course to save the file
if (!DocumentManager::enough_space(filesize($tmpfname), DocumentManager::get_course_quota())) {
    unlink($tmpfname);
    die(get_lang('UplNotEnoughSpace'));
}
//erase temporal file
unlink($tmpfname);
//add to disk
$fh = fopen($documentPath, 'w') or die("can't open file");
fwrite($fh, $content);
fclose($fh);
//add document to database
$doc_id = FileManager::add_document($_course, $webcamdir . '/' . $webcamname_to_save, 'file', filesize($documentPath), $title_to_save);
api_item_property_update($_course, TOOL_DOCUMENT, $doc_id, 'DocumentAdded', $_user['user_id'], $groupId, null, null, null, $current_session_id);
///
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $documentPath;
print "{$url}\n";
コード例 #16
0
ファイル: work.lib.php プロジェクト: annickvdp/Chamilo1.9.10
/**
 * @param array $my_folder_data
 * @param array $_course
 * @return array
 */
function uploadWork($my_folder_data, $_course)
{
    if (empty($_FILES['file']['size'])) {
        return array('error' => Display :: return_message(get_lang('UplUploadFailedSizeIsZero'), 'error'));
    }
    $updir = api_get_path(SYS_COURSE_PATH).$_course['path'].'/work/'; //directory path to upload

    // Try to add an extension to the file if it has'nt one
    $filename = add_ext_on_mime(stripslashes($_FILES['file']['name']), $_FILES['file']['type']);

    // Replace dangerous characters
    $filename = replace_dangerous_char($filename, 'strict');

    // Transform any .php file in .phps fo security
    $filename = php2phps($filename);
    $filesize = filesize($_FILES['file']['tmp_name']);

    if (empty($filesize)) {
        return array('error' => Display :: return_message(get_lang('UplUploadFailedSizeIsZero'), 'error'));
    } elseif (!filter_extension($new_file_name)) {
        return array('error' => Display :: return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
    }

    $totalSpace = DocumentManager::documents_total_space($_course['real_id']);
    $course_max_space = DocumentManager::get_course_quota($_course['code']);
    $total_size = $filesize + $totalSpace;

    if ($total_size > $course_max_space) {
        return array(
            'error' => Display :: return_message(get_lang('NoSpace'), 'error')
        );
    }

    // Compose a unique file name to avoid any conflict
    $new_file_name = api_get_unique_id();
    $curdirpath = basename($my_folder_data['url']);

    // If we come from the group tools the groupid will be saved in $work_table
    if (is_dir($updir.$curdirpath) || empty($curdirpath)) {
        $result = move_uploaded_file(
            $_FILES['file']['tmp_name'],
            $updir.$curdirpath.'/'.$new_file_name
        );
    } else {
        return array(
            'error' => Display :: return_message(
                get_lang('FolderDoesntExistsInFileSystem'),
                'error'
            )
        );
    }

    $url = null;
    if ($result) {
        $url = 'work/'.$curdirpath.'/'.$new_file_name;
    }

    return array(
        'url' => $url,
        'filename' => $filename,
        'error' => null
    );
}
コード例 #17
0
 /**
  * Imports a zip file into the Chamilo structure
  * @param    string    Zip file info as given by $_FILES['userFile']
  * @return    string    Absolute path to the imsmanifest.xml file or empty string on error
  */
 function import_package($zip_file_info, $current_dir = '')
 {
     if ($this->debug > 0) {
         error_log('In scorm::import_package(' . print_r($zip_file_info, true) . ',"' . $current_dir . '") method', 0);
     }
     $maxFilledSpace = DocumentManager::get_course_quota();
     $zip_file_path = $zip_file_info['tmp_name'];
     $zip_file_name = $zip_file_info['name'];
     if ($this->debug > 1) {
         error_log('New LP - import_package() - zip file path = ' . $zip_file_path . ', zip file name = ' . $zip_file_name, 0);
     }
     // scorm dir web path starting from /courses
     $course_rel_dir = api_get_course_path() . '/scorm';
     $course_sys_dir = api_get_path(SYS_COURSE_PATH) . $course_rel_dir;
     // Absolute system path for this course.
     if (!is_dir($course_sys_dir)) {
         mkdir($course_sys_dir, api_get_permissions_for_new_directories());
     }
     $current_dir = api_replace_dangerous_char(trim($current_dir), 'strict');
     // Current dir we are in, inside scorm/
     if ($this->debug > 1) {
         error_log('New LP - import_package() - current_dir = ' . $current_dir, 0);
     }
     //$uploaded_filename = $_FILES['userFile']['name'];
     // Get name of the zip file without the extension.
     if ($this->debug > 1) {
         error_log('New LP - Received zip file name: ' . $zip_file_path, 0);
     }
     $file_info = pathinfo($zip_file_name);
     $filename = $file_info['basename'];
     $extension = $file_info['extension'];
     $file_base_name = str_replace('.' . $extension, '', $filename);
     // Filename without its extension.
     $this->zipname = $file_base_name;
     // Save for later in case we don't have a title.
     if ($this->debug > 1) {
         error_log("New LP - base file name is : " . $file_base_name, 0);
     }
     $new_dir = api_replace_dangerous_char(trim($file_base_name), 'strict');
     $this->subdir = $new_dir;
     if ($this->debug > 1) {
         error_log("New LP - subdir is first set to : " . $this->subdir, 0);
     }
     $zipFile = new PclZip($zip_file_path);
     // Check the zip content (real size and file extension).
     $zipContentArray = $zipFile->listContent();
     $package_type = '';
     $at_root = false;
     $manifest = '';
     $realFileSize = 0;
     $manifest_list = array();
     // The following loop should be stopped as soon as we found the right imsmanifest.xml (how to recognize it?).
     foreach ($zipContentArray as $thisContent) {
         $file = $thisContent['filename'];
         //error_log('Looking at  '.$thisContent['filename'], 0);
         if (preg_match('~.(php.*|phtml)$~i', $file)) {
             $this->set_error_msg("File {$file} contains a PHP script");
             //return api_failure::set_failure('php_file_in_zip_file');
         } elseif (stristr($thisContent['filename'], 'imsmanifest.xml')) {
             //error_log('Found imsmanifest at '.$thisContent['filename'], 0);
             if ($thisContent['filename'] == basename($thisContent['filename'])) {
                 $at_root = true;
             } else {
                 //$this->subdir .= '/'.dirname($thisContent['filename']);
                 if ($this->debug > 2) {
                     error_log("New LP - subdir is now " . $this->subdir, 0);
                 }
             }
             $package_type = 'scorm';
             $manifest_list[] = $thisContent['filename'];
             $manifest = $thisContent['filename'];
             //just the relative directory inside scorm/
         } else {
             // Do nothing, if it has not been set as scorm somewhere else, it stays as '' default.
         }
         $realFileSize += $thisContent['size'];
     }
     // Now get the shortest path (basically, the imsmanifest that is the closest to the root).
     $shortest_path = $manifest_list[0];
     $slash_count = substr_count($shortest_path, '/');
     foreach ($manifest_list as $manifest_path) {
         $tmp_slash_count = substr_count($manifest_path, '/');
         if ($tmp_slash_count < $slash_count) {
             $shortest_path = $manifest_path;
             $slash_count = $tmp_slash_count;
         }
     }
     $this->subdir .= '/' . dirname($shortest_path);
     // Do not concatenate because already done above.
     $manifest = $shortest_path;
     if ($this->debug > 1) {
         error_log('New LP - Package type is now ' . $package_type, 0);
     }
     // && defined('CHECK_FOR_SCORM') && CHECK_FOR_SCORM)
     if ($package_type == '') {
         if ($this->debug > 1) {
             error_log('New LP - Package type is empty', 0);
         }
         return api_failure::set_failure('not_scorm_content');
     }
     // It happens on Linux that $new_dir sometimes doesn't start with '/'
     if ($new_dir[0] != '/') {
         $new_dir = '/' . $new_dir;
     }
     if ($new_dir[strlen($new_dir) - 1] == '/') {
         $new_dir = substr($new_dir, 0, -1);
     }
     $isDir = is_dir($course_sys_dir . $new_dir);
     if ($isDir == false) {
         mkdir($course_sys_dir . $new_dir, api_get_permissions_for_new_directories());
         $isDir = is_dir($course_sys_dir . $new_dir);
     }
     /* Uncompressing phase */
     /*
         We need to process each individual file in the zip archive to
         - add it to the database
         - parse & change relative html links
         - make sure the filenames are secure (filter funny characters or php extensions)
     */
     if ($isDir) {
         if (!FileManager::enough_size($realFileSize, $course_sys_dir, $maxFilledSpace)) {
             if ($this->debug > 1) {
                 error_log('New LP - Not enough space to store package', 0);
             }
             return api_failure::set_failure('not_enough_space');
         }
         // PHP method - slower...
         if ($this->debug >= 1) {
             error_log('New LP - Changing dir to ' . $course_sys_dir . $new_dir, 0);
         }
         $saved_dir = getcwd();
         chdir($course_sys_dir . $new_dir);
         $unzippingState = $zipFile->extract();
         for ($j = 0; $j < count($unzippingState); $j++) {
             $state = $unzippingState[$j];
             // TODO: Fix relative links in html files (?)
             $extension = strrchr($state['stored_filename'], '.');
             if ($this->debug >= 1) {
                 error_log('New LP - found extension ' . $extension . ' in ' . $state['stored_filename'], 0);
             }
         }
         if (!empty($new_dir)) {
             $new_dir = $new_dir . '/';
         }
         // Rename files, for example with \\ in it.
         if ($this->debug >= 1) {
             error_log('New LP - try to open: ' . $course_sys_dir . $new_dir, 0);
         }
         if ($dir = @opendir($course_sys_dir . $new_dir)) {
             if ($this->debug >= 1) {
                 error_log('New LP - Opened dir ' . $course_sys_dir . $new_dir, 0);
             }
             while ($file = readdir($dir)) {
                 if ($file != '.' && $file != '..') {
                     $filetype = 'file';
                     if (is_dir($course_sys_dir . $new_dir . $file)) {
                         $filetype = 'folder';
                     }
                     // TODO: RENAMING FILES CAN BE VERY DANGEROUS SCORM-WISE, avoid that as much as possible!
                     //$safe_file = replace_dangerous_char($file, 'strict');
                     $find_str = array('\\', '.php', '.phtml');
                     $repl_str = array('/', '.txt', '.txt');
                     $safe_file = str_replace($find_str, $repl_str, $file);
                     if ($this->debug >= 1) {
                         error_log('Comparing:  ' . $safe_file, 0);
                     }
                     if ($this->debug >= 1) {
                         error_log('and:  ' . $file, 0);
                     }
                     if ($safe_file != $file) {
                         $mydir = dirname($course_sys_dir . $new_dir . $safe_file);
                         if (!is_dir($mydir)) {
                             $mysubdirs = split('/', $mydir);
                             $mybasedir = '/';
                             foreach ($mysubdirs as $mysubdir) {
                                 if (!empty($mysubdir)) {
                                     $mybasedir = $mybasedir . $mysubdir . '/';
                                     if (!is_dir($mybasedir)) {
                                         @mkdir($mybasedir, api_get_permissions_for_new_directories());
                                         if ($this->debug >= 1) {
                                             error_log('New LP - Dir ' . $mybasedir . ' doesnt exist. Creating.', 0);
                                         }
                                     }
                                 }
                             }
                         }
                         @rename($course_sys_dir . $new_dir . $file, $course_sys_dir . $new_dir . $safe_file);
                         if ($this->debug >= 1) {
                             error_log('New LP - Renaming ' . $course_sys_dir . $new_dir . $file . ' to ' . $course_sys_dir . $new_dir . $safe_file, 0);
                         }
                     }
                 }
             }
             closedir($dir);
             chdir($saved_dir);
             api_chmod_R($course_sys_dir . $new_dir, api_get_permissions_for_new_directories());
             if ($this->debug > 1) {
                 error_log('New LP - changed back to init dir: ' . $course_sys_dir . $new_dir, 0);
             }
         }
     } else {
         return '';
     }
     return $course_sys_dir . $new_dir . $manifest;
 }
コード例 #18
0
ファイル: fileUpload.lib.php プロジェクト: daffef/chamilo-lms
/**
 * This function does the save-work for the documents.
 * It handles the uploaded file and adds the properties to the database
 * If unzip=1 and the file is a zipfile, it is extracted
 * If we decide to save ALL kinds of documents in one database,
 * we could extend this with a $type='document', 'scormdocument',...
 *
 * @param array $courseInfo
 * @param array $uploadedFile ($_FILES)
 * array(
 *  'name' => 'picture.jpg',
 *  'tmp_name' => '...', // absolute path
 * );
 * @param string $documentDir Example: /var/www/chamilo/courses/ABC/document
 * @param string $uploadPath Example: /folder1/folder2/
 * @param int $userId
 * @param int $groupId, 0 for everybody
 * @param int $toUserId, NULL for everybody
 * @param int $unzip 1/0
 * @param string $whatIfFileExists overwrite, rename or warn if exists (default)
 * @param boolean $output Optional output parameter.
 * @param bool $onlyUploadFile
 * @param string $comment
 * @param int $sessionId
 *
 * So far only use for unzip_uploaded_document function.
 * If no output wanted on success, set to false.
 * @param string $comment
 * @return string path of the saved file
 */
function handle_uploaded_document($courseInfo, $uploadedFile, $documentDir, $uploadPath, $userId, $groupId = 0, $toUserId = null, $unzip = 0, $whatIfFileExists = '', $output = true, $onlyUploadFile = false, $comment = null, $sessionId = null)
{
    if (!$userId) {
        return false;
    }
    $userInfo = api_get_user_info();
    $uploadedFile['name'] = stripslashes($uploadedFile['name']);
    // Add extension to files without one (if possible)
    $uploadedFile['name'] = add_ext_on_mime($uploadedFile['name'], $uploadedFile['type']);
    if (empty($sessionId)) {
        $sessionId = api_get_session_id();
    } else {
        $sessionId = intval($sessionId);
    }
    // Just in case process_uploaded_file is not called
    $maxSpace = DocumentManager::get_course_quota();
    // Check if there is enough space to save the file
    if (!DocumentManager::enough_space($uploadedFile['size'], $maxSpace)) {
        if ($output) {
            Display::display_error_message(get_lang('UplNotEnoughSpace'));
        }
        return false;
    }
    // If the want to unzip, check if the file has a .zip (or ZIP,Zip,ZiP,...) extension
    if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
        return unzip_uploaded_document($courseInfo, $userInfo, $uploadedFile, $uploadPath, $documentDir, $maxSpace, $sessionId, $groupId, $output);
    } elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
        // We can only unzip ZIP files (no gz, tar,...)
        if ($output) {
            Display::display_error_message(get_lang('UplNotAZip') . " " . get_lang('PleaseTryAgain'));
        }
        return false;
    } else {
        // Clean up the name, only ASCII characters should stay. (and strict)
        $cleanName = api_replace_dangerous_char($uploadedFile['name'], 'strict');
        // No "dangerous" files
        $cleanName = disable_dangerous_file($cleanName);
        // Checking file extension
        if (!filter_extension($cleanName)) {
            if ($output) {
                Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
            }
            return false;
        } else {
            // If the upload path differs from / (= root) it will need a slash at the end
            if ($uploadPath != '/') {
                $uploadPath = $uploadPath . '/';
            }
            // Full path to where we want to store the file with trailing slash
            $whereToSave = $documentDir . $uploadPath;
            // At least if the directory doesn't exist, tell so
            if (!is_dir($whereToSave)) {
                if (!mkdir($whereToSave, api_get_permissions_for_new_directories())) {
                    if ($output) {
                        Display::display_error_message(get_lang('DestDirectoryDoesntExist') . ' (' . $uploadPath . ')');
                    }
                    return false;
                }
            }
            // Just upload the file "as is"
            if ($onlyUploadFile) {
                $errorResult = moveUploadedFile($uploadedFile, $whereToSave . $cleanName);
                if ($errorResult) {
                    return $whereToSave . $cleanName;
                } else {
                    return $errorResult;
                }
            }
            /*
                Based in the clean name we generate a new filesystem name
                Using the session_id and group_id if values are not empty
            */
            /*$fileExists = DocumentManager::documentExists(
                  $uploadPath.$cleanName,
                  $courseInfo,
                  $sessionId,
                  $groupId
              );*/
            $fileSystemName = DocumentManager::fixDocumentName($cleanName, 'file', $courseInfo, $sessionId, $groupId);
            // Name of the document without the extension (for the title)
            $documentTitle = get_document_title($uploadedFile['name']);
            // Size of the uploaded file (in bytes)
            $fileSize = $uploadedFile['size'];
            // File permissions
            $filePermissions = api_get_permissions_for_new_files();
            // Example: /var/www/chamilo/courses/xxx/document/folder/picture.jpg
            $fullPath = $whereToSave . $fileSystemName;
            // Example: /folder/picture.jpg
            $filePath = $uploadPath . $fileSystemName;
            $docId = DocumentManager::get_document_id($courseInfo, $filePath, $sessionId);
            $documentList = DocumentManager::getDocumentByPathInCourse($courseInfo, $filePath);
            // This means that the path already exists in this course.
            if (!empty($documentList) && $whatIfFileExists != 'overwrite') {
                //$found = false;
                // Checking if we are talking about the same course + session
                /*foreach ($documentList as $document) {
                      if ($document['session_id'] == $sessionId) {
                          $found = true;
                          break;
                      }
                  }*/
                //if ($found == false) {
                $whatIfFileExists = 'rename';
                //}
            }
            // What to do if the target file exists
            switch ($whatIfFileExists) {
                // Overwrite the file if it exists
                case 'overwrite':
                    // Check if the target file exists, so we can give another message
                    $fileExists = file_exists($fullPath);
                    if (moveUploadedFile($uploadedFile, $fullPath)) {
                        chmod($fullPath, $filePermissions);
                        if ($fileExists && $docId) {
                            // UPDATE DATABASE
                            $documentId = DocumentManager::get_document_id($courseInfo, $filePath);
                            if (is_numeric($documentId)) {
                                // Update file size
                                update_existing_document($courseInfo, $documentId, $uploadedFile['size']);
                                // Update document item_property
                                api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentUpdated', $userId, $groupId, $toUserId, null, null, $sessionId);
                                // Redo visibility
                                api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                            } else {
                                // There might be cases where the file exists on disk but there is no registration of that in the database
                                // In this case, and if we are in overwrite mode, overwrite and create the db record
                                $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId);
                                if ($documentId) {
                                    // Put the document in item_property update
                                    api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId);
                                    // Redo visibility
                                    api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                                }
                            }
                            // If the file is in a folder, we need to update all parent folders
                            item_property_update_on_folder($courseInfo, $uploadPath, $userId);
                            // Display success message with extra info to user
                            if ($output) {
                                Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle . ' ' . get_lang('UplFileOverwritten'), false);
                            }
                            return $filePath;
                        } else {
                            // Put the document data in the database
                            $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId);
                            if ($documentId) {
                                // Put the document in item_property update
                                api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId);
                                // Redo visibility
                                api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                            }
                            // If the file is in a folder, we need to update all parent folders
                            item_property_update_on_folder($courseInfo, $uploadPath, $userId);
                            // Display success message to user
                            if ($output) {
                                Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle, false);
                            }
                            return $filePath;
                        }
                    } else {
                        if ($output) {
                            Display::display_error_message(get_lang('UplUnableToSaveFile'));
                        }
                        return false;
                    }
                    break;
                    // Rename the file if it exists
                // Rename the file if it exists
                case 'rename':
                    // Always rename.
                    $cleanName = DocumentManager::getUniqueFileName($uploadPath, $cleanName, $courseInfo, $sessionId, $groupId);
                    $fileSystemName = DocumentManager::fixDocumentName($cleanName, 'file', $courseInfo, $sessionId, $groupId);
                    $documentTitle = get_document_title($cleanName);
                    $fullPath = $whereToSave . $fileSystemName;
                    $filePath = $uploadPath . $fileSystemName;
                    if (moveUploadedFile($uploadedFile, $fullPath)) {
                        chmod($fullPath, $filePermissions);
                        // Put the document data in the database
                        $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId);
                        if ($documentId) {
                            // Update document item_property
                            api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId);
                            // Redo visibility
                            api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                        }
                        // If the file is in a folder, we need to update all parent folders
                        item_property_update_on_folder($courseInfo, $uploadPath, $userId);
                        // Display success message to user
                        if ($output) {
                            Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br />' . get_lang('UplFileSavedAs') . ' ' . $documentTitle, false);
                        }
                        return $filePath;
                    } else {
                        if ($output) {
                            Display::display_error_message(get_lang('UplUnableToSaveFile'));
                        }
                        return false;
                    }
                    break;
                default:
                    // Only save the file if it doesn't exist or warn user if it does exist
                    if (file_exists($fullPath) && $docId) {
                        if ($output) {
                            Display::display_error_message($cleanName . ' ' . get_lang('UplAlreadyExists'));
                        }
                    } else {
                        if (moveUploadedFile($uploadedFile, $fullPath)) {
                            chmod($fullPath, $filePermissions);
                            // Put the document data in the database
                            $documentId = add_document($courseInfo, $filePath, 'file', $fileSize, $documentTitle, $comment, 0, true, $groupId, $sessionId);
                            if ($documentId) {
                                // Update document item_property
                                api_item_property_update($courseInfo, TOOL_DOCUMENT, $documentId, 'DocumentAdded', $userId, $groupId, $toUserId, null, null, $sessionId);
                                // Redo visibility
                                api_set_default_visibility($documentId, TOOL_DOCUMENT, null, $courseInfo);
                            }
                            // If the file is in a folder, we need to update all parent folders
                            item_property_update_on_folder($courseInfo, $uploadPath, $userId);
                            // Display success message to user
                            if ($output) {
                                Display::display_confirmation_message(get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle, false);
                            }
                            return $filePath;
                        } else {
                            if ($output) {
                                Display::display_error_message(get_lang('UplUnableToSaveFile'));
                            }
                            return false;
                        }
                    }
                    break;
            }
        }
    }
}
コード例 #19
0
ファイル: QuickForm.php プロジェクト: ragebat/chamilo-lms
 /**
  * Class constructor
  * @param    string      $formName          Form's name.
  * @param    string      $method            (optional)Form's method defaults to 'POST'
  * @param    string      $action            (optional)Form's action
  * @param    string      $target            (optional)Form's target defaults to '_self'
  * @param    mixed       $attributes        (optional)Extra attributes for <form> tag
  * @param    bool        $trackSubmit       (optional)Whether to track if the form was submitted by adding a special hidden field
  * @access   public
  */
 public function __construct($formName = '', $method = 'post', $action = '', $target = '', $attributes = null, $trackSubmit = false)
 {
     HTML_Common::HTML_Common($attributes);
     $method = strtoupper($method) == 'GET' ? 'get' : 'post';
     // Modified by Chamilo team, 16-MAR-2010
     //$action = ($action == '') ? $_SERVER['PHP_SELF'] : $action;
     $action = $action == '' ? api_get_self() : $action;
     //
     $target = empty($target) ? array() : array('target' => $target);
     $form_id = $formName;
     if (isset($attributes['id']) && !empty($attributes['id'])) {
         $form_id = Security::remove_XSS($attributes['id']);
     }
     $attributes = array('action' => $action, 'method' => $method, 'name' => $formName, 'id' => $form_id) + $target;
     $this->updateAttributes($attributes);
     if (!$trackSubmit || isset($_REQUEST['_qf__' . $formName])) {
         if (1 == get_magic_quotes_gpc()) {
             $this->_submitValues = $this->_recursiveFilter('stripslashes', 'get' == $method ? $_GET : $_POST);
             foreach ($_FILES as $keyFirst => $valFirst) {
                 foreach ($valFirst as $keySecond => $valSecond) {
                     if ('name' == $keySecond) {
                         $this->_submitFiles[$keyFirst][$keySecond] = $this->_recursiveFilter('stripslashes', $valSecond);
                     } else {
                         $this->_submitFiles[$keyFirst][$keySecond] = $valSecond;
                     }
                 }
             }
         } else {
             $this->_submitValues = 'get' == $method ? $_GET : $_POST;
             $this->_submitFiles = $_FILES;
         }
         $this->_flagSubmitted = count($this->_submitValues) > 0 || count($this->_submitFiles) > 0;
     }
     if ($trackSubmit) {
         unset($this->_submitValues['_qf__' . $formName]);
         $this->addElement('hidden', '_qf__' . $formName, null);
     }
     if (preg_match('/^([0-9]+)([a-zA-Z]*)$/', ini_get('upload_max_filesize'), $matches)) {
         // see http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes
         switch (strtoupper($matches['2'])) {
             case 'G':
                 $this->_maxFileSize = $matches['1'] * 1073741824;
                 break;
             case 'M':
                 $this->_maxFileSize = $matches['1'] * 1048576;
                 break;
             case 'K':
                 $this->_maxFileSize = $matches['1'] * 1024;
                 break;
             default:
                 $this->_maxFileSize = $matches['1'];
         }
     }
     $course_id = api_get_course_int_id();
     //If I'm in a course replace the default max filesize with the course limits
     if (!empty($course_id)) {
         $free_course_quota = DocumentManager::get_course_quota() - DocumentManager::documents_total_space();
         if (empty($this->_maxFileSize) || $free_course_quota <= $this->_maxFileSize) {
             $this->_maxFileSize = intval($free_course_quota);
         }
     }
 }
コード例 #20
0
ファイル: upload.php プロジェクト: ilosada/chamilo-lms-icpna
         }
         // Compose a unique file name to avoid any conflict
         $new_file_name = api_get_unique_id();
         $curdirpath = basename($my_folder_data['url']);
         // If we come from the group tools the groupid will be saved in $work_table
         $result = move_uploaded_file($_FILES['file']['tmp_name'], $updir . $curdirpath . '/' . $new_file_name);
         if ($result) {
             $url = 'work/' . $curdirpath . '/' . $new_file_name;
             $contains_file = 1;
         }
     }
     if (empty($title)) {
         $title = get_lang('Untitled');
     }
     $documents_total_space = DocumentManager::documents_total_space();
     $course_max_space = DocumentManager::get_course_quota();
     $total_size = $filesize + $documents_total_space;
     if ($total_size > $course_max_space) {
         $error_message .= Display::return_message(get_lang('NoSpace'), 'warning');
     } else {
         $active = '1';
         $sql_add_publication = "INSERT INTO " . $work_table . " SET\n                                   c_id \t\t= {$course_id} ,\n                                   url         \t= '" . $url . "',\n                                   title       \t= '" . Database::escape_string($title) . "',\n                                   description\t= '" . Database::escape_string($description) . "',\n                                   contains_file = '" . $contains_file . "',\n                                   active\t\t= '" . $active . "',\n                                   accepted\t\t= '1',\n                                   post_group_id = '" . $group_id . "',\n                                   sent_date\t=  '" . api_get_utc_datetime() . "',\n                                   parent_id \t=  '" . $work_id . "' ,\n                                   session_id\t= '" . intval($id_session) . "' ,\n                                   user_id \t\t= '" . $user_id . "'";
         Database::query($sql_add_publication);
         $id = Database::insert_id();
     }
     if ($id) {
         api_item_property_update($course_info, 'work', $id, 'DocumentAdded', $user_id, api_get_group_id());
         $succeed = true;
     }
 } else {
     $error_message .= Display::return_message(get_lang('IsNotPosibleSaveTheDocument'), 'error');