WIP Documents: added Ability to replace a file in documents

- refs BT#17861
pull/3556/head
carlos alvarado 5 years ago
parent f6acf8c1db
commit 2d87c8b3ee
  1. 115
      main/document/document.php
  2. 272
      main/inc/lib/document.lib.php
  3. 44
      main/inc/lib/formvalidator/index.html

@ -37,6 +37,9 @@ $parent_id = null;
$lib_path = api_get_path(LIBRARY_PATH);
$actionsRight = '';
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';
if(isset($_POST['currentFile'])){
$action = 'replace';
}
$allowUseTool = false;
if ($allowDownloadDocumentsByApiKey) {
@ -213,6 +216,98 @@ $currentUrl = api_get_self().'?'.api_get_cidreq().'&id='.$document_id;
$curdirpath = isset($_GET['curdirpath']) ? Security::remove_XSS($_GET['curdirpath']) : null;
switch ($action) {
case 'replace':
if (($isAllowedToEdit ||
$groupMemberWithUploadRights ||
DocumentManager::isBasicCourseFolder($curdirpath, $sessionId) ||
DocumentManager::is_my_shared_folder(api_get_user_id(), $curdirpath, $sessionId) ||
DocumentManager::is_my_shared_folder(api_get_user_id(), $moveTo, $sessionId)) &&
isset($_POST['currentFile'])
) {
$fileTarget = $_POST['currentFile'];
if (isset($_FILES) && isset($_FILES['file_'.$fileTarget])) {
$fileId = (int)$_POST['id_'.$fileTarget];
if (!$isAllowedToEdit) {
if (api_is_coach()) {
if (!DocumentManager::is_visible_by_id(
$fileId,
$courseInfo,
$sessionId,
api_get_user_id()
)
) {
api_not_allowed();
}
}
if (DocumentManager::check_readonly($courseInfo, api_get_user_id(), '', $fileId, true)) {
api_not_allowed();
}
}
$documentInfo = DocumentManager::get_document_data_by_id(
$fileId,
$courseInfo['code'],
false,
$sessionId
);
GroupManager::allowUploadEditDocument(
$userId,
$courseId,
$group_properties,
$documentInfo,
true
);
// Check whether the document is in the database.
if (!empty($documentInfo) ) {
$file = $_FILES['file_'.$fileTarget];
/**/
if ($documentInfo['filetype'] == 'file') {
$deleteDocument = DocumentManager::writeContentIntoDocument(
$courseInfo,
null,
$base_work_dir,
$sessionId,
$fileId,
$groupIid,
$file
);
if ($deleteDocument) {
/*
$certificateId = isset($_GET['delete_certificate_id']) ? $_GET['delete_certificate_id'] : null;
DocumentManager::remove_attach_certificate(
api_get_course_id(),
$certificateId
);
*/
Display::addFlash(
Display::return_message(
get_lang('DocDeleted').': '.$documentInfo['title'],
'success'
)
);
} else {
Display::addFlash(Display::return_message(get_lang('DocDeleteError'), 'warning'));
}
}
/**/
} else {
Display::addFlash(Display::return_message(get_lang('FileNotFound'), 'warning'));
}
header("Location: $currentUrl");
exit;
}
}
break;
exit();
break;
case 'delete_item':
if ($isAllowedToEdit ||
$groupMemberWithUploadRights ||
@ -256,6 +351,7 @@ switch ($action) {
// Check whether the document is in the database.
if (!empty($documentInfo)) {
if ($documentInfo['filetype'] != 'link') {
$deleteDocument = DocumentManager::delete_document(
$courseInfo,
@ -2197,7 +2293,26 @@ if (false === $disableQuotaMessage && count($documentAndFolders) > 1) {
</script>';
echo '<span id="course_quota"></span>';
}
echo '<script>
var temporal = undefined;
$(function() {
$(".removeHiddenFile").click(function(){
temporal = this;
data = $(this).data("id");
$(".upload_element_"+data).removeClass("hidden");
$.each($(".currentFile"),function(a,b){$(b).val(data);});
});
$(".btnSendFile").click(function(){
temporal = this;
data = $(this).data("id");
$(".upload_element_"+data).removeClass("hidden");
$.each($(".currentFile"),function(a,b){$(b).val(data);});
});
$("form[name=form_teacher_table]").prop("enctype","multipart/form-data")
});
</script>
';
if (!empty($table_footer)) {
echo Display::return_message($table_footer, 'warning');
}

@ -5639,6 +5639,72 @@ class DocumentManager
api_get_self()."?$courseParams&action=export_to_pdf&id=$id&curdirpath=$curdirpath"
);
}
if ($type == 'file') {
$randomUploadName= md5(uniqid(mt_rand(), true));
$ur = "#!";
$modify_icons[] = Display::url(
Display::return_icon('upload_file.png', "****** REEMPLAZAAR ".get_lang('Export2PDF')),
$ur,
[
'data-id' => $randomUploadName,
'class' => 'removeHiddenFile'
]
);
$html = '';
$html .= "
<div class='upload_element_".$randomUploadName." hidden'>
<div class='form-group ' id='file_file'>
<label class='col-sm-2 control-label' for='file_".$randomUploadName."'>
".get_lang('File')."
</label>
<div class='col-sm-8'>
<input class='' name='file_".$randomUploadName."' style='width: 250px' type='file'>
</div>
<div class='col-sm-2'></div>
</div>
<div class='form-group '>
<label class='col-sm-2 control-label' for='upload_".$randomUploadName."_submitDocument'>
</label>
<div class='col-sm-8'>
<button class=' btn btn-primary ' id='upload_".$randomUploadName."_submitDocument'
name='submitDocument'
type='submit'>
<em class='fa fa-paper-plane'></em> ".get_lang('SendDocument')."
</button>
</div>
<div class='col-sm-2'></div>
</div>
<input class='currentFile' name='currentFile' type='hidden' >
<input id='upload_".$randomUploadName."__qf__upload_".$randomUploadName."' name='_qf__upload_".$randomUploadName."'
type='hidden'
value=''>
<input id='upload_".$randomUploadName."_id' name='id_$randomUploadName' type='hidden' value='$id'>
<input id='upload_".$randomUploadName."_MAX_FILE_SIZE' name='MAX_FILE_SIZE' type='hidden' value='".ini_get('upload_max_filesize')."'>
</div>
";
/*
$form->addElement('hidden', 'action', 'replace');
$form->addButtonSend(get_lang('SendDocument'), 'submitDocument',false,[
'data-id' => $randomUploadName,
'class' => 'btnSendFile'
]);
$form->setDefaults([]);
$form->addElement('html', '</div>');
$form->addElement('html', '<input name ="currentFile" class="currentFile" type="hidden">');
//$modify_icons[] = $form->returnForm();
*/
$modify_icons[] = $html;
if($html == null) {
$a = $html;
}
}
return implode(PHP_EOL, $modify_icons);
}
@ -7058,4 +7124,210 @@ class DocumentManager
return $btn;
}
/**
* TODO: Escribe nuevo contenido en un archivo in borrarlo
*
* @param array $_course
* @param string $path Path stored in the database
* @param string $base_work_dir Path to the documents folder (if not defined, $documentId must be used)
* @param int $sessionId The ID of the session, if any
* @param int $documentId The document id, if available
* @param int $groupId iid
* @param file $file $_FILE content
*
* @return bool true/false
*
* @todo now only files/folders in a folder get visibility 2, we should rename them too.
* @todo We should be able to get rid of this later when using only documentId (check further usage)
*/
public static function writeContentIntoDocument(
$_course,
$path = null,
$base_work_dir = null,
$sessionId = null,
$documentId = null,
$groupId = 0,
$file
) {
$TABLE_DOCUMENT = Database::get_course_table(TABLE_DOCUMENT);
$documentId = (int) $documentId;
$groupId = (int) $groupId;
if (empty($groupId)) {
$groupId = api_get_group_id();
}
$sessionId = (int) $sessionId;
if (empty($sessionId)) {
$sessionId = api_get_session_id();
}
$course_id = $_course['real_id'];
if (empty($course_id)) {
return false;
}
if (empty($base_work_dir)) {
return false;
}
if (empty($documentId)) {
$documentId = self::get_document_id($_course, $path, $sessionId);
$docInfo = self::get_document_data_by_id(
$documentId,
$_course['code'],
false,
$sessionId
);
$path = $docInfo['path'];
} else {
$docInfo = self::get_document_data_by_id(
$documentId,
$_course['code'],
false,
$sessionId
);
if (empty($docInfo)) {
return false;
}
$path = $docInfo['path'];
}
if (empty($path) || empty($docInfo) || empty($documentId)) {
return false;
}
$itemInfo = api_get_item_property_info(
$_course['real_id'],
TOOL_DOCUMENT,
$documentId,
$sessionId,
$groupId
);
if (empty($itemInfo)) {
return false;
}
// File was already deleted.
if ($itemInfo['lastedit_type'] == 'DocumentReplaced' ||
$itemInfo['lastedit_type'] == 'replace' ||
$itemInfo['visibility'] == 2
) {
return false;
}
// Filtering by group.
if ($itemInfo['to_group_id'] != $groupId) {
return false;
}
$now = new DateTime();
$now = $now->format('Y_m_d__H_i_s_');
$document_exists_in_disk = file_exists($base_work_dir.$path);
$new_path = $path.'_REPLACED_DATE_'.$now.'_ID_'.$documentId;
$file_deleted_from_disk = false;
$file_deleted_from_disk = true;
$fileMoved = fale;
$file_renamed_from_disk = false;
if ($document_exists_in_disk) {
/*
if (api_get_setting('permanently_remove_deleted_files') === 'true') {
// Delete documents, do it like this so metadata gets deleted too
my_delete($base_work_dir.$path);
// Hard delete.
self::deleteDocumentFromDb($documentId, $_course, $sessionId, true);
$file_deleted_from_disk = true;
} else
*/{
// Set visibility to 2 and rename file/folder to xxx_DELETED_#id (soft delete)
if (is_file($base_work_dir.$path) || is_dir($base_work_dir.$path)) {
if (rename($base_work_dir.$path, $base_work_dir.$new_path)) {
/*
$new_path = Database::escape_string($new_path);
$sql = "UPDATE $TABLE_DOCUMENT
SET path = '".$new_path."'
WHERE
c_id = $course_id AND
session_id = $sessionId AND
id = ".$documentId;
Database::query($sql);
// Soft delete.
self::deleteDocumentFromDb($documentId, $_course, $sessionId);
// Change path of sub folders and documents in database.
$old_item_path = $docInfo['path'];
$new_item_path = $new_path.substr($old_item_path, strlen($path));
$new_item_path = Database::escape_string($new_item_path);
$sql = "UPDATE $TABLE_DOCUMENT
SET path = '".$new_item_path."'
WHERE
c_id = $course_id AND
session_id = $sessionId AND
id = ".$documentId;
Database::query($sql);
*/
$file_renamed_from_disk = true;
} else {
// Couldn't rename - file permissions problem?
error_log(
__FILE__.' '.__LINE__.': Error renaming '.$base_work_dir.$path.' to '.$base_work_dir.$new_path.'. This is probably due to file permissions',
0
);
}
}
if (move_uploaded_file($file['tmp_name'], $base_work_dir.$path)) {
$size = filesize($base_work_dir.$path);
$sql = "UPDATE $TABLE_DOCUMENT
SET size = '".$size."'
WHERE
c_id = $course_id AND
session_id = $sessionId AND
id = ".$documentId;
Database::query($sql);
$fileMoved = true;
}
}
}
// Checking inconsistency
//error_log('Doc status: (1 del db :'.($file_deleted_from_db?'yes':'no').') - (2 del disk: '.($file_deleted_from_disk?'yes':'no').') - (3 ren disk: '.($file_renamed_from_disk?'yes':'no').')');
if ( $file_deleted_from_disk ||
$file_renamed_from_disk
) {
return true;
} else {
//Something went wrong
//The file or directory isn't there anymore (on the filesystem)
// This means it has been removed externally. To prevent a
// blocking error from happening, we drop the related items from the
// item_property and the document table.
error_log(
__FILE__.' '.__LINE__.': System inconsistency detected. The file or directory '.$base_work_dir.$path.' seems to have been removed from the filesystem independently from the web platform. To restore consistency, the elements using the same path will be removed from the database',
0
);
return false;
}
}
}

@ -1,6 +1,38 @@
<html>
<head>
</head>
<body>
</body>
</html>
<div class="upload_element_${$randomUploadName}">
<div class="form-group " id="file_file">
<label class="col-sm-2 control-label" for="file_${$randomUploadName">
File
</label>
<div class="col-sm-8">
<input class="" name="file_${$randomUploadName}" style="width: 250px" type="file">
<p class="help-block">Maximum file size: 100M<br>Space Available: 85.88M</p>
</div>
<div class="col-sm-2"></div>
</div>
<div class="form-group ">
<label class="col-sm-2 control-label" for="upload_${$randomUploadName}_submitDocument">
</label>
<div class="col-sm-8">
<button class=" btn btn-primary " id="upload_${$randomUploadName}_submitDocument" name="submitDocument"
type="submit"><em class="fa fa-paper-plane"></em> Upload file
</button>
</div>
<div class="col-sm-2"></div>
</div>
<input class="currentFile" name="currentFile" type="hidden" value="3380a9c8e39c825215abc6eba516616c">
<input id="upload_${$randomUploadName}__qf__upload_${$randomUploadName}" name="_qf__upload_${$randomUploadName}"
type="hidden"
value="">
<input id="upload_${$randomUploadName}_id" name="id" type="hidden" value="2511">
<input id="upload_${$randomUploadName}_curdirpath" name="curdirpath" type="hidden" value="/HiJackThis.log">
<input id="upload_${$randomUploadName}_basename" name="basename" type="hidden" value="HiJackThis.log">
<input id="upload_${$randomUploadName}_action" name="action" type="hidden" value="replace">
<input id="upload_${$randomUploadName}_MAX_FILE_SIZE" name="MAX_FILE_SIZE" type="hidden" value="104857600">
</div>
Loading…
Cancel
Save