first commit

This commit is contained in:
CHIEFSOFT\ameye
2024-09-30 18:11:26 -04:00
commit e592ca6823
27270 changed files with 5002257 additions and 0 deletions
+69
View File
@@ -0,0 +1,69 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @copyright 2012 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
class cc_assesment_question_essay extends cc_assesment_question_proc_base {
public function __construct($quiz, $questions, $manifest, $section, $question_node, $rootpath, $contextid, $outdir) {
parent::__construct($quiz, $questions, $manifest, $section, $question_node, $rootpath, $contextid, $outdir);
$this->qtype = cc_qti_profiletype::essay;
$maximum_quiz_grade = (int)$this->quiz->nodeValue('/activity/quiz/grade');
$this->total_grade_value = ($maximum_quiz_grade + 1).'.0000000';
}
public function on_generate_metadata() {
parent::on_generate_metadata();
// Mark essay for manual grading.
$this->qmetadata->enable_scoringpermitted();
$this->qmetadata->enable_computerscored(false);
}
public function on_generate_presentation() {
parent::on_generate_presentation();
$response_str = new cc_assesment_response_strtype();
$response_fib = new cc_assesment_render_fibtype();
$row_value = (int)$this->questions->nodeValue('plugin_qtype_essay_question//responsefieldlines', $this->question_node);
$response_fib->set_rows($row_value);
$response_str->set_render_fib($response_fib);
$this->qpresentation->set_response_str($response_str);
}
public function on_generate_response_processing() {
parent::on_generate_response_processing();
// Response conditions.
if (!empty($this->general_feedback)) {
$qrespcondition = new cc_assesment_respconditiontype();
$qrespcondition->set_title('General feedback');
$this->qresprocessing->add_respcondition($qrespcondition);
// Define the condition for success.
$qconditionvar = new cc_assignment_conditionvar();
$qrespcondition->set_conditionvar($qconditionvar);
$qother = new cc_assignment_conditionvar_othertype();
$qconditionvar->set_other($qother);
$qdisplayfeedback = new cc_assignment_displayfeedbacktype();
$qrespcondition->add_displayfeedback($qdisplayfeedback);
$qdisplayfeedback->set_feedbacktype(cc_qti_values::Response);
$qdisplayfeedback->set_linkrefid('general_fb');
}
}
}
+183
View File
@@ -0,0 +1,183 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @copyright 2012 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
require_once('cc_asssesment.php');
class cc_assesment_question_sfib extends cc_assesment_question_proc_base {
public function __construct($quiz, $questions, $manifest, $section, $question_node, $rootpath, $contextid, $outdir) {
parent::__construct($quiz, $questions, $manifest, $section, $question_node, $rootpath, $contextid, $outdir);
$this->qtype = cc_qti_profiletype::field_entry;
$this->correct_answer_node_id = $this->questions->nodeValue(
'plugin_qtype_truefalse_question/truefalse/trueanswer',
$this->question_node
);
$maximum_quiz_grade = (int)$this->quiz->nodeValue('/activity/quiz/grade');
$this->total_grade_value = ($maximum_quiz_grade + 1).'.0000000';
}
public function on_generate_metadata() {
parent::on_generate_metadata();
$category = $this->questions->nodeValue('../../name', $this->question_node);
if (!empty($category)) {
$this->qmetadata->set_category($category);
}
}
public function on_generate_presentation() {
parent::on_generate_presentation();
$response_str = new cc_assesment_response_strtype();
$response_fib = new cc_assesment_render_fibtype();
// The standard requires that only rows attribute must be set,
// the rest may or may not be configured. For the sake of brevity we leave it empty.
$response_fib->set_rows(1);
$response_str->set_render_fib($response_fib);
$this->qpresentation->set_response_str($response_str);
}
public function on_generate_feedbacks() {
parent::on_generate_feedbacks();
// Question combined feedback.
$responsenodes = $this->questions->nodeList('plugin_qtype_shortanswer_question//answer', $this->question_node);
$count = 0;
foreach ($responsenodes as $respnode) {
$content = $this->questions->nodeValue('feedback', $respnode);
if (empty($content)) {
continue;
}
$correct = (int)$this->questions->nodeValue('fraction', $respnode) == 1;
$answerid = (int)$this->questions->nodeValue('@id', $respnode);
$result = cc_helpers::process_linked_files( $content,
$this->manifest,
$this->rootpath,
$this->contextid,
$this->outdir);
$ident = $correct ? 'correct' : 'incorrect';
$ident .= '_'.$count.'_fb';
cc_assesment_helper::add_feedback( $this->qitem,
$result[0],
cc_qti_values::htmltype,
$ident);
pkg_resource_dependencies::instance()->add($result[1]);
if ($correct) {
$this->correct_feedbacks[$answerid] = $ident;
} else {
$this->incorrect_feedbacks[$answerid] = $ident;
}
++$count;
}
}
public function on_generate_response_processing() {
parent::on_generate_response_processing();
// General unconditional feedback must be added as a first respcondition
// without any condition and just displayfeedback (if exists).
if (!empty($this->general_feedback)) {
$qrespcondition = new cc_assesment_respconditiontype();
$qrespcondition->set_title('General feedback');
$this->qresprocessing->add_respcondition($qrespcondition);
$qrespcondition->enable_continue();
// Define the condition for success.
$qconditionvar = new cc_assignment_conditionvar();
$qrespcondition->set_conditionvar($qconditionvar);
$qother = new cc_assignment_conditionvar_othertype();
$qconditionvar->set_other($qother);
$qdisplayfeedback = new cc_assignment_displayfeedbacktype();
$qrespcondition->add_displayfeedback($qdisplayfeedback);
$qdisplayfeedback->set_feedbacktype(cc_qti_values::Response);
$qdisplayfeedback->set_linkrefid('general_fb');
}
// Answer separate conditions.
$correct_responses = $this->questions->nodeList(
'plugin_qtype_shortanswer_question//answer[fraction=1]', $this->question_node);
$incorrect_responses = $this->questions->nodeList(
'plugin_qtype_shortanswer_question//answer[fraction<1]', $this->question_node);
$items = array(
array($correct_responses, $this->correct_feedbacks),
array($incorrect_responses, $this->incorrect_feedbacks)
);
foreach ($items as $respfeed) {
foreach ($respfeed[0] as $coresponse) {
$qrespcondition = new cc_assesment_respconditiontype();
$qrespcondition->enable_continue();
$this->qresprocessing->add_respcondition($qrespcondition);
$qconditionvar = new cc_assignment_conditionvar();
$qrespcondition->set_conditionvar($qconditionvar);
$respc = $this->questions->nodeValue('answertext', $coresponse);
$resid = $this->questions->nodeValue('@id', $coresponse);
$qvarequal = new cc_assignment_conditionvar_varequaltype($respc);
$qconditionvar->set_varequal($qvarequal);
$qvarequal->set_respident('response');
$qvarequal->enable_case(false);
if (!empty($respfeed[1][$resid])) {
$qdisplayfeedback = new cc_assignment_displayfeedbacktype();
$qrespcondition->add_displayfeedback($qdisplayfeedback);
$qdisplayfeedback->set_feedbacktype(cc_qti_values::Response);
$qdisplayfeedback->set_linkrefid($respfeed[1][$resid]);
}
}
}
// Success condition.
// For all question types outside of the Essay question, scoring is done in a
// single <respcondition> with a continue flag set to No. The outcome is always
// a variable named SCORE which value must be set to 100 in case of correct answer.
// Partial scores (not 0 or 100) are not supported.
$qrespcondition = new cc_assesment_respconditiontype();
$qrespcondition->set_title('Correct');
$this->qresprocessing->add_respcondition($qrespcondition);
$qrespcondition->enable_continue(false);
$qsetvar = new cc_assignment_setvartype(100);
$qrespcondition->add_setvar($qsetvar);
// Define the condition for success.
$qconditionvar = new cc_assignment_conditionvar();
$qrespcondition->set_conditionvar($qconditionvar);
foreach ($correct_responses as $coresponse) {
$respc = $this->questions->nodeValue('answertext', $coresponse);
$qvarequal = new cc_assignment_conditionvar_varequaltype($respc);
$qconditionvar->set_varequal($qvarequal);
$qvarequal->set_respident('response');
$qvarequal->enable_case(false);
}
// Add incorrect handling.
$qrespcondition = new cc_assesment_respconditiontype();
$this->qresprocessing->add_respcondition($qrespcondition);
$qrespcondition->enable_continue(false);
// Define the condition for failure.
$qconditionvar = new cc_assignment_conditionvar();
$qrespcondition->set_conditionvar($qconditionvar);
$qother = new cc_assignment_conditionvar_othertype();
$qconditionvar->set_other($qother);
$qsetvar = new cc_assignment_setvartype(0);
$qrespcondition->add_setvar($qsetvar);
}
}
+183
View File
@@ -0,0 +1,183 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @copyright 2012 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
require_once('cc_asssesment.php');
class cc_assesment_question_truefalse extends cc_assesment_question_proc_base {
public function __construct($quiz, $questions, $manifest, $section, $question_node, $rootpath, $contextid, $outdir) {
parent::__construct($quiz, $questions, $manifest, $section, $question_node, $rootpath, $contextid, $outdir);
$this->qtype = cc_qti_profiletype::true_false;
// Determine the correct answer by finding out which answer has the non zero fraction...
// This is because a true / false question type can have 'false' as the correct answer.
$answers = $this->questions->nodeList('plugin_qtype_truefalse_question/answers/answer', $this->question_node);
foreach ($answers as $answer) {
$fraction = $this->questions->nodeValue('fraction', $answer);
if ($fraction != 0) {
$this->correct_answer_node_id = (int)$this->questions->nodeValue('@id', $answer);
}
}
$maximum_quiz_grade = (int)$this->quiz->nodeValue('/activity/quiz/grade');
$this->total_grade_value = ($maximum_quiz_grade + 1).'.0000000';
}
public function on_generate_answers() {
// Add responses holder.
$qresponse_lid = new cc_response_lidtype();
$this->qresponse_lid = $qresponse_lid;
$this->qpresentation->set_response_lid($qresponse_lid);
$qresponse_choice = new cc_assesment_render_choicetype();
$qresponse_lid->set_render_choice($qresponse_choice);
// Mark that question has only one correct answer -
// which applies for multiple choice and yes/no questions.
$qresponse_lid->set_rcardinality(cc_qti_values::Single);
// Are we to shuffle the responses?
$shuffle_answers = (int)$this->quiz->nodeValue('/activity/quiz/shuffleanswers') > 0;
$qresponse_choice->enable_shuffle($shuffle_answers);
$answerlist = array();
$qa_responses = $this->questions->nodeList('plugin_qtype_truefalse_question/answers/answer', $this->question_node);
foreach ($qa_responses as $node) {
$answer_content = $this->questions->nodeValue('answertext', $node);
$id = ((int)$this->questions->nodeValue('@id', $node) == $this->correct_answer_node_id);
$qresponse_label = cc_assesment_helper::add_answer( $qresponse_choice,
$answer_content,
cc_qti_values::htmltype);
$answer_ident = strtolower(trim($answer_content));
$qresponse_label->set_ident($answer_ident);
$feedback_ident = ($id) ? 'correct_fb' : 'incorrect_fb';
if (empty($this->correct_answer_ident) && $id) {
$this->correct_answer_ident = $answer_ident;
}
// Add answer specific feedback if not empty.
$content = $this->questions->nodeValue('feedback', $node);
if (!empty($content)) {
$result = cc_helpers::process_linked_files( $content,
$this->manifest,
$this->rootpath,
$this->contextid,
$this->outdir);
cc_assesment_helper::add_feedback( $this->qitem,
$result[0],
cc_qti_values::htmltype,
$feedback_ident);
pkg_resource_dependencies::instance()->add($result[1]);
$answerlist[$answer_ident] = $feedback_ident;
}
}
$this->answerlist = $answerlist;
}
public function on_generate_response_processing() {
parent::on_generate_response_processing();
// Response conditions.
// General unconditional feedback must be added as a first respcondition
// without any condition and just displayfeedback (if exists).
if (!empty($this->general_feedback)) {
$qrespcondition = new cc_assesment_respconditiontype();
$qrespcondition->set_title('General feedback');
$this->qresprocessing->add_respcondition($qrespcondition);
$qrespcondition->enable_continue();
// Define the condition for success.
$qconditionvar = new cc_assignment_conditionvar();
$qrespcondition->set_conditionvar($qconditionvar);
$qother = new cc_assignment_conditionvar_othertype();
$qconditionvar->set_other($qother);
$qdisplayfeedback = new cc_assignment_displayfeedbacktype();
$qrespcondition->add_displayfeedback($qdisplayfeedback);
$qdisplayfeedback->set_feedbacktype(cc_qti_values::Response);
$qdisplayfeedback->set_linkrefid('general_fb');
}
// Success condition.
// For all question types outside of the Essay question, scoring is done in a
// single <respcondition> with a continue flag set to No. The outcome is always
// a variable named SCORE which value must be set to 100 in case of correct answer.
// Partial scores (not 0 or 100) are not supported.
$qrespcondition = new cc_assesment_respconditiontype();
$qrespcondition->set_title('Correct');
$this->qresprocessing->add_respcondition($qrespcondition);
$qrespcondition->enable_continue(false);
$qsetvar = new cc_assignment_setvartype(100);
$qrespcondition->add_setvar($qsetvar);
// Define the condition for success.
$qconditionvar = new cc_assignment_conditionvar();
$qrespcondition->set_conditionvar($qconditionvar);
// TODO: recheck this.
$qvarequal = new cc_assignment_conditionvar_varequaltype($this->correct_answer_ident);
$qconditionvar->set_varequal($qvarequal);
$qvarequal->set_respident($this->qresponse_lid->get_ident());
if (array_key_exists($this->correct_answer_ident, $this->answerlist)) {
$qdisplayfeedback = new cc_assignment_displayfeedbacktype();
$qrespcondition->add_displayfeedback($qdisplayfeedback);
$qdisplayfeedback->set_feedbacktype(cc_qti_values::Response);
$qdisplayfeedback->set_linkrefid($this->answerlist[$this->correct_answer_ident]);
}
foreach ($this->correct_feedbacks as $ident) {
$qdisplayfeedback = new cc_assignment_displayfeedbacktype();
$qrespcondition->add_displayfeedback($qdisplayfeedback);
$qdisplayfeedback->set_feedbacktype(cc_qti_values::Response);
$qdisplayfeedback->set_linkrefid($ident);
}
// Rest of the conditions.
foreach ($this->answerlist as $ident => $refid) {
if ($ident == $this->correct_answer_ident) {
continue;
}
$qrespcondition = new cc_assesment_respconditiontype();
$this->qresprocessing->add_respcondition($qrespcondition);
$qsetvar = new cc_assignment_setvartype(0);
$qrespcondition->add_setvar($qsetvar);
// Define the condition for fail.
$qconditionvar = new cc_assignment_conditionvar();
$qrespcondition->set_conditionvar($qconditionvar);
$qvarequal = new cc_assignment_conditionvar_varequaltype($ident);
$qconditionvar->set_varequal($qvarequal);
$qvarequal->set_respident($this->qresponse_lid->get_ident());
$qdisplayfeedback = new cc_assignment_displayfeedbacktype();
$qrespcondition->add_displayfeedback($qdisplayfeedback);
$qdisplayfeedback->set_feedbacktype(cc_qti_values::Response);
$qdisplayfeedback->set_linkrefid($refid);
foreach ($this->incorrect_feedbacks as $ident) {
$qdisplayfeedback = new cc_assignment_displayfeedbacktype();
$qrespcondition->add_displayfeedback($qdisplayfeedback);
$qdisplayfeedback->set_feedbacktype(cc_qti_values::Response);
$qdisplayfeedback->set_linkrefid($ident);
}
}
}
}
File diff suppressed because it is too large Load Diff
+181
View File
@@ -0,0 +1,181 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_general.php';
class basicltil1_resurce_file extends general_cc_file {
const deafultname = 'basiclti.xml';
protected $rootns = 'xmlns';
protected $rootname = 'cartridge_basiclti_link';
protected $ccnamespaces = array('xmlns' => 'http://www.imsglobal.org/xsd/imslticc_v1p0',
'blti' => 'http://www.imsglobal.org/xsd/imsbasiclti_v1p0',
'lticm' => 'http://www.imsglobal.org/xsd/imslticm_v1p0',
'lticp' => 'http://www.imsglobal.org/xsd/imslticp_v1p0',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance');
protected $ccnsnames = array('xmlns' => 'http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticc_v1p0.xsd',
'blti' => 'http://www.imsglobal.org/xsd/lti/ltiv1p0/imsbasiclti_v1p0p1.xsd',
'lticm' => 'http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticm_v1p0.xsd',
'lticp' => 'http://www.imsglobal.org/xsd/lti/ltiv1p0/imslticp_v1p0.xsd');
protected $title = 'Untitled';
protected $description = 'description';
protected $custom_properties = array();
protected $extension_properties = array();
protected $extension_platform = null;
protected $launch_url = null;
protected $secure_launch_url = null;
protected $icon = null;
protected $secure_icon = null;
protected $vendor = false;
protected $vendor_code = 'I';
protected $vendor_name = null;
protected $vendor_description = null;
protected $vendor_url = null;
protected $vendor_contact = null;
protected $cartridge_bundle = null;
protected $cartridge_icon = null;
public function set_title($title) {
$this->title = self::safexml($title);
}
public function set_description($description) {
$this->description = self::safexml($description);
}
public function set_launch_url($url) {
$this->launch_url = $url;
}
public function set_secure_launch_url($url) {
$this->secure_launch_url = $url;
}
public function set_launch_icon($icon) {
$this->icon = $icon;
}
public function set_secure_launch_icon($icon) {
$this->secure_icon = $icon;
}
public function set_vendor_code($code) {
$this->vendor_code = $code;
$this->vendor = true;
}
public function set_vendor_name($name) {
$this->vendor_name = self::safexml($name);
$this->vendor = true;
}
public function set_vendor_description($desc) {
$this->vendor_description = self::safexml($desc);
$this->vendor = true;
}
public function set_vendor_url($url) {
$this->vendor_url = $url;
$this->vendor = true;
}
public function set_vendor_contact($email) {
$this->vendor_contact = array('email' => $email);
$this->vendor = true;
}
public function add_custom_property($property, $value) {
$this->custom_properties[$property] = $value;
}
public function add_extension($extension, $value) {
$this->extension_properties[$extension] = $value;
}
public function set_extension_platform($value) {
$this->extension_platform = $value;
}
public function set_cartridge_bundle($value) {
$this->cartridge_bundle = $value;
}
public function set_cartridge_icon($value) {
$this->cartridge_icon = $value;
}
protected function on_save() {
//this has to be done like this since order of apearance of the tags is also mandatory
//and specified in basiclti schema files
//main items
$rns = $this->ccnamespaces['blti'];
$this->append_new_element_ns($this->root, $rns, 'title' , $this->title );
$this->append_new_element_ns($this->root, $rns, 'description', $this->description);
//custom properties
if (!empty($this->custom_properties)) {
$custom = $this->append_new_element_ns($this->root, $rns, 'custom');
foreach ($this->custom_properties as $property => $value) {
$node = $this->append_new_element_ns($custom, $this->ccnamespaces['lticm'], 'property' , $value);
$this->append_new_attribute_ns($node, $this->ccnamespaces['xmlns'],'name', $property);
}
}
//extension properties
if (!empty($this->extension_properties)) {
$extension = $this->append_new_element_ns($this->root, $rns, 'extensions');
if (!empty($this->extension_platform)) {
$this->append_new_attribute_ns($extension, $this->ccnamespaces['xmlns'], 'platform', $this->extension_platform);
}
foreach ($this->extension_properties as $property => $value) {
$node = $this->append_new_element_ns($extension, $this->ccnamespaces['lticm'], 'property' , $value);
$this->append_new_attribute_ns($node, $this->ccnamespaces['xmlns'], 'name', $property);
}
}
$this->append_new_element_ns($this->root, $rns, 'launch_url' , $this->launch_url );
if (!empty($this->secure_launch_url)) {
$this->append_new_element_ns($this->root, $rns, 'secure_launch_url' , $this->secure_launch_url);
}
$this->append_new_element_ns($this->root, $rns, 'icon' , $this->icon );
if (!empty($this->secure_icon)) {
$this->append_new_element_ns($this->root, $rns, 'secure_icon' , $this->secure_icon);
}
//vendor info
$vendor = $this->append_new_element_ns($this->root, $rns, 'vendor');
$vcode = empty($this->vendor_code) ? 'I' : $this->vendor_code;
$this->append_new_element_ns($vendor, $this->ccnamespaces['lticp'], 'code', $vcode);
$this->append_new_element_ns($vendor, $this->ccnamespaces['lticp'], 'name', $this->vendor_name);
if (!empty($this->vendor_description)) {
$this->append_new_element_ns($vendor, $this->ccnamespaces['lticp'], 'description', $this->vendor_description);
}
if (!empty($this->vendor_url)) {
$this->append_new_element_ns($vendor, $this->ccnamespaces['lticp'], 'url', $this->vendor_url);
}
if (!empty($this->vendor_contact)) {
$vcontact = $this->append_new_element_ns($vendor, $this->ccnamespaces['lticp'], 'contact');
$this->append_new_element_ns($vcontact, $this->ccnamespaces['lticp'], 'email', $this->vendor_contact['email']);
}
//cartridge bundle and icon
if (!empty($this->cartridge_bundle)) {
$cbundle = $this->append_new_element_ns($this->root, $this->ccnamespaces['xmlns'], 'cartridge_bundle');
$this->append_new_attribute_ns($cbundle, $this->ccnamespaces['xmlns'], 'identifierref', $this->cartridge_bundle);
}
if (!empty($this->cartridge_icon)) {
$cicon = $this->append_new_element_ns($this->root, $this->ccnamespaces['xmlns'], 'cartridge_icon');
$this->append_new_attribute_ns($cicon, $this->ccnamespaces['xmlns'], 'identifierref', $this->cartridge_icon);
}
return true;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Factory pattern class
* Create the version class to use
*
*/
class cc_builder_creator {
public static function factory($version){
if (is_null($version)) {
throw new Exception("Version is null!");
}
if (include_once 'cc_version' . $version . '.php') {
$classname = 'cc_version' . $version;
return new $classname;
} else {
throw new Exception ("Dont find cc version class!");
}
}
}
+202
View File
@@ -0,0 +1,202 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
if (!extension_loaded('fileinfo')) {
die('You must install fileinfo extension!');
}
abstract class cc_convert_moodle2 {
/**
*
* Enter description here ...
* @param unknown_type $packagedir
* @param unknown_type $outdir
* @throws DOMException
* @throws InvalidArgumentException
*/
public static function convert($packagedir, $outdir) {
$dir = realpath($packagedir);
if (empty($dir)) {
throw new InvalidArgumentException('Directory does not exist!');
}
$odir = realpath($outdir);
if (empty($odir)) {
throw new InvalidArgumentException('Directory does not exist!');
}
$coursefile = $dir.DIRECTORY_SEPARATOR.'course'.DIRECTORY_SEPARATOR.'course.xml';
$doc = new XMLGenericDocument();
if ($doc->load($coursefile)) {
$course_name = $doc->nodeValue('/course/fullname');
$course_desc = $doc->nodeValue('/course/summary');
$course_language = $doc->nodeValue('/course/lang');
$course_language = empty($course_language) ? 'en' : $course_language;
$course_category = $doc->nodeValue('/course/category/name');
//Initialize the manifest metadata class
$meta = new cc_metadata_manifest();
//Package metadata
$metageneral = new cc_metadata_general();
$metageneral->set_language($course_language);
$metageneral->set_title($course_name, $course_language);
$metageneral->set_description($course_desc, $course_language);
$metageneral->set_catalog('category');
$metageneral->set_entry($course_category);
$meta->add_metadata_general($metageneral);
// Create the manifest
$manifest = new cc_manifest(cc_version::v11);
$manifest->add_metadata_manifest($meta);
$organization = null;
//Package structure - default organization and resources
//Get the course structure - this will be transformed into organization
//Step 1 - Get the list and order of sections/topics
$moodle_backup = $dir . DIRECTORY_SEPARATOR . 'moodle_backup.xml';
$secp = new XMLGenericDocument();
$docp = new XMLGenericDocument();
if ($docp->load($moodle_backup)) {
//sections
$sections = array();
$coursef = new XMLGenericDocument();
$course_file = $dir . DIRECTORY_SEPARATOR .'course' . DIRECTORY_SEPARATOR . 'course.xml';
$coursef->load($course_file);
//$numsections = (int)$coursef->nodeValue('/course/numsections');
// TODO MDL-35781, this is commented because numsections is now optional attribute
$section_list = $docp->nodeList('/moodle_backup/information/contents/sections/section');
if (!empty($section_list)) {
$count = 0;
foreach ($section_list as $node) {
//if ($count > $numsections) {
// break;
//}
$sectionid = $docp->nodeValue('sectionid', $node);
$sectiontitle = $docp->nodeValue('title' , $node);
$sectionpath = $docp->nodeValue('directory', $node);
$sequence = array();
//Get section stuff
$section_file = $dir .
DIRECTORY_SEPARATOR .
$sectionpath .
DIRECTORY_SEPARATOR .
'section.xml';
if ($secp->load($section_file)) {
$rawvalue = $secp->nodeValue('/section/sequence');
if ($rawvalue != '$@NULL@$') {
$sequence = explode(',', $rawvalue);
}
}
$sections[$sectionid] = array($sectiontitle, $sequence);
$count++;
}
}
//organization title
$organization = new cc_organization();
//Add section/topic items
foreach ($sections as $sectionid => $values) {
$item = new cc_item();
$item->title = $values[0];
self::process_sequence($item, $manifest, $values[1], $dir, $odir);
$organization->add_item($item);
}
$manifest->put_nodes();
}
if (!empty($organization)) {
$manifest->add_new_organization($organization);
}
$manifestpath = $outdir.DIRECTORY_SEPARATOR.'imsmanifest.xml';
$manifest->saveTo($manifestpath);
}
}
/**
*
* Process the activites and create item structure
* @param cc_i_item $item
* @param array $sequence
* @param string $packageroot - directory path
* @throws DOMException
*/
protected static function process_sequence(cc_i_item &$item, cc_i_manifest &$manifest, array $sequence, $packageroot, $outdir) {
$moodle_backup = $packageroot . DIRECTORY_SEPARATOR . 'moodle_backup.xml';
$doc = new XMLGenericDocument();
if(!$doc->load($moodle_backup)) {
return;
}
$activities = $doc->nodeList('/moodle_backup/information/contents/activities/activity');
if (!empty($activities)) {
$dpp = new XMLGenericDocument();
foreach ($activities as $activity) {
$moduleid = $doc->nodeValue('moduleid', $activity);
if (in_array($moduleid, $sequence)) {
//detect activity type
$directory = $doc->nodeValue('directory', $activity);
$path = $packageroot . DIRECTORY_SEPARATOR . $directory;
$module_file = $path . DIRECTORY_SEPARATOR . 'module.xml';
if ($dpp->load($module_file)) {
$activity_type = $dpp->nodeValue('/module/modulename');
$activity_indentation = $dpp->nodeValue('/module/indent');
$aitem = self::item_indenter($item, $activity_indentation);
$caller = "cc_converter_{$activity_type}";
if (class_exists($caller)) {
$obj = new $caller($aitem, $manifest, $packageroot, $path);
if (!$obj->convert($outdir)) {
throw new RuntimeException("failed to convert {$activity_type}");
}
}
}
}
}
}
}
protected static function item_indenter(cc_i_item &$item, $level = 0) {
$indent = (int)$level;
$indent = ($indent) <= 0 ? 0 : $indent;
$nprev = null;
$nfirst = null;
for ($pos = 0, $size = $indent; $pos < $size; $pos++) {
$nitem = new cc_item();
$nitem->title = '';
if (empty($nfirst)) {
$nfirst = $nitem;
}
if (!empty($nprev)) {
$nprev->add_child_item($nitem);
}
$nprev = $nitem;
}
$result = $item;
if (!empty($nfirst)) {
$item->add_child_item($nfirst);
$result = $nprev;
}
return $result;
}
}
@@ -0,0 +1,49 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_converters.php';
require_once 'cc_general.php';
require_once 'cc_basiclti.php';
class cc_converter_basiclti extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path){
$this->cc_type = cc_version11::basiclti;
$this->defaultfile = 'basiclti.xml';
$this->defaultname = basicltil1_resurce_file::deafultname;
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$rt = new basicltil1_resurce_file();
$title = $this->doc->nodeValue('/activity/basiclti/name');
$rt->set_title($title);
$rt->set_launch_url($this->doc->nodeValue('/activity/basiclti/toolurl'));
$rt->set_launch_icon('');
$rt->set_vendor_code($this->doc->nodeValue('/activity/basiclti/organizationid'));
$rt->set_vendor_description($this->doc->nodeValue('/activity/basiclti/organizationdescr'));
$rt->set_vendor_url($this->doc->nodeValue('/activity/basiclti/organizationurl'));
$this->store($rt, $outdir, $title);
return true;
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2012 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_converters.php');
require_once('cc_general.php');
class cc_converter_folder extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path) {
$this->defaultfile = 'folder.xml';
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$resitem = new cc_item();
$resitem->title = $this->doc->nodeValue('/activity/folder/name');
$this->item->add_child_item($resitem);
$contextid = $this->doc->nodeValue('/activity/@contextid');
cc_helpers::handle_static_content($this->manifest,
$this->rootpath,
$contextid,
$outdir);
return true;
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_converters.php';
require_once 'cc_general.php';
require_once 'cc_forum.php';
class cc_converter_forum extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path){
$this->cc_type = cc_version11::discussiontopic;
$this->defaultfile = 'forum.xml';
$this->defaultname = 'discussion.xml';
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$rt = new forum11_resurce_file();
$title = $this->doc->nodeValue('/activity/forum/name');
$rt->set_title($title);
$text = $this->doc->nodeValue('/activity/forum/intro');
$deps = null;
if (!empty($text)) {
$textformat = intval($this->doc->nodeValue('/activity/forum/introformat'));
$contextid = $this->doc->nodeValue('/activity/@contextid');
$result = cc_helpers::process_linked_files($text,
$this->manifest,
$this->rootpath,
$contextid,
$outdir);
$textformat = ($textformat == 1) ? 'text/html' : 'text/plain';
$rt->set_text($result[0], $textformat);
$deps = $result[1];
}
$this->store($rt, $outdir, $title, $deps);
return true;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2012 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_converters.php';
require_once 'cc_general.php';
class cc_converter_label extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path){
$this->defaultfile = 'label.xml';
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$resitem = new cc_item();
$resitem->title = $this->doc->nodeValue('/activity/label/name');
$this->item->add_child_item($resitem);
return true;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_converters.php';
require_once 'cc_general.php';
require_once 'cc_basiclti.php';
class cc_converter_lti extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path){
$this->cc_type = cc_version11::basiclti;
$this->defaultfile = 'lti.xml';
$this->defaultname = basicltil1_resurce_file::deafultname;
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$rt = new basicltil1_resurce_file();
$contextid = $this->doc->nodeValue('/activity/@contextid');
$title = $this->doc->nodeValue('/activity/lti/name');
$text = $this->doc->nodeValue('/activity/lti/intro');
$rt->set_title($title);
$result = cc_helpers::process_linked_files($text,
$this->manifest,
$this->rootpath,
$contextid,
$outdir);
$rt->set_description($result[0]);
$rt->set_launch_url($this->doc->nodeValue('/activity/lti/toolurl'));
$rt->set_launch_icon('');
$this->store($rt, $outdir, $title, $result[1]);
return true;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_converters.php';
require_once 'cc_general.php';
require_once 'cc_page.php';
class cc_converter_page extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path){
$this->cc_type = cc_version11::webcontent;
$this->defaultfile = 'page.xml';
$this->defaultname = uniqid().'.html';
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$rt = new page11_resurce_file();
$title = $this->doc->nodeValue('/activity/page/name');
$intro = $this->doc->nodeValue('/activity/page/intro');
$contextid = $this->doc->nodeValue('/activity/@contextid');
$pagecontent = $this->doc->nodeValue('/activity/page/content');
$rt->set_title($title);
$rawname = str_replace(' ', '_', strtolower(trim(clean_param($title, PARAM_FILE))));
if (!empty($rawname)) {
$this->defaultname = $rawname.".html";
}
$result = cc_helpers::process_linked_files( $pagecontent,
$this->manifest,
$this->rootpath,
$contextid,
$outdir,
true);
$rt->set_content($result[0]);
$rt->set_intro($intro);
//store everything
$this->store($rt, $outdir, $title, $result[1]);
return true;
}
}
+98
View File
@@ -0,0 +1,98 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2012 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_converters.php');
require_once('cc_general.php');
require_once('cc_asssesment.php');
require_once('cc_assesment_truefalse.php');
require_once('cc_assesment_essay.php');
require_once('cc_assesment_sfib.php');
class cc_converter_quiz extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path) {
$this->cc_type = cc_version11::assessment;
$this->defaultfile = 'quiz.xml';
$this->defaultname = assesment11_resurce_file::deafultname;
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$rt = new assesment11_resurce_file();
$title = $this->doc->nodeValue('/activity/quiz/name');
$rt->set_title($title);
// Metadata.
$metadata = new cc_assesment_metadata();
$rt->set_metadata($metadata);
$metadata->enable_feedback();
$metadata->enable_hints();
$metadata->enable_solutions();
// Attempts.
$max_attempts = (int)$this->doc->nodeValue('/activity/quiz/attempts_number');
if ($max_attempts > 0) {
// Qti does not support number of specific attempts bigger than 5 (??)
if ($max_attempts > 5) {
$max_attempts = cc_qti_values::unlimited;
}
$metadata->set_maxattempts($max_attempts);
}
// Time limit must be converted into minutes.
$timelimit = (int)floor((int)$this->doc->nodeValue('/activity/quiz/timelimit') / 60);
if ($timelimit > 0) {
$metadata->set_timelimit($timelimit);
$metadata->enable_latesubmissions(false);
}
$contextid = $this->doc->nodeValue('/activity/@contextid');
$result = cc_helpers::process_linked_files( $this->doc->nodeValue('/activity/quiz/intro'),
$this->manifest,
$this->rootpath,
$contextid,
$outdir);
cc_assesment_helper::add_assesment_description($rt, $result[0], cc_qti_values::htmltype);
// Section.
$section = new cc_assesment_section();
$rt->set_section($section);
// Process the actual questions.
$ndeps = cc_assesment_helper::process_questions($this->doc,
$this->manifest,
$section,
$this->rootpath,
$contextid,
$outdir);
if ($ndeps === false) {
// No exportable questions in quiz or quiz has no questions
// so just skip it.
return true;
}
// Store any additional dependencies.
$deps = array_merge($result[1], $ndeps);
// Store everything.
$this->store($rt, $outdir, $title, $deps);
return true;
}
}
@@ -0,0 +1,62 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_converters.php');
require_once('cc_general.php');
class cc_converter_resource extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path) {
$this->cc_type = cc_version11::webcontent;
$this->defaultfile = 'resource.xml';
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$title = $this->doc->nodeValue('/activity/resource/name');
$contextid = $this->doc->nodeValue('/activity/@contextid');
$files = cc_helpers::handle_resource_content($this->manifest,
$this->rootpath,
$contextid,
$outdir);
$deps = null;
$resvalue = null;
foreach ($files as $values) {
if ($values[2]) {
$resvalue = $values[0];
break;
}
}
$resitem = new cc_item();
$resitem->identifierref = $resvalue;
$resitem->title = $title;
$this->item->add_child_item($resitem);
// Checking the visibility.
$this->manifest->update_instructoronly($resvalue, !$this->is_visible());
return true;
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_converters.php';
require_once 'cc_general.php';
require_once 'cc_weblink.php';
class cc_converter_url extends cc_converter {
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path){
$this->cc_type = cc_version11::weblink;
$this->defaultfile = 'url.xml';
$this->defaultname = 'weblink.xml';
parent::__construct($item, $manifest, $rootpath, $path);
}
public function convert($outdir) {
$rt = new url11_resurce_file();
$title = $this->doc->nodeValue('/activity/url/name');
$rt->set_title($title);
$url = $this->doc->nodeValue('/activity/url/externalurl');
if (!empty($url)) {
/**
*
* Display value choices
* 0 - automatic (system chooses what to do) (usualy defaults to the open)
* 1 - embed - display within a frame
* 5 - open - just open it full in the same frame
* 6 - in popup - popup - new frame
*/
$display = intval($this->doc->nodeValue('/activity/forum/display'));
$target = ($display == 6) ? '_blank' : '_self';
//TODO: Moodle also supports custom parameters
//this should be transformed somehow into url where possible
$rt->set_url($url, $target);
}
$this->store($rt, $outdir, $title);
return true;
}
}
+148
View File
@@ -0,0 +1,148 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_interfaces.php');
abstract class cc_converter {
/**
*
* Enter description here ...
* @var cc_item
*/
protected $item = null;
/**
*
* Enter description here ...
* @var cc_manifest
*/
protected $manifest = null;
/**
*
* Enter description here ...
* @var string
*/
protected $rootpath = null;
/**
*
* Enter description here ...
* @var string
*/
protected $path = null;
/**
*
* Enter description here ...
* @var string
*/
protected $defaultfile = null;
/**
*
* Enter description here ...
* @var string
*/
protected $defaultname = null;
/**
*
* Enter description here ...
* @var string
*/
protected $cc_type = null;
/**
*
* Document
* @var XMLGenericDocument
*/
protected $doc = null;
/**
*
* ctor
* @param cc_i_item $item
* @param cc_i_manifest $manifest
* @param string $rootpath
* @param string $path
* @throws InvalidArgumentException
*/
public function __construct(cc_i_item &$item, cc_i_manifest &$manifest, $rootpath, $path) {
$rpath = realpath($rootpath);
if (empty($rpath)) {
throw new InvalidArgumentException('Invalid path!');
}
$rpath2 = realpath($path);
if (empty($rpath)) {
throw new InvalidArgumentException('Invalid path!');
}
$doc = new XMLGenericDocument();
if (!$doc->load($path . DIRECTORY_SEPARATOR . $this->defaultfile)) {
throw new RuntimeException('File does not exist!');
}
$this->doc = $doc;
$this->item = $item;
$this->manifest = $manifest;
$this->rootpath = $rpath;
$this->path = $rpath2;
}
/**
*
* performs conversion
* @param string $outdir - root directory of common cartridge
* @return boolean
*/
abstract public function convert($outdir);
/**
*
* Is the element visible in the course?
* @throws RuntimeException
* @return bool
*/
protected function is_visible() {
$tdoc = new XMLGenericDocument();
if (!$tdoc->load($this->path . DIRECTORY_SEPARATOR . 'module.xml')) {
throw new RuntimeException('File does not exist!');
}
$visible = (int)$tdoc->nodeValue('/module/visible');
return ($visible > 0);
}
/**
*
* Stores any files that need to be stored
*/
protected function store(general_cc_file $doc, $outdir, $title, $deps = null) {
$rdir = new cc_resource_location($outdir);
$rtp = $rdir->fullpath(true).$this->defaultname;
if ( $doc->saveTo($rtp) ) {
$resource = new cc_resource($rdir->rootdir(), $this->defaultname, $rdir->dirname(true));
$resource->dependency = empty($deps) ? array() : $deps;
$resource->instructoronly = !$this->is_visible();
$res = $this->manifest->add_resource($resource, null, $this->cc_type);
$resitem = new cc_item();
$resitem->attach_resource($res[0]);
$resitem->title = $title;
$this->item->add_child_item($resitem);
} else {
throw new RuntimeException("Unable to save file {$rtp}!");
}
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_general.php';
class forum1_resurce_file extends general_cc_file {
const deafultname = 'discussion.xml';
protected $rootns = 'dt';
protected $rootname = 'dt:topic';
protected $ccnamespaces = array('dt' => 'http://www.imsglobal.org/xsd/imsdt_v1p0',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance');
protected $ccnsnames = array('dt' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_6/imsdt_v1p0_localised.xsd');
protected $title = null;
protected $text_type = 'text/plain';
protected $text = null;
protected $attachments = array();
public function set_title($title) {
$this->title = self::safexml($title);
}
public function set_text($text, $type='text/plain') {
$this->text = self::safexml($text);
$this->text_type = $type;
}
public function set_attachments(array $attachments) {
$this->attachments = $attachments;
}
protected function on_save() {
$this->append_new_element($this->root, 'title', $this->title);
$text = $this->append_new_element($this->root, 'text', $this->text);
$this->append_new_attribute($text, 'texttype', $this->text_type);
if (!empty($this->attachments)) {
$attachments = $this->append_new_element($this->root, 'attachments');
foreach ($this->attachments as $value) {
$att = $this->append_new_element($attachments, 'attachment');
$this->append_new_attribute($att, 'href', $value);
}
}
return true;
}
}
class forum11_resurce_file extends forum1_resurce_file {
protected $rootns = 'dt';
protected $rootname = 'topic';
protected $ccnamespaces = array('dt' => 'http://www.imsglobal.org/xsd/imsccv1p1/imsdt_v1p1',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance');
protected $ccnsnames = array('dt' => 'http://www.imsglobal.org/profile/cc/ccv1p1/ccv1p1_imsdt_v1p1.xsd');
protected function on_save() {
$rns = $this->ccnamespaces[$this->rootns];
$this->append_new_element_ns($this->root, $rns, 'title', $this->title);
$text = $this->append_new_element_ns($this->root, $rns, 'text', $this->text);
$this->append_new_attribute_ns($text, $rns, 'texttype', $this->text_type);
if (!empty($this->attachments)) {
$attachments = $this->append_new_element_ns($this->root, $rns, 'attachments');
foreach ($this->attachments as $value) {
$att = $this->append_new_element_ns($attachments, $rns, 'attachment');
$this->append_new_attribute_ns($att, $rns, 'href', $value);
}
}
return true;
}
}
+74
View File
@@ -0,0 +1,74 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'gral_lib/cssparser.php';
require_once 'xmlbase.php';
class general_cc_file extends XMLGenericDocument {
/**
*
* Root element
* @var DOMElement
*/
protected $root = null;
protected $rootns = null;
protected $rootname = null;
protected $ccnamespaces = array();
protected $ccnsnames = array();
public function __construct() {
parent::__construct();
foreach ($this->ccnamespaces as $key => $value){
$this->registerNS($key,$value);
}
}
protected function on_create() {
$rootel = $this->append_new_element_ns($this->doc,
$this->ccnamespaces[$this->rootns],
$this->rootname);
//add all namespaces
foreach ($this->ccnamespaces as $key => $value) {
$dummy_attr = "{$key}:dummy";
$this->doc->createAttributeNS($value,$dummy_attr);
}
// add location of schemas
$schemaLocation='';
foreach ($this->ccnsnames as $key => $value) {
$vt = empty($schemaLocation) ? '' : ' ';
$schemaLocation .= $vt.$this->ccnamespaces[$key].' '.$value;
}
if (!empty($schemaLocation) && isset($this->ccnamespaces['xsi'])) {
$this->append_new_attribute_ns($rootel,
$this->ccnamespaces['xsi'],
'xsi:schemaLocation',
$schemaLocation);
}
$this->root = $rootel;
}
}
+116
View File
@@ -0,0 +1,116 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* CC Manifest Interface
*/
interface cc_i_manifest {
public function on_create();
public function on_load();
public function on_save();
public function add_new_organization(cc_i_organization &$org);
public function get_resources();
public function get_resource_list();
public function add_resource(cc_i_resource $res, $identifier=null, $type='webcontent');
public function add_metadata_manifest(cc_i_metadata_manifest $met);
public function add_metadata_resource(cc_i_metadata_resource $met,$identifier);
public function add_metadata_file(cc_i_metadata_file $met,$identifier,$filename);
public function put_nodes();
}
/**
* CC Organization Interface
*/
interface cc_i_organization {
public function add_item(cc_i_item &$item);
public function has_items();
public function attr_value(&$nod, $name, $ns=null);
public function process_organization(&$node,&$doc);
}
/**
* CC Item Interface
*/
interface cc_i_item {
public function add_child_item(cc_i_item &$item);
public function attach_resource($res); // can be object or value
public function has_child_items();
public function attr_value(&$nod, $name, $ns=null);
public function process_item(&$node,&$doc);
}
/**
* CC Resource Interface
*/
interface cc_i_resource {
public function get_attr_value(&$nod, $name, $ns=null);
public function add_resource($fname, $location='');
public function import_resource(DOMElement &$node, cc_i_manifest &$doc);
public function process_resource($manifestroot, &$fname,$folder);
}
/**
* CC Metadata Manifest Interface
*/
interface cc_i_metadata_manifest {
public function add_metadata_general($obj);
public function add_metadata_technical($obj);
public function add_metadata_rights($obj);
public function add_metadata_lifecycle($obj);
}
/**
* CC Metadata Resource Interface
*/
interface cc_i_metadata_resource {
public function add_metadata_resource_educational($obj);
}
/**
* CC Metadata File Interface
*/
interface cc_i_metadata_file {
public function add_metadata_file_educational($obj);
}
+356
View File
@@ -0,0 +1,356 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Manifest management
*
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_utils.php');
require_once('xmlbase.php');
require_once('cc_resources.php');
require_once('cc_version_base.php');
require_once('gral_lib/pathutils.php');
/**
* Manifest Class
*
*/
class cc_manifest extends XMLGenericDocument implements cc_i_manifest {
private $ccversion = null;
private $ccobj = null;
private $rootmanifest = null;
private $activemanifest = null;
private $parentmanifest = null;
private $parentparentmanifest = null;
private $ares = array();
private $mainidentifier = null;
public function __construct($ccver = cc_version::v1, $activemanifest=null,
$parentmanifest=null, $parentparentmanifest=null) {
if (is_int($ccver)) {
$this->ccversion=$ccver;
$classname = "cc_version{$ccver}";
$this->ccobj = new $classname;
parent::__construct('UTF-8', true);
} else if (is_object($ccver) && (get_class($ccver)=='cc_manifest')) {
$this->doc = $ccver->doc;
$this->rootmanifest = $ccver->rootmanifest;
$this->activemanifest = $activemanifest;
$this->parentmanifest = $parentmanifest;
$this->parentparentmanifest = $parentparentmanifest;
$this->ccversion = $ccver->ccversion;
$this->ccobj = $ccver;
$this->register_namespaces_for_xpath();
}
}
/**
* Register Namespace for use XPATH
*
*/
public function register_namespaces_for_xpath() {
$scnam = $this->activemanifest->get_cc_namespaces();
foreach ($scnam as $key => $value) {
$this->registerNS($key, $value);
}
}
/**
* TODO - implement this method - critical
* Enter description here ...
*/
private function fill_manifest() {
}
/**
* Add Metadata For Manifest
*
* @param cc_i_metadata_manifest $met
*/
public function add_metadata_manifest(cc_i_metadata_manifest $met) {
$metanode = $this->node("//imscc:manifest[@identifier='".
$this->activemanifest->manifestID().
"']/imscc:metadata");
$nmeta = $this->activemanifest->create_metadata_node($met, $this->doc, $metanode);
$metanode->appendChild($nmeta);
}
/**
* Add Metadata For Resource
*
* @param cc_i_metadata_resource $met
* @param string $identifier
*/
public function add_metadata_resource(cc_i_metadata_resource $met, $identifier) {
$metanode = $this->node("//imscc:resource".
"[@identifier='".
$identifier.
"']");
$metanode2 = $this->node("//imscc:resource".
"[@identifier='".
$identifier.
"']/imscc:file");
$nspaces = $this->activemanifest->get_cc_namespaces();
$dnode = $this->append_new_element_ns($metanode2, $nspaces['imscc'], 'metadata');
$this->activemanifest->create_metadata_resource_node($met, $this->doc, $dnode);
}
/**
* Add Metadata For File
*
* @param cc_i_metadata_file $met
* @param string $identifier
* @param string $filename
*/
public function add_metadata_file(cc_i_metadata_file $met, $identifier, $filename) {
if (empty($met) || empty($identifier) || empty($filename)) {
throw new Exception('Try to add a metadata file with nulls values given!');
}
$metanode = $this->node("//imscc:resource".
"[@identifier='".
$identifier.
"']/imscc:file".
"[@href='".
$filename.
"']");
$nspaces = $this->activemanifest->get_cc_namespaces();
$dnode = $this->doc->createElementNS($nspaces['imscc'], "metadata");
$metanode->appendChild($dnode);
$this->activemanifest->create_metadata_file_node($met, $this->doc, $dnode);
}
public function on_create() {
$this->activemanifest = cc_builder_creator::factory($this->ccversion);
$this->rootmanifest = $this->activemanifest;
$result = $this->activemanifest->create_manifest($this->doc);
$this->register_namespaces_for_xpath();
return $result;
}
public function get_relative_base_path() {
return $this->activemanifest->base();
}
public function parent_manifest() {
return new cc_manifest($this, $this->parentmanifest, $this->parentparentmanifest);
}
public function root_manifest() {
return new cc_manifest($this, $this->rootmanifest);
}
public function manifestID() {
return $this->activemanifest->manifestID();
}
public function get_manifest_namespaces() {
return $this->rootmanifest->get_cc_namespaces();
}
/**
* Add a new organization
*
* @param cc_i_organization $org
*/
public function add_new_organization(cc_i_organization &$org) {
$norg = $this->activemanifest->create_organization_node($org, $this->doc);
$orgnode = $this->node("//imscc:manifest[@identifier='".
$this->activemanifest->manifestID().
"']/imscc:organizations");
$orgnode->appendChild($norg);
}
public function get_resources($searchspecific='') {
$reslist = $this->get_resource_list($searchspecific);
$resourcelist = array();
foreach ($reslist as $resourceitem) {
$resourcelist[] = new cc_resource($this, $resourceitem);
}
return $resourcelist;
}
public function get_cc_namespace_path($nsname) {
if (is_string($nsname) && (!empty($nsname))) {
$scnam = $this->activemanifest->get_cc_namespaces();
return $scnam[$nsname];
}
return null;
}
public function get_resource_list($searchspecific = '') {
return $this->nodeList("//imscc:manifest[@identifier='".
$this->activemanifest->manifestID().
"']/imscc:resources/imscc:resource".$searchspecific);
}
public function on_load() {
$this->register_namespaces_for_xpath();
$this->fill_manifest();
return true;
}
public function on_save() {
return true;
}
/**
* Add a resource to the manifest
*
* @param cc_i_resource $res
* @param string $identifier
* @param string $type
* @return array
*/
public function add_resource(cc_i_resource $res, $identifier = null, $type = 'webcontent') {
if (!$this->ccobj->valid($type)) {
throw new Exception("Type invalid...");
}
if ($res == null) {
throw new Exception('Invalid Resource or dont give it');
}
$rst = $res;
// TODO: This has to be reviewed since it does not handle multiple files properly.
// Dependencies.
if (is_object($identifier)) {
$this->activemanifest->create_resource_node($rst, $this->doc, $identifier);
} else {
$nresnode = null;
$rst->type = $type;
if (!cc_helpers::is_html($rst->filename)) {
$rst->href = null;
}
$this->activemanifest->create_resource_node($rst, $this->doc, $nresnode);
foreach ($rst->files as $file) {
$ident = $this->get_identifier_by_filename($file);
if ($ident == null) {
$newres = new cc_resource($rst->manifestroot, $file);
if (!cc_helpers::is_html($file)) {
$newres->href = null;
}
$newres->type = 'webcontent';
$this->activemanifest->create_resource_node($newres, $this->doc, $nresnode);
}
}
}
$tmparray = array($rst->identifier, $rst->files[0]);
return $tmparray;
}
private function check_if_exist_in_other($name, $identifier) {
$status = array();
foreach ($this->activemanifest->resources as $value) {
if (($value->identifier != $identifier) && isset($value->files[$name])) {
$status[] = $value->identifier;
}
}
return $status;
}
private function replace_file_x_dependency($depen, $name) {
foreach ($depen as $key => $value) {
($key);
$ident = $this->get_identifier_by_filename($name);
$this->activemanifest->resources[$value]->files =
$this->array_remove_by_value($this->activemanifest->resources[$value]->files, $name);
if (!in_array($ident, $this->activemanifest->resources[$value]->dependency)) {
array_push($this->activemanifest->resources[$value]->dependency, $ident);
}
}
return true;
}
private function get_identifier_by_filename($name) {
$result = null;
if (isset($this->activemanifest->resources_ind[$name])) {
$result = $this->activemanifest->resources_ind[$name];
}
return $result;
}
private function array_remove_by_value($arr, $value) {
return array_values(array_diff($arr, array($value)));
}
private function array_remove_by_key($arr, $key) {
return array_values(array_diff_key($arr, array($key)));
}
public function update_instructoronly($identifier, $value = false) {
if (isset($this->activemanifest->resources[$identifier])) {
$resource = $this->activemanifest->resources[$identifier];
$resource->instructoronly = $value;
}
}
/**
* Append the resources nodes in the Manifest
*
* @return DOMNode
*/
public function put_nodes() {
$resnodestr = "//imscc:manifest[@identifier='".$this->activemanifest->manifestID().
"']/imscc:resources";
$resnode = $this->node($resnodestr);
foreach ($this->activemanifest->resources as $k => $v) {
($k);
$depen = $this->check_if_exist_in_other($v->files[0], $v->identifier);
if (!empty($depen)) {
$this->replace_file_x_dependency($depen, $v->files[0]);
$v->type = 'webcontent';
}
}
foreach ($this->activemanifest->resources as $node) {
$rnode = $this->activemanifest->create_resource_node($node, $this->doc, null);
$resnode->appendChild($rnode);
if ($node->instructoronly) {
$metafileceduc = new cc_metadata_resouce_educational();
$metafileceduc->set_value(intended_user_role::INSTRUCTOR);
$metafile = new cc_metadata_resouce();
$metafile->add_metadata_resource_educational($metafileceduc);
$this->activemanifest->create_metadata_educational($metafile, $this->doc, $rnode);
}
}
return $resnode;
}
}
+236
View File
@@ -0,0 +1,236 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
Defined as specified in CC 1.1
*/
class intended_user_role {
const LEARNER = 'Learner';
const INSTRUCTOR = 'Instructor';
const MENTOR = 'Mentor';
}
class technical_role {
const AUTHOR = 'author';
const PUBLISHER = 'publisher';
const UNKNOWN = 'unknown';
const INITIATOR = 'initiator';
const TERMINATOR = 'terminator';
const VALIDATOR = 'validator';
const EDITOR = 'editor';
const GRAPHICAL_DESIGNER = 'graphical designer';
const TECHNICAL_IMPLEMENTER = 'technical implementer';
const CONTENT_PROVIDER = 'content provider';
const TECHNICAL_VALIDATOR = 'technical validator';
const EDUCATION_VALIDATOR = 'educational validator';
const SCRIPT_WRITER = 'script writer';
const INSTRUCTIONAL_DESIGNER= 'instructional designer';
const SUBJET_MATTER_EXPERT = 'subject matter expert';
}
class rights_copyright {
const YES = 'yes';
const NO = 'no';
}
class rights_cost {
const YES = 'yes';
const NO = 'no';
}
// Language identifier (as defined in ISO 639-1, ISO 639-2, and ISO 3166-1)
class language_lom {
const US_ENGLISH = 'en-US';
const GB_ENGLISH = 'en-GB';
const AR_SPANISH = 'es-AR';
const GR_GREEK = 'el-GR';
}
/**
* Metadata Manifest
*
*/
class cc_metadata_manifest implements cc_i_metadata_manifest {
public $arraygeneral = array();
public $arraytech = array();
public $arrayrights = array();
public $arraylifecycle = array();
public function add_metadata_general($obj){
if (empty($obj)){
throw new Exception('Medatada Object given is invalid or null!');
}
!is_null($obj->title)? $this->arraygeneral['title']=$obj->title:null;
!is_null($obj->language)? $this->arraygeneral['language']=$obj->language:null;
!is_null($obj->description)? $this->arraygeneral['description']=$obj->description:null;
!is_null($obj->keyword)? $this->arraygeneral['keyword']=$obj->keyword:null;
!is_null($obj->coverage)? $this->arraygeneral['coverage']=$obj->coverage:null;
!is_null($obj->catalog)? $this->arraygeneral['catalog']=$obj->catalog:null;
!is_null($obj->entry)? $this->arraygeneral['entry']=$obj->entry:null;
}
public function add_metadata_technical($obj){
if (empty($obj)){
throw new Exception('Medatada Object given is invalid or null!');
}
!is_null($obj->format)? $this->arraytech['format']=$obj->format:null;
}
public function add_metadata_rights($obj){
if (empty($obj)){
throw new Exception('Medatada Object given is invalid or null!');
}
!is_null($obj->copyright)? $this->arrayrights['copyrightAndOtherRestrictions']=$obj->copyright:null;
!is_null($obj->description)? $this->arrayrights['description']=$obj->description:null;
!is_null($obj->cost)? $this->arrayrights['cost']=$obj->cost:null;
}
public function add_metadata_lifecycle($obj){
if (empty($obj)){
throw new Exception('Medatada Object given is invalid or null!');
}
!is_null($obj->role)? $this->arraylifecycle['role']=$obj->role:null;
!is_null($obj->entity)? $this->arraylifecycle['entity']=$obj->entity:null;
!is_null($obj->date)? $this->arraylifecycle['date']=$obj->date:null;
}
}
/**
* Metadata Lifecycle Type
*
*/
class cc_metadata_lifecycle{
public $role = array();
public $entity = array();
public $date = array();
public function set_role($role){
$this->role[] = array($role);
}
public function set_entity($entity){
$this->entity[] = array($entity);
}
public function set_date($date){
$this->date[] = array($date);
}
}
/**
* Metadata Rights Type
*
*/
class cc_metadata_rights {
public $copyright = array();
public $description = array();
public $cost = array();
public function set_copyright($copy){
$this->copyright[] = array($copy);
}
public function set_description($des,$language){
$this->description[] = array($language,$des);
}
public function set_cost($cost){
$this->cost[] = array($cost);
}
}
/**
* Metadata Technical Type
*
*/
class cc_metadata_technical {
public $format = array();
public function set_format($format){
$this->format[] = array($format);
}
}
/**
* Metadata General Type
*
*/
class cc_metadata_general {
public $title = array();
public $language = array();
public $description = array();
public $keyword = array();
public $coverage = array();
public $catalog = array();
public $entry = array();
public function set_coverage($coverage,$language){
$this->coverage[] = array($language,$coverage);
}
public function set_description($description,$language){
$this->description[] = array($language,$description);
}
public function set_keyword($keyword,$language){
$this->keyword[] = array($language,$keyword);
}
public function set_language($language){
$this->language[] = array($language);
}
public function set_title($title,$language){
$this->title[] = array($language,$title);
}
public function set_catalog($cat){
$this->catalog[] = array($cat);
}
public function set_entry($entry){
$this->entry[] = array($entry);
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Metadata management
*
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Metadata File Education Type
*
*/
class cc_metadata_file_educational{
public $value = array();
public function set_value($value){
$arr = array($value);
$this->value[] = $arr;
}
}
/**
* Metadata File
*
*/
class cc_metadata_file implements cc_i_metadata_file {
public $arrayeducational = array();
public function add_metadata_file_educational($obj){
if (empty($obj)){
throw new Exception('Medatada Object given is invalid or null!');
}
!is_null($obj->value)? $this->arrayeducational['value']=$obj->value:null;
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Metadata managing
*
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Metadata Resource Educational Type
*
*/
class cc_metadata_resouce_educational{
public $value = array();
public function set_value($value){
$arr = array($value);
$this->value[] = $arr;
}
}
/**
* Metadata Resource
*
*/
class cc_metadata_resouce implements cc_i_metadata_resource {
public $arrayeducational = array();
public function add_metadata_resource_educational($obj){
if (empty($obj)){
throw new Exception('Medatada Object given is invalid or null!');
}
!is_null($obj->value)? $this->arrayeducational['value']=$obj->value:null;
}
}
+280
View File
@@ -0,0 +1,280 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_utils.php';
require_once 'cc_version_base.php';
require_once 'cc_resources.php';
require_once 'cc_manifest.php';
/**
* Organization Class
*
*/
class cc_organization implements cc_i_organization {
public $title = null;
public $identifier = null;
public $structure = null;
public $itemlist = null;
private $metadata = null;
private $sequencing = null;
/** @var bool true if empty, otherwise false. */
protected $isempty;
public function __construct($node=null, $doc=null) {
if (is_object($node) && is_object($doc)) {
$this->process_organization($node,$doc);
} else {
$this->init_new();
}
}
/**
* Add one Item into the Organization
*
* @param cc_i_item $item
*/
public function add_item(cc_i_item &$item) {
if (is_null($this->itemlist)) {
$this->itemlist = array();
}
$this->itemlist[$item->identifier] = $item;
}
/**
* Add new Item into the Organization
*
* @param string $title
* @return cc_i_item
*/
public function add_new_item($title='') {
$nitem = new cc_item();
$nitem->title = $title;
$this->add_item($nitem);
return $nitem;
}
public function has_items() {
return is_array($this->itemlist) && (count($this->itemlist) > 0);
}
public function attr_value(&$nod, $name, $ns=null) {
return is_null($ns) ?
($nod->hasAttribute($name) ? $nod->getAttribute($name) : null) :
($nod->hasAttributeNS($ns, $name) ? $nod->getAttributeNS($ns, $name) : null);
}
public function process_organization(&$node,&$doc) {
$this->identifier = $this->attr_value($node,"identifier");
$this->structure = $this->attr_value($node,"structure");
$this->title = '';
$nlist = $node->getElementsByTagName('title');
if (is_object($nlist) && ($nlist->length > 0) ) {
$this->title = $nlist->item(0)->nodeValue;
}
$nlist = $doc->nodeList("//imscc:organization[@identifier='".$this->identifier."']/imscc:item");
$this->itemlist=array();
foreach ($nlist as $item) {
$this->itemlist[$item->getAttribute("identifier")] = new cc_item($item,$doc);
}
$this->isempty=false;
}
public function init_new() {
$this->title = null;
$this->identifier = cc_helpers::uuidgen('O_');
$this->structure = 'rooted-hierarchy';
$this->itemlist = null;
$this->metadata = null;
$this->sequencing = null;
}
public function uuidgen() {
$uuid = sprintf('%04x%04x', mt_rand(0, 65535), mt_rand(0, 65535));
return strtoupper(trim($uuid));
}
}
/**
* Item Class
*
*/
class cc_item implements cc_i_item {
public $identifier = null;
public $identifierref = null;
public $isvisible = null;
public $title = null;
public $parameters = null;
public $childitems = null;
private $parentItem = null;
private $isempty = true;
/** @var mixed node structure. */
public $structure;
public function __construct($node=null,$doc=null) {
if (is_object($node)) {
$clname = get_class($node);
if ($clname =='cc_resource') {
$this->init_new_item();
$this->identifierref = $node->identifier;
$this->title = is_string($doc) && (!empty($doc)) ? $doc : 'item';
} else if ($clname =='cc_manifest') {
$this->init_new_item();
$this->identifierref = $node->manifestID();
$this->title = is_string($doc) && (!empty($doc)) ? $doc : 'item';
} else if ( is_object($doc)){
$this->process_item($node,$doc);
} else {
$this->init_new_item();
}
} else {
$this->init_new_item();
}
}
public function attr_value(&$nod, $name, $ns=null) {
return is_null($ns) ?
($nod->hasAttribute($name) ? $nod->getAttribute($name) : null) :
($nod->hasAttributeNS($ns, $name) ? $nod->getAttributeNS($ns, $name) : null);
}
public function process_item(&$node,&$doc) {
$this->identifier = $this->attr_value($node,"identifier");
$this->structure = $this->attr_value($node,"structure");
$this->identifierref = $this->attr_value($node,"identifierref");
$atr = $this->attr_value($node,"isvisible");
$this->isvisible = is_null($atr) ? true : $atr;
$nlist = $node->getElementsByTagName('title');
if (is_object($nlist) && ($nlist->length > 0) ) {
$this->title = $nlist->item(0)->nodeValue;
}
$nlist = $doc->nodeList("//imscc:item[@identifier='".$this->identifier."']/imscc:item");
if ($nlist->length > 0) {
$this->childitems=array();
foreach ($nlist as $item) {
$key=$this->attr_value($item,"identifier");
$this->childitems[$key] = new cc_item($item,$doc);
}
}
$this->isempty = false;
}
/**
* Add one Child Item
*
* @param cc_i_item $item
*/
public function add_child_item(cc_i_item &$item) {
if (is_null($this->childitems)) {
$this->childitems = array();
}
$this->childitems[$item->identifier] = $item;
}
/**
* Add new child Item
*
* @param string $title
* @return cc_i_item
*/
public function add_new_child_item($title='') {
$sc = new cc_item();
$sc->title = $title;
$this->add_child_item($sc);
return $sc;
}
public function attach_resource($resource) {
if ($this->has_child_items()) {
throw new Exception("Can not attach resource to item that contains other items!");
}
$resident = null;
if (is_string($resource)) {
$resident = $resource;
} else if (is_object($resource)) {
$clname = get_class($resource);
if ($clname == 'cc_resource') {
$resident = $resource->identifier;
} else
if ($clname == 'cc_manifest') {
$resident = $resource->manifestID();
} else {
throw new Exception("Unable to attach resource. Invalid object.");
}
}
if (is_null($resident) || (empty($resident))) {
throw new Exception("Resource must have valid identifier!");
}
$this->identifierref = $resident;
}
public function has_child_items() {
return is_array($this->childitems) && (count($this->childitems) > 0);
}
public function child_item($identifier) {
return $this->has_child_items() ? $this->childitems[$identifier] : null;
}
public function init_clean() {
$this->identifier = null;
$this->isvisible = null;
$this->title = null;
$this->parameters = null;
$this->childitems = null;
$this->parentItem = null;
$this->isempty = true;
}
public function init_new_item() {
$this->identifier = cc_helpers::uuidgen('I_');
$this->isvisible = true; //default is true
$this->title = null;
$this->parameters = null;
$this->childitems = null;
$this->parentItem = null;
$this->isempty = false;
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_general.php');
class page11_resurce_file extends general_cc_file {
protected $rootns = 'xmlns';
protected $rootname = 'html';
protected $ccnamespaces = array('xmlns' => 'http://www.w3.org/1999/xhtml');
protected $content = null;
protected $title = null;
protected $intro = null;
public function set_content($value) {
// We are not cleaning up this one on purpose.
$this->content = $value;
}
public function set_title($value) {
$this->title = self::safexml($value);
}
public function set_intro($value) {
$this->intro = self::safexml(strip_tags($value));
}
protected function on_create() {
$impl = new DOMImplementation();
$dtd = $impl->createDocumentType( 'html',
'-//W3C//DTD XHTML 1.0 Strict//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd');
$doc = $impl->createDocument($this->ccnamespaces[$this->rootns], null, $dtd);
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$this->doc = $doc;
parent::on_create();
}
public function on_save() {
$rns = $this->ccnamespaces[$this->rootns];
// Add the basic tags.
$head = $this->append_new_element_ns($this->root, $rns, 'head');
$this->append_new_attribute_ns($head, $rns, 'profile', 'http://dublincore.org/documents/dc-html/');
// Linking Dublin Core Metadata 1.1.
$link_dc = $this->append_new_element_ns($head, $rns, 'link');
$this->append_new_attribute_ns($link_dc, $rns, 'rel', 'schema.DC');
$this->append_new_attribute_ns($link_dc, $rns, 'href', 'http://purl.org/dc/elements/1.1/');
$link_dcterms = $this->append_new_element_ns($head, $rns, 'link');
$this->append_new_attribute_ns($link_dcterms, $rns, 'rel', 'schema.DCTERMS');
$this->append_new_attribute_ns($link_dcterms, $rns, 'href', 'http://purl.org/dc/terms/');
// Content type.
$meta_type = $this->append_new_element_ns($head, $rns, 'meta');
$this->append_new_attribute_ns($meta_type, $rns, 'name', 'DC.type');
$this->append_new_attribute_ns($meta_type, $rns, 'scheme', 'DCTERMS.DCMIType');
$this->append_new_attribute_ns($meta_type, $rns, 'content', 'Text');
// Content description.
if (!empty($this->intro)) {
$meta_description = $this->append_new_element_ns($head, $rns, 'meta');
$this->append_new_attribute_ns($meta_description, $rns, 'name', 'DC.description');
$this->append_new_attribute_ns($meta_description, $rns, 'content', $this->intro);
}
$meta = $this->append_new_element_ns($head, $rns, 'meta');
$this->append_new_attribute_ns($meta, $rns, 'http-equiv', 'Content-type');
$this->append_new_attribute_ns($meta, $rns, 'content', 'text/html; charset=UTF-8');
// Set the title.
$title = $this->append_new_element_ns($head, $rns, 'title', $this->title);
$body = $this->append_new_element_ns($this->root, $rns, 'body');
// We are unable to use DOM for embedding HTML due to numerous content errors.
// Therefore we place a dummy tag that will be later replaced with the real content.
$this->append_new_element_ns($body, $rns, 'div', '##REPLACE##');
return true;
}
public function saveTo($fname) {
$result = $this->on_save();
if ($result) {
$dret = str_replace('<?xml version="1.0"?>'."\n", '', $this->viewXML());
$dret = str_replace('<div>##REPLACE##</div>', $this->content, $dret);
$result = (file_put_contents($fname, $dret) !== false);
if ($result) {
$this->filename = $fname;
$this->processPath();
}
}
return $result;
}
}
+235
View File
@@ -0,0 +1,235 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_interfaces.php');
require_once('xmlbase.php');
require_once('gral_lib/pathutils.php');
require_once('gral_lib/ccdependencyparser.php');
require_once('cc_version_base.php');
require_once('cc_version1.php');
require_once('cc_manifest.php');
/**
* Common Cartridge Version
*
*/
class cc_version{
const v1 = 1;
const v11 = 11;
}
class cc1_resource_type {
const webcontent = 'webcontent';
const questionbank = 'imsqti_xmlv1p2/imscc_xmlv1p0/question-bank';
const assessment = 'imsqti_xmlv1p2/imscc_xmlv1p0/assessment';
const associatedcontent = 'associatedcontent/imscc_xmlv1p0/learning-application-resource';
const discussiontopic = 'imsdt_xmlv1p0';
const weblink = 'imswl_xmlv1p0';
public static $checker = array(self::webcontent,
self::assessment,
self::associatedcontent,
self::discussiontopic,
self::questionbank,
self::weblink);
}
class cc11_resource_type {
const webcontent = 'webcontent';
const questionbank = 'imsqti_xmlv1p2/imscc_xmlv1p1/question-bank';
const assessment = 'imsqti_xmlv1p2/imscc_xmlv1p1/assessment';
const associatedcontent = 'associatedcontent/imscc_xmlv1p1/learning-application-resource';
const discussiontopic = 'imsdt_xmlv1p1';
const weblink = 'imswl_xmlv1p1';
const basiclti = 'imsbasiclti_xmlv1p0';
public static $checker = array(self::webcontent,
self::assessment,
self::associatedcontent,
self::discussiontopic,
self::questionbank,
self::weblink,
self::basiclti);
}
/**
* Resource Class
*
*/
class cc_resource implements cc_i_resource {
public $identifier = null;
public $type = null;
public $dependency = array();
public $identifierref = null;
public $href = null;
public $base = null;
public $persiststate = null;
public $metadata = array();
public $filename = null;
public $files = array();
public $isempty = null;
public $manifestroot = null;
public $folder = null;
public $instructoronly = false;
private $throwonerror = true;
public function __construct($manifest, $file, $folder='', $throwonerror = true) {
$this->throwonerror = $throwonerror;
if (is_string($manifest)) {
$this->folder = $folder;
$this->process_resource($manifest, $file, $folder);
$this->manifestroot = $manifest;
} else if (is_object($manifest)) {
$this->import_resource($file, $manifest);
}
}
/**
* Add resource
*
* @param string $fname
* @param string $location
*/
public function add_resource($fname, $location ='') {
$this->process_resource($fname, $location, null);
}
/**
* Import a resource
*
* @param DOMElement $node
* @param cc_i_manifest $doc
*/
public function import_resource(DOMElement &$node, cc_i_manifest &$doc) {
$searchstr = "//imscc:manifest[@identifier='".$doc->manifestID().
"']/imscc:resources/imscc:resource";
$this->identifier = $this->get_attr_value($node, "identifier");
$this->type = $this->get_attr_value($node, "type");
$this->href = $this->get_attr_value($node, "href");
$this->base = $this->get_attr_value($node, "base");
$this->persiststate = null;
$nodo = $doc->nodeList($searchstr."[@identifier='".
$this->identifier."']/metadata/@href");
$this->metadata = $nodo->nodeValue;
$this->filename = $this->href;
$nlist = $doc->nodeList($searchstr."[@identifier='".
$this->identifier."']/imscc:file/@href");
$this->files = array();
foreach ($nlist as $file) {
$this->files[] = $file->nodeValue;
}
$nlist = $doc->nodeList($searchstr."[@identifier='".
$this->identifier."']/imscc:dependency/@identifierref");
$this->dependency = array();
foreach ($nlist as $dependency) {
$this->dependency[] = $dependency->nodeValue;
}
$this->isempty = false;
}
/**
* Get a attribute value
*
* @param DOMElement $nod
* @param string $name
* @param string $ns
* @return string
*/
public function get_attr_value(&$nod, $name, $ns=null) {
if (is_null($ns)) {
return ($nod->hasAttribute($name) ? $nod->getAttribute($name) : null);
}
return ($nod->hasAttributeNS($ns, $name) ? $nod->getAttributeNS($ns, $name) : null);
}
/**
* Process a resource
*
* @param string $manifestroot
* @param string $fname
* @param string $folder
*/
public function process_resource($manifestroot, &$fname, $folder) {
$file = empty($folder) ? $manifestroot.'/'.$fname : $manifestroot.'/'.$folder.'/'.$fname;
if (!file_exists($file) && $this->throwonerror) {
throw new Exception('The file doesnt exist!');
}
GetDepFiles($manifestroot, $fname, $this->folder, $this->files);
array_unshift($this->files, $folder.$fname);
$this->init_empty_new();
$this->href = $folder.$fname;
$this->identifierref = $folder.$fname;
$this->filename = $fname;
$this->isempty = false;
$this->folder = $folder;
}
public function adjust_path($mroot, $fname) {
$result = null;
if (file_exists($fname->filename)) {
$result = pathDiff($fname->filename, $mroot);
} else if (file_exists($mroot.$fname->filename) || file_exists($mroot.DIRECTORY_SEPARATOR.$fname->filename)) {
$result = $fname->filename;
toUrlPath($result);
$result = trim($result, "/");
}
return $result;
}
public function init_clean() {
$this->identifier = null;
$this->type = null;
$this->href = null;
$this->base = null;
$this->metadata = array();
$this->dependency = array();
$this->identifierref = null;
$this->persiststate = null;
$this->filename = '';
$this->files = array();
$this->isempty = true;
}
public function init_empty_new() {
$this->identifier = cc_helpers::uuidgen('I_', '_R');
$this->type = null;
$this->href = null;
$this->persiststate = null;
$this->filename = null;
$this->isempty = false;
$this->identifierref = null;
}
public function get_manifestroot() {
return $this->manifestroot;
}
}
+468
View File
@@ -0,0 +1,468 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('xmlbase.php');
/**
*
* Various helper utils
* @author Darko Miletic dmiletic@moodlerooms.com
*
*/
abstract class cc_helpers {
/**
* Checks extension of the supplied filename
*
* @param string $filename
*/
public static function is_html($filename) {
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
return in_array($extension, array('htm', 'html'));
}
/**
* Generates unique identifier
* @param string $prefix
* @param string $suffix
* @return string
*/
public static function uuidgen($prefix = '', $suffix = '', $uppercase = true) {
$uuid = trim(sprintf('%s%04x%04x%s', $prefix, mt_rand(0, 65535), mt_rand(0, 65535), $suffix));
$result = $uppercase ? strtoupper($uuid) : strtolower($uuid);
return $result;
}
/**
* Creates new folder with random name
* @param string $where
* @param string $prefix
* @param string $suffix
* @return mixed - directory short name or false in case of failure
*/
public static function randomdir($where, $prefix = '', $suffix = '') {
global $CFG;
$dirname = false;
$randomname = self::uuidgen($prefix, $suffix, false);
$newdirname = $where.DIRECTORY_SEPARATOR.$randomname;
if (mkdir($newdirname)) {
chmod($newdirname, $CFG->directorypermissions);
$dirname = $randomname;
}
return $dirname;
}
public static function build_query($attributes, $search) {
$result = '';
foreach ($attributes as $attribute) {
if ($result != '') {
$result .= ' | ';
}
$result .= "//*[starts-with(@{$attribute},'{$search}')]/@{$attribute}";
}
return $result;
}
public static function process_embedded_files(&$doc, $attributes, $search, $customslash = null) {
$result = array();
$query = self::build_query($attributes, $search);
$list = $doc->nodeList($query);
foreach ($list as $filelink) {
$rvalue = str_replace($search, '', $filelink->nodeValue);
if (!empty($customslash)) {
$rvalue = str_replace($customslash, '/', $rvalue);
}
$result[] = rawurldecode($rvalue);
}
return $result;
}
/**
*
* Get list of embedded files
* @param string $html
* @return multitype:mixed
*/
public static function embedded_files($html) {
$result = array();
$doc = new XMLGenericDocument();
$doc->doc->validateOnParse = false;
$doc->doc->strictErrorChecking = false;
if (!empty($html) && $doc->loadHTML($html)) {
$attributes = array('src', 'href');
$result1 = self::process_embedded_files($doc, $attributes, '@@PLUGINFILE@@');
$result2 = self::process_embedded_files($doc, $attributes, '$@FILEPHP@$', '$@SLASH@$');
$result = array_merge($result1, $result2);
}
return $result;
}
public static function embedded_mapping($packageroot, $contextid = null) {
$main_file = $packageroot . DIRECTORY_SEPARATOR . 'files.xml';
$mfile = new XMLGenericDocument();
if (!$mfile->load($main_file)) {
return false;
}
$query = "/files/file[filename!='.']";
if (!empty($contextid)) {
$query .= "[contextid='{$contextid}']";
}
$files = $mfile->nodeList($query);
$depfiles = array();
foreach ($files as $node) {
$mainfile = intval($mfile->nodeValue('sortorder', $node));
$filename = $mfile->nodeValue('filename', $node);
$filepath = $mfile->nodeValue('filepath', $node);
$source = $mfile->nodeValue('source', $node);
$author = $mfile->nodeValue('author', $node);
$license = $mfile->nodeValue('license', $node);
$hashedname = $mfile->nodeValue('contenthash', $node);
$hashpart = substr($hashedname, 0, 2);
$location = 'files'.DIRECTORY_SEPARATOR.$hashpart.DIRECTORY_SEPARATOR.$hashedname;
$type = $mfile->nodeValue('mimetype', $node);
$depfiles[$filepath.$filename] = array( $location,
($mainfile == 1),
strtolower(str_replace(' ', '_', $filename)),
$type,
$source,
$author,
$license,
strtolower(str_replace(' ', '_', $filepath)));
}
return $depfiles;
}
public static function add_files(cc_i_manifest &$manifest, $packageroot, $outdir, $allinone = true) {
global $CFG;
if (pkg_static_resources::instance()->finished) {
return;
}
$files = cc_helpers::embedded_mapping($packageroot);
$rdir = $allinone ? new cc_resource_location($outdir) : null;
foreach ($files as $virtual => $values) {
$clean_filename = $values[2];
if (!$allinone) {
$rdir = new cc_resource_location($outdir);
}
$rtp = $rdir->fullpath().$values[7].$clean_filename;
//Are there any relative virtual directories?
//let us try to recreate them
$justdir = $rdir->fullpath(false).$values[7];
if (!file_exists($justdir)) {
if (!mkdir($justdir, $CFG->directorypermissions, true)) {
throw new RuntimeException('Unable to create directories!');
}
}
$source = $packageroot.DIRECTORY_SEPARATOR.$values[0];
if (!copy($source, $rtp)) {
throw new RuntimeException('Unable to copy files!');
}
$resource = new cc_resource($rdir->rootdir(),
$values[7].$clean_filename,
$rdir->dirname(false));
$res = $manifest->add_resource($resource, null, cc_version11::webcontent);
pkg_static_resources::instance()->add($virtual,
$res[0],
$rdir->dirname(false).$values[7].$clean_filename,
$values[1],
$resource);
}
pkg_static_resources::instance()->finished = true;
}
/**
*
* Excerpt from IMS CC 1.1 overview :
* No spaces in filenames, directory and file references should
* employ all lowercase or all uppercase - no mixed case
*
* @param cc_i_manifest $manifest
* @param string $packageroot
* @param integer $contextid
* @param string $outdir
* @param boolean $allinone
* @throws RuntimeException
*/
public static function handle_static_content(cc_i_manifest &$manifest, $packageroot, $contextid, $outdir, $allinone = true) {
self::add_files($manifest, $packageroot, $outdir, $allinone);
return pkg_static_resources::instance()->get_values();
}
public static function handle_resource_content(cc_i_manifest &$manifest, $packageroot, $contextid, $outdir, $allinone = true) {
$result = array();
self::add_files($manifest, $packageroot, $outdir, $allinone);
$files = self::embedded_mapping($packageroot, $contextid);
$rootnode = null;
$rootvals = null;
$depfiles = array();
$depres = array();
$flocation = null;
foreach ($files as $virtual => $values) {
$vals = pkg_static_resources::instance()->get_identifier($virtual);
$resource = $vals[3];
$identifier = $resource->identifier;
$flocation = $vals[1];
if ($values[1]) {
$rootnode = $resource;
$rootvals = $flocation;
continue;
}
$depres[] = $identifier;
$depfiles[] = $vals[1];
$result[$virtual] = array($identifier, $flocation, false);
}
if (!empty($rootnode)) {
$rootnode->files = array_merge($rootnode->files, $depfiles);
$result[$virtual] = array($rootnode->identifier, $rootvals, true);
}
return $result;
}
public static function process_linked_files($content, cc_i_manifest &$manifest, $packageroot,
$contextid, $outdir, $webcontent = false) {
// Detect all embedded files
// locate their physical counterparts in moodle 2 backup
// copy all files in the cc package stripping any spaces and using only lowercase letters
// add those files as resources of the type webcontent to the manifest
// replace the links to the resource using $IMS-CC-FILEBASE$ and their new locations
// cc_resource has array of files and array of dependencies
// most likely we would need to add all files as independent resources and than
// attach them all as dependencies to the forum tag.
$lfiles = self::embedded_files($content);
$text = $content;
$deps = array();
if (!empty($lfiles)) {
$files = self::handle_static_content($manifest,
$packageroot,
$contextid,
$outdir);
$replaceprefix = $webcontent ? '' : '$IMS-CC-FILEBASE$';
foreach ($lfiles as $lfile) {
if (isset($files[$lfile])) {
$filename = str_replace('%2F', '/', rawurlencode($lfile));
$content = str_replace('@@PLUGINFILE@@'.$filename,
$replaceprefix.'../'.$files[$lfile][1],
$content);
// For the legacy stuff.
$content = str_replace('$@FILEPHP@$'.str_replace('/', '$@SLASH@$', $filename),
$replaceprefix.'../'.$files[$lfile][1],
$content);
$deps[] = $files[$lfile][0];
}
}
$text = $content;
}
return array($text, $deps);
}
public static function relative_location($originpath, $linkingpath) {
return false;
}
}
final class cc_resource_location {
/**
*
* Root directory
* @var string
*/
private $rootdir = null;
/**
*
* new directory
* @var string
*/
private $dir = null;
/**
*
* Full precalculated path
* @var string
*/
private $fullpath = null;
/**
*
* ctor
* @param string $rootdir - path to the containing directory
* @throws InvalidArgumentException
* @throws RuntimeException
*/
public function __construct($rootdir) {
$rdir = realpath($rootdir);
if (empty($rdir)) {
throw new InvalidArgumentException('Invalid path!');
}
$dir = cc_helpers::randomdir($rdir, 'i_');
if ($dir === false) {
throw new RuntimeException('Unable to create directory!');
}
$this->rootdir = $rdir;
$this->dir = $dir;
$this->fullpath = $rdir.DIRECTORY_SEPARATOR.$dir;
}
/**
*
* Newly created directory
* @return string
*/
public function dirname($endseparator=false) {
return $this->dir.($endseparator ? '/' : '');
}
/**
*
* Full path to the new directory
* @return string
*/
public function fullpath($endseparator=false) {
return $this->fullpath.($endseparator ? DIRECTORY_SEPARATOR : '');
}
/**
* Returns containing dir
* @return string
*/
public function rootdir($endseparator=false) {
return $this->rootdir.($endseparator ? DIRECTORY_SEPARATOR : '');
}
}
class pkg_static_resources {
/**
* @var array
*/
private $values = array();
/**
* @var boolean
*/
public $finished = false;
/**
* @var pkg_static_resources
*/
private static $instance = null;
private function __clone() {
}
private function __construct() {
}
/**
* @return pkg_static_resources
*/
public static function instance() {
if (empty(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c();
}
return self::$instance;
}
/**
*
* add new element
* @param string $identifier
* @param string $file
* @param boolean $main
*/
public function add($key, $identifier, $file, $main, $node = null) {
$this->values[$key] = array($identifier, $file, $main, $node);
}
/**
* @return array
*/
public function get_values() {
return $this->values;
}
public function get_identifier($location) {
return isset($this->values[$location]) ? $this->values[$location] : false;
}
public function reset() {
$this->values = array();
$this->finished = false;
}
}
class pkg_resource_dependencies {
/**
* @var array
*/
private $values = array();
/**
* @var pkg_resource_dependencies
*/
private static $instance = null;
private function __clone() {
}
private function __construct() {
}
/**
* @return pkg_resource_dependencies
*/
public static function instance() {
if (empty(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c();
}
return self::$instance;
}
/**
* @param array $deps
*/
public function add(array $deps) {
$this->values = array_merge($this->values, $deps);
}
public function reset() {
$this->values = array();
}
/**
* @return array
*/
public function get_deps() {
return $this->values;
}
}
+524
View File
@@ -0,0 +1,524 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_utils.php');
require_once('cc_version_base.php');
require_once('cc_organization.php');
/**
* Version 1 class of Common Cartridge
*
*/
class cc_version1 extends cc_version_base {
const webcontent = 'webcontent';
const questionbank = 'imsqti_xmlv1p2/imscc_xmlv1p0/question-bank';
const assessment = 'imsqti_xmlv1p2/imscc_xmlv1p0/assessment';
const associatedcontent = 'associatedcontent/imscc_xmlv1p0/learning-application-resource';
const discussiontopic = 'imsdt_xmlv1p0';
const weblink = 'imswl_xmlv1p0';
/** @var array CC URL profiles. */
protected $ccnsnames = [];
public static $checker = array(self::webcontent,
self::assessment,
self::associatedcontent,
self::discussiontopic,
self::questionbank,
self::weblink);
/**
* Validate if the type are valid or not
*
* @param string $type
* @return bool
*/
public function valid($type) {
return in_array($type, self::$checker);
}
public function __construct() {
$this->ccnamespaces = array('imscc' => 'http://www.imsglobal.org/xsd/imscc/imscp_v1p1',
'lomimscc' => 'http://ltsc.ieee.org/xsd/imscc/LOM',
'lom' => 'http://ltsc.ieee.org/xsd/LOM',
'voc' => 'http://ltsc.ieee.org/xsd/LOM/vocab',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance'
);
$this->ccnsnames = array(
'imscc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/imscp_v1p2_localised.xsd',
'lom' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_2/lomLoose_localised.xsd',
'lomimscc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_1/lomLoose_localised.xsd',
'voc' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_2/vocab/loose.xsd'
);
$this->ccversion = '1.0.0';
$this->camversion = '1.0.0';
$this->_generator = 'Moodle 2 Common Cartridge generator';
}
protected function on_create(DOMDocument &$doc, $rootmanifestnode = null, $nmanifestID = null) {
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$this->manifestID = is_null($nmanifestID) ? cc_helpers::uuidgen('M_') : $nmanifestID;
$mUUID = $doc->createAttribute('identifier');
$mUUID->nodeValue = $this->manifestID;
if (is_null($rootmanifestnode)) {
if (!empty($this->_generator)) {
$comment = $doc->createComment($this->_generator);
$doc->appendChild($comment);
}
$rootel = $doc->createElementNS($this->ccnamespaces['imscc'], 'manifest');
$rootel->appendChild($mUUID);
$doc->appendChild($rootel);
// Add all namespaces.
foreach ($this->ccnamespaces as $key => $value) {
$dummy_attr = $key.":dummy";
$doc->createAttributeNS($value, $dummy_attr);
}
// Add location of schemas.
$schemaLocation = '';
foreach ($this->ccnsnames as $key => $value) {
$vt = empty($schemaLocation) ? '' : ' ';
$schemaLocation .= $vt.$this->ccnamespaces[$key].' '.$value;
}
$aSchemaLoc = $doc->createAttributeNS($this->ccnamespaces['xsi'], 'xsi:schemaLocation');
$aSchemaLoc->nodeValue = $schemaLocation;
$rootel->appendChild($aSchemaLoc);
} else {
$rootel = $doc->createElementNS($this->ccnamespaces['imscc'], 'imscc:manifest');
$rootel->appendChild($mUUID);
}
$metadata = $doc->createElementNS($this->ccnamespaces['imscc'], 'metadata');
$schema = $doc->createElementNS($this->ccnamespaces['imscc'], 'schema', 'IMS Common Cartridge');
$schemaversion = $doc->createElementNS($this->ccnamespaces['imscc'], 'schemaversion', $this->ccversion);
$metadata->appendChild($schema);
$metadata->appendChild($schemaversion);
$rootel->appendChild($metadata);
if (!is_null($rootmanifestnode)) {
$rootmanifestnode->appendChild($rootel);
}
$organizations = $doc->createElementNS($this->ccnamespaces['imscc'], 'organizations');
$rootel->appendChild($organizations);
$resources = $doc->createElementNS($this->ccnamespaces['imscc'], 'resources');
$rootel->appendChild($resources);
return true;
}
protected function update_attribute(DOMDocument &$doc, $attrname, $attrvalue, DOMElement &$node) {
$busenew = (is_object($node) && $node->hasAttribute($attrname));
$nResult = null;
if (!$busenew && is_null($attrvalue)) {
$node->removeAttribute($attrname);
} else {
$nResult = $busenew ? $node->getAttributeNode($attrname) : $doc->createAttribute($attrname);
$nResult->nodeValue = $attrvalue;
if (!$busenew) {
$node->appendChild($nResult);
}
}
return $nResult;
}
protected function update_attribute_ns(DOMDocument &$doc, $attrname, $attrnamespace,$attrvalue, DOMElement &$node) {
$busenew = (is_object($node) && $node->hasAttributeNS($attrnamespace, $attrname));
$nResult = null;
if (!$busenew && is_null($attrvalue)) {
$node->removeAttributeNS($attrnamespace, $attrname);
} else {
$nResult = $busenew ? $node->getAttributeNodeNS($attrnamespace, $attrname) :
$doc->createAttributeNS($attrnamespace, $attrname);
$nResult->nodeValue = $attrvalue;
if (!$busenew) {
$node->appendChild($nResult);
}
}
return $nResult;
}
protected function get_child_node(DOMDocument &$doc, $itemname, DOMElement &$node) {
$nlist = $node->getElementsByTagName($itemname);
$item = is_object($nlist) && ($nlist->length > 0) ? $nlist->item(0) : null;
return $item;
}
protected function update_child_item(DOMDocument &$doc, $itemname, $itemvalue, DOMElement &$node, $attrtostore=null) {
$tnode = $this->get_child_node($doc, 'title', $node);
$usenew = is_null($tnode);
$tnode = $usenew ? $doc->createElementNS($this->ccnamespaces['imscc'], $itemname) : $tnode;
if (!is_null($attrtostore)) {
foreach ($attrtostore as $key => $value) {
$this->update_attribute($doc, $key, $value, $tnode);
}
}
$tnode->nodeValue = $itemvalue;
if ($usenew) {
$node->appendChild($tnode);
}
}
protected function update_items($items, DOMDocument &$doc, DOMElement &$xmlnode) {
foreach ($items as $key => $item) {
$itemnode = $doc->createElementNS($this->ccnamespaces['imscc'], 'item');
$this->update_attribute($doc, 'identifier' , $key , $itemnode);
$this->update_attribute($doc, 'identifierref', $item->identifierref, $itemnode);
$this->update_attribute($doc, 'parameters' , $item->parameters , $itemnode);
if (!empty($item->title)) {
$titlenode = $doc->createElementNS($this->ccnamespaces['imscc'],
'title',
$item->title);
$itemnode->appendChild($titlenode);
}
if ($item->has_child_items()) {
$this->update_items($item->childitems, $doc, $itemnode);
}
$xmlnode->appendChild($itemnode);
}
}
/**
* Create a Resource (How to)
*
* @param cc_i_resource $res
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_resource(cc_i_resource &$res, DOMDocument &$doc, $xmlnode=null) {
$usenew = is_object($xmlnode);
$dnode = $usenew ? $xmlnode : $doc->createElementNS($this->ccnamespaces['imscc'], "resource");
$this->update_attribute($doc, 'identifier', $res->identifier, $dnode);
$this->update_attribute($doc, 'type', $res->type, $dnode);
!is_null($res->href) ? $this->update_attribute($doc, 'href', $res->href, $dnode) : null;
$this->update_attribute($doc, 'base', $res->base, $dnode);
foreach ($res->files as $file) {
$nd = $doc->createElementNS($this->ccnamespaces['imscc'], 'file');
$ndatt = $doc->createAttribute('href');
$ndatt->nodeValue = $file;
$nd->appendChild($ndatt);
$dnode->appendChild($nd);
}
$this->resources[$res->identifier] = $res;
$this->resources_ind[$res->files[0]] = $res->identifier;
foreach ($res->dependency as $dependency) {
$nd = $doc->createElementNS($this->ccnamespaces['imscc'], 'dependency');
$ndatt = $doc->createAttribute('identifierref');
$ndatt->nodeValue = $dependency;
$nd->appendChild($ndatt);
$dnode->appendChild($nd);
}
return $dnode;
}
/**
* Create an Item Folder (How To)
*
* @param cc_i_organization $org
* @param DOMDocument $doc
* @param DOMElement $xmlnode
*/
protected function create_item_folder(cc_i_organization &$org, DOMDocument &$doc, DOMElement &$xmlnode = null) {
$itemfoldernode = $doc->createElementNS($this->ccnamespaces['imscc'], 'item');
$this->update_attribute($doc, 'identifier', "root", $itemfoldernode);
if ($org->has_items()) {
$this->update_items($org->itemlist, $doc, $itemfoldernode);
}
if (is_null($this->organizations)) {
$this->organizations = array();
}
$this->organizations[$org->identifier] = $org;
$xmlnode->appendChild($itemfoldernode);
}
/**
* Create an Organization (How To)
*
* @param cc_i_organization $org
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_organization(cc_i_organization &$org, DOMDocument &$doc, $xmlnode = null) {
$usenew = is_object($xmlnode);
$dnode = $usenew ? $xmlnode : $doc->createElementNS($this->ccnamespaces['imscc'], "organization");
$this->update_attribute($doc, 'identifier', $org->identifier, $dnode);
$this->update_attribute($doc, 'structure', $org->structure, $dnode);
$this->create_item_folder($org, $doc, $dnode);
return $dnode;
}
/**
* Create Metadata For Manifest (How To)
*
* @param cc_i_metadata_manifest $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_manifest(cc_i_metadata_manifest $met, DOMDocument &$doc, $xmlnode = null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lomimscc'], "lom");
if (!empty($xmlnode)) {
$xmlnode->appendChild($dnode);
}
$dnodegeneral = empty($met->arraygeneral) ? null : $this->create_metadata_general($met, $doc, $xmlnode);
$dnodetechnical = empty($met->arraytech) ? null : $this->create_metadata_technical($met, $doc, $xmlnode);
$dnoderights = empty($met->arrayrights) ? null : $this->create_metadata_rights($met, $doc, $xmlnode);
$dnodelifecycle = empty($met->arraylifecycle) ? null : $this->create_metadata_lifecycle($met, $doc, $xmlnode);
!is_null($dnodegeneral) ? $dnode->appendChild($dnodegeneral) : null;
!is_null($dnodetechnical) ? $dnode->appendChild($dnodetechnical) : null;
!is_null($dnoderights) ? $dnode->appendChild($dnoderights) : null;
!is_null($dnodelifecycle) ? $dnode->appendChild($dnodelifecycle) : null;
return $dnode;
}
/**
* Create Metadata For Resource (How To)
*
* @param cc_i_metadata_resource $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_resource(cc_i_metadata_resource $met, DOMDocument &$doc, $xmlnode = null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lom'], "lom");
!empty($xmlnode) ? $xmlnode->appendChild($dnode) : null;
!empty($met->arrayeducational) ? $this->create_metadata_educational($met, $doc, $dnode) : null;
return $dnode;
}
/**
* Create Metadata For File (How To)
*
* @param cc_i_metadata_file $met
* @param DOMDocument $doc
* @param Object $xmlnode
* @return DOMNode
*/
protected function create_metadata_file(cc_i_metadata_file $met, DOMDocument &$doc, $xmlnode = null) {
$dnode = $doc->createElementNS($this->ccnamespaces['lom'], "lom");
!empty($xmlnode) ? $xmlnode->appendChild($dnode) : null;
!empty($met->arrayeducational) ? $this->create_metadata_educational($met, $doc, $dnode) : null;
return $dnode;
}
/**
* Create General Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_general($met, DOMDocument &$doc, $xmlnode) {
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'general');
foreach ($met->arraygeneral as $name => $value) {
!is_array($value) ? $value = array($value) : null;
foreach ($value as $v) {
if ($name != 'language' && $name != 'catalog' && $name != 'entry') {
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'], $name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'string', $v[1]);
$ndatt = $doc->createAttribute('language');
$ndatt->nodeValue = $v[0];
$nd3->appendChild($ndatt);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
} else {
if ($name == 'language') {
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'], $name, $v[0]);
$nd->appendChild($nd2);
}
}
}
}
if (!empty($met->arraygeneral['catalog']) || !empty($met->arraygeneral['entry'])) {
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'identifier');
$nd->appendChild($nd2);
if (!empty($met->arraygeneral['catalog'])) {
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'catalog', $met->arraygeneral['catalog'][0][0]);
$nd2->appendChild($nd3);
}
if (!empty($met->arraygeneral['entry'])) {
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'entry', $met->arraygeneral['entry'][0][0]);
$nd2->appendChild($nd4);
}
}
return $nd;
}
/**
* Create Technical Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_technical($met, DOMDocument &$doc, $xmlnode) {
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'technical');
$xmlnode->appendChild($nd);
foreach ($met->arraytech as $name => $value) {
!is_array($value) ? $value = array($value) : null;
foreach ($value as $v) {
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'], $name, $v[0]);
$nd->appendChild($nd2);
}
}
return $nd;
}
/**
* Create Rights Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_rights($met, DOMDocument &$doc, $xmlnode) {
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'rights');
foreach ($met->arrayrights as $name => $value) {
!is_array($value) ? $value = array($value) : null;
foreach ($value as $v) {
if ($name == 'description') {
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'], $name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'string', $v[1]);
$ndatt = $doc->createAttribute('language');
$ndatt->nodeValue = $v[0];
$nd3->appendChild($ndatt);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
} else if ($name == 'copyrightAndOtherRestrictions' || $name == 'cost') {
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'], $name);
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'value', $v[0]);
$nd2->appendChild($nd3);
$nd->appendChild($nd2);
}
}
}
return $nd;
}
/**
* Create Lifecycle Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
protected function create_metadata_lifecycle($met, DOMDocument &$doc, $xmlnode) {
$nd = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'lifeCycle');
$nd2 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'contribute');
$nd->appendChild($nd2);
$xmlnode->appendChild($nd);
foreach ($met->arraylifecycle as $name => $value) {
!is_array($value) ? $value = array($value) : null;
foreach ($value as $v) {
if ($name == 'role') {
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'], $name);
$nd2->appendChild($nd3);
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'value', $v[0]);
$nd3->appendChild($nd4);
} else {
if ($name == 'date') {
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'], $name);
$nd2->appendChild($nd3);
$nd4 = $doc->createElementNS($this->ccnamespaces['lomimscc'], 'dateTime', $v[0]);
$nd3->appendChild($nd4);
} else {
$nd3 = $doc->createElementNS($this->ccnamespaces['lomimscc'], $name, $v[0]);
$nd2->appendChild($nd3);
}
}
}
}
return $nd;
}
/**
* Create Education Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
public function create_metadata_educational($met, DOMDocument &$doc, $xmlnode) {
$nd = $doc->createElementNS($this->ccnamespaces['lom'], 'educational');
$nd2 = $doc->createElementNS($this->ccnamespaces['lom'], 'intendedEndUserRole');
$nd3 = $doc->createElementNS($this->ccnamespaces['voc'], 'vocabulary');
$xmlnode->appendChild($nd);
$nd->appendChild($nd2);
$nd2->appendChild($nd3);
foreach ($met->arrayeducational as $name => $value) {
!is_array($value) ? $value = array($value) : null;
foreach ($value as $v) {
$nd4 = $doc->createElementNS($this->ccnamespaces['voc'], $name, $v[0]);
$nd3->appendChild($nd4);
}
}
return $nd;
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once('cc_version1.php');
/**
* Version 1.1 class of Common Cartridge
*
*/
class cc_version11 extends cc_version1 {
const webcontent = 'webcontent';
const questionbank = 'imsqti_xmlv1p2/imscc_xmlv1p1/question-bank';
const assessment = 'imsqti_xmlv1p2/imscc_xmlv1p1/assessment';
const associatedcontent = 'associatedcontent/imscc_xmlv1p1/learning-application-resource';
const discussiontopic = 'imsdt_xmlv1p1';
const weblink = 'imswl_xmlv1p1';
const basiclti = 'imsbasiclti_xmlv1p0';
public static $checker = array(self::webcontent,
self::assessment,
self::associatedcontent,
self::discussiontopic,
self::questionbank,
self::weblink,
self::basiclti);
/**
* Validate if the type are valid or not
*
* @param string $type
* @return bool
*/
public function valid($type) {
return in_array($type, self::$checker);
}
public function __construct() {
$this->ccnamespaces = array('imscc' => 'http://www.imsglobal.org/xsd/imsccv1p1/imscp_v1p1',
'lomimscc' => 'http://ltsc.ieee.org/xsd/imsccv1p1/LOM/manifest' ,
'lom' => 'http://ltsc.ieee.org/xsd/imsccv1p1/LOM/resource' ,
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance'
);
$this->ccnsnames = array('imscc' => 'http://www.imsglobal.org/profile/cc/ccv1p1/ccv1p1_imscp_v1p2_v1p0.xsd' ,
'lomimscc' => 'http://www.imsglobal.org/profile/cc/ccv1p1/LOM/ccv1p1_lommanifest_v1p0.xsd',
'lom' => 'http://www.imsglobal.org/profile/cc/ccv1p1/LOM/ccv1p1_lomresource_v1p0.xsd'
);
$this->ccversion = '1.1.0';
$this->camversion = '1.1.0';
$this->_generator = 'Moodle 2 Common Cartridge generator';
}
protected function update_items($items, DOMDocument &$doc, DOMElement &$xmlnode) {
foreach ($items as $key => $item) {
$itemnode = $doc->createElementNS($this->ccnamespaces['imscc'], 'item');
$this->update_attribute($doc, 'identifier' , $key , $itemnode);
$this->update_attribute($doc, 'identifierref', $item->identifierref, $itemnode);
if (!is_null($item->title)) {
$titlenode = $doc->createElementNS($this->ccnamespaces['imscc'], 'title');
$titlenode->appendChild(new DOMText($item->title));
$itemnode->appendChild($titlenode);
}
if ($item->has_child_items()) {
$this->update_items($item->childitems, $doc, $itemnode);
}
$xmlnode->appendChild($itemnode);
}
}
/**
* Create Education Metadata (How To)
*
* @param object $met
* @param DOMDocument $doc
* @param object $xmlnode
* @return DOMNode
*/
public function create_metadata_educational($met, DOMDocument &$doc, $xmlnode) {
$metadata = $doc->createElementNS($this->ccnamespaces['imscc'], 'metadata');
$xmlnode->insertBefore($metadata, $xmlnode->firstChild);
$lom = $doc->createElementNS($this->ccnamespaces['lom'], 'lom');
$metadata->appendChild($lom);
$educational = $doc->createElementNS($this->ccnamespaces['lom'], 'educational');
$lom->appendChild($educational);
foreach ($met->arrayeducational as $value) {
!is_array($value) ? $value = array($value) : null;
foreach ($value as $v) {
$userrole = $doc->createElementNS($this->ccnamespaces['lom'], 'intendedEndUserRole');
$educational->appendChild($userrole);
$nd4 = $doc->createElementNS($this->ccnamespaces['lom'], 'source', 'IMSGLC_CC_Rolesv1p1');
$nd5 = $doc->createElementNS($this->ccnamespaces['lom'], 'value', $v[0]);
$userrole->appendChild($nd4);
$userrole->appendChild($nd5);
}
}
return $metadata;
}
}
+132
View File
@@ -0,0 +1,132 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_organization.php';
/**
* Abstract Version Base class
*
*/
abstract class cc_version_base {
protected $_generator = null;
protected $ccnamespaces = array();
protected $isrootmanifest = false;
protected $manifestID = null;
protected $organizationid = null;
public $resources = null;
public $resources_ind = null;
protected $metadata = null;
public $organizations = null;
protected $base = null;
public $ccversion = null;
public $camversion = null;
abstract protected function on_create(DOMDocument &$doc, $rootmanifestnode = null, $nmanifestID = null);
abstract protected function create_metadata_manifest(cc_i_metadata_manifest $met, DOMDocument &$doc, $xmlnode = null);
abstract protected function create_metadata_resource(cc_i_metadata_resource $met, DOMDocument &$doc, $xmlnode = null);
abstract protected function create_metadata_file(cc_i_metadata_file $met, DOMDocument &$doc, $xmlnode = null);
abstract protected function create_resource(cc_i_resource &$res, DOMDocument &$doc, $xmlnode=null);
abstract protected function create_organization(cc_i_organization &$org, DOMDocument &$doc, $xmlnode=null);
public function get_cc_namespaces() {
return $this->ccnamespaces;
}
public function create_manifest(DOMDocument &$doc, $rootmanifestnode = null) {
return $this->on_create($doc, $rootmanifestnode);
}
public function create_resource_node(cc_i_resource &$res, DOMDocument &$doc, $xmlnode = null) {
return $this->create_resource($res, $doc, $xmlnode);
}
public function create_metadata_node(&$met, DOMDocument &$doc, $xmlnode = null) {
return $this->create_metadata_manifest($met, $doc, $xmlnode);
}
public function create_metadata_resource_node(&$met, DOMDocument &$doc, $xmlnode = null) {
return $this->create_metadata_resource($met, $doc, $xmlnode);
}
public function create_metadata_file_node(&$met, DOMDocument &$doc, $xmlnode = null) {
return $this->create_metadata_file($met, $doc, $xmlnode);
}
public function create_organization_node(cc_i_organization &$org, DOMDocument &$doc, $xmlnode = null) {
return $this->create_organization($org, $doc, $xmlnode);
}
public function manifestID() {
return $this->manifestID;
}
public function set_manifestID($id) {
$this->manifestID = $id;
}
public function get_base() {
return $this->base;
}
public function set_base($baseval) {
$this->base = $baseval;
}
public function import_resources(DOMElement &$node, cc_i_manifest &$doc) {
if (is_null($this->resources)) {
$this->resources = array();
}
$nlist = $node->getElementsByTagNameNS($this->ccnamespaces['imscc'], 'resource');
if (is_object($nlist)) {
foreach ($nlist as $nd) {
$sc = new cc_resource($doc, $nd);
$this->resources[$sc->identifier] = $sc;
}
}
}
public function import_organization_items(DOMElement &$node, cc_i_manifest &$doc) {
if (is_null($this->organizations)) {
$this->organizations = array();
}
$nlist = $node->getElementsByTagNameNS($this->ccnamespaces['imscc'], 'organization');
if (is_object($nlist)) {
foreach ($nlist as $nd) {
$sc = new cc_organization($nd, $doc);
$this->organizations[$sc->identifier] = $sc;
}
}
}
public function set_generator($value) {
$this->_generator = $value;
}
}
+99
View File
@@ -0,0 +1,99 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package backup-convert
* @subpackage cc-library
* @copyright 2011 Darko Miletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once 'cc_general.php';
class url1_resurce_file extends general_cc_file {
const deafultname = 'weblink.xml';
protected $rootns = 'wl';
protected $rootname = 'wl:webLink';
protected $ccnamespaces = array('wl' => 'http://www.imsglobal.org/xsd/imswl_v1p0',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance');
protected $ccnsnames = array('wl' => 'http://www.imsglobal.org/profile/cc/ccv1p0/derived_schema/domainProfile_5/imswl_v1p0_localised.xsd');
protected $url = null;
protected $title = null;
protected $href = null;
protected $target = '_self';
protected $window_features = null;
/**
*
* Set the url title
* @param string $title
*/
public function set_title($title) {
$this->title = self::safexml($title);
}
/**
*
* Set the url specifics
* @param string $url
* @param string $target
* @param string $window_features
*/
public function set_url($url, $target='_self', $window_features=null) {
$this->url = $url;
$this->target = $target;
$this->window_features = $window_features;
}
protected function on_save() {
$this->append_new_element($this->root, 'title', $this->title);
$url = $this->append_new_element($this->root, 'url');
$this->append_new_attribute($url, 'href', $this->url);
if (!empty($this->target)) {
$this->append_new_attribute($url, 'target', $this->target);
}
if (!empty($this->window_features)) {
$this->append_new_attribute($url, 'windowFeatures', $this->window_features);
}
return true;
}
}
class url11_resurce_file extends url1_resurce_file {
protected $rootname = 'webLink';
protected $ccnamespaces = array('wl' => 'http://www.imsglobal.org/xsd/imsccv1p1/imswl_v1p1',
'xsi' => 'http://www.w3.org/2001/XMLSchema-instance');
protected $ccnsnames = array('wl' => 'http://www.imsglobal.org/profile/cc/ccv1p1/ccv1p1_imswl_v1p1.xsd');
protected function on_save() {
$rns = $this->ccnamespaces[$this->rootns];
$this->append_new_element_ns($this->root, $rns, 'title', $this->title);
$url = $this->append_new_element_ns($this->root, $rns, 'url');
$this->append_new_attribute_ns($url, $rns, 'href', $this->url);
if (!empty($this->target)) {
$this->append_new_attribute_ns($url, $rns, 'target', $this->target);
}
if (!empty($this->window_features)) {
$this->append_new_attribute_ns($url, $rns, 'windowFeatures', $this->window_features);
}
return true;
}
}
@@ -0,0 +1,131 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once(__DIR__ .'/../xmlbase.php');
require_once('cssparser.php');
require_once('pathutils.php');
/**
*
* Older version better suited for PHP < 5.2
* @deprecated
* @param mixed $url
* @return boolean
*/
function is_url_deprecated($url) {
if (
!preg_match('#^http\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url) &&
!preg_match('#^https\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url) &&
!preg_match('#^ftp\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url)
) {
$status = false;
} else {
$status = true;
}
return $status;
}
/**
*
* validates URL
* @param string $url
* @return boolean
*/
function is_url($url) {
$result = filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED) !== false;
return $result;
}
function GetDepFiles($manifestroot, $fname, $folder, &$filenames) {
static $types = array('xhtml' => true, 'html' => true, 'htm' => true);
$extension = strtolower(trim(pathinfo($fname, PATHINFO_EXTENSION)));
$filenames = array();
if (isset($types[$extension])) {
$dcx = new XMLGenericDocument();
$filename = $manifestroot.$folder.$fname;
if (!file_exists($filename)) {
$filename = $manifestroot.DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.$fname;
}
if (file_exists($filename)) {
$res = $dcx->loadHTMLFile($filename);
if ($res) {
GetDepFilesHTML($manifestroot, $fname, $filenames, $dcx, $folder);
}
}
}
}
function GetDepFilesHTML($manifestroot, $fname, &$filenames, &$dcx, $folder) {
$dcx->resetXpath();
$nlist = $dcx->nodeList("//img/@src | //link/@href | //script/@src | //a[not(starts-with(@href,'#'))]/@href");
$css_obj_array = array();
foreach ($nlist as $nl) {
$item = $folder.$nl->nodeValue;
$path_parts = pathinfo($item);
$fname = $path_parts['basename'];
$ext = array_key_exists('extension', $path_parts) ? $path_parts['extension'] : '';
if (!is_url($folder.$nl->nodeValue) && !is_url($nl->nodeValue)) {
$path = $folder.$nl->nodeValue;
$file = fullPath($path, "/");
toNativePath($file);
if (file_exists($manifestroot.DIRECTORY_SEPARATOR.$file)) {
$filenames[$file] = $file;
}
}
if ($ext == 'css') {
$css = new cssparser();
$css->Parse($dcx->filePath().$nl->nodeValue);
$css_obj_array[$item] = $css;
}
}
$nlist = $dcx->nodeList("//*/@class");
foreach ($nlist as $nl) {
$item = $folder.$nl->nodeValue;
foreach ($css_obj_array as $csskey => $cssobj) {
$bimg = $cssobj->Get($item, "background-image");
$limg = $cssobj->Get($item, "list-style-image");
$npath = pathinfo($csskey);
if ((!empty($bimg)) && ($bimg != 'none')) {
$value = stripUrl($bimg, $npath['dirname'].'/');
$filenames[$value] = $value;
} else if ((!empty($limg)) && ($limg != 'none')) {
$value = stripUrl($limg, $npath['dirname'].'/');
$filenames[$value] = $value;
}
}
}
$elems_to_check = array("body", "p", "ul", "h4", "a", "th");
$do_we_have_it = array();
foreach ($elems_to_check as $elem) {
$do_we_have_it[$elem] = ($dcx->nodeList("//".$elem)->length > 0);
}
foreach ($elems_to_check as $elem) {
if ($do_we_have_it[$elem]) {
foreach ($css_obj_array as $csskey => $cssobj) {
$sb = $cssobj->Get($elem, "background-image");
$sbl = $cssobj->Get($elem, "list-style-image");
$npath = pathinfo($csskey);
if ((!empty($sb)) && ($sb != 'none')) {
$value = stripUrl($sb, $npath['dirname'].'/');
$filenames[$value] = $value;
} else if ((!empty($sbl)) && ($sbl != 'none')) {
$value = stripUrl($sbl, $npath['dirname'].'/');
$filenames[$value] = $value;
}
}
}
}
}
+271
View File
@@ -0,0 +1,271 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
class cssparser {
private $css;
private $html;
public function __construct($html = true) {
// Register "destructor"
core_shutdown_manager::register_function(array(&$this, "finalize"));
$this->html = ($html != false);
$this->Clear();
}
/**
* Old syntax of class constructor. Deprecated in PHP7.
*
* @deprecated since Moodle 3.1
*/
public function cssparser($html = true) {
debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
self::__construct($html);
}
function finalize() {
unset($this->css);
}
function Clear() {
unset($this->css);
$this->css = array();
if($this->html) {
$this->Add("ADDRESS", "");
$this->Add("APPLET", "");
$this->Add("AREA", "");
$this->Add("A", "text-decoration : underline; color : Blue;");
$this->Add("A:visited", "color : Purple;");
$this->Add("BASE", "");
$this->Add("BASEFONT", "");
$this->Add("BIG", "");
$this->Add("BLOCKQUOTE", "");
$this->Add("BODY", "");
$this->Add("BR", "");
$this->Add("B", "font-weight: bold;");
$this->Add("CAPTION", "");
$this->Add("CENTER", "");
$this->Add("CITE", "");
$this->Add("CODE", "");
$this->Add("DD", "");
$this->Add("DFN", "");
$this->Add("DIR", "");
$this->Add("DIV", "");
$this->Add("DL", "");
$this->Add("DT", "");
$this->Add("EM", "");
$this->Add("FONT", "");
$this->Add("FORM", "");
$this->Add("H1", "");
$this->Add("H2", "");
$this->Add("H3", "");
$this->Add("H4", "");
$this->Add("H5", "");
$this->Add("H6", "");
$this->Add("HEAD", "");
$this->Add("HR", "");
$this->Add("HTML", "");
$this->Add("IMG", "");
$this->Add("INPUT", "");
$this->Add("ISINDEX", "");
$this->Add("I", "font-style: italic;");
$this->Add("KBD", "");
$this->Add("LINK", "");
$this->Add("LI", "");
$this->Add("MAP", "");
$this->Add("MENU", "");
$this->Add("META", "");
$this->Add("OL", "");
$this->Add("OPTION", "");
$this->Add("PARAM", "");
$this->Add("PRE", "");
$this->Add("P", "");
$this->Add("SAMP", "");
$this->Add("SCRIPT", "");
$this->Add("SELECT", "");
$this->Add("SMALL", "");
$this->Add("STRIKE", "");
$this->Add("STRONG", "");
$this->Add("STYLE", "");
$this->Add("SUB", "");
$this->Add("SUP", "");
$this->Add("TABLE", "");
$this->Add("TD", "");
$this->Add("TEXTAREA", "");
$this->Add("TH", "");
$this->Add("TITLE", "");
$this->Add("TR", "");
$this->Add("TT", "");
$this->Add("UL", "");
$this->Add("U", "text-decoration : underline;");
$this->Add("VAR", "");
}
}
function SetHTML($html) {
$this->html = ($html != false);
}
function Add($key, $codestr) {
$key = strtolower($key);
$codestr = strtolower($codestr);
if(!isset($this->css[$key])) {
$this->css[$key] = array();
}
$codes = explode(";",$codestr);
if(count($codes) > 0) {
$codekey=''; $codevalue='';
foreach($codes as $code) {
$code = trim($code);
$this->assignValues(explode(":",$code),$codekey,$codevalue);
if(strlen($codekey) > 0) {
$this->css[$key][trim($codekey)] = trim($codevalue);
}
}
}
}
private function assignValues($arr,&$val1,&$val2) {
$n = count($arr);
if ($n > 0) {
$val1=$arr[0];
$val2=($n > 1) ? $arr[1] : '';
}
}
function Get($key, $property) {
$key = strtolower($key);
$property = strtolower($property);
$tag='';$subtag='';$class='';$id='';
$this->assignValues(explode(":",$key),$tag,$subtag);
$this->assignValues(explode(".",$tag),$tag,$class);
$this->assignValues(explode("#",$tag),$tag,$id);
$result = "";
$_subtag=''; $_class=''; $_id='';
foreach($this->css as $_tag => $value) {
$this->assignValues(explode(":",$_tag),$_tag,$_subtag);
$this->assignValues(explode(".",$_tag),$_tag,$_class);
$this->assignValues(explode("#",$_tag),$_tag,$_id);
$tagmatch = (strcmp($tag, $_tag) == 0) | (strlen($_tag) == 0);
$subtagmatch = (strcmp($subtag, $_subtag) == 0) | (strlen($_subtag) == 0);
$classmatch = (strcmp($class, $_class) == 0) | (strlen($_class) == 0);
$idmatch = (strcmp($id, $_id) == 0);
if($tagmatch & $subtagmatch & $classmatch & $idmatch) {
$temp = $_tag;
if((strlen($temp) > 0) & (strlen($_class) > 0)) {
$temp .= ".".$_class;
} elseif(strlen($temp) == 0) {
$temp = ".".$_class;
}
if((strlen($temp) > 0) & (strlen($_subtag) > 0)) {
$temp .= ":".$_subtag;
} elseif(strlen($temp) == 0) {
$temp = ":".$_subtag;
}
if(isset($this->css[$temp][$property])) {
$result = $this->css[$temp][$property];
}
}
}
return $result;
}
function GetSection($key) {
$key = strtolower($key);
$tag='';$subtag='';$class='';$id='';
$_subtag=''; $_class=''; $_id='';
$this->assignValues(explode(":",$key),$tag,$subtag);
$this->assignValues(explode(".",$tag),$tag,$class);
$this->assignValues(explode("#",$tag),$tag,$id);
$result = array();
foreach($this->css as $_tag => $value) {
$this->assignValues(explode(":",$_tag),$_tag,$_subtag);
$this->assignValues(explode(".",$_tag),$_tag,$_class);
$this->assignValues(explode("#",$_tag),$_tag,$_id);
$tagmatch = (strcmp($tag, $_tag) == 0) | (strlen($_tag) == 0);
$subtagmatch = (strcmp($subtag, $_subtag) == 0) | (strlen($_subtag) == 0);
$classmatch = (strcmp($class, $_class) == 0) | (strlen($_class) == 0);
$idmatch = (strcmp($id, $_id) == 0);
if($tagmatch & $subtagmatch & $classmatch & $idmatch) {
$temp = $_tag;
if((strlen($temp) > 0) & (strlen($_class) > 0)) {
$temp .= ".".$_class;
} elseif(strlen($temp) == 0) {
$temp = ".".$_class;
}
if((strlen($temp) > 0) & (strlen($_subtag) > 0)) {
$temp .= ":".$_subtag;
} elseif(strlen($temp) == 0) {
$temp = ":".$_subtag;
}
foreach($this->css[$temp] as $property => $value) {
$result[$property] = $value;
}
}
}
return $result;
}
function ParseStr($str) {
$this->Clear();
// Remove comments
$str = preg_replace("/\/\*(.*)?\*\//Usi", "", $str);
// Parse this damn csscode
$parts = explode("}",$str);
if(count($parts) > 0) {
foreach($parts as $part) {
$keystr='';$codestr='';
$this->assignValues(explode("{",$part),$keystr,$codestr);
$keys = explode(",",trim($keystr));
if(count($keys) > 0) {
foreach($keys as $key) {
if(strlen($key) > 0) {
$key = str_replace("\n", "", $key);
$key = str_replace("\\", "", $key);
$this->Add($key, trim($codestr));
}
}
}
}
}
//
return (count($this->css) > 0);
}
function Parse($filename) {
$this->Clear();
if(file_exists($filename)) {
return $this->ParseStr(file_get_contents($filename));
} else {
return false;
}
}
function GetCSS() {
$result = "";
foreach($this->css as $key => $values) {
$result .= $key." {\n";
foreach($values as $key => $value) {
$result .= " $key: $value;\n";
}
$result .= "}\n\n";
}
return $result;
}
}
+131
View File
@@ -0,0 +1,131 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Librería de funciones básicas V1.0 (June, 16th 2009)
*
*
* @author Daniel Mühlrad
* @link daniel.muhlrad@uvcms.com
* @version 1.0
* @copyright 2009
*
*/
/**
* Make a Handler error with an exception msg error
*
* @param integer $errno
* @param string $errstr
* @param string $errfile
* @param string $errline
*/
function errorHandler($errno, $errstr, $errfile, $errline) {
// si deseas podes guardarlos en un archivo
($errfile);($errline);
throw new Exception($errstr, $errno);
}
/**
* Return de mime-type of a file
*
* @param string $file
* @param string $default_type
*
*/
function file_mime_type ($file, $default_type = 'application/octet-stream'){
$ftype = $default_type;
$magic_path = __DIR__
. DIRECTORY_SEPARATOR
. '..'
. DIRECTORY_SEPARATOR
. 'magic'
. DIRECTORY_SEPARATOR
. 'magic';
$finfo = @finfo_open(FILEINFO_MIME , $magic_path);
if ($finfo !== false) {
$fres = @finfo_file($finfo, $file);
if ( is_string($fres) && !empty($fres) ) {
$ftype = $fres;
}
@finfo_close($finfo);
}
return $ftype;
}
function array_remove_by_value($arr,$value) {
return array_values(array_diff($arr,array($value)));
}
function array_remove_by_key($arr,$key) {
return array_values(array_diff_key($arr,array($key)));
}
function cc_print_object($object) {
echo '<pre>' . htmlspecialchars(print_r($object,true), ENT_COMPAT) . '</pre>';
}
/**
* IndexOf - first version of find an element in the Array given
* returns the index of the *first* occurance
* @param mixed $needle
* @param array $haystack
* @return mixed The element or false if the function didnt find it
*/
function indexOf($needle, $haystack) {
for ($i = 0; $i < count($haystack) ; $i++) {
if ($haystack[$i] == $needle) {
return $i;
}
}
return false;
}
/**
* IndexOf2 - second version of find an element in the Array given
*
* @param mixed $needle
* @param array $haystack
* @return mixed The index of the element or false if the function didnt find it
*/
function indexOf2($needle, $haystack) {
for($i = 0,$z = count($haystack); $i < $z; $i++){
if ($haystack[$i] == $needle) { //finds the needle
return $i;
}
}
return false;
}
+149
View File
@@ -0,0 +1,149 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once $CFG->dirroot .'/backup/cc/cc_lib/xmlbase.php';
require_once 'cssparser.php';
require_once 'pathutils.php';
function is_url($url) {
if (
!preg_match('#^http\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url) &&
!preg_match('#^https\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url) &&
!preg_match('#^ftp\\:\\/\\/[a-z0-9\-]+\.([a-z0-9\-]+\.)?[a-z]+#i', $url)
) {
$status = false;
} else {
$status = true;
}
return $status;
}
function GetDepFiles($manifestroot, $fname,$folder,&$filenames) {
$extension = end(explode('.',$fname));
$filenames = array();
$dcx = new XMLGenericDocument();
$result = true;
switch ($extension){
case 'xml':
$result = @$dcx->loadXMLFile($manifestroot.$folder.$fname);
if (!$result) {
$result = @$dcx->loadXMLFile($manifestroot.DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.$fname);
}
GetDepFilesXML($manifestroot, $fname,$filenames,$dcx, $folder);
break;
case 'html':
case 'htm':
$result = @$dcx->loadHTMLFile($manifestroot.$folder.$fname);
if (!$result) {
$result = @$dcx->loadHTMLFile($manifestroot.DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.$fname);
}
GetDepFilesHTML($manifestroot, $fname,$filenames,$dcx, $folder);
break;
}
return $result;
}
function GetDepFilesXML ($manifestroot, $fname,&$filenames,&$dcx, $folder){
$nlist = $dcx->nodeList("//img/@src | //attachments/attachment/@href | //link/@href | //script/@src");
$css_obj_array = array();
foreach ($nlist as $nl) {
$item = $nl->nodeValue;
$path_parts = pathinfo($item);
$fname = $path_parts['basename'];
$ext = array_key_exists('extension',$path_parts) ? $path_parts['extension'] : '';
if (!is_url($nl->nodeValue)) {
//$file = $folder.$nl->nodeValue; // DEPENDERA SI SE QUIERE Q SEA RELATIVO O ABSOLUTO
$file = $nl->nodeValue;
toNativePath($file);
$filenames[]=$file;
}
}
$dcx->registerNS('qti','http://www.imsglobal.org/xsd/imscc/ims_qtiasiv1p2.xsd');
$dcx->resetXpath();
$nlist = $dcx->nodeList("//qti:mattext | //text");
$dcx2 = new XMLGenericDocument();
foreach ($nlist as $nl) {
if ($dcx2->loadString($nl->nodeValue)){
GetDepFilesHTML($manifestroot,$fname,$filenames,$dcx2,$folder);
}
}
}
function GetDepFilesHTML ($manifestroot, $fname,&$filenames,&$dcx, $folder){
$dcx->resetXpath();
$nlist = $dcx->nodeList("//img/@src | //link/@href | //script/@src | //a[not(starts-with(@href,'#'))]/@href");
$css_obj_array=array();
foreach ($nlist as $nl) {
$item = $nl->nodeValue;
$path_parts = pathinfo($item);
$fname = $path_parts['basename'];
$ext = array_key_exists('extension',$path_parts) ? $path_parts['extension'] : '';
if (!is_url($folder.$nl->nodeValue) && !is_url($nl->nodeValue)) {
$path = $nl->nodeValue;
//$file = fullPath($path,"/");
toNativePath($path);
$filenames[]= $path;
}
if ($ext == 'css') {
$css = new cssparser();
$css->Parse($dcx->filePath().$nl->nodeValue);
$css_obj_array[$item]=$css;
}
}
$nlist = $dcx->nodeList("//*/@class");
foreach ($nlist as $nl) {
$item = $nl->nodeValue;
foreach ($css_obj_array as $csskey => $cssobj) {
$bimg = $cssobj->Get($item,"background-image");
$limg = $cssobj->Get($item,"list-style-image");
$npath = pathinfo($csskey);
if ((!empty($bimg))&& ($bimg != 'none')) {
$filenames[] = stripUrl($bimg,$npath['dirname'].'/');
} else
if ((!empty($limg))&& ($limg != 'none')) {
$filenames[] = stripUrl($limg,$npath['dirname'].'/');
}
}
}
$elems_to_check = array("body","p","ul","h4","a","th");
$do_we_have_it = array();
foreach ($elems_to_check as $elem) {
$do_we_have_it[$elem]=($dcx->nodeList("//".$elem)->length > 0);
}
foreach ($elems_to_check as $elem) {
if ($do_we_have_it[$elem]) {
foreach ($css_obj_array as $csskey => $cssobj) {
$sb = $cssobj->Get($elem, "background-image");
$sbl = $cssobj->Get($elem,"list-style-image");
$npath = pathinfo($csskey);
if ((!empty($sb)) && ($sb != 'none')) {
$filenames[] = stripUrl($sb,$npath['dirname'].'/');
} else
if ((!empty($sbl)) && ($sbl != 'none')) {
$filenames[] = stripUrl($sbl,$npath['dirname'].'/');
}
}
}
}
}
+420
View File
@@ -0,0 +1,420 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Function expands all relative parts of supplied path string thus
* removing things like ../../ or ./../.
*
* @param string $path
* @param string $dirsep Character that represents directory separator should be
* specified here. Default is DIRECTORY_SEPARATOR.
* @return string
*/
function fullPath($path,$dirsep=DIRECTORY_SEPARATOR) {
$token = '$IMS-CC-FILEBASE$';
$path = str_replace($token,'',$path);
if ( is_string($path) && ($path != '') ) {
$sep = $dirsep;
$dotDir= '.';
$upDir = '..';
$length= strlen($path);
$rtemp= trim($path);
$start = strrpos($path, $sep);
$canContinue = ($start !== false);
$result= $canContinue ? '': $path;
$rcount=0;
while ($canContinue) {
$dirPart = ($start !== false) ? substr($rtemp,$start+1,$length-$start) : $rtemp;
$canContinue = ($dirPart !== false);
if ($canContinue) {
if ($dirPart != $dotDir) {
if ($dirPart == $upDir) {
$rcount++;
} else {
if ($rcount > 0) {
$rcount--;
} else {
$result = ($result == '') ? $dirPart : $dirPart.$sep.$result;
}
}
}
$rtemp = substr($path,0,$start);
$start = strrpos($rtemp, $sep);
$canContinue = (($start !== false) || (strlen($rtemp) > 0));
}
} //end while
}
return $result;
}
/**
* Function strips url part from css link
*
* @param string $path
* @param string $rootDir
* @return string
*/
function stripUrl($path, $rootDir='') {
$result = $path;
if ( is_string($path) && ($path != '') ) {
$start=strpos($path,'(')+1;
$length=strpos($path,')')-$start;
$rut = $rootDir.substr($path,$start,$length);
$result=fullPath($rut,'/');
}
return $result;
}
/**
* Converts direcotry separator in given path to / to validate in CC
* Value is passed byref hence variable itself is changed
*
* @param string $path
*/
function toNativePath(&$path) {
for ($count = 0 ; $count < strlen($path); ++$count) {
$chr = $path[$count];
if (($chr == '\\') || ($chr == '/')) {
$path[$count] = '/';
}
}
}
/**
* Converts direcotry separator in given path to the one on the server platform
* Value is passed byref hence variable itself is changed
*
* @param string $path
*/
function toNativePath2(&$path) {
for ($count = 0 ; $count < strlen($path); ++$count) {
$chr = $path[$count];
if (($chr == '\\') || ($chr == '/')) {
$path[$count] = DIRECTORY_SEPARATOR;
}
}
}
/**
* Converts \ Directory separator to the / more suitable for URL
*
* @param string $path
*/
function toUrlPath(&$path) {
for ($count = 0 ; $count < strlen($path); ++$count) {
$chr = $path[$count];
if (($chr == '\\')) {
$path[$count] = '/';
}
}
}
/**
* Returns relative path from two directories with full path
*
* @param string $path1
* @param string $path2
* @return string
*/
function pathDiff($path1, $path2) {
toUrlPath($path1);
toUrlPath($path2);
$result = "";
$bl2 = strlen($path2);
$a = strpos($path1,$path2);
if ($a !== false) {
$result = trim(substr($path1,$bl2+$a),'/');
}
return $result;
}
/**
* Copy a file, or recursively copy a folder and its contents
*
* @author Aidan Lister <aidan@php.net>
* @version 1.0.1
* @link http://aidanlister.com/repos/v/function.copyr.php
* @param string $source Source path
* @param string $dest Destination path
* @return bool Returns TRUE on success, FALSE on failure
*/
function copyr($source, $dest)
{
global $CFG;
// Simple copy for a file
if (is_file($source)) {
return copy($source, $dest);
}
// Make destination directory
if (!is_dir($dest)) {
mkdir($dest, $CFG->directorypermissions, true);
}
// Loop through the folder
$dir = dir($source);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == '.' || $entry == '..') {
continue;
}
// Deep copy directories
if ($dest !== "$source/$entry") {
copyr("$source/$entry", "$dest/$entry");
}
}
// Clean up
$dir->close();
return true;
}
/**
* Function returns array with directories contained in folder (only first level)
*
* @param string $rootDir directory to look into
* @param string $contains which string to look for
* @param array $excludeitems array of names to be excluded
* @param bool $startswith should the $contains value be searched only from
* beginning
* @return array Returns array of sub-directories. In case $rootDir path is
* invalid it returns FALSE.
*/
function getDirectories($rootDir, $contains, $excludeitems = null, $startswith = true) {
$result = is_dir($rootDir);
if ($result) {
$dirlist = dir($rootDir);
$entry = null;
$result = array();
while(false !== ($entry = $dirlist->read())) {
$currdir = $rootDir.$entry;
if (is_dir($currdir)) {
$bret = strpos($entry,$contains);
if (($bret !== false)) {
if (($startswith && ($bret == 0)) || !$startswith) {
if (!( is_array($excludeitems) && in_array($entry,$excludeitems) )) {
$result[] = $entry;
}
}
}
}
}
}
return $result;
}
function getFilesOnly($rootDir, $contains, $excludeitems = null, $startswith = true,$extension=null) {
$result = is_dir($rootDir);
if ($result) {
$filelist = dir($rootDir);
$entry = null;
$result = array();
while(false !== ($entry = $filelist->read())) {
$curritem = $rootDir.$entry;
$pinfo = pathinfo($entry);
$ext = array_key_exists('extension',$pinfo) ? $pinfo['extension'] : null;
if (is_file($curritem) && (is_null($extension) || ($ext == $extension) )) {
$bret = strpos($entry,$contains);
if (($bret !== false)) {
if (($startswith && ($bret == 0)) || !$startswith) {
if (!( is_array($excludeitems) && in_array($entry,$excludeitems) )) {
$result[] = $entry;
}
}
}
}
}
}
natcasesort($result);
return $result;
}
/**
* Search an identifier in array
*
* @param array $array
* @param string $name
*
*/
function search_ident_by_name($array,$name){
if (empty($array)){
throw new Exception('The array given is null');
}
$ident = null;
foreach ($array as $k => $v){
($k);
if ($v[1] == $name){
$ident = $v[0];
break;
}
}
return $ident;
}
/**
* Function returns files recursivly with appeneded relative path
*
* @param string $startDir
* @param string $rootDir
* @param array $excludedirs
* @param array $excludefileext
* @return array
*/
function getRawFiles($startDir, &$fhandle, $rootDir='', $excludedirs = null, $excludefileext = null) {
$result = is_dir($startDir);
if ($result) {
$dirlist = dir($startDir);
$entry = null;
while(false !== ($entry = $dirlist->read())) {
$curritem = $startDir.$entry;
if (($entry=='.') || ($entry =='..')) {
continue;
}
if (is_dir($curritem)) {
if (!( is_array($excludedirs) && in_array($entry,$excludedirs) )) {
getRawFiles($startDir.$entry."/",$fhandle,$rootDir.$entry."/",$excludedirs,$excludefileext);
}
continue;
}
if (is_file($curritem)){
$pinfo = pathinfo($entry);
$ext = array_key_exists('extension',$pinfo) ? $pinfo['extension'] : '';
if (!is_array($excludefileext) ||
(is_array($excludefileext) && !in_array($ext,$excludefileext))) {
fwrite($fhandle,$rootDir.$entry."\n");
}
}
}
}
return $result;
}
function getRawFiles2($startDir,&$arr, $rootDir='', $excludedirs = null, $excludefileext = null) {
$result = is_dir($startDir);
if ($result) {
$dirlist = dir($startDir);
$entry = null;
while(false !== ($entry = $dirlist->read())) {
$curritem = $startDir.$entry;
if (($entry=='.') || ($entry =='..')) {
continue;
}
if (is_dir($curritem)) {
if (!( is_array($excludedirs) && in_array($entry,$excludedirs) )) {
getRawFiles2($startDir.$entry."/",$arr,$rootDir.$entry."/",$excludedirs,$excludefileext);
}
continue;
}
if (is_file($curritem)){
$pinfo = pathinfo($entry);
$ext = array_key_exists('extension',$pinfo) ? $pinfo['extension'] : '';
if (!is_array($excludefileext) ||
(is_array($excludefileext) && !in_array($ext,$excludefileext))) {
array_push($arr,$rootDir.$entry);
// fwrite($fhandle,$rootDir.$entry."\n");
}
}
}
}
return $result;
}
function GetFiles($startDir, $outfile, $rootDir='', $excludedirs = null, $excludefileext = null) {
$fh = @fopen($outfile,"w+");
if ($fh !== FALSE) {
getRawFiles($startDir,$fh,$rootDir,$excludedirs,$excludefileext);
@fclose($fh);
@chmod($outfile,0777);
}
}
/**
* Function to get an array with all files in a directory and subdirectories
*
* @param string $startDir
* @param string $rootDir
* @param string $excludedirs
* @param string $excludefileext
* @return array
*/
function GetFilesArray($startDir, $rootDir='', $excludedirs = null, $excludefileext = null) {
$arr = array();
getRawFiles2($startDir,$arr,$rootDir,$excludedirs,$excludefileext);
return $arr;
}
/**
* Function returns array with directories contained in folder (only first level)
* simmilar to getDirectories but returned items are naturally sorted.
*
* @param string $rootDir
* @param string $contains
* @param array $excludeitems
* @param bool $startswith
* @return array
*/
function getCourseDirs ($rootDir, $contains, $excludeitems=null, $startswith=true) {
$result = getDirectories($rootDir,$contains,$excludeitems,$startswith);
if ($result !== false) {
natcasesort($result);
$result = array_values($result);
}
return $result;
}
/**
* Delete a directory recursive with files inside
*
* @param string $dirname
* @return bool
*/
function rmdirr($dirname)
{
if (!file_exists($dirname)) {
return false;
}
if (is_file($dirname) || is_link($dirname)) {
return unlink($dirname);
}
$dir = dir($dirname);
while (false !== $entry = $dir->read()) {
if ($entry == '.' || $entry == '..') {
continue;
}
rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
}
$dir->close();
return rmdir($dirname);
}
+426
View File
@@ -0,0 +1,426 @@
<?php
/**
* Implementation of Common Cartridge library based on
* {@link http://www.imsglobal.org/cc/ IMS Common Cartridge Standard v1.2}
*
* @author Darko Miletic
* @author Daniel Muhlrad (daniel.muhlrad@uvcms.com)
* @version 1.0
* @copyright 2009 {@link http://www.uvcms.com UVCMS e-learning}
* @package cc_library
*
*/
require_once('gral_lib/cssparser.php');
/**
* Base XML class
*
*/
class XMLGenericDocument {
private $charset;
/**
* Document
* @var DOMDocument
*/
public $doc = null;
/**
*
* Xpath
* @var DOMXPath
*/
protected $dxpath = null;
protected $filename;
private $filepath;
private $isloaded = false;
private $arrayPrefixNS = array();
private $is_html = false;
/**
* @param string $value
* @return string
*/
public static function safexml($value) {
$result = htmlspecialchars(html_entity_decode($value, ENT_QUOTES, 'UTF-8'),
ENT_NOQUOTES,
'UTF-8',
false);
return $result;
}
function __construct($ch = 'UTF-8', $validatenow = true) {
$this->charset = $ch;
$this->documentInit();
$this->doc->validateOnParse = $validatenow;
}
function __destruct() {
$this->dxpath = null;
$this->doc = null;
}
private function documentInit($withonCreate = true) {
$hg = false;
if ($this->isloaded) {
$guardstate = $this->doc->validateOnParse;
$hg = true;
unset($this->dxpath);
unset($this->doc);
$this->isloaded = false;
}
$this->doc = new DOMDocument("1.0", $this->charset);
$this->doc->strictErrorChecking = true;
if ($hg) {
$this->doc->validateOnParse = $guardstate;
}
$this->doc->formatOutput = true;
$this->doc->preserveWhiteSpace = true;
if ($withonCreate) {
$this->on_create();
}
}
public function viewXML() {
return $this->doc->saveXML();
}
public function registerNS($prefix, $nsuri) {
$this->arrayPrefixNS[$prefix] = $nsuri;
}
public function load($fname) {
// Sine xml will remain loaded should the repeated load fail we should recreate document to be empty.
$this->documentInit(false);
$this->isloaded = $this->doc->load($fname);
if ($this->isloaded) {
$this->filename = $fname;
$this->processPath();
$this->is_html = false;
}
return $this->on_load();
}
public function loadUrl($url) {
$this->documentInit();
$this->isloaded = true;
$this->doc->loadXML( file_get_contents($url) );
$this->is_html = false;
return $this->on_load();
}
public function loadHTML($content) {
$this->documentInit();
$this->doc->validateOnParse = false;
$this->isloaded = true;
$this->doc->loadHTML($content);
$this->is_html = true;
return $this->on_load();
}
public function loadXML($content) {
$this->documentInit();
$this->doc->validateOnParse = false;
$this->isloaded = true;
$this->doc->load($content);
$this->is_html = true;
return $this->on_load();
}
public function loadHTMLFile($fname) {
// Sine xml will remain loaded should the repeated load fail
// we should recreate document to be empty.
$this->documentInit();
$this->doc->validateOnParse = false;
$this->isloaded = $this->doc->loadHTMLFile($fname);
if ($this->isloaded) {
$this->filename = $fname;
$this->processPath();
$this->is_html=true;
}
return $this->on_load();
}
public function loadXMLFile($fname) {
// Sine xml will remain loaded should the repeated load fail
// we should recreate document to be empty.
$this->documentInit();
$this->doc->validateOnParse = false;
$this->isloaded = $this->doc->load($fname);
if ($this->isloaded) {
$this->filename = $fname;
$this->processPath();
$this->is_html = true;
}
return $this->on_load();
}
public function loadString($content) {
$this->doc = new DOMDocument("1.0", $this->charset);
$content = '<virtualtag>'.$content.'</virtualtag>';
$this->doc->loadXML($content);
return true;
}
public function save() {
$this->saveTo($this->filename);
}
public function saveTo($fname) {
$status = false;
if ($this->on_save()) {
if ($this->is_html) {
$this->doc->saveHTMLFile($fname);
} else {
$this->doc->save($fname);
}
$this->filename = $fname;
$this->processPath();
$status = true;
}
return $status;
}
public function validate() {
return $this->doc->validate();
}
public function attributeValue($path, $attrname, $node = null) {
$this->chkxpath();
$result = null;
$resultlist = null;
if (is_null($node)) {
$resultlist = $this->dxpath->query($path);
} else {
$resultlist = $this->dxpath->query($path, $node);
}
if (is_object($resultlist) && ($resultlist->length > 0) && $resultlist->item(0)->hasAttribute($attrname)) {
$result = $resultlist->item(0)->getAttribute($attrname);
}
return $result;
}
/**
*
* Get's text value of the node based on xpath query
* @param string $path
* @param DOMNode $node
* @param int $count
* @return string
*/
public function nodeValue($path, $node = null, $count = 1) {
$nd = $this->node($path, $node, $count);
return $this->nodeTextValue($nd);
}
/**
*
* Get's text value of the node
* @param DOMNode $node
* @return string
*/
public function nodeTextValue($node) {
$result = '';
if (is_object($node)) {
if ($node->hasChildNodes()) {
$chnodesList = $node->childNodes;
$types = array(XML_TEXT_NODE, XML_CDATA_SECTION_NODE);
foreach ($chnodesList as $chnode) {
if (in_array($chnode->nodeType, $types)) {
$result .= $chnode->wholeText;
}
}
}
}
return $result;
}
/**
*
* Enter description here ...
* @param string $path
* @param DOMNode $nd
* @param int $count
* @return DOMNode
*/
public function node($path, $nd = null, $count = 1) {
$result = null;
$resultlist = $this->nodeList($path,$nd);
if (is_object($resultlist) && ($resultlist->length > 0)) {
$result = $resultlist->item($count - 1);
}
return $result;
}
/**
*
* Enter description here ...
* @param string $path
* @param DOMNode $node
* @return DOMNodeList
*/
public function nodeList($path, $node = null) {
$this->chkxpath();
$resultlist = null;
if (is_null($node)) {
$resultlist = $this->dxpath->query($path);
} else {
$resultlist = $this->dxpath->query($path, $node);
}
return $resultlist;
}
/**
*
* Create new attribute
* @param string $namespace
* @param string $name
* @param string $value
* @return DOMAttr
*/
public function create_attribute_ns($namespace, $name, $value = null) {
$result = $this->doc->createAttributeNS($namespace, $name);
if (!is_null($value)) {
$result->nodeValue = $value;
}
return $result;
}
/**
*
* Create new attribute
* @param string $name
* @param string $value
* @return DOMAttr
*/
public function create_attribute($name, $value = null) {
$result = $this->doc->createAttribute($name);
if (!is_null($value)) {
$result->nodeValue = $value;
}
return $result;
}
/**
*
* Adds new node
* @param DOMNode $parentnode
* @param string $namespace
* @param string $name
* @param string $value
* @return DOMNode
*/
public function append_new_element_ns(DOMNode &$parentnode, $namespace, $name, $value = null) {
$newnode = null;
if (is_null($value)) {
$newnode = $this->doc->createElementNS($namespace, $name);
} else {
$newnode = $this->doc->createElementNS($namespace, $name, $value);
}
return $parentnode->appendChild($newnode);
}
/**
*
* New node with CDATA content
* @param DOMNode $parentnode
* @param string $namespace
* @param string $name
* @param string $value
*/
public function append_new_element_ns_cdata(DOMNode &$parentnode, $namespace, $name, $value = null) {
$newnode = $this->doc->createElementNS($namespace, $name);
if (!is_null($value)) {
$cdata = $this->doc->createCDATASection($value);
$newnode->appendChild($cdata);
}
return $parentnode->appendChild($newnode);
}
/**
*
* Adds new node
* @param DOMNode $parentnode
* @param string $name
* @param string $value
* @return DOMNode
*/
public function append_new_element(DOMNode &$parentnode, $name, $value = null) {
$newnode = null;
if (is_null($value)) {
$newnode = $this->doc->createElement($name);
} else {
$newnode = $this->doc->createElement($name, $value);
}
return $parentnode->appendChild($newnode);
}
/**
*
* Adds new attribute
* @param DOMNode $node
* @param string $name
* @param string $value
* @return DOMNode
*/
public function append_new_attribute(DOMNode &$node, $name, $value = null) {
return $node->appendChild($this->create_attribute($name, $value));
}
/**
*
* Adds new attribute
* @param DOMNode $node
* @param string $namespace
* @param string $name
* @param string $value
* @return DOMNode
*/
public function append_new_attribute_ns(DOMNode &$node, $namespace, $name, $value = null) {
return $node->appendChild($this->create_attribute_ns($namespace, $name, $value));
}
public function fileName() {
return $this->filename;
}
public function filePath() {
return $this->filepath;
}
protected function on_load() {
return $this->isloaded;
}
protected function on_save() {
return true;
}
protected function on_create() {
return true;
}
public function resetXpath() {
$this->dxpath = null;
$this->chkxpath();
}
private function chkxpath() {
if (!isset($this->dxpath) || is_null($this->dxpath)) {
$this->dxpath = new DOMXPath($this->doc);
foreach ($this->arrayPrefixNS as $nskey => $nsuri) {
$this->dxpath->registerNamespace($nskey, $nsuri);
}
}
}
protected function processPath() {
$path_parts = pathinfo($this->filename);
$this->filepath = array_key_exists('dirname', $path_parts) ? $path_parts['dirname']."/" : '';
}
}