Update code

This commit is contained in:
2025-08-20 23:33:52 +07:00
parent 7e99b228f5
commit a02171820c
29 changed files with 553 additions and 0 deletions

67
Moodle/PHP/createfile.php Normal file
View File

@@ -0,0 +1,67 @@
<?php
// Khai báo CLI
define('CLI_SCRIPT', true);
// Nạp config Moodle
require('/home/online.huph.edu.vn/public_html/online/config.php');
require_once($CFG->dirroot.'/course/lib.php');
require_once($CFG->dirroot.'/mod/resource/lib.php');
global $DB, $CFG;
// Ép user thành admin để tránh lỗi guest
$admin = get_admin();
\core\session\manager::set_user($admin);
// ==== Thông tin cần thay đổi ====
$courseid = 1645; // ID khóa học
$sectionnum = 1; // số thứ tự section/topic
$filepath = '/nas1videos/English Learning/English with Lucy - Beautiful British English B2 Programme (Upper Intermediate) 2025-6/02. PDF/B2 Week 1 Weekly Langua Prompts.pdf';
$filename = basename($filepath); // Tên activity
// Lấy course
$course = $DB->get_record('course', ['id'=>$courseid], '*', MUST_EXIST);
// Lấy section thực theo số thứ tự
$section = $DB->get_record('course_sections', ['course'=>$courseid,'section'=>$sectionnum], '*', MUST_EXIST);
$sectionid = $section->id;
// Module ID cho resource
$moduleid = $DB->get_field('modules','id',['name'=>'resource'], MUST_EXIST);
// ===== Tạo bản ghi resource =====
$resource = new stdClass();
$resource->course = $courseid;
$resource->name = $filename;
$resource->intro = '';
$resource->introformat = FORMAT_HTML;
$resource->display = 0; // hiển thị link trực tiếp
$resource->externalurl = $filepath; // link đến file repository
$resource->section = $sectionid;
$resource->timecreated = time();
$resource->timemodified = time();
$resource->visible = 1;
// Thêm vào bảng resource
$resource->id = $DB->insert_record('resource', $resource);
// ===== Tạo course module =====
$cm = new stdClass();
$cm->course = $courseid;
$cm->module = $moduleid;
$cm->instance = $resource->id;
$cm->section = $sectionid;
$cm->visible = 1;
$cm->added = time();
$cm->score = 0;
$cm->indent = 0;
$cm->completion = 0;
// Thêm vào bảng course_modules
$cm->id = $DB->insert_record('course_modules', $cm);
// ===== Cập nhật course_sections =====
course_add_cm_to_section($course, $cm->id, $sectionnum);
echo "✅ File activity '{$filename}' đã được tạo trong course {$courseid}, section {$sectionnum}, cmid={$cm->id}\n";

160
Moodle/PHP/newtest.php Normal file
View File

@@ -0,0 +1,160 @@
<?php
// Đặt cấu hình cho môi trường Moodle.
define('CLI_SCRIPT', true); // Định nghĩa để script chạy trên command line.
require_once(__DIR__ . '/config.php');
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->dirroot . '/mod/page/lib.php');
/**
* Hàm tạo một Page Activity trong Moodle.
*
* @param int $courseid ID của khóa học.
* @param int $topicid ID của topic (section) trong khóa học.
* @param string $page_name Tên của trang.
* @param string $page_content Nội dung của trang.
* @return int|false Trả về ID của page nếu thành công, hoặc `false` nếu thất bại.
* @throws Exception Nếu xảy ra lỗi.
*/
function create_page_activity($courseid, $topicid, $page_name, $page_content) {
global $DB;
try {
// Lấy thông tin khóa học.
$course = $DB->get_record('course', ['id' => $courseid], '*', MUST_EXIST);
// Kiểm tra section tồn tại.
$section = $DB->get_record('course_sections', ['course' => $courseid, 'section' => $topicid], '*', MUST_EXIST);
// Dữ liệu của activity page.
$page_data = (object)[
'course' => $courseid,
'name' => $page_name, // Tên của trang (tên tệp đã bóc tách).
'content' => $page_content, // Nội dung trang.
'contentformat' => FORMAT_HTML, // Định dạng nội dung.
'intro' => 'Automatically generated page activity.', // Phần giới thiệu mặc định.
'introformat' => FORMAT_HTML, // Định dạng phần giới thiệu.
'timemodified' => time() // Thời gian chỉnh sửa cuối cùng.
];
// Tạo bản ghi trong bảng `page`.
$pageid = $DB->insert_record('page', $page_data); // **Cập nhật DB: Bảng `page`.**
if (!$pageid) {
throw new moodle_exception('Không thể tạo bản ghi trong bảng page.');
}
// Tạo bản ghi trong bảng `course_modules` (CM).
$module = $DB->get_record('modules', ['name' => 'page'], '*', MUST_EXIST); // Lấy module ID cho `page`.
$module_instance = (object)[
'course' => $courseid,
'module' => $module->id,
'instance' => $pageid, // Liên kết với bản ghi trong `page`.
'section' => $section->id,
'added' => time(),
'visible' => 1, // Hoạt động này có hiển thị không.
'visibleold' => 1,
'groupmode' => 0,
'groupingid' => 0,
'groupmembersonly' => 0
];
$cmid = $DB->insert_record('course_modules', $module_instance); // **Cập nhật DB: Bảng `course_modules`.**
if (!$cmid) {
throw new moodle_exception('Không thể tạo bản ghi trong bảng course_modules.');
}
// Cập nhật bảng `course_sections`.
$section->sequence = trim($section->sequence . ',' . $cmid, ',');
$DB->update_record('course_sections', $section); // **Cập nhật DB: Bảng `course_sections`.**
rebuild_course_cache($courseid); // Xây dựng lại bộ nhớ đệm của khóa học.
// Ghi lại sự kiện trong `logstore_standard_log`.
$event = \core\event\course_module_created::create([
'context' => context_course::instance($courseid),
'objectid' => $cmid,
'courseid' => $courseid,
'relateduserid' => null, // Không cần thiết nếu chạy từ CLI.
'other' => [
'modulename' => 'page',
'instanceid' => $pageid, // Thêm instanceid.
'name' => $page_name // Thêm tên hoạt động.
]
]);
$event->trigger(); // **Ghi vào DB: Bảng `logstore_standard_log`.**
return $pageid;
} catch (Exception $e) {
echo "Lỗi: " . $e->getMessage() . "\n";
return false;
}
}
/**
* Hàm phân tích một dòng stream và bóc tách tên tệp.
*
* @param string $stream_line Dòng stream cần phân tích.
* @return array Mảng chứa tên tệp đã bóc tách và dòng stream.
*/
function parse_stream_line($stream_line) {
// Kiểm tra nếu chuỗi có dấu ngoặc vuông hay không.
if (strpos($stream_line, '[') === false || strpos($stream_line, ']') === false) {
return ['', '']; // Trả về giá trị mặc định nếu không có dấu ngoặc vuông.
}
// Giả sử tệp có dạng: [stream=tháng năm/tên_video.mp4]
preg_match('/\[(.*?)\]/', $stream_line, $matches);
// Kiểm tra nếu tìm thấy tên tệp trong dòng stream.
if (isset($matches[1])) {
$file_name_with_extension = $matches[1]; // Lấy tên tệp từ dòng stream.
// Loại bỏ phần mở rộng tệp (ví dụ .mp4, .avi, .jpg)
$file_name_without_extension = pathinfo($file_name_with_extension, PATHINFO_FILENAME);
// Loại bỏ các ký tự không cần thiết ở cuối (các phần sau dấu gạch nối, gạch dưới hoặc ký tự vô nghĩa)
// Chỉ giữ lại các phần tên hợp lý trước khi xuất hiện các ký tự đặc biệt.
$file_name_clean = preg_replace('/[^\w\s-]/', '', $file_name_without_extension); // Loại bỏ các ký tự đặc biệt.
$file_name_clean = preg_replace('/[-\s]+/', ' ', $file_name_clean); // Thay thế các dấu gạch nối và khoảng trắng liên tiếp bằng một dấu cách.
$file_name_clean = trim($file_name_clean); // Loại bỏ khoảng trắng ở đầu và cuối.
return [$file_name_clean, $stream_line]; // Trả về tên tệp đã được xử lý và dòng stream.
}
// Nếu không tìm thấy tên tệp, trả về giá trị mặc định.
return ['', ''];
}
// Chương trình chính
$courseid = 1347; // ID của khóa học.
$topicid = 0; // ID của topic (section) trong khóa học.
// Kiểm tra xem có truyền tên tệp từ dòng lệnh không
if ($argc < 2) {
echo "Vui lòng cung cấp tên tệp chứa các dòng stream.\n";
exit(1);
}
// Đọc tên tệp từ dòng lệnh
$filename = $argv[1];
// Kiểm tra nếu tệp có tồn tại không
if (!file_exists($filename)) {
echo "Tệp không tồn tại: {$filename}\n";
exit(1);
}
// Đọc tệp và xử lý từng dòng
$file_lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($file_lines as $stream_line) {
// Lấy tên tệp và dòng stream.
list($page_name, $page_content) = parse_stream_line($stream_line);
// Tạo Page Activity với nội dung từ dòng stream.
$pageid = create_page_activity($courseid, $topicid, $page_name, $page_content);
if ($pageid !== false) {
echo "Tạo Page Activity thành công! Page ID: {$pageid}\n";
} else {
echo "Không thể tạo Page Activity.\n";
}
}
?>

136
Moodle/PHP/objpage.php Normal file
View File

@@ -0,0 +1,136 @@
<?php
// Định nghĩa là script CLI
define('CLI_SCRIPT', true);
// Nạp cấu hình Moodle
require_once(__DIR__ . '/config.php');
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->dirroot . '/mod/page/lib.php');
class PageActivityGenerator {
protected $courseId;
protected $topicId;
protected $streamFile;
public function __construct($streamFile, $courseId, $topicId) {
$this->courseId = $courseId;
$this->topicId = $topicId;
$this->streamFile = $streamFile;
}
public function run() {
if (!file_exists($this->streamFile)) {
echo "Lỗi: Không tìm thấy file: {$this->streamFile}\n";
exit(1);
}
$lines = file($this->streamFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
list($filename, $url) = $this->parse_stream_line($line);
if (!$filename || !$url) {
echo "⚠️ Bỏ qua dòng không hợp lệ: $line\n";
continue;
}
$pageName = $this->ensure_utf8($filename);
$pageContent = $this->ensure_utf8('[stream=' . $url . ']');
$success = $this->create_page_activity($pageName, $pageContent);
if ($success) {
echo "✅ Đã tạo Page: $pageName\n";
}
}
}
protected function ensure_utf8($string) {
return mb_convert_encoding($string, 'UTF-8', mb_detect_encoding($string, 'UTF-8, ISO-8859-1, ISO-8859-15', true));
}
protected function parse_stream_line($line) {
if (preg_match('/\[stream=(.*?)\]/', $line, $matches)) {
$url = trim($matches[1]);
$filename = pathinfo($url, PATHINFO_FILENAME);
$filename_clean = preg_replace('/[^\p{L}\p{N}\s_-]/u', '', $filename); // Giữ unicode và ký tự hợp lệ
return [$filename_clean, $url];
}
return ['', ''];
}
protected function create_page_activity($pageName, $pageContent) {
global $DB;
try {
// Lấy thông tin course & topic
$course = $DB->get_record('course', ['id' => $this->courseId], '*', MUST_EXIST);
$section = $DB->get_record('course_sections', ['course' => $this->courseId, 'section' => $this->topicId], '*', MUST_EXIST);
// Tạo bản ghi trong bảng page
$page = (object)[
'course' => $this->courseId,
'name' => $pageName,
'content' => $pageContent,
'contentformat' => FORMAT_HTML,
'intro' => 'Automatically generated page activity.',
'introformat' => FORMAT_HTML,
'timemodified' => time()
];
$pageId = $DB->insert_record('page', $page);
if (!$pageId) {
throw new moodle_exception("Không thể tạo bản ghi trong bảng page.");
}
// Tạo bản ghi trong bảng course_modules
$module = $DB->get_record('modules', ['name' => 'page'], '*', MUST_EXIST);
$cm = (object)[
'course' => $this->courseId,
'module' => $module->id,
'instance' => $pageId,
'section' => $section->id,
'added' => time(),
'visible' => 1,
'visibleold' => 1,
'groupmode' => 0,
'groupingid' => 0,
'groupmembersonly' => 0
];
$cmid = $DB->insert_record('course_modules', $cm);
if (!$cmid) {
throw new moodle_exception("Không thể tạo bản ghi trong bảng course_modules.");
}
// Cập nhật chuỗi hoạt động của section
if (!empty($section->sequence)) {
$section->sequence .= ',' . $cmid;
} else {
$section->sequence = $cmid;
}
$DB->update_record('course_sections', $section);
// Làm mới cache khóa học
rebuild_course_cache($this->courseId);
return $pageId;
} catch (Exception $e) {
echo "❌ Lỗi: " . $e->getMessage() . "\n";
return false;
}
}
}
// CLI entry point
if ($argc !== 4) {
echo "Cách dùng: php script.php <stream_file> <courseid> <topicid>\n";
exit(1);
}
$streamFile = $argv[1];
$courseId = (int)$argv[2];
$topicId = (int)$argv[3];
$generator = new PageActivityGenerator($streamFile, $courseId, $topicId);
$generator->run();

123
Moodle/PHP/page.php Normal file
View File

@@ -0,0 +1,123 @@
<?php
// Đặt cấu hình cho môi trường Moodle.
define('CLI_SCRIPT', true); // Định nghĩa để script chạy trên command line.
require_once(__DIR__ . '/config.php');
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->dirroot . '/mod/page/lib.php');
/**
* Đảm bảo chuỗi ở định dạng UTF-8.
*
* @param string $string Chuỗi cần kiểm tra.
* @return string Chuỗi đã được đảm bảo là UTF-8.
*/
function ensure_utf8($string) {
return mb_convert_encoding($string, 'UTF-8', 'auto');
}
/**
* Hàm tạo một Page Activity trong Moodle.
*/
function create_page_activity($courseid, $topicid, $page_name, $page_content) {
global $DB;
try {
$course = $DB->get_record('course', ['id' => $courseid], '*', MUST_EXIST);
$section = $DB->get_record('course_sections', ['course' => $courseid, 'section' => $topicid], '*', MUST_EXIST);
// Đảm bảo tên và nội dung luôn là UTF-8
$page_name = ensure_utf8($page_name);
$page_content = ensure_utf8($page_content);
$page_data = (object)[
'course' => $courseid,
'name' => $page_name,
'content' => $page_content,
'contentformat' => FORMAT_HTML,
'intro' => 'Automatically generated page activity.',
'introformat' => FORMAT_HTML,
'timemodified' => time()
];
$pageid = $DB->insert_record('page', $page_data);
if (!$pageid) {
throw new moodle_exception('Không thể tạo bản ghi trong bảng page.');
}
$module = $DB->get_record('modules', ['name' => 'page'], '*', MUST_EXIST);
$module_instance = (object)[
'course' => $courseid,
'module' => $module->id,
'instance' => $pageid,
'section' => $section->id,
'added' => time(),
'visible' => 1,
'visibleold' => 1,
'groupmode' => 0,
'groupingid' => 0,
'groupmembersonly' => 0
];
$cmid = $DB->insert_record('course_modules', $module_instance);
if (!$cmid) {
throw new moodle_exception('Không thể tạo bản ghi trong bảng course_modules.');
}
$section->sequence = trim($section->sequence . ',' . $cmid, ',');
$DB->update_record('course_sections', $section);
rebuild_course_cache($courseid);
return $pageid;
} catch (Exception $e) {
echo "Lỗi: " . $e->getMessage() . "\n";
return false;
}
}
/**
* Phân tích dòng stream và đảm bảo tên UTF-8.
*/
function parse_stream_line($stream_line) {
if (strpos($stream_line, '[') === false || strpos($stream_line, ']') === false) {
return ['', ''];
}
preg_match('/\[(.*?)\]/', $stream_line, $matches);
if (isset($matches[1])) {
$file_name_with_extension = $matches[1];
$file_name_without_extension = pathinfo($file_name_with_extension, PATHINFO_FILENAME);
$file_name_clean = preg_replace('/[^\w\s-]/u', '', $file_name_without_extension); // Sử dụng flag `u` cho UTF-8
$file_name_clean = preg_replace('/[-\s]+/', ' ', $file_name_clean);
$file_name_clean = trim($file_name_clean);
return [ensure_utf8($file_name_clean), ensure_utf8($stream_line)];
}
return ['', ''];
}
// Nhận tham số từ dòng lệnh
if ($argc < 4) {
echo "Usage: php script.php <filename> <courseid> <topicid>\n";
exit(1);
}
$filename = $argv[1];
$courseid = intval($argv[2]);
$topicid = intval($argv[3]);
if (!file_exists($filename)) {
echo "Tệp không tồn tại: {$filename}\n";
exit(1);
}
$file_lines = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($file_lines as $stream_line) {
list($page_name, $page_content) = parse_stream_line($stream_line);
$pageid = create_page_activity($courseid, $topicid, $page_name, $page_content);
if ($pageid !== false) {
echo "Tạo Page Activity thành công! Page ID: {$pageid}\n";
} else {
echo "Không thể tạo Page Activity.\n";
}
}
?>

26
Moodle/SH/scan.sh Normal file
View File

@@ -0,0 +1,26 @@
#!/bin/bash
# Thư mục gốc của khóa học
COURSE_FOLDER="$(pwd)"
# Tìm tất cả các thư mục con
mapfile -t DIRS < <(find "$COURSE_FOLDER" -type d)
for dir in "${DIRS[@]}"; do
relative_path="${dir#*/vod/}"
OUTPUT_JSON="$dir/filelist.txt"
# Xóa tệp mdl.media cũ nếu tồn tại
rm -f "$OUTPUT_JSON"
# Tìm và sắp xếp các file .pdf và .xlsx theo thứ tự tự nhiên
mapfile -d '' -t FILES < <(find "$dir" -maxdepth 1 -type f \( -name '*.pdf' -o -name '*.xlsx' \) -print0 | sort -z -V)
for file in "${FILES[@]}"; do
filename=$(basename "$file")
vid="$relative_path/$filename"
echo "$vid" >> "$OUTPUT_JSON"
done
echo "File filelist.txt created successfully in $dir."
done

41
Moodle/SH/scan1.sh Normal file
View File

@@ -0,0 +1,41 @@
#!/bin/bash
COURSE_FOLDER="$(pwd)"
# Kiểm tra tham số
if [ -z "$1" ]; then
echo "Usage: $0 ext1,ext2,..."
exit 1
fi
# Tạo mảng extension
IFS=',' read -ra EXT_ARRAY <<< "$1"
# Quét tất cả thư mục con
mapfile -t DIRS < <(find "$COURSE_FOLDER" -type d)
for dir in "${DIRS[@]}"; do
relative_path="${dir#*/vod/}"
OUTPUT_FILE="$dir/filelist.txt"
rm -f "$OUTPUT_FILE"
# Duyệt tất cả file trong thư mục
for file in "$dir"/*; do
[ -f "$file" ] || continue
filename=$(basename "$file")
ext="${filename##*.}"
# Kiểm tra extension có trong danh sách không
for allowed_ext in "${EXT_ARRAY[@]}"; do
if [[ "${ext,,}" == "${allowed_ext,,}" ]]; then # ignore case
echo "$relative_path/$filename" >> "$OUTPUT_FILE"
break
fi
done
done
# Sắp xếp tự nhiên filelist.txt
if [ -s "$OUTPUT_FILE" ]; then
sort -V -o "$OUTPUT_FILE" "$OUTPUT_FILE"
echo "File filelist.txt created successfully in $dir."
fi
done