コード例 #1
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;
            }
        }
    }
}
コード例 #2
0
    if (DocumentManager::check_readonly($course_info, $user_id, $file)) {
        api_not_allowed();
    }
}
/* MAIN TOOL CODE */
/*	Code to change the comment	*/
if (isset($_POST['comment'])) {
    // Fixing the path if it is wrong
    $comment = trim($_POST['comment']);
    $title = trim($_POST['title']);
    // Just in case see BT#3525
    if (empty($title)) {
        $title = $document_data['title'];
    }
    if (empty($title)) {
        $title = get_document_title($_POST['filename']);
    }
    if (!empty($document_id)) {
        $params = ['comment' => $comment, 'title' => $title];
        Database::update($dbTable, $params, ['c_id = ? AND id = ?' => [$course_id, $document_id]]);
        Display::addFlash(Display::return_message(get_lang('fileModified')));
    }
}
/*	WYSIWYG HTML EDITOR - Program Logic */
if ($is_allowed_to_edit) {
    if (isset($_POST['formSent']) && $_POST['formSent'] == 1) {
        $filename = stripslashes($_POST['filename']);
        $extension = $_POST['extension'];
        $content = isset($_POST['content']) ? trim(str_replace(array("\r", "\n"), '', stripslashes($_POST['content']))) : null;
        $content = Security::remove_XSS($content, COURSEMANAGERLOWSECURITY);
        if ($dir == '/') {