From e7fc2ff42e7a7b1a13a3c0184d13d5e2ac5cc616 Mon Sep 17 00:00:00 2001 From: Andreas Grabs Date: Wed, 6 Jun 2012 23:17:35 +0200 Subject: [PATCH 001/130] MDL-27675 - Feedback module abuses data_submitted --- mod/feedback/complete.php | 8 +++----- mod/feedback/complete_guest.php | 12 +++++------- mod/feedback/item/captcha/lib.php | 8 ++++++++ mod/feedback/item/feedback_item_class.php | 19 +++++++++++++------ mod/feedback/item/info/lib.php | 8 ++++++++ mod/feedback/item/label/lib.php | 6 ++++++ mod/feedback/item/multichoice/lib.php | 4 ++++ mod/feedback/item/multichoicerated/lib.php | 7 +++++++ mod/feedback/item/numeric/lib.php | 13 ++++++++++++- mod/feedback/item/textarea/lib.php | 12 ++++++++++-- mod/feedback/item/textfield/lib.php | 12 ++++++++++-- mod/feedback/lib.php | 11 +++++++++++ 12 files changed, 97 insertions(+), 23 deletions(-) diff --git a/mod/feedback/complete.php b/mod/feedback/complete.php index 7fee6412d83..e4c202c50d9 100644 --- a/mod/feedback/complete.php +++ b/mod/feedback/complete.php @@ -507,11 +507,8 @@ if ($feedback_can_submit) { //get the value $frmvaluename = $feedbackitem->typ . '_'. $feedbackitem->id; if (isset($savereturn)) { - if (isset($formdata->{$frmvaluename})) { - $value = $formdata->{$frmvaluename}; - } else { - $value = null; - } + $value = isset($formdata->{$frmvaluename}) ? $formdata->{$frmvaluename} : null; + $value = feedback_clean_input_value($feedbackitem, $value); } else { if (isset($feedbackcompletedtmp->id)) { $value = feedback_get_item_value($feedbackcompletedtmp->id, @@ -530,6 +527,7 @@ if ($feedback_can_submit) { feedback_print_item_complete($feedbackitem, $value, $highlightrequired); echo $OUTPUT->box_end(); } + echo $OUTPUT->box_end(); $lastbreakposition = $feedbackitem->position; //last item-pos (item or pagebreak) diff --git a/mod/feedback/complete_guest.php b/mod/feedback/complete_guest.php index 25747a99082..b472c09e023 100644 --- a/mod/feedback/complete_guest.php +++ b/mod/feedback/complete_guest.php @@ -72,7 +72,7 @@ if (isset($formdata->sesskey) AND !isset($formdata->gonextpage) AND !isset($formdata->gopreviouspage)) { - $gopage = $formdata->lastpage; + $gopage = (int) $formdata->lastpage; } if (isset($formdata->savevalues)) { $savevalues = true; @@ -441,13 +441,10 @@ if ($feedback_can_submit) { echo $OUTPUT->box_start('feedback_item_box_'.$align.$dependstyle); $value = ''; //get the value - $frmvaluename = $feedbackitem->typ.'_'.$feedbackitem->id; + $frmvaluename = $feedbackitem->typ . '_'. $feedbackitem->id; if (isset($savereturn)) { - if (isset($formdata->{$frmvaluename})) { - $value = $formdata->{$frmvaluename}; - } else { - $value = null; - } + $value = isset($formdata->{$frmvaluename}) ? $formdata->{$frmvaluename} : null; + $value = feedback_clean_input_value($feedbackitem, $value); } else { if (isset($feedbackcompletedtmp->id)) { $value = feedback_get_item_value($feedbackcompletedtmp->id, @@ -466,6 +463,7 @@ if ($feedback_can_submit) { feedback_print_item_complete($feedbackitem, $value, $highlightrequired); echo $OUTPUT->box_end(); } + echo $OUTPUT->box_end(); $lastbreakposition = $feedbackitem->position; //last item-pos (item or pagebreak) diff --git a/mod/feedback/item/captcha/lib.php b/mod/feedback/item/captcha/lib.php index 126d51e3417..190b1365ecf 100644 --- a/mod/feedback/item/captcha/lib.php +++ b/mod/feedback/item/captcha/lib.php @@ -326,4 +326,12 @@ class feedback_item_captcha extends feedback_item_base { public function can_switch_require() { return false; } + + public function value_type() { + return PARAM_RAW; + } + + function clean_input_value($value) { + return clean_param($value, $this->value_type()); + } } diff --git a/mod/feedback/item/feedback_item_class.php b/mod/feedback/item/feedback_item_class.php index 981aefd58ea..f325ed7fbdc 100644 --- a/mod/feedback/item/feedback_item_class.php +++ b/mod/feedback/item/feedback_item_class.php @@ -41,14 +41,11 @@ abstract class feedback_item_base { return false; } - public function value_type() { - return PARAM_RAW; - } - public function value_is_array() { return false; } + abstract public function value_type(); abstract public function init(); abstract public function build_editform($item, $feedback, $cm); abstract public function save_item(); @@ -128,6 +125,14 @@ abstract class feedback_item_base { */ abstract public function print_item_show_value($item, $value = ''); + /** + * cleans the userinput while submitting the form + * + * @param mixed $value + * @return mixed + */ + abstract function clean_input_value($value); + } //a dummy class to realize pagebreaks @@ -175,7 +180,9 @@ class feedback_item_pagebreak extends feedback_item_base { } public function can_switch_require() { } + public function value_type() { + } + public function clean_input_value($value) { + } } - - diff --git a/mod/feedback/item/info/lib.php b/mod/feedback/item/info/lib.php index 299fef24b04..8d8eef5d75c 100644 --- a/mod/feedback/item/info/lib.php +++ b/mod/feedback/item/info/lib.php @@ -388,4 +388,12 @@ class feedback_item_info extends feedback_item_base { public function can_switch_require() { return false; } + + public function value_type() { + return PARAM_INT; + } + + function clean_input_value($value) { + return clean_param($value, $this->value_type()); + } } diff --git a/mod/feedback/item/label/lib.php b/mod/feedback/item/label/lib.php index 25c62a9f55d..06db9908851 100644 --- a/mod/feedback/item/label/lib.php +++ b/mod/feedback/item/label/lib.php @@ -270,4 +270,10 @@ class feedback_item_label extends feedback_item_base { } public function get_analysed($item, $groupid = false, $courseid = false) { } + public function value_type() { + return PARAM_BOOL; + } + public function clean_input_value($value) { + return ''; + } } diff --git a/mod/feedback/item/multichoice/lib.php b/mod/feedback/item/multichoice/lib.php index cfba141be16..3e5501fa90d 100644 --- a/mod/feedback/item/multichoice/lib.php +++ b/mod/feedback/item/multichoice/lib.php @@ -826,4 +826,8 @@ class feedback_item_multichoice extends feedback_item_base { public function value_is_array() { return true; } + + public function clean_input_value($value) { + return clean_param_array($value, $this->value_type()); + } } diff --git a/mod/feedback/item/multichoicerated/lib.php b/mod/feedback/item/multichoicerated/lib.php index 031f7b89540..5dd8583d1be 100644 --- a/mod/feedback/item/multichoicerated/lib.php +++ b/mod/feedback/item/multichoicerated/lib.php @@ -678,4 +678,11 @@ class feedback_item_multichoicerated extends feedback_item_base { return true; } + public function value_type() { + return PARAM_INT; + } + + function clean_input_value($value) { + return clean_param($value, $this->value_type()); + } } diff --git a/mod/feedback/item/numeric/lib.php b/mod/feedback/item/numeric/lib.php index 23694137d8f..280e8f9c41d 100644 --- a/mod/feedback/item/numeric/lib.php +++ b/mod/feedback/item/numeric/lib.php @@ -364,7 +364,7 @@ class feedback_item_numeric extends feedback_item_base { 'name="'.$item->typ.'_'.$item->id.'" '. 'size="10" '. 'maxlength="10" '. - 'value="'.($value ? $value : '').'" />'; + 'value="'.$value.'" />'; echo ''; echo ''; @@ -534,4 +534,15 @@ class feedback_item_numeric extends feedback_item_base { public function can_switch_require() { return true; } + + public function value_type() { + return PARAM_FLOAT; + } + + function clean_input_value($value) { + if (!is_numeric($value)) { + return null; + } + return clean_param($value, $this->value_type()); + } } diff --git a/mod/feedback/item/textarea/lib.php b/mod/feedback/item/textarea/lib.php index 54df5e6e47e..678fcf048c6 100644 --- a/mod/feedback/item/textarea/lib.php +++ b/mod/feedback/item/textarea/lib.php @@ -262,7 +262,7 @@ class feedback_item_textarea extends feedback_item_base { echo ''; echo ''; echo ''; @@ -308,7 +308,7 @@ class feedback_item_textarea extends feedback_item_base { } public function create_value($data) { - $data = clean_text($data); + $data = s($data); return $data; } @@ -333,4 +333,12 @@ class feedback_item_textarea extends feedback_item_base { public function can_switch_require() { return true; } + + public function value_type() { + return PARAM_RAW; + } + + function clean_input_value($value) { + return s($value); + } } diff --git a/mod/feedback/item/textfield/lib.php b/mod/feedback/item/textfield/lib.php index 4051ffb97c0..94e1cada376 100644 --- a/mod/feedback/item/textfield/lib.php +++ b/mod/feedback/item/textfield/lib.php @@ -252,7 +252,7 @@ class feedback_item_textfield extends feedback_item_base { 'name="'.$item->typ.'_'.$item->id.'" '. 'size="'.$presentation[0].'" '. 'maxlength="'.$presentation[1].'" '. - 'value="'.($value ? htmlspecialchars($value) : '').'" />'; + 'value="'.$value.'" />'; echo ''; echo ''; } @@ -295,7 +295,7 @@ class feedback_item_textfield extends feedback_item_base { } public function create_value($data) { - $data = clean_text($data); + $data = s($data); return $data; } @@ -320,4 +320,12 @@ class feedback_item_textfield extends feedback_item_base { public function can_switch_require() { return true; } + + public function value_type() { + return PARAM_RAW; + } + + function clean_input_value($value) { + return s($value); + } } diff --git a/mod/feedback/lib.php b/mod/feedback/lib.php index 3c9809b9f08..5807e8cb110 100644 --- a/mod/feedback/lib.php +++ b/mod/feedback/lib.php @@ -2058,6 +2058,17 @@ function feedback_get_page_to_continue($feedbackid, $courseid = false, $guestid //functions to handle the values //////////////////////////////////////////////// +/** + * cleans the userinput while submitting the form. + * + * @param mixed $value + * @return mixed + */ +function feedback_clean_input_value($item, $value) { + $itemobj = feedback_get_item_class($item->typ); + return $itemobj->clean_input_value($value); +} + /** * this saves the values of an completed. * if the param $tmp is set true so the values are saved temporary in table feedback_valuetmp. From 3d8fe4820af4fb45e0313f862442ab33dc29e326 Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Mon, 11 Jun 2012 11:46:22 +0800 Subject: [PATCH 002/130] MDL-33623 - course: add unit tests for section moving Including tracking of the course marker updates --- course/tests/courselib_test.php | 74 ++++++++++++++++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/course/tests/courselib_test.php b/course/tests/courselib_test.php index 2274e6d2ffb..42b8057ed93 100644 --- a/course/tests/courselib_test.php +++ b/course/tests/courselib_test.php @@ -66,7 +66,7 @@ class courselib_testcase extends advanced_testcase { $this->assertFalse($neworder); } - public function test_move_section() { + public function test_move_section_down() { global $DB; $this->resetAfterTest(true); @@ -78,6 +78,7 @@ class courselib_testcase extends advanced_testcase { } ksort($oldsections); + // Test move section down.. move_section_to($course, 2, 4); $sections = array(); foreach ($DB->get_records('course_sections', array('course'=>$course->id)) as $section) { @@ -94,6 +95,77 @@ class courselib_testcase extends advanced_testcase { $this->assertEquals($oldsections[6], $sections[6]); } + public function test_move_section_up() { + global $DB; + $this->resetAfterTest(true); + + $this->getDataGenerator()->create_course(array('numsections'=>5), array('createsections'=>true)); + $course = $this->getDataGenerator()->create_course(array('numsections'=>10), array('createsections'=>true)); + $oldsections = array(); + foreach ($DB->get_records('course_sections', array('course'=>$course->id)) as $section) { + $oldsections[$section->section] = $section->id; + } + ksort($oldsections); + + // Test move section up.. + move_section_to($course, 6, 4); + $sections = array(); + foreach ($DB->get_records('course_sections', array('course'=>$course->id)) as $section) { + $sections[$section->section] = $section->id; + } + ksort($sections); + + $this->assertEquals($oldsections[0], $sections[0]); + $this->assertEquals($oldsections[1], $sections[1]); + $this->assertEquals($oldsections[2], $sections[2]); + $this->assertEquals($oldsections[3], $sections[3]); + $this->assertEquals($oldsections[4], $sections[5]); + $this->assertEquals($oldsections[5], $sections[6]); + $this->assertEquals($oldsections[6], $sections[4]); + } + + public function test_move_section_marker() { + global $DB; + $this->resetAfterTest(true); + + $this->getDataGenerator()->create_course(array('numsections'=>5), array('createsections'=>true)); + $course = $this->getDataGenerator()->create_course(array('numsections'=>10), array('createsections'=>true)); + + // Set course marker to the section we are going to move.. + course_set_marker($course->id, 2); + // Verify that the course marker is set correctly. + $course = $DB->get_record('course', array('id' => $course->id)); + $this->assertEquals(2, $course->marker); + + // Test move the marked section down.. + move_section_to($course, 2, 4); + + // Verify that the coruse marker has been moved along with the section.. + $course = $DB->get_record('course', array('id' => $course->id)); + $this->assertEquals(4, $course->marker); + + // Test move the marked section up.. + move_section_to($course, 4, 3); + + // Verify that the course marker has been moved along with the section.. + $course = $DB->get_record('course', array('id' => $course->id)); + $this->assertEquals(3, $course->marker); + + // Test moving a non-marked section above the marked section.. + move_section_to($course, 4, 2); + + // Verify that the course marker has been moved down to accomodate.. + $course = $DB->get_record('course', array('id' => $course->id)); + $this->assertEquals(4, $course->marker); + + // Test moving a non-marked section below the marked section.. + move_section_to($course, 3, 6); + + // Verify that the course marker has been up to accomodate.. + $course = $DB->get_record('course', array('id' => $course->id)); + $this->assertEquals(3, $course->marker); + } + public function test_get_course_display_name_for_list() { global $CFG; $this->resetAfterTest(true); From 2365213fdb5a07870329627caf6025764b95f69b Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Mon, 11 Jun 2012 11:47:04 +0800 Subject: [PATCH 003/130] MDL-33623 - course: remove incorrect logic for marker moving --- course/lib.php | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/course/lib.php b/course/lib.php index 26fea7250e0..5e66fdb3187 100644 --- a/course/lib.php +++ b/course/lib.php @@ -3023,20 +3023,13 @@ function move_section_to($course, $section, $destination) { } } - // Adjust destination to reflect the actual section - $moveup = false; - if ($section > $destination) { - $destination++; - $moveup = true; - } - // If we move the highlighted section itself, then just highlight the destination. // Adjust the higlighted section location if we move something over it either direction. if ($section == $course->marker) { course_set_marker($course->id, $destination); - } elseif ($moveup && $section > $course->marker && $course->marker >= $destination) { + } elseif ($section > $course->marker && $course->marker >= $destination) { course_set_marker($course->id, $course->marker+1); - } elseif (!$moveup && $section < $course->marker && $course->marker <= $destination) { + } elseif ($section < $course->marker && $course->marker <= $destination) { course_set_marker($course->id, $course->marker-1); } From c17ec774d7b4101e38ea3793f1ed3bb817405920 Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Tue, 12 Jun 2012 22:32:43 +0800 Subject: [PATCH 004/130] MDL-33552 - portfolio api E_STRICT fixes admin_config_form and admin_config_validation are now static --- lib/portfolio/forms.php | 17 ++++------------- lib/portfolio/plugin.php | 4 ++-- portfolio/boxnet/lib.php | 2 +- portfolio/flickr/lib.php | 2 +- portfolio/googledocs/lib.php | 2 +- portfolio/mahara/lib.php | 2 +- portfolio/picasa/lib.php | 2 +- portfolio/upgrade.txt | 9 +++++++++ 8 files changed, 20 insertions(+), 20 deletions(-) create mode 100644 portfolio/upgrade.txt diff --git a/lib/portfolio/forms.php b/lib/portfolio/forms.php index 7b7c66908ed..2e95777326d 100644 --- a/lib/portfolio/forms.php +++ b/lib/portfolio/forms.php @@ -199,13 +199,9 @@ final class portfolio_admin_form extends moodleform { // let the plugin add the fields they want (either statically or not) if (portfolio_static_function($this->plugin, 'has_admin_config')) { - if (!$this->instance) { - require_once($CFG->libdir . '/portfolio/plugin.php'); - require_once($CFG->dirroot . '/portfolio/' . $this->plugin . '/lib.php'); - call_user_func(array('portfolio_plugin_' . $this->plugin, 'admin_config_form'), $mform); - } else { - $this->instance->admin_config_form($mform); - } + require_once($CFG->libdir . '/portfolio/plugin.php'); + require_once($CFG->dirroot . '/portfolio/' . $this->plugin . '/lib.php'); + call_user_func(array('portfolio_plugin_' . $this->plugin, 'admin_config_form'), $mform); } // and set the data if we have some. @@ -237,12 +233,7 @@ final class portfolio_admin_form extends moodleform { } $pluginerrors = array(); - if ($this->instance) { - $pluginerrors = $this->instance->admin_config_validation($data); - } - else { - $pluginerrors = portfolio_static_function($this->plugin, 'admin_config_validation', $data); - } + $pluginerrors = portfolio_static_function($this->plugin, 'admin_config_validation', $data); if (is_array($pluginerrors)) { $errors = array_merge($errors, $pluginerrors); } diff --git a/lib/portfolio/plugin.php b/lib/portfolio/plugin.php index 6c32ffc6420..34c40c8d3fd 100644 --- a/lib/portfolio/plugin.php +++ b/lib/portfolio/plugin.php @@ -347,7 +347,7 @@ abstract class portfolio_plugin_base { * * @param moodleform $mform passed by reference, add elements to it. */ - public function admin_config_form(&$mform) {} + public static function admin_config_form(&$mform) {} /** * Just like the moodle form validation function, @@ -356,7 +356,7 @@ abstract class portfolio_plugin_base { * * @param array $data data from form. */ - public function admin_config_validation($data) {} + public static function admin_config_validation($data) {} /** * mform to display to the user exporting data using this plugin. diff --git a/portfolio/boxnet/lib.php b/portfolio/boxnet/lib.php index 99c42ba940a..120f61e8030 100644 --- a/portfolio/boxnet/lib.php +++ b/portfolio/boxnet/lib.php @@ -106,7 +106,7 @@ class portfolio_plugin_boxnet extends portfolio_plugin_push_base { } } - public function admin_config_form(&$mform) { + public static function admin_config_form(&$mform) { global $CFG; $mform->addElement('text', 'apikey', get_string('apikey', 'portfolio_boxnet')); diff --git a/portfolio/flickr/lib.php b/portfolio/flickr/lib.php index fe63d9dbb17..2815a0f55c1 100644 --- a/portfolio/flickr/lib.php +++ b/portfolio/flickr/lib.php @@ -96,7 +96,7 @@ class portfolio_plugin_flickr extends portfolio_plugin_push_base { return true; } - public function admin_config_form(&$mform) { + public static function admin_config_form(&$mform) { global $CFG; $strrequired = get_string('required'); diff --git a/portfolio/googledocs/lib.php b/portfolio/googledocs/lib.php index 02ce15910ef..9695bc2ee75 100644 --- a/portfolio/googledocs/lib.php +++ b/portfolio/googledocs/lib.php @@ -100,7 +100,7 @@ class portfolio_plugin_googledocs extends portfolio_plugin_push_base { return array('clientid', 'secret'); } - public function admin_config_form(&$mform) { + public static function admin_config_form(&$mform) { $a = new stdClass; $a->docsurl = get_docs_url('Google_OAuth2_Setup'); $a->callbackurl = google_oauth::callback_url()->out(false); diff --git a/portfolio/mahara/lib.php b/portfolio/mahara/lib.php index beb43b1a37a..77c40d6f31a 100644 --- a/portfolio/mahara/lib.php +++ b/portfolio/mahara/lib.php @@ -84,7 +84,7 @@ class portfolio_plugin_mahara extends portfolio_plugin_pull_base { return true; } - public function admin_config_form(&$mform) { + public static function admin_config_form(&$mform) { $strrequired = get_string('required'); $hosts = self::get_mnet_hosts(); // this is called by sanity check but it's ok because it's cached foreach ($hosts as $host) { diff --git a/portfolio/picasa/lib.php b/portfolio/picasa/lib.php index 70200c13af8..cb72e850217 100644 --- a/portfolio/picasa/lib.php +++ b/portfolio/picasa/lib.php @@ -100,7 +100,7 @@ class portfolio_plugin_picasa extends portfolio_plugin_push_base { return array('clientid', 'secret'); } - public function admin_config_form(&$mform) { + public static function admin_config_form(&$mform) { $a = new stdClass; $a->docsurl = get_docs_url('Google_OAuth2_Setup'); $a->callbackurl = google_oauth::callback_url()->out(false); diff --git a/portfolio/upgrade.txt b/portfolio/upgrade.txt new file mode 100644 index 00000000000..efc88ea345e --- /dev/null +++ b/portfolio/upgrade.txt @@ -0,0 +1,9 @@ +This files describes API changes in /portfolio/ portfolio system, +information provided here is intended especially for developers. + +=== 2.3 === + +required changes: +* The following methods must now be declared static for php5 compatibility: + - admin_config_form + - admin_config_validation From b15ef0b058e2055b8bea57621e6c9781654dcf96 Mon Sep 17 00:00:00 2001 From: Rossiani Wijaya Date: Wed, 13 Jun 2012 15:25:23 +0800 Subject: [PATCH 005/130] MDL-33121 Book Module: Fixed documentation header --- mod/book/README.md | 23 ------------------- mod/book/backup/moodle1/lib.php | 2 +- .../backup/moodle2/restore_book_stepslib.php | 1 - mod/book/db/access.php | 2 +- mod/book/db/log.php | 2 +- mod/book/db/upgrade.php | 2 +- mod/book/delete.php | 2 +- mod/book/edit.php | 2 +- mod/book/edit_form.php | 2 +- mod/book/index.php | 2 +- mod/book/lang/en/book.php | 2 +- mod/book/lib.php | 2 +- mod/book/locallib.php | 2 +- mod/book/mod_form.php | 2 +- mod/book/move.php | 2 +- mod/book/settings.php | 2 +- mod/book/show.php | 2 +- mod/book/tool/exportimscp/db/access.php | 2 +- mod/book/tool/exportimscp/db/log.php | 2 +- mod/book/tool/exportimscp/index.php | 2 +- .../lang/en/booktool_exportimscp.php | 2 +- mod/book/tool/exportimscp/lib.php | 2 +- mod/book/tool/exportimscp/locallib.php | 2 +- mod/book/tool/exportimscp/version.php | 2 +- mod/book/tool/importhtml/db/access.php | 2 +- mod/book/tool/importhtml/import_form.php | 2 +- mod/book/tool/importhtml/index.php | 2 +- .../lang/en/booktool_importhtml.php | 2 +- mod/book/tool/importhtml/lib.php | 2 +- mod/book/tool/importhtml/locallib.php | 2 +- mod/book/tool/importhtml/version.php | 2 +- mod/book/tool/print/db/access.php | 2 +- mod/book/tool/print/db/log.php | 2 +- mod/book/tool/print/index.php | 2 +- .../tool/print/lang/en/booktool_print.php | 2 +- mod/book/tool/print/lib.php | 2 +- mod/book/tool/print/locallib.php | 2 +- mod/book/tool/print/version.php | 2 +- mod/book/version.php | 2 +- mod/book/view.php | 2 +- 40 files changed, 38 insertions(+), 62 deletions(-) diff --git a/mod/book/README.md b/mod/book/README.md index c4161c14b29..4aa893388bf 100644 --- a/mod/book/README.md +++ b/mod/book/README.md @@ -19,24 +19,6 @@ Created by: * Petr Skoda (skodak) - most of the coding & design * Mojmir Volf, Eloy Lafuente, Antonio Vicent and others - - -Project page: - -* https://github.com/skodak/moodle-mod_book -* http://moodle.org/plugins/view.php?plugin=mod_book - - -Installation: - -* http://docs.moodle.org/20/en/Installing_contributed_modules_or_plugins - - -Issue tracker: - -* https://github.com/skodak/moodle-mod_book/issues?milestone=&labels= - - Intentionally omitted features: * more chapter levels - it would encourage teachers to write too much complex and long books, better use standard standalone HTML editor and import it as Resource. DocBook format is another suitable solution. @@ -44,8 +26,3 @@ Intentionally omitted features: * PDF export - there is no elegant way AFAIK to convert HTML to PDF, use virtual PDF printer or better use DocBook format for authoring * detailed student tracking (postponed till officially supported) * export as zipped set of HTML pages - instead use browser command Save page as... in print view - - -Future: - -* No more development planned diff --git a/mod/book/backup/moodle1/lib.php b/mod/book/backup/moodle1/lib.php index 5a5852603f5..f0a1cba9cf8 100644 --- a/mod/book/backup/moodle1/lib.php +++ b/mod/book/backup/moodle1/lib.php @@ -1,5 +1,5 @@ Date: Wed, 13 Jun 2012 15:28:07 +0800 Subject: [PATCH 006/130] MDL-33121 Book Module: performed minor changes and cleanup for the module --- mod/book/backup/moodle1/lib.php | 4 +- mod/book/db/upgrade.php | 1 - mod/book/delete.php | 5 +- mod/book/edit.php | 5 +- mod/book/edit_form.php | 12 ++- mod/book/index.php | 6 +- mod/book/lang/en/book.php | 3 +- mod/book/lib.php | 10 +-- mod/book/locallib.php | 126 ++++++++++++++++++++-------- mod/book/styles.css | 6 +- mod/book/tool/exportimscp/index.php | 4 - mod/book/tool/exportimscp/lib.php | 5 +- mod/book/tool/importhtml/index.php | 5 +- mod/book/tool/importhtml/lib.php | 5 +- mod/book/tool/print/lib.php | 5 +- mod/book/tool/print/locallib.php | 52 ++++++++---- mod/book/view.php | 5 +- 17 files changed, 160 insertions(+), 99 deletions(-) diff --git a/mod/book/backup/moodle1/lib.php b/mod/book/backup/moodle1/lib.php index f0a1cba9cf8..00805bf2dbf 100644 --- a/mod/book/backup/moodle1/lib.php +++ b/mod/book/backup/moodle1/lib.php @@ -130,14 +130,14 @@ class moodle1_mod_book_handler extends moodle1_mod_handler { } /** - * This is executed when the parser reaches the opening element + * This is executed when the parser reaches the opening element */ public function on_book_chapters_start() { $this->xmlwriter->begin_tag('chapters'); } /** - * This is executed when the parser reaches the closing element + * This is executed when the parser reaches the closing element */ public function on_book_chapters_end() { $this->xmlwriter->end_tag('chapters'); diff --git a/mod/book/db/upgrade.php b/mod/book/db/upgrade.php index c25f93f6c36..735116cd360 100644 --- a/mod/book/db/upgrade.php +++ b/mod/book/db/upgrade.php @@ -13,7 +13,6 @@ // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . - /** * Book module upgrade code * diff --git a/mod/book/delete.php b/mod/book/delete.php index 196d10336a0..63c9507064a 100644 --- a/mod/book/delete.php +++ b/mod/book/delete.php @@ -45,9 +45,8 @@ $chapter = $DB->get_record('book_chapters', array('id'=>$chapterid, 'bookid'=>$b // Header and strings. -$PAGE->set_title(format_string($book->name)); -$PAGE->add_body_class('mod_book'); -$PAGE->set_heading(format_string($course->fullname)); +$PAGE->set_title($book->name); +$PAGE->set_heading($course->fullname); // Form processing. if ($confirm) { // the operation was confirmed. diff --git a/mod/book/edit.php b/mod/book/edit.php index a625636669b..541233daf48 100644 --- a/mod/book/edit.php +++ b/mod/book/edit.php @@ -108,9 +108,8 @@ if ($mform->is_cancelled()) { } // Otherwise fill and print the form. -$PAGE->set_title(format_string($book->name)); -$PAGE->add_body_class('mod_book'); -$PAGE->set_heading(format_string($course->fullname)); +$PAGE->set_title($book->name); +$PAGE->set_heading($course->fullname); echo $OUTPUT->header(); echo $OUTPUT->heading(get_string('editingchapter', 'mod_book')); diff --git a/mod/book/edit_form.php b/mod/book/edit_form.php index 4e424d91574..c62d6674411 100644 --- a/mod/book/edit_form.php +++ b/mod/book/edit_form.php @@ -29,11 +29,19 @@ require_once($CFG->libdir.'/formslib.php'); class book_chapter_edit_form extends moodleform { function definition() { - global $CFG; $chapter = $this->_customdata['chapter']; $options = $this->_customdata['options']; + //Disabled subchapter option when editing first node + $disabledmsg = null; + $disabledarr = null; + + if (!$chapter->id && $chapter->pagenum == 1 || $chapter->pagenum == 1) { + $disabledmsg = get_string('subchapternotice', 'book'); + $disabledarr = array('group' => 1, 'disabled' => 'disabled'); + } + $mform = $this->_form; $mform->addElement('header', 'general', get_string('edit')); @@ -42,7 +50,7 @@ class book_chapter_edit_form extends moodleform { $mform->setType('title', PARAM_RAW); $mform->addRule('title', null, 'required', null, 'client'); - $mform->addElement('advcheckbox', 'subchapter', get_string('subchapter', 'mod_book')); + $mform->addElement('advcheckbox', 'subchapter', get_string('subchapter', 'mod_book'), $disabledmsg, $disabledarr); $mform->addElement('editor', 'content_editor', get_string('content', 'mod_book'), null, $options); $mform->setType('content_editor', PARAM_RAW); diff --git a/mod/book/index.php b/mod/book/index.php index bf8b117b705..b413ba3cc2c 100644 --- a/mod/book/index.php +++ b/mod/book/index.php @@ -88,14 +88,14 @@ foreach ($books as $book) { $currentsection = $book->section; } } else { - $printsection = ''.userdate($book->timemodified).""; + $printsection = html_writer::tag('span', userdate($book->timemodified), array('class' => 'smallinfo')); } - $class = $book->visible ? '' : 'class="dimmed"'; // hidden modules are dimmed + $class = $book->visible ? null : array('class' => 'dimmed'); // hidden modules are dimmed $table->data[] = array ( $printsection, - "id\">".format_string($book->name)."", + html_writer::link(new moodle_url('view.php', array('id' => $cm->id)), format_string($book->name), $class), format_module_intro('book', $book, $cm->id)); } diff --git a/mod/book/lang/en/book.php b/mod/book/lang/en/book.php index 7b10beb3a1e..c853dd28383 100644 --- a/mod/book/lang/en/book.php +++ b/mod/book/lang/en/book.php @@ -58,7 +58,6 @@ $string['numbering2'] = 'Bullets'; $string['numbering3'] = 'Indented'; $string['numberingoptions'] = 'Available options for chapter formatting'; $string['numberingoptions_desc'] = 'Options for displaying chapters and subchapters in the table of contents'; -$string['chapterscount'] = 'Chapters'; $string['addafter'] = 'Add new chapter'; $string['confchapterdelete'] = 'Do you really want to delete this chapter?'; $string['confchapterdeleteall'] = 'Do you really want to delete this chapter and all its subchapters?'; @@ -73,6 +72,6 @@ $string['book:viewhiddenchapters'] = 'View hidden book chapters'; $string['errorchapter'] = 'Error reading chapter of book.'; $string['page-mod-book-x'] = 'Any book module page'; - +$string['subchapternotice'] = 'This option is disabled, because the first chapter cannot be a subchapter'; $string['subplugintype_booktool'] = 'Book tool'; $string['subplugintype_booktool_plural'] = 'Book tools'; diff --git a/mod/book/lib.php b/mod/book/lib.php index 50da68b4d19..7ba75b61138 100644 --- a/mod/book/lib.php +++ b/mod/book/lib.php @@ -29,7 +29,7 @@ defined('MOODLE_INTERNAL') || die; * @return array */ function book_get_numbering_types() { - global $CFG; // required for the include + require_once(dirname(__FILE__).'/locallib.php'); return array ( @@ -215,7 +215,6 @@ function book_scale_used_anywhere($scaleid) { * @return array */ function book_get_view_actions() { - global $CFG; // necessary for includes $return = array('view', 'view all'); @@ -240,7 +239,6 @@ function book_get_view_actions() { * @return array */ function book_get_post_actions() { - global $CFG; // necessary for includes $return = array('update'); @@ -291,13 +289,11 @@ function book_supports($feature) { * @return void */ function book_extend_settings_navigation(settings_navigation $settingsnav, navigation_node $booknode) { - global $USER, $PAGE, $CFG, $DB, $OUTPUT; - if ($PAGE->cm->modname !== 'book') { - return; - } + global $USER, $PAGE; $plugins = get_plugin_list('booktool'); + foreach ($plugins as $plugin => $dir) { if (file_exists("$dir/lib.php")) { require_once("$dir/lib.php"); diff --git a/mod/book/locallib.php b/mod/book/locallib.php index e51522b31cc..ae144c68d80 100644 --- a/mod/book/locallib.php +++ b/mod/book/locallib.php @@ -24,6 +24,8 @@ defined('MOODLE_INTERNAL') || die; +global $CFG; + require_once(dirname(__FILE__).'/lib.php'); require_once($CFG->libdir.'/filelib.php'); @@ -217,7 +219,7 @@ function book_add_fake_block($chapters, $chapter, $book, $cm, $edit) { function book_get_toc($chapters, $chapter, $book, $cm, $edit) { global $USER, $OUTPUT; - $toc = ''; // Representation of toc (HTML) + $toc =''; $nch = 0; // Chapter number $ns = 0; // Subchapter number $first = 1; @@ -226,27 +228,35 @@ function book_get_toc($chapters, $chapter, $book, $cm, $edit) { switch ($book->numbering) { case BOOK_NUM_NONE: - $toc .= '
'; + $toc .= html_writer::start_tag('div', array('class' => 'book_toc_none')); break; case BOOK_NUM_NUMBERS: - $toc .= '
'; + $toc .= html_writer::start_tag('div', array('class' => 'book_toc_numbered')); break; case BOOK_NUM_BULLETS: - $toc .= '
'; + $toc .= html_writer::start_tag('div', array('class' => 'book_toc_bullets')); break; case BOOK_NUM_INDENTED: - $toc .= '
'; + $toc .= html_writer::start_tag('div', array('class' => 'book_toc_indented')); break; } if ($edit) { // Teacher's TOC - $toc .= '
    '; + $toc .= html_writer::start_tag('ul'); $i = 0; foreach ($chapters as $ch) { $i++; $title = trim(format_string($ch->title, true, array('context'=>$context))); if (!$ch->subchapter) { - $toc .= ($first) ? '
  • ' : '
  • '; + + if ($first) { + $toc .= html_writer::start_tag('li'); + } else { + $toc .= html_writer::end_tag('ul'); + $toc .= html_writer::end_tag('li'); + $toc .= html_writer::start_tag('li'); + } + if (!$ch->hidden) { $nch++; $ns = 0; @@ -257,10 +267,18 @@ function book_get_toc($chapters, $chapter, $book, $cm, $edit) { if ($book->numbering == BOOK_NUM_NUMBERS) { $title = "x $title"; } - $title = ''.$title.''; + $title = html_writer::tag('span', $title, array('class' => 'dimmed_text')); } } else { - $toc .= ($first) ? '
    • ' : '
    • '; + + if ($first) { + $toc .= html_writer::start_tag('li'); + $toc .= html_writer::start_tag('ul'); + $toc .= html_writer::start_tag('li'); + } else { + $toc .= html_writer::start_tag('li'); + } + if (!$ch->hidden) { $ns++; if ($book->numbering == BOOK_NUM_NUMBERS) { @@ -270,75 +288,109 @@ function book_get_toc($chapters, $chapter, $book, $cm, $edit) { if ($book->numbering == BOOK_NUM_NUMBERS) { $title = "x.x $title"; } - $title = ''.$title.''; + $title = html_writer::tag('span', $title, array('class' => 'dimmed_text')); } } if ($ch->id == $chapter->id) { - $toc .= ''.$title.''; + $toc .= html_writer::tag('strong', $title); } else { - $toc .= ''.$title.''; + $toc .= html_writer::link(new moodle_url('view.php', array('id' => $cm->id, 'chapterid' => $ch->id)), $title, array('title' => s($title))); } $toc .= '  '; if ($i != 1) { - $toc .= ' '.get_string('up').''; + $toc .= html_writer::link(new moodle_url('move.php', array('id' => $cm->id, 'chapterid' => $ch->id, 'up' => '1', 'sesskey' => $USER->sesskey)), + $OUTPUT->pix_icon('t/up', get_string('up')), array('title' => get_string('up'))); } if ($i != count($chapters)) { - $toc .= ' '.get_string('down').''; + $toc .= html_writer::link(new moodle_url('move.php', array('id' => $cm->id, 'chapterid' => $ch->id, 'up' => '0', 'sesskey' => $USER->sesskey)), + $OUTPUT->pix_icon('t/down', get_string('down')), array('title' => get_string('down'))); } - $toc .= ' '.get_string('edit').''; - $toc .= ' '.get_string('delete').''; + $toc .= html_writer::link(new moodle_url('edit.php', array('cmid' => $cm->id, 'id' => $ch->id)), + $OUTPUT->pix_icon('t/edit', get_string('edit')), array('title' => get_string('edit'))); + $toc .= html_writer::link(new moodle_url('delete.php', array('id' => $cm->id, 'chapterid' => $ch->id, 'sesskey' => $USER->sesskey)), + $OUTPUT->pix_icon('t/delete', get_string('delete')), array('title' => get_string('delete'))); if ($ch->hidden) { - $toc .= ' '.get_string('show').''; + $toc .= html_writer::link(new moodle_url('show.php', array('id' => $cm->id, 'chapterid' => $ch->id, 'sesskey' => $USER->sesskey)), + $OUTPUT->pix_icon('t/show', get_string('show')), array('title' => get_string('show'))); } else { - $toc .= ' '.get_string('hide').''; + $toc .= html_writer::link(new moodle_url('show.php', array('id' => $cm->id, 'chapterid' => $ch->id, 'sesskey' => $USER->sesskey)), + $OUTPUT->pix_icon('t/hide', get_string('hide')), array('title' => get_string('hide'))); } - $toc .= ' '.get_string('addafter', 'mod_book').''; + $toc .= html_writer::link(new moodle_url('edit.php', array('cmid' => $cm->id, 'pagenum' => $ch->pagenum, 'subchapter' => $ch->subchapter)), + $OUTPUT->pix_icon('add', get_string('addafter', 'mod_book'), 'mod_book'), array('title' => get_string('addafter', 'mod_book'))); - $toc .= (!$ch->subchapter) ? '
        ' : ''; + + if (!$ch->subchapter) { + $toc .= html_writer::start_tag('ul'); + } else { + $toc .= html_writer::end_tag('li'); + } $first = 0; } - $toc .= '
    '; + + $toc .= html_writer::end_tag('ul'); + $toc .= html_writer::end_tag('li'); + $toc .= html_writer::end_tag('ul'); + } else { // Normal students view - $toc .= '
      '; + $toc .= html_writer::start_tag('ul'); foreach ($chapters as $ch) { $title = trim(format_string($ch->title, true, array('context'=>$context))); if (!$ch->hidden) { if (!$ch->subchapter) { $nch++; $ns = 0; - $toc .= ($first) ? '
    • ' : '
  • '; + + if ($first) { + $toc .= html_writer::start_tag('li'); + } else { + $toc .= html_writer::end_tag('ul'); + $toc .= html_writer::end_tag('li'); + $toc .= html_writer::start_tag('li'); + } + if ($book->numbering == BOOK_NUM_NUMBERS) { $title = "$nch $title"; } } else { $ns++; - $toc .= ($first) ? '
    • ' : '
    • '; + + if ($first) { + $toc .= html_writer::start_tag('li'); + $toc .= html_writer::start_tag('ul'); + $toc .= html_writer::start_tag('li'); + } else { + $toc .= html_writer::start_tag('li'); + } + if ($book->numbering == BOOK_NUM_NUMBERS) { $title = "$nch.$ns $title"; } } if ($ch->id == $chapter->id) { - $toc .= ''.$title.''; + $toc .= html_writer::tag('strong', $title); } else { - $toc .= ''.$title.''; + $toc .= html_writer::link(new moodle_url('view.php', array('id' => $cm->id, 'chapterid' => $ch->id)), $title, array('title' => s($title))); } - $toc .= (!$ch->subchapter) ? '
        ' : ''; + + if (!$ch->subchapter) { + $toc .= html_writer::start_tag('ul'); + } else { + $toc .= html_writer::end_tag('li'); + } + $first = 0; } } - $toc .= '
    '; + + $toc .= html_writer::end_tag('ul'); + $toc .= html_writer::end_tag('li'); + $toc .= html_writer::end_tag('ul'); + } - $toc .= '
  • '; + $toc .= html_writer::end_tag('div'); $toc = str_replace('
      ', '', $toc); // Cleanup of invalid structures. diff --git a/mod/book/styles.css b/mod/book/styles.css index 6ddaf09cf06..8bd9425ea9b 100644 --- a/mod/book/styles.css +++ b/mod/book/styles.css @@ -1,5 +1,5 @@ -.mod_book .book_chapter_title { +.path-mod-book .book_chapter_title { font-family: Tahoma, Verdana, Arial, Helvetica, sans-serif; text-align: left; font-size: large; @@ -9,7 +9,7 @@ margin-bottom: 20px; } -.mod_book img.bigicon { +.path-mod-book img.bigicon { vertical-align: middle; margin-right: 4px; margin-left: 4px; @@ -18,7 +18,7 @@ border: 0px; } -.mod_book .navtop { +.path-mod-book .navtop { text-align: right; margin-bottom: 0.5em; } diff --git a/mod/book/tool/exportimscp/index.php b/mod/book/tool/exportimscp/index.php index 29d7b445c10..5e05581efc5 100644 --- a/mod/book/tool/exportimscp/index.php +++ b/mod/book/tool/exportimscp/index.php @@ -44,10 +44,6 @@ $context = context_module::instance($cm->id); require_capability('mod/book:read', $context); require_capability('booktool/exportimscp:export', $context); -$strbooks = get_string('modulenameplural', 'book'); -$strbook = get_string('modulename', 'book'); -$strtop = get_string('top', 'book'); - add_to_log($course->id, 'book', 'exportimscp', 'tool/exportimscp/index.php?id='.$cm->id, $book->id, $cm->id); $file = booktool_exportimscp_build_package($book, $context); diff --git a/mod/book/tool/exportimscp/lib.php b/mod/book/tool/exportimscp/lib.php index d0f149c0495..620b524c611 100644 --- a/mod/book/tool/exportimscp/lib.php +++ b/mod/book/tool/exportimscp/lib.php @@ -31,11 +31,8 @@ defined('MOODLE_INTERNAL') || die; * @param navigation_node $node The node to add module settings to */ function booktool_exportimscp_extend_settings_navigation(settings_navigation $settings, navigation_node $node) { - global $USER, $PAGE, $CFG, $DB, $OUTPUT; - if ($PAGE->cm->modname !== 'book') { - return; - } + global $PAGE; if (has_capability('booktool/exportimscp:export', $PAGE->cm->context)) { $url = new moodle_url('/mod/book/tool/exportimscp/index.php', array('id'=>$PAGE->cm->id)); diff --git a/mod/book/tool/importhtml/index.php b/mod/book/tool/importhtml/index.php index 91a202c351a..eaae261f830 100644 --- a/mod/book/tool/importhtml/index.php +++ b/mod/book/tool/importhtml/index.php @@ -48,9 +48,8 @@ if ($chapterid) { $chapter = false; } -$PAGE->set_title(format_string($book->name)); -$PAGE->add_body_class('mod_book'); -$PAGE->set_heading(format_string($course->fullname)); +$PAGE->set_title($book->name); +$PAGE->set_heading($course->fullname); // Prepare the page header. $strbook = get_string('modulename', 'mod_book'); diff --git a/mod/book/tool/importhtml/lib.php b/mod/book/tool/importhtml/lib.php index 96cb709ee52..09d032f3e0c 100644 --- a/mod/book/tool/importhtml/lib.php +++ b/mod/book/tool/importhtml/lib.php @@ -31,11 +31,8 @@ defined('MOODLE_INTERNAL') || die; * @param navigation_node $node The node to add module settings to */ function booktool_importhtml_extend_settings_navigation(settings_navigation $settings, navigation_node $node) { - global $USER, $PAGE, $CFG, $DB, $OUTPUT; - if ($PAGE->cm->modname !== 'book') { - return; - } + global $PAGE; if (has_capability('booktool/importhtml:import', $PAGE->cm->context)) { $url = new moodle_url('/mod/book/tool/importhtml/index.php', array('id'=>$PAGE->cm->id)); diff --git a/mod/book/tool/print/lib.php b/mod/book/tool/print/lib.php index 427acc83e6c..f3b2f8cce8d 100644 --- a/mod/book/tool/print/lib.php +++ b/mod/book/tool/print/lib.php @@ -31,11 +31,8 @@ defined('MOODLE_INTERNAL') || die; * @param navigation_node $node The node to add module settings to */ function booktool_print_extend_settings_navigation(settings_navigation $settings, navigation_node $node) { - global $USER, $PAGE, $CFG, $DB, $OUTPUT; - if ($PAGE->cm->modname !== 'book') { - return; - } + global $PAGE; $params = $PAGE->url->params(); diff --git a/mod/book/tool/print/locallib.php b/mod/book/tool/print/locallib.php index c86303983d4..200bee74867 100644 --- a/mod/book/tool/print/locallib.php +++ b/mod/book/tool/print/locallib.php @@ -45,43 +45,67 @@ function booktool_print_get_toc($chapters, $book, $cm) { switch ($book->numbering) { case BOOK_NUM_NONE: - $toc .= '
      '; + $toc .= html_writer::start_tag('div', array('class' => 'book_toc_none')); break; case BOOK_NUM_NUMBERS: - $toc .= '
      '; + $toc .= html_writer::start_tag('div', array('class' => 'book_toc_numbered')); break; case BOOK_NUM_BULLETS: - $toc .= '
      '; + $toc .= html_writer::start_tag('div', array('class' => 'book_toc_bullets')); break; case BOOK_NUM_INDENTED: - $toc .= '
      '; + $toc .= html_writer::start_tag('div', array('class' => 'book_toc_indented')); break; } - $toc .= ''; // Representation of toc (HTML). + $toc .= html_writer::tag('a', '', array('name' => 'toc')); // Representation of toc (HTML). if ($book->customtitles) { - $toc .= '

      '.get_string('toc', 'mod_book').'

      '; + $toc .= html_writer::tag('h1', get_string('toc', 'mod_book')); } else { - $toc .= '

      '.get_string('toc', 'mod_book').'

      '; + $toc .= html_writer::tag('p', get_string('toc', 'mod_book'), array('class' => 'book_chapter_title')); } - $toc .= '
        '; + $toc .= html_writer::start_tag('ul'); foreach ($chapters as $ch) { if (!$ch->hidden) { $title = book_get_chapter_title($ch->id, $chapters, $book, $context); if (!$ch->subchapter) { - $toc .= $first ? '
      • ' : '
    • '; + + if ($first) { + $toc .= html_writer::start_tag('li'); + } else { + $toc .= html_writer::end_tag('ul'); + $toc .= html_writer::end_tag('li'); + $toc .= html_writer::start_tag('li'); + } + } else { - $toc .= $first ? '
      • ' : '
      • '; + + if ($first) { + $toc .= html_writer::start_tag('li'); + $toc .= html_writer::start_tag('ul'); + $toc .= html_writer::start_tag('li'); + } else { + $toc .= html_writer::start_tag('li'); + } + } $titles[$ch->id] = $title; - $toc .= ''.$title.''; - $toc .= (!$ch->subchapter) ? '
          ' : ''; + $toc .= html_writer::link(new moodle_url('#ch'.$ch->id), $title, array('title' => s($title))); + if (!$ch->subchapter) { + $toc .= html_writer::start_tag('ul'); + } else { + $toc .= html_writer::end_tag('li'); + } $first = false; } } - $toc .= '
      '; - $toc .= '
    • '; + + $toc .= html_writer::end_tag('ul'); + $toc .= html_writer::end_tag('li'); + $toc .= html_writer::end_tag('ul'); + $toc .= html_writer::end_tag('div'); + $toc = str_replace('
        ', '', $toc); // Cleanup of invalid structures. return array($toc, $titles); diff --git a/mod/book/view.php b/mod/book/view.php index f7adbbe98b1..26d5ac0b3d0 100644 --- a/mod/book/view.php +++ b/mod/book/view.php @@ -114,9 +114,8 @@ $strbook = get_string('modulename', 'mod_book'); $strtoc = get_string('toc', 'mod_book'); // prepare header -$PAGE->set_title(format_string($book->name)); -$PAGE->add_body_class('mod_book'); -$PAGE->set_heading(format_string($course->fullname)); +$PAGE->set_title($book->name); +$PAGE->set_heading($course->fullname); book_add_fake_block($chapters, $chapter, $book, $cm, $edit); From fb909757a678a230cc53254d7247aaced6893d75 Mon Sep 17 00:00:00 2001 From: Rossiani Wijaya Date: Wed, 13 Jun 2012 15:42:58 +0800 Subject: [PATCH 007/130] MDL-33121 Book Module: Removing unused book_log(), renamed css class and fixed the book_preload_chpaters: next and previous values --- mod/book/locallib.php | 42 ++++++++++-------------------------------- mod/book/styles.css | 42 +++++++++++++++++++++--------------------- 2 files changed, 31 insertions(+), 53 deletions(-) diff --git a/mod/book/locallib.php b/mod/book/locallib.php index ae144c68d80..d089abf7339 100644 --- a/mod/book/locallib.php +++ b/mod/book/locallib.php @@ -77,11 +77,6 @@ function book_preload_chapters($book) { $first = false; } if (!$ch->subchapter) { - $ch->prev = $prev; - $ch->next = null; - if ($prev) { - $chapters[$prev]->next = $ch->id; - } if ($ch->hidden) { if ($book->numbering == BOOK_NUM_NUMBERS) { $ch->number = 'x'; @@ -99,11 +94,6 @@ function book_preload_chapters($book) { $ch->parent = null; $ch->subchapters = array(); } else { - $ch->prev = $prevsub; - $ch->next = null; - if ($prevsub) { - $chapters[$prevsub]->next = $ch->id; - } $ch->parent = $parent; $ch->subchapters = null; $chapters[$parent]->subchapters[$ch->id] = $ch->id; @@ -122,11 +112,20 @@ function book_preload_chapters($book) { $ch->number = $j; } } + + // assigning previous and next page id + $ch->prev = $prev; + $ch->next = null; + if ($prev) { + $chapters[$prev]->next = $ch->id; + } + if ($oldch->subchapter != $ch->subchapter or $oldch->pagenum != $ch->pagenum or $oldch->hidden != $ch->hidden) { // update only if something changed $DB->update_record('book_chapters', $ch); } $chapters[$id] = $ch; + $prev = $ch->id; } return $chapters; @@ -161,27 +160,6 @@ function book_get_chapter_title($chid, $chapters, $book, $context) { return $title; } -/** - * General logging to table - * @param string $str1 - * @param string $str2 - * @param int $level - * @return void - */ -function book_log($str1, $str2, $level = 0) { - switch ($level) { - case 1: - echo ''.$str1.''.$str2.''; - break; - case 2: - echo ''.$str1.''.$str2.''; - break; - default: - echo ''.$str1.''.$str2.''; - break; - } -} - /** * Add the book TOC sticky block to the 1st region available * @@ -219,7 +197,7 @@ function book_add_fake_block($chapters, $chapter, $book, $cm, $edit) { function book_get_toc($chapters, $chapter, $book, $cm, $edit) { global $USER, $OUTPUT; - $toc =''; + $toc = ''; $nch = 0; // Chapter number $ns = 0; // Subchapter number $first = 1; diff --git a/mod/book/styles.css b/mod/book/styles.css index 8bd9425ea9b..39b941717cd 100644 --- a/mod/book/styles.css +++ b/mod/book/styles.css @@ -23,95 +23,95 @@ margin-bottom: 0.5em; } -.mod_book .navbottom { +.path-mod-book .navbottom { text-align: right; } /* == Fake toc block == */ /* toc style NONE */ -.mod_book .book_toc_none { +.path-mod-book .book_toc_none { font-size: 0.8em; } -.mod_book .book_toc_none ul { +.path-mod-book .book_toc_none ul { margin-left: 5px; padding-left: 0px; } -.mod_book .book_toc_none ul ul { +.path-mod-book .book_toc_none ul ul { margin-left: 0px; padding-left: 0px; } -.mod_book .book_toc_none li { +.path-mod-book .book_toc_none li { margin-top: 5px; list-style: none; } -.mod_book .book_toc_none li li { +.path-mod-book .book_toc_none li li { margin-top: 0px; list-style: none; } /* toc style NUMBERED */ -.mod_book .book_toc_numbered { +.path-mod-book .book_toc_numbered { font-size: 0.8em; } -.mod_book .book_toc_numbered ul { +.path-mod-book .book_toc_numbered ul { margin-left: 5px; padding-left: 0px; } -.mod_book .book_toc_numbered ul ul { +.path-mod-book .book_toc_numbered ul ul { margin-left: 0px; padding-left: 0px; } -.mod_book .book_toc_numbered li { +.path-mod-book .book_toc_numbered li { margin-top: 5px; list-style: none; } -.mod_book .book_toc_numbered li li { +.path-mod-book .book_toc_numbered li li { margin-top: 0px; list-style: none; } /*toc style BULLETS */ -.mod_book .book_toc_bullets { +.path-mod-book .book_toc_bullets { font-size: 0.8em; } -.mod_book .book_toc_bullets ul { +.path-mod-book .book_toc_bullets ul { margin-left: 5px; padding-left: 0px; } -.mod_book .book_toc_bullets ul ul { +.path-mod-book .book_toc_bullets ul ul { margin-left: 20px; padding-left: 0px; } -.mod_book .book_toc_bullets li { +.path-mod-book .book_toc_bullets li { margin-top: 5px; list-style: none; } -.mod_book .book_toc_bullets li li { +.path-mod-book .book_toc_bullets li li { margin-top: 0px; list-style: circle; } /* toc style INDENTED*/ -.mod_book .book_toc_indented { +.path-mod-book .book_toc_indented { font-size: 0.8em; } -.mod_book .book_toc_indented ul { +.path-mod-book .book_toc_indented ul { margin-left: 5px; padding-left: 0px; } -.mod_book .book_toc_indented ul ul { +.path-mod-book .book_toc_indented ul ul { margin-left: 15px; padding-left: 0px; } -.mod_book .book_toc_indented li { +.path-mod-book .book_toc_indented li { margin-top: 5px; list-style: none; } -.mod_book .book_toc_indented li li { +.path-mod-book .book_toc_indented li li { margin-top: 0px; list-style: none; } From 64063bdbe2fa81e5f2fc1353c4bae192ce97779e Mon Sep 17 00:00:00 2001 From: Barbara Ramiro Date: Tue, 12 Jun 2012 20:26:48 +0800 Subject: [PATCH 008/130] MDL-33661 Aligned assignment 2.2 and its subtypes --- theme/base/style/core.css | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/theme/base/style/core.css b/theme/base/style/core.css index 7e349d0eabb..9187c4c6320 100644 --- a/theme/base/style/core.css +++ b/theme/base/style/core.css @@ -819,8 +819,8 @@ sup {vertical-align: super;} } .moodle-dialogue-base .moodle-dialogue { - background-color: transparent; - border: 0px solid transparent!important; + background: none!important; + border: 0 none!important; } .chooserdialogue .moodle-dialogue-wrap { @@ -882,7 +882,7 @@ sup {vertical-align: super;} max-height: 550px; overflow-x: hidden; overflow-y: auto; - max-width: 18.5em; + max-width: 20.3em; box-shadow: inset 0px 0px 30px 0px #CCCCCC; -webkit-box-shadow: inset 0px 0px 30px 0px #CCCCCC; -moz-box-shadow: inset 0px 0px 30px 0px #CCCCCC; @@ -902,13 +902,10 @@ sup {vertical-align: super;} padding-bottom: 0.4em; } -.choosercontainer #chooseform .subtype { - margin-bottom: 0; - padding: 0 0 0 1em; -} - .choosercontainer #chooseform .option .typename, -.choosercontainer #chooseform .option span.modicon img.icon { +.choosercontainer #chooseform .option span.modicon img.icon, +.choosercontainer #chooseform .nonoption .typename, +.choosercontainer #chooseform .nonoption span.modicon img.icon { padding: 0 0 0 0.5em; } @@ -924,6 +921,21 @@ sup {vertical-align: super;} border-bottom: 1px solid #FFFFFF; } +.choosercontainer #chooseform .nonoption { + padding-left: 2.7em; + padding-top: 0.3em; + padding-bottom: 0.1em; +} + +.choosercontainer #chooseform .subtype { + margin-bottom: 0; + padding: 0 1.6em 0 3.2em; +} + +.choosercontainer #chooseform .subtype .typename { + margin: 0 0 0 0.2em; +} + /* The instruction/help area */ .choosercontainer #chooseform .instruction, .jsenabled .choosercontainer #chooseform .typesummary { @@ -932,7 +944,7 @@ sup {vertical-align: super;} top: 0px; right: 0px; bottom: 0px; - left: 18.5em; + left: 20.3em; margin: 0; padding: 2em 2em 2em 2.4em; background-color: white; From b95b05085c1ee1e68f275186acef77cb2a9dcd1d Mon Sep 17 00:00:00 2001 From: Andrew Robert Nicols Date: Mon, 11 Jun 2012 08:18:44 +0100 Subject: [PATCH 009/130] MDL-33649 Hide page scrollbars when a chooser is open This has the effect of preventing page scrolling which makes the chooser difficult to use when there are many options or the page is too small. --- lib/yui/chooserdialogue/chooserdialogue.js | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/lib/yui/chooserdialogue/chooserdialogue.js b/lib/yui/chooserdialogue/chooserdialogue.js index 7f720d26026..bd29b818770 100644 --- a/lib/yui/chooserdialogue/chooserdialogue.js +++ b/lib/yui/chooserdialogue/chooserdialogue.js @@ -17,6 +17,9 @@ YUI.add('moodle-core-chooserdialogue', function(Y) { // Any event listeners we may need to cancel later listenevents : [], + // The initial overflow setting + initialoverflow : '', + setup_chooser_dialogue : function(bodycontent, headercontent, config) { // Set Default options var params = { @@ -65,6 +68,14 @@ YUI.add('moodle-core-chooserdialogue', function(Y) { var bb = this.overlay.get('boundingBox'); var dialogue = this.container.one('.alloptions'); + // Get the overflow setting when the chooser was opened - we + // may need this later + if (Y.UA.ie > 0) { + this.initialoverflow = Y.one('html').getStyle('overflow'); + } else { + this.initialoverflow = Y.one('body').getStyle('overflow'); + } + var thisevent; // These will trigger a check_options call to display the correct help @@ -168,9 +179,21 @@ YUI.add('moodle-core-chooserdialogue', function(Y) { // Set a fixed position if the window is large enough if (newheight > this.get('minheight')) { bb.setStyle('position', 'fixed'); + // Disable the page scrollbars + if (Y.UA.ie > 0) { + Y.one('html').setStyle('overflow', 'hidden'); + } else { + Y.one('body').setStyle('overflow', 'hidden'); + } } else { bb.setStyle('position', 'absolute'); offsettop = Y.one('window').get('scrollTop'); + // Ensure that the page scrollbars are enabled + if (Y.UA.ie > 0) { + Y.one('html').setStyle('overflow', this.initialoverflow); + } else { + Y.one('body').setStyle('overflow', this.initialoverflow); + } } // Take off 15px top and bottom for borders, plus 40px each for the title and button area before setting the @@ -203,6 +226,14 @@ YUI.add('moodle-core-chooserdialogue', function(Y) { hide : function() { // Detach the global keypress handler before hiding Y.one('document').detach('keyup', this.handle_key_press, this); + + // Re-enable the page scrollbars + if (Y.UA.ie > 0) { + Y.one('html').setStyle('overflow', this.initialoverflow); + } else { + Y.one('body').setStyle('overflow', this.initialoverflow); + } + this.container.detachAll(); this.overlay.hide(); }, From d01ebb940d868c7020708fe318f99b4599ff8660 Mon Sep 17 00:00:00 2001 From: Rajesh Taneja Date: Thu, 14 Jun 2012 11:45:01 +0800 Subject: [PATCH 010/130] MDL-33506 Filepicker: Search box text will be selected on focus --- repository/filepicker.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/repository/filepicker.js b/repository/filepicker.js index 335f4c9614c..d27375e44c5 100644 --- a/repository/filepicker.js +++ b/repository/filepicker.js @@ -1743,6 +1743,14 @@ M.core_filepicker.init = function(Y, options) { if (obj.repo_id == scope.active_repo.id && obj.form) { // if we did not jump to another repository meanwhile searchform.setContent(obj.form); + // Highlight search text when user click for search. + var searchnode = searchform.one('input[name="s"]'); + if (searchnode) { + searchnode.once('click', function(e) { + e.preventDefault(); + this.select(); + }); + } } } }, false); From bc1f298b2a4feeb6be7f595bf32f9a278d2df678 Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Thu, 14 Jun 2012 13:24:10 +0800 Subject: [PATCH 011/130] MDL-33175 - filemanager: make dndupload icon clickable --- lib/form/filemanager.js | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/lib/form/filemanager.js b/lib/form/filemanager.js index 3b2bd3ea921..3949641b3a7 100644 --- a/lib/form/filemanager.js +++ b/lib/form/filemanager.js @@ -262,16 +262,12 @@ M.form_filemanager.init = function(Y, options) { var button_addfile = this.filemanager.one('.fp-btn-add'); // setup 'add file' button - // if maxfiles == -1, the no limit - button_addfile.on('click', function(e) { - e.preventDefault(); - var options = this.filepicker_options; - options.formcallback = this.filepicker_callback; - // XXX: magic here, to let filepicker use filemanager scope - options.magicscope = this; - options.savepath = this.currentpath; - M.core_filepicker.show(Y, options); - }, this); + button_addfile.on('click', this.show_filepicker, this); + + var dndarrow = this.filemanager.one('.dndupload-arrow'); + if (dndarrow) { + dndarrow.on('click', this.show_filepicker, this); + } // setup 'make a folder' button if (this.options.subdirs) { @@ -369,6 +365,18 @@ M.form_filemanager.init = function(Y, options) { } }, this); }, + + show_filepicker: function (e) { + // if maxfiles == -1, the no limit + e.preventDefault(); + var options = this.filepicker_options; + options.formcallback = this.filepicker_callback; + // XXX: magic here, to let filepicker use filemanager scope + options.magicscope = this; + options.savepath = this.currentpath; + M.core_filepicker.show(Y, options); + }, + print_path: function() { var p = this.options.path; this.pathbar.setContent('').addClass('empty'); From 247804bcc238967aa2db3a5713774b6357774f0c Mon Sep 17 00:00:00 2001 From: Frederic Massart Date: Wed, 13 Jun 2012 16:01:38 +0800 Subject: [PATCH 012/130] MDL-33582 Filepicker: set main file button disabled when not required --- lib/form/filemanager.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/form/filemanager.js b/lib/form/filemanager.js index ff00e31c6b6..6cde35fbdf8 100644 --- a/lib/form/filemanager.js +++ b/lib/form/filemanager.js @@ -814,8 +814,8 @@ M.form_filemanager.init = function(Y, options) { e.preventDefault(); var params = {}; var fileinfo = this.selectui.fileinfo; - if (fileinfo.type == 'folder') { - // this button should not even be shown for folders + if (!this.enablemainfile || fileinfo.type == 'folder') { + // this button should not even be shown for folders or when mainfile is disabled return; } params['filepath'] = fileinfo.filepath; From ed8e053e6431ca7ce7ca8401b8906e6eb49de599 Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Thu, 14 Jun 2012 16:27:20 +0800 Subject: [PATCH 013/130] MDL-33724 repository_equella: missing string --- repository/equella/lang/en/repository_equella.php | 1 + 1 file changed, 1 insertion(+) diff --git a/repository/equella/lang/en/repository_equella.php b/repository/equella/lang/en/repository_equella.php index f24ac9a2e31..48cc558149d 100644 --- a/repository/equella/lang/en/repository_equella.php +++ b/repository/equella/lang/en/repository_equella.php @@ -30,6 +30,7 @@ $string['breadcrumb'] = 'EQUELLA'; $string['equellaurl'] = 'EQUELLA URL'; $string['equellaaction'] = 'EQUELLA action'; $string['equellaoptions'] = 'EQUELLA options'; +$string['equella:view'] = 'View EQUELLA repository'; $string['sharedid'] = 'Shared secret ID'; $string['sharedsecrets'] = 'Shared secret'; From 7db27680f87f69e04f65eba52bc67e287c162db7 Mon Sep 17 00:00:00 2001 From: Andrew Robert Nicols Date: Thu, 14 Jun 2012 10:55:16 +0100 Subject: [PATCH 014/130] MDL-33728 Ensure that chooser dialogues are centred vertically --- lib/yui/chooserdialogue/chooserdialogue.js | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/yui/chooserdialogue/chooserdialogue.js b/lib/yui/chooserdialogue/chooserdialogue.js index ebc37e17b27..26b74959648 100644 --- a/lib/yui/chooserdialogue/chooserdialogue.js +++ b/lib/yui/chooserdialogue/chooserdialogue.js @@ -152,6 +152,7 @@ YUI.add('moodle-core-chooserdialogue', function(Y) { var bb = this.overlay.get('boundingBox'); var winheight = bb.get('winHeight'); + var winwidth = bb.get('winWidth'); var offsettop = 0; // Try and set a sensible max-height -- this must be done before setting the top @@ -187,6 +188,13 @@ YUI.add('moodle-core-chooserdialogue', function(Y) { // We need to set the height for the yui3-widget - can't work // out what we're setting at present -- shoud be the boudingBox bb.setStyle('top', dialoguetop + 'px'); + + // Calculate the left location of the chooser + // We don't set a minimum width in the same way as we do height as the width would be far lower than the + // optimal width for moodle anyway. + var dialoguewidth = bb.get('offsetWidth'); + var dialogueleft = (winwidth - dialoguewidth) / 2; + bb.setStyle('left', dialogueleft + 'px'); }, handle_key_press : function(e) { From 605f92ca1d74aae6c9ff790e631a49ef46271d23 Mon Sep 17 00:00:00 2001 From: Andrew Robert Nicols Date: Thu, 14 Jun 2012 11:10:04 +0100 Subject: [PATCH 015/130] MDL-33729 Ensure that the cancel_popup event is correctly called when using the [x] button on a chooser --- lib/yui/chooserdialogue/chooserdialogue.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/yui/chooserdialogue/chooserdialogue.js b/lib/yui/chooserdialogue/chooserdialogue.js index ebc37e17b27..576bf1b109f 100644 --- a/lib/yui/chooserdialogue/chooserdialogue.js +++ b/lib/yui/chooserdialogue/chooserdialogue.js @@ -95,10 +95,14 @@ YUI.add('moodle-core-chooserdialogue', function(Y) { }, this); // Hook onto the cancel button to hide the form - this.container.one('#addcancel').on('click', this.cancel_popup, this); + thisevent = this.container.one('#addcancel').on('click', this.cancel_popup, this); + this.listenevents.push(thisevent); + thisevent = bb.one('div.closebutton').on('click', this.cancel_popup, this); + this.listenevents.push(thisevent); // Grab global keyup events and handle them - Y.one('document').on('keyup', this.handle_key_press, this); + thisevent = Y.one('document').on('keyup', this.handle_key_press, this); + this.listenevents.push(thisevent); // Add references to various elements we adjust this.jumplink = this.container.one('#jump'); From 42642f6c35a3808fad91160a0733012101a12cc5 Mon Sep 17 00:00:00 2001 From: Darko Miletic Date: Thu, 14 Jun 2012 12:34:10 -0300 Subject: [PATCH 016/130] MDL-33523: for for missing image (the folder.gif is no longer available) --- backup/cc/entities.class.php | 4 ++-- backup/cc/entities11.class.php | 6 +++--- backup/cc/entity.label.class.php | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/backup/cc/entities.class.php b/backup/cc/entities.class.php index 625d390bc3b..e0737fdca11 100644 --- a/backup/cc/entities.class.php +++ b/backup/cc/entities.class.php @@ -262,14 +262,14 @@ class entities { if (!empty($labels) && ($labels->length > 0)) { $tname = 'course_files'; $dpath = cc2moodle::$path_to_manifest_folder . DIRECTORY_SEPARATOR . $tname; - $rfpath = 'folder.gif'; + $rfpath = 'files.gif'; $fpath = $dpath . DIRECTORY_SEPARATOR . $rfpath; if (!file_exists($dpath)) { mkdir($dpath); } //copy the folder.gif file - $folder_gif = "{$CFG->dirroot}/pix/f/folder.gif"; + $folder_gif = "{$CFG->dirroot}/pix/i/files.gif"; copy($folder_gif, $fpath); $all_files[] = $rfpath; } diff --git a/backup/cc/entities11.class.php b/backup/cc/entities11.class.php index 9af9f3c89c0..e9873da72a6 100644 --- a/backup/cc/entities11.class.php +++ b/backup/cc/entities11.class.php @@ -62,13 +62,13 @@ class entities11 extends entities { if (!empty($labels) && ($labels->length > 0)) { $tname = 'course_files'; $dpath = cc2moodle::$path_to_manifest_folder . DIRECTORY_SEPARATOR . $tname; - $rfpath = 'folder.gif'; - $fpath = $dpath . DIRECTORY_SEPARATOR . 'folder.gif'; + $rfpath = 'files.gif'; + $fpath = $dpath . DIRECTORY_SEPARATOR . 'files.gif'; if (!file_exists($dpath)) { mkdir($dpath); } //copy the folder.gif file - $folder_gif = "{$CFG->dirroot}/pix/f/folder.gif"; + $folder_gif = "{$CFG->dirroot}/pix/i/files.gif"; copy($folder_gif, $fpath); $all_files[] = $rfpath; } diff --git a/backup/cc/entity.label.class.php b/backup/cc/entity.label.class.php index 6c27bf2b27b..e8dfe82efcb 100644 --- a/backup/cc/entity.label.class.php +++ b/backup/cc/entity.label.class.php @@ -52,7 +52,7 @@ class cc_label extends entities { '[#date_now#]'); $title = isset($instance['title']) && !empty($instance['title']) ? $instance['title'] : 'Untitled'; - $content = "\"Folder\" {$title}"; + $content = "\"Folder\" {$title}"; $replace_values = array($instance['instance'], self::safexml($title), self::safexml($content), From 754794658047592e8dc663b9204eae3c19b0aed4 Mon Sep 17 00:00:00 2001 From: Darko Miletic Date: Thu, 14 Jun 2012 17:12:53 -0300 Subject: [PATCH 017/130] MDL-33523: Fixed item C of the issue --- backup/cc/cc2moodle.php | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/backup/cc/cc2moodle.php b/backup/cc/cc2moodle.php index 013d89123eb..05e8239f12d 100644 --- a/backup/cc/cc2moodle.php +++ b/backup/cc/cc2moodle.php @@ -620,15 +620,23 @@ class cc2moodle { $array_index++; if ($item->nodeName == "item") { + $identifierref = ''; + if ($item->hasAttribute('identifierref')) { + $identifierref = $item->getAttribute('identifierref'); + } - $identifierref = $xpath->query('@identifierref', $item); - $identifierref = !empty($identifierref->item(0)->nodeValue) ? $identifierref->item(0)->nodeValue : ''; - - $title = $xpath->query('imscc:title', $item); - $title = !empty($title->item(0)->nodeValue) ? $title->item(0)->nodeValue : ''; + $title = ''; + $titles = $xpath->query('imscc:title', $item); + if ($titles->length > 0) { + $title = $titles->item(0)->nodeValue; + } $cc_type = $this->get_item_cc_type($identifierref); $moodle_type = $this->convert_to_moodle_type($cc_type); + //Fix the label issue - MDL-33523 + if (empty($identifierref) && empty($title)) { + $moodle_type = TYPE_UNKNOWN; + } } elseif ($item->nodeName == "resource") { From 52474d74970993b59cc7d90b3b8722897d2845c3 Mon Sep 17 00:00:00 2001 From: Marina Glancy Date: Fri, 15 Jun 2012 14:48:02 +0800 Subject: [PATCH 018/130] MDL-33136 upload dnd files one after another --- lib/form/dndupload.js | 120 +++++++++++++++++++++++++++++++----------- 1 file changed, 89 insertions(+), 31 deletions(-) diff --git a/lib/form/dndupload.js b/lib/form/dndupload.js index 2e1514c9c3f..4cba3ec299a 100644 --- a/lib/form/dndupload.js +++ b/lib/form/dndupload.js @@ -30,6 +30,8 @@ M.form_dndupload.init = function(Y, options) { Y: null, // URL for upload requests url: M.cfg.wwwroot + '/repository/repository_ajax.php?action=upload', + // options may include: itemid, acceptedtypes, maxfiles, maxbytes, clientid, repositoryid, author + options: {}, // itemid used for repository upload itemid: null, // accepted filetypes accepted by this form passed to repository @@ -86,6 +88,7 @@ M.form_dndupload.init = function(Y, options) { return; // no upload repository is enabled to upload to } + this.options = options; this.acceptedtypes = options.acceptedtypes; this.clientid = options.clientid; this.maxfiles = options.maxfiles; @@ -301,19 +304,30 @@ M.form_dndupload.init = function(Y, options) { if (this.filemanager) { var currentfilecount = this.filemanager.filecount; if (((currentfilecount + files.length) > this.maxfiles) && (this.maxfiles != -1)) { - alert(M.util.get_string('maxfilesreached', 'moodle', this.maxfiles)); + // TODO in case of overwrite we don't need it! + alert(M.util.get_string('maxfilesreached', 'moodle', this.maxfiles)); // TODO change to YUI return false; } - this.show_progress_spinner(); - for (var i=0, f; f=files[i]; i++) { - if (this.upload_file(f)) { - currentfilecount++; - } - } + //this.show_progress_spinner(); + var options = { + files:files, + options: this.options, + repositoryid: this.repositoryid, + callback:this.callback ? Y.bind('callback', this) : Y.bind('update_filemanager', this) + }; + var uploader = new dnduploader(options); + uploader.doupload(); } else { - this.show_progress_spinner(); + //this.show_progress_spinner(); if (files.length >= 1) { - this.upload_file(files[0]); + options = { + files:[files[0]], + options: this.options, + repositoryid: this.repositoryid, + callback:this.callback ? Y.bind('callback', this) : Y.bind('update_filemanager', this) + }; + uploader = new dnduploader(options); + uploader.doupload(); } } @@ -398,16 +412,56 @@ M.form_dndupload.init = function(Y, options) { // update the filemanager that we've uploaded the files this.filemanager.filepicker_callback(); } + } + }; + + var dnduploader = function(options) { + dnduploader.superclass.constructor.apply(this, arguments); + }; + + Y.extend(dnduploader, Y.Base, { + api: M.cfg.wwwroot+'/repository/repository_ajax.php', + options: {}, + callback: null, + files: null, + repositoryid: 0, + processedfiles: 0, + + initializer: function(params) { + this.options = params.options; + this.repositoryid = params.repositoryid; + this.callback = params.callback; + this.files = params.files; // TODO make copy? + }, + + doupload: function(lastresult) { + console.log('doupload : '+this.processedfiles); + if (this.files && this.files.length > this.processedfiles) { + console.log('uploading file'); + console.log(this.files[this.processedfiles]) + this.upload_file(this.files[this.processedfiles]); + } else { + this.uploadfinished(lastresult); + } + }, + + uploadfinished: function(lastresult) { + console.log('upload finished') + this.callback(lastresult); + }, + + add_error: function(text, errorlevel) { + // TODO + console.log(text); }, /** * Upload a single file via an AJAX call to the 'upload' repository */ upload_file: function(file) { - if (file.size > this.maxbytes && this.maxbytes > 0) { + if (this.options.maxbytes > 0 && file.size > this.options.maxbytes) { // Check filesize before attempting to upload - this.hide_progress_spinner(); - alert(M.util.get_string('uploadformlimit', 'moodle')+"\n'"+file.name+"'"); + this.add_error(M.util.get_string('uploadformlimit', 'moodle')+"\n'"+file.name+"'"); //TODO proper string return false; } @@ -421,13 +475,14 @@ M.form_dndupload.init = function(Y, options) { var self = this; xhr.onreadystatechange = function() { // Process the server response if (xhr.readyState == 4) { - self.hide_progress_spinner(); if (xhr.status == 200) { + console.log(xhr.responseText) var result = JSON.parse(xhr.responseText); if (result) { + console.log(result) if (result.error) { - alert(result.error); - } else if (self.callback) { + self.add_error(result.error); // TODO add filename? + } else { // Only update the filepicker if there were no errors if (result.event == 'fileexists') { // Do not worry about this, as we only care about the last @@ -435,45 +490,48 @@ M.form_dndupload.init = function(Y, options) { result.file = result.newfile.filename; result.url = result.newfile.url; } - result.client_id = self.clientid; - self.callback(result); - } else { - self.update_filemanager(); + result.client_id = self.options.clientid; } } + self.processedfiles++; + self.doupload(result); // continue uploading } else { - alert(M.util.get_string('serverconnection', 'error')); + self.add_error(M.util.get_string('serverconnection', 'error')); + this.uploadfinished(); } } }; // Prepare the data to send var formdata = new FormData(); + formdata.append('action', 'upload'); formdata.append('repo_upload_file', file); // The FormData class allows us to attach a file formdata.append('sesskey', M.cfg.sesskey); formdata.append('repo_id', this.repositoryid); - formdata.append('itemid', this.itemid); - if (this.author) { - formdata.append('author', this.author); + formdata.append('itemid', this.options.itemid); + if (this.options.author) { + formdata.append('author', this.options.author); } - if (this.filemanager) { // Filepickers do not have folders - formdata.append('savepath', this.filemanager.currentpath); + if (this.options.filemanager) { // Filepickers do not have folders + formdata.append('savepath', this.options.filemanager.currentpath); } - if (this.acceptedtypes.constructor == Array) { - for (var i=0; i Date: Sat, 2 Jun 2012 02:42:55 +0100 Subject: [PATCH 019/130] MDL-32479 theme_base: some RTL fixes for Moodle 2.3 --- theme/base/layout/frontpage.php | 35 ++++++++++++++++++++++++-------- theme/base/layout/general.php | 36 +++++++++++++++++++++++++-------- theme/base/layout/report.php | 4 ++-- theme/base/style/blocks.css | 2 +- theme/base/style/core.css | 14 +++++++++---- theme/base/style/course.css | 11 +++++++--- theme/base/style/dock.css | 9 ++++++++- theme/base/style/user.css | 2 ++ 8 files changed, 86 insertions(+), 27 deletions(-) diff --git a/theme/base/layout/frontpage.php b/theme/base/layout/frontpage.php index 8a02304930e..bae039850f0 100644 --- a/theme/base/layout/frontpage.php +++ b/theme/base/layout/frontpage.php @@ -10,14 +10,22 @@ $hascustommenu = (empty($PAGE->layout_options['nocustommenu']) && !empty($custom $bodyclasses = array(); if ($showsidepre && !$showsidepost) { - $bodyclasses[] = 'side-pre-only'; + if (!right_to_left()) { + $bodyclasses[] = 'side-pre-only'; + }else{ + $bodyclasses[] = 'side-post-only'; + } } else if ($showsidepost && !$showsidepre) { - $bodyclasses[] = 'side-post-only'; + if (!right_to_left()) { + $bodyclasses[] = 'side-post-only'; + }else{ + $bodyclasses[] = 'side-pre-only'; + } } else if (!$showsidepost && !$showsidepre) { $bodyclasses[] = 'content-only'; } if ($hascustommenu) { - $bodyclasses[] = 'has_custom_menu'; + $bodyclasses[] = 'has-custom-menu'; } echo $OUTPUT->doctype() ?> @@ -58,18 +66,29 @@ echo $OUTPUT->doctype() ?>
        - +
        - blocks_for_region('side-pre') ?> + blocks_for_region('side-pre'); + } elseif ($hassidepost) { + echo $OUTPUT->blocks_for_region('side-post'); + } ?> +
        - +
        - blocks_for_region('side-post') ?> + blocks_for_region('side-post'); + } elseif ($hassidepre) { + echo $OUTPUT->blocks_for_region('side-pre'); + } ?>
        @@ -94,4 +113,4 @@ echo $OUTPUT->doctype() ?>
        standard_end_of_body_html() ?> - \ No newline at end of file + diff --git a/theme/base/layout/general.php b/theme/base/layout/general.php index afb9cfca411..65751412091 100644 --- a/theme/base/layout/general.php +++ b/theme/base/layout/general.php @@ -15,14 +15,22 @@ $hascustommenu = (empty($PAGE->layout_options['nocustommenu']) && !empty($custom $bodyclasses = array(); if ($showsidepre && !$showsidepost) { - $bodyclasses[] = 'side-pre-only'; + if (!right_to_left()) { + $bodyclasses[] = 'side-pre-only'; + }else{ + $bodyclasses[] = 'side-post-only'; + } } else if ($showsidepost && !$showsidepre) { - $bodyclasses[] = 'side-post-only'; + if (!right_to_left()) { + $bodyclasses[] = 'side-post-only'; + }else{ + $bodyclasses[] = 'side-pre-only'; + } } else if (!$showsidepost && !$showsidepre) { $bodyclasses[] = 'content-only'; } if ($hascustommenu) { - $bodyclasses[] = 'has_custom_menu'; + $bodyclasses[] = 'has-custom-menu'; } echo $OUTPUT->doctype() ?> @@ -73,21 +81,33 @@ echo $OUTPUT->doctype() ?>
        - +
        - blocks_for_region('side-pre') ?> + blocks_for_region('side-pre'); + } elseif ($hassidepost) { + echo $OUTPUT->blocks_for_region('side-post'); + } ?> +
        - +
        - blocks_for_region('side-post') ?> + blocks_for_region('side-post'); + } elseif ($hassidepre) { + echo $OUTPUT->blocks_for_region('side-pre'); + } ?>
        +
        @@ -107,4 +127,4 @@ echo $OUTPUT->doctype() ?> standard_end_of_body_html() ?> - \ No newline at end of file + diff --git a/theme/base/layout/report.php b/theme/base/layout/report.php index 46929179880..905c1b0d20f 100644 --- a/theme/base/layout/report.php +++ b/theme/base/layout/report.php @@ -16,7 +16,7 @@ if (!$showsidepre) { $bodyclasses[] = 'content-only'; } if ($hascustommenu) { - $bodyclasses[] = 'has_custom_menu'; + $bodyclasses[] = 'has-custom-menu'; } echo $OUTPUT->doctype() ?> @@ -87,4 +87,4 @@ echo $OUTPUT->doctype() ?> standard_end_of_body_html() ?> - \ No newline at end of file + diff --git a/theme/base/style/blocks.css b/theme/base/style/blocks.css index 512f2c06cf8..9fca8f98c9c 100644 --- a/theme/base/style/blocks.css +++ b/theme/base/style/blocks.css @@ -1,6 +1,6 @@ .block {border:1px solid;margin-bottom:1em;} .block .header h2 {margin:4px;} -.block .header .block_action {float:right;margin:0 4px;vertical-align:top;} +.block .header .block_action {float:right;margin:2px 4px 0;vertical-align:top;} .block .header .block_action input {margin-right:2px;} .block .header .commands {margin-left:4px;} .block .header .commands .icon img {width:11px;height:11px;margin-right:1px;} diff --git a/theme/base/style/core.css b/theme/base/style/core.css index 67922dd8ac8..813f353634f 100644 --- a/theme/base/style/core.css +++ b/theme/base/style/core.css @@ -210,7 +210,7 @@ a.skip:active {position: static;display: block;} .mform .fitem .fitemtitle {width:15%;text-align:right;float:left;} .mform .fitem .fitemtitle div {display: inline;} .mform .fitem .felement {border-width: 0;width:80%;margin-left:16%;} -.mform .fitem fieldset.felement {margin-left:15%;padding-left:1%;margin-bottom:0} +.mform .fitem fieldset.felement {margin-left:0;padding-left:1%;margin-bottom:0} .mform .error, .mform .required {color:#A00;} .mform .required .fgroup span label {color:#000;} @@ -661,7 +661,7 @@ body.tag .managelink {padding: 5px;} .dir-rtl .mod-indent-huge {margin-right:300px;margin-left:0;} .dir-rtl .felement.feditor select {margin-right:18.75%;margin-left:auto;} -.dir-rtl .mform .fitem .felement {margin-right: 16%;margin-left:auto;} +.dir-rtl .mform .fitem .felement {margin-right: 16%;margin-left:auto;text-align: right;} /* Audio player size in 'block' mode (can only change width, height is hardcoded in JS) */ .resourcecontent .mediaplugin_mp3 object {height:25px; width: 600px} @@ -723,8 +723,8 @@ sup {vertical-align: super;} .dir-rtl .ygtvcancel {background-position: 0 -8822px;} .dir-rtl .ygtvcancel:hover {background-position: 0 -8866px;} -.dir-rtl #yui-gen4.yui-layout-unit-left {left:500px !important;} -.dir-rtl #yui-gen6.yui-layout-unit-center {left:0px !important;} +.dir-rtl .file-picker .yui-layout-unit-left {left:500px !important;} +.dir-rtl .file-picker .yui-layout-unit-center {left:0px !important;} .dir-rtl.yui-skin-sam .yui-panel .hd {text-align:left;} .dir-rtl .yui-skin-sam .yui-layout .yui-layout-unit div.yui-layout-bd {text-align:right;} @@ -805,6 +805,11 @@ sup {vertical-align: super;} #page-admin-setting-enrolsettingsflatfile.dir-rtl .informationbox {direction: ltr;text-align: left;} #page-admin-grade-edit-scale-edit.dir-rtl .error input#id_name {margin-right: 170px;} +.initialbar a {padding-right: 2px;} + +/* Invert alignment of all hard coded table cell internal alignment, when in RTL mode */ +.dir-rtl td[align="left"] {text-align: right;} +.dir-rtl td[align="right"] {text-align: left;} /** * Chooser Dialogue @@ -955,3 +960,4 @@ sup {vertical-align: super;} -moz-box-shadow: 0px 0px 10px 0px #CCCCCC; } +#yui-module-debug {display:none;} diff --git a/theme/base/style/course.css b/theme/base/style/course.css index aeabb0bc635..77ba42f8888 100644 --- a/theme/base/style/course.css +++ b/theme/base/style/course.css @@ -42,9 +42,10 @@ .path-course-view li.activity form.togglecompletion {display:inline;position:absolute;right:-20px;top:0;padding:0.2em 0;} .path-course-view li.activity form.togglecompletion div {display:inline;} .path-course-view li.activity form.togglecompletion .ajaxworking {position:absolute;top:0; left:20px;width: 20px; height: 20px;background: url([[pix:i/ajaxloader]]) no-repeat;} -.dir-rtl.path-course-view li.activity {margin-right:0px;margin-left:20px;} +.dir-rtl.path-course-view li.activity {margin-right:20px;margin-left:20px;} .dir-rtl.path-course-view li.activity form.togglecompletion, -.dir-rtl.path-course-view li.activity span.autocompletion {right:auto;left:-20px;} +.dir-rtl.path-course-view li.activity span.autocompletion {right:-20px;left:auto;padding:0px;} +.dir-rtl.path-course-view .completionprogress {float: none;} .section img.movetarget {height:16px;width:80px;} @@ -106,6 +107,9 @@ .course_category_tree .category .courses .course_link {display:block;background-image:url([[pix:moodle|i/course]]);background-repeat: no-repeat;padding-left:18px;} .course_category_tree .category .course {position:relative;} .course_category_tree .category .course_info {position:absolute;right:0;top:0;} +.dir-rtl .course_category_tree .category .course_info { position: static; } +.dir-rtl .course_category_tree .category .course_info a, .dir-rtl .course_category_tree .category .course_info div {float: right;} +.dir-rtl .course_category_tree .controls div {padding: 7px;} .course_category_tree .category .course_info a, .course_category_tree .category .course_info div {float:left;width:16px;height:16px;} .jsenabled .course_category_tree .controls {visibility: visible;} @@ -144,7 +148,8 @@ table.category_subcategories {margin-bottom:1em;} table.category_subcategories td {white-space: nowrap;} -span.editinstructions { +.dir-rtl.path-course-view li.activity form.togglecompletion, +.dir-rtl.path-course-view li.activity span.autocompletion span.editinstructions { position: relative; top: 5px; left: 19px; diff --git a/theme/base/style/dock.css b/theme/base/style/dock.css index 30acfef1b28..97f866016e5 100644 --- a/theme/base/style/dock.css +++ b/theme/base/style/dock.css @@ -32,4 +32,11 @@ body.has_dock {margin-left:30px;} .ie6 #dockeditempanel {position:absolute;} /** Overide for RTL layout **/ -.dir-rtl #dockeditempanel {left:670%;} \ No newline at end of file +.dir-rtl #dockeditempanel {left:670%;} + +/* right align the DOCK panel +------------------------------*/ +.dir-rtl #dockeditempanel {right: 100%;} +.dir-rtl #dock {left:auto;right: 0%; border-left: 1px solid #DDD;} +.dir-rtl #dock .dockedtitle { border-bottom: 1px solid #DDD;border-top: 1px solid #EEE; cursor: pointer;} +body.dir-rtl.has_dock {margin-left: 0px; margin-right: 30px} \ No newline at end of file diff --git a/theme/base/style/user.css b/theme/base/style/user.css index 8276b71ffe6..b23d73417b3 100644 --- a/theme/base/style/user.css +++ b/theme/base/style/user.css @@ -54,3 +54,5 @@ .dir-rtl .userlist table#participants td, .dir-rtl .userlist table#participants th {text-align: right;} .dir-rtl .userlist table#participants {margin: 0 auto;} + +#page-my-index.dir-rtl .block h3.main { text-align: right;} From 7f3b68a89287bd8c17e30bdcce03c8ec5dae093b Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Sat, 16 Jun 2012 12:35:15 +0800 Subject: [PATCH 020/130] MDL-33294 - block_blog_tags: fix E_STRICT error Default object from empty value --- blocks/blog_tags/block_blog_tags.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/blocks/blog_tags/block_blog_tags.php b/blocks/blog_tags/block_blog_tags.php index c3fa8d8f2d7..c84f9d2e02f 100644 --- a/blocks/blog_tags/block_blog_tags.php +++ b/blocks/blog_tags/block_blog_tags.php @@ -93,6 +93,10 @@ class block_blog_tags extends block_base { // require the libs and do the work require_once($CFG->dirroot .'/blog/lib.php'); + if (empty($this->config)) { + $this->config = new stdClass(); + } + if (empty($this->config->timewithin)) { $this->config->timewithin = BLOCK_BLOG_TAGS_DEFAULTTIMEWITHIN; } From 15ea1c9105908b2019f51f74f7113ecd97505bcf Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Sat, 16 Jun 2012 12:46:07 +0800 Subject: [PATCH 021/130] MDL-33294 - block_blog_recent: fix E_STRICT error Default object from empty value --- blocks/blog_recent/block_blog_recent.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/blocks/blog_recent/block_blog_recent.php b/blocks/blog_recent/block_blog_recent.php index 20313b626a0..b3d564fde7f 100644 --- a/blocks/blog_recent/block_blog_recent.php +++ b/blocks/blog_recent/block_blog_recent.php @@ -69,6 +69,10 @@ class block_blog_recent extends block_base { require_once($CFG->dirroot .'/blog/lib.php'); require_once($CFG->dirroot .'/blog/locallib.php'); + if (empty($this->config)) { + $this->config = new stdClass(); + } + if (empty($this->config->recentbloginterval)) { $this->config->recentbloginterval = 8400; } From dd4502af6bedab6627404a46005856fe267618aa Mon Sep 17 00:00:00 2001 From: Dan Poltawski Date: Sat, 16 Jun 2012 14:12:51 +0800 Subject: [PATCH 022/130] MDL-3971 - mod_forum: contain () in span --- mod/forum/post.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mod/forum/post.php b/mod/forum/post.php index 7e864e51845..15a386d689d 100644 --- a/mod/forum/post.php +++ b/mod/forum/post.php @@ -520,7 +520,7 @@ if ($USER->id != $post->userid) { // Not the original author, so add a message if ($post->messageformat == FORMAT_HTML) { $data->name = ''. fullname($USER).''; - $post->message .= '

        ('.get_string('editedby', 'forum', $data).')

        '; + $post->message .= '

        ('.get_string('editedby', 'forum', $data).')

        '; } else { $data->name = fullname($USER); $post->message .= "\n\n(".get_string('editedby', 'forum', $data).')'; From 00902cd9745417163e7fc7a59703bb6d92255daf Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Tue, 5 Jun 2012 10:31:03 +0200 Subject: [PATCH 023/130] MDL-32003 fix phpdocs and use __DIR__ for includes in dml layer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DML layer is not supposed to use $CFG, it is better to rely on __DIR__ in self-contained libs… --- lib/dml/database_column_info.php | 13 ++--- lib/dml/moodle_database.php | 43 ++++++-------- lib/dml/moodle_recordset.php | 6 +- lib/dml/moodle_temptables.php | 5 +- lib/dml/moodle_transaction.php | 12 +--- lib/dml/mssql_native_moodle_database.php | 26 +++------ lib/dml/mssql_native_moodle_recordset.php | 8 +-- lib/dml/mssql_native_moodle_temptables.php | 7 +-- lib/dml/mysqli_native_moodle_database.php | 24 +++----- lib/dml/mysqli_native_moodle_recordset.php | 9 +-- lib/dml/mysqli_native_moodle_temptables.php | 8 +-- lib/dml/oci_native_moodle_database.php | 31 ++++------ lib/dml/oci_native_moodle_package.sql | 3 +- lib/dml/oci_native_moodle_recordset.php | 9 +-- lib/dml/oci_native_moodle_temptables.php | 14 ++--- lib/dml/pdo_moodle_database.php | 14 ++--- lib/dml/pdo_moodle_recordset.php | 12 ++-- lib/dml/pgsql_native_moodle_database.php | 24 +++----- lib/dml/pgsql_native_moodle_recordset.php | 12 ++-- lib/dml/pgsql_native_moodle_temptables.php | 6 +- lib/dml/sqlite3_pdo_moodle_database.php | 10 +--- lib/dml/sqlsrv_native_moodle_database.php | 64 +++++++++------------ lib/dml/sqlsrv_native_moodle_recordset.php | 8 +-- lib/dml/sqlsrv_native_moodle_temptables.php | 11 ++-- lib/dml/tests/dml_test.php | 31 +++++----- 25 files changed, 150 insertions(+), 260 deletions(-) diff --git a/lib/dml/database_column_info.php b/lib/dml/database_column_info.php index b6198838689..4aee79aa35e 100644 --- a/lib/dml/database_column_info.php +++ b/lib/dml/database_column_info.php @@ -1,5 +1,4 @@ . - /** * Database column information. * - * @package core - * @category dml - * @subpackage dml + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -34,10 +30,9 @@ defined('MOODLE_INTERNAL') || die(); * It is based on the adodb library's ADOFieldObject object. * 'column' does mean 'the field' here. * - * @package core - * @category dml - * @copyright 2008 Petr Skoda (http://skodak.org) - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @package core_dml + * @copyright 2008 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class database_column_info { /** diff --git a/lib/dml/moodle_database.php b/lib/dml/moodle_database.php index faf097e074c..48a992c73eb 100644 --- a/lib/dml/moodle_database.php +++ b/lib/dml/moodle_database.php @@ -14,24 +14,19 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . - /** * Abstract database driver class. * - * @package core - * @category dml - * @subpackage dml - * @copyright 2008 Petr Skoda (http://skodak.org) - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @package core_dml + * @copyright 2008 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/database_column_info.php'); -require_once($CFG->libdir.'/dml/moodle_recordset.php'); -require_once($CFG->libdir.'/dml/moodle_transaction.php'); - -/// GLOBAL CONSTANTS ///////////////////////////////////////////////////////// +require_once(__DIR__.'/database_column_info.php'); +require_once(__DIR__.'/moodle_recordset.php'); +require_once(__DIR__.'/moodle_transaction.php'); /** SQL_PARAMS_NAMED - Bitmask, indicates :name type parameters are supported by db backend. */ define('SQL_PARAMS_NAMED', 1); @@ -61,8 +56,7 @@ define('SQL_QUERY_AUX', 5); * Abstract class representing moodle database interface. * @link http://docs.moodle.org/dev/DML_functions * - * @package core - * @category dml + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -89,7 +83,7 @@ abstract class moodle_database { /** @var string Prefix added to table names. */ protected $prefix; - /** @var array Database or driver specific options, such as sockets or TCPIP db connections. */ + /** @var array Database or driver specific options, such as sockets or TCP/IP db connections. */ protected $dboptions; /** @var bool True means non-moodle external database used.*/ @@ -324,7 +318,7 @@ abstract class moodle_database { $backtrace = $lowesttransaction->get_backtrace(); if (defined('PHPUNIT_TEST') and PHPUNIT_TEST) { - //no need to log sudden exits in our PHPunit test cases + //no need to log sudden exits in our PHPUnit test cases } else { error_log('Potential coding error - active database transaction detected when disposing database:'."\n".format_backtrace($backtrace, true)); } @@ -422,7 +416,7 @@ abstract class moodle_database { /** * This logs the last query based on 'logall', 'logslow' and 'logerrors' options configured via $CFG->dboptions . - * @param string $error or false if not error + * @param string|bool $error or false if not error * @return void */ public function query_log($error=false) { @@ -463,7 +457,7 @@ abstract class moodle_database { /** * Returns database server info array - * @return array Array containing 'description' and 'version' atleast. + * @return array Array containing 'description' and 'version' at least. */ public abstract function get_server_info(); @@ -687,6 +681,7 @@ abstract class moodle_database { * Internal private utitlity function used to fix parameters. * Used with {@link preg_replace_callback()} * @param array $match Refer to preg_replace_callback usage for description. + * @return string */ private function _fix_sql_params_dollar_callback($match) { $this->fix_sql_params_i++; @@ -697,6 +692,7 @@ abstract class moodle_database { * Detects object parameters and throws exception if found * @param mixed $value * @return void + * @throws coding_exception if object detected */ protected function detect_objects($value) { if (is_object($value)) { @@ -723,7 +719,7 @@ abstract class moodle_database { $params[$key] = is_bool($value) ? (int)$value : $value; } - // NICOLAS C: Fixed regexp for negative backwards lookahead of double colons. Thanks for Sam Marshall's help + // NICOLAS C: Fixed regexp for negative backwards look-ahead of double colons. Thanks for Sam Marshall's help $named_count = preg_match_all('/(?is_transaction_started()) { @@ -2232,7 +2223,6 @@ abstract class moodle_database { $this->force_rollback = false; } -// session locking /** * Is session lock supported in this driver? * @return bool @@ -2261,7 +2251,6 @@ abstract class moodle_database { public function release_session_lock($rowid) { } -// performance and logging /** * Returns the number of reads done by this database. * @return int Number of reads. diff --git a/lib/dml/moodle_recordset.php b/lib/dml/moodle_recordset.php index d1e7005120a..975b253d79e 100644 --- a/lib/dml/moodle_recordset.php +++ b/lib/dml/moodle_recordset.php @@ -1,5 +1,4 @@ . - /** * Abstract recordset. * - * @package core - * @category dml - * @subpackage dml + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ diff --git a/lib/dml/moodle_temptables.php b/lib/dml/moodle_temptables.php index c89348ae1da..19f0c20ce78 100644 --- a/lib/dml/moodle_temptables.php +++ b/lib/dml/moodle_temptables.php @@ -1,5 +1,4 @@ . - /** * Delegated database transaction support. * - * @package core - * @category dml - * @subpackage dml + * @package core_dml * @copyright 2009 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -31,9 +27,7 @@ defined('MOODLE_INTERNAL') || die(); /** * Delegated transaction class. * - * @package core - * @category dml - * @subpackage dml + * @package core_dml * @copyright 2009 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -110,4 +104,4 @@ class moodle_transaction { } $this->database->rollback_delegated_transaction($this, $e); } -} \ No newline at end of file +} diff --git a/lib/dml/mssql_native_moodle_database.php b/lib/dml/mssql_native_moodle_database.php index 5ae728e86c6..7d134d2fc61 100644 --- a/lib/dml/mssql_native_moodle_database.php +++ b/lib/dml/mssql_native_moodle_database.php @@ -1,5 +1,4 @@ . - /** * Native mssql class representing moodle database interface. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_database.php'); -require_once($CFG->libdir.'/dml/mssql_native_moodle_recordset.php'); -require_once($CFG->libdir.'/dml/mssql_native_moodle_temptables.php'); +require_once(__DIR__.'/moodle_database.php'); +require_once(__DIR__.'/mssql_native_moodle_recordset.php'); +require_once(__DIR__.'/mssql_native_moodle_temptables.php'); /** * Native mssql class representing moodle database interface. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -515,7 +511,7 @@ class mssql_native_moodle_database extends moodle_database { protected function normalise_value($column, $value) { $this->detect_objects($value); - if (is_bool($value)) { /// Always, convert boolean to int + if (is_bool($value)) { // Always, convert boolean to int $value = (int)$value; } // And continue processing because text columns with numeric info need special handling below @@ -619,7 +615,7 @@ class mssql_native_moodle_database extends moodle_database { if (empty($params)) { return $sql; } - /// ok, we have verified sql statement with ? and correct number of params + // ok, we have verified sql statement with ? and correct number of params $parts = explode('?', $sql); $return = array_shift($parts); foreach ($params as $param) { @@ -1039,7 +1035,7 @@ class mssql_native_moodle_database extends moodle_database { // convert params to ? types list($select, $params, $type) = $this->fix_sql_params($select, $params); - /// Get column metadata + // Get column metadata $columns = $this->get_columns($table); $column = $columns[$newfield]; @@ -1094,8 +1090,6 @@ class mssql_native_moodle_database extends moodle_database { return true; } -/// SQL helper functions - public function sql_cast_char2int($fieldname, $text=false) { if (!$text) { return ' CAST(' . $fieldname . ' AS INT) '; @@ -1251,8 +1245,6 @@ s only returning name of SQL substring function, it now requires all parameters. } } -/// session locking - public function session_lock_supported() { return true; } @@ -1315,8 +1307,6 @@ s only returning name of SQL substring function, it now requires all parameters. $this->free_result($result); } -/// transactions - /** * Driver specific start of real database transaction, * this can not be used directly in code. diff --git a/lib/dml/mssql_native_moodle_recordset.php b/lib/dml/mssql_native_moodle_recordset.php index d383d31860b..2c7b7110fbd 100644 --- a/lib/dml/mssql_native_moodle_recordset.php +++ b/lib/dml/mssql_native_moodle_recordset.php @@ -1,5 +1,4 @@ libdir.'/dml/moodle_recordset.php'); +require_once(__DIR__.'/moodle_recordset.php'); class mssql_native_moodle_recordset extends moodle_recordset { @@ -54,7 +52,7 @@ class mssql_native_moodle_recordset extends moodle_recordset { } public function key() { - /// return first column value as key + // return first column value as key if (!$this->current) { return false; } diff --git a/lib/dml/mssql_native_moodle_temptables.php b/lib/dml/mssql_native_moodle_temptables.php index 9242059978b..df04cca1d03 100644 --- a/lib/dml/mssql_native_moodle_temptables.php +++ b/lib/dml/mssql_native_moodle_temptables.php @@ -1,5 +1,4 @@ libdir.'/dml/moodle_temptables.php'); +require_once(__DIR__.'/moodle_temptables.php'); class mssql_native_moodle_temptables extends moodle_temptables { @@ -50,5 +48,4 @@ class mssql_native_moodle_temptables extends moodle_temptables { // TODO: throw exception if exists: if ($this->is_temptable... $this->temptables[$tablename] = '#' . $this->prefix . $tablename; } - } diff --git a/lib/dml/mysqli_native_moodle_database.php b/lib/dml/mysqli_native_moodle_database.php index 535eca61fe8..93311bd5fd4 100644 --- a/lib/dml/mysqli_native_moodle_database.php +++ b/lib/dml/mysqli_native_moodle_database.php @@ -1,5 +1,4 @@ . - /** * Native mysqli class representing moodle database interface. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_database.php'); -require_once($CFG->libdir.'/dml/mysqli_native_moodle_recordset.php'); -require_once($CFG->libdir.'/dml/mysqli_native_moodle_temptables.php'); +require_once(__DIR__.'/moodle_database.php'); +require_once(__DIR__.'/mysqli_native_moodle_recordset.php'); +require_once(__DIR__.'/mysqli_native_moodle_temptables.php'); /** * Native mysqli class representing moodle database interface. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -77,7 +73,7 @@ class mysqli_native_moodle_database extends moodle_database { $dbport = 3306; } ob_start(); - $conn = new mysqli($dbhost, $dbuser, $dbpass, '', $dbport, $dbsocket); /// Connect without db + $conn = new mysqli($dbhost, $dbuser, $dbpass, '', $dbport, $dbsocket); // Connect without db $dberr = ob_get_contents(); ob_end_clean(); $errorno = @$conn->connect_errno; @@ -324,7 +320,7 @@ class mysqli_native_moodle_database extends moodle_database { $this->query_end($result); } - // Connection stabilished and configured, going to instantiate the temptables controller + // Connection stabilised and configured, going to instantiate the temptables controller $this->temptables = new mysqli_native_moodle_temptables($this); return true; @@ -736,7 +732,7 @@ class mysqli_native_moodle_database extends moodle_database { if (empty($params)) { return $sql; } - /// ok, we have verified sql statement with ? and correct number of params + // ok, we have verified sql statement with ? and correct number of params $parts = explode('?', $sql); $return = array_shift($parts); foreach ($params as $param) { @@ -1264,7 +1260,6 @@ class mysqli_native_moodle_database extends moodle_database { return ' CAST(' . $fieldname . ' AS SIGNED) '; } -/// session locking public function session_lock_supported() { return true; } @@ -1273,7 +1268,7 @@ class mysqli_native_moodle_database extends moodle_database { * Obtain session lock * @param int $rowid id of the row with session record * @param int $timeout max allowed time to wait for the lock in seconds - * @return bool success + * @return void */ public function get_session_lock($rowid, $timeout) { parent::get_session_lock($rowid, $timeout); @@ -1309,7 +1304,6 @@ class mysqli_native_moodle_database extends moodle_database { } } -/// transactions /** * Are transactions supported? * It is not responsible to run productions servers diff --git a/lib/dml/mysqli_native_moodle_recordset.php b/lib/dml/mysqli_native_moodle_recordset.php index e8dc5bce994..230ef8c6edc 100644 --- a/lib/dml/mysqli_native_moodle_recordset.php +++ b/lib/dml/mysqli_native_moodle_recordset.php @@ -1,5 +1,4 @@ . - /** * Mysqli specific recordset. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_recordset.php'); +require_once(__DIR__.'/moodle_recordset.php'); /** * Mysqli specific moodle recordset class @@ -63,7 +60,7 @@ class mysqli_native_moodle_recordset extends moodle_recordset { } public function key() { - /// return first column value as key + // return first column value as key if (!$this->current) { return false; } diff --git a/lib/dml/mysqli_native_moodle_temptables.php b/lib/dml/mysqli_native_moodle_temptables.php index 0ad5132328f..4d777be009b 100644 --- a/lib/dml/mysqli_native_moodle_temptables.php +++ b/lib/dml/mysqli_native_moodle_temptables.php @@ -1,5 +1,4 @@ libdir.'/dml/moodle_temptables.php'); +require_once(__DIR__.'/moodle_temptables.php'); class mysqli_native_moodle_temptables extends moodle_temptables { - /// I love these classes :-P + // I love these classes :-P } diff --git a/lib/dml/oci_native_moodle_database.php b/lib/dml/oci_native_moodle_database.php index 08df721afd2..b62ac9baddc 100644 --- a/lib/dml/oci_native_moodle_database.php +++ b/lib/dml/oci_native_moodle_database.php @@ -1,5 +1,4 @@ . - /** * Native oci class representing moodle database interface. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_database.php'); -require_once($CFG->libdir.'/dml/oci_native_moodle_recordset.php'); -require_once($CFG->libdir.'/dml/oci_native_moodle_temptables.php'); +require_once(__DIR__.'/moodle_database.php'); +require_once(__DIR__.'/oci_native_moodle_recordset.php'); +require_once(__DIR__.'/oci_native_moodle_temptables.php'); /** * Native oci class representing moodle database interface. @@ -37,8 +34,7 @@ require_once($CFG->libdir.'/dml/oci_native_moodle_temptables.php'); * One complete reference for PHP + OCI: * http://www.oracle.com/technology/tech/php/underground-php-oracle-manual.html * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -809,7 +805,7 @@ class oci_native_moodle_database extends moodle_database { // of empties will need to use the sql_empty() and sql_isempty() helper functions. // MDL-17491. - // If the field ins't VARCHAR or CLOB, skip + // If the field isn't VARCHAR or CLOB, skip if ($column->meta_type != 'C' and $column->meta_type != 'X') { return $value; } @@ -835,7 +831,7 @@ class oci_native_moodle_database extends moodle_database { return '0'; // Transform 0 to '0' that evaluates the same for PHP } else if ($value === '') { - return ' '; // Transform '' to ' ' that DONT'T EVALUATE THE SAME + return ' '; // Transform '' to ' ' that DON'T EVALUATE THE SAME // (we'll transform back again on get_records_XXX functions and others)!! } @@ -1449,7 +1445,6 @@ class oci_native_moodle_database extends moodle_database { return ' FROM dual'; } -// Bitwise operations protected function bitwise_supported() { if (isset($this->bitwise_supported)) { // Use cached value if available return $this->bitwise_supported; @@ -1551,11 +1546,11 @@ class oci_native_moodle_database extends moodle_database { } } - // NOTE: Oracle concat implementation isn't ANSI compliant when using NULLs (the result of - // any concatenation with NULL must return NULL) because of his inability to differentiate - // NULLs and empty strings. So this function will cause some tests to fail. Hopefully - // it's only a side case and it won't affect normal concatenation operations in Moodle. public function sql_concat() { + // NOTE: Oracle concat implementation isn't ANSI compliant when using NULLs (the result of + // any concatenation with NULL must return NULL) because of his inability to differentiate + // NULLs and empty strings. So this function will cause some tests to fail. Hopefully + // it's only a side case and it won't affect normal concatenation operations in Moodle. $arr = func_get_args(); $s = implode(' || ', $arr); if ($s === '') { @@ -1604,7 +1599,6 @@ class oci_native_moodle_database extends moodle_database { return 'dbms_lob.substr(' . $fieldname . ', ' . $numchars . ',1)'; } -/// session locking public function session_lock_supported() { if (isset($this->dblocks_supported)) { // Use cached value if available return $this->dblocks_supported; @@ -1629,7 +1623,7 @@ class oci_native_moodle_database extends moodle_database { * Obtain session lock * @param int $rowid id of the row with session record * @param int $timeout max allowed time to wait for the lock in seconds - * @return bool success + * @return void */ public function get_session_lock($rowid, $timeout) { if (!$this->session_lock_supported()) { @@ -1668,7 +1662,6 @@ class oci_native_moodle_database extends moodle_database { oci_free_statement($stmt); } -/// transactions /** * Driver specific start of real database transaction, * this can not be used directly in code. diff --git a/lib/dml/oci_native_moodle_package.sql b/lib/dml/oci_native_moodle_package.sql index 042c6106645..2585f713d08 100644 --- a/lib/dml/oci_native_moodle_package.sql +++ b/lib/dml/oci_native_moodle_package.sql @@ -14,8 +14,7 @@ -- along with Moodle. If not, see . /** - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @version 20091010 (plz, keep this updated for easier reference) diff --git a/lib/dml/oci_native_moodle_recordset.php b/lib/dml/oci_native_moodle_recordset.php index 4d8694a54b1..e21e2310542 100644 --- a/lib/dml/oci_native_moodle_recordset.php +++ b/lib/dml/oci_native_moodle_recordset.php @@ -1,5 +1,4 @@ . - /** * Oracle specific recordset. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_recordset.php'); +require_once(__DIR__.'/moodle_recordset.php'); class oci_native_moodle_recordset extends moodle_recordset { @@ -57,7 +54,7 @@ class oci_native_moodle_recordset extends moodle_recordset { } public function key() { - /// return first column value as key + // return first column value as key if (!$this->current) { return false; } diff --git a/lib/dml/oci_native_moodle_temptables.php b/lib/dml/oci_native_moodle_temptables.php index 1343d06dfe6..3b7fd3f7dd5 100644 --- a/lib/dml/oci_native_moodle_temptables.php +++ b/lib/dml/oci_native_moodle_temptables.php @@ -1,5 +1,4 @@ libdir.'/dml/moodle_temptables.php'); +require_once(__DIR__.'/moodle_temptables.php'); class oci_native_moodle_temptables extends moodle_temptables { - protected $unique_session_id; // To store unique_session_id. Needed for temp tables unique naming (upto 24cc) - protected $counter; // To get incrementally different temptable names on each add_temptable() request + /** @var int To store unique_session_id. Needed for temp tables unique naming (upto 24cc) */ + protected $unique_session_id; // + /** @var int To get incrementally different temptable names on each add_temptable() request */ + protected $counter; /** * Creates new moodle_temptables instance @@ -50,7 +50,7 @@ class oci_native_moodle_temptables extends moodle_temptables { /** * Add one temptable to the store. * - * Overriden because OCI only support global temptables, so we need to change completely the name, based + * Overridden because OCI only support global temptables, so we need to change completely the name, based * in unique session identifier, to get local-like temp tables support * tables before the prefix. * diff --git a/lib/dml/pdo_moodle_database.php b/lib/dml/pdo_moodle_database.php index 8b090a49161..4aae9ce6ed6 100644 --- a/lib/dml/pdo_moodle_database.php +++ b/lib/dml/pdo_moodle_database.php @@ -1,5 +1,4 @@ . - /** * Experimental pdo database class * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_database.php'); -require_once($CFG->libdir.'/dml/pdo_moodle_recordset.php'); +require_once(__DIR__.'/moodle_database.php'); +require_once(__DIR__.'/pdo_moodle_recordset.php'); /** * Experimental pdo database class * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -102,7 +98,7 @@ abstract class pdo_moodle_database extends moodle_database { } protected function configure_dbconnection() { - ///TODO: not needed preconfigure_dbconnection() stuff for PDO drivers? + //TODO: not needed preconfigure_dbconnection() stuff for PDO drivers? } /** diff --git a/lib/dml/pdo_moodle_recordset.php b/lib/dml/pdo_moodle_recordset.php index 803416f590c..673d91f30b1 100644 --- a/lib/dml/pdo_moodle_recordset.php +++ b/lib/dml/pdo_moodle_recordset.php @@ -1,5 +1,4 @@ . - /** * Experimental pdo recordset * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_recordset.php'); +require_once(__DIR__.'/moodle_recordset.php'); /** * Experimental pdo recordset * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -64,7 +60,7 @@ class pdo_moodle_recordset extends moodle_recordset { } public function key() { - /// return first column value as key + // return first column value as key if (!$this->current) { return false; } diff --git a/lib/dml/pgsql_native_moodle_database.php b/lib/dml/pgsql_native_moodle_database.php index 57a007a9cd7..c883aed83e2 100644 --- a/lib/dml/pgsql_native_moodle_database.php +++ b/lib/dml/pgsql_native_moodle_database.php @@ -1,5 +1,4 @@ . - /** * Native pgsql class representing moodle database interface. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_database.php'); -require_once($CFG->libdir.'/dml/pgsql_native_moodle_recordset.php'); -require_once($CFG->libdir.'/dml/pgsql_native_moodle_temptables.php'); +require_once(__DIR__.'/moodle_database.php'); +require_once(__DIR__.'/pgsql_native_moodle_recordset.php'); +require_once(__DIR__.'/pgsql_native_moodle_temptables.php'); /** * Native pgsql class representing moodle database interface. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -566,7 +562,7 @@ class pgsql_native_moodle_database extends moodle_database { * @return bool */ public function setup_is_unicodedb() { - /// Get PostgreSQL server_encoding value + // Get PostgreSQL server_encoding value $sql = "SHOW server_encoding"; $this->query_start($sql, null, SQL_QUERY_AUX); $result = pg_query($this->pgsql, $sql); @@ -1044,13 +1040,13 @@ class pgsql_native_moodle_database extends moodle_database { list($select, $params, $type) = $this->fix_sql_params($select, $params); $i = count($params)+1; - /// Get column metadata + // Get column metadata $columns = $this->get_columns($table); $column = $columns[$newfield]; $normalised_value = $this->normalise_value($column, $newvalue); if (is_array($normalised_value) && array_key_exists('blob', $normalised_value)) { - /// Update BYTEA and return + // Update BYTEA and return $normalised_value = pg_escape_bytea($this->pgsql, $normalised_value['blob']); $sql = "UPDATE {$this->prefix}$table SET $newfield = '$normalised_value'::bytea $select"; $this->query_start($sql, NULL, SQL_QUERY_UPDATE); @@ -1152,7 +1148,7 @@ class pgsql_native_moodle_database extends moodle_database { return " '' "; } // Add always empty string element so integer-exclusive concats - // will work without needing to cast each element explicity + // will work without needing to cast each element explicitly return " '' || $s "; } @@ -1175,7 +1171,6 @@ class pgsql_native_moodle_database extends moodle_database { return $positivematch ? '~*' : '!~*'; } -/// session locking public function session_lock_supported() { return true; } @@ -1252,7 +1247,6 @@ class pgsql_native_moodle_database extends moodle_database { } } -/// transactions /** * Driver specific start of real database transaction, * this can not be used directly in code. diff --git a/lib/dml/pgsql_native_moodle_recordset.php b/lib/dml/pgsql_native_moodle_recordset.php index 6d00d157f56..76fe53ea01f 100644 --- a/lib/dml/pgsql_native_moodle_recordset.php +++ b/lib/dml/pgsql_native_moodle_recordset.php @@ -1,5 +1,4 @@ . - /** * Native postgresql recordset. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/moodle_recordset.php'); +require_once(__DIR__.'/moodle_recordset.php'); /** * pgsql specific moodle recordset class * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -82,7 +78,7 @@ class pgsql_native_moodle_recordset extends moodle_recordset { } public function key() { - /// return first column value as key + // return first column value as key if (!$this->current) { return false; } diff --git a/lib/dml/pgsql_native_moodle_temptables.php b/lib/dml/pgsql_native_moodle_temptables.php index 4227da15cf9..cd87ef2e27c 100644 --- a/lib/dml/pgsql_native_moodle_temptables.php +++ b/lib/dml/pgsql_native_moodle_temptables.php @@ -1,5 +1,4 @@ libdir.'/dml/moodle_temptables.php'); +require_once(__DIR__.'/moodle_temptables.php'); class pgsql_native_moodle_temptables extends moodle_temptables { // I love these classes :-P diff --git a/lib/dml/sqlite3_pdo_moodle_database.php b/lib/dml/sqlite3_pdo_moodle_database.php index c52b2f1916a..e7410a5d50d 100644 --- a/lib/dml/sqlite3_pdo_moodle_database.php +++ b/lib/dml/sqlite3_pdo_moodle_database.php @@ -1,5 +1,4 @@ . - /** * Experimental pdo database class. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); -require_once($CFG->libdir.'/dml/pdo_moodle_database.php'); +require_once(__DIR__.'/pdo_moodle_database.php'); /** * Experimental pdo database class * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ diff --git a/lib/dml/sqlsrv_native_moodle_database.php b/lib/dml/sqlsrv_native_moodle_database.php index 90ec10479e5..168c68234c0 100644 --- a/lib/dml/sqlsrv_native_moodle_database.php +++ b/lib/dml/sqlsrv_native_moodle_database.php @@ -1,5 +1,4 @@ libdir.'/dml/moodle_database.php'); -require_once($CFG->libdir.'/dml/sqlsrv_native_moodle_recordset.php'); -require_once($CFG->libdir.'/dml/sqlsrv_native_moodle_temptables.php'); +require_once(__DIR__.'/moodle_database.php'); +require_once(__DIR__.'/sqlsrv_native_moodle_recordset.php'); +require_once(__DIR__.'/sqlsrv_native_moodle_temptables.php'); /** * Native sqlsrv class representing moodle database interface. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later */ @@ -331,29 +328,32 @@ class sqlsrv_native_moodle_database extends moodle_database { return $errorMessage; } - /*** - * Bound variables *are* supported. Until I can get it to work, emulate the bindings - * The challenge/problem/bug is that although they work, doing a SELECT SCOPE_IDENTITY() - * doesn't return a value (no result set) - */ - /** * Prepare the query binding and do the actual query. * * @param string $sql The sql statement - * @param mixed $params array of params for binding. If NULL, they are ignored. - * @param mixed $sql_query_type - Type of operation - * @param mixed $free_result - Default true, transaction query will be freed. - * @param mixed $scrollable - Default false, to use for quickly seeking to target records + * @param array $params array of params for binding. If NULL, they are ignored. + * @param int $sql_query_type - Type of operation + * @param bool $free_result - Default true, transaction query will be freed. + * @param bool $scrollable - Default false, to use for quickly seeking to target records + * @return resource|bool result */ private function do_query($sql, $params, $sql_query_type, $free_result = true, $scrollable = false) { list($sql, $params, $type) = $this->fix_sql_params($sql, $params); + /* + * Bound variables *are* supported. Until I can get it to work, emulate the bindings + * The challenge/problem/bug is that although they work, doing a SELECT SCOPE_IDENTITY() + * doesn't return a value (no result set) + * + * -- somebody from MS + */ + $sql = $this->emulate_bound_params($sql, $params); $this->query_start($sql, $params, $sql_query_type); if (!$scrollable) { // Only supporting next row $result = sqlsrv_query($this->sqlsrv, $sql); - } else { // Suporting absolute/relative rows + } else { // Supporting absolute/relative rows $result = sqlsrv_query($this->sqlsrv, $sql, array(), array('Scrollable' => SQLSRV_CURSOR_STATIC)); } @@ -575,7 +575,7 @@ class sqlsrv_native_moodle_database extends moodle_database { protected function normalise_value($column, $value) { $this->detect_objects($value); - if (is_bool($value)) { /// Always, convert boolean to int + if (is_bool($value)) { // Always, convert boolean to int $value = (int)$value; } // And continue processing because text columns with numeric info need special handling below @@ -585,9 +585,9 @@ class sqlsrv_native_moodle_database extends moodle_database { $value = unpack('H*hex', $value); // we leave it as array, so emulate_bound_params() can detect it } // easily and "bind" the param ok. - } else if ($column->meta_type == 'X') { // sqlsrv doesn't cast from int to text, so if text column + } else if ($column->meta_type == 'X') { // sqlsrv doesn't cast from int to text, so if text column if (is_numeric($value)) { // and is numeric value then cast to string - $value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how + $value = array('numstr' => (string)$value); // and put into array, so emulate_bound_params() will know how } // to "bind" the param ok, avoiding reverse conversion to number } else if ($value === '') { @@ -602,6 +602,7 @@ class sqlsrv_native_moodle_database extends moodle_database { * Selectively call sqlsrv_free_stmt(), avoiding some warnings without using the horrible @ * * @param sqlsrv_resource $resource resource to be freed if possible + * @return bool */ private function free_result($resource) { if (!is_bool($resource)) { // true/false resources cannot be freed @@ -688,7 +689,6 @@ class sqlsrv_native_moodle_database extends moodle_database { return null; } - /** * Workaround for SQL*Server Native driver similar to MSSQL driver for * consistent behavior. @@ -698,7 +698,7 @@ class sqlsrv_native_moodle_database extends moodle_database { if (empty($params)) { return $sql; } - /// ok, we have verified sql statement with ? and correct number of params + // ok, we have verified sql statement with ? and correct number of params $parts = explode('?', $sql); $return = array_shift($parts); foreach ($params as $param) { @@ -1099,7 +1099,7 @@ class sqlsrv_native_moodle_database extends moodle_database { // convert params to ? types list($select, $params, $type) = $this->fix_sql_params($select, $params); - /// Get column metadata + // Get column metadata $columns = $this->get_columns($table); $column = $columns[$newfield]; @@ -1141,8 +1141,6 @@ class sqlsrv_native_moodle_database extends moodle_database { } - /// SQL helper functions - public function sql_cast_char2int($fieldname, $text = false) { if (!$text) { return ' CAST(' . $fieldname . ' AS INT) '; @@ -1300,8 +1298,6 @@ class sqlsrv_native_moodle_database extends moodle_database { } } - /// session locking - public function session_lock_supported() { return true; } @@ -1310,7 +1306,7 @@ class sqlsrv_native_moodle_database extends moodle_database { * Obtain session lock * @param int $rowid id of the row with session record * @param int $timeout max allowed time to wait for the lock in seconds - * @return bool success + * @return void */ public function get_session_lock($rowid, $timeout) { if (!$this->session_lock_supported()) { @@ -1361,14 +1357,6 @@ class sqlsrv_native_moodle_database extends moodle_database { $this->free_result($result); } - - /// transactions - - // NOTE: - // TODO -- should these be wrapped in query start/end? They arn't a query - // but information and error capture is nice. msk - - /** * Driver specific start of real database transaction, * this can not be used directly in code. diff --git a/lib/dml/sqlsrv_native_moodle_recordset.php b/lib/dml/sqlsrv_native_moodle_recordset.php index 1f9965506cb..6ca88aad323 100644 --- a/lib/dml/sqlsrv_native_moodle_recordset.php +++ b/lib/dml/sqlsrv_native_moodle_recordset.php @@ -1,5 +1,4 @@ libdir.'/dml/moodle_recordset.php'); +require_once(__DIR__.'/moodle_recordset.php'); class sqlsrv_native_moodle_recordset extends moodle_recordset { @@ -55,7 +53,7 @@ class sqlsrv_native_moodle_recordset extends moodle_recordset { } public function key() { - /// return first column value as key + // return first column value as key if (!$this->current) { return false; } diff --git a/lib/dml/sqlsrv_native_moodle_temptables.php b/lib/dml/sqlsrv_native_moodle_temptables.php index fe860346586..2d9cc62b9c7 100644 --- a/lib/dml/sqlsrv_native_moodle_temptables.php +++ b/lib/dml/sqlsrv_native_moodle_temptables.php @@ -1,5 +1,4 @@ libdir.'/dml/mssql_native_moodle_temptables.php'); +require_once(__DIR__.'/mssql_native_moodle_temptables.php'); -/*** +/** * This class is not specific to the SQL Server Native Driver but rather * to the family of Microsoft SQL Servers. * - * @package core - * @subpackage dml_driver + * @package core_dml * @copyright 2009 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v2 or later */ diff --git a/lib/dml/tests/dml_test.php b/lib/dml/tests/dml_test.php index 410c7ffef3b..4993d3596bb 100644 --- a/lib/dml/tests/dml_test.php +++ b/lib/dml/tests/dml_test.php @@ -17,8 +17,7 @@ /** * DML layer tests * - * @package core - * @subpackage dml + * @package core_dml * @category phpunit * @copyright 2008 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later @@ -63,8 +62,6 @@ class dml_testcase extends database_driver_testcase { return $debuginfo; } - // NOTE: please keep order of test methods here matching the order of moodle_database class methods - function test_diagnose() { $DB = $this->tdb; $result = $DB->diagnose(); @@ -1090,7 +1087,7 @@ class dml_testcase extends database_driver_testcase { $this->assertEquals(3, $counter); $rs->close(); - $rs = $DB->get_recordset_list($tablename, 'course',array()); /// Must return 0 rows without conditions. MDL-17645 + $rs = $DB->get_recordset_list($tablename, 'course',array()); // Must return 0 rows without conditions. MDL-17645 $counter = 0; foreach ($rs as $record) { @@ -1316,7 +1313,7 @@ class dml_testcase extends database_driver_testcase { $this->assertEquals(2, next($records)->id); $this->assertEquals(4, next($records)->id); - $this->assertSame(array(), $records = $DB->get_records_list($tablename, 'course', array())); /// Must return 0 rows without conditions. MDL-17645 + $this->assertSame(array(), $records = $DB->get_records_list($tablename, 'course', array())); // Must return 0 rows without conditions. MDL-17645 $this->assertEquals(0, count($records)); // note: delegate limits testing to test_get_records_sql() @@ -3070,7 +3067,7 @@ class dml_testcase extends database_driver_testcase { $this->assertTrue($DB->delete_records_list($tablename, 'course', array(2, 3))); $this->assertEquals(1, $DB->count_records($tablename)); - $this->assertTrue($DB->delete_records_list($tablename, 'course', array())); /// Must delete 0 rows without conditions. MDL-17645 + $this->assertTrue($DB->delete_records_list($tablename, 'course', array())); // Must delete 0 rows without conditions. MDL-17645 $this->assertEquals(1, $DB->count_records($tablename)); } @@ -3560,13 +3557,13 @@ class dml_testcase extends database_driver_testcase { function test_coalesce() { $DB = $this->tdb; - // Testing not-null ocurrences, return 1st + // Testing not-null occurrences, return 1st $sql = "SELECT COALESCE('returnthis', 'orthis', 'orwhynotthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(:paramvalue, 'orthis', 'orwhynotthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); - // Testing null ocurrences, return 2nd + // Testing null occurrences, return 2nd $sql = "SELECT COALESCE(null, 'returnthis', 'orthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(:paramvalue, 'returnthis', 'orthis') AS test" . $DB->sql_null_from_clause(); @@ -3574,7 +3571,7 @@ class dml_testcase extends database_driver_testcase { $sql = "SELECT COALESCE(null, :paramvalue, 'orthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); - // Testing null ocurrences, return 3rd + // Testing null occurrences, return 3rd $sql = "SELECT COALESCE(null, null, 'returnthis') AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array())); $sql = "SELECT COALESCE(null, :paramvalue, 'returnthis') AS test" . $DB->sql_null_from_clause(); @@ -3582,7 +3579,7 @@ class dml_testcase extends database_driver_testcase { $sql = "SELECT COALESCE(null, null, :paramvalue) AS test" . $DB->sql_null_from_clause(); $this->assertEquals('returnthis', $DB->get_field_sql($sql, array('paramvalue' => 'returnthis'))); - // Testing all null ocurrences, return null + // Testing all null occurrences, return null // Note: under mssql, if all elements are nulls, at least one must be a "typed" null, hence // we cannot test this in a cross-db way easily, so next 2 tests are using // different queries depending of the DB family @@ -3603,7 +3600,7 @@ class dml_testcase extends database_driver_testcase { $DB = $this->tdb; $dbman = $DB->get_manager(); - /// Testing all sort of values + // Testing all sort of values $sql = "SELECT ".$DB->sql_concat("?", "?", "?")." AS fullname ". $DB->sql_null_from_clause(); // string, some unicode chars $params = array('name', 'áéíóú', 'name3'); @@ -3621,7 +3618,7 @@ class dml_testcase extends database_driver_testcase { $params = array(123.45, null, 'test'); $this->assertNull($DB->get_field_sql($sql, $params), 'ANSI behaviour: Concatenating NULL must return NULL - But in Oracle :-(. [%s]'); // Concatenate NULL with anything result = NULL - /// Testing fieldnames + values and also integer fieldnames + // Testing fieldnames + values and also integer fieldnames $table = $this->get_test_table(); $tablename = $table->getName(); @@ -4328,7 +4325,7 @@ class dml_testcase extends database_driver_testcase { $DB2 = moodle_database::get_driver_instance($cfg->dbtype, $cfg->dblibrary); $DB2->connect($cfg->dbhost, $cfg->dbuser, $cfg->dbpass, $cfg->dbname, $cfg->prefix, $cfg->dboptions); - // Testing that acquiring a lock efectively locks + // Testing that acquiring a lock effectively locks // Get a session lock on connection1 $rowid = rand(100, 200); $timeout = 1; @@ -4337,14 +4334,14 @@ class dml_testcase extends database_driver_testcase { // Try to get the same session lock on connection2 try { $DB2->get_session_lock($rowid, $timeout); - $DB2->release_session_lock($rowid); // Should not be excuted, but here for safety + $DB2->release_session_lock($rowid); // Should not be executed, but here for safety $this->fail('An Exception is missing, expected due to session lock acquired.'); } catch (exception $e) { $this->assertTrue($e instanceof dml_sessionwait_exception); $DB->release_session_lock($rowid); // Release lock on connection1 } - // Testing that releasing a lock efectively frees + // Testing that releasing a lock effectively frees // Get a session lock on connection1 $rowid = rand(100, 200); $timeout = 1; @@ -4613,7 +4610,7 @@ class moodle_database_for_testing extends moodle_database { /** - * Dumb test class with toString() returrning 1. + * Dumb test class with toString() returning 1. */ class dml_test_object_one { public function __toString() { From 5a070f0477c40fdb79da4b1307fc47dd9a96eb6b Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Tue, 5 Jun 2012 12:14:02 +0200 Subject: [PATCH 024/130] MDL-32003 fix phpdocs in DDL layer --- lib/ddl/database_manager.php | 127 ++++++----- lib/ddl/mssql_sql_generator.php | 261 +++++++++++++++-------- lib/ddl/mysql_sql_generator.php | 165 ++++++++++----- lib/ddl/oracle_sql_generator.php | 267 ++++++++++++++++-------- lib/ddl/postgres_sql_generator.php | 218 ++++++++++++------- lib/ddl/sql_generator.php | 324 ++++++++++++++--------------- lib/ddl/sqlite_sql_generator.php | 126 +++++++---- lib/ddl/tests/ddl_test.php | 23 +- 8 files changed, 924 insertions(+), 587 deletions(-) diff --git a/lib/ddl/database_manager.php b/lib/ddl/database_manager.php index ee6f9bd9dc0..aba9282770c 100644 --- a/lib/ddl/database_manager.php +++ b/lib/ddl/database_manager.php @@ -14,13 +14,10 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . - /** * Database manager instance is responsible for all database structure modifications. * - * @package core - * @category ddl - * @subpackage ddl + * @package core_ddl * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com * 2008 Petr Skoda http://skodak.org @@ -34,9 +31,7 @@ defined('MOODLE_INTERNAL') || die(); * * It is using db specific generators to find out the correct SQL syntax to do that. * - * @package core - * @category ddl - * @subpackage ddl + * @package core_ddl * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com * 2008 Petr Skoda http://skodak.org @@ -44,8 +39,9 @@ defined('MOODLE_INTERNAL') || die(); */ class database_manager { - /** @var moodle_database A moodle_database driver speific instance.*/ + /** @var moodle_database A moodle_database driver specific instance.*/ protected $mdb; + /** @var sql_generator A driver specific SQL generator instance. Public because XMLDB editor needs to access it.*/ public $generator; @@ -55,8 +51,6 @@ class database_manager { * @param sql_generator $generator A driver specific SQL generator instance. */ public function __construct($mdb, $generator) { - global $CFG; - $this->mdb = $mdb; $this->generator = $generator; } @@ -100,7 +94,7 @@ class database_manager { /** * Given one xmldb_table, check if it exists in DB (true/false). * - * @param mixed $table The table to be searched (string name or xmldb_table instance). + * @param string|xmldb_table $table The table to be searched (string name or xmldb_table instance). * @return bool true/false True is a table exists, false otherwise. */ public function table_exists($table) { @@ -138,14 +132,14 @@ class database_manager { * @throws ddl_table_missing_exception */ public function field_exists($table, $field) { - /// Calculate the name of the table + // Calculate the name of the table if (is_string($table)) { $tablename = $table; } else { $tablename = $table->getName(); } - /// Check the table exists + // Check the table exists if (!$this->table_exists($table)) { throw new ddl_table_missing_exception($tablename); } @@ -153,11 +147,11 @@ class database_manager { if (is_string($field)) { $fieldname = $field; } else { - /// Calculate the name of the table + // Calculate the name of the table $fieldname = $field->getName(); } - /// Get list of fields in table + // Get list of fields in table $columns = $this->mdb->get_columns($tablename); $exists = array_key_exists($fieldname, $columns); @@ -175,32 +169,32 @@ class database_manager { * @throws ddl_table_missing_exception Thrown when table is not found. */ public function find_index_name(xmldb_table $xmldb_table, xmldb_index $xmldb_index) { - /// Calculate the name of the table + // Calculate the name of the table $tablename = $xmldb_table->getName(); - /// Check the table exists + // Check the table exists if (!$this->table_exists($xmldb_table)) { throw new ddl_table_missing_exception($tablename); } - /// Extract index columns + // Extract index columns $indcolumns = $xmldb_index->getFields(); - /// Get list of indexes in table + // Get list of indexes in table $indexes = $this->mdb->get_indexes($tablename); - /// Iterate over them looking for columns coincidence + // Iterate over them looking for columns coincidence foreach ($indexes as $indexname => $index) { $columns = $index['columns']; - /// Check if index matchs queried index + // Check if index matches queried index $diferences = array_merge(array_diff($columns, $indcolumns), array_diff($indcolumns, $columns)); - /// If no diferences, we have find the index + // If no differences, we have find the index if (empty($diferences)) { return $indexname; } } - /// Arriving here, index not found + // Arriving here, index not found return false; } @@ -233,23 +227,23 @@ class database_manager { $keycolumns = $xmldb_key->getFields(); - /// Get list of keys in table - /// first primaries (we aren't going to use this now, because the MetaPrimaryKeys is awful) - ///TODO: To implement when we advance in relational integrity - /// then uniques (note that Moodle, for now, shouldn't have any UNIQUE KEY for now, but unique indexes) - ///TODO: To implement when we advance in relational integrity (note that AdoDB hasn't any MetaXXX for this. - /// then foreign (note that Moodle, for now, shouldn't have any FOREIGN KEY for now, but indexes) - ///TODO: To implement when we advance in relational integrity (note that AdoDB has one MetaForeignKeys() - ///but it's far from perfect. - /// TODO: To create the proper functions inside each generator to retrieve all the needed KEY info (name - /// columns, reftable and refcolumns + // Get list of keys in table + // first primaries (we aren't going to use this now, because the MetaPrimaryKeys is awful) + //TODO: To implement when we advance in relational integrity + // then uniques (note that Moodle, for now, shouldn't have any UNIQUE KEY for now, but unique indexes) + //TODO: To implement when we advance in relational integrity (note that AdoDB hasn't any MetaXXX for this. + // then foreign (note that Moodle, for now, shouldn't have any FOREIGN KEY for now, but indexes) + //TODO: To implement when we advance in relational integrity (note that AdoDB has one MetaForeignKeys() + //but it's far from perfect. + // TODO: To create the proper functions inside each generator to retrieve all the needed KEY info (name + // columns, reftable and refcolumns - /// So all we do is to return the official name of the requested key without any confirmation!) - /// One exception, hardcoded primary constraint names + // So all we do is to return the official name of the requested key without any confirmation!) + // One exception, hardcoded primary constraint names if ($this->generator->primary_key_name && $xmldb_key->getType() == XMLDB_KEY_PRIMARY) { return $this->generator->primary_key_name; } else { - /// Calculate the name suffix + // Calculate the name suffix switch ($xmldb_key->getType()) { case XMLDB_KEY_PRIMARY: $suffix = 'pk'; @@ -262,7 +256,7 @@ class database_manager { $suffix = 'fk'; break; } - /// And simply, return the official name + // And simply, return the official name return $this->generator->getNameForObject($xmldb_table->getName(), implode(', ', $xmldb_key->getFields()), $suffix); } } @@ -285,7 +279,7 @@ class database_manager { $structure = $xmldb_file->getStructure(); if (!$loaded || !$xmldb_file->isLoaded()) { - /// Show info about the error if we can find it + // Show info about the error if we can find it if ($structure) { if ($errors = $structure->getAllErrors()) { throw new ddl_exception('ddlxmlfileerror', null, 'Errors found in XMLDB file: '. implode (', ', $errors)); @@ -312,7 +306,7 @@ class database_manager { * @return void */ public function drop_table(xmldb_table $xmldb_table) { - /// Check table exists + // Check table exists if (!$this->table_exists($xmldb_table)) { throw new ddl_table_missing_exception($xmldb_table->getName()); } @@ -338,7 +332,7 @@ class database_manager { $loaded = $xmldb_file->loadXMLStructure(); if (!$loaded || !$xmldb_file->isLoaded()) { - /// Show info about the error if we can find it + // Show info about the error if we can find it if ($structure =& $xmldb_file->getStructure()) { if ($errors = $structure->getAllErrors()) { throw new ddl_exception('ddlxmlfileerror', null, 'Errors found in XMLDB file: '. implode (', ', $errors)); @@ -418,7 +412,7 @@ class database_manager { * @return void */ public function create_table(xmldb_table $xmldb_table) { - /// Check table doesn't exist + // Check table doesn't exist if ($this->table_exists($xmldb_table)) { throw new ddl_exception('ddltablealreadyexists', $xmldb_table->getName()); } @@ -477,14 +471,14 @@ class database_manager { * @return void */ public function rename_table(xmldb_table $xmldb_table, $newname) { - /// Check newname isn't empty + // Check newname isn't empty if (!$newname) { throw new ddl_exception('ddlunknownerror', null, 'newname can not be empty'); } $check = new xmldb_table($newname); - /// Check table already renamed + // Check table already renamed if (!$this->table_exists($xmldb_table)) { if ($this->table_exists($check)) { throw new ddl_exception('ddlunknownerror', null, 'table probably already renamed'); @@ -493,7 +487,7 @@ class database_manager { } } - /// Check new table doesn't exist + // Check new table doesn't exist if ($this->table_exists($check)) { throw new ddl_exception('ddltablealreadyexists', $xmldb_table->getName(), 'can not rename table'); } @@ -505,7 +499,6 @@ class database_manager { $this->execute_sql_arr($sqlarr); } - /** * This function will add the field to the table passed as arguments * @@ -514,13 +507,13 @@ class database_manager { * @return void */ public function add_field(xmldb_table $xmldb_table, xmldb_field $xmldb_field) { - /// Check the field doesn't exist + // Check the field doesn't exist if ($this->field_exists($xmldb_table, $xmldb_field)) { throw new ddl_exception('ddlfieldalreadyexists', $xmldb_field->getName()); } - /// If NOT NULL and no default given (we ask the generator about the - /// *real* default that will be used) check the table is empty + // If NOT NULL and no default given (we ask the generator about the + // *real* default that will be used) check the table is empty if ($xmldb_field->getNotNull() && $this->generator->getDefaultValue($xmldb_field) === NULL && $this->mdb->count_records($xmldb_table->getName())) { throw new ddl_exception('ddlunknownerror', null, 'Field ' . $xmldb_table->getName() . '->' . $xmldb_field->getName() . ' cannot be added. Not null fields added to non empty tables require default value. Create skipped'); @@ -543,11 +536,11 @@ class database_manager { if (!$this->table_exists($xmldb_table)) { throw new ddl_table_missing_exception($xmldb_table->getName()); } - /// Check the field exists + // Check the field exists if (!$this->field_exists($xmldb_table, $xmldb_field)) { throw new ddl_field_missing_exception($xmldb_field->getName(), $xmldb_table->getName()); } - /// Check for dependencies in the DB before performing any action + // Check for dependencies in the DB before performing any action $this->check_field_dependencies($xmldb_table, $xmldb_field); if (!$sqlarr = $this->generator->getDropFieldSQL($xmldb_table, $xmldb_field)) { @@ -568,11 +561,11 @@ class database_manager { if (!$this->table_exists($xmldb_table)) { throw new ddl_table_missing_exception($xmldb_table->getName()); } - /// Check the field exists + // Check the field exists if (!$this->field_exists($xmldb_table, $xmldb_field)) { throw new ddl_field_missing_exception($xmldb_field->getName(), $xmldb_table->getName()); } - /// Check for dependencies in the DB before performing any action + // Check for dependencies in the DB before performing any action $this->check_field_dependencies($xmldb_table, $xmldb_field); if (!$sqlarr = $this->generator->getAlterFieldSQL($xmldb_table, $xmldb_field)) { @@ -590,7 +583,7 @@ class database_manager { * @return void */ public function change_field_precision(xmldb_table $xmldb_table, xmldb_field $xmldb_field) { - /// Just a wrapper over change_field_type. Does exactly the same processing + // Just a wrapper over change_field_type. Does exactly the same processing $this->change_field_type($xmldb_table, $xmldb_field); } @@ -615,7 +608,7 @@ class database_manager { * @return void */ public function change_field_notnull(xmldb_table $xmldb_table, xmldb_field $xmldb_field) { - /// Just a wrapper over change_field_type. Does exactly the same processing + // Just a wrapper over change_field_type. Does exactly the same processing $this->change_field_type($xmldb_table, $xmldb_field); } @@ -631,11 +624,11 @@ class database_manager { if (!$this->table_exists($xmldb_table)) { throw new ddl_table_missing_exception($xmldb_table->getName()); } - /// Check the field exists + // Check the field exists if (!$this->field_exists($xmldb_table, $xmldb_field)) { throw new ddl_field_missing_exception($xmldb_field->getName(), $xmldb_table->getName()); } - /// Check for dependencies in the DB before performing any action + // Check for dependencies in the DB before performing any action $this->check_field_dependencies($xmldb_table, $xmldb_field); if (!$sqlarr = $this->generator->getModifyDefaultSQL($xmldb_table, $xmldb_field)) { @@ -663,19 +656,19 @@ class database_manager { throw new ddl_table_missing_exception($xmldb_table->getName()); } - /// Check the field exists + // Check the field exists if (!$this->field_exists($xmldb_table, $xmldb_field)) { throw new ddl_field_missing_exception($xmldb_field->getName(), $xmldb_table->getName()); } - /// Check we have included full field specs + // Check we have included full field specs if (!$xmldb_field->getType()) { throw new ddl_exception('ddlunknownerror', null, 'Field ' . $xmldb_table->getName() . '->' . $xmldb_field->getName() . ' must contain full specs. Rename skipped'); } - /// Check field isn't id. Renaming over that field is not allowed + // Check field isn't id. Renaming over that field is not allowed if ($xmldb_field->getName() == 'id') { throw new ddl_exception('ddlunknownerror', null, 'Field ' . $xmldb_table->getName() . '->' . $xmldb_field->getName() . @@ -701,17 +694,17 @@ class database_manager { */ private function check_field_dependencies(xmldb_table $xmldb_table, xmldb_field $xmldb_field) { - /// Check the table exists + // Check the table exists if (!$this->table_exists($xmldb_table)) { throw new ddl_table_missing_exception($xmldb_table->getName()); } - /// Check the field exists + // Check the field exists if (!$this->field_exists($xmldb_table, $xmldb_field)) { throw new ddl_field_missing_exception($xmldb_field->getName(), $xmldb_table->getName()); } - /// Check the field isn't in use by any index in the table + // Check the field isn't in use by any index in the table if ($indexes = $this->mdb->get_indexes($xmldb_table->getName(), false)) { foreach ($indexes as $indexname => $index) { $columns = $index['columns']; @@ -774,7 +767,7 @@ class database_manager { public function rename_key(xmldb_table $xmldb_table, xmldb_key $xmldb_key, $newname) { debugging('rename_key() is one experimental feature. You must not use it in production!', DEBUG_DEVELOPER); - /// Check newname isn't empty + // Check newname isn't empty if (!$newname) { throw new ddl_exception('ddlunknownerror', null, 'newname can not be empty'); } @@ -799,7 +792,7 @@ class database_manager { throw new ddl_table_missing_exception($xmldb_table->getName()); } - /// Check index doesn't exist + // Check index doesn't exist if ($this->index_exists($xmldb_table, $xmldb_intex)) { throw new ddl_exception('ddlunknownerror', null, 'Index ' . $xmldb_table->getName() . '->' . $xmldb_intex->getName() . @@ -826,7 +819,7 @@ class database_manager { throw new ddl_table_missing_exception($xmldb_table->getName()); } - /// Check index exists + // Check index exists if (!$this->index_exists($xmldb_table, $xmldb_intex)) { throw new ddl_exception('ddlunknownerror', null, 'Index ' . $xmldb_table->getName() . '->' . $xmldb_intex->getName() . @@ -853,12 +846,12 @@ class database_manager { public function rename_index($xmldb_table, $xmldb_intex, $newname) { debugging('rename_index() is one experimental feature. You must not use it in production!', DEBUG_DEVELOPER); - /// Check newname isn't empty + // Check newname isn't empty if (!$newname) { throw new ddl_exception('ddlunknownerror', null, 'newname can not be empty'); } - /// Check index exists + // Check index exists if (!$this->index_exists($xmldb_table, $xmldb_intex)) { throw new ddl_exception('ddlunknownerror', null, 'Index ' . $xmldb_table->getName() . '->' . $xmldb_intex->getName() . diff --git a/lib/ddl/mssql_sql_generator.php b/lib/ddl/mssql_sql_generator.php index ed9942e17a9..bbf769ded3d 100644 --- a/lib/ddl/mssql_sql_generator.php +++ b/lib/ddl/mssql_sql_generator.php @@ -1,5 +1,4 @@ . - /** * MSSQL specific SQL code generator. * - * @package core - * @subpackage ddl_generator + * @package core_ddl * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later @@ -30,51 +27,70 @@ defined('MOODLE_INTERNAL') || die(); require_once($CFG->libdir.'/ddl/sql_generator.php'); -/// This class generate SQL code to be used against MSSQL -/// It extends XMLDBgenerator so everything can be -/// overridden as needed to generate correct SQL. - +/** + * This class generate SQL code to be used against MSSQL + * It extends XMLDBgenerator so everything can be + * overridden as needed to generate correct SQL. + * + * @package core_ddl + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ class mssql_sql_generator extends sql_generator { -/// Only set values that are different from the defaults present in XMLDBgenerator + // Only set values that are different from the defaults present in XMLDBgenerator - public $statement_end = "\ngo"; // String to be automatically added at the end of each statement + /** @var string To be automatically added at the end of each statement. */ + public $statement_end = "\ngo"; - public $number_type = 'DECIMAL'; // Proper type for NUMBER(x) in this DB + /** @var string Proper type for NUMBER(x) in this DB. */ + public $number_type = 'DECIMAL'; - public $default_for_char = ''; // To define the default to set for NOT NULLs CHARs without default (null=do nothing) + /** @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).*/ + public $default_for_char = ''; - public $specify_nulls = true; //To force the generator if NULL clauses must be specified. It shouldn't be necessary - //but some mssql drivers require them or everything is created as NOT NULL :-( + /** + * @var bool To force the generator if NULL clauses must be specified. It shouldn't be necessary. + * note: some mssql drivers require them or everything is created as NOT NULL :-( + */ + public $specify_nulls = true; - public $sequence_extra_code = false; //Does the generator need to add extra code to generate the sequence fields - public $sequence_name = 'IDENTITY(1,1)'; //Particular name for inline sequences in this generator - public $sequence_only = false; //To avoid to output the rest of the field specs, leaving only the name and the sequence_name variable + /** @var bool True if the generator needs to add extra code to generate the sequence fields.*/ + public $sequence_extra_code = false; - public $add_table_comments = false; // Does the generator need to add code for table comments + /** @var string The particular name for inline sequences in this generator.*/ + public $sequence_name = 'IDENTITY(1,1)'; - public $concat_character = '+'; //Characters to be used as concatenation operator. If not defined - //MySQL CONCAT function will be use + /** @var bool To avoid outputting the rest of the field specs, leaving only the name and the sequence_name returned.*/ + public $sequence_only = false; - public $rename_table_sql = "sp_rename 'OLDNAME', 'NEWNAME'"; //SQL sentence to rename one table, both - //OLDNAME and NEWNAME are dynamically replaced + /** @var bool True if the generator needs to add code for table comments.*/ + public $add_table_comments = false; + /** @var string Characters to be used as concatenation operator.*/ + public $concat_character = '+'; + + /** @var string SQL sentence to rename one table, both 'OLDNAME' and 'NEWNAME' keywords are dynamically replaced.*/ + public $rename_table_sql = "sp_rename 'OLDNAME', 'NEWNAME'"; + + /** @var string SQL sentence to rename one column where 'TABLENAME', 'OLDFIELDNAME' and 'NEWFIELDNAME' keywords are dynamically replaced.*/ public $rename_column_sql = "sp_rename 'TABLENAME.OLDFIELDNAME', 'NEWFIELDNAME', 'COLUMN'"; - ///TABLENAME, OLDFIELDNAME and NEWFIELDNAME are dyanmically replaced - public $drop_index_sql = 'DROP INDEX TABLENAME.INDEXNAME'; //SQL sentence to drop one index - //TABLENAME, INDEXNAME are dynamically replaced + /** @var string SQL sentence to drop one index where 'TABLENAME', 'INDEXNAME' keywords are dynamically replaced.*/ + public $drop_index_sql = 'DROP INDEX TABLENAME.INDEXNAME'; - public $rename_index_sql = "sp_rename 'TABLENAME.OLDINDEXNAME', 'NEWINDEXNAME', 'INDEX'"; //SQL sentence to rename one index - //TABLENAME, OLDINDEXNAME, NEWINDEXNAME are dynamically replaced + /** @var string SQL sentence to rename one index where 'TABLENAME', 'OLDINDEXNAME' and 'NEWINDEXNAME' are dynamically replaced.*/ + public $rename_index_sql = "sp_rename 'TABLENAME.OLDINDEXNAME', 'NEWINDEXNAME', 'INDEX'"; - public $rename_key_sql = null; //SQL sentence to rename one key - //TABLENAME, OLDKEYNAME, NEWKEYNAME are dynamically replaced + /** @var string SQL sentence to rename one key 'TABLENAME', 'OLDKEYNAME' and 'NEWKEYNAME' are dynamically replaced.*/ + public $rename_key_sql = null; /** * Reset a sequence to the id field of a table. - * @param string $table name of table or xmldb_table object - * @return array sql commands to execute + * + * @param xmldb_table|string $table name of table or the table object. + * @return array of sql statements */ public function getResetSequenceSQL($table) { @@ -109,14 +125,14 @@ class mssql_sql_generator extends sql_generator { * @return string the correct name of the table */ public function getTableName(xmldb_table $xmldb_table, $quoted=true) { - /// Get the name, supporting special mssql names for temp tables + // Get the name, supporting special mssql names for temp tables if ($this->temptables->is_temptable($xmldb_table->getName())) { $tablename = $this->temptables->get_correct_name($xmldb_table->getName()); } else { $tablename = $this->prefix . $xmldb_table->getName(); } - /// Apply quotes optionally + // Apply quotes optionally if ($quoted) { $tablename = $this->getEncQuoted($tablename); } @@ -124,10 +140,12 @@ class mssql_sql_generator extends sql_generator { return $tablename; } - /** * Given one correct xmldb_table, returns the SQL statements - * to create temporary table (inside one array) + * to create temporary table (inside one array). + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array of sql statements */ public function getCreateTempTableSQL($xmldb_table) { $this->temptables->add_temptable($xmldb_table->getName()); @@ -151,7 +169,12 @@ class mssql_sql_generator extends sql_generator { } /** - * Given one XMLDB Type, lenght and decimals, returns the DB proper SQL type + * Given one XMLDB Type, length and decimals, returns the DB proper SQL type. + * + * @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants. + * @param int $xmldb_length The length of that data type. + * @param int $xmldb_decimals The decimal places of precision of the data type. + * @return string The DB defined data type. */ public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) { @@ -171,7 +194,7 @@ class mssql_sql_generator extends sql_generator { case XMLDB_TYPE_NUMBER: $dbtype = $this->number_type; if (!empty($xmldb_length)) { - /// 38 is the max allowed + // 38 is the max allowed if ($xmldb_length > 38) { $xmldb_length = 38; } @@ -211,23 +234,27 @@ class mssql_sql_generator extends sql_generator { } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop the field from the table + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop the field from the table. * MSSQL overwrites the standard sentence because it needs to do some extra work dropping the default and * check constraints + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from. + * @return array The SQL statement for dropping a field from the table. */ public function getDropFieldSQL($xmldb_table, $xmldb_field) { $results = array(); - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); - /// Look for any default constraint in this field and drop it + // Look for any default constraint in this field and drop it if ($defaultname = $this->getDefaultConstraintName($xmldb_table, $xmldb_field)) { $results[] = 'ALTER TABLE ' . $tablename . ' DROP CONSTRAINT ' . $defaultname; } - /// Build the standard alter table drop column + // Build the standard alter table drop column $results[] = 'ALTER TABLE ' . $tablename . ' DROP COLUMN ' . $fieldname; return $results; @@ -235,33 +262,43 @@ class mssql_sql_generator extends sql_generator { /** * Given one correct xmldb_field and the new name, returns the SQL statements - * to rename it (inside one array) + * to rename it (inside one array). + * * MSSQL is special, so we overload the function here. It needs to * drop the constraints BEFORE renaming the field + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to get the renamed field from. + * @param string $newname The new name to rename the field to. + * @return array The SQL statements for renaming the field. */ public function getRenameFieldSQL($xmldb_table, $xmldb_field, $newname) { $results = array(); //Array where all the sentences will be stored - /// Although this is checked in database_manager::rename_field() - double check - /// that we aren't trying to rename one "id" field. Although it could be - /// implemented (if adding the necessary code to rename sequences, defaults, - /// triggers... and so on under each getRenameFieldExtraSQL() function, it's - /// better to forbid it, mainly because this field is the default PK and - /// in the future, a lot of FKs can be pointing here. So, this field, more - /// or less, must be considered immutable! + // Although this is checked in database_manager::rename_field() - double check + // that we aren't trying to rename one "id" field. Although it could be + // implemented (if adding the necessary code to rename sequences, defaults, + // triggers... and so on under each getRenameFieldExtraSQL() function, it's + // better to forbid it, mainly because this field is the default PK and + // in the future, a lot of FKs can be pointing here. So, this field, more + // or less, must be considered immutable! if ($xmldb_field->getName() == 'id') { return array(); } - /// Call to standard (parent) getRenameFieldSQL() function + // Call to standard (parent) getRenameFieldSQL() function $results = array_merge($results, parent::getRenameFieldSQL($xmldb_table, $xmldb_field, $newname)); return $results; } /** - * Returns the code (array of statements) needed to execute extra statements on table rename + * Returns the code (array of statements) needed to execute extra statements on table rename. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param string $newname The new name for the table. + * @return array Array of extra SQL statements to rename a table. */ public function getRenameTableExtraSQL($xmldb_table, $newname) { @@ -271,17 +308,24 @@ class mssql_sql_generator extends sql_generator { } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table. + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from. + * @param string $skip_type_clause The type clause on alter columns, NULL by default. + * @param string $skip_default_clause The default clause on alter columns, NULL by default. + * @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default. + * @return string The field altering SQL statement. */ public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) { - $results = array(); /// To store all the needed SQL commands + $results = array(); // To store all the needed SQL commands - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $xmldb_table->getName(); $fieldname = $xmldb_field->getName(); - /// Take a look to field metadata + // Take a look to field metadata $meta = $this->mdb->get_columns($tablename); $metac = $meta[$fieldname]; $oldmetatype = $metac->meta_type; @@ -294,7 +338,7 @@ class mssql_sql_generator extends sql_generator { $typechanged = true; //By default, assume that the column type has changed $lengthchanged = true; //By default, assume that the column length has changed - /// Detect if we are changing the type of the column + // Detect if we are changing the type of the column if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && $oldmetatype == 'I') || ($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') || ($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') || @@ -304,8 +348,8 @@ class mssql_sql_generator extends sql_generator { $typechanged = false; } - /// If the new field (and old) specs are for integer, let's be a bit more specific differentiating - /// types of integers. Else, some combinations can cause things like MDL-21868 + // If the new field (and old) specs are for integer, let's be a bit more specific differentiating + // types of integers. Else, some combinations can cause things like MDL-21868 if ($xmldb_field->getType() == XMLDB_TYPE_INTEGER && $oldmetatype == 'I') { if ($xmldb_field->getLength() > 9) { // Convert our new lenghts to detailed meta types $newmssqlinttype = 'I8'; @@ -326,20 +370,20 @@ class mssql_sql_generator extends sql_generator { } } - /// Detect if we are changing the length of the column, not always necessary to drop defaults - /// if only the length changes, but it's safe to do it always + // Detect if we are changing the length of the column, not always necessary to drop defaults + // if only the length changes, but it's safe to do it always if ($xmldb_field->getLength() == $oldlength) { $lengthchanged = false; } - /// If type or length have changed drop the default if exists + // If type or length have changed drop the default if exists if ($typechanged || $lengthchanged) { $results = $this->getDropDefaultSQL($xmldb_table, $xmldb_field); } - /// Some changes of type require multiple alter statements, because mssql lacks direct implicit cast between such types - /// Here it is the matrix: http://msdn.microsoft.com/en-us/library/ms187928(SQL.90).aspx - /// Going to store such intermediate alters in array of objects, storing all the info needed + // Some changes of type require multiple alter statements, because mssql lacks direct implicit cast between such types + // Here it is the matrix: http://msdn.microsoft.com/en-us/library/ms187928(SQL.90).aspx + // Going to store such intermediate alters in array of objects, storing all the info needed $multiple_alter_stmt = array(); $targettype = $xmldb_field->getType(); @@ -377,7 +421,7 @@ class mssql_sql_generator extends sql_generator { $multiple_alter_stmt[0]->length = 255; } - /// Just prevent default clauses in this type of sentences for mssql and launch the parent one + // Just prevent default clauses in this type of sentences for mssql and launch the parent one if (empty($multiple_alter_stmt)) { // Direct implicit conversion allowed, launch it $results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field, NULL, true, NULL)); @@ -394,25 +438,29 @@ class mssql_sql_generator extends sql_generator { $results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field, NULL, true, NULL)); } - /// Finally, process the default clause to add it back if necessary + // Finally, process the default clause to add it back if necessary if ($typechanged || $lengthchanged) { $results = array_merge($results, $this->getCreateDefaultSQL($xmldb_table, $xmldb_field)); } - /// Return results + // Return results return $results; } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to modify the default of the field in the table + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to modify the default of the field in the table. + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to get the modified default value from. + * @return array The SQL statement for modifying the default value. */ public function getModifyDefaultSQL($xmldb_table, $xmldb_field) { - /// MSSQL is a bit special with default constraints because it implements them as external constraints so - /// normal ALTER TABLE ALTER COLUMN don't work to change defaults. Because this, we have this method overloaded here + // MSSQL is a bit special with default constraints because it implements them as external constraints so + // normal ALTER TABLE ALTER COLUMN don't work to change defaults. Because this, we have this method overloaded here $results = array(); - /// Decide if we are going to create/modify or to drop the default + // Decide if we are going to create/modify or to drop the default if ($xmldb_field->getDefault() === null) { $results = $this->getDropDefaultSQL($xmldb_table, $xmldb_field); //Drop but, under some circumstances, re-enable $default_clause = $this->getDefaultClause($xmldb_field); @@ -428,22 +476,26 @@ class mssql_sql_generator extends sql_generator { } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to create its default + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default * (usually invoked from getModifyDefaultSQL() + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. */ public function getCreateDefaultSQL($xmldb_table, $xmldb_field) { - /// MSSQL is a bit special and it requires the corresponding DEFAULT CONSTRAINT to be dropped + // MSSQL is a bit special and it requires the corresponding DEFAULT CONSTRAINT to be dropped $results = array(); - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); - /// Now, check if, with the current field attributes, we have to build one default + // Now, check if, with the current field attributes, we have to build one default $default_clause = $this->getDefaultClause($xmldb_field); if ($default_clause) { - /// We need to build the default (Moodle) default, so do it + // We need to build the default (Moodle) default, so do it $sql = 'ALTER TABLE ' . $tablename . ' ADD' . $default_clause . ' FOR ' . $fieldname; $results[] = $sql; } @@ -454,17 +506,25 @@ class mssql_sql_generator extends sql_generator { /** * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default * (usually invoked from getModifyDefaultSQL() + * + * Note that this method may be dropped in future. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. + * + * @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL() */ public function getDropDefaultSQL($xmldb_table, $xmldb_field) { - /// MSSQL is a bit special and it requires the corresponding DEFAULT CONSTRAINT to be dropped + // MSSQL is a bit special and it requires the corresponding DEFAULT CONSTRAINT to be dropped $results = array(); - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); - /// Look for the default contraint and, if found, drop it + // Look for the default contraint and, if found, drop it if ($defaultname = $this->getDefaultConstraintName($xmldb_table, $xmldb_field)) { $results[] = 'ALTER TABLE ' . $tablename . ' DROP CONSTRAINT ' . $defaultname; } @@ -476,14 +536,18 @@ class mssql_sql_generator extends sql_generator { * Given one xmldb_table and one xmldb_field, returns the name of its default constraint in DB * or false if not found * This function should be considered internal and never used outside from generator + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return mixed */ - public function getDefaultConstraintName($xmldb_table, $xmldb_field) { + protected function getDefaultConstraintName($xmldb_table, $xmldb_field) { - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $xmldb_field->getName(); - /// Look for any default constraint in this field and drop it + // Look for any default constraint in this field and drop it if ($default = $this->mdb->get_record_sql("SELECT id, object_name(cdefault) AS defaultconstraint FROM syscolumns WHERE id = object_id(?) @@ -508,6 +572,10 @@ class mssql_sql_generator extends sql_generator { * but the alternative involves modifying all the creation table code to avoid naming * constraints for temp objects and that will dupe a lot of code. * + * @param string $tablename The table name. + * @param string $fields A list of comma separated fields. + * @param string $suffix A suffix for the object name. + * @return string Object's name. */ public function getNameForObject($tablename, $fields, $suffix='') { if ($this->temptables->is_temptable($tablename)) { // Is temp table, inject random field names @@ -518,9 +586,17 @@ class mssql_sql_generator extends sql_generator { } /** - * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg) - * return if such name is currently in use (true) or no (false) - * (invoked from getNameForObject() + * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg). + * + * (MySQL requires the whole xmldb_table object to be specified, so we add it always) + * + * This is invoked from getNameForObject(). + * Only some DB have this implemented. + * + * @param string $object_name The object's name to check for. + * @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg). + * @param string $table_name The table's name to check in + * @return bool If such name is currently in use (true) or no (false) */ public function isNameInUse($object_name, $type, $table_name) { switch($type) { @@ -549,12 +625,20 @@ class mssql_sql_generator extends sql_generator { } /** - * Returns the code (in array) needed to add one comment to the table + * Returns the code (array of statements) needed to add one comment to the table. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array Array of SQL statements to add one comment to the table. */ public function getCommentSQL($xmldb_table) { return array(); } + /** + * Adds slashes to string. + * @param string $s + * @return string The escaped string. + */ public function addslashes($s) { // do not use php addslashes() because it depends on PHP quote settings! $s = str_replace("'", "''", $s); @@ -563,10 +647,11 @@ class mssql_sql_generator extends sql_generator { /** * Returns an array of reserved words (lowercase) for this DB + * @return array An array of database specific reserved words */ public static function getReservedWords() { - /// This file contains the reserved words for MSSQL databases - /// from http://msdn2.microsoft.com/en-us/library/ms189822.aspx + // This file contains the reserved words for MSSQL databases + // from http://msdn2.microsoft.com/en-us/library/ms189822.aspx $reserved_words = array ( 'add', 'all', 'alter', 'and', 'any', 'as', 'asc', 'authorization', 'avg', 'backup', 'begin', 'between', 'break', 'browse', 'bulk', diff --git a/lib/ddl/mysql_sql_generator.php b/lib/ddl/mysql_sql_generator.php index 801d7401e0f..6ae310f6411 100644 --- a/lib/ddl/mysql_sql_generator.php +++ b/lib/ddl/mysql_sql_generator.php @@ -1,5 +1,4 @@ . - /** * Mysql specific SQL code generator. * - * @package core - * @subpackage ddl_generator + * @package core_ddl * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later @@ -30,55 +27,72 @@ defined('MOODLE_INTERNAL') || die(); require_once($CFG->libdir.'/ddl/sql_generator.php'); -/// This class generate SQL code to be used against MySQL -/// It extends XMLDBgenerator so everything can be -/// overridden as needed to generate correct SQL. - +/** + * This class generate SQL code to be used against MySQL + * It extends XMLDBgenerator so everything can be + * overridden as needed to generate correct SQL. + * + * @package core_ddl + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ class mysql_sql_generator extends sql_generator { -/// Only set values that are different from the defaults present in XMLDBgenerator + // Only set values that are different from the defaults present in XMLDBgenerator - public $quote_string = '`'; // String used to quote names + /** @var string Used to quote names. */ + public $quote_string = '`'; - public $default_for_char = ''; // To define the default to set for NOT NULLs CHARs without default (null=do nothing) + /** @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).*/ + public $default_for_char = ''; - public $drop_default_value_required = true; //To specify if the generator must use some DEFAULT clause to drop defaults - public $drop_default_value = NULL; //The DEFAULT clause required to drop defaults + /** @var bool To specify if the generator must use some DEFAULT clause to drop defaults.*/ + public $drop_default_value_required = true; - public $primary_key_name = ''; //To force primary key names to one string (null=no force) + /** @var string The DEFAULT clause required to drop defaults.*/ + public $drop_default_value = null; - public $drop_primary_key = 'ALTER TABLE TABLENAME DROP PRIMARY KEY'; // Template to drop PKs - // with automatic replace for TABLENAME and KEYNAME + /** @var string To force primary key names to one string (null=no force).*/ + public $primary_key_name = ''; - public $drop_unique_key = 'ALTER TABLE TABLENAME DROP KEY KEYNAME'; // Template to drop UKs - // with automatic replace for TABLENAME and KEYNAME + /** @var string Template to drop PKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ + public $drop_primary_key = 'ALTER TABLE TABLENAME DROP PRIMARY KEY'; - public $drop_foreign_key = 'ALTER TABLE TABLENAME DROP FOREIGN KEY KEYNAME'; // Template to drop FKs - // with automatic replace for TABLENAME and KEYNAME + /** @var string Template to drop UKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ + public $drop_unique_key = 'ALTER TABLE TABLENAME DROP KEY KEYNAME'; - public $sequence_extra_code = false; //Does the generator need to add extra code to generate the sequence fields - public $sequence_name = 'auto_increment'; //Particular name for inline sequences in this generator + /** @var string Template to drop FKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ + public $drop_foreign_key = 'ALTER TABLE TABLENAME DROP FOREIGN KEY KEYNAME'; + + /** @var bool True if the generator needs to add extra code to generate the sequence fields.*/ + public $sequence_extra_code = false; + + /** @var string The particular name for inline sequences in this generator.*/ + public $sequence_name = 'auto_increment'; public $add_after_clause = true; // Does the generator need to add the after clause for fields - public $concat_character = null; //Characters to be used as concatenation operator. If not defined - //MySQL CONCAT function will be use + /** @var string Characters to be used as concatenation operator.*/ + public $concat_character = null; - public $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY COLUMN COLUMNSPECS'; //The SQL template to alter columns + /** @var string The SQL template to alter columns where the 'TABLENAME' and 'COLUMNSPECS' keywords are dynamically replaced.*/ + public $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY COLUMN COLUMNSPECS'; - public $drop_index_sql = 'ALTER TABLE TABLENAME DROP INDEX INDEXNAME'; //SQL sentence to drop one index - //TABLENAME, INDEXNAME are dynamically replaced + /** @var string SQL sentence to drop one index where 'TABLENAME', 'INDEXNAME' keywords are dynamically replaced.*/ + public $drop_index_sql = 'ALTER TABLE TABLENAME DROP INDEX INDEXNAME'; - public $rename_index_sql = null; //SQL sentence to rename one index (MySQL doesn't support this!) - //TABLENAME, OLDINDEXNAME, NEWINDEXNAME are dynamically replaced + /** @var string SQL sentence to rename one index where 'TABLENAME', 'OLDINDEXNAME' and 'NEWINDEXNAME' are dynamically replaced.*/ + public $rename_index_sql = null; - public $rename_key_sql = null; //SQL sentence to rename one key (MySQL doesn't support this!) - //TABLENAME, OLDKEYNAME, NEWKEYNAME are dynamically replaced + /** @var string SQL sentence to rename one key 'TABLENAME', 'OLDKEYNAME' and 'NEWKEYNAME' are dynamically replaced.*/ + public $rename_key_sql = null; /** * Reset a sequence to the id field of a table. - * @param string $table name of table or xmldb_table object - * @return array sql commands to execute + * + * @param xmldb_table|string $table name of table or the table object. + * @return array of sql statements */ public function getResetSequenceSQL($table) { @@ -96,7 +110,11 @@ class mysql_sql_generator extends sql_generator { /** * Given one correct xmldb_table, returns the SQL statements - * to create it (inside one array) + * to create it (inside one array). + * + * @param xmldb_table $xmldb_table An xmldb_table instance. + * @return array An array of SQL statements, starting with the table creation SQL followed + * by any of its comments, indexes and sequence creation SQL statements. */ public function getCreateTableSQL($xmldb_table) { // first find out if want some special db engine @@ -124,7 +142,10 @@ class mysql_sql_generator extends sql_generator { /** * Given one correct xmldb_table, returns the SQL statements - * to create temporary table (inside one array) + * to create temporary table (inside one array). + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array of sql statements */ public function getCreateTempTableSQL($xmldb_table) { $this->temptables->add_temptable($xmldb_table->getName()); @@ -150,7 +171,12 @@ class mysql_sql_generator extends sql_generator { } /** - * Given one XMLDB Type, length and decimals, returns the DB proper SQL type + * Given one XMLDB Type, length and decimals, returns the DB proper SQL type. + * + * @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants. + * @param int $xmldb_length The length of that data type. + * @param int $xmldb_decimals The decimal places of precision of the data type. + * @return string The DB defined data type. */ public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) { @@ -219,26 +245,35 @@ class mysql_sql_generator extends sql_generator { } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to create its default + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default * (usually invoked from getModifyDefaultSQL() + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. */ public function getCreateDefaultSQL($xmldb_table, $xmldb_field) { - /// Just a wrapper over the getAlterFieldSQL() function for MySQL that - /// is capable of handling defaults + // Just a wrapper over the getAlterFieldSQL() function for MySQL that + // is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** * Given one correct xmldb_field and the new name, returns the SQL statements - * to rename it (inside one array) - * MySQL is pretty different from the standard to justify this overloading + * to rename it (inside one array). + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to get the renamed field from. + * @param string $newname The new name to rename the field to. + * @return array The SQL statements for renaming the field. */ public function getRenameFieldSQL($xmldb_table, $xmldb_field, $newname) { + // NOTE: MySQL is pretty different from the standard to justify this overloading. - /// Need a clone of xmldb_field to perform the change leaving original unmodified + // Need a clone of xmldb_field to perform the change leaving original unmodified $xmldb_field_clone = clone($xmldb_field); - /// Change the name of the field to perform the change + // Change the name of the field to perform the change $xmldb_field_clone->setName($newname); $fieldsql = $this->getFieldSQL($xmldb_table, $xmldb_field_clone); @@ -252,15 +287,26 @@ class mysql_sql_generator extends sql_generator { /** * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default * (usually invoked from getModifyDefaultSQL() + * + * Note that this method may be dropped in future. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. + * + * @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL() */ public function getDropDefaultSQL($xmldb_table, $xmldb_field) { - /// Just a wrapper over the getAlterFieldSQL() function for MySQL that - /// is capable of handling defaults + // Just a wrapper over the getAlterFieldSQL() function for MySQL that + // is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** - * Returns the code (in array) needed to add one comment to the table + * Returns the code (array of statements) needed to add one comment to the table. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array Array of SQL statements to add one comment to the table. */ function getCommentSQL ($xmldb_table) { $comment = ''; @@ -273,25 +319,33 @@ class mysql_sql_generator extends sql_generator { } /** - * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg) - * return if such name is currently in use (true) or no (false) - * (invoked from getNameForObject() + * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg). + * + * (MySQL requires the whole xmldb_table object to be specified, so we add it always) + * + * This is invoked from getNameForObject(). + * Only some DB have this implemented. + * + * @param string $object_name The object's name to check for. + * @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg). + * @param string $table_name The table's name to check in + * @return bool If such name is currently in use (true) or no (false) */ public function isNameInUse($object_name, $type, $table_name) { - /// Calculate the real table name + // Calculate the real table name $xmldb_table = new xmldb_table($table_name); $tname = $this->getTableName($xmldb_table); switch($type) { case 'ix': case 'uix': - /// First of all, check table exists + // First of all, check table exists $metatables = $this->mdb->get_tables(); if (isset($metatables[$tname])) { - /// Fetch all the indexes in the table + // Fetch all the indexes in the table if ($indexes = $this->mdb->get_indexes($tname)) { - /// Look for existing index in array + // Look for existing index in array if (isset($indexes[$object_name])) { return true; } @@ -305,10 +359,11 @@ class mysql_sql_generator extends sql_generator { /** * Returns an array of reserved words (lowercase) for this DB + * @return array An array of database specific reserved words */ public static function getReservedWords() { - /// This file contains the reserved words for MySQL databases - /// from http://dev.mysql.com/doc/refman/6.0/en/reserved-words.html + // This file contains the reserved words for MySQL databases + // from http://dev.mysql.com/doc/refman/6.0/en/reserved-words.html $reserved_words = array ( 'accessible', 'add', 'all', 'alter', 'analyze', 'and', 'as', 'asc', 'asensitive', 'before', 'between', 'bigint', 'binary', diff --git a/lib/ddl/oracle_sql_generator.php b/lib/ddl/oracle_sql_generator.php index 312c97d4e03..e096c871ec2 100644 --- a/lib/ddl/oracle_sql_generator.php +++ b/lib/ddl/oracle_sql_generator.php @@ -1,5 +1,4 @@ . - /** * Oracle specific SQL code generator. * - * @package core - * @subpackage ddl_generator + * @package core_ddl * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later @@ -30,37 +27,61 @@ defined('MOODLE_INTERNAL') || die(); require_once($CFG->libdir.'/ddl/sql_generator.php'); -/// This class generate SQL code to be used against Oracle -/// It extends XMLDBgenerator so everything can be -/// overridden as needed to generate correct SQL. - +/** + * This class generate SQL code to be used against Oracle + * It extends XMLDBgenerator so everything can be + * overridden as needed to generate correct SQL. + * + * @package core_ddl + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ class oracle_sql_generator extends sql_generator { -/// Only set values that are different from the defaults present in XMLDBgenerator + // Only set values that are different from the defaults present in XMLDBgenerator - public $statement_end = "\n/"; // String to be automatically added at the end of each statement - // Using "/" because the standard ";" isn't good for stored procedures (triggers) + /** + * @var string To be automatically added at the end of each statement. + * note: Using "/" because the standard ";" isn't good for stored procedures (triggers) + */ + public $statement_end = "\n/"; - public $number_type = 'NUMBER'; // Proper type for NUMBER(x) in this DB + /** @var string Proper type for NUMBER(x) in this DB. */ + public $number_type = 'NUMBER'; - public $default_for_char = ' '; // To define the default to set for NOT NULLs CHARs without default (null=do nothing) - // Using this whitespace here because Oracle doesn't distinguish empty and null! :-( + /** + * @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing). + * note: Using this whitespace here because Oracle doesn't distinguish empty and null! :-( + */ + public $default_for_char = ' '; - public $drop_default_value_required = true; //To specify if the generator must use some DEFAULT clause to drop defaults - public $drop_default_value = NULL; //The DEFAULT clause required to drop defaults + /** @var bool To specify if the generator must use some DEFAULT clause to drop defaults.*/ + public $drop_default_value_required = true; - public $default_after_null = false; //To decide if the default clause of each field must go after the null clause + /** @var string The DEFAULT clause required to drop defaults.*/ + public $drop_default_value = null; - public $sequence_extra_code = true; //Does the generator need to add extra code to generate the sequence fields - public $sequence_name = ''; //Particular name for inline sequences in this generator - public $sequence_cache_size = 20; //Size of the sequences values cache (20 = Oracle Default) + /** @var bool To decide if the default clause of each field must go after the null clause.*/ + public $default_after_null = false; - public $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY (COLUMNSPECS)'; //The SQL template to alter columns + /** @var bool True if the generator needs to add extra code to generate the sequence fields.*/ + public $sequence_extra_code = true; + + /** @var string The particular name for inline sequences in this generator.*/ + public $sequence_name = ''; + + /** @var string The SQL template to alter columns where the 'TABLENAME' and 'COLUMNSPECS' keywords are dynamically replaced.*/ + public $alter_column_sql = 'ALTER TABLE TABLENAME MODIFY (COLUMNSPECS)'; + + /** @var int var ugly Oracle hack - size of the sequences values cache (20 = Default)*/ + public $sequence_cache_size = 20; /** * Reset a sequence to the id field of a table. - * @param string $table name of table or xmldb_table object - * @return array sql commands to execute + * + * @param xmldb_table|string $table name of table or the table object. + * @return array of sql statements */ public function getResetSequenceSQL($table) { @@ -78,7 +99,7 @@ class oracle_sql_generator extends sql_generator { $seqname = $this->getSequenceFromDB($xmldb_table); if (!$seqname) { - /// Fallback, seqname not found, something is wrong. Inform and use the alternative getNameForObject() method + // Fallback, seqname not found, something is wrong. Inform and use the alternative getNameForObject() method $seqname = $this->getNameForObject($table, 'id', 'seq'); } @@ -95,14 +116,14 @@ class oracle_sql_generator extends sql_generator { * @return string the correct name of the table */ public function getTableName(xmldb_table $xmldb_table, $quoted=true) { - /// Get the name, supporting special oci names for temp tables + // Get the name, supporting special oci names for temp tables if ($this->temptables->is_temptable($xmldb_table->getName())) { $tablename = $this->temptables->get_correct_name($xmldb_table->getName()); } else { $tablename = $this->prefix . $xmldb_table->getName(); } - /// Apply quotes optionally + // Apply quotes optionally if ($quoted) { $tablename = $this->getEncQuoted($tablename); } @@ -112,7 +133,10 @@ class oracle_sql_generator extends sql_generator { /** * Given one correct xmldb_table, returns the SQL statements - * to create temporary table (inside one array) + * to create temporary table (inside one array). + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array of sql statements */ public function getCreateTempTableSQL($xmldb_table) { $this->temptables->add_temptable($xmldb_table->getName()); @@ -138,7 +162,12 @@ class oracle_sql_generator extends sql_generator { } /** - * Given one XMLDB Type, length and decimals, returns the DB proper SQL type + * Given one XMLDB Type, length and decimals, returns the DB proper SQL type. + * + * @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants. + * @param int $xmldb_length The length of that data type. + * @param int $xmldb_decimals The decimal places of precision of the data type. + * @return string The DB defined data type. */ public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) { @@ -152,7 +181,7 @@ class oracle_sql_generator extends sql_generator { case XMLDB_TYPE_FLOAT: case XMLDB_TYPE_NUMBER: $dbtype = $this->number_type; - /// 38 is the max allowed + // 38 is the max allowed if ($xmldb_length > 38) { $xmldb_length = 38; } @@ -188,7 +217,12 @@ class oracle_sql_generator extends sql_generator { } /** - * Returns the code needed to create one sequence for the xmldb_table and xmldb_field passes + * Returns the code (array of statements) needed + * to create one sequence for the xmldb_table and xmldb_field passed in. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create the sequence. */ public function getCreateSequenceSQL($xmldb_table, $xmldb_field) { @@ -207,6 +241,11 @@ class oracle_sql_generator extends sql_generator { /** * Returns the code needed to create one trigger for the xmldb_table and xmldb_field passed + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @param string $sequence_name + * @return array Array of SQL statements to create the sequence. */ public function getCreateTriggerSQL($xmldb_table, $xmldb_field, $sequence_name) { @@ -228,6 +267,11 @@ class oracle_sql_generator extends sql_generator { /** * Returns the code needed to drop one sequence for the xmldb_table and xmldb_field passed * Can, optionally, specify if the underlying trigger will be also dropped + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @param bool $include_trigger + * @return array Array of SQL statements to create the sequence. */ public function getDropSequenceSQL($xmldb_table, $xmldb_field, $include_trigger=false) { @@ -245,7 +289,10 @@ class oracle_sql_generator extends sql_generator { } /** - * Returns the code (in array) needed to add one comment to the table + * Returns the code (array of statements) needed to add one comment to the table. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array Array of SQL statements to add one comment to the table. */ function getCommentSQL ($xmldb_table) { @@ -257,6 +304,9 @@ class oracle_sql_generator extends sql_generator { /** * Returns the code (array of statements) needed to execute extra statements on table drop + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array Array of extra SQL statements to drop a table. */ public function getDropTableExtraSQL($xmldb_table) { $xmldb_field = new xmldb_field('id'); // Fields having sequences should be exclusively, id. @@ -264,7 +314,11 @@ class oracle_sql_generator extends sql_generator { } /** - * Returns the code (array of statements) needed to execute extra statements on table rename + * Returns the code (array of statements) needed to execute extra statements on table rename. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param string $newname The new name for the table. + * @return array Array of extra SQL statements to rename a table. */ public function getRenameTableExtraSQL($xmldb_table, $newname) { @@ -278,28 +332,36 @@ class oracle_sql_generator extends sql_generator { $oldtriggername = $this->getTriggerFromDB($xmldb_table); $newtriggername = $this->getNameForObject($newname, $xmldb_field->getName(), 'trg'); - /// Drop old trigger (first of all) + // Drop old trigger (first of all) $results[] = "DROP TRIGGER " . $oldtriggername; - /// Rename the sequence, disablig CACHE before and enablig it later - /// to avoid consuming of values on rename + // Rename the sequence, disablig CACHE before and enablig it later + // to avoid consuming of values on rename $results[] = 'ALTER SEQUENCE ' . $oldseqname . ' NOCACHE'; $results[] = 'RENAME ' . $oldseqname . ' TO ' . $newseqname; $results[] = 'ALTER SEQUENCE ' . $newseqname . ' CACHE ' . $this->sequence_cache_size; - /// Create new trigger - $newt = new xmldb_table($newname); /// Temp table for trigger code generation + // Create new trigger + $newt = new xmldb_table($newname); // Temp table for trigger code generation $results = array_merge($results, $this->getCreateTriggerSQL($newt, $xmldb_field, $newseqname)); return $results; } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table. + * * Oracle has some severe limits: * - clob and blob fields doesn't allow type to be specified * - error is dropped if the null/not null clause is specified and hasn't changed * - changes in precision/decimals of numeric fields drop an ORA-1440 error + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from. + * @param string $skip_type_clause The type clause on alter columns, NULL by default. + * @param string $skip_default_clause The default clause on alter columns, NULL by default. + * @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default. + * @return string The field altering SQL statement. */ public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) { @@ -307,20 +369,20 @@ class oracle_sql_generator extends sql_generator { $skip_default_clause = is_null($skip_default_clause) ? $this->alter_column_skip_default : $skip_default_clause; $skip_notnull_clause = is_null($skip_notnull_clause) ? $this->alter_column_skip_notnull : $skip_notnull_clause; - $results = array(); /// To store all the needed SQL commands + $results = array(); // To store all the needed SQL commands - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $xmldb_field->getName(); - /// Take a look to field metadata + // Take a look to field metadata $meta = $this->mdb->get_columns($xmldb_table->getName()); $metac = $meta[$fieldname]; $oldmetatype = $metac->meta_type; $oldlength = $metac->max_length; - /// To calculate the oldlength if the field is numeric, we need to perform one extra query - /// because ADOdb has one bug here. http://phplens.com/lens/lensforum/msgs.php?id=15883 + // To calculate the oldlength if the field is numeric, we need to perform one extra query + // because ADOdb has one bug here. http://phplens.com/lens/lensforum/msgs.php?id=15883 if ($oldmetatype == 'N') { $uppertablename = strtoupper($tablename); $upperfieldname = strtoupper($fieldname); @@ -343,7 +405,7 @@ class oracle_sql_generator extends sql_generator { $from_temp_fields = false; //By default don't assume we are going to use temporal fields - /// Detect if we are changing the type of the column + // Detect if we are changing the type of the column if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && $oldmetatype == 'I') || ($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') || ($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') || @@ -352,14 +414,14 @@ class oracle_sql_generator extends sql_generator { ($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) { $typechanged = false; } - /// Detect if precision has changed + // Detect if precision has changed if (($xmldb_field->getType() == XMLDB_TYPE_TEXT) || ($xmldb_field->getType() == XMLDB_TYPE_BINARY) || ($oldlength == -1) || ($xmldb_field->getLength() == $oldlength)) { $precisionchanged = false; } - /// Detect if decimal has changed + // Detect if decimal has changed if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER) || ($xmldb_field->getType() == XMLDB_TYPE_CHAR) || ($xmldb_field->getType() == XMLDB_TYPE_TEXT) || @@ -369,29 +431,29 @@ class oracle_sql_generator extends sql_generator { ($xmldb_field->getDecimals() == $olddecimals)) { $decimalchanged = false; } - /// Detect if we are changing the default + // Detect if we are changing the default if (($xmldb_field->getDefault() === null && $olddefault === null) || ($xmldb_field->getDefault() === $olddefault) || //Check both equality and ("'" . $xmldb_field->getDefault() . "'" === $olddefault)) { //Equality with quotes because ADOdb returns the default with quotes $defaultchanged = false; } - /// Detect if we are changing the nullability + // Detect if we are changing the nullability if (($xmldb_field->getNotnull() === $oldnotnull)) { $notnullchanged = false; } - /// If type has changed or precision or decimal has changed and we are in one numeric field - /// - create one temp column with the new specs - /// - fill the new column with the values from the old one - /// - drop the old column - /// - rename the temp column to the original name + // If type has changed or precision or decimal has changed and we are in one numeric field + // - create one temp column with the new specs + // - fill the new column with the values from the old one + // - drop the old column + // - rename the temp column to the original name if (($typechanged) || (($oldmetatype == 'N' || $oldmetatype == 'I') && ($precisionchanged || $decimalchanged))) { $tempcolname = $xmldb_field->getName() . '___tmp'; // Short tmp name, surely not conflicting ever if (strlen($tempcolname) > 30) { // Safeguard we don't excess the 30cc limit $tempcolname = 'ongoing_alter_column_tmp'; } - /// Prevent temp field to have both NULL/NOT NULL and DEFAULT constraints + // Prevent temp field to have both NULL/NOT NULL and DEFAULT constraints $skip_notnull_clause = true; $skip_default_clause = true; $xmldb_field->setName($tempcolname); @@ -400,9 +462,9 @@ class oracle_sql_generator extends sql_generator { if (isset($meta[$tempcolname])) { $results = array_merge($results, $this->getDropFieldSQL($xmldb_table, $xmldb_field)); } - /// Create the temporal column + // Create the temporal column $results = array_merge($results, $this->getAddFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_type_clause, $skip_notnull_clause)); - /// Copy contents from original col to the temporal one + // Copy contents from original col to the temporal one // From TEXT to integer/number we need explicit conversion if ($oldmetatype == 'X' && $xmldb_field->GetType() == XMLDB_TYPE_INTEGER) { @@ -414,47 +476,47 @@ class oracle_sql_generator extends sql_generator { } else { $results[] = 'UPDATE ' . $tablename . ' SET ' . $tempcolname . ' = ' . $fieldname; } - /// Drop the old column + // Drop the old column $xmldb_field->setName($fieldname); //Set back the original field name $results = array_merge($results, $this->getDropFieldSQL($xmldb_table, $xmldb_field)); - /// Rename the temp column to the original one + // Rename the temp column to the original one $results[] = 'ALTER TABLE ' . $tablename . ' RENAME COLUMN ' . $tempcolname . ' TO ' . $fieldname; - /// Mark we have performed one change based in temp fields + // Mark we have performed one change based in temp fields $from_temp_fields = true; - /// Re-enable the notnull and default sections so the general AlterFieldSQL can use it + // Re-enable the notnull and default sections so the general AlterFieldSQL can use it $skip_notnull_clause = false; $skip_default_clause = false; - /// Dissable the type section because we have done it with the temp field + // Disable the type section because we have done it with the temp field $skip_type_clause = true; - /// If new field is nullable, nullability hasn't changed + // If new field is nullable, nullability hasn't changed if (!$xmldb_field->getNotnull()) { $notnullchanged = false; } - /// If new field hasn't default, default hasn't changed + // If new field hasn't default, default hasn't changed if ($xmldb_field->getDefault() === null) { $defaultchanged = false; } } - /// If type and precision and decimals hasn't changed, prevent the type clause + // If type and precision and decimals hasn't changed, prevent the type clause if (!$typechanged && !$precisionchanged && !$decimalchanged) { $skip_type_clause = true; } - /// If NULL/NOT NULL hasn't changed - /// prevent null clause to be specified + // If NULL/NOT NULL hasn't changed + // prevent null clause to be specified if (!$notnullchanged) { - $skip_notnull_clause = true; /// Initially, prevent the notnull clause - /// But, if we have used the temp field and the new field is not null, then enforce the not null clause + $skip_notnull_clause = true; // Initially, prevent the notnull clause + // But, if we have used the temp field and the new field is not null, then enforce the not null clause if ($from_temp_fields && $xmldb_field->getNotnull()) { $skip_notnull_clause = false; } } - /// If default hasn't changed - /// prevent default clause to be specified + // If default hasn't changed + // prevent default clause to be specified if (!$defaultchanged) { - $skip_default_clause = true; /// Initially, prevent the default clause - /// But, if we have used the temp field and the new field has default clause, then enforce the default clause + $skip_default_clause = true; // Initially, prevent the default clause + // But, if we have used the temp field and the new field has default clause, then enforce the default clause if ($from_temp_fields) { $default_clause = $this->getDefaultClause($xmldb_field); if ($default_clause) { @@ -463,33 +525,45 @@ class oracle_sql_generator extends sql_generator { } } - /// If arriving here, something is not being skipped (type, notnull, default), calculate the standard AlterFieldSQL + // If arriving here, something is not being skipped (type, notnull, default), calculate the standard AlterFieldSQL if (!$skip_type_clause || !$skip_notnull_clause || !$skip_default_clause) { $results = array_merge($results, parent::getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_default_clause, $skip_notnull_clause)); return $results; } - /// Finally return results + // Finally return results return $results; } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to create its default + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default * (usually invoked from getModifyDefaultSQL() + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. */ public function getCreateDefaultSQL($xmldb_table, $xmldb_field) { - /// Just a wrapper over the getAlterFieldSQL() function for Oracle that - /// is capable of handling defaults + // Just a wrapper over the getAlterFieldSQL() function for Oracle that + // is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needded to drop its default + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default * (usually invoked from getModifyDefaultSQL() + * + * Note that this method may be dropped in future. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. + * + * @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL() */ public function getDropDefaultSQL($xmldb_table, $xmldb_field) { - /// Just a wrapper over the getAlterFieldSQL() function for Oracle that - /// is capable of handling defaults + // Just a wrapper over the getAlterFieldSQL() function for Oracle that + // is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } @@ -499,7 +573,8 @@ class oracle_sql_generator extends sql_generator { * The sequence name for oracle is calculated by looking the corresponding * trigger and retrieving the sequence name from it (because sequences are * independent elements) - * If no sequence is found, returns false + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return string|bool If no sequence is found, returns false */ public function getSequenceFromDB($xmldb_table) { @@ -511,7 +586,7 @@ class oracle_sql_generator extends sql_generator { FROM user_triggers WHERE table_name = ? AND trigger_name LIKE ?", array($tablename, "{$prefixupper}%_ID%_TRG"))) { - /// If trigger found, regexp it looking for the sequence name + // If trigger found, regexp it looking for the sequence name preg_match('/.*SELECT (.*)\.nextval/i', $trigger->trigger_body, $matches); if (isset($matches[1])) { $sequencename = $matches[1]; @@ -524,7 +599,9 @@ class oracle_sql_generator extends sql_generator { /** * Given one xmldb_table returns one string with the trigger * in the table (fetched from DB) - * If no trigger is found, returns false + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return string|bool If no trigger is found, returns false */ public function getTriggerFromDB($xmldb_table) { @@ -543,9 +620,17 @@ class oracle_sql_generator extends sql_generator { } /** - * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg) - * return if such name is currently in use (true) or no (false) - * (invoked from getNameForObject() + * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg). + * + * (MySQL requires the whole xmldb_table object to be specified, so we add it always) + * + * This is invoked from getNameForObject(). + * Only some DB have this implemented. + * + * @param string $object_name The object's name to check for. + * @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg). + * @param string $table_name The table's name to check in + * @return bool If such name is currently in use (true) or no (false) */ public function isNameInUse($object_name, $type, $table_name) { switch($type) { @@ -573,6 +658,11 @@ class oracle_sql_generator extends sql_generator { return false; //No name in use found } + /** + * Adds slashes to string. + * @param string $s + * @return string The escaped string. + */ public function addslashes($s) { // do not use php addslashes() because it depends on PHP quote settings! $s = str_replace("'", "''", $s); @@ -581,10 +671,11 @@ class oracle_sql_generator extends sql_generator { /** * Returns an array of reserved words (lowercase) for this DB + * @return array An array of database specific reserved words */ public static function getReservedWords() { - /// This file contains the reserved words for Oracle databases - /// from http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/ap_keywd.htm + // This file contains the reserved words for Oracle databases + // from http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96540/ap_keywd.htm $reserved_words = array ( 'access', 'add', 'all', 'alter', 'and', 'any', 'as', 'asc', 'audit', 'between', 'by', 'char', diff --git a/lib/ddl/postgres_sql_generator.php b/lib/ddl/postgres_sql_generator.php index 46436fc8156..8d410868e01 100644 --- a/lib/ddl/postgres_sql_generator.php +++ b/lib/ddl/postgres_sql_generator.php @@ -1,5 +1,4 @@ . - /** * PostgreSQL specific SQL code generator. * - * @package core - * @subpackage ddl_generator + * @package core_ddl * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later @@ -30,35 +27,53 @@ defined('MOODLE_INTERNAL') || die(); require_once($CFG->libdir.'/ddl/sql_generator.php'); -/// This class generate SQL code to be used against PostgreSQL -/// It extends XMLDBgenerator so everything can be -/// overridden as needed to generate correct SQL. +/** + * This class generate SQL code to be used against PostgreSQL + * It extends XMLDBgenerator so everything can be + * overridden as needed to generate correct SQL. + * + * @package core_ddl + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ class postgres_sql_generator extends sql_generator { -/// Only set values that are different from the defaults present in XMLDBgenerator + // Only set values that are different from the defaults present in XMLDBgenerator - public $number_type = 'NUMERIC'; // Proper type for NUMBER(x) in this DB + /** @var string Proper type for NUMBER(x) in this DB. */ + public $number_type = 'NUMERIC'; - public $default_for_char = ''; // To define the default to set for NOT NULLs CHARs without default (null=do nothing) + /** @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).*/ + public $default_for_char = ''; - public $sequence_extra_code = false; //Does the generator need to add extra code to generate the sequence fields - public $sequence_name = 'BIGSERIAL'; //Particular name for inline sequences in this generator - public $sequence_name_small = 'SERIAL'; //Particular name for inline sequences in this generator - public $sequence_only = true; //To avoid to output the rest of the field specs, leaving only the name and the sequence_name variable + /** @var bool True if the generator needs to add extra code to generate the sequence fields.*/ + public $sequence_extra_code = false; - public $rename_index_sql = 'ALTER TABLE OLDINDEXNAME RENAME TO NEWINDEXNAME'; //SQL sentence to rename one index - //TABLENAME, OLDINDEXNAME, NEWINDEXNAME are dynamically replaced + /** @var string The particular name for inline sequences in this generator.*/ + public $sequence_name = 'BIGSERIAL'; - public $rename_key_sql = null; //SQL sentence to rename one key (PostgreSQL doesn't support this!) - //TABLENAME, OLDKEYNAME, NEWKEYNAME are dynamically replaced + /** @var string The particular name for inline sequences in this generator.*/ + public $sequence_name_small = 'SERIAL'; - protected $std_strings = null; // '' or \' quotes + /** @var bool To avoid outputting the rest of the field specs, leaving only the name and the sequence_name returned.*/ + public $sequence_only = true; + + /** @var string SQL sentence to rename one index where 'TABLENAME', 'OLDINDEXNAME' and 'NEWINDEXNAME' are dynamically replaced.*/ + public $rename_index_sql = 'ALTER TABLE OLDINDEXNAME RENAME TO NEWINDEXNAME'; + + /** @var string SQL sentence to rename one key 'TABLENAME', 'OLDKEYNAME' and 'NEWKEYNAME' are dynamically replaced.*/ + public $rename_key_sql = null; + + /** @var string type of string quoting used - '' or \' quotes*/ + protected $std_strings = null; /** * Reset a sequence to the id field of a table. - * @param string $table name of table or xmldb_table object - * @return array sql commands to execute + * + * @param xmldb_table|string $table name of table or the table object. + * @return array of sql statements */ public function getResetSequenceSQL($table) { @@ -76,7 +91,10 @@ class postgres_sql_generator extends sql_generator { /** * Given one correct xmldb_table, returns the SQL statements - * to create temporary table (inside one array) + * to create temporary table (inside one array). + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array of sql statements */ public function getCreateTempTableSQL($xmldb_table) { $this->temptables->add_temptable($xmldb_table->getName()); @@ -101,7 +119,12 @@ class postgres_sql_generator extends sql_generator { } /** - * Given one XMLDB Type, length and decimals, returns the DB proper SQL type + * Given one XMLDB Type, length and decimals, returns the DB proper SQL type. + * + * @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants. + * @param int $xmldb_length The length of that data type. + * @param int $xmldb_decimals The decimal places of precision of the data type. + * @return string The DB defined data type. */ public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) { @@ -157,7 +180,10 @@ class postgres_sql_generator extends sql_generator { } /** - * Returns the code (in array) needed to add one comment to the table + * Returns the code (array of statements) needed to add one comment to the table. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array Array of SQL statements to add one comment to the table. */ function getCommentSQL ($xmldb_table) { @@ -168,7 +194,11 @@ class postgres_sql_generator extends sql_generator { } /** - * Returns the code (array of statements) needed to execute extra statements on table rename + * Returns the code (array of statements) needed to execute extra statements on table rename. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param string $newname The new name for the table. + * @return array Array of extra SQL statements to rename a table. */ public function getRenameTableExtraSQL($xmldb_table, $newname) { @@ -181,29 +211,37 @@ class postgres_sql_generator extends sql_generator { $oldseqname = $this->getTableName($xmldb_table) . '_' . $xmldb_field->getName() . '_seq'; $newseqname = $this->getTableName($newt) . '_' . $xmldb_field->getName() . '_seq'; - /// Rename de sequence + // Rename de sequence $results[] = 'ALTER TABLE ' . $oldseqname . ' RENAME TO ' . $newseqname; return $results; } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table. + * * PostgreSQL has some severe limits: * - Any change of type or precision requires a new temporary column to be created, values to * be transfered potentially casting them, to apply defaults if the column is not null and * finally, to rename it * - Changes in null/not null require the SET/DROP NOT NULL clause * - Changes in default require the SET/DROP DEFAULT clause + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from. + * @param string $skip_type_clause The type clause on alter columns, NULL by default. + * @param string $skip_default_clause The default clause on alter columns, NULL by default. + * @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default. + * @return string The field altering SQL statement. */ public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) { - $results = array(); /// To store all the needed SQL commands + $results = array(); // To store all the needed SQL commands - /// Get the normla names of the table and field + // Get the normal names of the table and field $tablename = $xmldb_table->getName(); $fieldname = $xmldb_field->getName(); - /// Take a look to field metadata + // Take a look to field metadata $meta = $this->mdb->get_columns($tablename); $metac = $meta[$xmldb_field->getName()]; $oldmetatype = $metac->meta_type; @@ -218,7 +256,7 @@ class postgres_sql_generator extends sql_generator { $defaultchanged = true; //By default, assume that the column default has changed $notnullchanged = true; //By default, assume that the column notnull has changed - /// Detect if we are changing the type of the column + // Detect if we are changing the type of the column if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER && $oldmetatype == 'I') || ($xmldb_field->getType() == XMLDB_TYPE_NUMBER && $oldmetatype == 'N') || ($xmldb_field->getType() == XMLDB_TYPE_FLOAT && $oldmetatype == 'F') || @@ -227,14 +265,14 @@ class postgres_sql_generator extends sql_generator { ($xmldb_field->getType() == XMLDB_TYPE_BINARY && $oldmetatype == 'B')) { $typechanged = false; } - /// Detect if we are changing the precision + // Detect if we are changing the precision if (($xmldb_field->getType() == XMLDB_TYPE_TEXT) || ($xmldb_field->getType() == XMLDB_TYPE_BINARY) || ($oldlength == -1) || ($xmldb_field->getLength() == $oldlength)) { $precisionchanged = false; } - /// Detect if we are changing the decimals + // Detect if we are changing the decimals if (($xmldb_field->getType() == XMLDB_TYPE_INTEGER) || ($xmldb_field->getType() == XMLDB_TYPE_CHAR) || ($xmldb_field->getType() == XMLDB_TYPE_TEXT) || @@ -244,32 +282,32 @@ class postgres_sql_generator extends sql_generator { ($xmldb_field->getDecimals() == $olddecimals)) { $decimalchanged = false; } - /// Detect if we are changing the default + // Detect if we are changing the default if (($xmldb_field->getDefault() === null && $olddefault === null) || ($xmldb_field->getDefault() === $olddefault)) { $defaultchanged = false; } - /// Detect if we are changing the nullability + // Detect if we are changing the nullability if (($xmldb_field->getNotnull() === $oldnotnull)) { $notnullchanged = false; } - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); - /// Decide if we have changed the column specs (type/precision/decimals) + // Decide if we have changed the column specs (type/precision/decimals) $specschanged = $typechanged || $precisionchanged || $decimalchanged; - /// if specs have changed, need to alter column + // if specs have changed, need to alter column if ($specschanged) { - /// Always drop any exiting default before alter column (some type changes can cause casting error in default for column) + // Always drop any exiting default before alter column (some type changes can cause casting error in default for column) if ($olddefault !== null) { - $results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' DROP DEFAULT'; /// Drop default clause + $results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' DROP DEFAULT'; // Drop default clause } $alterstmt = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $this->getEncQuoted($xmldb_field->getName()) . ' TYPE' . $this->getFieldSQL($xmldb_table, $xmldb_field, null, true, true, null, false); - /// Some castings must be performed explicity (mainly from text|char to numeric|integer) + // Some castings must be performed explicitly (mainly from text|char to numeric|integer) if (($oldmetatype == 'C' || $oldmetatype == 'X') && ($xmldb_field->getType() == XMLDB_TYPE_NUMBER || $xmldb_field->getType() == XMLDB_TYPE_FLOAT)) { $alterstmt .= ' USING CAST('.$fieldname.' AS NUMERIC)'; // from char or text to number or float @@ -280,20 +318,20 @@ class postgres_sql_generator extends sql_generator { $results[] = $alterstmt; } - /// If the default has changed or we have performed one change in specs + // If the default has changed or we have performed one change in specs if ($defaultchanged || $specschanged) { $default_clause = $this->getDefaultClause($xmldb_field); if ($default_clause) { - $sql = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' SET' . $default_clause; /// Add default clause + $sql = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' SET' . $default_clause; // Add default clause $results[] = $sql; } else { - if (!$specschanged) { /// Only drop default if we haven't performed one specs change - $results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' DROP DEFAULT'; /// Drop default clause + if (!$specschanged) { // Only drop default if we haven't performed one specs change + $results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' DROP DEFAULT'; // Drop default clause } } } - /// If the not null has changed + // If the not null has changed if ($notnullchanged) { if ($xmldb_field->getNotnull()) { $results[] = 'ALTER TABLE ' . $tablename . ' ALTER COLUMN ' . $fieldname . ' SET NOT NULL'; @@ -302,30 +340,47 @@ class postgres_sql_generator extends sql_generator { } } - /// Return the results + // Return the results return $results; } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to create its default + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default * (usually invoked from getModifyDefaultSQL() + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. */ public function getCreateDefaultSQL($xmldb_table, $xmldb_field) { - /// Just a wrapper over the getAlterFieldSQL() function for PostgreSQL that - /// is capable of handling defaults + // Just a wrapper over the getAlterFieldSQL() function for PostgreSQL that + // is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } /** * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default * (usually invoked from getModifyDefaultSQL() + * + * Note that this method may be dropped in future. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. + * + * @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL() */ public function getDropDefaultSQL($xmldb_table, $xmldb_field) { - /// Just a wrapper over the getAlterFieldSQL() function for PostgreSQL that - /// is capable of handling defaults + // Just a wrapper over the getAlterFieldSQL() function for PostgreSQL that + // is capable of handling defaults return $this->getAlterFieldSQL($xmldb_table, $xmldb_field); } + /** + * Adds slashes to string. + * @param string $s + * @return string The escaped string. + */ public function addslashes($s) { // Postgres is gradually switching to ANSI quotes, we need to check what is expected if (!isset($this->std_strings)) { @@ -344,33 +399,43 @@ class postgres_sql_generator extends sql_generator { return $s; } -/** - * Given one xmldb_table returns one string with the sequence of the table - * in the table (fetched from DB) - * The sequence name for Postgres has one standard name convention: - * tablename_fieldname_seq - * so we just calculate it and confirm it's present in pg_class - * If no sequence is found, returns false - */ -function getSequenceFromDB($xmldb_table) { + /** + * Given one xmldb_table returns one string with the sequence of the table + * in the table (fetched from DB) + * The sequence name for Postgres has one standard name convention: + * tablename_fieldname_seq + * so we just calculate it and confirm it's present in pg_class + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return string|bool If no sequence is found, returns false + */ + function getSequenceFromDB($xmldb_table) { - $tablename = $this->getTableName($xmldb_table); - $sequencename = $tablename . '_id_seq'; + $tablename = $this->getTableName($xmldb_table); + $sequencename = $tablename . '_id_seq'; - if (!$this->mdb->get_record_sql("SELECT * - FROM pg_class - WHERE relname = ? AND relkind = 'S'", - array($sequencename))) { - $sequencename = false; + if (!$this->mdb->get_record_sql("SELECT * + FROM pg_class + WHERE relname = ? AND relkind = 'S'", + array($sequencename))) { + $sequencename = false; + } + + return $sequencename; } - return $sequencename; -} - /** - * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg) - * return if such name is currently in use (true) or no (false) - * (invoked from getNameForObject() + * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg). + * + * (MySQL requires the whole xmldb_table object to be specified, so we add it always) + * + * This is invoked from getNameForObject(). + * Only some DB have this implemented. + * + * @param string $object_name The object's name to check for. + * @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg). + * @param string $table_name The table's name to check in + * @return bool If such name is currently in use (true) or no (false) */ public function isNameInUse($object_name, $type, $table_name) { switch($type) { @@ -406,10 +471,11 @@ function getSequenceFromDB($xmldb_table) { /** * Returns an array of reserved words (lowercase) for this DB + * @return array An array of database specific reserved words */ public static function getReservedWords() { - /// This file contains the reserved words for PostgreSQL databases - /// http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html + // This file contains the reserved words for PostgreSQL databases + // http://www.postgresql.org/docs/current/static/sql-keywords-appendix.html $reserved_words = array ( 'all', 'analyse', 'analyze', 'and', 'any', 'array', 'as', 'asc', 'asymmetric', 'authorization', 'between', 'binary', 'both', 'case', diff --git a/lib/ddl/sql_generator.php b/lib/ddl/sql_generator.php index 4cc1eedb8b3..805189a3419 100644 --- a/lib/ddl/sql_generator.php +++ b/lib/ddl/sql_generator.php @@ -14,16 +14,13 @@ // You should have received a copy of the GNU General Public License // along with Moodle. If not, see . - /** * This class represent the base generator class where all the needed functions to generate proper SQL are defined. * * The rest of classes will inherit, by default, the same logic. * Functions will be overridden as needed to generate correct SQL. * - * @package core - * @category ddl - * @subpackage ddl + * @package core_ddl * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later @@ -34,19 +31,17 @@ defined('MOODLE_INTERNAL') || die(); /** * Abstract sql generator class, base for all db specific implementations. * - * @package core - * @category ddl - * @subpackage ddl + * @package core_ddl * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ abstract class sql_generator { -/// Please, avoid editing this defaults in this base class! -/// It could change the behaviour of the rest of generators -/// that, by default, inherit this configuration. -/// To change any of them, do it in extended classes instead. + // Please, avoid editing this defaults in this base class! + // It could change the behaviour of the rest of generators + // that, by default, inherit this configuration. + // To change any of them, do it in extended classes instead. /** @var string Used to quote names. */ public $quote_string = '"'; @@ -55,10 +50,11 @@ abstract class sql_generator { public $statement_end = ';'; /** @var bool To decide if we want to quote all the names or only the reserved ones. */ - public $quote_all = false; + public $quote_all = false; /** @var bool To create all the integers as NUMBER(x) (also called DECIMAL, NUMERIC...). */ public $integer_to_number = false; + /** @var bool To create all the floats as NUMBER(x) (also called DECIMAL, NUMERIC...). */ public $float_to_number = false; @@ -70,16 +66,14 @@ abstract class sql_generator { /** @var bool To specify if the generator must use some DEFAULT clause to drop defaults.*/ public $drop_default_value_required = false; + /** @var string The DEFAULT clause required to drop defaults.*/ public $drop_default_value = ''; /** @var bool To decide if the default clause of each field must go after the null clause.*/ public $default_after_null = true; - /** - * @var bool To force the generator if NULL clauses must be specified. It shouldn't be necessary. - * note: some mssql drivers require them or everything is created as NOT NULL :-( - */ + /** @var bool To force the generator if NULL clauses must be specified. It shouldn't be necessary.*/ public $specify_nulls = false; /** @var string To force primary key names to one string (null=no force).*/ @@ -87,34 +81,31 @@ abstract class sql_generator { /** @var bool True if the generator builds primary keys.*/ public $primary_keys = true; + /** @var bool True if the generator builds unique keys.*/ public $unique_keys = false; + /** @var bool True if the generator builds foreign keys.*/ public $foreign_keys = false; - /** - * @var string Template to drop PKs. - * 'TABLENAME' and 'KEYNAME' will be replaced from this template. - */ + /** @var string Template to drop PKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ public $drop_primary_key = 'ALTER TABLE TABLENAME DROP CONSTRAINT KEYNAME'; - /** - * @var string Template to drop UKs. - * 'TABLENAME' and 'KEYNAME' will be replaced from this template. - */ + /** @var string Template to drop UKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ public $drop_unique_key = 'ALTER TABLE TABLENAME DROP CONSTRAINT KEYNAME'; - /** @var string Template to drop FKs. - * 'TABLENAME' and 'KEYNAME' will be replaced from this template. - */ + /** @var string Template to drop FKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ public $drop_foreign_key = 'ALTER TABLE TABLENAME DROP CONSTRAINT KEYNAME'; /** @var bool True if the generator needs to add extra code to generate the sequence fields.*/ public $sequence_extra_code = true; + /** @var string The particular name for inline sequences in this generator.*/ public $sequence_name = 'auto_increment'; + /** @var string|bool Different name for small (4byte) sequences or false if same.*/ public $sequence_name_small = false; + /** * @var bool To avoid outputting the rest of the field specs, leaving only the name and the sequence_name returned. * @see getFieldSQL() @@ -136,9 +127,7 @@ abstract class sql_generator { /** @var int Maximum length for key/index/sequence/trigger/check names (keep 30 for all!).*/ public $names_max_length = 30; - /** @var string Characters to be used as concatenation operator. - * If not defined, MySQL CONCAT function will be used. - */ + /** @var string Characters to be used as concatenation operator. If not defined, MySQL CONCAT function will be used.*/ public $concat_character = '||'; /** @var string SQL sentence to rename one table, both 'OLDNAME' and 'NEWNAME' keywords are dynamically replaced.*/ @@ -179,6 +168,7 @@ abstract class sql_generator { /** @var moodle_database The moodle_database instance.*/ public $mdb; + /** @var Control existing temptables.*/ protected $temptables; @@ -207,6 +197,7 @@ abstract class sql_generator { * @see $statement_end * * @param array|string $input SQL statement(s). + * @return array|string */ public function getEndedStatements($input) { @@ -231,11 +222,11 @@ abstract class sql_generator { if (is_string($table)) { $tablename = $table; } else { - /// Calculate the name of the table + // Calculate the name of the table $tablename = $table->getName(); } - /// get all tables in moodle database + // get all tables in moodle database $tables = $this->mdb->get_tables(); $exists = in_array($tablename, $tables); @@ -244,10 +235,10 @@ abstract class sql_generator { /** * This function will return the SQL code needed to create db tables and statements. + * @see xmldb_structure * * @param xmldb_structure $xmldb_structure An xmldb_structure instance. - * - * @see xmldb_structure + * @return array */ public function getCreateStructureSQL($xmldb_structure) { $results = array(); @@ -272,10 +263,10 @@ abstract class sql_generator { * @return string The correct name of the table. */ public function getTableName(xmldb_table $xmldb_table, $quoted=true) { - /// Get the name + // Get the name $tablename = $this->prefix.$xmldb_table->getName(); - /// Apply quotes optionally + // Apply quotes optionally if ($quoted) { $tablename = $this->getEncQuoted($tablename); } @@ -298,7 +289,7 @@ abstract class sql_generator { $results = array(); //Array where all the sentences will be stored - /// Table header + // Table header $table = 'CREATE TABLE ' . $this->getTableName($xmldb_table) . ' ('; if (!$xmldb_fields = $xmldb_table->getFields()) { @@ -307,7 +298,7 @@ abstract class sql_generator { $sequencefield = null; - /// Add the fields, separated by commas + // Add the fields, separated by commas foreach ($xmldb_fields as $xmldb_field) { if ($xmldb_field->getSequence()) { $sequencefield = $xmldb_field->getName(); @@ -315,21 +306,21 @@ abstract class sql_generator { $table .= "\n " . $this->getFieldSQL($xmldb_table, $xmldb_field); $table .= ','; } - /// Add the keys, separated by commas + // Add the keys, separated by commas if ($xmldb_keys = $xmldb_table->getKeys()) { foreach ($xmldb_keys as $xmldb_key) { if ($keytext = $this->getKeySQL($xmldb_table, $xmldb_key)) { $table .= "\nCONSTRAINT " . $keytext . ','; } - /// If the key is XMLDB_KEY_FOREIGN_UNIQUE, create it as UNIQUE too + // If the key is XMLDB_KEY_FOREIGN_UNIQUE, create it as UNIQUE too if ($xmldb_key->getType() == XMLDB_KEY_FOREIGN_UNIQUE) { - ///Duplicate the key + //Duplicate the key $xmldb_key->setType(XMLDB_KEY_UNIQUE); if ($keytext = $this->getKeySQL($xmldb_table, $xmldb_key)) { $table .= "\nCONSTRAINT " . $keytext . ','; } } - /// make sure sequence field is unique + // make sure sequence field is unique if ($sequencefield and $xmldb_key->getType() == XMLDB_KEY_PRIMARY) { $field = reset($xmldb_key->getFields()); if ($sequencefield === $field) { @@ -338,45 +329,45 @@ abstract class sql_generator { } } } - /// throw error if sequence field does not have unique key defined + // throw error if sequence field does not have unique key defined if ($sequencefield) { throw new ddl_exception('ddsequenceerror', $xmldb_table->getName()); } - /// Table footer, trim the latest comma + // Table footer, trim the latest comma $table = trim($table,','); $table .= "\n)"; - /// Add the CREATE TABLE to results + // Add the CREATE TABLE to results $results[] = $table; - /// Add comments if specified and it exists + // Add comments if specified and it exists if ($this->add_table_comments && $xmldb_table->getComment()) { $comment = $this->getCommentSQL($xmldb_table); - /// Add the COMMENT to results + // Add the COMMENT to results $results = array_merge($results, $comment); } - /// Add the indexes (each one, one statement) + // Add the indexes (each one, one statement) if ($xmldb_indexes = $xmldb_table->getIndexes()) { foreach ($xmldb_indexes as $xmldb_index) { - ///tables do not exist yet, which means indexed can not exist yet + //tables do not exist yet, which means indexed can not exist yet if ($indextext = $this->getCreateIndexSQL($xmldb_table, $xmldb_index)) { $results = array_merge($results, $indextext); } } } - /// Also, add the indexes needed from keys, based on configuration (each one, one statement) + // Also, add the indexes needed from keys, based on configuration (each one, one statement) if ($xmldb_keys = $xmldb_table->getKeys()) { foreach ($xmldb_keys as $xmldb_key) { - /// If we aren't creating the keys OR if the key is XMLDB_KEY_FOREIGN (not underlying index generated - /// automatically by the RDBMS) create the underlying (created by us) index (if doesn't exists) + // If we aren't creating the keys OR if the key is XMLDB_KEY_FOREIGN (not underlying index generated + // automatically by the RDBMS) create the underlying (created by us) index (if doesn't exists) if (!$this->getKeySQL($xmldb_table, $xmldb_key) || $xmldb_key->getType() == XMLDB_KEY_FOREIGN) { - /// Create the interim index + // Create the interim index $index = new xmldb_index('anyname'); $index->setFields($xmldb_key->getFields()); - ///tables do not exist yet, which means indexed can not exist yet + //tables do not exist yet, which means indexed can not exist yet $createindex = false; //By default switch ($xmldb_key->getType()) { case XMLDB_KEY_UNIQUE: @@ -391,7 +382,7 @@ abstract class sql_generator { } if ($createindex) { if ($indextext = $this->getCreateIndexSQL($xmldb_table, $index)) { - /// Add the INDEX to the array + // Add the INDEX to the array $results = array_merge($results, $indextext); } } @@ -399,14 +390,14 @@ abstract class sql_generator { } } - /// Add sequence extra code if needed + // Add sequence extra code if needed if ($this->sequence_extra_code) { - /// Iterate over fields looking for sequences + // Iterate over fields looking for sequences foreach ($xmldb_fields as $xmldb_field) { if ($xmldb_field->getSequence()) { - /// returns an array of statements needed to create one sequence + // returns an array of statements needed to create one sequence $sequence_sentences = $this->getCreateSequenceSQL($xmldb_table, $xmldb_field); - /// Add the SEQUENCE to the array + // Add the SEQUENCE to the array $results = array_merge($results, $sequence_sentences); } } @@ -467,13 +458,13 @@ abstract class sql_generator { $skip_notnull_clause = is_null($skip_notnull_clause) ? $this->alter_column_skip_notnull : $skip_notnull_clause; $specify_nulls_clause = is_null($specify_nulls_clause) ? $this->specify_nulls : $specify_nulls_clause; - /// First of all, convert integers to numbers if defined + // First of all, convert integers to numbers if defined if ($this->integer_to_number) { if ($xmldb_field->getType() == XMLDB_TYPE_INTEGER) { $xmldb_field->setType(XMLDB_TYPE_NUMBER); } } - /// Same for floats + // Same for floats if ($this->float_to_number) { if ($xmldb_field->getType() == XMLDB_TYPE_FLOAT) { $xmldb_field->setType(XMLDB_TYPE_NUMBER); @@ -481,19 +472,19 @@ abstract class sql_generator { } $field = ''; // Let's accumulate the whole expression based on params and settings - /// The name + // The name if ($specify_field_name) { $field .= $this->getEncQuoted($xmldb_field->getName()); } - /// The type and length only if we don't want to skip it + // The type and length only if we don't want to skip it if (!$skip_type_clause) { - /// The type and length + // The type and length $field .= ' ' . $this->getTypeSQL($xmldb_field->getType(), $xmldb_field->getLength(), $xmldb_field->getDecimals()); } - /// note: unsigned is not supported any more since moodle 2.3, all numbers are signed - /// Calculate the not null clause + // note: unsigned is not supported any more since moodle 2.3, all numbers are signed + // Calculate the not null clause $notnull = ''; - /// Only if we don't want to skip it + // Only if we don't want to skip it if (!$skip_notnull_clause) { if ($xmldb_field->getNotNull()) { $notnull = ' NOT NULL'; @@ -503,18 +494,18 @@ abstract class sql_generator { } } } - /// Calculate the default clause + // Calculate the default clause $default_clause = ''; if (!$skip_default_clause) { //Only if we don't want to skip it $default_clause = $this->getDefaultClause($xmldb_field); } - /// Based on default_after_null, set both clauses properly + // Based on default_after_null, set both clauses properly if ($this->default_after_null) { $field .= $notnull . $default_clause; } else { $field .= $default_clause . $notnull; } - /// The sequence + // The sequence if ($xmldb_field->getSequence()) { if($xmldb_field->getLength()<=9 && $this->sequence_name_small) { $sequencename=$this->sequence_name_small; @@ -523,8 +514,8 @@ abstract class sql_generator { } $field .= ' ' . $sequencename; if ($this->sequence_only) { - /// We only want the field name and sequence name to be printed - /// so, calculate it and return + // We only want the field name and sequence name to be printed + // so, calculate it and return $sql = $this->getEncQuoted($xmldb_field->getName()) . ' ' . $sequencename; return $sql; } @@ -596,15 +587,15 @@ abstract class sql_generator { $default = $xmldb_field->getDefault(); } } else { - /// We force default '' for not null char columns without proper default - /// some day this should be out! + // We force default '' for not null char columns without proper default + // some day this should be out! if ($this->default_for_char !== NULL && $xmldb_field->getType() == XMLDB_TYPE_CHAR && $xmldb_field->getNotNull()) { $default = "'" . $this->default_for_char . "'"; } else { - /// If the DB requires to explicity define some clause to drop one default, do it here - /// never applying defaults to TEXT and BINARY fields + // If the DB requires to explicity define some clause to drop one default, do it here + // never applying defaults to TEXT and BINARY fields if ($this->drop_default_value_required && $xmldb_field->getType() != XMLDB_TYPE_TEXT && $xmldb_field->getType() != XMLDB_TYPE_BINARY && !$xmldb_field->getNotNull()) { @@ -651,7 +642,7 @@ abstract class sql_generator { $results[] = $rename; - /// Call to getRenameTableExtraSQL() override if needed + // Call to getRenameTableExtraSQL() override if needed $extra_sentences = $this->getRenameTableExtraSQL($xmldb_table, $newname); $results = array_merge($results, $extra_sentences); @@ -673,7 +664,7 @@ abstract class sql_generator { $results[] = $drop; - /// call to getDropTableExtraSQL(), override if needed + // call to getDropTableExtraSQL(), override if needed $extra_sentences = $this->getDropTableExtraSQL($xmldb_table); $results = array_merge($results, $extra_sentences); @@ -698,15 +689,15 @@ abstract class sql_generator { $results = array(); - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); - /// Build the standard alter table add + // Build the standard alter table add $sql = $this->getFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_default_clause, $skip_notnull_clause); $altertable = 'ALTER TABLE ' . $tablename . ' ADD ' . $sql; - /// Add the after clause if necesary + // Add the after clause if necessary if ($this->add_after_clause && $xmldb_field->getPrevious()) { $altertable .= ' AFTER ' . $this->getEncQuoted($xmldb_field->getPrevious()); } @@ -726,11 +717,11 @@ abstract class sql_generator { $results = array(); - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); - /// Build the standard alter table drop + // Build the standard alter table drop $results[] = 'ALTER TABLE ' . $tablename . ' DROP COLUMN ' . $fieldname; return $results; @@ -754,11 +745,11 @@ abstract class sql_generator { $results = array(); - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); - /// Build de alter sentence using the alter_column_sql template + // Build de alter sentence using the alter_column_sql template $alter = str_replace('TABLENAME', $this->getTableName($xmldb_table), $this->alter_column_sql); $colspec = $this->getFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause, $skip_default_clause, @@ -766,12 +757,12 @@ abstract class sql_generator { true); $alter = str_replace('COLUMNSPECS', $colspec, $alter); - /// Add the after clause if necesary + // Add the after clause if necessary if ($this->add_after_clause && $xmldb_field->getPrevious()) { $alter .= ' after ' . $this->getEncQuoted($xmldb_field->getPrevious()); } - /// Build the standard alter table modify + // Build the standard alter table modify $results[] = $alter; return $results; @@ -788,11 +779,11 @@ abstract class sql_generator { $results = array(); - /// Get the quoted name of the table and field + // Get the quoted name of the table and field $tablename = $this->getTableName($xmldb_table); $fieldname = $this->getEncQuoted($xmldb_field->getName()); - /// Decide if we are going to create/modify or to drop the default + // Decide if we are going to create/modify or to drop the default if ($xmldb_field->getDefault() === null) { $results = $this->getDropDefaultSQL($xmldb_table, $xmldb_field); //Drop } else { @@ -815,13 +806,13 @@ abstract class sql_generator { $results = array(); //Array where all the sentences will be stored - /// Although this is checked in database_manager::rename_field() - double check - /// that we aren't trying to rename one "id" field. Although it could be - /// implemented (if adding the necessary code to rename sequences, defaults, - /// triggers... and so on under each getRenameFieldExtraSQL() function, it's - /// better to forbid it, mainly because this field is the default PK and - /// in the future, a lot of FKs can be pointing here. So, this field, more - /// or less, must be considered immutable! + // Although this is checked in database_manager::rename_field() - double check + // that we aren't trying to rename one "id" field. Although it could be + // implemented (if adding the necessary code to rename sequences, defaults, + // triggers... and so on under each getRenameFieldExtraSQL() function, it's + // better to forbid it, mainly because this field is the default PK and + // in the future, a lot of FKs can be pointing here. So, this field, more + // or less, must be considered immutable! if ($xmldb_field->getName() == 'id') { return array(); } @@ -832,7 +823,7 @@ abstract class sql_generator { $results[] = $rename; - /// Call to getRenameFieldExtraSQL(), override if needed + // Call to getRenameFieldExtraSQL(), override if needed $extra_sentences = $this->getRenameFieldExtraSQL($xmldb_table, $xmldb_field, $newname); $results = array_merge($results, $extra_sentences); @@ -851,18 +842,18 @@ abstract class sql_generator { $results = array(); - /// Just use the CreateKeySQL function + // Just use the CreateKeySQL function if ($keyclause = $this->getKeySQL($xmldb_table, $xmldb_key)) { $key = 'ALTER TABLE ' . $this->getTableName($xmldb_table) . ' ADD CONSTRAINT ' . $keyclause; $results[] = $key; } - /// If we aren't creating the keys OR if the key is XMLDB_KEY_FOREIGN (not underlying index generated - /// automatically by the RDBMS) create the underlying (created by us) index (if doesn't exists) + // If we aren't creating the keys OR if the key is XMLDB_KEY_FOREIGN (not underlying index generated + // automatically by the RDBMS) create the underlying (created by us) index (if doesn't exists) if (!$keyclause || $xmldb_key->getType() == XMLDB_KEY_FOREIGN) { - /// Only if they don't exist - if ($xmldb_key->getType() == XMLDB_KEY_FOREIGN) { ///Calculate type of index based on type ok key + // Only if they don't exist + if ($xmldb_key->getType() == XMLDB_KEY_FOREIGN) { //Calculate type of index based on type ok key $indextype = XMLDB_INDEX_NOTUNIQUE; } else { $indextype = XMLDB_INDEX_UNIQUE; @@ -873,14 +864,14 @@ abstract class sql_generator { } } - /// If the key is XMLDB_KEY_FOREIGN_UNIQUE, create it as UNIQUE too + // If the key is XMLDB_KEY_FOREIGN_UNIQUE, create it as UNIQUE too if ($xmldb_key->getType() == XMLDB_KEY_FOREIGN_UNIQUE && $this->unique_keys) { - ///Duplicate the key + //Duplicate the key $xmldb_key->setType(XMLDB_KEY_UNIQUE); $results = array_merge($results, $this->getAddKeySQL($xmldb_table, $xmldb_key)); } - /// Return results + // Return results return $results; } @@ -895,14 +886,14 @@ abstract class sql_generator { $results = array(); - /// Get the key name (note that this doesn't introspect DB, so could cause some problems sometimes!) - /// TODO: We'll need to overwrite the whole getDropKeySQL() method inside each DB to do the proper queries - /// against the dictionary or require ADOdb to support it or change the find_key_name() method to - /// perform DB introspection directly. But, for now, as we aren't going to enable referential integrity - /// it won't be a problem at all + // Get the key name (note that this doesn't introspect DB, so could cause some problems sometimes!) + // TODO: We'll need to overwrite the whole getDropKeySQL() method inside each DB to do the proper queries + // against the dictionary or require ADOdb to support it or change the find_key_name() method to + // perform DB introspection directly. But, for now, as we aren't going to enable referential integrity + // it won't be a problem at all $dbkeyname = $this->mdb->get_manager()->find_key_name($xmldb_table, $xmldb_key); - /// Only if such type of key generation is enabled + // Only if such type of key generation is enabled $dropkey = false; switch ($xmldb_key->getType()) { case XMLDB_KEY_PRIMARY: @@ -925,33 +916,33 @@ abstract class sql_generator { } break; } - /// If we have decided to drop the key, let's do it + // If we have decided to drop the key, let's do it if ($dropkey) { - /// Replace TABLENAME, CONSTRAINTTYPE and KEYNAME as needed + // Replace TABLENAME, CONSTRAINTTYPE and KEYNAME as needed $dropsql = str_replace('TABLENAME', $this->getTableName($xmldb_table), $template); $dropsql = str_replace('KEYNAME', $dbkeyname, $dropsql); $results[] = $dropsql; } - /// If we aren't dropping the keys OR if the key is XMLDB_KEY_FOREIGN (not underlying index generated - /// automatically by the RDBMS) drop the underlying (created by us) index (if exists) + // If we aren't dropping the keys OR if the key is XMLDB_KEY_FOREIGN (not underlying index generated + // automatically by the RDBMS) drop the underlying (created by us) index (if exists) if (!$dropkey || $xmldb_key->getType() == XMLDB_KEY_FOREIGN) { - /// Only if they exist + // Only if they exist $xmldb_index = new xmldb_index('anyname', XMLDB_INDEX_UNIQUE, $xmldb_key->getFields()); if ($this->mdb->get_manager()->index_exists($xmldb_table, $xmldb_index)) { $results = array_merge($results, $this->getDropIndexSQL($xmldb_table, $xmldb_index)); } } - /// If the key is XMLDB_KEY_FOREIGN_UNIQUE, drop the UNIQUE too + // If the key is XMLDB_KEY_FOREIGN_UNIQUE, drop the UNIQUE too if ($xmldb_key->getType() == XMLDB_KEY_FOREIGN_UNIQUE && $this->unique_keys) { - ///Duplicate the key + //Duplicate the key $xmldb_key->setType(XMLDB_KEY_UNIQUE); $results = array_merge($results, $this->getDropKeySQL($xmldb_table, $xmldb_key)); } - /// Return results + // Return results return $results; } @@ -968,27 +959,27 @@ abstract class sql_generator { $results = array(); - /// Get the real key name + // Get the real key name $dbkeyname = $this->mdb->get_manager()->find_key_name($xmldb_table, $xmldb_key); - /// Check we are really generating this type of keys + // Check we are really generating this type of keys if (($xmldb_key->getType() == XMLDB_KEY_PRIMARY && !$this->primary_keys) || ($xmldb_key->getType() == XMLDB_KEY_UNIQUE && !$this->unique_keys) || ($xmldb_key->getType() == XMLDB_KEY_FOREIGN && !$this->foreign_keys) || ($xmldb_key->getType() == XMLDB_KEY_FOREIGN_UNIQUE && !$this->unique_keys && !$this->foreign_keys)) { - /// We aren't generating this type of keys, delegate to child indexes + // We aren't generating this type of keys, delegate to child indexes $xmldb_index = new xmldb_index($xmldb_key->getName()); $xmldb_index->setFields($xmldb_key->getFields()); return $this->getRenameIndexSQL($xmldb_table, $xmldb_index, $newname); } - /// Arrived here so we are working with keys, lets rename them - /// Replace TABLENAME and KEYNAME as needed + // Arrived here so we are working with keys, lets rename them + // Replace TABLENAME and KEYNAME as needed $renamesql = str_replace('TABLENAME', $this->getTableName($xmldb_table), $this->rename_key_sql); $renamesql = str_replace('OLDKEYNAME', $dbkeyname, $renamesql); $renamesql = str_replace('NEWKEYNAME', $newname, $renamesql); - /// Some DB doesn't support key renaming so this can be empty + // Some DB doesn't support key renaming so this can be empty if ($renamesql) { $results[] = $renamesql; } @@ -1005,7 +996,7 @@ abstract class sql_generator { */ public function getAddIndexSQL($xmldb_table, $xmldb_index) { - /// Just use the CreateIndexSQL function + // Just use the CreateIndexSQL function return $this->getCreateIndexSQL($xmldb_table, $xmldb_index); } @@ -1020,10 +1011,10 @@ abstract class sql_generator { $results = array(); - /// Get the real index name + // Get the real index name $dbindexname = $this->mdb->get_manager()->find_index_name($xmldb_table, $xmldb_index); - /// Replace TABLENAME and INDEXNAME as needed + // Replace TABLENAME and INDEXNAME as needed $dropsql = str_replace('TABLENAME', $this->getTableName($xmldb_table), $this->drop_index_sql); $dropsql = str_replace('INDEXNAME', $this->getEncQuoted($dbindexname), $dropsql); @@ -1042,14 +1033,14 @@ abstract class sql_generator { * @return array An array of SQL statements to rename the index. */ function getRenameIndexSQL($xmldb_table, $xmldb_index, $newname) { - /// Some DB doesn't support index renaming (MySQL) so this can be empty + // Some DB doesn't support index renaming (MySQL) so this can be empty if (empty($this->rename_index_sql)) { return array(); } - /// Get the real index name + // Get the real index name $dbindexname = $this->mdb->get_manager()->find_index_name($xmldb_table, $xmldb_index); - /// Replace TABLENAME and INDEXNAME as needed + // Replace TABLENAME and INDEXNAME as needed $renamesql = str_replace('TABLENAME', $this->getTableName($xmldb_table), $this->rename_index_sql); $renamesql = str_replace('OLDINDEXNAME', $this->getEncQuoted($dbindexname), $renamesql); $renamesql = str_replace('NEWINDEXNAME', $this->getEncQuoted($newname), $renamesql); @@ -1073,14 +1064,14 @@ abstract class sql_generator { $name = ''; - /// Implement one basic cache to avoid object name duplication - /// along all the request life, but never to return cached results - /// We need this because sql statements are created before executing - /// them, hence names doesn't exist "physically" yet in DB, so we need - /// to known which ones have been used + // Implement one basic cache to avoid object name duplication + // along all the request life, but never to return cached results + // We need this because sql statements are created before executing + // them, hence names doesn't exist "physically" yet in DB, so we need + // to known which ones have been used static $used_names = array(); - /// Use standard naming. See http://docs.moodle.org/en/XMLDB_key_and_index_naming + // Use standard naming. See http://docs.moodle.org/en/XMLDB_key_and_index_naming $tablearr = explode ('_', $tablename); foreach ($tablearr as $table) { $name .= substr(trim($table),0,4); @@ -1090,24 +1081,24 @@ abstract class sql_generator { foreach ($fieldsarr as $field) { $name .= substr(trim($field),0,3); } - /// Prepend the prefix + // Prepend the prefix $name = $this->prefix . $name; $name = substr(trim($name), 0, $this->names_max_length - 1 - strlen($suffix)); //Max names_max_length - /// Add the suffix + // Add the suffix $namewithsuffix = $name; if ($suffix) { $namewithsuffix = $namewithsuffix . '_' . $suffix; } - /// If the calculated name is in the cache, or if we detect it by introspecting the DB let's modify if + // If the calculated name is in the cache, or if we detect it by introspecting the DB let's modify if if (in_array($namewithsuffix, $used_names) || $this->isNameInUse($namewithsuffix, $suffix, $tablename)) { $counter = 2; - /// If have free space, we add 2 + // If have free space, we add 2 if (strlen($namewithsuffix) < $this->names_max_length) { $newname = $name . $counter; - /// Else replace the last char by 2 + // Else replace the last char by 2 } else { $newname = substr($name, 0, strlen($name)-1) . $counter; } @@ -1115,7 +1106,7 @@ abstract class sql_generator { if ($suffix) { $newnamewithsuffix = $newnamewithsuffix . '_' . $suffix; } - /// Now iterate until not used name is found, incrementing the counter + // Now iterate until not used name is found, incrementing the counter while (in_array($newnamewithsuffix, $used_names) || $this->isNameInUse($newnamewithsuffix, $suffix, $tablename)) { $counter++; $newname = substr($name, 0, strlen($newname)-1) . $counter; @@ -1127,10 +1118,10 @@ abstract class sql_generator { $namewithsuffix = $newnamewithsuffix; } - /// Add the name to the cache + // Add the name to the cache $used_names[] = $namewithsuffix; - /// Quote it if necessary (reserved words) + // Quote it if necessary (reserved words) $namewithsuffix = $this->getEncQuoted($namewithsuffix); return $namewithsuffix; @@ -1141,7 +1132,7 @@ abstract class sql_generator { * if it's a reserved word * * @param string|array $input String to quote. - * @return Quoted string. + * @return string Quoted string. */ public function getEncQuoted($input) { @@ -1151,9 +1142,9 @@ abstract class sql_generator { } return $input; } else { - /// Always lowercase + // Always lowercase $input = strtolower($input); - /// if reserved or quote_all or has hyphens, quote it + // if reserved or quote_all or has hyphens, quote it if ($this->quote_all || in_array($input, $this->reserved_words) || strpos($input, '-') !== false) { $input = $this->quote_string . $input . $this->quote_string; } @@ -1173,39 +1164,39 @@ abstract class sql_generator { if ($sentences = $statement->getSentences()) { foreach ($sentences as $sentence) { - /// Get the list of fields + // Get the list of fields $fields = $statement->getFieldsFromInsertSentence($sentence); - /// Get the values of fields + // Get the values of fields $values = $statement->getValuesFromInsertSentence($sentence); - /// Look if we have some CONCAT value and transform it dynamically + // Look if we have some CONCAT value and transform it dynamically foreach($values as $key => $value) { - /// Trim single quotes + // Trim single quotes $value = trim($value,"'"); if (stristr($value, 'CONCAT') !== false){ - /// Look for data between parenthesis + // Look for data between parenthesis preg_match("/CONCAT\s*\((.*)\)$/is", trim($value), $matches); if (isset($matches[1])) { $part = $matches[1]; - /// Convert the comma separated string to an array + // Convert the comma separated string to an array $arr = xmldb_object::comma2array($part); if ($arr) { $value = $this->getConcatSQL($arr); } } } - /// Values to be sent to DB must be properly escaped + // Values to be sent to DB must be properly escaped $value = $this->addslashes($value); - /// Back trimmed quotes + // Back trimmed quotes $value = "'" . $value . "'"; - /// Back to the array + // Back to the array $values[$key] = $value; } - /// Iterate over fields, escaping them if necessary + // Iterate over fields, escaping them if necessary foreach($fields as $key => $field) { $fields[$key] = $this->getEncQuoted($field); } - /// Build the final SQL sentence and add it to the array of results + // Build the final SQL sentence and add it to the array of results $sql = 'INSERT INTO ' . $this->getEncQuoted($this->prefix . $statement->getTable()) . '(' . implode(', ', $fields) . ') ' . 'VALUES (' . implode(', ', $values) . ')'; @@ -1228,7 +1219,7 @@ abstract class sql_generator { */ public function getConcatSQL($elements) { - /// Replace double quoted elements by single quotes + // Replace double quoted elements by single quotes foreach($elements as $key => $element) { $element = trim($element); if (substr($element, 0, 1) == '"' && @@ -1237,7 +1228,7 @@ abstract class sql_generator { } } - /// Now call the standard $DB->sql_concat() DML function + // Now call the standard $DB->sql_concat() DML function return call_user_func_array(array($this->mdb, 'sql_concat'), $elements); } @@ -1271,22 +1262,22 @@ abstract class sql_generator { } -/// ALL THESE FUNCTION MUST BE CUSTOMISED BY ALL THE XMLDGenerator classes +// ====== FOLLOWING FUNCTION MUST BE CUSTOMISED BY ALL THE XMLDGenerator classes ======== /** * Reset a sequence to the id field of a table. * - * @param string $tablename name of table. - * @return success + * @param xmldb_table|string $table name of table or the table object. + * @return array of sql statements */ - public abstract function getResetSequenceSQL($tablename); + public abstract function getResetSequenceSQL($table); /** * Given one correct xmldb_table, returns the SQL statements * to create temporary table (inside one array). * * @param xmldb_table $xmldb_table The xmldb_table object instance. - * @return array SQL statements. + * @return array of sql statements */ abstract public function getCreateTempTableSQL($xmldb_table); @@ -1360,6 +1351,7 @@ abstract class sql_generator { * * @param xmldb_table $xmldb_table The xmldb_table object instance. * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. * * @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL() */ diff --git a/lib/ddl/sqlite_sql_generator.php b/lib/ddl/sqlite_sql_generator.php index e10b24a869b..c0b088cfbbd 100644 --- a/lib/ddl/sqlite_sql_generator.php +++ b/lib/ddl/sqlite_sql_generator.php @@ -1,5 +1,4 @@ . - /** * Experimental SQLite specific SQL code generator. * - * @package core - * @subpackage ddl_generator + * @package core_ddl * @copyright 2008 Andrei Bautu * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -37,31 +34,41 @@ class sqlite_sql_generator extends sql_generator { /// Only set values that are different from the defaults present in XMLDBgenerator - public $drop_default_value_required = true; //To specify if the generator must use some DEFAULT clause to drop defaults - public $drop_default_value = NULL; //The DEFAULT clause required to drop defaults + /** @var bool To specify if the generator must use some DEFAULT clause to drop defaults.*/ + public $drop_default_value_required = true; - public $drop_primary_key = 'ALTER TABLE TABLENAME DROP PRIMARY KEY'; // Template to drop PKs - // with automatic replace for TABLENAME and KEYNAME + /** @var string The DEFAULT clause required to drop defaults.*/ + public $drop_default_value = NULL; - public $drop_unique_key = 'ALTER TABLE TABLENAME DROP KEY KEYNAME'; // Template to drop UKs - // with automatic replace for TABLENAME and KEYNAME + /** @var string Template to drop PKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ + public $drop_primary_key = 'ALTER TABLE TABLENAME DROP PRIMARY KEY'; - public $drop_foreign_key = 'ALTER TABLE TABLENAME DROP FOREIGN KEY KEYNAME'; // Template to drop FKs - // with automatic replace for TABLENAME and KEYNAME - public $default_for_char = ''; // To define the default to set for NOT NULLs CHARs without default (null=do nothing) + /** @var string Template to drop UKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ + public $drop_unique_key = 'ALTER TABLE TABLENAME DROP KEY KEYNAME'; - public $sequence_only = true; //To avoid to output the rest of the field specs, leaving only the name and the sequence_name publiciable - public $sequence_extra_code = false; //Does the generator need to add extra code to generate the sequence fields - public $sequence_name = 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'; //Particular name for inline sequences in this generator + /** @var string Template to drop FKs. 'TABLENAME' and 'KEYNAME' will be replaced from this template.*/ + public $drop_foreign_key = 'ALTER TABLE TABLENAME DROP FOREIGN KEY KEYNAME'; - public $drop_index_sql = 'ALTER TABLE TABLENAME DROP INDEX INDEXNAME'; //SQL sentence to drop one index - //TABLENAME, INDEXNAME are dynamically replaced + /** @var string To define the default to set for NOT NULLs CHARs without default (null=do nothing).*/ + public $default_for_char = ''; - public $rename_index_sql = null; //SQL sentence to rename one index (MySQL doesn't support this!) - //TABLENAME, OLDINDEXNAME, NEWINDEXNAME are dynamically replaced + /** @var bool To avoid outputting the rest of the field specs, leaving only the name and the sequence_name returned.*/ + public $sequence_only = true; - public $rename_key_sql = null; //SQL sentence to rename one key (MySQL doesn't support this!) - //TABLENAME, OLDKEYNAME, NEWKEYNAME are dynamically replaced + /** @var bool True if the generator needs to add extra code to generate the sequence fields.*/ + public $sequence_extra_code = false; + + /** @var string The particular name for inline sequences in this generator.*/ + public $sequence_name = 'INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL'; + + /** @var string SQL sentence to drop one index where 'TABLENAME', 'INDEXNAME' keywords are dynamically replaced.*/ + public $drop_index_sql = 'ALTER TABLE TABLENAME DROP INDEX INDEXNAME'; + + /** @var string SQL sentence to rename one index where 'TABLENAME', 'OLDINDEXNAME' and 'NEWINDEXNAME' are dynamically replaced.*/ + public $rename_index_sql = null; + + /** @var string SQL sentence to rename one key 'TABLENAME', 'OLDKEYNAME' and 'NEWKEYNAME' are dynamically replaced.*/ + public $rename_key_sql = null; /** * Creates one new XMLDBmysql @@ -72,8 +79,9 @@ class sqlite_sql_generator extends sql_generator { /** * Reset a sequence to the id field of a table. - * @param string $table name of table or xmldb_object - * @return bool success + * + * @param xmldb_table|string $table name of table or the table object. + * @return array of sql statements */ public function getResetSequenceSQL($table) { @@ -125,7 +133,12 @@ class sqlite_sql_generator extends sql_generator { } /** - * Given one XMLDB Type, length and decimals, returns the DB proper SQL type + * Given one XMLDB Type, length and decimals, returns the DB proper SQL type. + * + * @param int $xmldb_type The xmldb_type defined constant. XMLDB_TYPE_INTEGER and other XMLDB_TYPE_* constants. + * @param int $xmldb_length The length of that data type. + * @param int $xmldb_decimals The decimal places of precision of the data type. + * @return string The DB defined data type. */ public function getTypeSQL($xmldb_type, $xmldb_length=null, $xmldb_decimals=null) { @@ -263,7 +276,14 @@ class sqlite_sql_generator extends sql_generator { } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to alter the field in the table. + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from. + * @param string $skip_type_clause The type clause on alter columns, NULL by default. + * @param string $skip_default_clause The default clause on alter columns, NULL by default. + * @param string $skip_notnull_clause The null/notnull clause on alter columns, NULL by default. + * @return string The field altering SQL statement. */ public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) { return $this->getAlterTableSchema($xmldb_table, $xmldb_field, $xmldb_field); @@ -279,8 +299,12 @@ class sqlite_sql_generator extends sql_generator { } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to create its default + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to add its default * (usually invoked from getModifyDefaultSQL() + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. */ public function getCreateDefaultSQL($xmldb_table, $xmldb_field) { return $this->getAlterTableSchema($xmldb_table, $xmldb_field, $xmldb_field); @@ -288,8 +312,12 @@ class sqlite_sql_generator extends sql_generator { /** * Given one correct xmldb_field and the new name, returns the SQL statements - * to rename it (inside one array) - * SQLite is pretty different from the standard to justify this overloading + * to rename it (inside one array). + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to get the renamed field from. + * @param string $newname The new name to rename the field to. + * @return array The SQL statements for renaming the field. */ public function getRenameFieldSQL($xmldb_table, $xmldb_field, $newname) { $oldfield = clone($xmldb_field); @@ -321,7 +349,11 @@ class sqlite_sql_generator extends sql_generator { } /** - * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop the field from the table + * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop the field from the table. + * + * @param xmldb_table $xmldb_table The table related to $xmldb_field. + * @param xmldb_field $xmldb_field The instance of xmldb_field to create the SQL from. + * @return array The SQL statement for dropping a field from the table. */ public function getDropFieldSQL($xmldb_table, $xmldb_field) { return $this->getAlterTableSchema($xmldb_table, NULL, $xmldb_field); @@ -346,31 +378,50 @@ class sqlite_sql_generator extends sql_generator { /** * Given one xmldb_table and one xmldb_field, return the SQL statements needed to drop its default * (usually invoked from getModifyDefaultSQL() + * + * Note that this method may be dropped in future. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @param xmldb_field $xmldb_field The xmldb_field object instance. + * @return array Array of SQL statements to create a field's default. + * + * @todo MDL-31147 Moodle 2.1 - Drop getDropDefaultSQL() */ public function getDropDefaultSQL($xmldb_table, $xmldb_field) { return $this->getAlterTableSchema($xmldb_table, $xmldb_field, $xmldb_field); } /** - * Returns the code (in array) needed to add one comment to the table + * Returns the code (array of statements) needed to add one comment to the table. + * + * @param xmldb_table $xmldb_table The xmldb_table object instance. + * @return array Array of SQL statements to add one comment to the table. */ function getCommentSQL ($xmldb_table) { return array(); } /** - * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg) - * return if such name is currently in use (true) or no (false) - * (invoked from getNameForObject() + * Given one object name and it's type (pk, uk, fk, ck, ix, uix, seq, trg). + * + * (MySQL requires the whole xmldb_table object to be specified, so we add it always) + * + * This is invoked from getNameForObject(). + * Only some DB have this implemented. + * + * @param string $object_name The object's name to check for. + * @param string $type The object's type (pk, uk, fk, ck, ix, uix, seq, trg). + * @param string $table_name The table's name to check in + * @return bool If such name is currently in use (true) or no (false) */ public function isNameInUse($object_name, $type, $table_name) { // TODO: add introspection code return false; //No name in use found } - /** * Returns an array of reserved words (lowercase) for this DB + * @return array An array of database specific reserved words */ public static function getReservedWords() { /// From http://www.sqlite.org/lang_keywords.html @@ -399,6 +450,11 @@ class sqlite_sql_generator extends sql_generator { return $reserved_words; } + /** + * Adds slashes to string. + * @param string $s + * @return string The escaped string. + */ public function addslashes($s) { // do not use php addslashes() because it depends on PHP quote settings! $s = str_replace("'", "''", $s); diff --git a/lib/ddl/tests/ddl_test.php b/lib/ddl/tests/ddl_test.php index 352202f4190..64f7d6ddc02 100644 --- a/lib/ddl/tests/ddl_test.php +++ b/lib/ddl/tests/ddl_test.php @@ -17,8 +17,7 @@ /** * DDL layer tests * - * @package core - * @subpackage ddl + * @package core_ddl * @category phpunit * @copyright 2008 Nicolas Connault * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later @@ -646,7 +645,7 @@ class ddl_testcase extends database_driver_testcase { // fill the table with some records before adding fields $this->fill_deftable('test_table1'); - /// add one not null field without specifying default value (throws ddl_exception) + // add one not null field without specifying default value (throws ddl_exception) $field = new xmldb_field('onefield'); $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); try { @@ -656,7 +655,7 @@ class ddl_testcase extends database_driver_testcase { $this->assertTrue($e instanceof ddl_exception); } - /// add one existing field (throws ddl_exception) + // add one existing field (throws ddl_exception) $field = new xmldb_field('course'); $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 2); try { @@ -670,7 +669,7 @@ class ddl_testcase extends database_driver_testcase { // TODO: add one text field with default, must throw exception // TODO: add one binary field with default, must throw exception - /// add one integer field and check it + // add one integer field and check it $field = new xmldb_field('oneinteger'); $field->set_attributes(XMLDB_TYPE_INTEGER, '6', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 2); $dbman->add_field($table, $field); @@ -686,7 +685,7 @@ class ddl_testcase extends database_driver_testcase { $this->assertEquals($columns['oneinteger']->meta_type ,'I'); $this->assertEquals($DB->get_field('test_table1', 'oneinteger', array(), IGNORE_MULTIPLE), 2); //check default has been applied - /// add one numeric field and check it + // add one numeric field and check it $field = new xmldb_field('onenumber'); $field->set_attributes(XMLDB_TYPE_NUMBER, '6,3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 2.55); $dbman->add_field($table, $field); @@ -703,7 +702,7 @@ class ddl_testcase extends database_driver_testcase { $this->assertEquals($columns['onenumber']->meta_type ,'N'); $this->assertEquals($DB->get_field('test_table1', 'onenumber', array(), IGNORE_MULTIPLE), 2.550); //check default has been applied - /// add one float field and check it (not official type - must work as number) + // add one float field and check it (not official type - must work as number) $field = new xmldb_field('onefloat'); $field->set_attributes(XMLDB_TYPE_FLOAT, '6,3', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 3.550); $dbman->add_field($table, $field); @@ -723,7 +722,7 @@ class ddl_testcase extends database_driver_testcase { // this isn't a real problem at all. $this->assertEquals(round($DB->get_field('test_table1', 'onefloat', array(), IGNORE_MULTIPLE), 7), 3.550); //check default has been applied - /// add one char field and check it + // add one char field and check it $field = new xmldb_field('onechar'); $field->set_attributes(XMLDB_TYPE_CHAR, '25', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, 'Nice dflt!'); $dbman->add_field($table, $field); @@ -740,7 +739,7 @@ class ddl_testcase extends database_driver_testcase { $this->assertEquals($columns['onechar']->meta_type ,'C'); $this->assertEquals($DB->get_field('test_table1', 'onechar', array(), IGNORE_MULTIPLE), 'Nice dflt!'); //check default has been applied - /// add one big text field and check it + // add one big text field and check it $field = new xmldb_field('onetext'); $field->set_attributes(XMLDB_TYPE_TEXT, 'big'); $dbman->add_field($table, $field); @@ -756,21 +755,21 @@ class ddl_testcase extends database_driver_testcase { $this->assertEquals($columns['onetext']->default_value, null); $this->assertEquals($columns['onetext']->meta_type ,'X'); - /// add one medium text field and check it + // add one medium text field and check it $field = new xmldb_field('mediumtext'); $field->set_attributes(XMLDB_TYPE_TEXT, 'medium'); $dbman->add_field($table, $field); $columns = $DB->get_columns('test_table1'); $this->assertTrue(($columns['mediumtext']->max_length == -1) or ($columns['mediumtext']->max_length >= 16777215)); // -1 means unknown or big - /// add one small text field and check it + // add one small text field and check it $field = new xmldb_field('smalltext'); $field->set_attributes(XMLDB_TYPE_TEXT, 'small'); $dbman->add_field($table, $field); $columns = $DB->get_columns('test_table1'); $this->assertTrue(($columns['smalltext']->max_length == -1) or ($columns['smalltext']->max_length >= 65535)); // -1 means unknown or big - /// add one binary field and check it + // add one binary field and check it $field = new xmldb_field('onebinary'); $field->set_attributes(XMLDB_TYPE_BINARY); $dbman->add_field($table, $field); From 94417438b31985623bda471f6555f05e18232cb7 Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Tue, 5 Jun 2012 13:13:21 +0200 Subject: [PATCH 025/130] MDL-32003 fix phpdocs in xmldb abstraction --- lib/dml/tests/dml_test.php | 2 +- lib/xmldb/xmldb_constants.php | 153 +++++++++++-------- lib/xmldb/xmldb_field.php | 185 ++++++++++++++--------- lib/xmldb/xmldb_file.php | 91 ++++++----- lib/xmldb/xmldb_index.php | 100 +++++++----- lib/xmldb/xmldb_key.php | 155 +++++++++++-------- lib/xmldb/xmldb_object.php | 150 +++++++++++------- lib/xmldb/xmldb_structure.php | 169 ++++++++++++--------- lib/xmldb/xmldb_table.php | 276 ++++++++++++++++++++-------------- 9 files changed, 772 insertions(+), 509 deletions(-) diff --git a/lib/dml/tests/dml_test.php b/lib/dml/tests/dml_test.php index 4993d3596bb..0b3824c1b25 100644 --- a/lib/dml/tests/dml_test.php +++ b/lib/dml/tests/dml_test.php @@ -774,7 +774,7 @@ class dml_testcase extends database_driver_testcase { $next_field = next($fields); } - $this->assertEquals($next_column->name, $next_field->name); + $this->assertEquals($next_column->name, $next_field->getName()); } // Test get_columns for non-existing table returns empty array. MDL-30147 diff --git a/lib/xmldb/xmldb_constants.php b/lib/xmldb/xmldb_constants.php index 347f728671d..7166880176e 100644 --- a/lib/xmldb/xmldb_constants.php +++ b/lib/xmldb/xmldb_constants.php @@ -1,72 +1,99 @@ . -/////////////////////////////////////////////////////////////////////////// -// // -// NOTICE OF COPYRIGHT // -// // -// Moodle - Modular Object-Oriented Dynamic Learning Environment // -// http://moodle.com // -// // -// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // -// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // -// // -// This program 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 2 of the License, or // -// (at your option) any later version. // -// // -// This program 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: // -// // -// http://www.gnu.org/copyleft/gpl.html // -// // -/////////////////////////////////////////////////////////////////////////// +/** + * This file contains all the constants and variables used + * by the XMLDB interface + * + * @package core_xmldb + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ -/// This file contains all the constants and variables used -/// by the XMLDB interface +defined('MOODLE_INTERNAL') || die(); -/// First, some constants to be used by actions - define('ACTION_NONE', 0); //Default flags for class - define('ACTION_GENERATE_HTML', 1); //The invoke function will return HTML - define('ACTION_GENERATE_XML', 2); //The invoke function will return HTML - define('ACTION_HAVE_SUBACTIONS', 1); //The class can have subaction -/// Now the allowed DB Field Types - define ('XMLDB_TYPE_INCORRECT', 0); //Wrong DB Type - define ('XMLDB_TYPE_INTEGER', 1); //Integer - define ('XMLDB_TYPE_NUMBER', 2); //Decimal number - define ('XMLDB_TYPE_FLOAT', 3); //Floating Point number - define ('XMLDB_TYPE_CHAR', 4); //String - define ('XMLDB_TYPE_TEXT', 5); //Text - define ('XMLDB_TYPE_BINARY', 6); //Binary - define ('XMLDB_TYPE_DATETIME', 7); //Datetime - define ('XMLDB_TYPE_TIMESTAMP', 8); //Timestamp +// ==== First, some constants to be used by actions ==== +/** Default flags for class */ +define('ACTION_NONE', 0); +/** The invoke function will return HTML */ +define('ACTION_GENERATE_HTML', 1); +/** The invoke function will return HTML */ +define('ACTION_GENERATE_XML', 2); +/** The class can have subaction */ +define('ACTION_HAVE_SUBACTIONS', 1); -/// Now the allowed DB Keys - define ('XMLDB_KEY_INCORRECT', 0); //Wrong DB Key - define ('XMLDB_KEY_PRIMARY', 1); //Primary Keys - define ('XMLDB_KEY_UNIQUE', 2); //Unique Keys - define ('XMLDB_KEY_FOREIGN', 3); //Foreign Keys - define ('XMLDB_KEY_CHECK', 4); //Check Constraints - NOT USED! - define ('XMLDB_KEY_FOREIGN_UNIQUE',5); //Foreign Key + Unique Key +// ==== Now the allowed DB Field Types ==== +/** Wrong DB Type */ +define ('XMLDB_TYPE_INCORRECT', 0); +/** Integer */ +define ('XMLDB_TYPE_INTEGER', 1); +/** Decimal number */ +define ('XMLDB_TYPE_NUMBER', 2); +/** Floating Point number */ +define ('XMLDB_TYPE_FLOAT', 3); +/** String */ +define ('XMLDB_TYPE_CHAR', 4); +/** Text */ +define ('XMLDB_TYPE_TEXT', 5); +/** Binary */ +define ('XMLDB_TYPE_BINARY', 6); +/** Datetime */ +define ('XMLDB_TYPE_DATETIME', 7); +/** Timestamp */ +define ('XMLDB_TYPE_TIMESTAMP', 8); -/// Now the allowed Statement Types - define ('XMLDB_STATEMENT_INCORRECT', 0); //Wrong Statement Type - define ('XMLDB_STATEMENT_INSERT', 1); //Insert Statements - define ('XMLDB_STATEMENT_UPDATE', 2); //Update Statements - define ('XMLDB_STATEMENT_DELETE', 3); //Delete Statements - define ('XMLDB_STATEMENT_CUSTOM', 4); //Custom Statements +// TODO: delete these unused constants - can not be used in 2.3 upgrade +define ('XMLDB_STATEMENT_INCORRECT', 0); //Wrong Statement Type +define ('XMLDB_STATEMENT_INSERT', 1); //Insert Statements +define ('XMLDB_STATEMENT_UPDATE', 2); //Update Statements +define ('XMLDB_STATEMENT_DELETE', 3); //Delete Statements +define ('XMLDB_STATEMENT_CUSTOM', 4); //Custom Statements -/// Some other useful Constants - define ('XMLDB_UNSIGNED', true); //If the field is going to be unsigned @deprecated since 2.3 - define ('XMLDB_NOTNULL', true); //If the field is going to be not null - define ('XMLDB_SEQUENCE', true); //If the field is going to be a sequence - define ('XMLDB_INDEX_UNIQUE', true); //If the index is going to be unique - define ('XMLDB_INDEX_NOTUNIQUE',false); //If the index is NOT going to be unique +// ==== Now the allowed DB Keys ==== +/** Wrong DB Key */ +define ('XMLDB_KEY_INCORRECT', 0); +/** Primary Keys */ +define ('XMLDB_KEY_PRIMARY', 1); +/** Unique Keys */ +define ('XMLDB_KEY_UNIQUE', 2); +/** Foreign Keys */ +define ('XMLDB_KEY_FOREIGN', 3); +/** Check Constraints - NOT USED! */ +define ('XMLDB_KEY_CHECK', 4); +/** Foreign Key + Unique Key */ +define ('XMLDB_KEY_FOREIGN_UNIQUE',5); -/// Some strings used widely - define ('XMLDB_LINEFEED', "\n"); - define ('XMLDB_PHP_HEADER', ' if ($oldversion < XXXXXXXXXX) {' . XMLDB_LINEFEED); - define ('XMLDB_PHP_FOOTER', ' }' . XMLDB_LINEFEED); +// ==== Some other useful Constants ==== +/** If the field is going to be unsigned @deprecated since 2.3 */ +define ('XMLDB_UNSIGNED', true); +/** If the field is going to be not null */ +define ('XMLDB_NOTNULL', true); +/** If the field is going to be a sequence */ +define ('XMLDB_SEQUENCE', true); +/** If the index is going to be unique */ +define ('XMLDB_INDEX_UNIQUE', true); +/** If the index is NOT going to be unique */ +define ('XMLDB_INDEX_NOTUNIQUE',false); + +// ==== Some strings used widely ==== +/** New line in xmldb generated files */ +define ('XMLDB_LINEFEED', "\n"); +/** Upgrade start in upgrade.php */ +define ('XMLDB_PHP_HEADER', ' if ($oldversion < XXXXXXXXXX) {' . XMLDB_LINEFEED); +/** Upgrade end in upgrade.php */ +define ('XMLDB_PHP_FOOTER', ' }' . XMLDB_LINEFEED); diff --git a/lib/xmldb/xmldb_field.php b/lib/xmldb/xmldb_field.php index 11e7a2d39a1..f84879aa2e1 100644 --- a/lib/xmldb/xmldb_field.php +++ b/lib/xmldb/xmldb_field.php @@ -1,38 +1,49 @@ . -/////////////////////////////////////////////////////////////////////////// -// // -// NOTICE OF COPYRIGHT // -// // -// Moodle - Modular Object-Oriented Dynamic Learning Environment // -// http://moodle.com // -// // -// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // -// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // -// // -// This program 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 2 of the License, or // -// (at your option) any later version. // -// // -// This program 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: // -// // -// http://www.gnu.org/copyleft/gpl.html // -// // -/////////////////////////////////////////////////////////////////////////// +/** + * This class represent one XMLDB Field + * + * @package core_xmldb + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); -/// This class represent one XMLDB Field class xmldb_field extends xmldb_object { + /** @var int XMLDB_TYPE_ constants */ var $type; + + /** @var int size of field */ var $length; + + /** @var bool is null forbidden? XMLDB_NOTNULL */ var $notnull; + + /** @var mixed default value */ var $default; + + /** @var bool use automatic counter */ var $sequence; + + /** @var int number of decimals */ var $decimals; /** @@ -72,6 +83,14 @@ class xmldb_field extends xmldb_object { /** * Creates one new xmldb_field + * @param string $name of field + * @param int $type XMLDB_TYPE_INTEGER, XMLDB_TYPE_NUMBER, XMLDB_TYPE_CHAR, XMLDB_TYPE_TEXT, XMLDB_TYPE_BINARY + * @param string $precision length for integers and chars, two-comma separated numbers for numbers + * @param bool $unsigned XMLDB_UNSIGNED or null (or false) + * @param bool $notnull XMLDB_NOTNULL or null (or false) + * @param bool $sequence XMLDB_SEQUENCE or null (or false) + * @param mixed $default meaningful default o null (or false) + * @param xmldb_object $previous */ function __construct($name, $type=null, $precision=null, $unsigned=null, $notnull=null, $sequence=null, $default=null, $previous=null) { $this->type = NULL; @@ -87,12 +106,13 @@ class xmldb_field extends xmldb_object { /** * Set all the attributes of one xmldb_field * - * @param string type XMLDB_TYPE_INTEGER, XMLDB_TYPE_NUMBER, XMLDB_TYPE_CHAR, XMLDB_TYPE_TEXT, XMLDB_TYPE_BINARY - * @param string precision length for integers and chars, two-comma separated numbers for numbers - * @param string unsigned XMLDB_UNSIGNED or null (or false) - * @param string notnull XMLDB_NOTNULL or null (or false) - * @param string sequence XMLDB_SEQUENCE or null (or false) - * @param string default meaningful default o null (or false) + * @param int $type XMLDB_TYPE_INTEGER, XMLDB_TYPE_NUMBER, XMLDB_TYPE_CHAR, XMLDB_TYPE_TEXT, XMLDB_TYPE_BINARY + * @param string $precision length for integers and chars, two-comma separated numbers for numbers + * @param bool $unsigned XMLDB_UNSIGNED or null (or false) + * @param bool $notnull XMLDB_NOTNULL or null (or false) + * @param bool $sequence XMLDB_SEQUENCE or null (or false) + * @param mixed $default meaningful default o null (or false) + * @param xmldb_object $previous */ function set_attributes($type, $precision=null, $unsigned=null, $notnull=null, $sequence=null, $default=null, $previous=null) { $this->type = $type; @@ -120,6 +140,7 @@ class xmldb_field extends xmldb_object { /** * Get the type + * @return int */ function getType() { return $this->type; @@ -127,6 +148,7 @@ class xmldb_field extends xmldb_object { /** * Get the length + * @return int */ function getLength() { return $this->length; @@ -134,6 +156,7 @@ class xmldb_field extends xmldb_object { /** * Get the decimals + * @return string */ function getDecimals() { return $this->decimals; @@ -141,6 +164,7 @@ class xmldb_field extends xmldb_object { /** * Get the notnull + * @return bool */ function getNotNull() { return $this->notnull; @@ -149,6 +173,7 @@ class xmldb_field extends xmldb_object { /** * Get the unsigned * @deprecated since moodle 2.3 + * @return bool */ function getUnsigned() { return false; @@ -156,6 +181,7 @@ class xmldb_field extends xmldb_object { /** * Get the sequence + * @return bool */ function getSequence() { return $this->sequence; @@ -163,6 +189,7 @@ class xmldb_field extends xmldb_object { /** * Get the default + * @return mixed */ function getDefault() { return $this->default; @@ -170,6 +197,7 @@ class xmldb_field extends xmldb_object { /** * Set the field type + * @param int $type */ function setType($type) { $this->type = $type; @@ -177,6 +205,7 @@ class xmldb_field extends xmldb_object { /** * Set the field length + * @param int $length */ function setLength($length) { $this->length = $length; @@ -184,6 +213,7 @@ class xmldb_field extends xmldb_object { /** * Set the field decimals + * @param string */ function setDecimals($decimals) { $this->decimals = $decimals; @@ -192,12 +222,14 @@ class xmldb_field extends xmldb_object { /** * Set the field unsigned * @deprecated since moodle 2.3 + * @param bool $unsigned */ function setUnsigned($unsigned=true) { } /** * Set the field notnull + * @param bool $notnull */ function setNotNull($notnull=true) { $this->notnull = $notnull; @@ -205,6 +237,7 @@ class xmldb_field extends xmldb_object { /** * Set the field sequence + * @param bool $sequence */ function setSequence($sequence=true) { $this->sequence = $sequence; @@ -212,16 +245,17 @@ class xmldb_field extends xmldb_object { /** * Set the field default + * @param mixed $default */ function setDefault($default) { - /// Check, warn and auto-fix '' (empty) defaults for CHAR NOT NULL columns, changing them - /// to NULL so XMLDB will apply the proper default + // Check, warn and auto-fix '' (empty) defaults for CHAR NOT NULL columns, changing them + // to NULL so XMLDB will apply the proper default if ($this->type == XMLDB_TYPE_CHAR && $this->notnull && $default === '') { $this->errormsg = 'XMLDB has detected one CHAR NOT NULL column (' . $this->name . ") with '' (empty string) as DEFAULT value. This type of columns must have one meaningful DEFAULT declared or none (NULL). XMLDB have fixed it automatically changing it to none (NULL). The process will continue ok and proper defaults will be created accordingly with each DB requirements. Please fix it in source (XML and/or upgrade script) to avoid this message to be displayed."; $this->debug($this->errormsg); $default = null; } - /// Check, warn and autofix TEXT|BINARY columns having a default clause (only null is allowed) + // Check, warn and autofix TEXT|BINARY columns having a default clause (only null is allowed) if (($this->type == XMLDB_TYPE_TEXT || $this->type == XMLDB_TYPE_BINARY) && $default !== null) { $this->errormsg = 'XMLDB has detected one TEXT/BINARY column (' . $this->name . ") with some DEFAULT defined. This type of columns cannot have any default value. Please fix it in source (XML and/or upgrade script) to avoid this message to be displayed."; $this->debug($this->errormsg); @@ -232,18 +266,19 @@ class xmldb_field extends xmldb_object { /** * Load data from XML to the table + * @param array $xmlarr */ function arr2xmldb_field($xmlarr) { $result = true; - /// Debug the table - /// traverse_xmlize($xmlarr); //Debug - /// print_object ($GLOBALS['traverse_array']); //Debug - /// $GLOBALS['traverse_array']=""; //Debug + // Debug the table + // traverse_xmlize($xmlarr); //Debug + // print_object ($GLOBALS['traverse_array']); //Debug + // $GLOBALS['traverse_array']=""; //Debug - /// Process table attributes (name, type, length - /// notnull, sequence, decimals, comment, previous, next) + // Process table attributes (name, type, length + // notnull, sequence, decimals, comment, previous, next) if (isset($xmlarr['@']['NAME'])) { $this->name = trim($xmlarr['@']['NAME']); } else { @@ -253,7 +288,7 @@ class xmldb_field extends xmldb_object { } if (isset($xmlarr['@']['TYPE'])) { - /// Check for valid type + // Check for valid type $type = $this->getXMLDBFieldType(trim($xmlarr['@']['TYPE'])); if ($type) { $this->type = $type; @@ -270,7 +305,7 @@ class xmldb_field extends xmldb_object { if (isset($xmlarr['@']['LENGTH'])) { $length = trim($xmlarr['@']['LENGTH']); - /// Check for integer values + // Check for integer values if ($this->type == XMLDB_TYPE_INTEGER || $this->type == XMLDB_TYPE_NUMBER || $this->type == XMLDB_TYPE_CHAR) { @@ -284,12 +319,12 @@ class xmldb_field extends xmldb_object { $result = false; } } - /// Remove length from text and binary + // Remove length from text and binary if ($this->type == XMLDB_TYPE_TEXT || $this->type == XMLDB_TYPE_BINARY) { $length = null; } - /// Finally, set the length + // Finally, set the length $this->length = $length; } @@ -326,7 +361,7 @@ class xmldb_field extends xmldb_object { $decimals = NULL; if (isset($xmlarr['@']['DECIMALS'])) { $decimals = trim($xmlarr['@']['DECIMALS']); - /// Check for integer values + // Check for integer values if ($this->type == XMLDB_TYPE_NUMBER || $this->type == XMLDB_TYPE_FLOAT) { if (!(is_numeric($decimals)&&(intval($decimals)==floatval($decimals)))) { @@ -348,7 +383,7 @@ class xmldb_field extends xmldb_object { $decimals = 0; } } - // Finally, set the decimals + // Finally, set the decimals if ($this->type == XMLDB_TYPE_NUMBER || $this->type == XMLDB_TYPE_FLOAT) { $this->decimals = $decimals; @@ -366,7 +401,7 @@ class xmldb_field extends xmldb_object { $this->next = trim($xmlarr['@']['NEXT']); } - /// Set some attributes + // Set some attributes if ($result) { $this->loaded = true; } @@ -377,6 +412,8 @@ class xmldb_field extends xmldb_object { /** * This function returns the correct XMLDB_TYPE_XXX value for the * string passed as argument + * @param string $type + * @return int */ function getXMLDBFieldType($type) { @@ -405,13 +442,15 @@ class xmldb_field extends xmldb_object { $result = XMLDB_TYPE_DATETIME; break; } - /// Return the normalized XMLDB_TYPE + // Return the normalized XMLDB_TYPE return $result; } /** * This function returns the correct name value for the * XMLDB_TYPE_XXX passed as argument + * @param int $type + * @return string */ function getXMLDBTypeName($type) { @@ -440,12 +479,14 @@ class xmldb_field extends xmldb_object { $result = 'datetime'; break; } - /// Return the normalized name + // Return the normalized name return $result; } /** * This function calculate and set the hash of one xmldb_field + * @param bool $recursive + * @return void, modifies $this->hash */ function calculateHash($recursive = false) { if (!$this->loaded) { @@ -459,7 +500,8 @@ class xmldb_field extends xmldb_object { } /** - *This function will output the XML text for one field + * This function will output the XML text for one field + * @return string */ function xmlOutput() { $o = ''; @@ -503,10 +545,12 @@ class xmldb_field extends xmldb_object { /** * This function will set all the attributes of the xmldb_field object * based on information passed in one ADOField + * @param string $adofield + * @return void, sets $this->type */ function setFromADOField($adofield) { - /// Calculate the XMLDB_TYPE + // Calculate the XMLDB_TYPE switch (strtolower($adofield->type)) { case 'int': case 'tinyint': @@ -549,7 +593,7 @@ class xmldb_field extends xmldb_object { default: $this->type = XMLDB_TYPE_TEXT; } - /// Calculate the length of the field + // Calculate the length of the field if ($adofield->max_length > 0 && ($this->type == XMLDB_TYPE_INTEGER || $this->type == XMLDB_TYPE_NUMBER || @@ -563,38 +607,40 @@ class xmldb_field extends xmldb_object { if ($this->type == XMLDB_TYPE_BINARY) { $this->length = null; } - /// Calculate the decimals of the field + // Calculate the decimals of the field if ($adofield->max_length > 0 && $adofield->scale && ($this->type == XMLDB_TYPE_NUMBER || $this->type == XMLDB_TYPE_FLOAT)) { $this->decimals = $adofield->scale; } - /// Calculate the notnull field + // Calculate the notnull field if ($adofield->not_null) { $this->notnull = true; } - /// Calculate the default field + // Calculate the default field if ($adofield->has_default) { $this->default = $adofield->default_value; } - /// Calculate the sequence field + // Calculate the sequence field if ($adofield->auto_increment) { $this->sequence = true; } - /// Some more fields + // Some more fields $this->loaded = true; $this->changed = true; } /** * Returns the PHP code needed to define one xmldb_field + * @param bool $includeprevious + * @return string */ function getPHP($includeprevious=true) { $result = ''; - /// The XMLDBTYPE + // The XMLDBTYPE switch ($this->getType()) { case XMLDB_TYPE_INTEGER: $result .= 'XMLDB_TYPE_INTEGER' . ', '; @@ -621,7 +667,7 @@ class xmldb_field extends xmldb_object { $result .= 'XMLDB_TYPE_TIMESTAMP' . ', '; break; } - /// The length + // The length $length = $this->getLength(); $decimals = $this->getDecimals(); if (!empty($length)) { @@ -633,30 +679,30 @@ class xmldb_field extends xmldb_object { } else { $result .= 'null, '; } - /// Unsigned is not used any more since Moodle 2.3 + // Unsigned is not used any more since Moodle 2.3 $result .= 'null, '; - /// Not Null + // Not Null $notnull = $this->getNotnull(); if (!empty($notnull)) { $result .= 'XMLDB_NOTNULL' . ', '; } else { $result .= 'null, '; } - /// Sequence + // Sequence $sequence = $this->getSequence(); if (!empty($sequence)) { $result .= 'XMLDB_SEQUENCE' . ', '; } else { $result .= 'null, '; } - /// Default + // Default $default = $this->getDefault(); if ($default !== null && !$this->getSequence()) { $result .= "'" . $default . "'"; } else { $result .= 'null'; } - /// Previous (decided by parameter) + // Previous (decided by parameter) if ($includeprevious) { $previous = $this->getPrevious(); if (!empty($previous)) { @@ -665,18 +711,19 @@ class xmldb_field extends xmldb_object { $result .= ', null'; } } - /// Return result + // Return result return $result; } /** * Shows info in a readable format + * @return string */ function readableInfo() { $o = ''; - /// type + // type $o .= $this->getXMLDBTypeName($this->type); - /// length + // length if ($this->type == XMLDB_TYPE_INTEGER || $this->type == XMLDB_TYPE_NUMBER || $this->type == XMLDB_TYPE_FLOAT || @@ -692,11 +739,11 @@ class xmldb_field extends xmldb_object { $o .= ')'; } } - /// not null + // not null if ($this->notnull) { $o .= ' not null'; } - /// default + // default if ($this->default !== NULL) { $o .= ' default '; if ($this->type == XMLDB_TYPE_CHAR || @@ -706,7 +753,7 @@ class xmldb_field extends xmldb_object { $o .= $this->default; } } - /// sequence + // sequence if ($this->sequence) { $o .= ' auto-numbered'; } diff --git a/lib/xmldb/xmldb_file.php b/lib/xmldb/xmldb_file.php index 92fa9b162b4..042869ab702 100644 --- a/lib/xmldb/xmldb_file.php +++ b/lib/xmldb/xmldb_file.php @@ -1,40 +1,48 @@ . -/////////////////////////////////////////////////////////////////////////// -// // -// NOTICE OF COPYRIGHT // -// // -// Moodle - Modular Object-Oriented Dynamic Learning Environment // -// http://moodle.com // -// // -// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // -// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // -// // -// This program 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 2 of the License, or // -// (at your option) any later version. // -// // -// This program 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: // -// // -// http://www.gnu.org/copyleft/gpl.html // -// // -/////////////////////////////////////////////////////////////////////////// +/** + * This class represent one XMLDB file + * + * @package core_xmldb + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); -/// This class represents an entire XMLDB file class xmldb_file extends xmldb_object { + /** @var string path to file */ var $path; + + /** @var string path to schema */ var $schema; + + /** @var string document dtd */ var $dtd; + + /** @var xmldb_structure the structure stored in file */ var $xmldb_structure; /** * Constructor of the xmldb_file + * @param string $path */ function __construct($path) { parent::__construct($path); @@ -44,6 +52,7 @@ class xmldb_file extends xmldb_object { /** * Determine if the XML file exists + * @return bool */ function fileExists() { if (file_exists($this->path) && is_readable($this->path)) { @@ -54,6 +63,7 @@ class xmldb_file extends xmldb_object { /** * Determine if the XML is writeable + * @return bool */ function fileWriteable() { if (is_writeable(dirname($this->path))) { @@ -70,10 +80,11 @@ class xmldb_file extends xmldb_object { * This function will check/validate the XML file for correctness * Dynamically if will use the best available checker/validator * (expat syntax checker or DOM schema validator + * @return true */ function validateXMLStructure() { - /// Create and load XML file + // Create and load XML file $parser = new DOMDocument(); $contents = file_get_contents($this->path); if (strpos($contents, '')) { @@ -89,30 +100,30 @@ class xmldb_file extends xmldb_object { libxml_clear_errors(); $parser->loadXML($contents); - /// Only validate if we have a schema + // Only validate if we have a schema if (!empty($this->schema) && file_exists($this->schema)) { $parser->schemaValidate($this->schema); } - /// Check for errors + // Check for errors $errors = libxml_get_errors(); // Stop capturing errors libxml_use_internal_errors($olderrormode); - /// Prepare errors + // Prepare errors if (!empty($errors)) { - /// Create one structure to store errors + // Create one structure to store errors $structure = new xmldb_structure($this->path); - /// Add errors to structure + // Add errors to structure $structure->errormsg = 'XML Error: '; foreach ($errors as $error) { $structure->errormsg .= sprintf("%s at line %d. ", trim($error->message, "\n\r\t ."), $error->line); } - /// Add structure to file + // Add structure to file $this->xmldb_structure = $structure; - /// Check has failed + // Check has failed return false; } @@ -121,10 +132,11 @@ class xmldb_file extends xmldb_object { /** * Load and the XMLDB structure from file + * @return true */ function loadXMLStructure() { if ($this->fileExists()) { - /// Let's validate the XML file + // Let's validate the XML file if (!$this->validateXMLStructure()) { return false; } @@ -134,12 +146,12 @@ class xmldb_file extends xmldb_object { $contents = preg_replace('|.*|s', '', $contents); debugging('STATEMENTS section is not supported any more, please use db/install.php or db/log.php'); } - /// File exists, so let's process it - /// Load everything to a big array + // File exists, so let's process it + // Load everything to a big array $xmlarr = xmlize($contents); - /// Convert array to xmldb structure + // Convert array to xmldb structure $this->xmldb_structure = $this->arr2xmldb_structure($xmlarr); - /// Analize results + // Analyze results if ($this->xmldb_structure->isLoaded()) { $this->loaded = true; return true; @@ -152,6 +164,8 @@ class xmldb_file extends xmldb_object { /** * This function takes an xmlized array and put it into one xmldb_structure + * @param array $xmlarr + * @return xmldb_structure */ function arr2xmldb_structure ($xmlarr) { $structure = new xmldb_structure($this->path); @@ -161,6 +175,7 @@ class xmldb_file extends xmldb_object { /** * This function sets the DTD of the XML file + * @param string */ function setDTD($path) { $this->dtd = $path; @@ -168,6 +183,7 @@ class xmldb_file extends xmldb_object { /** * This function sets the schema of the XML file + * @param string */ function setSchema($path) { $this->schema = $path; @@ -175,6 +191,7 @@ class xmldb_file extends xmldb_object { /** * This function saves the whole xmldb_structure to its file + * @return int|bool false on failure, number of written bytes on success */ function saveXMLFile() { diff --git a/lib/xmldb/xmldb_index.php b/lib/xmldb/xmldb_index.php index 8e02412d43c..7b1b26da277 100644 --- a/lib/xmldb/xmldb_index.php +++ b/lib/xmldb/xmldb_index.php @@ -1,34 +1,37 @@ . -/////////////////////////////////////////////////////////////////////////// -// // -// NOTICE OF COPYRIGHT // -// // -// Moodle - Modular Object-Oriented Dynamic Learning Environment // -// http://moodle.com // -// // -// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // -// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // -// // -// This program 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 2 of the License, or // -// (at your option) any later version. // -// // -// This program 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: // -// // -// http://www.gnu.org/copyleft/gpl.html // -// // -/////////////////////////////////////////////////////////////////////////// +/** + * This class represent one XMLDB Index + * + * @package core_xmldb + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); -/// This class represent one XMLDB Index class xmldb_index extends xmldb_object { + /** @var bool is unique? */ var $unique; + + /** @var array index fields */ var $fields; /** @@ -49,12 +52,16 @@ class xmldb_index extends xmldb_object { /** * Creates one new xmldb_index + * + * @param string $name + * @param string type XMLDB_INDEX_UNIQUE, XMLDB_INDEX_NOTUNIQUE + * @param array fields an array of fieldnames to build the index over */ function __construct($name, $type=null, $fields=array()) { $this->unique = false; $this->fields = array(); parent::__construct($name); - return $this->set_attributes($type, $fields); + $this->set_attributes($type, $fields); } /** @@ -70,6 +77,7 @@ class xmldb_index extends xmldb_object { /** * Get the index unique + * @return bool */ function getUnique() { return $this->unique; @@ -77,6 +85,7 @@ class xmldb_index extends xmldb_object { /** * Set the index unique + * @param bool $unique */ function setUnique($unique = true) { $this->unique = $unique; @@ -84,6 +93,7 @@ class xmldb_index extends xmldb_object { /** * Set the index fields + * @param array $fields */ function setFields($fields) { $this->fields = $fields; @@ -91,6 +101,7 @@ class xmldb_index extends xmldb_object { /** * Get the index fields + * @return array reference to fields array */ function &getFields() { return $this->fields; @@ -98,17 +109,19 @@ class xmldb_index extends xmldb_object { /** * Load data from XML to the index + * @param $xmlarr array + * @return bool */ function arr2xmldb_index($xmlarr) { $result = true; - /// Debug the table - /// traverse_xmlize($xmlarr); //Debug - /// print_object ($GLOBALS['traverse_array']); //Debug - /// $GLOBALS['traverse_array']=""; //Debug + // Debug the table + // traverse_xmlize($xmlarr); //Debug + // print_object ($GLOBALS['traverse_array']); //Debug + // $GLOBALS['traverse_array']=""; //Debug - /// Process key attributes (name, unique, fields, comment, previous, next) + // Process key attributes (name, unique, fields, comment, previous, next) if (isset($xmlarr['@']['NAME'])) { $this->name = trim($xmlarr['@']['NAME']); } else { @@ -157,7 +170,7 @@ class xmldb_index extends xmldb_object { $this->debug($this->errormsg); $result = false; } - /// Finally, set the array of fields + // Finally, set the array of fields $this->fields = $fieldsarr; if (isset($xmlarr['@']['COMMENT'])) { @@ -172,7 +185,7 @@ class xmldb_index extends xmldb_object { $this->next = trim($xmlarr['@']['NEXT']); } - /// Set some attributes + // Set some attributes if ($result) { $this->loaded = true; } @@ -182,6 +195,7 @@ class xmldb_index extends xmldb_object { /** * This function calculate and set the hash of one xmldb_index + * @retur nvoid, changes $this->hash */ function calculateHash($recursive = false) { if (!$this->loaded) { @@ -194,6 +208,7 @@ class xmldb_index extends xmldb_object { /** *This function will output the XML text for one index + * @return string */ function xmlOutput() { $o = ''; @@ -222,56 +237,60 @@ class xmldb_index extends xmldb_object { /** * This function will set all the attributes of the xmldb_index object * based on information passed in one ADOindex + * @param array + * @return void */ function setFromADOIndex($adoindex) { - /// Set the unique field + // Set the unique field $this->unique = false; - /// Set the fields, converting all them to lowercase + // Set the fields, converting all them to lowercase $fields = array_flip(array_change_key_case(array_flip($adoindex['columns']))); $this->fields = $fields; - /// Some more fields + // Some more fields $this->loaded = true; $this->changed = true; } /** * Returns the PHP code needed to define one xmldb_index + * @return string */ function getPHP() { $result = ''; - /// The type + // The type $unique = $this->getUnique(); if (!empty($unique)) { $result .= 'XMLDB_INDEX_UNIQUE, '; } else { $result .= 'XMLDB_INDEX_NOTUNIQUE, '; } - /// The fields + // The fields $indexfields = $this->getFields(); if (!empty($indexfields)) { $result .= 'array(' . "'". implode("', '", $indexfields) . "')"; } else { $result .= 'null'; } - /// Return result + // Return result return $result; } /** * Shows info in a readable format + * @return string */ function readableInfo() { $o = ''; - /// unique + // unique if ($this->unique) { $o .= 'unique'; } else { $o .= 'not unique'; } - /// fields + // fields $o .= ' (' . implode(', ', $this->fields) . ')'; return $o; @@ -344,5 +363,4 @@ class xmldb_index extends xmldb_object { return null; } - } diff --git a/lib/xmldb/xmldb_key.php b/lib/xmldb/xmldb_key.php index de02a3f72d9..03636e65e97 100644 --- a/lib/xmldb/xmldb_key.php +++ b/lib/xmldb/xmldb_key.php @@ -1,40 +1,52 @@ . -/////////////////////////////////////////////////////////////////////////// -// // -// NOTICE OF COPYRIGHT // -// // -// Moodle - Modular Object-Oriented Dynamic Learning Environment // -// http://moodle.com // -// // -// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // -// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // -// // -// This program 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 2 of the License, or // -// (at your option) any later version. // -// // -// This program 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: // -// // -// http://www.gnu.org/copyleft/gpl.html // -// // -/////////////////////////////////////////////////////////////////////////// +/** + * This class represent one XMLDB Key + * + * @package core_xmldb + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); -/// This class represent one XMLDB Key class xmldb_key extends xmldb_object { + /** @var int type of key */ var $type; + + /** @var array of fields */ var $fields; + + /** @var string referenced table */ var $reftable; + + /** @var array referenced fields */ var $reffields; /** * Creates one new xmldb_key + * @param string $name + * @param string $type XMLDB_KEY_[PRIMARY|UNIQUE|FOREIGN|FOREIGN_UNIQUE] + * @param array $fields an array of fieldnames to build the key over + * @param string $reftable name of the table the FK points to or null + * @param array $reffields an array of fieldnames in the FK table or null */ function __construct($name, $type=null, $fields=array(), $reftable=null, $reffields=null) { $this->type = NULL; @@ -48,10 +60,10 @@ class xmldb_key extends xmldb_object { /** * Set all the attributes of one xmldb_key * - * @param string type XMLDB_KEY_[PRIMARY|UNIQUE|FOREIGN|FOREIGN_UNIQUE] - * @param array fields an array of fieldnames to build the key over - * @param string reftable name of the table the FK points to or null - * @param array reffields an array of fieldnames in the FK table or null + * @param string $type XMLDB_KEY_[PRIMARY|UNIQUE|FOREIGN|FOREIGN_UNIQUE] + * @param array $fields an array of fieldnames to build the key over + * @param string $reftable name of the table the FK points to or null + * @param array $reffields an array of fieldnames in the FK table or null */ function set_attributes($type, $fields, $reftable=null, $reffields=null) { $this->type = $type; @@ -62,6 +74,7 @@ class xmldb_key extends xmldb_object { /** * Get the key type + * @return int */ function getType() { return $this->type; @@ -69,6 +82,7 @@ class xmldb_key extends xmldb_object { /** * Set the key type + * @param int $type */ function setType($type) { $this->type = $type; @@ -76,6 +90,7 @@ class xmldb_key extends xmldb_object { /** * Set the key fields + * @param array $fields */ function setFields($fields) { $this->fields = $fields; @@ -83,6 +98,7 @@ class xmldb_key extends xmldb_object { /** * Set the key reftable + * @param string $reftable */ function setRefTable($reftable) { $this->reftable = $reftable; @@ -90,6 +106,7 @@ class xmldb_key extends xmldb_object { /** * Set the key reffields + * @param array $reffields */ function setRefFields($reffields) { $this->reffields = $reffields; @@ -97,6 +114,7 @@ class xmldb_key extends xmldb_object { /** * Get the key fields + * @return array reference to fields array */ function &getFields() { return $this->fields; @@ -104,6 +122,7 @@ class xmldb_key extends xmldb_object { /** * Get the key reftable + * @return string reference */ function &getRefTable() { return $this->reftable; @@ -111,6 +130,7 @@ class xmldb_key extends xmldb_object { /** * Get the key reffields + * @return array reference to ref fields */ function &getRefFields() { return $this->reffields; @@ -118,18 +138,20 @@ class xmldb_key extends xmldb_object { /** * Load data from XML to the key + * @param array $xmlarr + * @return bool success */ function arr2xmldb_key($xmlarr) { $result = true; - /// Debug the table - /// traverse_xmlize($xmlarr); //Debug - /// print_object ($GLOBALS['traverse_array']); //Debug - /// $GLOBALS['traverse_array']=""; //Debug + // Debug the table + // traverse_xmlize($xmlarr); //Debug + // print_object ($GLOBALS['traverse_array']); //Debug + // $GLOBALS['traverse_array']=""; //Debug - /// Process key attributes (name, type, fields, reftable, - /// reffields, comment, previous, next) + // Process key attributes (name, type, fields, reftable, + // reffields, comment, previous, next) if (isset($xmlarr['@']['NAME'])) { $this->name = trim($xmlarr['@']['NAME']); } else { @@ -139,7 +161,7 @@ class xmldb_key extends xmldb_object { } if (isset($xmlarr['@']['TYPE'])) { - /// Check for valid type + // Check for valid type $type = $this->getXMLDBKeyType(trim($xmlarr['@']['TYPE'])); if ($type) { $this->type = $type; @@ -177,11 +199,11 @@ class xmldb_key extends xmldb_object { $this->debug($this->errormsg); $result = false; } - /// Finally, set the array of fields + // Finally, set the array of fields $this->fields = $fieldsarr; if (isset($xmlarr['@']['REFTABLE'])) { - /// Check we are in a FK + // Check we are in a FK if ($this->type == XMLDB_KEY_FOREIGN || $this->type == XMLDB_KEY_FOREIGN_UNIQUE) { $reftable = strtolower(trim($xmlarr['@']['REFTABLE'])); @@ -201,14 +223,14 @@ class xmldb_key extends xmldb_object { $this->debug($this->errormsg); $result = false; } - /// Finally, set the reftable + // Finally, set the reftable if ($this->type == XMLDB_KEY_FOREIGN || $this->type == XMLDB_KEY_FOREIGN_UNIQUE) { $this->reftable = $reftable; } if (isset($xmlarr['@']['REFFIELDS'])) { - /// Check we are in a FK + // Check we are in a FK if ($this->type == XMLDB_KEY_FOREIGN || $this->type == XMLDB_KEY_FOREIGN_UNIQUE) { $reffields = strtolower(trim($xmlarr['@']['REFFIELDS'])); @@ -239,7 +261,7 @@ class xmldb_key extends xmldb_object { $this->debug($this->errormsg); $result = false; } - /// Finally, set the array of reffields + // Finally, set the array of reffields if ($this->type == XMLDB_KEY_FOREIGN || $this->type == XMLDB_KEY_FOREIGN_UNIQUE) { $this->reffields = $reffieldsarr; @@ -257,7 +279,7 @@ class xmldb_key extends xmldb_object { $this->next = trim($xmlarr['@']['NEXT']); } - /// Set some attributes + // Set some attributes if ($result) { $this->loaded = true; } @@ -268,6 +290,8 @@ class xmldb_key extends xmldb_object { /** * This function returns the correct XMLDB_KEY_XXX value for the * string passed as argument + * @param string $type + * @return int */ function getXMLDBKeyType($type) { @@ -286,23 +310,25 @@ class xmldb_key extends xmldb_object { case 'foreign-unique': $result = XMLDB_KEY_FOREIGN_UNIQUE; break; - /// case 'check': //Not supported - /// $result = XMLDB_KEY_CHECK; - /// break; + // case 'check': //Not supported + // $result = XMLDB_KEY_CHECK; + // break; } - /// Return the normalized XMLDB_KEY + // Return the normalized XMLDB_KEY return $result; } /** * This function returns the correct name value for the * XMLDB_KEY_XXX passed as argument + * @param int $type + * @return string */ function getXMLDBKeyName($type) { $result = ''; - switch (strtolower($type)) { + switch ($type) { case XMLDB_KEY_PRIMARY: $result = 'primary'; break; @@ -315,16 +341,17 @@ class xmldb_key extends xmldb_object { case XMLDB_KEY_FOREIGN_UNIQUE: $result = 'foreign-unique'; break; - /// case XMLDB_KEY_CHECK: //Not supported - /// $result = 'check'; - /// break; + // case XMLDB_KEY_CHECK: //Not supported + // $result = 'check'; + // break; } - /// Return the normalized name + // Return the normalized name return $result; } /** * This function calculate and set the hash of one xmldb_key + * @param bool $recursive */ function calculateHash($recursive = false) { if (!$this->loaded) { @@ -342,6 +369,7 @@ class xmldb_key extends xmldb_object { /** *This function will output the XML text for one key + * @return string */ function xmlOutput() { $o = ''; @@ -370,10 +398,11 @@ class xmldb_key extends xmldb_object { /** * This function will set all the attributes of the xmldb_key object * based on information passed in one ADOkey + * @oaram array $adokey */ function setFromADOKey($adokey) { - /// Calculate the XMLDB_KEY + // Calculate the XMLDB_KEY switch (strtolower($adokey['name'])) { case 'primary': $this->type = XMLDB_KEY_PRIMARY; @@ -381,22 +410,23 @@ class xmldb_key extends xmldb_object { default: $this->type = XMLDB_KEY_UNIQUE; } - /// Set the fields, converting all them to lowercase + // Set the fields, converting all them to lowercase $fields = array_flip(array_change_key_case(array_flip($adokey['columns']))); $this->fields = $fields; - /// Some more fields + // Some more fields $this->loaded = true; $this->changed = true; } /** * Returns the PHP code needed to define one xmldb_key + * @return string */ function getPHP() { $result = ''; - /// The type + // The type switch ($this->getType()) { case XMLDB_KEY_PRIMARY: $result .= 'XMLDB_KEY_PRIMARY' . ', '; @@ -411,24 +441,24 @@ class xmldb_key extends xmldb_object { $result .= 'XMLDB_KEY_FOREIGN_UNIQUE' . ', '; break; } - /// The fields + // The fields $keyfields = $this->getFields(); if (!empty($keyfields)) { $result .= 'array(' . "'". implode("', '", $keyfields) . "')"; } else { $result .= 'null'; } - /// The FKs attributes + // The FKs attributes if ($this->getType() == XMLDB_KEY_FOREIGN || $this->getType() == XMLDB_KEY_FOREIGN_UNIQUE) { - /// The reftable + // The reftable $reftable = $this->getRefTable(); if (!empty($reftable)) { $result .= ", '" . $reftable . "', "; } else { $result .= 'null, '; } - /// The reffields + // The reffields $reffields = $this->getRefFields(); if (!empty($reffields)) { $result .= 'array(' . "'". implode("', '", $reffields) . "')"; @@ -436,20 +466,21 @@ class xmldb_key extends xmldb_object { $result .= 'null'; } } - /// Return result + // Return result return $result; } /** * Shows info in a readable format + * @return string */ function readableInfo() { $o = ''; - /// type + // type $o .= $this->getXMLDBKeyName($this->type); - /// fields + // fields $o .= ' (' . implode(', ', $this->fields) . ')'; - /// foreign key + // foreign key if ($this->type == XMLDB_KEY_FOREIGN || $this->type == XMLDB_KEY_FOREIGN_UNIQUE) { $o .= ' references ' . $this->reftable . ' (' . implode(', ', $this->reffields) . ')'; diff --git a/lib/xmldb/xmldb_object.php b/lib/xmldb/xmldb_object.php index 4fd59acbee5..3683028cf21 100644 --- a/lib/xmldb/xmldb_object.php +++ b/lib/xmldb/xmldb_object.php @@ -1,45 +1,60 @@ . -/////////////////////////////////////////////////////////////////////////// -// // -// NOTICE OF COPYRIGHT // -// // -// Moodle - Modular Object-Oriented Dynamic Learning Environment // -// http://moodle.com // -// // -// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // -// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // -// // -// This program 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 2 of the License, or // -// (at your option) any later version. // -// // -// This program 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: // -// // -// http://www.gnu.org/copyleft/gpl.html // -// // -/////////////////////////////////////////////////////////////////////////// +/** + * This class represent the XMLDB base class where all the common pieces are defined + * + * @package core_xmldb + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); -/// This class represent the XMLDB base class where all the common pieces -/// are defined class xmldb_object { + /** @var string name of obejct */ var $name; + + /** @var string comment on object */ var $comment; + + /** @var xmldb_object */ var $previous; + + /** @var xmldb_object */ var $next; + + /** @var string hash of object */ var $hash; + + /** @var bool is it loaded yet */ var $loaded; + + /** @var bool was object changed */ var $changed; + + /** @var string error message */ var $errormsg; /** * Creates one new xmldb_object + * @param string $name */ function __construct($name) { $this->name = $name; @@ -54,6 +69,7 @@ class xmldb_object { /** * This function returns true/false, if the xmldb_object has been loaded + * @return bool */ function isLoaded() { return $this->loaded; @@ -61,6 +77,7 @@ class xmldb_object { /** * This function returns true/false, if the xmldb_object has changed + * @return bool */ function hasChanged() { return $this->changed; @@ -68,6 +85,7 @@ class xmldb_object { /** * This function returns the comment of one xmldb_object + * @return string */ function getComment() { return $this->comment; @@ -75,6 +93,7 @@ class xmldb_object { /** * This function returns the hash of one xmldb_object + * @return string */ function getHash() { return $this->hash; @@ -82,6 +101,7 @@ class xmldb_object { /** * This function will return the name of the previous xmldb_object + * @return xmldb_object */ function getPrevious() { return $this->previous; @@ -89,6 +109,7 @@ class xmldb_object { /** * This function will return the name of the next xmldb_object + * @return xmldb_object */ function getNext() { return $this->next; @@ -96,6 +117,7 @@ class xmldb_object { /** * This function will return the name of the xmldb_object + * @return string */ function getName() { return $this->name; @@ -103,6 +125,7 @@ class xmldb_object { /** * This function will return the error detected in the object + * @return string */ function getError() { return $this->errormsg; @@ -110,6 +133,7 @@ class xmldb_object { /** * This function will set the comment of the xmldb_object + * @param string $comment */ function setComment($comment) { $this->comment = $comment; @@ -117,6 +141,7 @@ class xmldb_object { /** * This function will set the previous of the xmldb_object + * @param xmldb_object $previous */ function setPrevious($previous) { $this->previous = $previous; @@ -124,6 +149,7 @@ class xmldb_object { /** * This function will set the next of the xmldb_object + * @param xmldb_object $next */ function setNext($next) { $this->next = $next; @@ -131,6 +157,7 @@ class xmldb_object { /** * This function will set the hash of the xmldb_object + * @param string $hash */ function setHash($hash) { $this->hash = $hash; @@ -138,6 +165,7 @@ class xmldb_object { /** * This function will set the loaded field of the xmldb_object + * @param bool $loaded */ function setLoaded($loaded = true) { $this->loaded = $loaded; @@ -145,12 +173,14 @@ class xmldb_object { /** * This function will set the changed field of the xmldb_object + * @param bool $changed */ function setChanged($changed = true) { $this->changed = $changed; } /** * This function will set the name field of the xmldb_object + * @param string $name */ function setName($name) { $this->name = $name; @@ -160,6 +190,7 @@ class xmldb_object { /** * This function will check if one key name is ok or no (true/false) * only lowercase a-z, 0-9 and _ are allowed + * @return bool */ function checkName () { $result = true; @@ -173,12 +204,14 @@ class xmldb_object { /** * This function will check that all the elements in one array * have a correct name [a-z0-9_] + * @param array $arr + * @return bool */ function checkNameValues(&$arr) { $result = true; - /// TODO: Perhaps, add support for reserved words + // TODO: Perhaps, add support for reserved words - /// Check the name only contains valid chars + // Check the name only contains valid chars if ($arr) { foreach($arr as $element) { if (!$element->checkName()) { @@ -186,7 +219,7 @@ class xmldb_object { } } } - /// Check there aren't duplicate names + // Check there aren't duplicate names if ($arr) { $existing_fields = array(); foreach($arr as $element) { @@ -202,6 +235,8 @@ class xmldb_object { /** * Reconstruct previous/next attributes. + * @param array $arr + * @return bool */ function fixPrevNext(&$arr) { global $CFG; @@ -235,6 +270,8 @@ class xmldb_object { /** * This function will check that all the elements in one array * have a consistent info in their previous/next fields + * @param array $arr + * @return bool */ function checkPreviousNextValues(&$arr) { global $CFG; @@ -242,7 +279,7 @@ class xmldb_object { return true; } $result = true; - /// Check that only one element has the previous not set + // Check that only one element has the previous not set if ($arr) { $counter = 0; foreach($arr as $element) { @@ -255,7 +292,7 @@ class xmldb_object { $result = false; } } - /// Check that only one element has the next not set + // Check that only one element has the next not set if ($result && $arr) { $counter = 0; foreach($arr as $element) { @@ -268,7 +305,7 @@ class xmldb_object { $result = false; } } - /// Check that all the previous elements are existing elements + // Check that all the previous elements are existing elements if ($result && $arr) { foreach($arr as $element) { if ($element->getPrevious()) { @@ -280,7 +317,7 @@ class xmldb_object { } } } - /// Check that all the next elements are existing elements + // Check that all the next elements are existing elements if ($result && $arr) { foreach($arr as $element) { if ($element->getNext()) { @@ -292,7 +329,7 @@ class xmldb_object { } } } - /// Check that there aren't duplicates in the previous values + // Check that there aren't duplicates in the previous values if ($result && $arr) { $existarr = array(); foreach($arr as $element) { @@ -304,7 +341,7 @@ class xmldb_object { } } } - /// Check that there aren't duplicates in the next values + // Check that there aren't duplicates in the next values if ($result && $arr) { $existarr = array(); foreach($arr as $element) { @@ -316,7 +353,7 @@ class xmldb_object { } } } - /// Check that there aren't next values pointing to themselves + // Check that there aren't next values pointing to themselves if ($result && $arr) { foreach($arr as $element) { if ($element->getNext() == $element->getName()) { @@ -325,7 +362,7 @@ class xmldb_object { } } } - /// Check that there aren't prev values pointing to themselves + // Check that there aren't prev values pointing to themselves if ($result && $arr) { foreach($arr as $element) { if ($element->getPrevious() == $element->getName()) { @@ -340,6 +377,8 @@ class xmldb_object { /** * This function will order all the elements in one array, following * the previous/next rules + * @param array $arr + * @return array|bool */ function orderElements($arr) { global $CFG; @@ -347,11 +386,11 @@ class xmldb_object { if (!empty($CFG->xmldbdisablenextprevchecking)) { return $arr; } - /// Create a new array + // Create a new array $newarr = array(); if (!empty($arr)) { $currentelement = NULL; - /// Get the element without previous + // Get the element without previous foreach($arr as $key => $element) { if (!$element->getPrevious()) { $currentelement = $arr[$key]; @@ -361,7 +400,7 @@ class xmldb_object { if (!$currentelement) { $result = false; } - /// Follow the next rules + // Follow the next rules $counter = 1; while ($result && $currentelement->getNext()) { $i = $this->findObjectInArray($currentelement->getNext(), $arr); @@ -369,11 +408,11 @@ class xmldb_object { $newarr[$counter] = $arr[$i]; $counter++; } - /// Compare number of elements between original and new array + // Compare number of elements between original and new array if ($result && count($arr) != count($newarr)) { $result = false; } - /// Check that previous/next is ok (redundant but...) + // Check that previous/next is ok (redundant but...) if ($this->checkPreviousNextValues($newarr)) { $result = $newarr; } else { @@ -387,6 +426,9 @@ class xmldb_object { /** * Returns the position of one object in the array. + * @param string $objectname + * @param array $arr + * @return mixed */ function &findObjectInArray($objectname, $arr) { foreach ($arr as $i => $object) { @@ -401,6 +443,7 @@ class xmldb_object { /** * This function will display a readable info about the xmldb_object * (should be implemented inside each XMLDBxxx object) + * @return string */ function readableInfo() { return get_class($this); @@ -416,12 +459,13 @@ class xmldb_object { * * Call to the external hook function can be disabled by request by * defining XMLDB_SKIP_DEBUG_HOOK + * @param string $message */ function debug($message) { - /// Check for xmldb_debug($message, $xmldb_object) + // Check for xmldb_debug($message, $xmldb_object) $funcname = 'xmldb_debug'; - /// If exists and XMLDB_SKIP_DEBUG_HOOK is undefined + // If exists and XMLDB_SKIP_DEBUG_HOOK is undefined if (function_exists($funcname) && !defined('XMLDB_SKIP_DEBUG_HOOK')) { $funcname($message, $this); } @@ -430,13 +474,15 @@ class xmldb_object { /** * Returns one array of elements from one comma separated string, * supporting quoted strings containing commas and concat function calls + * @param string $string + * @return array */ function comma2array($string) { $foundquotes = array(); $foundconcats = array(); - /// Extract all the concat elements from the string + // Extract all the concat elements from the string preg_match_all("/(CONCAT\(.*?\))/is", $string, $matches); foreach (array_unique($matches[0]) as $key=>$value) { $foundconcats['<#'.$key.'#>'] = $value; @@ -445,8 +491,8 @@ class xmldb_object { $string = str_replace($foundconcats,array_keys($foundconcats),$string); } - /// Extract all the quoted elements from the string (skipping - /// backslashed quotes that are part of the content. + // Extract all the quoted elements from the string (skipping + // backslashed quotes that are part of the content. preg_match_all("/(''|'.*?[^\\\\]')/is", $string, $matches); foreach (array_unique($matches[0]) as $key=>$value) { $foundquotes['<%'.$key.'%>'] = $value; @@ -455,23 +501,23 @@ class xmldb_object { $string = str_replace($foundquotes,array_keys($foundquotes),$string); } - /// Explode safely the string + // Explode safely the string $arr = explode (',', $string); - /// Put the concat and quoted elements back again, trimming every element + // Put the concat and quoted elements back again, trimming every element if ($arr) { foreach ($arr as $key => $element) { - /// Clear some spaces + // Clear some spaces $element = trim($element); - /// Replace the quoted elements if exists + // Replace the quoted elements if exists if (!empty($foundquotes)) { $element = str_replace(array_keys($foundquotes), $foundquotes, $element); } - /// Replace the concat elements if exists + // Replace the concat elements if exists if (!empty($foundconcats)) { $element = str_replace(array_keys($foundconcats), $foundconcats, $element); } - /// Delete any backslash used for quotes. XMLDB stuff will add them before insert + // Delete any backslash used for quotes. XMLDB stuff will add them before insert $arr[$key] = str_replace("\\'", "'", $element); } } diff --git a/lib/xmldb/xmldb_structure.php b/lib/xmldb/xmldb_structure.php index 41e48bb12d8..0b34cac140a 100644 --- a/lib/xmldb/xmldb_structure.php +++ b/lib/xmldb/xmldb_structure.php @@ -1,39 +1,45 @@ . -/////////////////////////////////////////////////////////////////////////// -// // -// NOTICE OF COPYRIGHT // -// // -// Moodle - Modular Object-Oriented Dynamic Learning Environment // -// http://moodle.com // -// // -// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // -// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // -// // -// This program 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 2 of the License, or // -// (at your option) any later version. // -// // -// This program 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: // -// // -// http://www.gnu.org/copyleft/gpl.html // -// // -/////////////////////////////////////////////////////////////////////////// +/** + * This class represent one XMLDB structure + * + * @package core_xmldb + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); -/// This class represent one XMLDB structure class xmldb_structure extends xmldb_object { + /** @var string */ var $path; + + /** @var string */ var $version; + + /** @var array tables */ var $tables; /** * Creates one new xmldb_structure + * @param string $name */ function __construct($name) { parent::__construct($name); @@ -44,6 +50,7 @@ class xmldb_structure extends xmldb_object { /** * Returns the path of the structure + * @return string */ function getPath() { return $this->path; @@ -51,6 +58,7 @@ class xmldb_structure extends xmldb_object { /** * Returns the version of the structure + * @return string */ function getVersion() { return $this->version; @@ -58,6 +66,8 @@ class xmldb_structure extends xmldb_object { /** * Returns one xmldb_table + * @param string $tablename + * @return xmldb_table */ function &getTable($tablename) { $i = $this->findTableInArray($tablename); @@ -70,6 +80,8 @@ class xmldb_structure extends xmldb_object { /** * Returns the position of one table in the array. + * @param string $tablename + * @return xmldb_table */ function &findTableInArray($tablename) { foreach ($this->tables as $i => $table) { @@ -83,6 +95,7 @@ class xmldb_structure extends xmldb_object { /** * This function will reorder the array of tables + * @return bool success */ function orderTables() { $result = $this->orderElements($this->tables); @@ -96,6 +109,7 @@ class xmldb_structure extends xmldb_object { /** * Returns the tables of the structure + * @return array reference to table arrays */ function &getTables() { return $this->tables; @@ -103,6 +117,7 @@ class xmldb_structure extends xmldb_object { /** * Set the structure version + * @param string version */ function setVersion($version) { $this->version = $version; @@ -111,10 +126,12 @@ class xmldb_structure extends xmldb_object { /** * Add one table to the structure, allowing to specify the desired order * If it's not specified, then the table is added at the end. + * @param xmldb_table $table + * @param mixed $after */ function addTable(&$table, $after=NULL) { - /// Calculate the previous and next tables + // Calculate the previous and next tables $prevtable = NULL; $nexttable = NULL; @@ -131,7 +148,7 @@ class xmldb_structure extends xmldb_object { $nexttable =& $this->getTable($prevtable->getNext()); } - /// Set current table previous and next attributes + // Set current table previous and next attributes if ($prevtable) { $table->setPrevious($prevtable->getName()); $prevtable->setNext($table->getName()); @@ -140,45 +157,46 @@ class xmldb_structure extends xmldb_object { $table->setNext($nexttable->getName()); $nexttable->setPrevious($table->getName()); } - /// Some more attributes + // Some more attributes $table->setLoaded(true); $table->setChanged(true); - /// Add the new table + // Add the new table $this->tables[] =& $table; - /// Reorder the whole structure + // Reorder the whole structure $this->orderTables($this->tables); - /// Recalculate the hash + // Recalculate the hash $this->calculateHash(true); - /// We have one new table, so the structure has changed + // We have one new table, so the structure has changed $this->setVersion(userdate(time(), '%Y%m%d', 99, false)); $this->setChanged(true); } /** * Delete one table from the Structure + * @param string $tablename */ function deleteTable($tablename) { $table =& $this->getTable($tablename); if ($table) { $i = $this->findTableInArray($tablename); - /// Look for prev and next table + // Look for prev and next table $prevtable =& $this->getTable($table->getPrevious()); $nexttable =& $this->getTable($table->getNext()); - /// Change their previous and next attributes + // Change their previous and next attributes if ($prevtable) { $prevtable->setNext($table->getNext()); } if ($nexttable) { $nexttable->setPrevious($table->getPrevious()); } - /// Delete the table + // Delete the table unset($this->tables[$i]); - /// Reorder the tables + // Reorder the tables $this->orderTables($this->tables); - /// Recalculate the hash + // Recalculate the hash $this->calculateHash(true); - /// We have one deleted table, so the structure has changed + // We have one deleted table, so the structure has changed $this->setVersion(userdate(time(), '%Y%m%d', 99, false)); $this->setChanged(true); } @@ -186,6 +204,7 @@ class xmldb_structure extends xmldb_object { /** * Set the tables + * @param array $tables */ function setTables(&$tables) { $this->tables = $tables; @@ -193,6 +212,8 @@ class xmldb_structure extends xmldb_object { /** * Load data from XML to the structure + * @param array $xmlarr + * @return bool */ function arr2xmldb_structure($xmlarr) { @@ -200,12 +221,12 @@ class xmldb_structure extends xmldb_object { $result = true; - /// Debug the structure - /// traverse_xmlize($xmlarr); //Debug - /// print_object ($GLOBALS['traverse_array']); //Debug - /// $GLOBALS['traverse_array']=""; //Debug + // Debug the structure + // traverse_xmlize($xmlarr); //Debug + // print_object ($GLOBALS['traverse_array']); //Debug + // $GLOBALS['traverse_array']=""; //Debug - /// Process structure attributes (path, comment and version) + // Process structure attributes (path, comment and version) if (isset($xmlarr['XMLDB']['@']['PATH'])) { $this->path = trim($xmlarr['XMLDB']['@']['PATH']); } else { @@ -230,7 +251,7 @@ class xmldb_structure extends xmldb_object { $result = false; } - /// Iterate over tables + // Iterate over tables if (isset($xmlarr['XMLDB']['#']['TABLES']['0']['#']['TABLE'])) { foreach ($xmlarr['XMLDB']['#']['TABLES']['0']['#']['TABLE'] as $xmltable) { if (!$result) { //Skip on error @@ -252,22 +273,22 @@ class xmldb_structure extends xmldb_object { $result = false; } - /// Perform some general checks over tables + // Perform some general checks over tables if ($result && $this->tables) { - /// Check tables names are ok (lowercase, a-z _-) + // Check tables names are ok (lowercase, a-z _-) if (!$this->checkNameValues($this->tables)) { $this->errormsg = 'Some TABLES name values are incorrect'; $this->debug($this->errormsg); $result = false; } - /// Check previous & next are ok (duplicates and existing tables) + // Check previous & next are ok (duplicates and existing tables) $this->fixPrevNext($this->tables); if ($result && !$this->checkPreviousNextValues($this->tables)) { $this->errormsg = 'Some TABLES previous/next values are incorrect'; $this->debug($this->errormsg); $result = false; } - /// Order tables + // Order tables if ($result && !$this->orderTables($this->tables)) { $this->errormsg = 'Error ordering the tables'; $this->debug($this->errormsg); @@ -275,7 +296,7 @@ class xmldb_structure extends xmldb_object { } } - /// Set some attributes + // Set some attributes if ($result) { $this->loaded = true; } @@ -285,6 +306,7 @@ class xmldb_structure extends xmldb_object { /** * This function calculate and set the hash of one xmldb_structure + * @param bool $recursive */ function calculateHash($recursive = false) { if (!$this->loaded) { @@ -306,6 +328,7 @@ class xmldb_structure extends xmldb_object { /** * This function will output the XML text for one structure + * @return string */ function xmlOutput() { $o = '' . "\n"; @@ -319,7 +342,7 @@ class xmldb_structure extends xmldb_object { $o.= ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'."\n"; $o.= ' xsi:noNamespaceSchemaLocation="'.$rel.'/lib/xmldb/xmldb.xsd"'."\n"; $o.= '>' . "\n"; - /// Now the tables + // Now the tables if ($this->tables) { $o.= ' ' . "\n"; foreach ($this->tables as $table) { @@ -336,13 +359,15 @@ class xmldb_structure extends xmldb_object { * This function returns the number of uses of one table inside * a whole XMLDStructure. Useful to detect if the table must be * locked. Return false if no uses are found. + * @param string $tablename + * @return mixed */ function getTableUses($tablename) { $uses = array(); - /// Check if some foreign key in the whole structure is using it - /// (by comparing the reftable with the tablename) + // Check if some foreign key in the whole structure is using it + // (by comparing the reftable with the tablename) $alltables = $this->getTables(); if ($alltables) { foreach ($alltables as $table) { @@ -359,7 +384,7 @@ class xmldb_structure extends xmldb_object { } } - /// Return result + // Return result if (!empty($uses)) { return $uses; } else { @@ -371,12 +396,15 @@ class xmldb_structure extends xmldb_object { * This function returns the number of uses of one field inside * a whole xmldb_structure. Useful to detect if the field must be * locked. Return false if no uses are found. + * @param string $tablename + * @param string $fieldname + * @return mixed */ function getFieldUses($tablename, $fieldname) { $uses = array(); - /// Check if any key in the table is using it + // Check if any key in the table is using it $table = $this->getTable($tablename); if ($keys = $table->getKeys()) { foreach ($keys as $key) { @@ -386,7 +414,7 @@ class xmldb_structure extends xmldb_object { } } } - /// Check if any index in the table is using it + // Check if any index in the table is using it $table = $this->getTable($tablename); if ($indexes = $table->getIndexes()) { foreach ($indexes as $index) { @@ -395,8 +423,8 @@ class xmldb_structure extends xmldb_object { } } } - /// Check if some foreign key in the whole structure is using it - /// By comparing the reftable and refields with the field) + // Check if some foreign key in the whole structure is using it + // By comparing the reftable and refields with the field) $alltables = $this->getTables(); if ($alltables) { foreach ($alltables as $table) { @@ -416,7 +444,7 @@ class xmldb_structure extends xmldb_object { } } - /// Return result + // Return result if (!empty($uses)) { return $uses; } else { @@ -428,13 +456,16 @@ class xmldb_structure extends xmldb_object { * This function returns the number of uses of one key inside * a whole xmldb_structure. Useful to detect if the key must be * locked. Return false if no uses are found. + * @param string $tablename + * @param string $keyname + * @return mixed */ function getKeyUses($tablename, $keyname) { $uses = array(); - /// Check if some foreign key in the whole structure is using it - /// (by comparing the reftable and reffields with the fields in the key) + // Check if some foreign key in the whole structure is using it + // (by comparing the reftable and reffields with the fields in the key) $mytable = $this->getTable($tablename); $mykey = $mytable->getKey($keyname); $alltables = $this->getTables(); @@ -455,7 +486,7 @@ class xmldb_structure extends xmldb_object { } } - /// Return result + // Return result if (!empty($uses)) { return $uses; } else { @@ -467,15 +498,18 @@ class xmldb_structure extends xmldb_object { * This function returns the number of uses of one index inside * a whole xmldb_structure. Useful to detect if the index must be * locked. Return false if no uses are found. + * @param string $tablename + * @param string $indexname + * @return mixed */ function getIndexUses($tablename, $indexname) { $uses = array(); - /// Nothing to check, beause indexes haven't uses! Leave it here - /// for future checks... + // Nothing to check, beause indexes haven't uses! Leave it here + // for future checks... - /// Return result + // Return result if (!empty($uses)) { return $uses; } else { @@ -487,27 +521,28 @@ class xmldb_structure extends xmldb_object { * This function will return all the errors found in one structure * looking recursively inside each table. Returns * an array of errors or false + * @return mixed */ function getAllErrors() { $errors = array(); - /// First the structure itself + // First the structure itself if ($this->getError()) { $errors[] = $this->getError(); } - /// Delegate to tables + // Delegate to tables if ($tables = $this->getTables()) { foreach ($tables as $table) { if ($tableerrors = $table->getAllErrors()) { } } - /// Add them to the errors array + // Add them to the errors array if ($tableerrors) { $errors = array_merge($errors, $tableerrors); } } - /// Return decision + // Return decision if (count($errors)) { return $errors; } else { diff --git a/lib/xmldb/xmldb_table.php b/lib/xmldb/xmldb_table.php index 614354fed52..14f560f4f5c 100644 --- a/lib/xmldb/xmldb_table.php +++ b/lib/xmldb/xmldb_table.php @@ -1,35 +1,40 @@ . -/////////////////////////////////////////////////////////////////////////// -// // -// NOTICE OF COPYRIGHT // -// // -// Moodle - Modular Object-Oriented Dynamic Learning Environment // -// http://moodle.com // -// // -// Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com // -// (C) 2001-3001 Eloy Lafuente (stronk7) http://contiento.com // -// // -// This program 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 2 of the License, or // -// (at your option) any later version. // -// // -// This program 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: // -// // -// http://www.gnu.org/copyleft/gpl.html // -// // -/////////////////////////////////////////////////////////////////////////// +/** + * This class represent one XMLDB table + * + * @package core_xmldb + * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com + * 2001-3001 Eloy Lafuente (stronk7) http://contiento.com + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +defined('MOODLE_INTERNAL') || die(); -/// This class represent one XMLDB table class xmldb_table extends xmldb_object { + /** @var array table columns */ var $fields; + + /** @var array keys */ var $keys; + + /** @var array indexes */ var $indexes; /** @@ -43,6 +48,7 @@ class xmldb_table extends xmldb_object { /** * Creates one new xmldb_table + * @param string $name */ function __construct($name) { parent::__construct($name); @@ -54,15 +60,18 @@ class xmldb_table extends xmldb_object { /** * Add one field to the table, allowing to specify the desired order * If it's not specified, then the field is added at the end + * @param xmldb_field $field + * @param xmldb_object $after + * @return xmldb_field */ function addField(&$field, $after=NULL) { - /// Detect duplicates first + // Detect duplicates first if ($this->getField($field->getName())) { throw new coding_exception('Duplicate field '.$field->getName().' specified in table '.$this->getName()); } - /// Calculate the previous and next fields + // Calculate the previous and next fields $prevfield = NULL; $nextfield = NULL; @@ -79,7 +88,7 @@ class xmldb_table extends xmldb_object { $nextfield =& $this->getField($prevfield->getNext()); } - /// Set current field previous and next attributes + // Set current field previous and next attributes if ($prevfield) { $field->setPrevious($prevfield->getName()); $prevfield->setNext($field->getName()); @@ -88,16 +97,16 @@ class xmldb_table extends xmldb_object { $field->setNext($nextfield->getName()); $nextfield->setPrevious($field->getName()); } - /// Some more attributes + // Some more attributes $field->setLoaded(true); $field->setChanged(true); - /// Add the new field + // Add the new field $this->fields[] = $field; - /// Reorder the field + // Reorder the field $this->orderFields($this->fields); - /// Recalculate the hash + // Recalculate the hash $this->calculateHash(true); - /// We have one new field, so the table has changed + // We have one new field, so the table has changed $this->setChanged(true); return $field; @@ -106,15 +115,17 @@ class xmldb_table extends xmldb_object { /** * Add one key to the table, allowing to specify the desired order * If it's not specified, then the key is added at the end + * @param xmldb_key $key + * @param xmldb_object $after */ function addKey(&$key, $after=NULL) { - /// Detect duplicates first + // Detect duplicates first if ($this->getKey($key->getName())) { throw new coding_exception('Duplicate key '.$key->getName().' specified in table '.$this->getName()); } - /// Calculate the previous and next keys + // Calculate the previous and next keys $prevkey = NULL; $nextkey = NULL; @@ -131,7 +142,7 @@ class xmldb_table extends xmldb_object { $nextkey =& $this->getKey($prevkey->getNext()); } - /// Set current key previous and next attributes + // Set current key previous and next attributes if ($prevkey) { $key->setPrevious($prevkey->getName()); $prevkey->setNext($key->getName()); @@ -140,31 +151,33 @@ class xmldb_table extends xmldb_object { $key->setNext($nextkey->getName()); $nextkey->setPrevious($key->getName()); } - /// Some more attributes + // Some more attributes $key->setLoaded(true); $key->setChanged(true); - /// Add the new key + // Add the new key $this->keys[] = $key; - /// Reorder the keys + // Reorder the keys $this->orderKeys($this->keys); - /// Recalculate the hash + // Recalculate the hash $this->calculateHash(true); - /// We have one new field, so the table has changed + // We have one new field, so the table has changed $this->setChanged(true); } /** * Add one index to the table, allowing to specify the desired order * If it's not specified, then the index is added at the end + * @param xmldb_index $index + * @param xmldb_object $after */ function addIndex(&$index, $after=NULL) { - /// Detect duplicates first + // Detect duplicates first if ($this->getIndex($index->getName())) { throw new coding_exception('Duplicate index '.$index->getName().' specified in table '.$this->getName()); } - /// Calculate the previous and next indexes + // Calculate the previous and next indexes $previndex = NULL; $nextindex = NULL; @@ -181,7 +194,7 @@ class xmldb_table extends xmldb_object { $nextindex =& $this->getIndex($previndex->getNext()); } - /// Set current index previous and next attributes + // Set current index previous and next attributes if ($previndex) { $index->setPrevious($previndex->getName()); $previndex->setNext($index->getName()); @@ -191,21 +204,22 @@ class xmldb_table extends xmldb_object { $nextindex->setPrevious($index->getName()); } - /// Some more attributes + // Some more attributes $index->setLoaded(true); $index->setChanged(true); - /// Add the new index + // Add the new index $this->indexes[] = $index; - /// Reorder the indexes + // Reorder the indexes $this->orderIndexes($this->indexes); - /// Recalculate the hash + // Recalculate the hash $this->calculateHash(true); - /// We have one new index, so the table has changed + // We have one new index, so the table has changed $this->setChanged(true); } /** * This function will return the array of fields in the table + * @return array */ function &getFields() { return $this->fields; @@ -213,6 +227,7 @@ class xmldb_table extends xmldb_object { /** * This function will return the array of keys in the table + * @return array */ function &getKeys() { return $this->keys; @@ -220,6 +235,7 @@ class xmldb_table extends xmldb_object { /** * This function will return the array of indexes in the table + * @return array */ function &getIndexes() { return $this->indexes; @@ -227,6 +243,8 @@ class xmldb_table extends xmldb_object { /** * Returns one xmldb_field + * @param string $fieldname + * @return mixed */ function &getField($fieldname) { $i = $this->findFieldInArray($fieldname); @@ -239,6 +257,8 @@ class xmldb_table extends xmldb_object { /** * Returns the position of one field in the array. + * @param string $fieldname + * @return mixed */ function &findFieldInArray($fieldname) { foreach ($this->fields as $i => $field) { @@ -252,6 +272,7 @@ class xmldb_table extends xmldb_object { /** * This function will reorder the array of fields + * @return bool */ function orderFields() { $result = $this->orderElements($this->fields); @@ -265,6 +286,8 @@ class xmldb_table extends xmldb_object { /** * Returns one xmldb_key + * @param string $keyname + * @return mixed */ function &getKey($keyname) { $i = $this->findKeyInArray($keyname); @@ -277,6 +300,8 @@ class xmldb_table extends xmldb_object { /** * Returns the position of one key in the array. + * @param string $keyname + * @return mixed */ function &findKeyInArray($keyname) { foreach ($this->keys as $i => $key) { @@ -290,6 +315,7 @@ class xmldb_table extends xmldb_object { /** * This function will reorder the array of keys + * @return bool */ function orderKeys() { $result = $this->orderElements($this->keys); @@ -303,6 +329,8 @@ class xmldb_table extends xmldb_object { /** * Returns one xmldb_index + * @param string $indexname + * @return mixed */ function &getIndex($indexname) { $i = $this->findIndexInArray($indexname); @@ -315,6 +343,8 @@ class xmldb_table extends xmldb_object { /** * Returns the position of one index in the array. + * @param string $idnexname + * @return mixed */ function &findIndexInArray($indexname) { foreach ($this->indexes as $i => $index) { @@ -328,6 +358,7 @@ class xmldb_table extends xmldb_object { /** * This function will reorder the array of indexes + * @return bool */ function orderIndexes() { $result = $this->orderElements($this->indexes); @@ -341,6 +372,7 @@ class xmldb_table extends xmldb_object { /** * This function will set the array of fields in the table + * @param array $fields */ function setFields($fields) { $this->fields = $fields; @@ -348,6 +380,7 @@ class xmldb_table extends xmldb_object { /** * This function will set the array of keys in the table + * @param array $keys */ function setKeys($keys) { $this->keys = $keys; @@ -355,6 +388,7 @@ class xmldb_table extends xmldb_object { /** * This function will set the array of indexes in the table + * @param array $indexes */ function setIndexes($indexes) { $this->indexes = $indexes; @@ -362,93 +396,98 @@ class xmldb_table extends xmldb_object { /** * Delete one field from the table + * @param string $fieldname */ function deleteField($fieldname) { $field =& $this->getField($fieldname); if ($field) { $i = $this->findFieldInArray($fieldname); - /// Look for prev and next field + // Look for prev and next field $prevfield =& $this->getField($field->getPrevious()); $nextfield =& $this->getField($field->getNext()); - /// Change their previous and next attributes + // Change their previous and next attributes if ($prevfield) { $prevfield->setNext($field->getNext()); } if ($nextfield) { $nextfield->setPrevious($field->getPrevious()); } - /// Delete the field + // Delete the field unset($this->fields[$i]); - /// Reorder the whole structure + // Reorder the whole structure $this->orderFields($this->fields); - /// Recalculate the hash + // Recalculate the hash $this->calculateHash(true); - /// We have one deleted field, so the table has changed + // We have one deleted field, so the table has changed $this->setChanged(true); } } /** * Delete one key from the table + * @param string $keyname */ function deleteKey($keyname) { $key =& $this->getKey($keyname); if ($key) { $i = $this->findKeyInArray($keyname); - /// Look for prev and next key + // Look for prev and next key $prevkey =& $this->getKey($key->getPrevious()); $nextkey =& $this->getKey($key->getNext()); - /// Change their previous and next attributes + // Change their previous and next attributes if ($prevkey) { $prevkey->setNext($key->getNext()); } if ($nextkey) { $nextkey->setPrevious($key->getPrevious()); } - /// Delete the key + // Delete the key unset($this->keys[$i]); - /// Reorder the Keys + // Reorder the Keys $this->orderKeys($this->keys); - /// Recalculate the hash + // Recalculate the hash $this->calculateHash(true); - /// We have one deleted key, so the table has changed + // We have one deleted key, so the table has changed $this->setChanged(true); } } /** * Delete one index from the table + * @param string $idnexname */ function deleteIndex($indexname) { $index =& $this->getIndex($indexname); if ($index) { $i = $this->findIndexInArray($indexname); - /// Look for prev and next index + // Look for prev and next index $previndex =& $this->getIndex($index->getPrevious()); $nextindex =& $this->getIndex($index->getNext()); - /// Change their previous and next attributes + // Change their previous and next attributes if ($previndex) { $previndex->setNext($index->getNext()); } if ($nextindex) { $nextindex->setPrevious($index->getPrevious()); } - /// Delete the index + // Delete the index unset($this->indexes[$i]); - /// Reorder the indexes + // Reorder the indexes $this->orderIndexes($this->indexes); - /// Recalculate the hash + // Recalculate the hash $this->calculateHash(true); - /// We have one deleted index, so the table has changed + // We have one deleted index, so the table has changed $this->setChanged(true); } } /** * Load data from XML to the table + * @param array $xmlarr + * @return bool success */ function arr2xmldb_table($xmlarr) { @@ -456,12 +495,12 @@ class xmldb_table extends xmldb_object { $result = true; - /// Debug the table - /// traverse_xmlize($xmlarr); //Debug - /// print_object ($GLOBALS['traverse_array']); //Debug - /// $GLOBALS['traverse_array']=""; //Debug + // Debug the table + // traverse_xmlize($xmlarr); //Debug + // print_object ($GLOBALS['traverse_array']); //Debug + // $GLOBALS['traverse_array']=""; //Debug - /// Process table attributes (name, comment, previoustable and nexttable) + // Process table attributes (name, comment, previoustable and nexttable) if (isset($xmlarr['@']['NAME'])) { $this->name = trim($xmlarr['@']['NAME']); } else { @@ -485,7 +524,7 @@ class xmldb_table extends xmldb_object { $this->next = trim($xmlarr['@']['NEXT']); } - /// Iterate over fields + // Iterate over fields if (isset($xmlarr['#']['FIELDS']['0']['#']['FIELD'])) { foreach ($xmlarr['#']['FIELDS']['0']['#']['FIELD'] as $xmlfield) { if (!$result) { //Skip on error @@ -507,22 +546,22 @@ class xmldb_table extends xmldb_object { $result = false; } - /// Perform some general checks over fields + // Perform some general checks over fields if ($result && $this->fields) { - /// Check field names are ok (lowercase, a-z _-) + // Check field names are ok (lowercase, a-z _-) if (!$this->checkNameValues($this->fields)) { $this->errormsg = 'Some FIELDS name values are incorrect'; $this->debug($this->errormsg); $result = false; } - /// Check previous & next are ok (duplicates and existing fields) + // Check previous & next are ok (duplicates and existing fields) $this->fixPrevNext($this->fields); if ($result && !$this->checkPreviousNextValues($this->fields)) { $this->errormsg = 'Some FIELDS previous/next values are incorrect'; $this->debug($this->errormsg); $result = false; } - /// Order fields + // Order fields if ($result && !$this->orderFields($this->fields)) { $this->errormsg = 'Error ordering the fields'; $this->debug($this->errormsg); @@ -530,7 +569,7 @@ class xmldb_table extends xmldb_object { } } - /// Iterate over keys + // Iterate over keys if (isset($xmlarr['#']['KEYS']['0']['#']['KEY'])) { foreach ($xmlarr['#']['KEYS']['0']['#']['KEY'] as $xmlkey) { if (!$result) { //Skip on error @@ -552,33 +591,33 @@ class xmldb_table extends xmldb_object { $result = false; } - /// Perform some general checks over keys + // Perform some general checks over keys if ($result && $this->keys) { - /// Check keys names are ok (lowercase, a-z _-) + // Check keys names are ok (lowercase, a-z _-) if (!$this->checkNameValues($this->keys)) { $this->errormsg = 'Some KEYS name values are incorrect'; $this->debug($this->errormsg); $result = false; } - /// Check previous & next are ok (duplicates and existing keys) + // Check previous & next are ok (duplicates and existing keys) $this->fixPrevNext($this->keys); if ($result && !$this->checkPreviousNextValues($this->keys)) { $this->errormsg = 'Some KEYS previous/next values are incorrect'; $this->debug($this->errormsg); $result = false; } - /// Order keys + // Order keys if ($result && !$this->orderKeys($this->keys)) { $this->errormsg = 'Error ordering the keys'; $this->debug($this->errormsg); $result = false; } - /// TODO: Only one PK - /// TODO: Not keys with repeated fields - /// TODO: Check fields and reffieds exist in table + // TODO: Only one PK + // TODO: Not keys with repeated fields + // TODO: Check fields and reffieds exist in table } - /// Iterate over indexes + // Iterate over indexes if (isset($xmlarr['#']['INDEXES']['0']['#']['INDEX'])) { foreach ($xmlarr['#']['INDEXES']['0']['#']['INDEX'] as $xmlindex) { if (!$result) { //Skip on error @@ -596,32 +635,32 @@ class xmldb_table extends xmldb_object { } } - /// Perform some general checks over indexes + // Perform some general checks over indexes if ($result && $this->indexes) { - /// Check field names are ok (lowercase, a-z _-) + // Check field names are ok (lowercase, a-z _-) if (!$this->checkNameValues($this->indexes)) { $this->errormsg = 'Some INDEXES name values are incorrect'; $this->debug($this->errormsg); $result = false; } - /// Check previous & next are ok (duplicates and existing INDEXES) + // Check previous & next are ok (duplicates and existing INDEXES) $this->fixPrevNext($this->indexes); if ($result && !$this->checkPreviousNextValues($this->indexes)) { $this->errormsg = 'Some INDEXES previous/next values are incorrect'; $this->debug($this->errormsg); $result = false; } - /// Order indexes + // Order indexes if ($result && !$this->orderIndexes($this->indexes)) { $this->errormsg = 'Error ordering the indexes'; $this->debug($this->errormsg); $result = false; } - /// TODO: Not indexes with repeated fields - /// TODO: Check fields exist in table + // TODO: Not indexes with repeated fields + // TODO: Check fields exist in table } - /// Set some attributes + // Set some attributes if ($result) { $this->loaded = true; } @@ -631,6 +670,7 @@ class xmldb_table extends xmldb_object { /** * This function calculate and set the hash of one xmldb_table + * @param bool $recursive */ function calculateHash($recursive = false) { if (!$this->loaded) { @@ -689,8 +729,10 @@ class xmldb_table extends xmldb_object { return null; } - /** + + /** * This function will output the XML text for one table + * @return string */ function xmlOutput() { $o = ''; @@ -705,7 +747,7 @@ class xmldb_table extends xmldb_object { $o.= ' NEXT="' . $this->next . '"'; } $o.= '>' . "\n"; - /// Now the fields + // Now the fields if ($this->fields) { $o.= ' ' . "\n"; foreach ($this->fields as $field) { @@ -713,7 +755,7 @@ class xmldb_table extends xmldb_object { } $o.= ' ' . "\n"; } - /// Now the keys + // Now the keys if ($this->keys) { $o.= ' ' . "\n"; foreach ($this->keys as $key) { @@ -721,7 +763,7 @@ class xmldb_table extends xmldb_object { } $o.= ' ' . "\n"; } - /// Now the indexes + // Now the indexes if ($this->indexes) { $o.= ' ' . "\n"; foreach ($this->indexes as $index) { @@ -738,14 +780,14 @@ class xmldb_table extends xmldb_object { * This function will add one new field to the table with all * its attributes defined * - * @param string name name of the field - * @param string type XMLDB_TYPE_INTEGER, XMLDB_TYPE_NUMBER, XMLDB_TYPE_CHAR, XMLDB_TYPE_TEXT, XMLDB_TYPE_BINARY - * @param string precision length for integers and chars, two-comma separated numbers for numbers - * @param string unsigned XMLDB_UNSIGNED or null (or false) - * @param string notnull XMLDB_NOTNULL or null (or false) - * @param string sequence XMLDB_SEQUENCE or null (or false) - * @param string default meaningful default o null (or false) - * @param string previous name of the previous field in the table or null (or false) + * @param string $name name of the field + * @param int $type XMLDB_TYPE_INTEGER, XMLDB_TYPE_NUMBER, XMLDB_TYPE_CHAR, XMLDB_TYPE_TEXT, XMLDB_TYPE_BINARY + * @param string $precision length for integers and chars, two-comma separated numbers for numbers + * @param bool $unsigned XMLDB_UNSIGNED or null (or false) + * @param bool $notnull XMLDB_NOTNULL or null (or false) + * @param bool $sequence XMLDB_SEQUENCE or null (or false) + * @param mixed $default meaningful default o null (or false) + * @param xmldb_object $previous name of the previous field in the table or null (or false) */ function add_field($name, $type, $precision=null, $unsigned=null, $notnull=null, $sequence=null, $default=null, $previous=null) { $field = new xmldb_field($name, $type, $precision, $unsigned, $notnull, $sequence, $default); @@ -758,11 +800,11 @@ class xmldb_table extends xmldb_object { * This function will add one new key to the table with all * its attributes defined * - * @param string name name of the key - * @param string type XMLDB_KEY_PRIMARY, XMLDB_KEY_UNIQUE, XMLDB_KEY_FOREIGN - * @param array fields an array of fieldnames to build the key over - * @param string reftable name of the table the FK points to or null - * @param array reffields an array of fieldnames in the FK table or null + * @param string $name name of the key + * @param int $type XMLDB_KEY_PRIMARY, XMLDB_KEY_UNIQUE, XMLDB_KEY_FOREIGN + * @param array $fields an array of fieldnames to build the key over + * @param string $reftable name of the table the FK points to or null + * @param array $reffields an array of fieldnames in the FK table or null */ function add_key($name, $type, $fields, $reftable=null, $reffields=null) { $key = new xmldb_key($name, $type, $fields, $reftable, $reffields); @@ -773,9 +815,9 @@ class xmldb_table extends xmldb_object { * This function will add one new index to the table with all * its attributes defined * - * @param string name name of the index - * @param string type XMLDB_INDEX_UNIQUE, XMLDB_INDEX_NOTUNIQUE - * @param array fields an array of fieldnames to build the index over + * @param string $name name of the index + * @param int $type XMLDB_INDEX_UNIQUE, XMLDB_INDEX_NOTUNIQUE + * @param array $fields an array of fieldnames to build the index over */ function add_index($name, $type, $fields) { $index = new xmldb_index($name, $type, $fields); @@ -790,11 +832,11 @@ class xmldb_table extends xmldb_object { function getAllErrors() { $errors = array(); - /// First the table itself + // First the table itself if ($this->getError()) { $errors[] = $this->getError(); } - /// Delegate to fields + // Delegate to fields if ($fields = $this->getFields()) { foreach ($fields as $field) { if ($field->getError()) { @@ -802,7 +844,7 @@ class xmldb_table extends xmldb_object { } } } - /// Delegate to keys + // Delegate to keys if ($keys = $this->getKeys()) { foreach ($keys as $key) { if ($key->getError()) { @@ -810,7 +852,7 @@ class xmldb_table extends xmldb_object { } } } - /// Delegate to indexes + // Delegate to indexes if ($indexes = $this->getIndexes()) { foreach ($indexes as $index) { if ($index->getError()) { @@ -818,7 +860,7 @@ class xmldb_table extends xmldb_object { } } } - /// Return decision + // Return decision if (count($errors)) { return $errors; } else { From 01be2287c77e6b5460a2d357c6d3450c0f9b83a1 Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Tue, 5 Jun 2012 13:14:58 +0200 Subject: [PATCH 026/130] MDL-32003 drop unused statement constants These were last used in 2.2 upgrade, not allowed any more. --- lib/xmldb/xmldb_constants.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/lib/xmldb/xmldb_constants.php b/lib/xmldb/xmldb_constants.php index 7166880176e..de3f0c935e5 100644 --- a/lib/xmldb/xmldb_constants.php +++ b/lib/xmldb/xmldb_constants.php @@ -57,13 +57,6 @@ define ('XMLDB_TYPE_DATETIME', 7); /** Timestamp */ define ('XMLDB_TYPE_TIMESTAMP', 8); -// TODO: delete these unused constants - can not be used in 2.3 upgrade -define ('XMLDB_STATEMENT_INCORRECT', 0); //Wrong Statement Type -define ('XMLDB_STATEMENT_INSERT', 1); //Insert Statements -define ('XMLDB_STATEMENT_UPDATE', 2); //Update Statements -define ('XMLDB_STATEMENT_DELETE', 3); //Delete Statements -define ('XMLDB_STATEMENT_CUSTOM', 4); //Custom Statements - // ==== Now the allowed DB Keys ==== /** Wrong DB Key */ define ('XMLDB_KEY_INCORRECT', 0); From ef7c3f108aceb8a7c84a801a0ce25bedeb32f859 Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Tue, 5 Jun 2012 13:16:37 +0200 Subject: [PATCH 027/130] MDL-32003 protect xmldb class internals Use getters and setters instead! --- lib/xmldb/xmldb_field.php | 12 ++++++------ lib/xmldb/xmldb_file.php | 8 ++++---- lib/xmldb/xmldb_index.php | 4 ++-- lib/xmldb/xmldb_key.php | 8 ++++---- lib/xmldb/xmldb_object.php | 16 ++++++++-------- lib/xmldb/xmldb_structure.php | 6 +++--- lib/xmldb/xmldb_table.php | 6 +++--- 7 files changed, 30 insertions(+), 30 deletions(-) diff --git a/lib/xmldb/xmldb_field.php b/lib/xmldb/xmldb_field.php index f84879aa2e1..d209bceed20 100644 --- a/lib/xmldb/xmldb_field.php +++ b/lib/xmldb/xmldb_field.php @@ -29,22 +29,22 @@ defined('MOODLE_INTERNAL') || die(); class xmldb_field extends xmldb_object { /** @var int XMLDB_TYPE_ constants */ - var $type; + protected $type; /** @var int size of field */ - var $length; + protected $length; /** @var bool is null forbidden? XMLDB_NOTNULL */ - var $notnull; + protected $notnull; /** @var mixed default value */ - var $default; + protected $default; /** @var bool use automatic counter */ - var $sequence; + protected $sequence; /** @var int number of decimals */ - var $decimals; + protected $decimals; /** * Note: diff --git a/lib/xmldb/xmldb_file.php b/lib/xmldb/xmldb_file.php index 042869ab702..72a4c78e183 100644 --- a/lib/xmldb/xmldb_file.php +++ b/lib/xmldb/xmldb_file.php @@ -29,16 +29,16 @@ defined('MOODLE_INTERNAL') || die(); class xmldb_file extends xmldb_object { /** @var string path to file */ - var $path; + protected $path; /** @var string path to schema */ - var $schema; + protected $schema; /** @var string document dtd */ - var $dtd; + protected $dtd; /** @var xmldb_structure the structure stored in file */ - var $xmldb_structure; + protected $xmldb_structure; /** * Constructor of the xmldb_file diff --git a/lib/xmldb/xmldb_index.php b/lib/xmldb/xmldb_index.php index 7b1b26da277..67344f9bfb2 100644 --- a/lib/xmldb/xmldb_index.php +++ b/lib/xmldb/xmldb_index.php @@ -29,10 +29,10 @@ defined('MOODLE_INTERNAL') || die(); class xmldb_index extends xmldb_object { /** @var bool is unique? */ - var $unique; + protected $unique; /** @var array index fields */ - var $fields; + protected $fields; /** * Note: diff --git a/lib/xmldb/xmldb_key.php b/lib/xmldb/xmldb_key.php index 03636e65e97..1831418b27a 100644 --- a/lib/xmldb/xmldb_key.php +++ b/lib/xmldb/xmldb_key.php @@ -29,16 +29,16 @@ defined('MOODLE_INTERNAL') || die(); class xmldb_key extends xmldb_object { /** @var int type of key */ - var $type; + protected $type; /** @var array of fields */ - var $fields; + protected $fields; /** @var string referenced table */ - var $reftable; + protected $reftable; /** @var array referenced fields */ - var $reffields; + protected $reffields; /** * Creates one new xmldb_key diff --git a/lib/xmldb/xmldb_object.php b/lib/xmldb/xmldb_object.php index 3683028cf21..5c0925c55b4 100644 --- a/lib/xmldb/xmldb_object.php +++ b/lib/xmldb/xmldb_object.php @@ -29,28 +29,28 @@ defined('MOODLE_INTERNAL') || die(); class xmldb_object { /** @var string name of obejct */ - var $name; + protected $name; /** @var string comment on object */ - var $comment; + protected $comment; /** @var xmldb_object */ - var $previous; + protected $previous; /** @var xmldb_object */ - var $next; + protected $next; /** @var string hash of object */ - var $hash; + protected $hash; /** @var bool is it loaded yet */ - var $loaded; + protected $loaded; /** @var bool was object changed */ - var $changed; + protected $changed; /** @var string error message */ - var $errormsg; + protected $errormsg; /** * Creates one new xmldb_object diff --git a/lib/xmldb/xmldb_structure.php b/lib/xmldb/xmldb_structure.php index 0b34cac140a..75dbada3c20 100644 --- a/lib/xmldb/xmldb_structure.php +++ b/lib/xmldb/xmldb_structure.php @@ -29,13 +29,13 @@ defined('MOODLE_INTERNAL') || die(); class xmldb_structure extends xmldb_object { /** @var string */ - var $path; + protected $path; /** @var string */ - var $version; + protected $version; /** @var array tables */ - var $tables; + protected $tables; /** * Creates one new xmldb_structure diff --git a/lib/xmldb/xmldb_table.php b/lib/xmldb/xmldb_table.php index 14f560f4f5c..7f2280222e6 100644 --- a/lib/xmldb/xmldb_table.php +++ b/lib/xmldb/xmldb_table.php @@ -29,13 +29,13 @@ defined('MOODLE_INTERNAL') || die(); class xmldb_table extends xmldb_object { /** @var array table columns */ - var $fields; + protected $fields; /** @var array keys */ - var $keys; + protected $keys; /** @var array indexes */ - var $indexes; + protected $indexes; /** * Note: From a6d9d4efc26a9cee64ae28413d68cfb4547d22f7 Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Tue, 5 Jun 2012 13:32:00 +0200 Subject: [PATCH 028/130] MDL-32003 fix PHP4-isms in core xmldb code --- lib/ddl/database_manager.php | 2 +- lib/ddl/sql_generator.php | 3 +- lib/ddl/tests/ddl_test.php | 17 +++++++++- lib/dml/tests/dml_test.php | 3 ++ lib/xmldb/xmldb_file.php | 4 +-- lib/xmldb/xmldb_index.php | 4 +-- lib/xmldb/xmldb_key.php | 10 +++--- lib/xmldb/xmldb_object.php | 13 ++++---- lib/xmldb/xmldb_structure.php | 62 ++++++++++++++++------------------- 9 files changed, 65 insertions(+), 53 deletions(-) diff --git a/lib/ddl/database_manager.php b/lib/ddl/database_manager.php index aba9282770c..dffcc2dd20f 100644 --- a/lib/ddl/database_manager.php +++ b/lib/ddl/database_manager.php @@ -333,7 +333,7 @@ class database_manager { $loaded = $xmldb_file->loadXMLStructure(); if (!$loaded || !$xmldb_file->isLoaded()) { // Show info about the error if we can find it - if ($structure =& $xmldb_file->getStructure()) { + if ($structure = $xmldb_file->getStructure()) { if ($errors = $structure->getAllErrors()) { throw new ddl_exception('ddlxmlfileerror', null, 'Errors found in XMLDB file: '. implode (', ', $errors)); } diff --git a/lib/ddl/sql_generator.php b/lib/ddl/sql_generator.php index 805189a3419..9157f1ebfeb 100644 --- a/lib/ddl/sql_generator.php +++ b/lib/ddl/sql_generator.php @@ -322,7 +322,8 @@ abstract class sql_generator { } // make sure sequence field is unique if ($sequencefield and $xmldb_key->getType() == XMLDB_KEY_PRIMARY) { - $field = reset($xmldb_key->getFields()); + $fields = $xmldb_key->getFields(); + $field = reset($fields); if ($sequencefield === $field) { $sequencefield = null; } diff --git a/lib/ddl/tests/ddl_test.php b/lib/ddl/tests/ddl_test.php index 64f7d6ddc02..19f30a65c60 100644 --- a/lib/ddl/tests/ddl_test.php +++ b/lib/ddl/tests/ddl_test.php @@ -1233,6 +1233,7 @@ class ddl_testcase extends database_driver_testcase { $index = new xmldb_index('secondname'); $index->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('course', 'name')); $dbman->add_index($table, $index); + $this->assertTrue($dbman->index_exists($table, $index)); } public function testFindIndexName() { @@ -1291,6 +1292,9 @@ class ddl_testcase extends database_driver_testcase { $key = new xmldb_key('id-course-grade'); $key->set_attributes(XMLDB_KEY_UNIQUE, array('id', 'course', 'grade')); $dbman->add_key($table, $key); + + // No easy way to test it, this just makes sure no errors are encountered. + $this->assertTrue(true); } public function testAddForeignUniqueKey() { @@ -1302,6 +1306,9 @@ class ddl_testcase extends database_driver_testcase { $key = new xmldb_key('course'); $key->set_attributes(XMLDB_KEY_FOREIGN_UNIQUE, array('course'), 'test_table0', array('id')); $dbman->add_key($table, $key); + + // No easy way to test it, this just makes sure no errors are encountered. + $this->assertTrue(true); } public function testDropKey() { @@ -1315,6 +1322,9 @@ class ddl_testcase extends database_driver_testcase { $dbman->add_key($table, $key); $dbman->drop_key($table, $key); + + // No easy way to test it, this just makes sure no errors are encountered. + $this->assertTrue(true); } public function testAddForeignKey() { @@ -1326,6 +1336,9 @@ class ddl_testcase extends database_driver_testcase { $key = new xmldb_key('course'); $key->set_attributes(XMLDB_KEY_FOREIGN, array('course'), 'test_table0', array('id')); $dbman->add_key($table, $key); + + // No easy way to test it, this just makes sure no errors are encountered. + $this->assertTrue(true); } public function testDropForeignKey() { @@ -1339,6 +1352,9 @@ class ddl_testcase extends database_driver_testcase { $dbman->add_key($table, $key); $dbman->drop_key($table, $key); + + // No easy way to test it, this just makes sure no errors are encountered. + $this->assertTrue(true); } public function testRenameField() { @@ -1357,7 +1373,6 @@ class ddl_testcase extends database_driver_testcase { $this->assertTrue(array_key_exists('newfieldname', $columns)); } - public function testIndexExists() { // Skipping: this is just a test of find_index_name } diff --git a/lib/dml/tests/dml_test.php b/lib/dml/tests/dml_test.php index 0b3824c1b25..e431b91e09f 100644 --- a/lib/dml/tests/dml_test.php +++ b/lib/dml/tests/dml_test.php @@ -4443,6 +4443,9 @@ class dml_testcase extends database_driver_testcase { $DB->get_fieldset_sql("SELECT id FROM {{$tablename}} WHERE course = :select", array('select'=>1)); $DB->set_field_select($tablename, 'course', '1', "id = :select", array('select'=>1)); $DB->delete_records_select($tablename, "id = :select", array('select'=>1)); + + // if we get here test passed ok + $this->assertTrue(true); } public function test_limits_and_offsets() { diff --git a/lib/xmldb/xmldb_file.php b/lib/xmldb/xmldb_file.php index 72a4c78e183..7ad7889d654 100644 --- a/lib/xmldb/xmldb_file.php +++ b/lib/xmldb/xmldb_file.php @@ -72,7 +72,7 @@ class xmldb_file extends xmldb_object { return false; } - function &getStructure() { + function getStructure() { return $this->xmldb_structure; } @@ -195,7 +195,7 @@ class xmldb_file extends xmldb_object { */ function saveXMLFile() { - $structure =& $this->getStructure(); + $structure = $this->getStructure(); $result = file_put_contents($this->path, $structure->xmlOutput()); diff --git a/lib/xmldb/xmldb_index.php b/lib/xmldb/xmldb_index.php index 67344f9bfb2..574b1a12af8 100644 --- a/lib/xmldb/xmldb_index.php +++ b/lib/xmldb/xmldb_index.php @@ -101,9 +101,9 @@ class xmldb_index extends xmldb_object { /** * Get the index fields - * @return array reference to fields array + * @return array */ - function &getFields() { + function getFields() { return $this->fields; } diff --git a/lib/xmldb/xmldb_key.php b/lib/xmldb/xmldb_key.php index 1831418b27a..34f09327164 100644 --- a/lib/xmldb/xmldb_key.php +++ b/lib/xmldb/xmldb_key.php @@ -114,17 +114,17 @@ class xmldb_key extends xmldb_object { /** * Get the key fields - * @return array reference to fields array + * @return array */ - function &getFields() { + function getFields() { return $this->fields; } /** * Get the key reftable - * @return string reference + * @return string */ - function &getRefTable() { + function getRefTable() { return $this->reftable; } @@ -132,7 +132,7 @@ class xmldb_key extends xmldb_object { * Get the key reffields * @return array reference to ref fields */ - function &getRefFields() { + function getRefFields() { return $this->reffields; } diff --git a/lib/xmldb/xmldb_object.php b/lib/xmldb/xmldb_object.php index 5c0925c55b4..4c2dbdcd5fd 100644 --- a/lib/xmldb/xmldb_object.php +++ b/lib/xmldb/xmldb_object.php @@ -207,7 +207,7 @@ class xmldb_object { * @param array $arr * @return bool */ - function checkNameValues(&$arr) { + function checkNameValues($arr) { $result = true; // TODO: Perhaps, add support for reserved words @@ -236,7 +236,7 @@ class xmldb_object { /** * Reconstruct previous/next attributes. * @param array $arr - * @return bool + * @return bool true if $arr modified */ function fixPrevNext(&$arr) { global $CFG; @@ -271,9 +271,9 @@ class xmldb_object { * This function will check that all the elements in one array * have a consistent info in their previous/next fields * @param array $arr - * @return bool + * @return bool true means ok, false invalid prev/next present */ - function checkPreviousNextValues(&$arr) { + function checkPreviousNextValues($arr) { global $CFG; if (!empty($CFG->xmldbdisablenextprevchecking)) { return true; @@ -430,14 +430,13 @@ class xmldb_object { * @param array $arr * @return mixed */ - function &findObjectInArray($objectname, $arr) { + function findObjectInArray($objectname, $arr) { foreach ($arr as $i => $object) { if ($objectname == $object->getName()) { return $i; } } - $null = NULL; - return $null; + return null; } /** diff --git a/lib/xmldb/xmldb_structure.php b/lib/xmldb/xmldb_structure.php index 75dbada3c20..c52a9c6d61c 100644 --- a/lib/xmldb/xmldb_structure.php +++ b/lib/xmldb/xmldb_structure.php @@ -69,35 +69,33 @@ class xmldb_structure extends xmldb_object { * @param string $tablename * @return xmldb_table */ - function &getTable($tablename) { + function getTable($tablename) { $i = $this->findTableInArray($tablename); if ($i !== NULL) { return $this->tables[$i]; } - $null = NULL; - return $null; + return null; } /** * Returns the position of one table in the array. * @param string $tablename - * @return xmldb_table + * @return mixed */ - function &findTableInArray($tablename) { + function findTableInArray($tablename) { foreach ($this->tables as $i => $table) { if ($tablename == $table->getName()) { return $i; } } - $null = NULL; - return $null; + return null; } /** * This function will reorder the array of tables * @return bool success */ - function orderTables() { + protected function orderTables() { $result = $this->orderElements($this->tables); if ($result) { $this->setTables($result); @@ -109,9 +107,9 @@ class xmldb_structure extends xmldb_object { /** * Returns the tables of the structure - * @return array reference to table arrays + * @return array */ - function &getTables() { + function getTables() { return $this->tables; } @@ -129,23 +127,22 @@ class xmldb_structure extends xmldb_object { * @param xmldb_table $table * @param mixed $after */ - function addTable(&$table, $after=NULL) { + function addTable($table, $after=NULL) { // Calculate the previous and next tables $prevtable = NULL; $nexttable = NULL; if (!$after) { - $alltables =& $this->getTables(); - if ($alltables) { - end($alltables); - $prevtable =& $alltables[key($alltables)]; + if ($this->tables) { + end($this->tables); + $prevtable = $this->tables[key($alltables)]; } } else { - $prevtable =& $this->getTable($after); + $prevtable = $this->getTable($after); } if ($prevtable && $prevtable->getNext()) { - $nexttable =& $this->getTable($prevtable->getNext()); + $nexttable = $this->getTable($prevtable->getNext()); } // Set current table previous and next attributes @@ -161,7 +158,7 @@ class xmldb_structure extends xmldb_object { $table->setLoaded(true); $table->setChanged(true); // Add the new table - $this->tables[] =& $table; + $this->tables[] = $table; // Reorder the whole structure $this->orderTables($this->tables); // Recalculate the hash @@ -177,12 +174,12 @@ class xmldb_structure extends xmldb_object { */ function deleteTable($tablename) { - $table =& $this->getTable($tablename); + $table = $this->getTable($tablename); if ($table) { $i = $this->findTableInArray($tablename); // Look for prev and next table - $prevtable =& $this->getTable($table->getPrevious()); - $nexttable =& $this->getTable($table->getNext()); + $prevtable = $this->getTable($table->getPrevious()); + $nexttable = $this->getTable($table->getNext()); // Change their previous and next attributes if ($prevtable) { $prevtable->setNext($table->getNext()); @@ -206,7 +203,7 @@ class xmldb_structure extends xmldb_object { * Set the tables * @param array $tables */ - function setTables(&$tables) { + function setTables($tables) { $this->tables = $tables; } @@ -315,7 +312,7 @@ class xmldb_structure extends xmldb_object { $key = $this->name . $this->path . $this->comment; if ($this->tables) { foreach ($this->tables as $tbl) { - $table =& $this->getTable($tbl->getName()); + $table = $this->getTable($tbl->getName()); if ($recursive) { $table->calculateHash($recursive); } @@ -368,9 +365,8 @@ class xmldb_structure extends xmldb_object { // Check if some foreign key in the whole structure is using it // (by comparing the reftable with the tablename) - $alltables = $this->getTables(); - if ($alltables) { - foreach ($alltables as $table) { + if ($this->tables) { + foreach ($this->tables as $table) { $keys = $table->getKeys(); if ($keys) { foreach ($keys as $key) { @@ -425,9 +421,8 @@ class xmldb_structure extends xmldb_object { } // Check if some foreign key in the whole structure is using it // By comparing the reftable and refields with the field) - $alltables = $this->getTables(); - if ($alltables) { - foreach ($alltables as $table) { + if ($this->tables) { + foreach ($this->tables as $table) { $keys = $table->getKeys(); if ($keys) { foreach ($keys as $key) { @@ -468,9 +463,8 @@ class xmldb_structure extends xmldb_object { // (by comparing the reftable and reffields with the fields in the key) $mytable = $this->getTable($tablename); $mykey = $mytable->getKey($keyname); - $alltables = $this->getTables(); - if ($alltables && $mykey) { - foreach ($alltables as $table) { + if ($this->tables && $mykey) { + foreach ($this->tables as $table) { $allkeys = $table->getKeys(); if ($allkeys) { foreach ($allkeys as $key) { @@ -531,8 +525,8 @@ class xmldb_structure extends xmldb_object { $errors[] = $this->getError(); } // Delegate to tables - if ($tables = $this->getTables()) { - foreach ($tables as $table) { + if ($this->tables) { + foreach ($this->tables as $table) { if ($tableerrors = $table->getAllErrors()) { } From 85d6dd382eda37c23e848a1d60509771d814b8dd Mon Sep 17 00:00:00 2001 From: Petr Skoda Date: Wed, 6 Jun 2012 10:10:38 +0200 Subject: [PATCH 029/130] MDL-32003 fix xmldb editor code indentations, phpdocs and PHP4-isms --- .../tool/xmldb/actions/XMLDBAction.class.php | 45 +++--- .../xmldb/actions/XMLDBCheckAction.class.php | 8 +- .../check_bigints/check_bigints.class.php | 6 +- .../check_defaults/check_defaults.class.php | 6 +- .../check_foreign_keys.class.php | 6 +- .../check_indexes/check_indexes.class.php | 6 +- .../check_oracle_semantics.class.php | 4 +- .../create_xml_file/create_xml_file.class.php | 6 +- .../delete_field/delete_field.class.php | 26 ++- .../delete_index/delete_index.class.php | 26 ++- .../actions/delete_key/delete_key.class.php | 26 ++- .../delete_table/delete_table.class.php | 12 +- .../delete_xml_file/delete_xml_file.class.php | 8 +- .../actions/edit_field/edit_field.class.php | 26 ++- .../xmldb/actions/edit_field/edit_field.js | 3 +- .../edit_field_save/edit_field_save.class.php | 18 +-- .../actions/edit_index/edit_index.class.php | 21 ++- .../edit_index_save/edit_index_save.class.php | 18 +-- .../xmldb/actions/edit_key/edit_key.class.php | 22 ++- admin/tool/xmldb/actions/edit_key/edit_key.js | 3 +- .../edit_key_save/edit_key_save.class.php | 20 ++- .../actions/edit_table/edit_table.class.php | 26 ++- .../edit_table_save/edit_table_save.class.php | 20 ++- .../edit_xml_file/edit_xml_file.class.php | 12 +- .../edit_xml_file_save.class.php | 14 +- .../generate_all_documentation.class.php | 6 +- .../generate_documentation.class.php | 6 +- .../get_db_directories.class.php | 6 +- .../load_xml_file/load_xml_file.class.php | 8 +- .../load_xml_files/load_xml_files.class.php | 8 +- .../actions/main_view/main_view.class.php | 14 +- .../move_updown_field.class.php | 32 ++-- .../move_updown_index.class.php | 32 ++-- .../move_updown_key/move_updown_key.class.php | 32 ++-- .../move_updown_table.class.php | 28 ++-- .../actions/new_field/new_field.class.php | 18 +-- .../actions/new_index/new_index.class.php | 18 +-- .../xmldb/actions/new_key/new_key.class.php | 18 +-- .../actions/new_table/new_table.class.php | 16 +- .../new_table_from_mysql.class.php | 14 +- .../revert_changes/revert_changes.class.php | 8 +- .../save_xml_file/save_xml_file.class.php | 12 +- .../xmldb/actions/template/template.class.php | 12 +- .../unload_xml_file/unload_xml_file.class.php | 8 +- .../view_field_xml/view_field_xml.class.php | 16 +- .../view_index_xml/view_index_xml.class.php | 18 +-- .../view_key_xml/view_key_xml.class.php | 18 +-- .../view_reserved_words.class.php | 6 +- .../view_structure_php.class.php | 14 +- .../view_structure_sql.class.php | 12 +- .../view_structure_xml.class.php | 12 +- .../view_table_php/view_table_php.class.php | 14 +- .../actions/view_table_php/view_table_php.js | 3 +- .../view_table_sql/view_table_sql.class.php | 12 +- .../view_table_xml/view_table_xml.class.php | 16 +- .../xmldb/actions/view_xml/view_xml.class.php | 7 +- admin/tool/xmldb/index.php | 151 +++++++++--------- admin/tool/xmldb/lang/en/tool_xmldb.php | 3 +- admin/tool/xmldb/settings.php | 3 +- admin/tool/xmldb/version.php | 3 +- 60 files changed, 446 insertions(+), 546 deletions(-) diff --git a/admin/tool/xmldb/actions/XMLDBAction.class.php b/admin/tool/xmldb/actions/XMLDBAction.class.php index d984894fabf..3c7ca7a52ce 100644 --- a/admin/tool/xmldb/actions/XMLDBAction.class.php +++ b/admin/tool/xmldb/actions/XMLDBAction.class.php @@ -15,8 +15,7 @@ // along with Moodle. If not, see . /** - * @package tool - * @subpackage xmldb + * @package tool_xmldb * @copyright 2003 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -27,35 +26,35 @@ * Main xmldb action class. It implements all the basic * functionalities to be shared by each action. * - * @package tool - * @subpackage xmldb + * @package tool_xmldb * @copyright 2003 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class XMLDBAction { - var $does_generate; //Type of value returned by the invoke method - //ACTION_GENERATE_HTML have contents to show - //set by each specialized invoke + /** @var bool Type of value returned by the invoke method, ACTION_GENERATE_HTML have contents to show, set by each specialized invoke*/ + protected $does_generate; - var $title; //Title of the Action (class name, by default) - //set by parent init automatically + /** @var string Title of the Action (class name, by default), set by parent init automatically*/ + protected $title; - var $str; //Strings used by the action - //set by each specialized init, calling loadStrings + /** @var string Strings used by the action set by each specialized init, calling loadStrings*/ + protected $str; - var $output; //Output of the action - //set by each specialized invoke, get with getOutput + /** @var string Output of the action, set by each specialized invoke, get with getOutput*/ + protected $output; - var $errormsg; //Last Error produced. Check when any invoke returns false - //get with getError + /** @var string Last Error produced. Check when any invoke returns false, get with getError*/ + protected $errormsg; - var $postaction; //Action to execute at the end of the invoke script + /** @var string Action to execute at the end of the invoke script*/ + protected $postaction; - var $sesskey_protected; // Actions must be protected by sesskey mechanism + /** @var bool Actions must be protected by sesskey mechanism*/ + protected $sesskey_protected; /** - * Constructor to keep PHP5 happy + * Constructor */ function __construct() { $this->init(); @@ -76,7 +75,8 @@ class XMLDBAction { } /** - * returns the type of output of the file + * Returns the type of output of the file + * @return bool */ function getDoesGenerate() { return $this->does_generate; @@ -85,6 +85,7 @@ class XMLDBAction { /** * getError method, returns the last error string. * Used if the invoke() methods returns false + * @return string */ function getError() { return $this->errormsg; @@ -93,6 +94,7 @@ class XMLDBAction { /** * getOutput method, returns the output generated by the action. * Used after execution of the invoke() methods if they return true + * @return string */ function getOutput() { return $this->output; @@ -101,6 +103,7 @@ class XMLDBAction { /** * getPostAction method, returns the action to launch after executing * another one + * @return string */ function getPostAction() { return $this->postaction; @@ -109,6 +112,7 @@ class XMLDBAction { /** * getTitle method returns the title of the action (that is part * of the $str array attribute + * @return string */ function getTitle() { return $this->str['title']; @@ -117,6 +121,7 @@ class XMLDBAction { /** * loadStrings method, loads the required strings specified in the * array parameter + * @params array $strings */ function loadStrings($strings) { // Load some commonly used strings @@ -162,6 +167,8 @@ class XMLDBAction { /** * launch method, used to easily call invoke methods between actions + * @param string $action + * @return mixed */ function launch($action) { diff --git a/admin/tool/xmldb/actions/XMLDBCheckAction.class.php b/admin/tool/xmldb/actions/XMLDBCheckAction.class.php index 547f00e9877..1e1e20136a4 100644 --- a/admin/tool/xmldb/actions/XMLDBCheckAction.class.php +++ b/admin/tool/xmldb/actions/XMLDBCheckAction.class.php @@ -15,8 +15,7 @@ // along with Moodle. If not, see . /** - * @package tool - * @subpackage xmldb + * @package tool_xmldb * @copyright 2008 onwards Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -25,8 +24,7 @@ * This is a base class for the various actions that interate over all the * tables and check some aspect of their definition. * - * @package tool - * @subpackage xmldb + * @package tool_xmldb * @copyright 2008 onwards Tim Hunt * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ @@ -117,7 +115,7 @@ abstract class XMLDBCheckAction extends XMLDBAction { // Iterate over $XMLDB->dbdirs, loading their XML data to memory if ($XMLDB->dbdirs) { - $dbdirs =& $XMLDB->dbdirs; + $dbdirs = $XMLDB->dbdirs; $o='