Remove unused/legacy documents code

pull/3924/head
Julio Montoya 4 years ago
parent cd0b9b0d5b
commit bbdf875b11
  1. 5
      public/main/inc/ajax/session.ajax.php
  2. 353
      public/main/inc/lib/document.lib.php
  3. 182
      public/main/inc/lib/fileManage.lib.php
  4. 171
      public/main/inc/lib/fileUpload.lib.php
  5. 22
      public/main/inc/lib/pdf.lib.php
  6. 5
      public/main/inc/lib/webservices/Rest.php

@ -289,7 +289,7 @@ switch ($action) {
$http_www = api_get_path(WEB_COURSE_PATH).$courseInfo['directory'].'/document';
$documentAndFolders = DocumentManager::getAllDocumentData(
/*$documentAndFolders = DocumentManager::getAllDocumentData(
$courseInfo,
$folderName,
0,
@ -297,7 +297,8 @@ switch ($action) {
false,
false,
$session->getId()
);
);*/
$documentAndFolders = [];
$documentAndFolders = array_filter(
$documentAndFolders,

@ -518,183 +518,6 @@ class DocumentManager
return $condition;
}
/**
* Fetches all document data for the given user/group.
*
* @param array $courseInfo
* @param string $path
* @param int $toGroupId iid
* @param int $toUserId
* @param bool $canSeeInvisible
* @param bool $search
* @param int $sessionId
*
* @return array with all document data
*/
public static function getAllDocumentData(
$courseInfo,
$path = '/',
$toGroupId = 0,
$toUserId = null,
$canSeeInvisible = false,
$search = false,
$sessionId = 0,
User $currentUser = null
) {
if (empty($courseInfo)) {
return [];
}
$tblDocument = Database::get_course_table(TABLE_DOCUMENT);
$currentUser = $currentUser ?: api_get_current_user();
// Escape underscores in the path so they don't act as a wildcard
$originalPath = $path;
$path = str_replace('_', '\_', $path);
// The given path will not end with a slash, unless it's the root '/'
// so no root -> add slash
$addedSlash = '/' == $path ? '' : '/';
$sharedCondition = null;
if ('/shared_folder' == $originalPath) {
$students = CourseManager::get_user_list_from_course_code($courseInfo['code'], $sessionId);
if (!empty($students)) {
$conditionList = [];
foreach ($students as $studentInfo) {
$conditionList[] = '/shared_folder/sf_user_'.$studentInfo['user_id'];
}
$sharedCondition .= ' AND docs.path IN ("'.implode('","', $conditionList).'")';
}
}
$sql = "SELECT
docs.iid,
docs.filetype,
docs.path,
docs.title,
docs.comment,
docs.size,
docs.readonly,
docs.session_id,
creator_id,
visibility,
n.updated_at,
n.created_at,
n.creator_id
FROM resource_node AS n
INNER JOIN $tblDocument AS docs
ON (docs.resource_node_id = n.id)
INNER JOIN resource_link l
ON (l.resource_node_id = n.id)
WHERE
l.c_id = {$courseInfo['real_id']} AND
n.path LIKE '".Database::escape_string($path.$addedSlash.'%')."' AND
n.path NOT LIKE '".Database::escape_string($path.$addedSlash.'%/%')."' AND
l.visibility NOT IN ('".ResourceLink::VISIBILITY_DELETED."')
$sharedCondition
";
//$userGroupFilter AND
//$conditionSession
$result = Database::query($sql);
$documentData = [];
$isAllowedToEdit = api_is_allowed_to_edit(null, true);
$isCoach = api_is_coach();
if (false !== $result && 0 != Database::num_rows($result)) {
$rows = [];
$hideInvisibleDocuments = api_get_configuration_value('hide_invisible_course_documents_in_sessions');
while ($row = Database::fetch_array($result, 'ASSOC')) {
if (isset($rows[$row['id']])) {
continue;
}
// If we are in session and hide_invisible_course_documents_in_sessions is enabled
// Then we avoid the documents that have visibility in session but that they come from a base course
/*if ($hideInvisibleDocuments && $sessionId) {
if ($row['item_property_session_id'] == $sessionId && empty($row['session_id'])) {
continue;
}
}*/
if (self::isBasicCourseFolder($row['path'], $sessionId)) {
$basicCourseDocumentsContent = self::getAllDocumentData(
$courseInfo,
$row['path']
);
if (empty($basicCourseDocumentsContent)) {
continue;
}
}
$rows[$row['id']] = $row;
}
// If we are in session and hide_invisible_course_documents_in_sessions is enabled
// Or if we are students
// Then don't list the invisible or deleted documents
if (($sessionId && $hideInvisibleDocuments) || (!$isCoach && !$isAllowedToEdit)) {
$rows = array_filter($rows, function ($row) {
if (in_array(
$row['visibility'],
[
ResourceLink::VISIBILITY_DELETED,
ResourceLink::VISIBILITY_DRAFT,
]
)) {
return false;
}
return true;
});
}
foreach ($rows as $row) {
if ('file' == $row['filetype'] &&
'html' == pathinfo($row['path'], PATHINFO_EXTENSION)
) {
// Templates management
$tblTemplate = Database::get_main_table(TABLE_MAIN_TEMPLATES);
$sql = "SELECT id FROM $tblTemplate
WHERE
c_id = '".$courseInfo['real_id']."' AND
user_id = '".$currentUser->getId()."' AND
ref_doc = '".$row['id']."'";
$templateResult = Database::query($sql);
$row['is_template'] = (Database::num_rows($templateResult) > 0) ? 1 : 0;
}
$row['basename'] = basename($row['path']);
// Just filling $document_data.
$documentData[$row['id']] = $row;
}
// Only for the student we filter the results see BT#1652
if (!$isCoach && !$isAllowedToEdit) {
// Checking parents visibility.
$finalDocumentData = [];
foreach ($documentData as $row) {
$isVisible = self::check_visibility_tree(
$row['id'],
$courseInfo,
$sessionId,
$currentUser->getId(),
$toGroupId
);
if ($isVisible) {
$finalDocumentData[$row['id']] = $row;
}
}
} else {
$finalDocumentData = $documentData;
}
return $finalDocumentData;
}
return [];
}
/**
* Gets the paths of all folders in a course
* can show all folders (except for the deleted ones) or only visible ones.
@ -3281,168 +3104,6 @@ class DocumentManager
return $defaultVisibility;
}
/**
* @param string $filePath
* @param string $path
* @param array $courseInfo
* @param int $sessionId
* @param string $whatIfFileExists overwrite|rename
* @param int $userId
* @param int $groupId
* @param int $toUserId
* @param string $comment
*
* @return bool|path
*/
public static function addFileToDocumentTool(
$filePath,
$path,
$courseInfo,
$sessionId,
$userId,
$whatIfFileExists = 'overwrite',
$groupId = null,
$toUserId = null,
$comment = null
) {
if (!file_exists($filePath)) {
return false;
}
$fileInfo = pathinfo($filePath);
$file = [
'name' => $fileInfo['basename'],
'tmp_name' => $filePath,
'size' => filesize($filePath),
'from_file' => true,
];
$course_dir = $courseInfo['path'].'/document';
$baseWorkDir = api_get_path(SYS_COURSE_PATH).$course_dir;
$filePath = handle_uploaded_document(
$courseInfo,
$file,
$baseWorkDir,
$path,
$userId,
$groupId,
$toUserId,
false,
$whatIfFileExists,
false,
false,
$comment,
$sessionId
);
if ($filePath) {
return self::get_document_id(
$courseInfo,
$filePath,
$sessionId
);
}
return false;
}
/**
* Converts wav to mp3 file.
* Requires the ffmpeg lib. In ubuntu: sudo apt-get install ffmpeg.
*
* @param string $wavFile
* @param bool $removeWavFileIfSuccess
*
* @return bool
*/
public static function convertWavToMp3($wavFile, $removeWavFileIfSuccess = false)
{
if (file_exists($wavFile)) {
try {
$ffmpeg = \FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($wavFile);
$mp3File = str_replace('wav', 'mp3', $wavFile);
$result = $video->save(new FFMpeg\Format\Audio\Mp3(), $mp3File);
if ($result && $removeWavFileIfSuccess) {
unlink($wavFile);
}
if (file_exists($mp3File)) {
return $mp3File;
}
} catch (Exception $e) {
error_log($e->getMessage());
error_log($e->getPrevious()->getMessage());
}
}
return false;
}
/**
* @param string $documentData wav document information
* @param array $courseInfo
* @param int $sessionId
* @param int $userId user that adds the document
* @param string $whatIfFileExists
* @param bool $deleteWavFile
*
* @return bool
*/
public static function addAndConvertWavToMp3(
$documentData,
$courseInfo,
$sessionId,
$userId,
$whatIfFileExists = 'overwrite',
$deleteWavFile = false
) {
if (empty($documentData)) {
return false;
}
if (isset($documentData['absolute_path']) &&
file_exists($documentData['absolute_path'])
) {
$mp3FilePath = self::convertWavToMp3($documentData['absolute_path']);
if (!empty($mp3FilePath) && file_exists($mp3FilePath)) {
$documentId = self::addFileToDocumentTool(
$mp3FilePath,
dirname($documentData['path']),
$courseInfo,
$sessionId,
$userId,
$whatIfFileExists,
null,
null,
$documentData['comment']
);
if (!empty($documentId)) {
if ($deleteWavFile) {
$coursePath = $courseInfo['directory'].'/document';
$documentPath = api_get_path(SYS_COURSE_PATH).$coursePath;
self::delete_document(
$courseInfo,
null,
$documentPath,
$sessionId,
$documentData['id']
);
}
return $documentId;
}
}
}
return false;
}
/**
* @param array $_course
*
@ -4053,12 +3714,12 @@ This folder contains all sessions that have been opened in the chat. Although th
}
$userEntity = api_get_user_entity($userId);
if (empty($userEntity)) {
if (null === $userEntity) {
return false;
}
$courseEntity = api_get_course_entity($courseInfo['real_id']);
if (empty($courseEntity)) {
if (null === $courseEntity) {
return false;
}
@ -4099,8 +3760,7 @@ This folder contains all sessions that have been opened in the chat. Although th
// }
// is updated using the title
$document = new CDocument();
$document
$document = (new CDocument())
->setFiletype($fileType)
->setTitle($title)
->setComment($comment)
@ -4112,9 +3772,14 @@ This folder contains all sessions that have been opened in the chat. Although th
$em = Database::getManager();
$em->persist($document);
$em->flush();
$repo = Container::getDocumentRepository();
if (!empty($content)) {
$repo = Container::getDocumentRepository();
$repo->addFileFromString($document, $title, 'text/html', $content, true);
} else {
if (!empty($realPath) && !is_dir($realPath) && file_exists($realPath)) {
$repo->addFileFromPath($document, $title, $realPath);
}
}
if ($document) {

@ -3,69 +3,6 @@
use Symfony\Component\Filesystem\Filesystem;
/**
* This is the file manage library for Chamilo.
* Include/require it in your code to use its functionality.
*/
/**
* Cheks a file or a directory actually exist at this location.
*
* @author Hugues Peeters <peeters@ipm.ucl.ac.be>
*
* @param string $file_path Path of the presume existing file or dir
*
* @return bool TRUE if the file or the directory exists or FALSE otherwise
*/
function check_name_exist($file_path)
{
clearstatcache();
$save_dir = getcwd();
if (!is_dir(dirname($file_path))) {
return false;
}
chdir(dirname($file_path));
$file_name = basename($file_path);
if (file_exists($file_name)) {
chdir($save_dir);
return true;
} else {
chdir($save_dir);
return false;
}
}
/**
* Deletes a file or a directory.
*
* @author - Hugues Peeters
*
* @param $file (String) - the path of file or directory to delete
*
* @return bool - true if the delete succeed, false otherwise
*
* @see - delete() uses check_name_exist() and removeDir() functions
*/
function my_delete($file)
{
if (check_name_exist($file)) {
if (is_file($file)) { // FILE CASE
unlink($file);
return true;
} elseif (is_dir($file)) { // DIRECTORY CASE
removeDir($file);
return true;
}
}
return false; // no file or directory to delete
}
/**
* Removes a directory recursively.
*
@ -105,86 +42,6 @@ function removeDir($dir)
return true;
}
/**
* Moves a file or a directory to an other area.
*
* @author Hugues Peeters <peeters@ipm.ucl.ac.be>
*
* @param string $source the path of file or directory to move
* @param string $target the path of the new area
* @param bool $forceMove Whether to force a move or to make a copy (safer but slower) and then delete the original
* @param bool $moveContent In some cases (including migrations), we need to move the *content* and not the folder itself
*
* @return bool true if the move succeed, false otherwise
*
* @see move() uses check_name_exist() and copyDirTo() functions
*/
function move($source, $target, $forceMove = true, $moveContent = false)
{
$target = realpath($target); // remove trailing slash
$source = realpath($source);
if (check_name_exist($source)) {
$file_name = basename($source);
// move onto self illegal: mv a/b/c a/b/c or mv a/b/c a/b
if (0 === strcasecmp($target, dirname($source))) {
return false;
}
$isWindowsOS = api_is_windows_os();
$canExec = function_exists('exec');
/* File case */
if (is_file($source)) {
if ($forceMove) {
if (!$isWindowsOS && $canExec) {
exec('mv '.$source.' '.$target.'/'.$file_name);
} else {
// Try copying
copy($source, $target.'/'.$file_name);
unlink($source);
}
} else {
copy($source, $target.'/'.$file_name);
unlink($source);
}
return true;
} elseif (is_dir($source)) {
// move dir down will cause loop: mv a/b/ a/b/c/ not legal
if (0 == strncasecmp($target, $source, strlen($source))) {
return false;
}
/* Directory */
if ($forceMove && !$isWindowsOS && $canExec) {
if ($moveContent) {
$base = basename($source);
$out = [];
$retVal = -1;
exec('mv '.$source.'/* '.$target.'/'.$base, $out, $retVal);
if (0 !== $retVal) {
return false; // mv should return 0 on success
}
exec('rm -rf '.$source);
} else {
$out = [];
$retVal = -1;
exec("mv $source $target", $out, $retVal);
if (0 !== $retVal) {
error_log("Chamilo error fileManage.lib.php: mv $source $target\n");
return false; // mv should return 0 on success
}
}
} else {
return copyDirTo($source, $target);
}
return true;
}
}
return false;
}
/**
* Moves a directory and its content to an other area.
*
@ -215,45 +72,6 @@ function copyDirTo($source, $destination, $move = true)
return true;
}
/**
* Copy a directory and its directories (not files) to an other area.
*
* @param string $source the path of the directory to move
* @param string $destination the path of the new area
*
* @return bool false on error
*/
function copyDirWithoutFilesTo($source, $destination)
{
$fs = new Filesystem();
if (!is_dir($source)) {
return false;
}
if (!$fs->exists($destination)) {
$fs->mkdir($destination);
}
$dirIterator = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($dirIterator, RecursiveIteratorIterator::SELF_FIRST);
/** @var \SplFileInfo $item */
foreach ($iterator as $item) {
if ($item->isFile()) {
continue;
}
$newDir = $destination.'/'.$item->getFilename();
if (!$fs->exists($newDir)) {
$fs->mkdir($destination.'/'.$item->getFilename());
}
}
return true;
}
/**
* Get a list of all PHP (.php) files in a given directory. Includes .tpl files.
*

@ -1286,174 +1286,3 @@ function create_unexisting_directory(
return false;
}
/**
* This recursive function can be used during the upgrade process form older
* versions of Chamilo
* It crawls the given directory, checks if the file is in the DB and adds
* it if it's not.
*
* @param array $courseInfo
* @param array $userInfo
* @param string $base_work_dir course document dir
* @param string $folderPath folder to read
* @param int $sessionId
* @param int $groupId group.id
* @param bool $output
* @param array $parent
* @param string $whatIfFileExists
*
* @return bool
*/
function add_all_documents_in_folder_to_database(
$courseInfo,
$userInfo,
$base_work_dir,
$folderPath,
$sessionId = 0,
$groupId = 0,
$output = false,
$parent = [],
$whatIfFileExists = 'overwrite'
) {
if (empty($userInfo) || empty($courseInfo)) {
return false;
}
$userId = $userInfo['user_id'];
// Open dir
$handle = opendir($folderPath);
if (is_dir($folderPath)) {
// Run trough
while ($file = readdir($handle)) {
if ('.' == $file || '..' == $file) {
continue;
}
$parentPath = '';
if (!empty($parent) && isset($parent['path'])) {
$parentPath = $parent['path'];
if ('/' == $parentPath) {
$parentPath = '';
}
}
$completePath = $parentPath.'/'.$file;
$sysFolderPath = $folderPath.'/'.$file;
// Is directory?
if (is_dir($sysFolderPath)) {
$folderExists = DocumentManager::folderExists(
$completePath,
$courseInfo,
$sessionId,
$groupId
);
if (true === $folderExists) {
switch ($whatIfFileExists) {
case 'overwrite':
$documentId = DocumentManager::get_document_id($courseInfo, $completePath, $sessionId);
if ($documentId) {
$newFolderData = DocumentManager::get_document_data_by_id(
$documentId,
$courseInfo['code'],
false,
$sessionId
);
}
break;
case 'rename':
$newFolderData = create_unexisting_directory(
$courseInfo,
$userId,
$sessionId,
$groupId,
null,
$base_work_dir,
$completePath,
null,
null,
true
);
break;
case 'nothing':
if ($output) {
$documentId = DocumentManager::get_document_id($courseInfo, $completePath, $sessionId);
if ($documentId) {
$folderData = DocumentManager::get_document_data_by_id(
$documentId,
$courseInfo['code'],
false,
$sessionId
);
Display::addFlash(
Display::return_message(
$folderData['path'].' '.get_lang(' already exists.'),
'warning'
)
);
}
}
continue 2;
break;
}
} else {
$newFolderData = create_unexisting_directory(
$courseInfo,
$userId,
$sessionId,
$groupId,
null,
$base_work_dir,
$completePath,
null,
null,
false
);
}
// Recursive
add_all_documents_in_folder_to_database(
$courseInfo,
$userInfo,
$base_work_dir,
$sysFolderPath,
$sessionId,
$groupId,
$output,
$newFolderData,
$whatIfFileExists
);
} else {
// Rename
$uploadedFile = [
'name' => $file,
'tmp_name' => $sysFolderPath,
'size' => filesize($sysFolderPath),
'type' => null,
'from_file' => true,
'move_file' => true,
];
handle_uploaded_document(
$courseInfo,
$uploadedFile,
$base_work_dir,
$parentPath,
$userId,
$groupId,
null,
0,
$whatIfFileExists,
$output,
false,
null,
$sessionId
);
}
}
}
}

@ -801,7 +801,7 @@ class PDF
*
* @return string The PDF path
*/
public function exportFromHtmlToFile($html, $fileName, $dest = null)
public function exportFromHtmlToFile($html, $fileName)
{
$this->template = $this->template ?: new Template('', false, false, false, false, false, false);
@ -819,13 +819,7 @@ class PDF
'F'
);
if (!$dest) {
return $pdfPath;
}
move($pdfPath, $dest);
return $dest.basename($pdfPath);
return $pdfPath;
}
/**
@ -844,17 +838,15 @@ class PDF
) {
$userId = api_get_user_id();
$courseInfo = api_get_course_info_by_id($courseId);
$courseDirectory = api_get_path(SYS_COURSE_PATH).$courseInfo['directory'].'/document/';
$docPath = $this->exportFromHtmlToFile(
$htmlContent,
$fileName,
$courseDirectory
$fileName
);
DocumentManager::addDocument(
$courseInfo,
str_replace($courseDirectory, '/', $docPath),
'',
'file',
filesize($docPath),
$fileName,
@ -863,7 +855,11 @@ class PDF
true,
null,
$sessionId,
$userId
$userId,
false,
'',
null,
$docPath
);
Display::addFlash(Display::return_message(get_lang('Item added')));

@ -407,7 +407,7 @@ class Rest extends WebService
}
$courseInfo = api_get_course_info_by_id($this->course->getId());
$documents = DocumentManager::getAllDocumentData(
/*$documents = DocumentManager::getAllDocumentData(
$courseInfo,
$path,
0,
@ -415,7 +415,8 @@ class Rest extends WebService
false,
false,
$sessionId
);
);*/
$documents = [];
$results = [];
if (!empty($documents)) {

Loading…
Cancel
Save