Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 87 additions & 23 deletions public/main/lp/learnpath.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -793,8 +793,23 @@ public function delete($courseInfo = null, $id = null, $delete = 'keep')

$course = api_get_course_entity();
$session = api_get_session_entity();
/* @var CLp $lp */
$lp = Container::getLpRepository()->find($this->lp_id);

// 1) Detach the asset to avoid FK constraint
$asset = $lp->getAsset();
if ($asset) {
$lp->setAsset(null);
$em = Database::getManager();
$em->persist($lp);
$em->flush();
}

// 2) Now delete the asset and its folder
if ($asset) {
Container::getAssetRepository()->delete($asset);
}

Database::getManager()
->getRepository(ResourceLink::class)
->removeByResourceInContext($lp, $course, $session);
Expand Down Expand Up @@ -7051,40 +7066,89 @@ public function copy()
);
}

/**
* Verify document size.
*
* @param string $s
*
* @return bool
*/
public static function verify_document_size($s)
public static function getQuotaInfo(string $localFilePath): array
{
$post_max = ini_get('post_max_size');
if ('M' == substr($post_max, -1, 1)) {
$post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024;
} elseif ('G' == substr($post_max, -1, 1)) {
$post_max = intval(substr($post_max, 0, -1)) * 1024 * 1024 * 1024;
$post_max_raw = ini_get('post_max_size');
$post_max_bytes = (int) rtrim($post_max_raw, 'MG') * (str_ends_with($post_max_raw,'G') ? 1024**3 : 1024**2);
$upload_max_raw = ini_get('upload_max_filesize');
$upload_max_bytes = (int) rtrim($upload_max_raw, 'MG') * (str_ends_with($upload_max_raw,'G') ? 1024**3 : 1024**2);

$em = Database::getManager();
$course = api_get_course_entity(api_get_course_int_id());

$nodes = Container::getResourceNodeRepository()->findByResourceTypeAndCourse('file', $course);
$root = null;
foreach ($nodes as $n) {
if ($n->getParent() === null) {
$root = $n; break;
}
}
$upl_max = ini_get('upload_max_filesize');
if ('M' == substr($upl_max, -1, 1)) {
$upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024;
} elseif ('G' == substr($upl_max, -1, 1)) {
$upl_max = intval(substr($upl_max, 0, -1)) * 1024 * 1024 * 1024;
$docsSize = $root
? Container::getDocumentRepository()->getFolderSize($root, $course)
: 0;

$assetRepo = Container::getAssetRepository();
$fs = $assetRepo->getFileSystem();
$scormSize = 0;
foreach (Container::getLpRepository()->findScormByCourse($course) as $lp) {
if ($asset = $lp->getAsset()) {
$folder = $assetRepo->getFolder($asset);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.zip files are detected as folders, apparently.

if ($folder && $fs->directoryExists($folder)) {
$scormSize += self::getFolderSize($folder);
}
}
}

$repo = Container::getDocumentRepository();
$documents_total_space = $repo->getTotalSpace(api_get_course_int_id());
$uploadedSize = filesize($localFilePath);
$existingTotal = $docsSize + $scormSize;
$combined = $existingTotal + $uploadedSize;

$quotaMb = DocumentManager::get_course_quota();
$quotaBytes = $quotaMb * 1024 * 1024;

$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 [
'post_max' => $post_max_bytes,
'upload_max' => $upload_max_bytes,
'docs_size' => $docsSize,
'scorm_size' => $scormSize,
'existing_total'=> $existingTotal,
'uploaded_size' => $uploadedSize,
'combined' => $combined,
'quota_bytes' => $quotaBytes,
];
}

/**
* Verify document size.
*/
public static function verify_document_size(string $localFilePath): bool
{
$info = self::getQuotaInfo($localFilePath);
if ($info['uploaded_size'] > $info['post_max']
|| $info['uploaded_size'] > $info['upload_max']
|| $info['combined'] > $info['quota_bytes']
) {
Container::getSession()->set('quota_info', $info);
return true;
}

return false;
}

private static function getFolderSize(string $path): int
{
$size = 0;
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS)
);
foreach ($iterator as $file) {
if ($file->isFile()) {
$size += $file->getSize();
}
}
return $size;
}

/**
* Clear LP prerequisites.
*/
Expand Down
78 changes: 34 additions & 44 deletions public/main/lp/lp_upload.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

/* For licensing terms, see /license.txt */

use Chamilo\CoreBundle\Helpers\ChamiloHelper;
use Chamilo\CourseBundle\Component\CourseCopy\CourseArchiver;
use Chamilo\CourseBundle\Component\CourseCopy\CourseRestorer;

Expand Down Expand Up @@ -29,56 +30,54 @@
* because if the file size exceed the maximum file upload
* size set in php.ini, all variables from POST are cleared !
*/
$user_file = $_GET['user_file'] ?? [];
$user_file = $user_file ? $user_file : [];
$is_error = $user_file['error'] ?? false;
$em = Database::getManager();
$user_file = $_FILES['user_file'] ?? [];
$is_error = $user_file['error'] ?? false;
$em = Database::getManager();

if (isset($_POST) && $is_error) {
Display::addFlash(
Display::return_message(get_lang('The file is too big to upload.'))
);

return false;
unset($_FILES['user_file']);
} elseif ('POST' === $_SERVER['REQUEST_METHOD'] && count($_FILES) > 0 && !empty($_FILES['user_file']['name'])) {
ChamiloHelper::redirectTo(api_get_path(WEB_PATH).'main/upload/index.php?'.api_get_cidreq().'&origin=course&curdirpath=/&tool=learnpath');
}
elseif ('POST' === $_SERVER['REQUEST_METHOD']
&& !empty($_FILES['user_file']['name'])
) {
// A file upload has been detected, now deal with the file...
// Directory creation.
$stopping_error = false;
$s = $_FILES['user_file']['name'];

// Get name of the zip file without the extension.
$info = pathinfo($s);
$filename = $info['basename'];
$extension = $info['extension'];
$info = pathinfo($s);
$filename = $info['basename'];
$extension = $info['extension'];
$file_base_name = str_replace('.'.$extension, '', $filename);

$new_dir = api_replace_dangerous_char(trim($file_base_name));
$type = learnpath::getPackageType($_FILES['user_file']['tmp_name'], $_FILES['user_file']['name']);

$proximity = 'local';
if (!empty($_REQUEST['content_proximity'])) {
$proximity = $_REQUEST['content_proximity'];
}
$type = learnpath::getPackageType(
$_FILES['user_file']['tmp_name'],
$_FILES['user_file']['name']
);

$maker = 'Scorm';
if (!empty($_REQUEST['content_maker'])) {
$maker = $_REQUEST['content_maker'];
}
// Defaults
$proximity = $_REQUEST['content_proximity'] ?? 'local';
$maker = $_REQUEST['content_maker'] ?? 'Scorm';

switch ($type) {
case 'chamilo':
$filename = CourseArchiver::importUploadedFile($_FILES['user_file']['tmp_name']);
if ($filename) {
$course = CourseArchiver::readCourse($filename, false);
$course = CourseArchiver::readCourse($filename, false);
$courseRestorer = new CourseRestorer($course);
// FILE_SKIP, FILE_RENAME or FILE_OVERWRITE
$courseRestorer->set_file_option(FILE_OVERWRITE);
$courseRestorer->restore('', api_get_session_id());
Display::addFlash(Display::return_message(get_lang('File upload succeeded!')));
}
break;
case 'scorm':
$tmpFile = $_FILES['user_file']['tmp_name'];
$fileSize = filesize($tmpFile);
$blocked = learnpath::verify_document_size($tmpFile);
if ($blocked) {
ChamiloHelper::redirectTo(api_get_path(WEB_PATH).'main/upload/index.php?'.api_get_cidreq().'&origin=course&curdirpath=/&tool=learnpath');
}
$scorm = new scorm();
$scorm->import_package(
$_FILES['user_file'],
Expand All @@ -92,10 +91,8 @@
$scorm->parse_manifest();
$lp = $scorm->import_manifest(api_get_course_int_id(), $_REQUEST['use_max_score']);
if ($lp) {
$lp
->setContentLocal($proximity)
->setContentMaker($maker)
;
$lp->setContentLocal($proximity)
->setContentMaker($maker);
$em->persist($lp);
$em->flush();
Display::addFlash(Display::return_message(get_lang('File upload succeeded!')));
Expand All @@ -104,31 +101,25 @@
break;
case 'aicc':
$oAICC = new aicc();
//$entity = $oAICC->getEntity();
$config_dir = $oAICC->import_package($_FILES['user_file']);
if (!empty($config_dir)) {
$oAICC->parse_config_files($config_dir);
$oAICC->import_aicc(api_get_course_id());
Display::addFlash(Display::return_message(get_lang('File upload succeeded!')));
}
/*$entity
->setContentLocal($proximity)
->setContentMaker($maker)
->setJsLib('aicc_api.php')
;
$em->persist($entity);
$em->flush();*/
break;
case 'oogie':
$take_slide_name = empty($_POST['take_slide_name']) ? false : true;
$take_slide_name = !empty($_POST['take_slide_name']);
$o_ppt = new OpenofficePresentation($take_slide_name);
$first_item_id = $o_ppt->convert_document($_FILES['user_file'], 'make_lp', $_POST['slide_size']);
$o_ppt->convert_document($_FILES['user_file'], 'make_lp', $_POST['slide_size']);
Display::addFlash(Display::return_message(get_lang('File upload succeeded!')));
break;
case 'woogie':
$split_steps = empty($_POST['split_steps']) || 'per_page' === $_POST['split_steps'] ? 'per_page' : 'per_chapter';
$split_steps = (!empty($_POST['split_steps']) && $_POST['split_steps'] === 'per_chapter')
? 'per_chapter'
: 'per_page';
$o_doc = new OpenofficeText($split_steps);
$first_item_id = $o_doc->convert_document($_FILES['user_file']);
$o_doc->convert_document($_FILES['user_file']);
Display::addFlash(Display::return_message(get_lang('File upload succeeded!')));
break;
case '':
Expand Down Expand Up @@ -235,6 +226,5 @@
);

return false;
break;
}
}
14 changes: 14 additions & 0 deletions public/main/upload/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,20 @@ function check_unzip() {
'normal',
false
);

$quotaInfo = Session::read('quota_info');
if (!empty($quotaInfo)) {
$msg = sprintf(
"Upload failed: file %d bytes, PHP post_max=%d, upload_max=%d, total after upload=%d, quota=%d",
$quotaInfo['uploaded_size'],
$quotaInfo['post_max'],
$quotaInfo['upload_max'],
$quotaInfo['combined'],
$quotaInfo['quota_bytes']
);
echo Display::return_message(htmlentities($msg), 'error');
Session::erase('quota_info');
}
$form->display();

Display::display_footer();
22 changes: 19 additions & 3 deletions src/CoreBundle/Repository/AssetRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -161,11 +161,27 @@ public function update(Asset $asset): void
$this->getEntityManager()->flush();
}

/**
* Deletes an Asset from the database.
* If it is a SCORM package, first removes its extracted folder on disk.
*/
public function delete(?Asset $asset = null): void
{
if (null !== $asset) {
$this->getEntityManager()->remove($asset);
$this->getEntityManager()->flush();
if (null === $asset) {
return;
}

// If this is a SCORM package, delete its directory and all its contents
if (Asset::SCORM === $asset->getCategory()) {
$folder = $this->getFolder($asset); // e.g. "/scorm/MyScormPackage/"
if ($folder && $this->filesystem->directoryExists($folder)) {
$this->filesystem->deleteDirectory($folder);
}
}

// Remove the asset record from the database
$em = $this->getEntityManager();
$em->remove($asset);
$em->flush();
}
}
15 changes: 15 additions & 0 deletions src/CourseBundle/Repository/CLpRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,21 @@ public function getLpSessionId(int $lpId): ?int
return null;
}

public function findScormByCourse(Course $course): array
{
return $this->createQueryBuilder('lp')
->innerJoin('lp.resourceNode', 'rn')
->innerJoin('rn.resourceLinks', 'rl')
->andWhere('rl.course = :course')
->andWhere('lp.lpType = :scormType')
->setParameters([
'course' => $course,
'scormType' => CLp::SCORM_TYPE
])
->getQuery()
->getResult();
}

public function lastProgressForUser(iterable $lps, User $user, ?Session $session): array
{
$lpIds = [];
Expand Down
Loading