Adding __session_id___group_id sufix when creating a document/folder

see BT#8852
1.9.x
Julio Montoya 11 years ago
parent 74a7f4a35e
commit 0f7272708f
  1. 18
      main/document/create_document.php
  2. 89
      main/document/downloadfolder.inc.php
  3. 279
      main/inc/lib/document.lib.php
  4. 485
      main/inc/lib/fileUpload.lib.php

@ -347,15 +347,21 @@ $defaults['id'] = $folder_id;
$form->addElement('hidden', 'title_edited', 'false', 'id="title_edited"');
/**
* Check if a document width the choosen filename allready exists
* Check if a document width the chosen filename already exists
*/
function document_exists($filename) {
global $filepath;
$filename = addslashes(trim($filename));
global $dir;
return DocumentManager::documentExists(
$dir.$filename.'.html',
api_get_course_info(),
api_get_session_id(),
api_get_group_id()
);
/*$filename = addslashes(trim($filename));
$filename = Security::remove_XSS($filename);
$filename = replace_dangerous_char($filename);
$filename = disable_dangerous_file($filename);
return !file_exists($filepath.$filename.'.html');
return !file_exists($filepath.$filename.'.html');*/
}
// Add group to the form
@ -499,8 +505,7 @@ if ($form->validate()) {
$filename = Security::remove_XSS($filename);
$filename = replace_dangerous_char($filename);
$filename = disable_dangerous_file($filename);
$filename .= get_document_suffix(
$filename .= DocumentManager::getDocumentSuffix(
$_course,
api_get_session_id(),
api_get_group_id()
@ -519,6 +524,7 @@ if ($form->validate()) {
}
// Don't create file with the same name.
if (file_exists($filepath.$filename.'.'.$extension)) {
Display:: display_header($nameTools, 'Doc');
Display:: display_error_message(get_lang('FileExists').' '.$title, false);

@ -6,9 +6,12 @@
* @package chamilo.document
*/
use \ChamiloSession as Session;
set_time_limit(0);
require_once '../inc/global.inc.php';
api_protect_course_script();
$sysCoursePath = api_get_path(SYS_COURSE_PATH);
@ -72,7 +75,28 @@ $remove_dir = ($path != '/') ? substr($path, 0, strlen($path) - strlen(basename(
// Put the files in the zip
// 2 possibilities: Admins get all files and folders in the selected folder (except for the deleted ones)
// Normal users get only visible files that are in visible folders
function fixDocumentNameCallback($p_event, &$p_header)
{
global $remove_dir;
$files = Session::read('doc_files_to_download');
$storedFile = $remove_dir.$p_header['stored_filename'];
if (!isset($files[$storedFile])) {
return 0;
}
$documentData = $files[$storedFile];
$documentNameFixed = DocumentManager::undoFixDocumentName(
$documentData['path'],
$documentData['c_id'],
$documentData['id_session'],
$documentData['to_group_id']
);
$p_header['stored_filename'] = $documentNameFixed;
return 1;
}
// Admins are allowed to download invisible files
if (api_is_allowed_to_edit()) {
// Set the path that will be used in the query
@ -83,7 +107,7 @@ if (api_is_allowed_to_edit()) {
}
$querypath = Database::escape_string($querypath);
// Search for all files that are not deleted => visibility != 2
$sql = "SELECT path, id_session
$sql = "SELECT path, id_session, docs.id, props.to_group_id, docs.c_id
FROM $doc_table AS docs INNER JOIN $prop_table AS props
ON
docs.id = props.ref AND
@ -98,9 +122,17 @@ if (api_is_allowed_to_edit()) {
docs.c_id = ".$courseId." ";
$sql.= DocumentManager::getSessionFolderFilters($querypath, $sessionId);
$query = Database::query($sql);
// Add tem to the zip file
while ($not_deleted_file = Database::fetch_assoc($query)) {
$result = Database::query($sql);
$files = array();
while ($row = Database::fetch_array($result)) {
$files[$row['path']] = $row;
}
Session::write('doc_files_to_download', $files);
foreach ($files as $not_deleted_file) {
// Filtering folders and
if (strpos($not_deleted_file['path'], 'chat_files') > 0 ||
strpos($not_deleted_file['path'], 'shared_folder') > 0
@ -111,12 +143,17 @@ if (api_is_allowed_to_edit()) {
}
}
}
$zip->add(
$sysCoursePath.$courseInfo['path'].'/document'.$not_deleted_file['path'],
PCLZIP_OPT_REMOVE_PATH,
$sysCoursePath.$courseInfo['path'].'/document'.$remove_dir
$sysCoursePath.$courseInfo['path'].'/document'.$remove_dir,
PCLZIP_CB_PRE_ADD,
'fixDocumentNameCallback'
);
}
Session::erase('doc_files_to_download');
} else {
// For other users, we need to create a zip file with only visible files and folders
@ -132,7 +169,7 @@ if (api_is_allowed_to_edit()) {
1st: Get all files that are visible in the given path
*/
$querypath = Database::escape_string($querypath);
$sql = "SELECT path, id_session
$sql = "SELECT path, id_session, docs.id, props.to_group_id, docs.c_id
FROM $doc_table AS docs INNER JOIN $prop_table AS props
ON
docs.id = props.ref AND
@ -147,10 +184,12 @@ if (api_is_allowed_to_edit()) {
props.to_group_id = ".$groupId;
$sql.= DocumentManager::getSessionFolderFilters($querypath, $sessionId);
$result = Database::query($sql);
$files = array();
$query = Database::query($sql);
// Add them to an array
while ($all_visible_files = Database::fetch_assoc($query)) {
while ($all_visible_files = Database::fetch_assoc($result)) {
if (strpos($all_visible_files['path'], 'chat_files') > 0 ||
strpos($all_visible_files['path'], 'shared_folder') > 0
) {
@ -161,10 +200,11 @@ if (api_is_allowed_to_edit()) {
}
}
$all_visible_files_path[] = $all_visible_files['path'];
$files[$all_visible_files['path']] = $all_visible_files;
}
// 2nd: Get all folders that are invisible in the given path
$sql = "SELECT path
$sql = "SELECT path, id_session, docs.id, props.to_group_id, docs.c_id
FROM $doc_table AS docs INNER JOIN $prop_table AS props
ON
docs.id = props.ref AND
@ -179,12 +219,15 @@ if (api_is_allowed_to_edit()) {
$query2 = Database::query($sql);
// If we get invisible folders, we have to filter out these results from all visible files we found
if (Database::num_rows($query2) > 0) {
$files = array();
// Add item to an array
while ($invisible_folders = Database::fetch_assoc($query2)) {
//3rd: Get all files that are in the found invisible folder (these are "invisible" too)
$sql = "SELECT path
FROM $doc_table AS docs INNER JOIN $prop_table AS props
$sql = "SELECT path, docs.id, props.to_group_id, docs.c_id
FROM $doc_table AS docs
INNER JOIN $prop_table AS props
ON
docs.id = props.ref AND
docs.c_id = props.c_id
@ -199,25 +242,36 @@ if (api_is_allowed_to_edit()) {
// Add tem to an array
while ($files_in_invisible_folder = Database::fetch_assoc($query3)) {
$files_in_invisible_folder_path[] = $files_in_invisible_folder['path'];
$files[$files_in_invisible_folder['path']] = $files_in_invisible_folder;
}
}
// Compare the array with visible files and the array with files in invisible folders
// and keep the difference (= all visible files that are not in an invisible folder)
$files_for_zipfile = diff((array)$all_visible_files_path, (array)$files_in_invisible_folder_path);
$files_for_zipfile = diff(
(array) $all_visible_files_path,
(array) $files_in_invisible_folder_path
);
} else {
// No invisible folders found, so all visible files can be added to the zipfile
$files_for_zipfile = $all_visible_files_path;
}
Session::write('doc_files_to_download', $files);
// Add all files in our final array to the zipfile
for ($i = 0; $i < count($files_for_zipfile); $i++) {
$zip->add(
$sysCoursePath . $courseInfo['path'] . '/document' . $files_for_zipfile[$i],
PCLZIP_OPT_REMOVE_PATH,
$sysCoursePath . $courseInfo['path'] . '/document' . $remove_dir
$sysCoursePath . $courseInfo['path'] . '/document' . $remove_dir,
PCLZIP_CB_PRE_ADD,
'fixDocumentNameCallback'
);
}
} // end for other users
Session::erase('doc_files_to_download');
}
// Launch event
event_download(($path == '/') ? 'documents.zip (folder)' : basename($path).'.zip (folder)');
@ -226,9 +280,11 @@ event_download(($path == '/') ? 'documents.zip (folder)' : basename($path).'.zip
$name = ($path == '/') ? 'documents.zip' : $documentInfo['title'].'.zip';
if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
DocumentManager::file_send_for_download($tempZipFile, true, $name);
$result = DocumentManager::file_send_for_download($tempZipFile, true, $name);
@unlink($tempZipFile);
exit;
} else {
api_not_allowed(true);
}
/**
@ -240,7 +296,8 @@ if (Security::check_abs_path($tempZipFile, api_get_path(SYS_ARCHIVE_PATH))) {
*
* @return array difference between the two arrays
*/
function diff($arr1, $arr2) {
function diff($arr1, $arr2)
{
$res = array();
$r = 0;
foreach ($arr1 as & $av) {

@ -315,7 +315,6 @@ class DocumentManager
if (!is_file($full_file_name)) {
return false;
}
$filename = ($name == '') ? basename($full_file_name) : replace_dangerous_char($name);
$len = filesize($full_file_name);
// Fixing error when file name contains a ","
@ -325,7 +324,8 @@ class DocumentManager
// Force the browser to save the file instead of opening it
global $_configuration;
if (isset($_configuration['enable_x_sendfile_headers']) && !empty($_configuration['enable_x_sendfile_headers'])) {
if (isset($_configuration['enable_x_sendfile_headers']) &&
!empty($_configuration['enable_x_sendfile_headers'])) {
header("X-Sendfile: $filename");
}
@ -1301,26 +1301,28 @@ class DocumentManager
*/
public static function get_document_id($courseInfo, $path, $sessionId = null)
{
$TABLE_DOCUMENT = Database :: get_course_table(TABLE_DOCUMENT);
$course_id = $courseInfo['real_id'];
$table = Database :: get_course_table(TABLE_DOCUMENT);
$courseId = $courseInfo['real_id'];
if (!isset($sessionId)) {
$sessionId = api_get_session_id();
} else {
$sessionId = intval($sessionId);
}
$path = Database::escape_string($path);
if (!empty($course_id) && !empty($path)) {
$sql = "SELECT id FROM $TABLE_DOCUMENT
$path = Database::escape_string($path);
if (!empty($courseId) && !empty($path)) {
$sql = "SELECT id FROM $table
WHERE
c_id = $course_id AND
c_id = $courseId AND
path LIKE BINARY '$path' AND
session_id = $sessionId
LIMIT 1";
$result = Database::query($sql);
if ($result && Database::num_rows($result)) {
if (Database::num_rows($result)) {
$row = Database::fetch_array($result);
return intval($row[0]);
return intval($row['id']);
}
}
@ -2704,15 +2706,19 @@ class DocumentManager
if (!empty($documentId)) {
$table_document = Database::get_course_table(TABLE_DOCUMENT);
$params = array();
if ($if_exists == 'rename') {
error_log('dd');
error_log($if_exists);
/*if ($if_exists == 'rename') {
// Remove prefix
$suffix = get_document_suffix(
$suffix = DocumentManager::getDocumentSuffix(
$course_info,
$sessionId,
api_get_group_id()
);
$new_path = basename($new_path);
$new_path = str_replace($suffix, '', $new_path);
error_log('renamed');
error_log($new_path);
$params['title'] = get_document_title($new_path);
} else {
if (!empty($title)) {
@ -2720,7 +2726,7 @@ class DocumentManager
} else {
$params['title'] = get_document_title($files['file']['name']);
}
}
}*/
if (!empty($comment)) {
$params['comment'] = trim($comment);
@ -4487,8 +4493,9 @@ class DocumentManager
/**
* Generate a default certificate for a courses
*
* @global string $css CSS directory
* @global string $img_dir Imgage direcory
* @global string $img_dir image directory
* @global string $default_course_dir Course directory
* @global string $js JS directory
* @param array $courseData The course info
@ -4539,4 +4546,248 @@ class DocumentManager
}
}
/**
* Get folder/file suffix
*
* @param array $courseInfo
* @param int $sessionId
* @param int $groupId
*
* @return string
*/
public static function getDocumentSuffix($courseInfo, $sessionId, $groupId)
{
// If no session or group, then no suffix.
if (empty($sessionId) && empty($groupId)) {
return '';
}
return '__'.intval($sessionId).'__'.intval($groupId);
}
/**
* Fix a document name adding session id and group id
* Turns picture.jpg -> picture__1__2.jpg
* Where 1 = session id and 2 group id
* Of session id and group id are empty then the function returns:
* picture.jpg -> picture.jpg
*
* @param string $name folder or file name
* @param string $type 'folder' or 'file'
* @param array $courseInfo
* @param int $sessionId
* @param int $groupId
*
* @return string
*/
public static function fixDocumentName($name, $type, $courseInfo, $sessionId, $groupId)
{
$suffix = self::getDocumentSuffix($courseInfo, $sessionId, $groupId);
switch ($type) {
case 'folder':
$name = $name.$suffix;
break;
case 'file':
$name = self::addSuffixToFileName($name, $suffix);
break;
}
return $name;
}
/**
* Add a suffix to a file Example:
* /folder/picture.jpg => to /folder/picture_this.jpg
* where "_this" is the suffix
* @param string $name
* @param string $suffix
* @return string
*/
public static function addSuffixToFileName($name, $suffix)
{
$extension = pathinfo($name, PATHINFO_EXTENSION);
$fileName = pathinfo($name, PATHINFO_FILENAME);
$dir = pathinfo($name, PATHINFO_DIRNAME);
if ($dir == '.') {
$dir = null;
}
if (!empty($dir)) {
$dir = $dir.'/';
}
$name = $dir.$fileName.$suffix.'.'.$extension;
return $name;
}
/**
* Check if folder exist in the course base or in the session course
* @param string $folder Example: /folder/folder2
* @param array $courseInfo
* @param int $sessionId
* @param int $groupId
*
* @return bool
*/
public static function folderExists(
$folder,
$courseInfo,
$sessionId,
$groupId
) {
$courseId = $courseInfo['real_id'];
if (empty($courseId)) {
return false;
}
$sessionId = intval($sessionId);
$folder = Database::escape_string($folder);
$folderWithSuffix = self::fixDocumentName(
$folder,
'folder',
$courseInfo,
$sessionId,
$groupId
);
$folderWithSuffix = Database::escape_string($folderWithSuffix);
// Check if pathname already exists inside document table
$tbl_document = Database::get_course_table(TABLE_DOCUMENT);
$sql = "SELECT id, path FROM $tbl_document
WHERE
filetype = 'folder' AND
c_id = $courseId AND
(path = '".$folder."' OR path = '$folderWithSuffix') AND
(session_id = 0 OR session_id = $sessionId)
";
$rs = Database::query($sql);
if (Database::num_rows($rs)) {
return true;
}
return false;
}
/**
* Check if file exist in the course base or in the session course
* @param string $fileName Example: /folder/picture.jpg
* @param array $courseInfo
* @param int $sessionId
* @param int $groupId
*
* @return bool
*/
public static function documentExists(
$fileName,
$courseInfo,
$sessionId,
$groupId
) {
$courseId = $courseInfo['real_id'];
if (empty($courseId)) {
return false;
}
$sessionId = intval($sessionId);
$fileNameEscape = Database::escape_string($fileName);
$fileNameWithSuffix = self::fixDocumentName(
$fileName,
'file',
$courseInfo,
$sessionId,
$groupId
);
$fileNameWithSuffix = Database::escape_string($fileNameWithSuffix);
// Check if pathname already exists inside document table
$tbl_document = Database::get_course_table(TABLE_DOCUMENT);
$sql = "SELECT id, path FROM $tbl_document
WHERE
filetype = 'file' AND
c_id = $courseId AND
(
path = '".$fileNameEscape."' OR
path ='$fileNameWithSuffix'
) AND
(session_id = 0 OR session_id = $sessionId)
";
$rs = Database::query($sql);
if (Database::num_rows($rs)) {
return true;
}
return false;
}
/**
* Undo the suffix applied to a file example:
* turns picture__1__1.jpg to picture.jpg
* @param string $name
* @param int $courseId
* @param int $sessionId
* @param int $groupId
*
* @return string
*/
public static function undoFixDocumentName(
$name,
$courseId,
$sessionId,
$groupId
) {
if (empty($sessionId) && empty($groupId)) {
return $name;
}
$suffix = self::getDocumentSuffix(
array('real_id' => $courseId),
$sessionId,
$groupId
);
$name = str_replace($suffix, '', $name);
return $name;
}
/**
* @param string $path
* @param string $name
* @param array $courseInfo
* @param int $sessionId
* @param int $groupId
*
* @return string
*/
public static function getUniqueFileName($path, $name, $courseInfo, $sessionId, $groupId)
{
$counter = 1;
$filePath = $path.$name;
error_log('getUniqueFileName');
error_log($filePath);
$uniqueName = $name;
while($documentExists = self::documentExists(
$filePath,
$courseInfo,
$sessionId,
$groupId
)) {
$uniqueName = self::addSuffixToFileName($name, '_'.$counter);
$filePath = $path.$uniqueName;
error_log($filePath);
$counter++;
}
error_log($uniqueName);
return $uniqueName;
}
}

@ -53,6 +53,8 @@ function disable_dangerous_file($filename) {
* @param string $path
* @param string $name
*
* @deprecated
*
* @return string new unique name
*/
function unique_name($path, $name)
@ -168,348 +170,422 @@ function process_uploaded_file($uploaded_file, $show_output = true)
* 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 array $courseInfo
* @param array $uploadedFile ($_FILES)
* @param string $documentDir
* @param string $uploadPath
* @param int $userId
* @param int $groupId, 0 for everybody
* @param int $toUserId, 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.
* @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(
$_course,
$uploaded_file,
$base_work_dir,
$upload_path,
$user_id,
$to_group_id = 0,
$to_user_id = null,
$courseInfo,
$uploadedFile,
$documentDir,
$uploadPath,
$userId,
$groupId = 0,
$toUserId = null,
$unzip = 0,
$what_if_file_exists = '',
$whatIfFileExists = '',
$output = true,
$onlyUploadFile = false,
$comment = null,
$sessionId = null
) {
if (!$user_id) {
if (!$userId) {
return false;
}
$uploaded_file['name'] = stripslashes($uploaded_file['name']);
$uploadedFile['name'] = stripslashes($uploadedFile['name']);
// Add extension to files without one (if possible)
$uploaded_file['name'] = add_ext_on_mime($uploaded_file['name'], $uploaded_file['type']);
$uploadedFile['name'] = add_ext_on_mime($uploadedFile['name'], $uploadedFile['type']);
if (empty($sessionId)) {
$current_session_id = api_get_session_id();
$sessionId = api_get_session_id();
} else {
$current_session_id = intval($sessionId);
$sessionId = intval($sessionId);
}
// Just in case process_uploaded_file is not called
$max_filled_space = DocumentManager::get_course_quota();
$maxSpace = 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 (!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($uploaded_file['name']))) {
if ($unzip == 1 && preg_match('/.zip$/', strtolower($uploadedFile['name']))) {
return unzip_uploaded_document(
$uploaded_file,
$upload_path,
$base_work_dir,
$max_filled_space,
$uploadedFile,
$uploadPath,
$documentDir,
$maxSpace,
$output,
$to_group_id
$groupId
);
} elseif ($unzip == 1 && !preg_match('/.zip$/', strtolower($uploaded_file['name']))) {
} 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'));
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 = replace_dangerous_char($uploaded_file['name'], 'strict');
$cleanName = replace_dangerous_char($uploadedFile['name'], 'strict');
// No "dangerous" files
$clean_name = disable_dangerous_file($clean_name);
$cleanName = disable_dangerous_file($cleanName);
// Checking file extension
if (!filter_extension($clean_name)) {
if (!filter_extension($cleanName)) {
if ($output) {
Display::display_error_message(get_lang('UplUnableToSaveFileFilteredExtension'));
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 ($upload_path != '/') {
$upload_path = $upload_path.'/';
if ($uploadPath != '/') {
$uploadPath = $uploadPath.'/';
}
// Full path to where we want to store the file with trailing slash
$where_to_save = $base_work_dir.$upload_path;
$whereToSave = $documentDir.$uploadPath;
// At least if the directory doesn't exist, tell so
if (!is_dir($where_to_save)) {
if (!mkdir($where_to_save, api_get_permissions_for_new_directories())) {
if (!is_dir($whereToSave)) {
if (!mkdir($whereToSave, api_get_permissions_for_new_directories())) {
if ($output) {
Display::display_error_message(
get_lang('DestDirectoryDoesntExist').' ('.$upload_path.')'
get_lang('DestDirectoryDoesntExist').' ('.$uploadPath.')'
);
}
return false;
}
}
// Full path of the destination
$suffix = get_document_suffix($_course, $sessionId, $to_group_id);
$fileInfo = pathinfo($clean_name);
$fileSystemName = $fileInfo['filename'].$suffix.'.'.$fileInfo['extension'];
$store_path = $where_to_save.$fileSystemName;
$file_path = $upload_path.$fileSystemName;
// Name of the document without the extension (for the title)
$document_name = 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();
// Just upload the file.
// Just upload the file "as is"
if ($onlyUploadFile) {
$errorResult = moveUploadedFile($uploaded_file, $store_path);
$errorResult = moveUploadedFile($uploadedFile, $whereToSave.$cleanName);
if ($errorResult) {
return $store_path;
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
);
error_log('ddd');
error_log($cleanName);
$fileSystemName = DocumentManager::fixDocumentName(
$cleanName,
'file',
$courseInfo,
$sessionId,
$groupId
);
error_log($fileSystemName);
// 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(
$_course,
$file_path,
$current_session_id
$courseInfo,
$filePath,
$sessionId
);
error_log($docId);
$documentList = DocumentManager::getDocumentByPathInCourse(
$_course,
$file_path
$courseInfo,
$filePath //$filePath
);
//var_dump($documentList);
// This means that the path already exists in this course.
if (!empty($documentList)) {
$found = false;
//$found = false;
// Checking if we are talking about the same course + session
foreach ($documentList as $document) {
if ($document['session_id'] == $current_session_id) {
/*foreach ($documentList as $document) {
if ($document['session_id'] == $sessionId) {
$found = true;
break;
}
}
}*/
if ($found == false) {
$what_if_file_exists = 'rename';
}
//if ($found == false) {
$whatIfFileExists = 'rename';
//}
}
error_log($whatIfFileExists);
// What to do if the target file exists
switch ($what_if_file_exists) {
switch ($whatIfFileExists) {
// 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 (moveUploadedFile($uploaded_file, $store_path)) {
chmod($store_path, $files_perm);
if ($file_exists && $docId) {
$fileExists = file_exists($fullPath);
error_log('11');
error_log($fileExists);
if (moveUploadedFile($uploadedFile, $fullPath)) {
chmod($fullPath, $filePermissions);
error_log('222');
if ($fileExists && $docId) {
error_log('333');
// UPDATE DATABASE
$document_id = DocumentManager::get_document_id($_course, $file_path);
if (is_numeric($document_id)) {
$documentId = DocumentManager::get_document_id(
$courseInfo,
$filePath
);
if (is_numeric($documentId)) {
// Update file size
update_existing_document(
$_course,
$document_id,
$uploaded_file['size']
$courseInfo,
$documentId,
$uploadedFile['size']
);
// Update document item_property
api_item_property_update(
$_course,
$courseInfo,
TOOL_DOCUMENT,
$document_id,
$documentId,
'DocumentUpdated',
$user_id,
$to_group_id,
$to_user_id,
$userId,
$groupId,
$toUserId,
null,
null,
$current_session_id
$sessionId
);
// Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $document_id);
api_set_default_visibility(TOOL_DOCUMENT, $documentId);
} 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
$document_id = add_document(
$_course,
$file_path,
$documentId = add_document(
$courseInfo,
$filePath,
'file',
$file_size,
$document_name,
$fileSize,
$documentTitle,
$comment,
0,
true,
$to_group_id,
$current_session_id
$groupId,
$sessionId
);
if ($document_id) {
if ($documentId) {
// Put the document in item_property update
api_item_property_update(
$_course,
$courseInfo,
TOOL_DOCUMENT,
$document_id,
$documentId,
'DocumentAdded',
$user_id,
$to_group_id,
$to_user_id,
$userId,
$groupId,
$toUserId,
null,
null,
$current_session_id
$sessionId
);
// Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $document_id);
api_set_default_visibility(TOOL_DOCUMENT, $documentId);
}
}
// If the file is in a folder, we need to update all parent folders
item_property_update_on_folder($_course, $upload_path, $user_id);
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 /> ' . $document_name . ' ' . get_lang('UplFileOverwritten'),
get_lang('UplUploadSucceeded') . '<br /> ' . $documentTitle . ' ' . get_lang('UplFileOverwritten'),
false
);
}
return $file_path;
return $filePath;
} else {
// Put the document data in the database
$document_id = add_document(
$_course,
$file_path,
$documentId = add_document(
$courseInfo,
$filePath,
'file',
$file_size,
$document_name,
$fileSize,
$documentTitle,
$comment,
0,
true,
$to_group_id,
$current_session_id
$groupId,
$sessionId
);
if ($document_id) {
if ($documentId) {
// Put the document in item_property update
api_item_property_update(
$_course,
$courseInfo,
TOOL_DOCUMENT,
$document_id,
$documentId,
'DocumentAdded',
$user_id,
$to_group_id,
$to_user_id,
$userId,
$groupId,
$toUserId,
null,
null,
$current_session_id
$sessionId
);
// Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $document_id);
api_set_default_visibility(TOOL_DOCUMENT, $documentId);
}
// If the file is in a folder, we need to update all parent folders
item_property_update_on_folder($_course, $upload_path, $user_id);
item_property_update_on_folder($courseInfo, $uploadPath, $userId);
// Display success message to user
if ($output) {
Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br /> '.$document_name, false);
Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br /> '.$documentTitle, false);
}
return $file_path;
return $filePath;
}
} else {
if ($output) {
Display::display_error_message(get_lang('UplUnableToSaveFile'));
}
return false;
}
break;
// Rename the file if it exists
case 'rename':
// Always rename.
$new_name = unique_name($where_to_save, $fileSystemName);
$softName = unique_name($where_to_save, $clean_name);
$document_name = $softName;
$store_path = $where_to_save.$new_name;
$new_file_path = $upload_path.$new_name;
$cleanName = DocumentManager::getUniqueFileName(
$uploadPath,
$cleanName,
$courseInfo,
$sessionId,
$groupId
);
if (moveUploadedFile($uploaded_file, $store_path)) {
$fileSystemName = DocumentManager::fixDocumentName(
$cleanName,
'file',
$courseInfo,
$sessionId,
$groupId
);
$documentTitle = get_document_title($cleanName);
error_log('---->fin');
error_log($fileSystemName);
error_log($cleanName);
$fullPath = $whereToSave.$fileSystemName;
$filePath = $uploadPath.$fileSystemName;
chmod($store_path, $files_perm);
if (moveUploadedFile($uploadedFile, $fullPath)) {
chmod($fullPath, $filePermissions);
// Put the document data in the database
$document_id = add_document(
$_course,
$new_file_path,
$documentId = add_document(
$courseInfo,
$filePath,
'file',
$file_size,
$document_name,
$fileSize,
$documentTitle,
$comment, // comment
0, // read only
true, // save visibility
$to_group_id,
$current_session_id
$groupId,
$sessionId
);
if ($document_id) {
if ($documentId) {
// Update document item_property
api_item_property_update(
$_course,
$courseInfo,
TOOL_DOCUMENT,
$document_id,
$documentId,
'DocumentAdded',
$user_id,
$to_group_id,
$to_user_id,
$userId,
$groupId,
$toUserId,
null,
null,
$current_session_id
$sessionId
);
// Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $document_id);
api_set_default_visibility(TOOL_DOCUMENT, $documentId);
}
// If the file is in a folder, we need to update all parent folders
item_property_update_on_folder($_course, $upload_path, $user_id);
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') .' '.$document_name,
get_lang('UplUploadSucceeded') . '<br />' . get_lang('UplFileSavedAs') .' '.$documentTitle,
false
);
}
return $new_file_path;
error_log($filePath);
return $filePath;
} else {
if ($output) {
Display::display_error_message(get_lang('UplUnableToSaveFile'));
@ -519,59 +595,59 @@ function handle_uploaded_document(
break;
default:
// Only save the file if it doesn't exist or warn user if it does exist
if (file_exists($store_path) && $docId) {
if (file_exists($fullPath) && $docId) {
if ($output) {
Display::display_error_message($clean_name.' '.get_lang('UplAlreadyExists'));
Display::display_error_message($cleanName.' '.get_lang('UplAlreadyExists'));
}
} else {
if (moveUploadedFile($uploaded_file, $store_path)) {
chmod($store_path, $files_perm);
if (moveUploadedFile($uploadedFile, $fullPath)) {
chmod($fullPath, $filePermissions);
// Put the document data in the database
$document_id = add_document(
$_course,
$file_path,
$documentId = add_document(
$courseInfo,
$filePath,
'file',
$file_size,
$document_name,
$fileSize,
$documentTitle,
$comment,
0,
true,
$to_group_id,
$current_session_id
$groupId,
$sessionId
);
if ($document_id) {
if ($documentId) {
// Update document item_property
api_item_property_update(
$_course,
$courseInfo,
TOOL_DOCUMENT,
$document_id,
$documentId,
'DocumentAdded',
$user_id,
$to_group_id,
$to_user_id,
$userId,
$groupId,
$toUserId,
null,
null,
$current_session_id
$sessionId
);
// Redo visibility
api_set_default_visibility(TOOL_DOCUMENT, $document_id);
api_set_default_visibility(TOOL_DOCUMENT, $documentId);
}
// If the file is in a folder, we need to update all parent folders
item_property_update_on_folder(
$_course,
$upload_path,
$user_id
$courseInfo,
$uploadPath,
$userId
);
// Display success message to user
if ($output){
Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br /> '.$document_name, false);
Display::display_confirmation_message(get_lang('UplUploadSucceeded').'<br /> '.$documentTitle, false);
}
return $file_path;
return $filePath;
} else {
if ($output) {
Display::display_error_message(get_lang('UplUnableToSaveFile'));
@ -1136,13 +1212,13 @@ function add_document(
VALUES ($c_id, '$path','$filetype','$filesize','$title', '$comment', $readonly, $session_id)";
if (Database::query($sql)) {
$document_id = Database::insert_id();
if ($document_id) {
$documentId = Database::insert_id();
if ($documentId) {
if ($save_visibility) {
api_set_default_visibility($document_id, TOOL_DOCUMENT, $group_id);
api_set_default_visibility($documentId, TOOL_DOCUMENT, $group_id);
}
}
return $document_id;
return $documentId;
} else {
return false;
}
@ -1153,21 +1229,21 @@ function add_document(
* as the file exists, we only need to change the size
*
* @param array $_course
* @param int $document_id
* @param int $documentId
* @param int $filesize
* @param int $readonly
* @return boolean true /false
*/
function update_existing_document($_course, $document_id, $filesize, $readonly = 0)
function update_existing_document($_course, $documentId, $filesize, $readonly = 0)
{
$document_table = Database::get_course_table(TABLE_DOCUMENT);
$document_id = intval($document_id);
$documentId = intval($documentId);
$filesize = intval($filesize);
$readonly = intval($readonly);
$course_id = $_course['real_id'];
$sql = "UPDATE $document_table SET size = '$filesize' , readonly = '$readonly'
WHERE c_id = $course_id AND id = $document_id";
WHERE c_id = $course_id AND id = $documentId";
if (Database::query($sql)) {
return true;
} else {
@ -1340,19 +1416,6 @@ function search_img_from_html($html_file) {
return $img_path_list;
}
/**
* Get folder/file suffix
* @param array $courseInfo
* @param int $sessionId
* @param int $groupId
*
* @return string
*/
function get_document_suffix($courseInfo, $sessionId, $groupId)
{
return '_'.intval($sessionId).'_'.intval($groupId);
}
/**
* Creates a new directory trying to find a directory name
* that doesn't already exist
@ -1383,22 +1446,34 @@ function create_unexisting_directory(
$title = null,
$visibility = null
) {
$course_id = $_course['real_id'];
$session_id = intval($session_id);
$folderExists = DocumentManager::folderExists(
$desired_dir_name,
$_course,
$session_id,
$to_group_id
);
if ($folderExists == true) {
return false;
}
$systemFolderName = $desired_dir_name;
// Adding prefix folder prefix
$prefix = get_document_suffix($_course, $session_id, $to_group_id);
$systemFolderName .= $prefix;
/*$nb = '';
// add numerical suffix to directory if another one of the same number already exists
while (file_exists($base_work_dir.$systemFolderName.$nb)) {
$nb += 1;
}*/
// Adding suffix
$suffix = DocumentManager::getDocumentSuffix(
$_course,
$session_id,
$to_group_id
);
$systemFolderName .= $suffix;
if ($title == null) {
$title = basename($desired_dir_name);
}
$course_id = $_course['real_id'];
if (!is_dir($base_work_dir.$systemFolderName)) {
mkdir(

Loading…
Cancel
Save