Skip to content

Learnpath: Add support for selective LP item PDF export - refs #2969 #6222

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
38 changes: 38 additions & 0 deletions public/main/inc/ajax/lp.ajax.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,44 @@
$sessionId = api_get_session_id();

switch ($action) {
case 'get_lp_export_items':
$lpItems = [];
if ($lp) {
$items = learnpath::get_flat_ordered_items_list($lp);
$lpItemRepo = Container::getLpItemRepository();
$documentRepo = Container::getDocumentRepository();
foreach ($items as $itemId) {
$item = $lpItemRepo->find($itemId);

if ('document' !== $item->getItemType()) {
continue;
}

$document = $documentRepo->find((int) $item->getPath());
if (!$document instanceof CDocument) {
continue;
}

// Only export if it's a valid HTML file
try {
$content = $documentRepo->getResourceFileContent($document);
if (!is_string($content) || !preg_match('/^\s*<(?!!--|!doctype|html|body)/i', $content)) {
continue;
}

$lpItems[] = [
'id' => $item->getIid(),
'title' => $item->getTitle(),
];
} catch (\Throwable $e) {
// Skip silently
}
}
}

header('Content-Type: application/json');
echo json_encode(['items' => $lpItems]);
exit;
case 'get_lp_list_by_course':
$course_id = (isset($_GET['course_id']) && !empty($_GET['course_id'])) ? (int) $_GET['course_id'] : 0;
$session_id = (isset($_GET['session_id']) && !empty($_GET['session_id'])) ? (int) $_GET['session_id'] : 0;
Expand Down
90 changes: 37 additions & 53 deletions public/main/inc/lib/pdf.lib.php
Original file line number Diff line number Diff line change
Expand Up @@ -243,46 +243,45 @@ public function html_to_pdf(

$counter = 1;
foreach ($htmlFileArray as $file) {
//Add a page break per file
$pageBreak = '<pagebreak>';
if ($counter == count($htmlFileArray)) {
$pageBreak = '';
}

//if the array provided contained subarrays with 'title' entry,
// then print the title in the PDF
if (is_array($file) && isset($file['title'])) {
$htmlTitle = $file['title'];
$file = $file['path'];
$pageBreak = ($counter === count($htmlFileArray)) ? '' : '<pagebreak>';
$htmlTitle = '';
$filePath = null;
$content = null;

if (is_array($file)) {
$htmlTitle = $file['title'] ?? '';
$content = $file['content'] ?? null;
$filePath = $file['path'] ?? null;
} else {
//we suppose we've only been sent a file path
$filePath = $file;
$htmlTitle = basename($file);
}

$counter++;
if ($counter === 1 && !empty($mainTitle)) {
$this->pdf->WriteHTML('<html><body><h2 style="text-align: center">'.$mainTitle.'</h2></body></html>');
}

if (empty($file) && !empty($htmlTitle)) {
// this is a chapter, print title & skip the rest
if (2 === $counter && !empty($mainTitle)) {
$this->pdf->WriteHTML(
'<html><body><h2 style="text-align: center">'.$mainTitle.'</h2></body></html>'
);
}
if ($printTitle) {
$this->pdf->WriteHTML(
'<html><body><h3>'.$htmlTitle.'</h3></body></html>'.$pageBreak
);
// New support for direct HTML content
if (!empty($content)) {
if ($printTitle && !empty($htmlTitle)) {
$this->pdf->WriteHTML('<html><body><h3>'.$htmlTitle.'</h3></body></html>', 2);
}
$this->pdf->WriteHTML($content.$pageBreak, 2);
$counter++;
continue;
} else {
if (2 === $counter && !empty($mainTitle)) {
$this->pdf->WriteHTML(
'<html><body><h2 style="text-align: center">'.$mainTitle.'</h2></body></html>'
);
}

// Original logic for physical files
if (empty($filePath)) {
if ($printTitle && !empty($htmlTitle)) {
$this->pdf->WriteHTML('<html><body><h3>'.$htmlTitle.'</h3></body></html>'.$pageBreak);
}
$counter++;
continue;
}

if (!file_exists($file)) {
if (!file_exists($filePath)) {
$counter++;
continue;
}

Expand All @@ -292,28 +291,21 @@ public function html_to_pdf(
$this->pdf->WriteHTML($css, 1);
}

//it's not a chapter but the file exists, print its title
if ($printTitle) {
if ($printTitle && !empty($htmlTitle)) {
$this->pdf->WriteHTML('<html><body><h3>'.$htmlTitle.'</h3></body></html>', 2);
}

$file_info = pathinfo($file);
$file_info = pathinfo($filePath);
$extension = $file_info['extension'];

if (in_array($extension, ['html', 'htm'])) {
$dirName = $file_info['dirname'];
$filename = $file_info['basename'];
$filename = str_replace('_', ' ', $filename);

if ('html' === $extension) {
$filename = basename($filename, '.html');
} elseif ('htm' === $extension) {
$filename = basename($filename, '.htm');
}
$filename = str_replace('_', ' ', $file_info['basename']);
$filename = basename($filename, '.'.$extension);

$webPath = api_get_path(WEB_PATH);

$documentHtml = @file_get_contents($file);
$documentHtml = @file_get_contents($filePath);
$documentHtml = preg_replace($clean_search, '', $documentHtml);

$crawler = new Crawler($documentHtml);
Expand Down Expand Up @@ -342,25 +334,17 @@ public function html_to_pdf(
);
}

//$documentHtml = self::fixImagesPaths($documentHtml, $courseInfo, $dirName);
// The library mPDF expects UTF-8 encoded input data.
api_set_encoding_html($documentHtml, 'UTF-8');
// TODO: Maybe it is better idea the title to be passed through
$title = api_get_title_html($documentHtml, 'UTF-8', 'UTF-8');
// $_GET[] too, as it is done with file name.
// At the moment the title is retrieved from the html document itself.
if (empty($title)) {
$title = $filename; // Here file name is expected to contain ASCII symbols only.
}

if (!empty($documentHtml)) {
$this->pdf->WriteHTML($documentHtml.$pageBreak, 2);
}
} elseif (in_array($extension, ['jpg', 'jpeg', 'png', 'gif'])) {
// Images
$image = Display::img($file);
$image = Display::img($filePath);
$this->pdf->WriteHTML('<html><body>'.$image.'</body></html>'.$pageBreak, 2);
}

$counter++;
}

$outputFile = 'pdf_'.api_get_local_time().'.pdf';
Expand Down
146 changes: 79 additions & 67 deletions public/main/lp/ScormExport.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
/* For licensing terms, see /license.txt */

use Chamilo\CoreBundle\Framework\Container;
use Chamilo\CourseBundle\Entity\CDocument;
use Chamilo\CourseBundle\Entity\CLp;
use Chamilo\CourseBundle\Entity\CLpItem;
use Symfony\Component\Filesystem\Filesystem;
Expand Down Expand Up @@ -1002,84 +1003,95 @@ public static function export(learnpath $lp)
DocumentManager::file_send_for_download($temp_zip_file, true, $name);
}

public static function exportToPdf($lp_id, $courseInfo)
/**
* Export selected learning path items to a PDF.
*/
public static function exportToPdf(int $lpId, array $courseInfo, array $selectedItems = []): ?bool
{
// @todo fix exportToPdf
$lp_id = (int) $lp_id;
/** @var CLp $lp */
$lp = Container::getLpRepository()->find($lp_id);
$lp = Container::getLpRepository()->find($lpId);
if (!$lp || empty($courseInfo)) {
return false;
}

$lpItemRepo = Container::getLpItemRepository();
$documentRepo = Container::getDocumentRepository();
$filesToExport = [];
$courseCode = $courseInfo['code'];
$scormPath = null;

$files_to_export = [];
$orderedItemIds = learnpath::get_flat_ordered_items_list($lp);

$sessionId = api_get_session_id();
$courseCode = $courseInfo['code'];
$scorm_path = null;

if (!empty($courseInfo)) {
//$scorm_path = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/scorm/'.$this->path;
$list = learnpath::get_flat_ordered_items_list($lp);
if (!empty($list)) {
foreach ($list as $item_id) {
/** @var CLpItem $item */
$item = $lpItemRepo->find($item_id);
$type = $item->getItemType();
switch ($type) {
case 'document':
// Getting documents from a LP with chamilo documents
$file_data = DocumentManager::get_document_data_by_id($item->getPath(), $courseCode);
// Try loading document from the base course.
if (empty($file_data) && !empty($sessionId)) {
$file_data = DocumentManager::get_document_data_by_id(
$item->getPath(),
$courseCode,
false,
0
);
}
$file_path = api_get_path(SYS_COURSE_PATH).$courseCode['path'].'/document'.$file_data['path'];
if (file_exists($file_path)) {
$files_to_export[] = [
'title' => $item->get_title(),
'path' => $file_path,
];
}
break;
case 'asset': //commes from a scorm package generated by chamilo
case 'sco':
$file_path = $scorm_path.'/'.$item->getPath();
if (file_exists($file_path)) {
$files_to_export[] = [
'title' => $item->get_title(),
'path' => $file_path,
];
}
break;
case 'dir':
$files_to_export[] = [
'title' => $item->get_title(),
'path' => null,
];
foreach ($orderedItemIds as $itemId) {
if (!empty($selectedItems) && !in_array($itemId, $selectedItems)) {
continue;
}

/** @var CLpItem $item */
$item = $lpItemRepo->find($itemId);
$type = $item->getItemType();

switch ($type) {
case 'document':
$document = $documentRepo->find((int) $item->getPath());
if (!$document instanceof CDocument) {
break;
}

$fileType = $document->getFiletype();
$resourceNode = $document->getResourceNode();

if ($fileType !== 'file' || !$resourceNode->hasResourceFile()) {
break;
}

try {
$content = $documentRepo->getResourceFileContent($document);

if (!is_string($content) || !preg_match('/^\s*<(?!!--|!doctype|html|body)/i', $content)) {
break;
}

$filesToExport[] = [
'title' => $item->getTitle(),
'content' => $content,
];
} catch (\Throwable) {
break;
}
}
}

$pdf = new PDF();
$result = $pdf->html_to_pdf(
$files_to_export,
$lp->getTitle(),
$courseCode,
true,
true,
true,
$lp->getTitle()
);
break;

return $result;
case 'asset':
case 'sco':
$filePath = $scormPath.'/'.$item->getPath();
if (file_exists($filePath)) {
$filesToExport[] = [
'title' => $item->getTitle(),
'path' => $filePath,
];
}
break;

case 'dir':
$filesToExport[] = [
'title' => $item->getTitle(),
'path' => null,
];
break;
}
}

return false;
$pdf = new PDF();

return $pdf->html_to_pdf(
$filesToExport,
$lp->getTitle(),
$courseCode,
true,
true,
true,
$lp->getTitle()
);
}
}
3 changes: 2 additions & 1 deletion public/main/lp/lp_controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,8 @@
if (!$lp_found) {
require 'lp_list.php';
} else {
$result = ScormExport::exportToPdf($lpId, $courseInfo);
$selectedItems = isset($_GET['items']) ? explode(',', $_GET['items']) : [];
$result = ScormExport::exportToPdf($lpId, $courseInfo, $selectedItems);
if (!$result) {
require 'lp_list.php';
}
Expand Down
Loading
Loading