Merge branch 'MDL-29906' of git://github.com/timhunt/moodle
authorSam Hemelryk <sam@moodle.com>
Mon, 24 Oct 2011 23:25:28 +0000 (12:25 +1300)
committerSam Hemelryk <sam@moodle.com>
Mon, 24 Oct 2011 23:25:28 +0000 (12:25 +1300)
40 files changed:
course/externallib.php
enrol/externallib.php
enrol/manual/db/services.php
enrol/manual/externallib.php
enrol/manual/version.php
files/externallib.php
group/externallib.php
lang/en/moodle.php
lang/en/webservice.php
lib/accesslib.php
lib/base32.php [deleted file]
lib/csshover.htc [deleted file]
lib/db/services.php
lib/filestorage/stored_file.php
lib/md5.js [deleted file]
lib/odbc.php [deleted file]
lib/setup.php
lib/setuplib.php
lib/swfobject/swfobject.js [deleted file]
lib/thirdpartylibs.xml
lib/typo3/class.t3lib_cs.php
lib/typo3/class.t3lib_div.php
lib/typo3/readme_moodle.txt
message/externallib.php
mod/feedback/backup/moodle2/restore_feedback_activity_task.class.php
mod/lesson/locallib.php
mod/quiz/review.php
mod/scorm/userreport.php
mod/url/lang/en/url.php
mod/url/view.php
notes/externallib.php
question/type/multichoice/edit_multichoice_form.php
question/type/multichoice/lang/en/qtype_multichoice.php
rss/renderer.php
user/externallib.php
version.php
webservice/amf/testclient/index.php
webservice/externallib.php
webservice/lib.php
webservice/rest/locallib.php

index 7d9e6d6..3724e30 100644 (file)
@@ -28,7 +28,10 @@ defined('MOODLE_INTERNAL') || die;
 
 require_once("$CFG->libdir/externallib.php");
 
-class moodle_course_external extends external_api {
+/**
+ * Course functions
+ */
+class core_course_external extends external_api {
 
     /**
      * Returns description of method parameters
@@ -363,4 +366,68 @@ class moodle_course_external extends external_api {
         );
     }
 
+}
+
+/**
+ * Deprecated course functions
+ * @deprecated since Moodle 2.2 please use core_course_external instead
+ */
+class moodle_course_external extends external_api {
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_course_external::get_courses_parameters instead
+     * @return external_function_parameters
+     */
+    public static function get_courses_parameters() {
+        return core_course_external::get_courses_parameters();
+    }
+
+    /**
+     * Get courses
+     * @param array $options
+     * @deprecated since Moodle 2.2 please use core_course_external::get_courses instead
+     * @return array
+     */
+    public static function get_courses($options) {
+        return core_course_external::get_courses($options);
+    }
+
+    /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_course_external::get_courses_returns instead
+     * @return external_description
+     */
+    public static function get_courses_returns() {
+        return core_course_external::get_courses_returns();
+    }
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_course_external::create_courses_parameters instead
+     * @return external_function_parameters
+     */
+    public static function create_courses_parameters() {
+        return core_course_external::create_courses_parameters();
+    }
+
+    /**
+     * Create  courses
+     * @deprecated since Moodle 2.2 please use core_course_external::create_courses instead
+     * @param array $courses
+     * @return array courses (id and shortname only)
+     */
+    public static function create_courses($courses) {
+        return core_course_external::create_courses($courses);
+    }
+
+    /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_course_external::create_courses_returns instead
+     * @return external_description
+     */
+    public static function create_courses_returns() {
+        return core_course_external::create_courses_returns();
+    }
+
 }
\ No newline at end of file
index b11271c..6100fdd 100644 (file)
@@ -31,12 +31,416 @@ defined('MOODLE_INTERNAL') || die();
 
 require_once("$CFG->libdir/externallib.php");
 
+/**
+ * Enrol functions
+ */
+class core_enrol_external extends external_api {
+
+    /**
+     * Returns description of method parameters
+     * @return external_function_parameters
+     */
+    public static function get_users_courses_parameters() {
+        return new external_function_parameters(
+            array(
+                'userid' => new external_value(PARAM_INT, 'user id'),
+            )
+        );
+    }
+
+    /**
+     * Get list of courses user is enrolled in (only active enrolments are returned).
+     *
+     * Please note the current user must be able to access the course, otherwise the course is not included.
+     *
+     * @param int $userid
+     * @return array of courses
+     */
+    public static function get_users_courses($userid) {
+        global $USER;
+
+        // Do basic automatic PARAM checks on incoming data, using params description
+        // If any problems are found then exceptions are thrown with helpful error messages
+        $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid'=>$userid));
+
+        $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible');
+        $result = array();
+
+        foreach ($courses as $course) {
+            $context = get_context_instance(CONTEXT_COURSE, $course->id);
+            try {
+                self::validate_context($context);
+            } catch (Exception $e) {
+                // current user can not access this course, sorry we can not disclose who is enrolled in this course!
+                continue;
+            }
+            if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) {
+                // we need capability to view participants
+                continue;
+            }
+
+            $result[] = array('id'=>$course->id, 'shortname'=>$course->shortname, 'fullname'=>$course->fullname, 'idnumber'=>$course->idnumber,'visible'=>$course->visible);
+        }
 
+        return $result;
+    }
+
+    /**
+     * Returns description of method result value
+     * @return external_description
+     */
+    public static function get_users_courses_returns() {
+        return new external_multiple_structure(
+            new external_single_structure(
+                array(
+                    'id'        => new external_value(PARAM_INT, 'id of course'),
+                    'shortname' => new external_value(PARAM_RAW, 'short name of course'),
+                    'fullname'  => new external_value(PARAM_RAW, 'long name of course'),
+                    'idnumber'  => new external_value(PARAM_RAW, 'id number of course'),
+                    'visible'   => new external_value(PARAM_INT, '1 means visible, 0 means hidden course'),
+                )
+            )
+        );
+    }
+    
+    
+    /**
+     * Returns description of method parameters
+     * @return external_function_parameters
+     */
+    public static function get_enrolled_users_parameters() {
+        return new external_function_parameters(
+            array(
+                'courseid' => new external_value(PARAM_INT, 'course id'),
+                'options'  => new external_multiple_structure(
+                    new external_single_structure(
+                        array(
+                            'name'  => new external_value(PARAM_ALPHANUMEXT, 'option name'),
+                            'value' => new external_value(PARAM_RAW, 'option value')
+                        )
+                    ), 'method options'),
+            )
+        );
+    }
+
+    /**
+     * Get course participants details
+     * @param int $courseid  course id
+     * @param array $options options {
+     *          'name' => option name
+     *          'value' => option value
+     * }
+     * @return array An array of users
+     */
+    public static function get_enrolled_users($courseid, $options) {
+        global $CFG, $USER, $DB;
+        require_once($CFG->dirroot . "/user/lib.php");
+
+        $params = self::validate_parameters(
+            self::get_users_by_course_id_parameters(),
+            array(
+                'courseid'=>$courseid,
+                'options'=>$options
+            )
+        );
+        $withcapability = '';
+        $groupid        = 0;
+        $onlyactive     = false;
+        foreach ($options as $option) {
+            switch ($option['name']) {
+            case 'withcapability':
+                $withcapability = $option['value'];
+                break;
+            case 'groupid':
+                $groupid = (int)$option['value'];
+                break;
+            case 'onlyactive':
+                $onlyactive = !empty($option['value']);
+                break;
+            }
+        }
+
+        // to overwrite this parameter, you need role:review capability
+        if ($withcapability) {
+            require_capability('moodle/role:review', $coursecontext);
+        }
+        // need accessallgroups capability if you want to overwrite this option
+        if (!empty($groupid) && groups_is_member($groupid)) {
+            require_capability('moodle/site:accessallgroups', $context);
+        }
+        // to overwrite this option, you need course:enrolereview permission
+        if ($onlyactive) {
+            require_capability('moodle/course:enrolreview', $coursecontext);
+        }
+
+        list($coursectxselect, $coursectxjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
+        $coursesql = "SELECT c.* $coursectxselect
+                        FROM {course} c $coursectxjoin
+                       WHERE c.id = $courseid";
+        $course = $DB->get_record_sql($coursesql);
+        context_instance_preload($course);
+        $coursecontext = get_context_instance(CONTEXT_COURSE, $params['courseid']);
+        if ($courseid == SITEID) {
+            $context = get_system_context();
+        } else {
+            $context = $coursecontext;
+        }
+        try {
+            self::validate_context($context);
+        } catch (Exception $e) {
+            $exceptionparam = new stdClass();
+            $exceptionparam->message = $e->getMessage();
+            $exceptionparam->courseid = $params['courseid'];
+            throw new moodle_exception(get_string('errorcoursecontextnotvalid' , 'webservice', $exceptionparam));
+        }
+
+        list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
+        list($ctxselect, $ctxjoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
+        $records = $DB->get_records_sql($enrolledsql, $enrolledparams);
+        $sqlparams['courseid'] = $courseid;
+        $sql = "SELECT u.* $ctxselect
+                  FROM {user} u $ctxjoin
+                 WHERE u.id IN ($enrolledsql)
+                 ORDER BY u.id ASC";
+        $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams);
+        $users = array();
+        foreach ($enrolledusers as $user) {
+            if (!empty($user->deleted)) {
+                continue;
+            }
+            context_instance_preload($user);
+            if ($userdetails = user_get_user_details($user, $course)) {
+                $users[] = $userdetails;
+            }
+        }
+        $enrolledusers->close();
+
+        return $users;
+    }
+    
+    /**
+     * Returns description of method result value
+     * @return external_description
+     */
+    public static function get_enrolled_users_returns() {
+        return new external_multiple_structure(
+            new external_single_structure(
+                array(
+                    'id'    => new external_value(PARAM_NUMBER, 'ID of the user'),
+                    'username'    => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
+                    'firstname'   => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
+                    'lastname'    => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
+                    'fullname'    => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
+                    'email'       => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
+                    'address'     => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
+                    'phone1'      => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
+                    'phone2'      => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
+                    'icq'         => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
+                    'skype'       => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
+                    'yahoo'       => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
+                    'aim'         => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
+                    'msn'         => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
+                    'department'  => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
+                    'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
+                    'interests'   => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
+                    'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
+                    'lastaccess'  => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
+                    'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
+                    'descriptionformat' => new external_value(PARAM_INT, 'User profile description format', VALUE_OPTIONAL),
+                    'city'        => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
+                    'url'         => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
+                    'country'     => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
+                    'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
+                    'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
+                    'customfields' => new external_multiple_structure(
+                        new external_single_structure(
+                            array(
+                                'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
+                                'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
+                                'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
+                                'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
+                            )
+                        ), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
+                    'groups' => new external_multiple_structure(
+                        new external_single_structure(
+                            array(
+                                'id'  => new external_value(PARAM_INT, 'group id'),
+                                'name' => new external_value(PARAM_RAW, 'group name'),
+                                'description' => new external_value(PARAM_RAW, 'group description'),
+                            )
+                        ), 'user groups', VALUE_OPTIONAL),
+                    'roles' => new external_multiple_structure(
+                        new external_single_structure(
+                            array(
+                                'roleid'       => new external_value(PARAM_INT, 'role id'),
+                                'name'         => new external_value(PARAM_RAW, 'role name'),
+                                'shortname'    => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
+                                'sortorder'    => new external_value(PARAM_INT, 'role sortorder')
+                            )
+                        ), 'user roles', VALUE_OPTIONAL),
+                    'preferences' => new external_multiple_structure(
+                        new external_single_structure(
+                            array(
+                                'name'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
+                                'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
+                            )
+                    ), 'User preferences', VALUE_OPTIONAL),
+                    'enrolledcourses' => new external_multiple_structure(
+                        new external_single_structure(
+                            array(
+                                'id'  => new external_value(PARAM_INT, 'Id of the course'),
+                                'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
+                                'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
+                            )
+                    ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
+                )
+            )
+        );
+    }
+
+}
+
+/**
+ * Role functions
+ */
+class core_role_external extends external_api {
+
+    /**
+     * Returns description of method parameters
+     * @return external_function_parameters
+     */
+    public static function assign_roles_parameters() {
+        return new external_function_parameters(
+            array(
+                'assignments' => new external_multiple_structure(
+                    new external_single_structure(
+                        array(
+                            'roleid'    => new external_value(PARAM_INT, 'Role to assign to the user'),
+                            'userid'    => new external_value(PARAM_INT, 'The user that is going to be assigned'),
+                            'contextid' => new external_value(PARAM_INT, 'The context to assign the user role in'),
+                        )
+                    )
+                )
+            )
+        );
+    }
+
+    /**
+     * Manual role assignments to users
+     *
+     * @param array $assignment  An array of manual role assignment
+     * @return null
+     */
+    public static function assign_roles($assignments) {
+        global $DB;
+
+        // Do basic automatic PARAM checks on incoming data, using params description
+        // If any problems are found then exceptions are thrown with helpful error messages
+        $params = self::validate_parameters(self::assign_roles_parameters(), array('assignments'=>$assignments));
+
+        $transaction = $DB->start_delegated_transaction();
+
+        foreach ($params['assignments'] as $assignment) {
+            // Ensure the current user is allowed to run this function in the enrolment context
+            $context = get_context_instance_by_id($assignment['contextid']);
+            self::validate_context($context);
+            require_capability('moodle/role:assign', $context);
+
+            // throw an exception if user is not able to assign the role in this context
+            $roles = get_assignable_roles($context, ROLENAME_SHORT);
+
+            if (!key_exists($assignment['roleid'], $roles)) {
+                throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
+            }
+
+            role_assign($assignment['roleid'], $assignment['userid'], $assignment['contextid']);
+        }
+
+        $transaction->allow_commit();
+    }
+
+    /**
+     * Returns description of method result value
+     * @return external_description
+     */
+    public static function assign_roles_returns() {
+        return null;
+    }
+
+
+    /**
+     * Returns description of method parameters
+     * @return external_function_parameters
+     */
+    public static function unassign_roles_parameters() {
+        return new external_function_parameters(
+            array(
+                'unassignments' => new external_multiple_structure(
+                    new external_single_structure(
+                        array(
+                            'roleid'    => new external_value(PARAM_INT, 'Role to assign to the user'),
+                            'userid'    => new external_value(PARAM_INT, 'The user that is going to be assigned'),
+                            'contextid' => new external_value(PARAM_INT, 'The context to unassign the user role from'),
+                        )
+                    )
+                )
+            )
+        );
+    }
+
+     /**
+     * Unassign roles from users
+     *
+     * @param array $unassignment  An array of unassignment
+     * @return null
+     */
+    public static function unassign_roles($unassignments) {
+         global $DB;
+
+        // Do basic automatic PARAM checks on incoming data, using params description
+        // If any problems are found then exceptions are thrown with helpful error messages
+        $params = self::validate_parameters(self::unassign_roles_parameters(), array('unassignments'=>$unassignments));
+
+        $transaction = $DB->start_delegated_transaction();
+
+        foreach ($params['unassignments'] as $unassignment) {
+            // Ensure the current user is allowed to run this function in the unassignment context
+            $context = get_context_instance_by_id($unassignment['contextid']);
+            self::validate_context($context);
+            require_capability('moodle/role:assign', $context);
+
+            // throw an exception if user is not able to unassign the role in this context
+            $roles = get_assignable_roles($context, ROLENAME_SHORT);
+            if (!key_exists($unassignment['roleid'], $roles)) {
+                throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
+            }
+
+            role_unassign($unassignment['roleid'], $unassignment['userid'], $unassignment['contextid']);
+        }
+
+        $transaction->allow_commit();
+    }
+
+   /**
+     * Returns description of method result value
+     * @return null
+     */
+    public static function unassign_roles_returns() {
+        return null;
+    }
+}
+
+
+/**
+ * Deprecated enroll and role functions
+ * @deprecated since Moodle 2.2 please use core_enrol_external or core_role_external instead
+ */
 class moodle_enrol_external extends external_api {
 
 
     /**
      * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_enrol_external::get_enrolled_users_parameters() instead
      * @return external_function_parameters
      */
     public static function get_enrolled_users_parameters() {
@@ -52,7 +456,7 @@ class moodle_enrol_external extends external_api {
 
     /**
      * Get list of course participants.
-     *
+     * @deprecated since Moodle 2.2 please use core_enrol_external::get_enrolled_users() instead
      * @param int $courseid
      * @param text $withcapability
      * @param int $groupid
@@ -143,6 +547,7 @@ class moodle_enrol_external extends external_api {
 
     /**
      * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_enrol_external::get_enrolled_users_returns() instead
      * @return external_description
      */
     public static function get_enrolled_users_returns() {
@@ -164,192 +569,89 @@ class moodle_enrol_external extends external_api {
 
     /**
      * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_enrol_external::get_users_courses_parameters() instead
      * @return external_function_parameters
      */
     public static function get_users_courses_parameters() {
-        return new external_function_parameters(
-            array(
-                'userid' => new external_value(PARAM_INT, 'user id'),
-            )
-        );
+        return core_enrol_external::get_users_courses_parameters();
     }
 
     /**
      * Get list of courses user is enrolled in (only active enrolments are returned).
      *
      * Please note the current user must be able to access the course, otherwise the course is not included.
-     *
+     * @deprecated since Moodle 2.2 please use core_enrol_external::get_users_courses() instead
      * @param int $userid
      * @return array of courses
      */
     public static function get_users_courses($userid) {
-        global $USER;
-
-        // Do basic automatic PARAM checks on incoming data, using params description
-        // If any problems are found then exceptions are thrown with helpful error messages
-        $params = self::validate_parameters(self::get_users_courses_parameters(), array('userid'=>$userid));
-
-        $courses = enrol_get_users_courses($params['userid'], true, 'id, shortname, fullname, idnumber, visible');
-        $result = array();
-
-        foreach ($courses as $course) {
-            $context = get_context_instance(CONTEXT_COURSE, $course->id);
-            try {
-                self::validate_context($context);
-            } catch (Exception $e) {
-                // current user can not access this course, sorry we can not disclose who is enrolled in this course!
-                continue;
-            }
-            if ($userid != $USER->id and !has_capability('moodle/course:viewparticipants', $context)) {
-                // we need capability to view participants
-                continue;
-            }
-
-            $result[] = array('id'=>$course->id, 'shortname'=>$course->shortname, 'fullname'=>$course->fullname, 'idnumber'=>$course->idnumber,'visible'=>$course->visible);
-        }
-
-        return $result;
+        return core_enrol_external::get_users_courses($userid);
     }
 
     /**
      * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_enrol_external::get_users_courses_returns() instead
      * @return external_description
      */
     public static function get_users_courses_returns() {
-        return new external_multiple_structure(
-            new external_single_structure(
-                array(
-                    'id'        => new external_value(PARAM_INT, 'id of course'),
-                    'shortname' => new external_value(PARAM_RAW, 'short name of course'),
-                    'fullname'  => new external_value(PARAM_RAW, 'long name of course'),
-                    'idnumber'  => new external_value(PARAM_RAW, 'id number of course'),
-                    'visible'   => new external_value(PARAM_INT, '1 means visible, 0 means hidden course'),
-                )
-            )
-        );
+        return core_enrol_external::get_users_courses_returns();
     }
 
 
     /**
      * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_role_external::assign_roles_parameters() instead
      * @return external_function_parameters
      */
     public static function role_assign_parameters() {
-        return new external_function_parameters(
-            array(
-                'assignments' => new external_multiple_structure(
-                    new external_single_structure(
-                        array(
-                            'roleid'    => new external_value(PARAM_INT, 'Role to assign to the user'),
-                            'userid'    => new external_value(PARAM_INT, 'The user that is going to be assigned'),
-                            'contextid' => new external_value(PARAM_INT, 'The context to assign the user role in'),
-                        )
-                    )
-                )
-            )
-        );
+        return core_role_external::assign_roles_parameters();
     }
 
     /**
      * Manual role assignments to users
-     *
+     * @deprecated since Moodle 2.2 please use core_role_external::assign_roles() instead
      * @param array $assignment  An array of manual role assignment
      * @return null
      */
     public static function role_assign($assignments) {
-        global $DB;
-
-        // Do basic automatic PARAM checks on incoming data, using params description
-        // If any problems are found then exceptions are thrown with helpful error messages
-        $params = self::validate_parameters(self::role_assign_parameters(), array('assignments'=>$assignments));
-
-        $transaction = $DB->start_delegated_transaction();
-
-        foreach ($params['assignments'] as $assignment) {
-            // Ensure the current user is allowed to run this function in the enrolment context
-            $context = get_context_instance_by_id($assignment['contextid']);
-            self::validate_context($context);
-            require_capability('moodle/role:assign', $context);
-
-            // throw an exception if user is not able to assign the role in this context
-            $roles = get_assignable_roles($context, ROLENAME_SHORT);
-            if (!key_exists($assignment['roleid'], $roles)) {
-                throw new invalid_parameter_exception('Can not assign roleid='.$assignment['roleid'].' in contextid='.$assignment['contextid']);
-            }
-
-            role_assign($assignment['roleid'], $assignment['userid'], $assignment['contextid']);
-        }
-
-        $transaction->allow_commit();
+        return core_role_external::assign_roles($assignments);
     }
 
     /**
      * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_role_external::assign_roles_returns() instead
      * @return external_description
      */
     public static function role_assign_returns() {
-        return null;
+        return core_role_external::assign_roles_returns();
     }
 
 
     /**
      * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_role_external::unassign_roles_parameters() instead
      * @return external_function_parameters
      */
     public static function role_unassign_parameters() {
-        return new external_function_parameters(
-            array(
-                'unassignments' => new external_multiple_structure(
-                    new external_single_structure(
-                        array(
-                            'roleid'    => new external_value(PARAM_INT, 'Role to assign to the user'),
-                            'userid'    => new external_value(PARAM_INT, 'The user that is going to be assigned'),
-                            'contextid' => new external_value(PARAM_INT, 'The context to unassign the user role from'),
-                        )
-                    )
-                )
-            )
-        );
+        return core_role_external::unassign_roles_parameters();
     }
 
      /**
      * Unassign roles from users
-     *
+     * @deprecated since Moodle 2.2 please use core_role_external::unassign_roles() instead
      * @param array $unassignment  An array of unassignment
      * @return null
      */
     public static function role_unassign($unassignments) {
-         global $DB;
-
-        // Do basic automatic PARAM checks on incoming data, using params description
-        // If any problems are found then exceptions are thrown with helpful error messages
-        $params = self::validate_parameters(self::role_unassign_parameters(), array('unassignments'=>$unassignments));
-
-        $transaction = $DB->start_delegated_transaction();
-
-        foreach ($params['unassignments'] as $unassignment) {
-            // Ensure the current user is allowed to run this function in the unassignment context
-            $context = get_context_instance_by_id($unassignment['contextid']);
-            self::validate_context($context);
-            require_capability('moodle/role:assign', $context);
-
-            // throw an exception if user is not able to unassign the role in this context
-            $roles = get_assignable_roles($context, ROLENAME_SHORT);
-            if (!key_exists($unassignment['roleid'], $roles)) {
-                throw new invalid_parameter_exception('Can not unassign roleid='.$unassignment['roleid'].' in contextid='.$unassignment['contextid']);
-            }
-
-            role_unassign($unassignment['roleid'], $unassignment['userid'], $unassignment['contextid']);
-        }
-
-        $transaction->allow_commit();
+         return core_role_external::unassign_roles($unassignments);
     }
 
    /**
      * Returns description of method result value
+    * @deprecated since Moodle 2.2 please use core_role_external::unassign_roles_returns() instead
      * @return external_description
      */
     public static function role_unassign_returns() {
-        return null;
+        return core_role_external::unassign_roles_returns();
     }
 }
index cd49d1b..4b41d24 100644 (file)
@@ -28,8 +28,17 @@ $functions = array(
 
     // === enrol related functions ===
     'moodle_enrol_manual_enrol_users' => array(
-        'classname'   => 'moodle_enrol_manual_external',
-        'methodname'  => 'manual_enrol_users',
+        'classname'   => 'enrol_manual_external',
+        'methodname'  => 'enrol_users',
+        'classpath'   => 'enrol/manual/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as enrol_manual_enrol_users()',
+        'capabilities'=> 'enrol/manual:enrol',
+        'type'        => 'write',
+    ),
+
+    'enrol_manual_enrol_users' => array(
+        'classname'   => 'enrol_manual_external',
+        'methodname'  => 'enrol_users',
         'classpath'   => 'enrol/manual/externallib.php',
         'description' => 'Manual enrol users',
         'capabilities'=> 'enrol/manual:enrol',
index 2edc992..f2daf62 100644 (file)
@@ -29,13 +29,16 @@ defined('MOODLE_INTERNAL') || die();
 
 require_once("$CFG->libdir/externallib.php");
 
-class moodle_enrol_manual_external extends external_api {
+/**
+ * Manual enrolment functions
+ */
+class enrol_manual_external extends external_api {
 
     /**
      * Returns description of method parameters
      * @return external_function_parameters
      */
-    public static function manual_enrol_users_parameters() {
+    public static function enrol_users_parameters() {
         return new external_function_parameters(
                 array(
                     'enrolments' => new external_multiple_structure(
@@ -60,12 +63,12 @@ class moodle_enrol_manual_external extends external_api {
      * @param array $enrolments  An array of user enrolment
      * @return null
      */
-    public static function manual_enrol_users($enrolments) {
+    public static function enrol_users($enrolments) {
         global $DB, $CFG;
 
         require_once($CFG->libdir . '/enrollib.php');
 
-        $params = self::validate_parameters(self::manual_enrol_users_parameters(),
+        $params = self::validate_parameters(self::enrol_users_parameters(),
                 array('enrolments' => $enrolments));
 
         $transaction = $DB->start_delegated_transaction(); //rollback all enrolment if an error occurs
@@ -134,10 +137,47 @@ class moodle_enrol_manual_external extends external_api {
 
     /**
      * Returns description of method result value
+     * @return null
+     */
+    public static function enrol_users_returns() {
+        return null;
+    }
+
+}
+
+/**
+ * Deprecated manual enrolment functions
+ * @deprecated since Moodle 2.2 please use enrol_manual_external instead
+ */
+class moodle_enrol_manual_external extends external_api {
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use enrol_manual_external::enrol_users_parameters instead
+     * @return external_function_parameters
+     */
+    public static function manual_enrol_users_parameters() {
+        return enrol_manual_external::enrol_users_parameters();
+    }
+
+    /**
+     * Enrolment of users
+     * Function throw an exception at the first error encountered.
+     * @deprecated since Moodle 2.2 please use enrol_manual_external::enrol_users instead
+     * @param array $enrolments  An array of user enrolment
+     * @return null
+     */
+    public static function manual_enrol_users($enrolments) {
+        return enrol_manual_external::enrol_users($enrolments);
+    }
+
+    /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use enrol_manual_external::enrol_users_returns instead
      * @return external_description
      */
     public static function manual_enrol_users_returns() {
-        return null;
+        return enrol_manual_external::enrol_users_returns();
     }
 
 }
index 5f2e9e6..e011c76 100644 (file)
@@ -26,4 +26,4 @@
 
 defined('MOODLE_INTERNAL') || die();
 
-$plugin->version = 2010071201;
+$plugin->version = 2010071201.02;
index d71cb72..530f18d 100644 (file)
 require_once("$CFG->libdir/externallib.php");
 require_once("$CFG->libdir/filelib.php");
 
-class moodle_file_external extends external_api {
+/**
+ * Files functions
+ */
+class core_files_external extends external_api {
 
     /**
      * Returns description of get_files parameters
@@ -296,3 +299,77 @@ class moodle_file_external extends external_api {
         );
     }
 }
+
+/**
+ * Deprecated files functions
+ * @deprecated since Moodle 2.2 please use core_files_external instead
+ */
+class moodle_file_external extends external_api {
+
+    /**
+     * Returns description of get_files parameters
+     * @deprecated since Moodle 2.2 please use core_files_external::get_files_parameters instead
+     * @return external_function_parameters
+     */
+    public static function get_files_parameters() {
+        return core_files_external::get_files_parameters();
+    }
+
+    /**
+     * Return moodle files listing
+     * @deprecated since Moodle 2.2 please use core_files_external::get_files instead
+     * @param int $contextid
+     * @param int $component
+     * @param int $filearea
+     * @param int $itemid
+     * @param string $filepath
+     * @param string $filename
+     * @return array
+     */
+    public static function get_files($contextid, $component, $filearea, $itemid, $filepath, $filename) {
+        return core_files_external::get_files($contextid, $component, $filearea, $itemid, $filepath, $filename);
+    }
+
+    /**
+     * Returns description of get_files returns
+     * @deprecated since Moodle 2.2 please use core_files_external::get_files_returns instead
+     * @return external_multiple_structure
+     */
+    public static function get_files_returns() {
+        return core_files_external::get_files_returns();
+    }
+
+    /**
+     * Returns description of upload parameters
+     * @deprecated since Moodle 2.2 please use core_files_external::upload_parameters instead
+     * @return external_function_parameters
+     */
+    public static function upload_parameters() {
+        return core_files_external::upload_parameters();
+    }
+
+    /**
+     * Uploading a file to moodle
+     * @deprecated since Moodle 2.2 please use core_files_external::upload instead
+     * @param int $contextid
+     * @param string $component
+     * @param string $filearea
+     * @param int $itemid
+     * @param string $filepath
+     * @param string $filename
+     * @param string $filecontent
+     * @return array
+     */
+    public static function upload($contextid, $component, $filearea, $itemid, $filepath, $filename, $filecontent) {
+        return core_files_external::upload($contextid, $component, $filearea, $itemid, $filepath, $filename, $filecontent);
+    }
+
+    /**
+     * Returns description of upload returns
+     * @deprecated since Moodle 2.2 please use core_files_external::upload_returns instead
+     * @return external_multiple_structure
+     */
+    public static function upload_returns() {
+        return core_files_external::upload_returns();
+    }
+}
index a37cf64..160dcbf 100644 (file)
 
 require_once("$CFG->libdir/externallib.php");
 
-class moodle_group_external extends external_api {
+/**
+ * Group functions
+ */
+class core_group_external extends external_api {
 
     /**
      * Returns description of method parameters
@@ -305,7 +308,7 @@ class moodle_group_external extends external_api {
      * Returns description of method parameters
      * @return external_function_parameters
      */
-    public static function get_groupmembers_parameters() {
+    public static function get_group_members_parameters() {
         return new external_function_parameters(
             array(
                 'groupids' => new external_multiple_structure(new external_value(PARAM_INT, 'Group ID')),
@@ -318,10 +321,10 @@ class moodle_group_external extends external_api {
      * @param array $groupids array of group ids
      * @return array with  group id keys containing arrays of user ids
      */
-    public static function get_groupmembers($groupids) {
+    public static function get_group_members($groupids) {
         $members = array();
 
-        $params = self::validate_parameters(self::get_groupmembers_parameters(), array('groupids'=>$groupids));
+        $params = self::validate_parameters(self::get_group_members_parameters(), array('groupids'=>$groupids));
 
         foreach ($params['groupids'] as $groupid) {
             // validate params
@@ -351,7 +354,7 @@ class moodle_group_external extends external_api {
      * Returns description of method result value
      * @return external_description
      */
-    public static function get_groupmembers_returns() {
+    public static function get_group_members_returns() {
         return new external_multiple_structure(
             new external_single_structure(
                 array(
@@ -367,7 +370,7 @@ class moodle_group_external extends external_api {
      * Returns description of method parameters
      * @return external_function_parameters
      */
-    public static function add_groupmembers_parameters() {
+    public static function add_group_members_parameters() {
         return new external_function_parameters(
             array(
                 'members'=> new external_multiple_structure(
@@ -387,11 +390,11 @@ class moodle_group_external extends external_api {
      * @param array $members of arrays with keys userid, groupid
      * @return void
      */
-    public static function add_groupmembers($members) {
+    public static function add_group_members($members) {
         global $CFG, $DB;
         require_once("$CFG->dirroot/group/lib.php");
 
-        $params = self::validate_parameters(self::add_groupmembers_parameters(), array('members'=>$members));
+        $params = self::validate_parameters(self::add_group_members_parameters(), array('members'=>$members));
 
         $transaction = $DB->start_delegated_transaction();
         foreach ($params['members'] as $member) {
@@ -429,9 +432,9 @@ class moodle_group_external extends external_api {
 
    /**
      * Returns description of method result value
-     * @return external_description
+     * @return null
      */
-    public static function add_groupmembers_returns() {
+    public static function add_group_members_returns() {
         return null;
     }
 
@@ -440,7 +443,7 @@ class moodle_group_external extends external_api {
      * Returns description of method parameters
      * @return external_function_parameters
      */
-    public static function delete_groupmembers_parameters() {
+    public static function delete_group_members_parameters() {
         return new external_function_parameters(
             array(
                 'members'=> new external_multiple_structure(
@@ -460,11 +463,11 @@ class moodle_group_external extends external_api {
      * @param array $members of arrays with keys userid, groupid
      * @return void
      */
-    public static function delete_groupmembers($members) {
+    public static function delete_group_members($members) {
         global $CFG, $DB;
         require_once("$CFG->dirroot/group/lib.php");
 
-        $params = self::validate_parameters(self::delete_groupmembers_parameters(), array('members'=>$members));
+        $params = self::validate_parameters(self::delete_group_members_parameters(), array('members'=>$members));
 
         $transaction = $DB->start_delegated_transaction();
 
@@ -497,10 +500,217 @@ class moodle_group_external extends external_api {
 
    /**
      * Returns description of method result value
-     * @return external_description
+     * @return null
      */
-    public static function delete_groupmembers_returns() {
+    public static function delete_group_members_returns() {
         return null;
     }
 
 }
+
+/**
+ * Deprecated group functions
+ * @deprecated since Moodle 2.2 please use core_group_external instead
+ */
+class moodle_group_external extends external_api {
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_group_external::create_groups_parameters instead
+     * @return external_function_parameters
+     */
+    public static function create_groups_parameters() {
+        return core_group_external::create_groups_parameters();
+    }
+
+    /**
+     * Create groups
+     * @deprecated since Moodle 2.2 please use core_group_external::create_groups instead
+     * @param array $groups array of group description arrays (with keys groupname and courseid)
+     * @return array of newly created groups
+     */
+    public static function create_groups($groups) {
+        return core_group_external::create_groups($groups);
+    }
+
+   /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_group_external::create_groups_returns instead
+     * @return external_description
+     */
+    public static function create_groups_returns() {
+        return core_group_external::create_groups_returns();
+    }
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_group_external::get_groups_parameters instead
+     * @return external_function_parameters
+     */
+    public static function get_groups_parameters() {
+        return core_group_external::get_groups_parameters();
+    }
+
+    /**
+     * Get groups definition specified by ids
+     * @deprecated since Moodle 2.2 please use core_group_external::get_groups instead
+     * @param array $groupids arrays of group ids
+     * @return array of group objects (id, courseid, name, enrolmentkey)
+     */
+    public static function get_groups($groupids) {
+        return core_group_external::get_groups($groupids);
+    }
+
+   /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_group_external::get_groups_returns instead
+     * @return external_description
+     */
+    public static function get_groups_returns() {
+        return core_group_external::get_groups_returns();
+    }
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_group_external::get_course_groups_parameters instead
+     * @return external_function_parameters
+     */
+    public static function get_course_groups_parameters() {
+        return core_group_external::get_course_groups_parameters();
+    }
+
+    /**
+     * Get all groups in the specified course
+     * @deprecated since Moodle 2.2 please use core_group_external::get_course_groups instead
+     * @param int $courseid id of course
+     * @return array of group objects (id, courseid, name, enrolmentkey)
+     */
+    public static function get_course_groups($courseid) {
+        return core_group_external::get_course_groups($courseid);
+    }
+
+   /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_group_external::get_course_groups_returns instead
+     * @return external_description
+     */
+    public static function get_course_groups_returns() {
+        return core_group_external::get_course_groups_returns();
+    }
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_group_external::delete_group_members_parameters instead
+     * @return external_function_parameters
+     */
+    public static function delete_groups_parameters() {
+        return core_group_external::delete_group_members_parameters();
+    }
+
+    /**
+     * Delete groups
+     * @deprecated since Moodle 2.2 please use core_group_external::delete_groups instead
+     * @param array $groupids array of group ids
+     * @return void
+     */
+    public static function delete_groups($groupids) {
+        return core_group_external::delete_groups($groupids);
+    }
+
+   /**
+     * Returns description of method result value
+    * @deprecated since Moodle 2.2 please use core_group_external::delete_group_members_returns instead
+     * @return external_description
+     */
+    public static function delete_groups_returns() {
+        return core_group_external::delete_group_members_returns();
+    }
+
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_group_external::get_group_members_parameters instead
+     * @return external_function_parameters
+     */
+    public static function get_groupmembers_parameters() {
+        return core_group_external::get_group_members_parameters();
+    }
+
+    /**
+     * Return all members for a group
+     * @deprecated since Moodle 2.2 please use core_group_external::get_group_members instead
+     * @param array $groupids array of group ids
+     * @return array with  group id keys containing arrays of user ids
+     */
+    public static function get_groupmembers($groupids) {
+        return core_group_external::get_group_members($groupids);
+    }
+
+   /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_group_external::get_group_members_returns instead
+     * @return external_description
+     */
+    public static function get_groupmembers_returns() {
+        return core_group_external::get_group_members_returns();
+    }
+
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_group_external::add_group_members_parameters instead
+     * @return external_function_parameters
+     */
+    public static function add_groupmembers_parameters() {
+        return core_group_external::add_group_members_parameters();
+    }
+
+    /**
+     * Add group members
+     * @deprecated since Moodle 2.2 please use core_group_external::add_group_members instead
+     * @param array $members of arrays with keys userid, groupid
+     * @return void
+     */
+    public static function add_groupmembers($members) {
+        return core_group_external::add_group_members($members);
+    }
+
+   /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_group_external::add_group_members_returns instead
+     * @return external_description
+     */
+    public static function add_groupmembers_returns() {
+        return core_group_external::add_group_members_returns();
+    }
+
+
+    /**
+     * Returns description of method parameters
+     * @deprecated since Moodle 2.2 please use core_group_external::delete_group_members_parameters instead
+     * @return external_function_parameters
+     */
+    public static function delete_groupmembers_parameters() {
+        return core_group_external::delete_group_members_parameters();
+    }
+
+    /**
+     * Delete group members
+     * @deprecated since Moodle 2.2 please use core_group_external::delete_group_members instead
+     * @param array $members of arrays with keys userid, groupid
+     * @return void
+     */
+    public static function delete_groupmembers($members) {
+        return core_group_external::delete_group_members($members);
+    }
+
+   /**
+     * Returns description of method result value
+     * @deprecated since Moodle 2.2 please use core_group_external::delete_group_members_returns instead
+     * @return external_description
+     */
+    public static function delete_groupmembers_returns() {
+        return core_group_external::delete_group_members_returns();
+    }
+
+}
\ No newline at end of file
index dc1bc8f..446e8d7 100644 (file)
@@ -1391,6 +1391,7 @@ $string['rssarticles'] = 'Number of RSS recent articles';
 $string['rsserror'] = 'Error reading RSS data';
 $string['rsserrorauth'] = 'Your RSS link does not contain a valid authentication token.';
 $string['rsserrorguest'] = 'This feed uses guest access to access the data, but guest does not have permission to read the data. Visit the original location that this feed comes from (URL) as a valid user and get a new RSS link from there.';
+$string['rsskeyshelp'] = 'To ensure security and privacy, RSS feed URLs contain a special token that identifies the user they are for. This prevents other users from accessing areas of Moodle they shouldn\'t have access to via RSS feeds.</p><p>This token is automatically created the first time you access an area of Moodle that produces an RSS feed. If you feel that your RSS feed token has been compromised in some way you can request a new one by clicking the Reset link here. Please note that your current RSS feed URLs will then become invalid.';
 $string['rsstype'] = 'RSS feed for this activity';
 $string['saveandnext'] = 'Save and show next';
 $string['savedat'] = 'Saved at:';
index 075ca23..2012768 100644 (file)
@@ -24,7 +24,6 @@
  */
 
 $string['accessexception'] = 'Access control exception';
-$string['accessnotallowed'] = 'Access to web service not allowed';
 $string['actwebserviceshhdr'] = 'Active web service protocols';
 $string['accesstofunctionnotallowed'] = 'Access to the function {$a}() is not allowed. Please check if a service containing the function is enabled. In the service settings: if the service is restricted check that the user is listed. Still in the service settings check for IP restriction or if the service requires a capability.';
 $string['addaservice'] = 'Add service';
@@ -130,6 +129,7 @@ $string['potusers'] = 'Not authorised users';
 $string['potusersmatching'] = 'Not authorised users matching';
 $string['print'] = 'Print all';
 $string['protocol'] = 'Protocol';
+$string['protocolnotallowed'] = 'You are not allowed to use the {$a} protocol (missing capability: webservice/{$a}:use)';
 $string['removefunction'] = 'Remove';
 $string['removefunctionconfirm'] = 'Do you really want to remove function "{$a->function}" from service "{$a->service}"?';
 $string['requireauthentication'] = 'This method requires authentication with xxx permission.';
index 21ba4b4..cc685ff 100644 (file)
@@ -4426,237 +4426,6 @@ function role_change_permission($roleid, $context, $capname, $permission) {
 }
 
 
-/**
- * Context maintenance and helper methods.
- *
- * This is "extends context" is a bloody hack that tires to work around the deficiencies
- * in the "protected" keyword in PHP, this helps us to hide all the internals of context
- * level implementation from the rest of code, the code completion returns what developers need.
- *
- * Thank you Tim Hunt for helping me with this nasty trick.
- *
- * @author Petr Skoda
- */
-class context_helper extends context {
-
-    private static $alllevels = array(
-            CONTEXT_SYSTEM    => 'context_system',
-            CONTEXT_USER      => 'context_user',
-            CONTEXT_COURSECAT => 'context_coursecat',
-            CONTEXT_COURSE    => 'context_course',
-            CONTEXT_MODULE    => 'context_module',
-            CONTEXT_BLOCK     => 'context_block',
-    );
-
-    /**
-     * Instance does not make sense here, only static use
-     */
-    protected function __construct() {
-    }
-
-    /**
-     * Returns a class name of the context level class
-     *
-     * @static
-     * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
-     * @return string class name of the context class
-     */
-    public static function get_class_for_level($contextlevel) {
-        if (isset(self::$alllevels[$contextlevel])) {
-            return self::$alllevels[$contextlevel];
-        } else {
-            throw new coding_exception('Invalid context level specified');
-        }
-    }
-
-    /**
-     * Returns a list of all context levels
-     *
-     * @static
-     * @return array int=>string (level=>level class name)
-     */
-    public static function get_all_levels() {
-        return self::$alllevels;
-    }
-
-    /**
-     * Remove stale contexts that belonged to deleted instances.
-     * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
-     *
-     * @static
-     * @return void
-     */
-    public static function cleanup_instances() {
-        global $DB;
-        $sqls = array();
-        foreach (self::$alllevels as $level=>$classname) {
-            $sqls[] = $classname::get_cleanup_sql();
-        }
-
-        $sql = implode(" UNION ", $sqls);
-
-        // it is probably better to use transactions, it might be faster too
-        $transaction = $DB->start_delegated_transaction();
-
-        $rs = $DB->get_recordset_sql($sql);
-        foreach ($rs as $record) {
-            $context = context::create_instance_from_record($record);
-            $context->delete();
-        }
-        $rs->close();
-
-        $transaction->allow_commit();
-    }
-
-    /**
-     * Create all context instances at the given level and above.
-     *
-     * @static
-     * @param int $contextlevel null means all levels
-     * @param bool $buildpaths
-     * @return void
-     */
-    public static function create_instances($contextlevel = null, $buildpaths = true) {
-        foreach (self::$alllevels as $level=>$classname) {
-            if ($contextlevel and $level > $contextlevel) {
-                // skip potential sub-contexts
-                continue;
-            }
-            $classname::create_level_instances();
-            if ($buildpaths) {
-                $classname::build_paths(false);
-            }
-        }
-    }
-
-    /**
-     * Rebuild paths and depths in all context levels.
-     *
-     * @static
-     * @param bool $force false means add missing only
-     * @return void
-     */
-    public static function build_all_paths($force = false) {
-        foreach (self::$alllevels as $classname) {
-            $classname::build_paths($force);
-        }
-
-        // reset static course cache - it might have incorrect cached data
-        accesslib_clear_all_caches(true);
-    }
-
-    /**
-     * Resets the cache to remove all data.
-     * @static
-     */
-    public static function reset_caches() {
-        context::reset_caches();
-    }
-
-    /**
-     * Returns all fields necessary for context preloading from user $rec.
-     *
-     * This helps with performance when dealing with hundreds of contexts.
-     *
-     * @static
-     * @param string $tablealias context table alias in the query
-     * @return array (table.column=>alias, ...)
-     */
-    public static function get_preload_record_columns($tablealias) {
-        return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
-    }
-
-    /**
-     * Returns all fields necessary for context preloading from user $rec.
-     *
-     * This helps with performance when dealing with hundreds of contexts.
-     *
-     * @static
-     * @param string $tablealias context table alias in the query
-     * @return string
-     */
-    public static function get_preload_record_columns_sql($tablealias) {
-        return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
-    }
-
-    /**
-     * Preloads context information from db record and strips the cached info.
-     *
-     * The db request has to contain all columns from context_helper::get_preload_record_columns().
-     *
-     * @static
-     * @param stdClass $rec
-     * @return void (modifies $rec)
-     */
-     public static function preload_from_record(stdClass $rec) {
-         context::preload_from_record($rec);
-     }
-
-    /**
-     * Preload all contexts instances from course.
-     *
-     * To be used if you expect multiple queries for course activities...
-     *
-     * @static
-     * @param $courseid
-     */
-    public static function preload_course($courseid) {
-        // Users can call this multiple times without doing any harm
-        if (isset(context::$cache_preloaded[$courseid])) {
-            return;
-        }
-        $coursecontext = context_course::instance($courseid);
-        $coursecontext->get_child_contexts();
-
-        context::$cache_preloaded[$courseid] = true;
-    }
-
-    /**
-     * Delete context instance
-     *
-     * @static
-     * @param int $contextlevel
-     * @param int $instanceid
-     * @return void
-     */
-    public static function delete_instance($contextlevel, $instanceid) {
-        global $DB;
-
-        // double check the context still exists
-        if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
-            $context = context::create_instance_from_record($record);
-            $context->delete();
-        } else {
-            // we should try to purge the cache anyway
-        }
-    }
-
-    /**
-     * Returns the name of specified context level
-     *
-     * @static
-     * @param int $contextlevel
-     * @return string name of the context level
-     */
-    public static function get_level_name($contextlevel) {
-        $classname = context_helper::get_class_for_level($contextlevel);
-        return $classname::get_level_name();
-    }
-
-    /**
-     * not used
-     */
-    public function get_url() {
-    }
-
-    /**
-     * not used
-     */
-    public function get_capabilities() {
-    }
-}
-
-
 /**
  * Basic moodle context abstraction class.
  *
@@ -5393,6 +5162,237 @@ abstract class context extends stdClass {
 }
 
 
+/**
+ * Context maintenance and helper methods.
+ *
+ * This is "extends context" is a bloody hack that tires to work around the deficiencies
+ * in the "protected" keyword in PHP, this helps us to hide all the internals of context
+ * level implementation from the rest of code, the code completion returns what developers need.
+ *
+ * Thank you Tim Hunt for helping me with this nasty trick.
+ *
+ * @author Petr Skoda
+ */
+class context_helper extends context {
+
+    private static $alllevels = array(
+            CONTEXT_SYSTEM    => 'context_system',
+            CONTEXT_USER      => 'context_user',
+            CONTEXT_COURSECAT => 'context_coursecat',
+            CONTEXT_COURSE    => 'context_course',
+            CONTEXT_MODULE    => 'context_module',
+            CONTEXT_BLOCK     => 'context_block',
+    );
+
+    /**
+     * Instance does not make sense here, only static use
+     */
+    protected function __construct() {
+    }
+
+    /**
+     * Returns a class name of the context level class
+     *
+     * @static
+     * @param int $contextlevel (CONTEXT_SYSTEM, etc.)
+     * @return string class name of the context class
+     */
+    public static function get_class_for_level($contextlevel) {
+        if (isset(self::$alllevels[$contextlevel])) {
+            return self::$alllevels[$contextlevel];
+        } else {
+            throw new coding_exception('Invalid context level specified');
+        }
+    }
+
+    /**
+     * Returns a list of all context levels
+     *
+     * @static
+     * @return array int=>string (level=>level class name)
+     */
+    public static function get_all_levels() {
+        return self::$alllevels;
+    }
+
+    /**
+     * Remove stale contexts that belonged to deleted instances.
+     * Ideally all code should cleanup contexts properly, unfortunately accidents happen...
+     *
+     * @static
+     * @return void
+     */
+    public static function cleanup_instances() {
+        global $DB;
+        $sqls = array();
+        foreach (self::$alllevels as $level=>$classname) {
+            $sqls[] = $classname::get_cleanup_sql();
+        }
+
+        $sql = implode(" UNION ", $sqls);
+
+        // it is probably better to use transactions, it might be faster too
+        $transaction = $DB->start_delegated_transaction();
+
+        $rs = $DB->get_recordset_sql($sql);
+        foreach ($rs as $record) {
+            $context = context::create_instance_from_record($record);
+            $context->delete();
+        }
+        $rs->close();
+
+        $transaction->allow_commit();
+    }
+
+    /**
+     * Create all context instances at the given level and above.
+     *
+     * @static
+     * @param int $contextlevel null means all levels
+     * @param bool $buildpaths
+     * @return void
+     */
+    public static function create_instances($contextlevel = null, $buildpaths = true) {
+        foreach (self::$alllevels as $level=>$classname) {
+            if ($contextlevel and $level > $contextlevel) {
+                // skip potential sub-contexts
+                continue;
+            }
+            $classname::create_level_instances();
+            if ($buildpaths) {
+                $classname::build_paths(false);
+            }
+        }
+    }
+
+    /**
+     * Rebuild paths and depths in all context levels.
+     *
+     * @static
+     * @param bool $force false means add missing only
+     * @return void
+     */
+    public static function build_all_paths($force = false) {
+        foreach (self::$alllevels as $classname) {
+            $classname::build_paths($force);
+        }
+
+        // reset static course cache - it might have incorrect cached data
+        accesslib_clear_all_caches(true);
+    }
+
+    /**
+     * Resets the cache to remove all data.
+     * @static
+     */
+    public static function reset_caches() {
+        context::reset_caches();
+    }
+
+    /**
+     * Returns all fields necessary for context preloading from user $rec.
+     *
+     * This helps with performance when dealing with hundreds of contexts.
+     *
+     * @static
+     * @param string $tablealias context table alias in the query
+     * @return array (table.column=>alias, ...)
+     */
+    public static function get_preload_record_columns($tablealias) {
+        return array("$tablealias.id"=>"ctxid", "$tablealias.path"=>"ctxpath", "$tablealias.depth"=>"ctxdepth", "$tablealias.contextlevel"=>"ctxlevel", "$tablealias.instanceid"=>"ctxinstance");
+    }
+
+    /**
+     * Returns all fields necessary for context preloading from user $rec.
+     *
+     * This helps with performance when dealing with hundreds of contexts.
+     *
+     * @static
+     * @param string $tablealias context table alias in the query
+     * @return string
+     */
+    public static function get_preload_record_columns_sql($tablealias) {
+        return "$tablealias.id AS ctxid, $tablealias.path AS ctxpath, $tablealias.depth AS ctxdepth, $tablealias.contextlevel AS ctxlevel, $tablealias.instanceid AS ctxinstance";
+    }
+
+    /**
+     * Preloads context information from db record and strips the cached info.
+     *
+     * The db request has to contain all columns from context_helper::get_preload_record_columns().
+     *
+     * @static
+     * @param stdClass $rec
+     * @return void (modifies $rec)
+     */
+     public static function preload_from_record(stdClass $rec) {
+         context::preload_from_record($rec);
+     }
+
+    /**
+     * Preload all contexts instances from course.
+     *
+     * To be used if you expect multiple queries for course activities...
+     *
+     * @static
+     * @param $courseid
+     */
+    public static function preload_course($courseid) {
+        // Users can call this multiple times without doing any harm
+        if (isset(context::$cache_preloaded[$courseid])) {
+            return;
+        }
+        $coursecontext = context_course::instance($courseid);
+        $coursecontext->get_child_contexts();
+
+        context::$cache_preloaded[$courseid] = true;
+    }
+
+    /**
+     * Delete context instance
+     *
+     * @static
+     * @param int $contextlevel
+     * @param int $instanceid
+     * @return void
+     */
+    public static function delete_instance($contextlevel, $instanceid) {
+        global $DB;
+
+        // double check the context still exists
+        if ($record = $DB->get_record('context', array('contextlevel'=>$contextlevel, 'instanceid'=>$instanceid))) {
+            $context = context::create_instance_from_record($record);
+            $context->delete();
+        } else {
+            // we should try to purge the cache anyway
+        }
+    }
+
+    /**
+     * Returns the name of specified context level
+     *
+     * @static
+     * @param int $contextlevel
+     * @return string name of the context level
+     */
+    public static function get_level_name($contextlevel) {
+        $classname = context_helper::get_class_for_level($contextlevel);
+        return $classname::get_level_name();
+    }
+
+    /**
+     * not used
+     */
+    public function get_url() {
+    }
+
+    /**
+     * not used
+     */
+    public function get_capabilities() {
+    }
+}
+
+
 /**
  * Basic context class
  * @author Petr Skoda (http://skodak.org)
diff --git a/lib/base32.php b/lib/base32.php
deleted file mode 100644 (file)
index 831c712..0000000
+++ /dev/null
@@ -1,196 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | Base32 Library                                                     |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 2001 The PHP Group                                     |
-// +----------------------------------------------------------------------+
-// | This source file is dual-licensed. It is available under the terms   | 
-// | of the GNU GPL v2.0 and under the terms of the PHP license version   |
-// | 2.02,  available at through the world-wide-web at                    |
-// | available at through the world-wide-web at                           |
-// | http://www.php.net/license/2_02.txt.                                 |
-// +----------------------------------------------------------------------+
-// |  Minor fixes and additional functions by Allan Hansen.               |
-// |  Moodle porting work by Martin Langhoff                              |
-// +----------------------------------------------------------------------+
-// | base32.php - based on race.php  - RACE encode and decode strings.    |
-// +----------------------------------------------------------------------+
-// | Authors: Allan Hansen  <All@nHansen.dk>                              |
-// |          Arjan Wekking <a.wekking@synantics.nl>                      |
-// |          Martin Langhoff <martin@catalyst.net.nz>                    |
-// +----------------------------------------------------------------------+
-//
-
-/**
- * @package moodlecore
- * @copyright (c) 2001 The PHP Group
- * @license GNU GPL v2.0 http://www.php.net/license/2_02.txt
- */
-
-/**
- * Base32 encode a binary string
- *
- * @param    $inString   Binary string to base32 encode
- *
- * @return   $outString  Base32 encoded $inString
- *
- * @access   private
- *
- */
-
-function base32_encode ($inString) 
-{ 
-    $outString = ""; 
-    $compBits = ""; 
-    $BASE32_TABLE = array( 
-                          '00000' => 0x61, 
-                          '00001' => 0x62, 
-                          '00010' => 0x63, 
-                          '00011' => 0x64, 
-                          '00100' => 0x65, 
-                          '00101' => 0x66, 
-                          '00110' => 0x67, 
-                          '00111' => 0x68, 
-                          '01000' => 0x69, 
-                          '01001' => 0x6a, 
-                          '01010' => 0x6b, 
-                          '01011' => 0x6c, 
-                          '01100' => 0x6d, 
-                          '01101' => 0x6e, 
-                          '01110' => 0x6f, 
-                          '01111' => 0x70, 
-                          '10000' => 0x71, 
-                          '10001' => 0x72, 
-                          '10010' => 0x73, 
-                          '10011' => 0x74, 
-                          '10100' => 0x75, 
-                          '10101' => 0x76, 
-                          '10110' => 0x77, 
-                          '10111' => 0x78, 
-                          '11000' => 0x79, 
-                          '11001' => 0x7a, 
-                          '11010' => 0x32, 
-                          '11011' => 0x33, 
-                          '11100' => 0x34, 
-                          '11101' => 0x35, 
-                          '11110' => 0x36, 
-                          '11111' => 0x37, 
-                          ); 
-    
-    /* Turn the compressed string into a string that represents the bits as 0 and 1. */
-    for ($i = 0; $i < strlen($inString); $i++) {
-        $compBits .= str_pad(decbin(ord(substr($inString,$i,1))), 8, '0', STR_PAD_LEFT);
-    }
-    
-    /* Pad the value with enough 0's to make it a multiple of 5 */
-    if((strlen($compBits) % 5) != 0) {
-        $compBits = str_pad($compBits, strlen($compBits)+(5-(strlen($compBits)%5)), '0', STR_PAD_RIGHT);
-    }
-    
-    /* Create an array by chunking it every 5 chars */
-    $fiveBitsArray = explode("\n",rtrim(chunk_split($compBits, 5, "\n"))); 
-    
-    /* Look-up each chunk and add it to $outstring */
-    foreach($fiveBitsArray as $fiveBitsString) { 
-        $outString .= chr($BASE32_TABLE[$fiveBitsString]); 
-    } 
-    
-    return $outString; 
-} 
-
-
-
-/**
- * Base32 decode to a binary string
- *
- * @param    $inString   String to base32 decode
- *
- * @return   $outString  Base32 decoded $inString
- *
- * @access   private
- *
- */
-
-function Base32_decode($inString) {
-    /* declaration */
-    $inputCheck = null;
-    $deCompBits = null;
-    
-    $BASE32_TABLE = array( 
-                          0x61 => '00000', 
-                          0x62 => '00001', 
-                          0x63 => '00010', 
-                          0x64 => '00011', 
-                          0x65 => '00100', 
-                          0x66 => '00101', 
-                          0x67 => '00110', 
-                          0x68 => '00111', 
-                          0x69 => '01000', 
-                          0x6a => '01001', 
-                          0x6b => '01010', 
-                          0x6c => '01011', 
-                          0x6d => '01100', 
-                          0x6e => '01101', 
-                          0x6f => '01110', 
-                          0x70 => '01111', 
-                          0x71 => '10000', 
-                          0x72 => '10001', 
-                          0x73 => '10010', 
-                          0x74 => '10011', 
-                          0x75 => '10100', 
-                          0x76 => '10101', 
-                          0x77 => '10110', 
-                          0x78 => '10111', 
-                          0x79 => '11000', 
-                          0x7a => '11001', 
-                          0x32 => '11010', 
-                          0x33 => '11011', 
-                          0x34 => '11100', 
-                          0x35 => '11101', 
-                          0x36 => '11110', 
-                          0x37 => '11111', 
-                          ); 
-    
-    /* Step 1 */
-    $inputCheck = strlen($inString) % 8;
-    if(($inputCheck == 1)||($inputCheck == 3)||($inputCheck == 6)) { 
-        trigger_error('input to Base32Decode was a bad mod length: '.$inputCheck);
-        return false; 
-        //return $this->raiseError('input to Base32Decode was a bad mod length: '.$inputCheck, null, 
-        // PEAR_ERROR_DIE, null, null, 'Net_RACE_Error', false );
-    }
-    
-    /* $deCompBits is a string that represents the bits as 0 and 1.*/
-    for ($i = 0; $i < strlen($inString); $i++) {
-        $inChar = ord(substr($inString,$i,1));
-        if(isset($BASE32_TABLE[$inChar])) {
-            $deCompBits .= $BASE32_TABLE[$inChar];
-        } else {
-            trigger_error('input to Base32Decode had a bad character: '.$inChar);
-            return false;
-            //return $this->raiseError('input to Base32Decode had a bad character: '.$inChar, null, 
-            //    PEAR_ERROR_DIE, null, null, 'Net_RACE_Error', false );
-        }
-    }
-    
-    /* Step 5 */
-    $padding = strlen($deCompBits) % 8;
-    $paddingContent = substr($deCompBits, (strlen($deCompBits) - $padding));
-    if(substr_count($paddingContent, '1')>0) { 
-        trigger_error('found non-zero padding in Base32Decode');
-        return false;
-        //return $this->raiseError('found non-zero padding in Base32Decode', null, 
-        //    PEAR_ERROR_DIE, null, null, 'Net_RACE_Error', false );
-    }
-    
-    /* Break the decompressed string into octets for returning */
-    $deArr = array();
-    for($i = 0; $i < (int)(strlen($deCompBits) / 8); $i++) {
-        $deArr[$i] = chr(bindec(substr($deCompBits, $i*8, 8)));
-    }
-    
-    $outString = join('',$deArr);
-    
-    return $outString;
-}
diff --git a/lib/csshover.htc b/lib/csshover.htc
deleted file mode 100644 (file)
index f00536d..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-<attach event="ondocumentready" handler="parseStylesheets" />
-<script type="text/javascript">
-/**
- *     Pseudos - V1.30.050121 - hover & active
- *     ---------------------------------------------
- *     Peterned - http://www.xs4all.nl/~peterned/
- *     (c) 2005 - Peter Nederlof
- *
- *     Credits  - Arnoud Berendsen 
- *              - Martin Reurings
- *           - Robert Hanson
- *
- *     howto: body { behavior:url("csshover.htc"); }
- *     ---------------------------------------------
- */
-
-var currentSheet, doc = window.document, activators = {
-       onhover:{on:'onmouseover', off:'onmouseout'},
-       onactive:{on:'onmousedown', off:'onmouseup'}
-}
-
-function parseStylesheets() {
-       var sheets = doc.styleSheets, l = sheets.length;
-       for(var i=0; i<l; i++) 
-               parseStylesheet(sheets[i]);
-}
-       function parseStylesheet(sheet) {
-               if(sheet.imports) {
-                       try {
-                               var imports = sheet.imports, l = imports.length;
-                               for(var i=0; i<l; i++) parseStylesheet(sheet.imports[i]);
-                       } catch(securityException){}
-               }
-
-               try {
-                       var rules = (currentSheet = sheet).rules, l = rules.length;
-                       for(var j=0; j<l; j++) parseCSSRule(rules[j]);
-               } catch(securityException){}
-       }
-
-       function parseCSSRule(rule) {
-               var select = rule.selectorText, style = rule.style.cssText;
-               if(!(/(^|\s)(([^a]([^ ]+)?)|(a([^#.][^ ]+)+)):(hover|active)/i).test(select) || !style) return;
-               
-               var pseudo = select.replace(/[^:]+:([a-z-]+).*/i, 'on$1');
-               var newSelect = select.replace(/(\.([a-z0-9_-]+):[a-z]+)|(:[a-z]+)/gi, '.$2' + pseudo);
-               var className = (/\.([a-z0-9_-]*on(hover|active))/i).exec(newSelect)[1];
-               var affected = select.replace(/:hover.*$/, '');
-               var elements = getElementsBySelect(affected);
-
-               currentSheet.addRule(newSelect, style);
-               for(var i=0; i<elements.length; i++)
-                       new HoverElement(elements[i], className, activators[pseudo]);
-       }
-
-function HoverElement(node, className, events) {
-       if(!node.hovers) node.hovers = {};
-       if(node.hovers[className]) return;
-       node.hovers[className] = true;
-       node.attachEvent(events.on,
-               function() { node.className += ' ' + className; });
-       node.attachEvent(events.off,
-               function() { node.className = 
-                       node.className.replace(new RegExp('\\s+'+className, 'g'),''); });
-}
-
-function getElementsBySelect(rule) {
-       var parts, nodes = [doc];
-       parts = rule.split(' ');
-       for(var i=0; i<parts.length; i++) {
-               nodes = getSelectedNodes(parts[i], nodes);
-       }       return nodes;
-}
-       function getSelectedNodes(select, elements) {
-               var result, node, nodes = [];
-               var classname = (/\.([a-z0-9_-]+)/i).exec(select);
-               var identify = (/\#([a-z0-9_-]+)/i).exec(select);
-               var tagName = select.replace(/(\.|\#|\:)[a-z0-9_-]+/i, '');
-               for(var i=0; i<elements.length; i++) {
-                       result = tagName? elements[i].all.tags(tagName):elements[i].all; 
-                       for(var j=0; j<result.length; j++) {
-                               node = result[j];
-                               if((identify && node.id != identify[1]) || (classname && !(new RegExp('\\b' +
-                                       classname[1] + '\\b').exec(node.className)))) continue;
-                               nodes[nodes.length] = node;
-                       }
-               }       return nodes;
-       }
-</script>
\ No newline at end of file
index 117bf9d..90df2e6 100644 (file)
@@ -29,7 +29,16 @@ $functions = array(
     // === group related functions ===
 
     'moodle_group_create_groups' => array(
-        'classname'   => 'moodle_group_external',
+        'classname'   => 'core_group_external',
+        'methodname'  => 'create_groups',
+        'classpath'   => 'group/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_group_create_groups(). ',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/course:managegroups',
+    ),
+
+    'core_group_create_groups' => array(
+        'classname'   => 'core_group_external',
         'methodname'  => 'create_groups',
         'classpath'   => 'group/externallib.php',
         'description' => 'Creates new groups.',
@@ -38,7 +47,16 @@ $functions = array(
     ),
 
     'moodle_group_get_groups' => array(
-        'classname'   => 'moodle_group_external',
+        'classname'   => 'core_group_external',
+        'methodname'  => 'get_groups',
+        'classpath'   => 'group/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_group_get_groups()',
+        'type'        => 'read',
+        'capabilities'=> 'moodle/course:managegroups',
+    ),
+
+    'core_group_get_groups' => array(
+        'classname'   => 'core_group_external',
         'methodname'  => 'get_groups',
         'classpath'   => 'group/externallib.php',
         'description' => 'Returns group details.',
@@ -47,7 +65,16 @@ $functions = array(
     ),
 
     'moodle_group_get_course_groups' => array(
-        'classname'   => 'moodle_group_external',
+        'classname'   => 'core_group_external',
+        'methodname'  => 'get_course_groups',
+        'classpath'   => 'group/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_group_get_course_groups()',
+        'type'        => 'read',
+        'capabilities'=> 'moodle/course:managegroups',
+    ),
+
+    'core_group_get_course_groups' => array(
+        'classname'   => 'core_group_external',
         'methodname'  => 'get_course_groups',
         'classpath'   => 'group/externallib.php',
         'description' => 'Returns all groups in specified course.',
@@ -56,7 +83,16 @@ $functions = array(
     ),
 
     'moodle_group_delete_groups' => array(
-        'classname'   => 'moodle_group_external',
+        'classname'   => 'core_group_external',
+        'methodname'  => 'delete_groups',
+        'classpath'   => 'group/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_group_delete_groups()',
+        'type'        => 'delete',
+        'capabilities'=> 'moodle/course:managegroups',
+    ),
+
+    'core_group_delete_groups' => array(
+        'classname'   => 'core_group_external',
         'methodname'  => 'delete_groups',
         'classpath'   => 'group/externallib.php',
         'description' => 'Deletes all specified groups.',
@@ -65,8 +101,17 @@ $functions = array(
     ),
 
     'moodle_group_get_groupmembers' => array(
-        'classname'   => 'moodle_group_external',
-        'methodname'  => 'get_groupmembers',
+        'classname'   => 'core_group_external',
+        'methodname'  => 'get_group_members',
+        'classpath'   => 'group/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_group_get_group_members()',
+        'type'        => 'read',
+        'capabilities'=> 'moodle/course:managegroups',
+    ),
+
+    'core_group_get_group_members' => array(
+        'classname'   => 'core_group_external',
+        'methodname'  => 'get_group_members',
         'classpath'   => 'group/externallib.php',
         'description' => 'Returns group members.',
         'type'        => 'read',
@@ -74,8 +119,17 @@ $functions = array(
     ),
 
     'moodle_group_add_groupmembers' => array(
-        'classname'   => 'moodle_group_external',
-        'methodname'  => 'add_groupmembers',
+        'classname'   => 'core_group_external',
+        'methodname'  => 'add_group_members',
+        'classpath'   => 'group/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_group_add_group_members()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/course:managegroups',
+    ),
+
+    'core_group_add_group_members' => array(
+        'classname'   => 'core_group_external',
+        'methodname'  => 'add_group_members',
         'classpath'   => 'group/externallib.php',
         'description' => 'Adds group members.',
         'type'        => 'write',
@@ -83,26 +137,51 @@ $functions = array(
     ),
 
     'moodle_group_delete_groupmembers' => array(
-        'classname'   => 'moodle_group_external',
-        'methodname'  => 'delete_groupmembers',
+        'classname'   => 'core_group_external',
+        'methodname'  => 'delete_group_members',
         'classpath'   => 'group/externallib.php',
-        'description' => 'Deletes group members.',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_group_delete_group_members()',
         'type'        => 'delete',
         'capabilities'=> 'moodle/course:managegroups',
     ),
 
+    'core_group_delete_group_members' => array(
+        'classname'   => 'core_group_external',
+        'methodname'  => 'delete_group_members',
+        'classpath'   => 'group/externallib.php',
+        'description' => 'Deletes group members.',
+        'type'        => 'delete',
+        'capabilities'=> 'moodle/course:managegroups',
+    ),
 
     // === file related functions ===
 
     'moodle_file_get_files' => array(
-        'classname'   => 'moodle_file_external',
+        'classname'   => 'core_files_external',
+        'methodname'  => 'get_files',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_files_get_files()',
+        'type'        => 'read',
+        'classpath'   => 'files/externallib.php',
+    ),
+
+    'core_files_get_files' => array(
+        'classname'   => 'core_files_external',
         'methodname'  => 'get_files',
         'description' => 'browse moodle files',
         'type'        => 'read',
         'classpath'   => 'files/externallib.php',
     ),
+
     'moodle_file_upload' => array(
-        'classname'   => 'moodle_file_external',
+        'classname'   => 'core_files_external',
+        'methodname'  => 'upload',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_files_upload()',
+        'type'        => 'write',
+        'classpath'   => 'files/externallib.php',
+    ),
+
+    'core_files_upload' => array(
+        'classname'   => 'core_files_external',
         'methodname'  => 'upload',
         'description' => 'upload a file to moodle',
         'type'        => 'write',
@@ -112,7 +191,16 @@ $functions = array(
     // === user related functions ===
 
     'moodle_user_create_users' => array(
-        'classname'   => 'moodle_user_external',
+        'classname'   => 'core_user_external',
+        'methodname'  => 'create_users',
+        'classpath'   => 'user/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_user_create_users()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/user:create',
+    ),
+
+    'core_user_create_users' => array(
+        'classname'   => 'core_user_external',
         'methodname'  => 'create_users',
         'classpath'   => 'user/externallib.php',
         'description' => 'Create users.',
@@ -121,7 +209,16 @@ $functions = array(
     ),
 
     'moodle_user_get_users_by_id' => array(
-        'classname'   => 'moodle_user_external',
+        'classname'   => 'core_user_external',
+        'methodname'  => 'get_users_by_id',
+        'classpath'   => 'user/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_user_get_users_by_id()',
+        'type'        => 'read',
+        'capabilities'=> 'moodle/user:viewdetails, moodle/user:viewhiddendetails, moodle/course:useremail, moodle/user:update',
+    ),
+
+    'core_user_get_users_by_id' => array(
+        'classname'   => 'core_user_external',
         'methodname'  => 'get_users_by_id',
         'classpath'   => 'user/externallib.php',
         'description' => 'Get users by id.',
@@ -130,25 +227,43 @@ $functions = array(
     ),
 
     'moodle_user_get_users_by_courseid' => array(
-        'classname'   => 'moodle_user_external',
-        'methodname'  => 'get_users_by_courseid',
-        'classpath'   => 'user/externallib.php',
-        'description' => 'Get enrolled users by course id.',
+        'classname'   => 'core_enrol_external',
+        'methodname'  => 'get_enrolled_users',
+        'classpath'   => 'enrol/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_enrol_get_enrolled_users()',
         'type'        => 'read',
         'capabilities'=> 'moodle/user:viewdetails, moodle/user:viewhiddendetails, moodle/course:useremail, moodle/user:update, moodle/site:accessallgroups',
     ),
 
     'moodle_user_get_course_participants_by_id' => array(
-        'classname'   => 'moodle_user_external',
-        'methodname'  => 'get_course_participants_by_id',
+        'classname'   => 'core_user_external',
+        'methodname'  => 'get_course_user_profiles',
         'classpath'   => 'user/externallib.php',
-        'description' => 'Get course user profiles by id.',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_user_get_course_user_profiles()',
+        'type'        => 'read',
+        'capabilities'=> 'moodle/user:viewdetails, moodle/user:viewhiddendetails, moodle/course:useremail, moodle/user:update, moodle/site:accessallgroups',
+    ),
+
+    'core_user_get_course_user_profiles' => array(
+        'classname'   => 'core_user_external',
+        'methodname'  => 'get_course_user_profiles',
+        'classpath'   => 'user/externallib.php',
+        'description' => 'Get course user profiles (each of the profils matching a course id and a user id).',
         'type'        => 'read',
         'capabilities'=> 'moodle/user:viewdetails, moodle/user:viewhiddendetails, moodle/course:useremail, moodle/user:update, moodle/site:accessallgroups',
     ),
 
     'moodle_user_delete_users' => array(
-        'classname'   => 'moodle_user_external',
+        'classname'   => 'core_user_external',
+        'methodname'  => 'delete_users',
+        'classpath'   => 'user/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_user_delete_users()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/user:delete',
+    ),
+
+    'core_user_delete_users' => array(
+        'classname'   => 'core_user_external',
         'methodname'  => 'delete_users',
         'classpath'   => 'user/externallib.php',
         'description' => 'Delete users.',
@@ -157,7 +272,16 @@ $functions = array(
     ),
 
     'moodle_user_update_users' => array(
-        'classname'   => 'moodle_user_external',
+        'classname'   => 'core_user_external',
+        'methodname'  => 'update_users',
+        'classpath'   => 'user/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_user_update_users()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/user:update',
+    ),
+
+    'core_user_update_users' => array(
+        'classname'   => 'core_user_external',
         'methodname'  => 'update_users',
         'classpath'   => 'user/externallib.php',
         'description' => 'Update users.',
@@ -171,24 +295,53 @@ $functions = array(
         'classname'   => 'moodle_enrol_external',
         'methodname'  => 'get_enrolled_users',
         'classpath'   => 'enrol/externallib.php',
-        'description' => 'Get list of course participants',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. Please use core_enrol_get_enrolled_users() (previously known as moodle_user_get_users_by_courseid).',
         'type'        => 'read',
         'capabilities'=> 'moodle/site:viewparticipants, moodle/course:viewparticipants,
             moodle/role:review, moodle/site:accessallgroups, moodle/course:enrolreview',
     ),
+    
+    'core_enrol_get_enrolled_users' => array(
+        'classname'   => 'core_enrol_external',
+        'methodname'  => 'get_enrolled_users',
+        'classpath'   => 'enrol/externallib.php',
+        'description' => 'Get enrolled users by course id.',
+        'type'        => 'read',
+        'capabilities'=> 'moodle/user:viewdetails, moodle/user:viewhiddendetails, moodle/course:useremail, moodle/user:update, moodle/site:accessallgroups',
+    ),
 
     'moodle_enrol_get_users_courses' => array(
-        'classname'   => 'moodle_enrol_external',
+        'classname'   => 'core_enrol_external',
         'methodname'  => 'get_users_courses',
         'classpath'   => 'enrol/externallib.php',
-        'description' => 'Get list of courses user is enrolled in',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_enrol_get_users_courses()',
         'type'        => 'read',
         'capabilities'=> 'moodle/course:viewparticipants',
     ),
 
+    'core_enrol_get_users_courses' => array(
+        'classname'   => 'core_enrol_external',
+        'methodname'  => 'get_users_courses',
+        'classpath'   => 'enrol/externallib.php',
+        'description' => 'Get the list of courses where a user is enrolled in',
+        'type'        => 'read',
+        'capabilities'=> 'moodle/course:viewparticipants',
+    ),
+
+    // === Role related functions ===
+
     'moodle_role_assign' => array(
-        'classname'   => 'moodle_enrol_external',
-        'methodname'  => 'role_assign',
+        'classname'   => 'core_role_external',
+        'methodname'  => 'assign_roles',
+        'classpath'   => 'enrol/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_role_assign_role()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/role:assign',
+    ),
+
+    'core_role_assign_roles' => array(
+        'classname'   => 'core_role_external',
+        'methodname'  => 'assign_roles',
         'classpath'   => 'enrol/externallib.php',
         'description' => 'Manual role assignments.',
         'type'        => 'write',
@@ -196,8 +349,17 @@ $functions = array(
     ),
 
     'moodle_role_unassign' => array(
-        'classname'   => 'moodle_enrol_external',
-        'methodname'  => 'role_unassign',
+        'classname'   => 'core_role_external',
+        'methodname'  => 'unassign_roles',
+        'classpath'   => 'enrol/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_role_unassign_role()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/role:assign',
+    ),
+
+    'core_role_unassign_roles' => array(
+        'classname'   => 'core_role_external',
+        'methodname'  => 'unassign_roles',
         'classpath'   => 'enrol/externallib.php',
         'description' => 'Manual role unassignments.',
         'type'        => 'write',
@@ -207,7 +369,16 @@ $functions = array(
     // === course related functions ===
 
     'moodle_course_get_courses' => array(
-        'classname'   => 'moodle_course_external',
+        'classname'   => 'core_course_external',
+        'methodname'  => 'get_courses',
+        'classpath'   => 'course/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_course_get_courses()',
+        'type'        => 'read',
+        'capabilities'=> 'moodle/course:view,moodle/course:update,moodle/course:viewhiddencourses',
+    ),
+
+    'core_course_get_courses' => array(
+        'classname'   => 'core_course_external',
         'methodname'  => 'get_courses',
         'classpath'   => 'course/externallib.php',
         'description' => 'Return course details',
@@ -216,7 +387,16 @@ $functions = array(
     ),
 
     'moodle_course_create_courses' => array(
-        'classname'   => 'moodle_course_external',
+        'classname'   => 'core_course_external',
+        'methodname'  => 'create_courses',
+        'classpath'   => 'course/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_course_create_courses()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/course:create,moodle/course:visibility',
+    ),
+
+    'core_course_create_courses' => array(
+        'classname'   => 'core_course_external',
         'methodname'  => 'create_courses',
         'classpath'   => 'course/externallib.php',
         'description' => 'Create new courses',
@@ -227,8 +407,17 @@ $functions = array(
     // === message related functions ===
 
     'moodle_message_send_instantmessages' => array(
-        'classname'   => 'moodle_message_external',
-        'methodname'  => 'send_instantmessages',
+        'classname'   => 'core_message_external',
+        'methodname'  => 'send_instant_messages',
+        'classpath'   => 'message/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_message_send_instant_messages()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/site:sendmessage',
+    ),
+
+    'core_message_send_instant_messages' => array(
+        'classname'   => 'core_message_external',
+        'methodname'  => 'send_instant_messages',
         'classpath'   => 'message/externallib.php',
         'description' => 'Send instant messages',
         'type'        => 'write',
@@ -238,7 +427,16 @@ $functions = array(
     // === notes related functions ===
 
     'moodle_notes_create_notes' => array(
-        'classname'   => 'moodle_notes_external',
+        'classname'   => 'core_notes_external',
+        'methodname'  => 'create_notes',
+        'classpath'   => 'notes/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_notes_create_notes()',
+        'type'        => 'write',
+        'capabilities'=> 'moodle/notes:manage',
+    ),
+
+    'core_notes_create_notes' => array(
+        'classname'   => 'core_notes_external',
         'methodname'  => 'create_notes',
         'classpath'   => 'notes/externallib.php',
         'description' => 'Create notes',
@@ -249,8 +447,16 @@ $functions = array(
     // === webservice related functions ===
 
     'moodle_webservice_get_siteinfo' => array(
-        'classname'   => 'moodle_webservice_external',
-        'methodname'  => 'get_siteinfo',
+        'classname'   => 'core_webservice_external',
+        'methodname'  => 'get_site_info',
+        'classpath'   => 'webservice/externallib.php',
+        'description' => 'DEPRECATED: this deprecated function will be removed in a future version. This function has be renamed as core_webservice_get_site_info()',
+        'type'        => 'read',
+    ),
+
+    'core_webservice_get_site_info' => array(
+        'classname'   => 'core_webservice_external',
+        'methodname'  => 'get_site_info',
         'classpath'   => 'webservice/externallib.php',
         'description' => 'Return some site info / user info / list web service functions',
         'type'        => 'read',
index 835fc76..212179c 100644 (file)
@@ -452,7 +452,7 @@ class stored_file {
      * @return string
      */
     public function get_author() {
-        return $this->file_record->license;
+        return $this->file_record->author;
     }
 
     /**
diff --git a/lib/md5.js b/lib/md5.js
deleted file mode 100644 (file)
index 46d2aab..0000000
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
- * Digest Algorithm, as defined in RFC 1321.
- * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
- * Distributed under the BSD License
- * See http://pajhome.org.uk/crypt/md5 for more info.
- */
-
-/*
- * Configurable variables. You may need to tweak these to be compatible with
- * the server-side, but the defaults work in most cases.
- */
-var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
-var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
-var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */
-
-/*
- * These are the functions you'll usually want to call
- * They take string arguments and return either hex or base-64 encoded strings
- */
-function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
-function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
-function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
-function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
-function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
-function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
-
-/*
- * Perform a simple self-test to see if the VM is working
- */
-function md5_vm_test()
-{
-  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
-}
-
-/*
- * Calculate the MD5 of an array of little-endian words, and a bit length
- */
-function core_md5(x, len)
-{
-  /* append padding */
-  x[len >> 5] |= 0x80 << ((len) % 32);
-  x[(((len + 64) >>> 9) << 4) + 14] = len;
-
-  var a =  1732584193;
-  var b = -271733879;
-  var c = -1732584194;
-  var d =  271733878;
-
-  for(var i = 0; i < x.length; i += 16)
-  {
-    var olda = a;
-    var oldb = b;
-    var oldc = c;
-    var oldd = d;
-
-    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
-    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
-    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
-    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
-    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
-    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
-    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
-    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
-    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
-    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
-    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
-    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
-    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
-    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
-    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
-    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);
-
-    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
-    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
-    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
-    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
-    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
-    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
-    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
-    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
-    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
-    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
-    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
-    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
-    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
-    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
-    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
-    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
-
-    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
-    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
-    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
-    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
-    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
-    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
-    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
-    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
-    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
-    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
-    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
-    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
-    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
-    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
-    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
-    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
-
-    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
-    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
-    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
-    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
-    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
-    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
-    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
-    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
-    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
-    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
-    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
-    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
-    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
-    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
-    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
-    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
-
-    a = safe_add(a, olda);
-    b = safe_add(b, oldb);
-    c = safe_add(c, oldc);
-    d = safe_add(d, oldd);
-  }
-  return Array(a, b, c, d);
-
-}
-
-/*
- * These functions implement the four basic operations the algorithm uses.
- */
-function md5_cmn(q, a, b, x, s, t)
-{
-  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
-}
-function md5_ff(a, b, c, d, x, s, t)
-{
-  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
-}
-function md5_gg(a, b, c, d, x, s, t)
-{
-  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
-}
-function md5_hh(a, b, c, d, x, s, t)
-{
-  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
-}
-function md5_ii(a, b, c, d, x, s, t)
-{
-  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
-}
-
-/*
- * Calculate the HMAC-MD5, of a key and some data
- */
-function core_hmac_md5(key, data)
-{
-  var bkey = str2binl(key);
-  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
-
-  var ipad = Array(16), opad = Array(16);
-  for(var i = 0; i < 16; i++)
-  {
-    ipad[i] = bkey[i] ^ 0x36363636;
-    opad[i] = bkey[i] ^ 0x5C5C5C5C;
-  }
-
-  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
-  return core_md5(opad.concat(hash), 512 + 128);
-}
-
-/*
- * Add integers, wrapping at 2^32. This uses 16-bit operations internally
- * to work around bugs in some JS interpreters.
- */
-function safe_add(x, y)
-{
-  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
-  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
-  return (msw << 16) | (lsw & 0xFFFF);
-}
-
-/*
- * Bitwise rotate a 32-bit number to the left.
- */
-function bit_rol(num, cnt)
-{
-  return (num << cnt) | (num >>> (32 - cnt));
-}
-
-/*
- * Convert a string to an array of little-endian words
- * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
- */
-function str2binl(str)
-{
-  var bin = Array();
-  var mask = (1 << chrsz) - 1;
-  for(var i = 0; i < str.length * chrsz; i += chrsz)
-    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
-  return bin;
-}
-
-/*
- * Convert an array of little-endian words to a string
- */
-function binl2str(bin)
-{
-  var str = "";
-  var mask = (1 << chrsz) - 1;
-  for(var i = 0; i < bin.length * 32; i += chrsz)
-    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
-  return str;
-}
-
-/*
- * Convert an array of little-endian words to a hex string.
- */
-function binl2hex(binarray)
-{
-  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
-  var str = "";
-  for(var i = 0; i < binarray.length * 4; i++)
-  {
-    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
-           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
-  }
-  return str;
-}
-
-/*
- * Convert an array of little-endian words to a base-64 string
- */
-function binl2b64(binarray)
-{
-  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-  var str = "";
-  for(var i = 0; i < binarray.length * 4; i += 3)
-  {
-    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
-                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
-                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
-    for(var j = 0; j < 4; j++)
-    {
-      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
-      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
-    }
-  }
-  return str;
-}
diff --git a/lib/odbc.php b/lib/odbc.php
deleted file mode 100644 (file)
index 3c773a3..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-<?php
-
-/**
- * odbc.php - This is the ODBC Socket Server class PHP client class 
- * with sample usage at bottom.
- *
- * Released into the public domain for version 0.90 of ODBC Socket Server
- * {@link http://odbc.linuxbox.com/}
- * 
- * @package moodlecore
- * @author Team FXML
- * @copyright Copyright (c) 1999 Team FXML
- * @license http://odbc.linuxbox.com/ public domain
- */
-/**
- * ODBC Socket Server class
- *
- * @package moodlecore
- * @copyright Copyright (c) 1999 Team FXML
- * @license http://odbc.linuxbox.com/ public domain
- */
-class ODBCSocketServer {
-
-   /**
-    * Name of the host to connect to
-    * @var string $sHostName 
-    */
-    var $sHostName;
-   /**
-    * Port to connect to
-    * @var int $nPort 
-    */
-    var $nPort;
-   /**
-    * Connection string to use
-    * @var string $sConnectionString 
-    */
-    var $sConnectionString;
-
-    // 
-    /** 
-     * Function to parse the SQL
-     *
-     * @param string $sSQL The SQL statement to parse
-     * @return string
-     */
-    function ExecSQL($sSQL) {
-
-        $fToOpen = fsockopen($this->sHostName, $this->nPort, &$errno, &$errstr, 30);
-        if (!$fToOpen)
-        {
-            //contruct error string to return
-            $sReturn = "<?xml version=\"1.0\"?>\r\n<result state=\"failure\">\r\n<error>$errstr</error>\r\n</result>\r\n";
-        }
-        else
-        {
-            //construct XML to send
-            //search and replace HTML chars in SQL first
-            $sSQL = HTMLSpecialChars($sSQL);
-            $sSend = "<?xml version=\"1.0\"?>\r\n<request>\r\n<connectionstring>$this->sConnectionString</connectionstring>\r\n<sql>$sSQL</sql>\r\n</request>\r\n";
-            //write request
-            fputs($fToOpen, $sSend);
-            //now read response
-            while (!feof($fToOpen))
-            {
-                $sReturn = $sReturn . fgets($fToOpen, 128);
-            }
-            fclose($fToOpen);
-        }
-        return $sReturn;
-    }
-}//class
-?>
index e2faeef..5e7587b 100644 (file)
@@ -675,6 +675,9 @@ if (isset($_SERVER['PHP_SELF'])) {
     unset($phppos);
 }
 
+// initialise ME's - this must be done BEFORE starting of session!
+initialise_fullme();
+
 // init session prevention flag - this is defined on pages that do not want session
 if (CLI_SCRIPT) {
     // no sessions in CLI scripts possible
@@ -697,10 +700,6 @@ session_get_instance();
 $SESSION = &$_SESSION['SESSION'];
 $USER    = &$_SESSION['USER'];
 
-// initialise ME's
-// This must presently come AFTER $USER has been set up.
-initialise_fullme();
-
 // Late profiling, only happening if early one wasn't started
 if (!empty($CFG->profilingenabled)) {
     require_once($CFG->libdir . '/xhprof/xhprof_moodle.php');
index 9b300c2..f06f6b5 100644 (file)
@@ -661,7 +661,7 @@ function initialise_cfg() {
  * setup.php.
  */
 function initialise_fullme() {
-    global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
+    global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT, $USER;
 
     // Detect common config error.
     if (substr($CFG->wwwroot, -1) == '/') {
@@ -715,6 +715,11 @@ function initialise_fullme() {
             if (!defined('NO_MOODLE_COOKIES')) {
                 define('NO_MOODLE_COOKIES', true);
             }
+            if (!isset($USER->id)) {
+                // MDL-27899 workaround
+                $USER = new stdClass();
+                $USER->id = 0;
+            }
             redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
         }
     }
diff --git a/lib/swfobject/swfobject.js b/lib/swfobject/swfobject.js
deleted file mode 100644 (file)
index 17481e4..0000000
+++ /dev/null
@@ -1,784 +0,0 @@
-//one change has been done related to http://code.google.com/p/swfobject/issues/detail?id=332
-//we added lines: 204, 205, 207, 208, 209 (try-catch)
-/*!    SWFObject v2.2 <http://code.google.com/p/swfobject/>
-       is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
-*/
-
-var swfobject = function() {
-
-       var UNDEF = "undefined",
-               OBJECT = "object",
-               SHOCKWAVE_FLASH = "Shockwave Flash",
-               SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
-               FLASH_MIME_TYPE = "application/x-shockwave-flash",
-               EXPRESS_INSTALL_ID = "SWFObjectExprInst",
-               ON_READY_STATE_CHANGE = "onreadystatechange",
-
-               win = window,
-               doc = document,
-               nav = navigator,
-
-               plugin = false,
-               domLoadFnArr = [main],
-               regObjArr = [],
-               objIdArr = [],
-               listenersArr = [],
-               storedAltContent,
-               storedAltContentId,
-               storedCallbackFn,
-               storedCallbackObj,
-               isDomLoaded = false,
-               isExpressInstallActive = false,
-               dynamicStylesheet,
-               dynamicStylesheetMedia,
-               autoHideShow = true,
-
-       /* Centralized function for browser feature detection
-               - User agent string detection is only used when no good alternative is possible
-               - Is executed directly for optimal performance
-       */
-       ua = function() {
-               var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
-                       u = nav.userAgent.toLowerCase(),
-                       p = nav.platform.toLowerCase(),
-                       windows = p ? /win/.test(p) : /win/.test(u),
-                       mac = p ? /mac/.test(p) : /mac/.test(u),
-                       webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
-                       ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html
-                       playerVersion = [0,0,0],
-                       d = null;
-               if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
-                       d = nav.plugins[SHOCKWAVE_FLASH].description;
-                       if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
-                               plugin = true;
-                               ie = false; // cascaded feature detection for Internet Explorer
-                               d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
-                               playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
-                               playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
-                               playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0;
-                       }
-               }
-               else if (typeof win.ActiveXObject != UNDEF) {
-                       try {
-                               var a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
-                               if (a) { // a will return null when ActiveX is disabled
-                                       d = a.GetVariable("$version");
-                                       if (d) {
-                                               ie = true; // cascaded feature detection for Internet Explorer
-                                               d = d.split(" ")[1].split(",");
-                                               playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
-                                       }
-                               }
-                       }
-                       catch(e) {}
-               }
-               return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac };
-       }(),
-
-       /* Cross-browser onDomLoad
-               - Will fire an event as soon as the DOM of a web page is loaded
-               - Internet Explorer workaround based on Diego Perini's solution: http://javascript.nwbox.com/IEContentLoaded/
-               - Regular onload serves as fallback
-       */
-       onDomLoad = function() {
-               if (!ua.w3) { return; }
-               if ((typeof doc.readyState != UNDEF && doc.readyState == "complete") || (typeof doc.readyState == UNDEF && (doc.getElementsByTagName("body")[0] || doc.body))) { // function is fired after onload, e.g. when script is inserted dynamically
-                       callDomLoadFunctions();
-               }
-               if (!isDomLoaded) {
-                       if (typeof doc.addEventListener != UNDEF) {
-                               doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, false);
-                       }
-                       if (ua.ie && ua.win) {
-                               doc.attachEvent(ON_READY_STATE_CHANGE, function() {
-                                       if (doc.readyState == "complete") {
-                                               doc.detachEvent(ON_READY_STATE_CHANGE, arguments.callee);
-                                               callDomLoadFunctions();
-                                       }
-                               });
-                               if (win == top) { // if not inside an iframe
-                                       (function(){
-                                               if (isDomLoaded) { return; }
-                                               try {
-                                                       doc.documentElement.doScroll("left");
-                                               }
-                                               catch(e) {
-                                                       setTimeout(arguments.callee, 0);
-                                                       return;
-                                               }
-                                               callDomLoadFunctions();
-                                       })();
-                               }
-                       }
-                       if (ua.wk) {
-                               (function(){
-                                       if (isDomLoaded) { return; }
-                                       if (!/loaded|complete/.test(doc.readyState)) {
-                                               setTimeout(arguments.callee, 0);
-                                               return;
-                                       }
-                                       callDomLoadFunctions();
-                               })();
-                       }
-                       addLoadEvent(callDomLoadFunctions);
-               }
-       }();
-
-       function callDomLoadFunctions() {
-               if (isDomLoaded) { return; }
-               try { // test if we can really add/remove elements to/from the DOM; we don't want to fire it too early
-                       var t = doc.getElementsByTagName("body")[0].appendChild(createElement("span"));
-                       t.parentNode.removeChild(t);
-               }
-               catch (e) { return; }
-               isDomLoaded = true;
-               var dl = domLoadFnArr.length;
-               for (var i = 0; i < dl; i++) {
-                       domLoadFnArr[i]();
-               }
-       }
-
-       function addDomLoadEvent(fn) {
-               if (isDomLoaded) {
-                       fn();
-               }
-               else {
-                       domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
-               }
-       }
-
-       /* Cross-browser onload
-               - Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
-               - Will fire an event as soon as a web page including all of its assets are loaded
-        */
-       function addLoadEvent(fn) {
-               if (typeof win.addEventListener != UNDEF) {
-                       win.addEventListener("load", fn, false);
-               }
-               else if (typeof doc.addEventListener != UNDEF) {
-                       doc.addEventListener("load", fn, false);
-               }
-               else if (typeof win.attachEvent != UNDEF) {
-                       addListener(win, "onload", fn);
-               }
-               else if (typeof win.onload == "function") {
-                       var fnOld = win.onload;
-                       win.onload = function() {
-                               fnOld();
-                               fn();
-                       };
-               }
-               else {
-                       win.onload = fn;
-               }
-       }
-
-       /* Main function
-               - Will preferably execute onDomLoad, otherwise onload (as a fallback)
-       */
-       function main() {
-               if (plugin) {
-                       testPlayerVersion();
-               }
-               else {
-                       matchVersions();
-               }
-       }
-
-       /* Detect the Flash Player version for non-Internet Explorer browsers
-               - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description:
-                 a. Both release and build numbers can be detected
-                 b. Avoid wrong descriptions by corrupt installers provided by Adobe
-                 c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports
-               - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available
-       */
-       function testPlayerVersion() {
-               var b = doc.getElementsByTagName("body")[0];
-               var o = createElement(OBJECT);
-               o.setAttribute("type", FLASH_MIME_TYPE);
-               var t = b.appendChild(o);
-               if (t) {
-                       var counter = 0;
-                       (function(){
-                               if (typeof t.GetVariable != UNDEF) {
-                                    try
-                                    {
-                                       var d = t.GetVariable("$version");
-                                    } catch(err) {
-                                         //Handle errors here
-                                    }
-                                       if (d) {
-                                               d = d.split(" ")[1].split(",");
-                                               ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
-                                       }
-                               }
-                               else if (counter < 10) {
-                                       counter++;
-                                       setTimeout(arguments.callee, 10);
-                                       return;
-                               }
-                               b.removeChild(o);
-                               t = null;
-                               matchVersions();
-                       })();
-               }
-               else {
-                       matchVersions();
-               }
-       }
-
-       /* Perform Flash Player and SWF version matching; static publishing only
-       */
-       function matchVersions() {
-               var rl = regObjArr.length;
-               if (rl > 0) {
-                       for (var i = 0; i < rl; i++) { // for each registered object element
-                               var id = regObjArr[i].id;
-                               var cb = regObjArr[i].callbackFn;
-                               var cbObj = {success:false, id:id};
-                               if (ua.pv[0] > 0) {
-                                       var obj = getElementById(id);
-                                       if (obj) {
-                                               if (hasPlayerVersion(regObjArr[i].swfVersion) && !(ua.wk && ua.wk < 312)) { // Flash Player version >= published SWF version: Houston, we have a match!
-                                                       setVisibility(id, true);
-                                                       if (cb) {
-                                                               cbObj.success = true;
-                                                               cbObj.ref = getObjectById(id);
-                                                               cb(cbObj);
-                                                       }
-                                               }
-                                               else if (regObjArr[i].expressInstall && canExpressInstall()) { // show the Adobe Express Install dialog if set by the web page author and if supported
-                                                       var att = {};
-                                                       att.data = regObjArr[i].expressInstall;
-                                                       att.width = obj.getAttribute("width") || "0";
-                                                       att.height = obj.getAttribute("height") || "0";
-                                                       if (obj.getAttribute("class")) { att.styleclass = obj.getAttribute("class"); }
-                                                       if (obj.getAttribute("align")) { att.align = obj.getAttribute("align"); }
-                                                       // parse HTML object param element's name-value pairs
-                                                       var par = {};
-                                                       var p = obj.getElementsByTagName("param");
-                                                       var pl = p.length;
-                                                       for (var j = 0; j < pl; j++) {
-                                                               if (p[j].getAttribute("name").toLowerCase() != "movie") {
-                                                                       par[p[j].getAttribute("name")] = p[j].getAttribute("value");
-                                                               }
-                                                       }
-                                                       showExpressInstall(att, par, id, cb);
-                                               }
-                                               else { // Flash Player and SWF version mismatch or an older Webkit engine that ignores the HTML object element's nested param elements: display alternative content instead of SWF
-                                                       displayAltContent(obj);
-                                                       if (cb) { cb(cbObj); }
-                                               }
-                                       }
-                               }
-                               else {  // if no Flash Player is installed or the fp version cannot be detected we let the HTML object element do its job (either show a SWF or alternative content)
-                                       setVisibility(id, true);
-                                       if (cb) {
-                                               var o = getObjectById(id); // test whether there is an HTML object element or not
-                                               if (o && typeof o.SetVariable != UNDEF) {
-                                                       cbObj.success = true;
-                                                       cbObj.ref = o;
-                                               }
-                                               cb(cbObj);
-                                       }
-                               }
-                       }
-               }
-       }
-
-       function getObjectById(objectIdStr) {
-               var r = null;
-               var o = getElementById(objectIdStr);
-               if (o && o.nodeName == "OBJECT") {
-                       if (typeof o.SetVariable != UNDEF) {
-                               r = o;
-                       }
-                       else {
-                               var n = o.getElementsByTagName(OBJECT)[0];
-                               if (n) {
-                                       r = n;
-                               }
-                       }
-               }
-               return r;
-       }
-
-       /* Requirements for Adobe Express Install
-               - only one instance can be active at a time
-               - fp 6.0.65 or higher
-               - Win/Mac OS only
-               - no Webkit engines older than version 312
-       */
-       function canExpressInstall() {
-               return !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac) && !(ua.wk && ua.wk < 312);
-       }
-
-       /* Show the Adobe Express Install dialog
-               - Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
-       */
-       function showExpressInstall(att, par, replaceElemIdStr, callbackFn) {
-               isExpressInstallActive = true;
-               storedCallbackFn = callbackFn || null;
-               storedCallbackObj = {success:false, id:replaceElemIdStr};
-               var obj = getElementById(replaceElemIdStr);
-               if (obj) {
-                       if (obj.nodeName == "OBJECT") { // static publishing
-                               storedAltContent = abstractAltContent(obj);
-                               storedAltContentId = null;
-                       }
-                       else { // dynamic publishing
-                               storedAltContent = obj;
-                               storedAltContentId = replaceElemIdStr;
-                       }
-                       att.id = EXPRESS_INSTALL_ID;
-                       if (typeof att.width == UNDEF || (!/%$/.test(att.width) && parseInt(att.width, 10) < 310)) { att.width = "310"; }
-                       if (typeof att.height == UNDEF || (!/%$/.test(att.height) && parseInt(att.height, 10) < 137)) { att.height = "137"; }
-                       doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
-                       var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
-                               fv = "MMredirectURL=" + win.location.toString().replace(/&/g,"%26") + "&MMplayerType=" + pt + "&MMdoctitle=" + doc.title;
-                       if (typeof par.flashvars != UNDEF) {
-                               par.flashvars += "&" + fv;
-                       }
-                       else {
-                               par.flashvars = fv;
-                       }
-                       // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
-                       // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
-                       if (ua.ie && ua.win && obj.readyState != 4) {
-                               var newObj = createElement("div");
-                               replaceElemIdStr += "SWFObjectNew";
-                               newObj.setAttribute("id", replaceElemIdStr);
-                               obj.parentNode.insertBefore(newObj, obj); // insert placeholder div that will be replaced by the object element that loads expressinstall.swf
-                               obj.style.display = "none";
-                               (function(){
-                                       if (obj.readyState == 4) {
-                                               obj.parentNode.removeChild(obj);
-                                       }
-                                       else {
-                                               setTimeout(arguments.callee, 10);
-                                       }
-                               })();
-                       }
-                       createSWF(att, par, replaceElemIdStr);
-               }
-       }
-
-       /* Functions to abstract and display alternative content
-       */
-       function displayAltContent(obj) {
-               if (ua.ie && ua.win && obj.readyState != 4) {
-                       // IE only: when a SWF is loading (AND: not available in cache) wait for the readyState of the object element to become 4 before removing it,
-                       // because you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
-                       var el = createElement("div");
-                       obj.parentNode.insertBefore(el, obj); // insert placeholder div that will be replaced by the alternative content
-                       el.parentNode.replaceChild(abstractAltContent(obj), el);
-                       obj.style.display = "none";
-                       (function(){
-                               if (obj.readyState == 4) {
-                                       obj.parentNode.removeChild(obj);
-                               }
-                               else {
-                                       setTimeout(arguments.callee, 10);
-                               }
-                       })();
-               }
-               else {
-                       obj.parentNode.replaceChild(abstractAltContent(obj), obj);
-               }
-       }
-
-       function abstractAltContent(obj) {
-               var ac = createElement("div");
-               if (ua.win && ua.ie) {
-                       ac.innerHTML = obj.innerHTML;
-               }
-               else {
-                       var nestedObj = obj.getElementsByTagName(OBJECT)[0];
-                       if (nestedObj) {
-                               var c = nestedObj.childNodes;
-                               if (c) {
-                                       var cl = c.length;
-                                       for (var i = 0; i < cl; i++) {
-                                               if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
-                                                       ac.appendChild(c[i].cloneNode(true));
-                                               }
-                                       }
-                               }
-                       }
-               }
-               return ac;
-       }
-
-       /* Cross-browser dynamic SWF creation
-       */
-       function createSWF(attObj, parObj, id) {
-               var r, el = getElementById(id);
-               if (ua.wk && ua.wk < 312) { return r; }
-               if (el) {
-                       if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
-                               attObj.id = id;
-                       }
-                       if (ua.ie && ua.win) { // Internet Explorer + the HTML object element + W3C DOM methods do not combine: fall back to outerHTML
-                               var att = "";
-                               for (var i in attObj) {
-                                       if (attObj[i] != Object.prototype[i]) { // filter out prototype additions from other potential libraries
-                                               if (i.toLowerCase() == "data") {
-                                                       parObj.movie = attObj[i];
-                                               }
-                                               else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
-                                                       att += ' class="' + attObj[i] + '"';
-                                               }
-                                               else if (i.toLowerCase() != "classid") {
-                                                       att += ' ' + i + '="' + attObj[i] + '"';
-                                               }
-                                       }
-                               }
-                               var par = "";
-                               for (var j in parObj) {
-                                       if (parObj[j] != Object.prototype[j]) { // filter out prototype additions from other potential libraries
-                                               par += '<param name="' + j + '" value="' + parObj[j] + '" />';
-                                       }
-                               }
-                               el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
-                               objIdArr[objIdArr.length] = attObj.id; // stored to fix object 'leaks' on unload (dynamic publishing only)
-                               r = getElementById(attObj.id);
-                       }
-                       else { // well-behaving browsers
-                               var o = createElement(OBJECT);
-                               o.setAttribute("type", FLASH_MIME_TYPE);
-                               for (var m in attObj) {
-                                       if (attObj[m] != Object.prototype[m]) { // filter out prototype additions from other potential libraries
-                                               if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
-                                                       o.setAttribute("class", attObj[m]);
-                                               }
-                                               else if (m.toLowerCase() != "classid") { // filter out IE specific attribute
-                                                       o.setAttribute(m, attObj[m]);
-                                               }
-                                       }
-                               }
-                               for (var n in parObj) {
-                                       if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // filter out prototype additions from other potential libraries and IE specific param element
-                                               createObjParam(o, n, parObj[n]);
-                                       }
-                               }
-                               el.parentNode.replaceChild(o, el);
-                               r = o;
-                       }
-               }
-               return r;
-       }
-
-       function createObjParam(el, pName, pValue) {
-               var p = createElement("param");
-               p.setAttribute("name", pName);
-               p.setAttribute("value", pValue);
-               el.appendChild(p);
-       }
-
-       /* Cross-browser SWF removal
-               - Especially needed to safely and completely remove a SWF in Internet Explorer
-       */
-       function removeSWF(id) {
-               var obj = getElementById(id);
-               if (obj && obj.nodeName == "OBJECT") {
-                       if (ua.ie && ua.win) {
-                               obj.style.display = "none";
-                               (function(){
-                                       if (obj.readyState == 4) {
-                                               removeObjectInIE(id);
-                                       }
-                                       else {
-                                               setTimeout(arguments.callee, 10);
-                                       }
-                               })();
-                       }
-                       else {
-                               obj.parentNode.removeChild(obj);
-                       }
-               }
-       }
-
-       function removeObjectInIE(id) {
-               var obj = getElementById(id);
-               if (obj) {
-                       for (var i in obj) {
-                               if (typeof obj[i] == "function") {
-                                       obj[i] = null;
-                               }
-                       }
-                       obj.parentNode.removeChild(obj);
-               }
-       }
-
-       /* Functions to optimize JavaScript compression
-       */
-       function getElementById(id) {
-               var el = null;
-               try {
-                       el = doc.getElementById(id);
-               }
-               catch (e) {}
-               return el;
-       }
-
-       function createElement(el) {
-               return doc.createElement(el);
-       }
-
-       /* Updated attachEvent function for Internet Explorer
-               - Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
-       */
-       function addListener(target, eventType, fn) {
-               target.attachEvent(eventType, fn);
-               listenersArr[listenersArr.length] = [target, eventType, fn];
-       }
-
-       /* Flash Player and SWF content version matching
-       */
-       function hasPlayerVersion(rv) {
-               var pv = ua.pv, v = rv.split(".");
-               v[0] = parseInt(v[0], 10);
-               v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
-               v[2] = parseInt(v[2], 10) || 0;
-               return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
-       }
-
-       /* Cross-browser dynamic CSS creation
-               - Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
-       */
-       function createCSS(sel, decl, media, newStyle) {
-               if (ua.ie && ua.mac) { return; }
-               var h = doc.getElementsByTagName("head")[0];
-               if (!h) { return; } // to also support badly authored HTML pages that lack a head element
-               var m = (media && typeof media == "string") ? media : "screen";
-               if (newStyle) {
-                       dynamicStylesheet = null;
-                       dynamicStylesheetMedia = null;
-               }
-               if (!dynamicStylesheet || dynamicStylesheetMedia != m) {
-                       // create dynamic stylesheet + get a global reference to it
-                       var s = createElement("style");
-                       s.setAttribute("type", "text/css");
-                       s.setAttribute("media", m);
-                       dynamicStylesheet = h.appendChild(s);
-                       if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
-                               dynamicStylesheet = doc.styleSheets[doc.styleSheets.length - 1];
-                       }
-                       dynamicStylesheetMedia = m;
-               }
-               // add style rule
-               if (ua.ie && ua.win) {
-                       if (dynamicStylesheet && typeof dynamicStylesheet.addRule == OBJECT) {
-                               dynamicStylesheet.addRule(sel, decl);
-                       }
-               }
-               else {
-                       if (dynamicStylesheet && typeof doc.createTextNode != UNDEF) {
-                               dynamicStylesheet.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
-                       }
-               }
-       }
-
-       function setVisibility(id, isVisible) {
-               if (!autoHideShow) { return; }
-               var v = isVisible ? "visible" : "hidden";
-               if (isDomLoaded && getElementById(id)) {
-                       getElementById(id).style.visibility = v;
-               }
-               else {
-                       createCSS("#" + id, "visibility:" + v);
-               }
-       }
-
-       /* Filter to avoid XSS attacks
-       */
-       function urlEncodeIfNecessary(s) {
-               var regex = /[\\\"<>\.;]/;
-               var hasBadChars = regex.exec(s) != null;
-               return hasBadChars && typeof encodeURIComponent != UNDEF ? encodeURIComponent(s) : s;
-       }
-
-       /* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
-       */
-       var cleanup = function() {
-               if (ua.ie && ua.win) {
-                       window.attachEvent("onunload", function() {
-                               // remove listeners to avoid memory leaks
-                               var ll = listenersArr.length;
-                               for (var i = 0; i < ll; i++) {
-                                       listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
-                               }
-                               // cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
-                               var il = objIdArr.length;
-                               for (var j = 0; j < il; j++) {
-                                       removeSWF(objIdArr[j]);
-                               }
-                               // cleanup library's main closures to avoid memory leaks
-                               for (var k in ua) {
-                                       ua[k] = null;
-                               }
-                               ua = null;
-                               for (var l in swfobject) {
-                                       swfobject[l] = null;
-                               }
-                               swfobject = null;
-                       });
-               }
-       }();
-
-       return {
-               /* Public API
-                       - Reference: http://code.google.com/p/swfobject/wiki/documentation
-               */
-               registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr, callbackFn) {
-                       if (ua.w3 && objectIdStr && swfVersionStr) {
-                               var regObj = {};
-                               regObj.id = objectIdStr;
-                               regObj.swfVersion = swfVersionStr;
-                               regObj.expressInstall = xiSwfUrlStr;
-                               regObj.callbackFn = callbackFn;
-                               regObjArr[regObjArr.length] = regObj;
-                               setVisibility(objectIdStr, false);
-                       }
-                       else if (callbackFn) {
-                               callbackFn({success:false, id:objectIdStr});
-                       }
-               },
-
-               getObjectById: function(objectIdStr) {
-                       if (ua.w3) {
-                               return getObjectById(objectIdStr);
-                       }
-               },
-
-               embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) {
-                       var callbackObj = {success:false, id:replaceElemIdStr};
-                       if (ua.w3 && !(ua.wk && ua.wk < 312) && swfUrlStr && replaceElemIdStr && widthStr && heightStr && swfVersionStr) {
-                               setVisibility(replaceElemIdStr, false);
-                               addDomLoadEvent(function() {
-                                       widthStr += ""; // auto-convert to string
-                                       heightStr += "";
-                                       var att = {};
-                                       if (attObj && typeof attObj === OBJECT) {
-                                               for (var i in attObj) { // copy object to avoid the use of references, because web authors often reuse attObj for multiple SWFs
-                                                       att[i] = attObj[i];
-                                               }
-                                       }
-                                       att.data = swfUrlStr;
-                                       att.width = widthStr;
-                                       att.height = heightStr;
-                                       var par = {};
-                                       if (parObj && typeof parObj === OBJECT) {
-                                               for (var j in parObj) { // copy object to avoid the use of references, because web authors often reuse parObj for multiple SWFs
-                                                       par[j] = parObj[j];
-                                               }
-                                       }
-                                       if (flashvarsObj && typeof flashvarsObj === OBJECT) {
-                                               for (var k in flashvarsObj) { // copy object to avoid the use of references, because web authors often reuse flashvarsObj for multiple SWFs
-                                                       if (typeof par.flashvars != UNDEF) {
-                                                               par.flashvars += "&" + k + "=" + flashvarsObj[k];
-                                                       }
-                                                       else {
-                                                               par.flashvars = k + "=" + flashvarsObj[k];
-                                                       }
-                                               }
-                                       }
-                                       if (hasPlayerVersion(swfVersionStr)) { // create SWF
-                                               var obj = createSWF(att, par, replaceElemIdStr);
-                                               if (att.id == replaceElemIdStr) {
-                                                       setVisibility(replaceElemIdStr, true);
-                                               }
-                                               callbackObj.success = true;
-                                               callbackObj.ref = obj;
-                                       }
-                                       else if (xiSwfUrlStr && canExpressInstall()) { // show Adobe Express Install
-                                               att.data = xiSwfUrlStr;
-                                               showExpressInstall(att, par, replaceElemIdStr, callbackFn);
-                                               return;
-                                       }
-                                       else { // show alternative content
-                                               setVisibility(replaceElemIdStr, true);
-                                       }
-                                       if (callbackFn) { callbackFn(callbackObj); }
-                               });
-                       }
-                       else if (callbackFn) { callbackFn(callbackObj); }
-               },
-
-               switchOffAutoHideShow: function() {
-                       autoHideShow = false;
-               },
-
-               ua: ua,
-
-               getFlashPlayerVersion: function() {
-                       return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
-               },
-
-               hasFlashPlayerVersion: hasPlayerVersion,
-
-               createSWF: function(attObj, parObj, replaceElemIdStr) {
-                       if (ua.w3) {
-                               return createSWF(attObj, parObj, replaceElemIdStr);
-                       }
-                       else {
-                               return undefined;
-                       }
-               },
-
-               showExpressInstall: function(att, par, replaceElemIdStr, callbackFn) {
-                       if (ua.w3 && canExpressInstall()) {
-                               showExpressInstall(att, par, replaceElemIdStr, callbackFn);
-                       }
-               },
-
-               removeSWF: function(objElemIdStr) {
-                       if (ua.w3) {
-                               removeSWF(objElemIdStr);
-                       }
-               },
-
-               createCSS: function(selStr, declStr, mediaStr, newStyleBoolean) {
-                       if (ua.w3) {
-                               createCSS(selStr, declStr, mediaStr, newStyleBoolean);
-                       }
-               },
-
-               addDomLoadEvent: addDomLoadEvent,
-
-               addLoadEvent: addLoadEvent,
-
-               getQueryParamValue: function(param) {
-                       var q = doc.location.search || doc.location.hash;
-                       if (q) {
-                               if (/\?/.test(q)) { q = q.split("?")[1]; } // strip question mark
-                               if (param == null) {
-                                       return urlEncodeIfNecessary(q);
-                               }
-                               var pairs = q.split("&");
-                               for (var i = 0; i < pairs.length; i++) {
-                                       if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
-                                               return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
-                                       }
-                               }
-                       }
-                       return "";
-               },
-
-               // For internal usage only
-               expressInstallCallback: function() {
-                       if (isExpressInstallActive) {
-                               var obj = getElementById(EXPRESS_INSTALL_ID);
-                               if (obj && storedAltContent) {
-                                       obj.parentNode.replaceChild(storedAltContent, obj);
-                                       if (storedAltContentId) {
-                                               setVisibility(storedAltContentId, true);
-                                               if (ua.ie && ua.win) { storedAltContent.style.display = "block"; }
-                                       }
-                                       if (storedCallbackFn) { storedCallbackFn(storedCallbackObj); }
-                               }
-                               isExpressInstallActive = false;
-                       }
-               }
-       };
-}();
index 0acdd8f..222203e 100644 (file)
@@ -60,7 +60,7 @@
     <location>PEAR_GeoIP</location>
     <name>GeoIP</name>
     <license>LGPL</license>
-    <version>1.0.0RC3</version>
+    <version>1.0.0</version>
     <licenseversion>2.1+</licenseversion>
   </library>
   <library>
     <location>typo3</location>
     <name>Typo3</name>
     <license>GPL</license>
-    <version>4.2.1</version>
+    <version>4.5.0</version>
     <licenseversion>2.0+</licenseversion>
   </library>
   <library>
     <version></version>
     <licenseversion>2.0+</licenseversion>
   </library>
-  <library>
-    <location>base32.php</location>
-    <name>Base32 Library</name>
-    <license>GPL/PHP</license>
-    <version></version>
-    <licenseversion>2.0+/2.0.2</licenseversion>
-  </library>
-  <library>
-    <location>odbc.php</location>
-    <name>ODBC server/client</name>
-    <license>Public Domain</license>
-    <version></version>
-    <licenseversion></licenseversion>
-  </library>
   <library>
     <location>html2text.php</location>
     <name>HTML2Text</name>
index 7885d63..0bcbfe2 100644 (file)
@@ -1,32 +1,32 @@
 <?php
 /***************************************************************
-*  Copyright notice
-*
-*  (c) 2003-2009 Kasper Skaarhoj (kasperYYYY@typo3.com)
-*  All rights reserved
-*
-*  This script is part of the Typo3 project. The Typo3 project 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.
-*
-*  The GNU General Public License can be found at
-*  http://www.gnu.org/copyleft/gpl.html.
-*
-*  This script 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.
-*
-*  This copyright notice MUST APPEAR in all copies of the script!
-***************************************************************/
+ *  Copyright notice
+ *
+ *  (c) 2003-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
+ *  All rights reserved
+ *
+ *  This script is part of the Typo3 project. The Typo3 project 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.
+ *
+ *  The GNU General Public License can be found at
+ *  http://www.gnu.org/copyleft/gpl.html.
+ *
+ *  This script 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.
+ *
+ *  This copyright notice MUST APPEAR in all copies of the script!
+ ***************************************************************/
 /**
  * Class for conversion between charsets.
  *
- * Id: class.t3lib_cs.php 5844 2009-08-30 10:02:57Z rupi $
+ * $Id$
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  * @author     Martin Kutschker <martin.t.kutschker@blackbox.net>
  */
 /**
  *
  *
  *  136: class t3lib_cs
- *  488:     function parse_charset($charset)
- *  507:     function get_locale_charset($locale)
+ *  488:        function parse_charset($charset)
+ *  507:        function get_locale_charset($locale)
  *
- *              SECTION: Charset Conversion functions
- *  560:     function conv($str,$fromCS,$toCS,$useEntityForNoChar=0)
- *  600:     function convArray(&$array,$fromCS,$toCS,$useEntityForNoChar=0)
- *  617:     function utf8_encode($str,$charset)
- *  663:     function utf8_decode($str,$charset,$useEntityForNoChar=0)
- *  706:     function utf8_to_entities($str)
- *  739:     function entities_to_utf8($str,$alsoStdHtmlEnt=0)
- *  773:     function utf8_to_numberarray($str,$convEntities=0,$retChar=0)
- *  823:     function UnumberToChar($cbyte)
- *  868:     function utf8CharToUnumber($str,$hex=0)
+ *                       SECTION: Charset Conversion functions
+ *  560:        function conv($str,$fromCS,$toCS,$useEntityForNoChar=0)
+ *  600:        function convArray(&$array,$fromCS,$toCS,$useEntityForNoChar=0)
+ *  617:        function utf8_encode($str,$charset)
+ *  663:        function utf8_decode($str,$charset,$useEntityForNoChar=0)
+ *  706:        function utf8_to_entities($str)
+ *  739:        function entities_to_utf8($str,$alsoStdHtmlEnt=0)
+ *  773:        function utf8_to_numberarray($str,$convEntities=0,$retChar=0)
+ *  823:        function UnumberToChar($cbyte)
+ *  868:        function utf8CharToUnumber($str,$hex=0)
  *
- *              SECTION: Init functions
- *  911:     function initCharset($charset)
- *  973:     function initUnicodeData($mode=null)
- * 1198:     function initCaseFolding($charset)
- * 1260:     function initToASCII($charset)
+ *                       SECTION: Init functions
+ *  911:        function initCharset($charset)
+ *  973:        function initUnicodeData($mode=null)
+ * 1198:        function initCaseFolding($charset)
+ * 1260:        function initToASCII($charset)
  *
- *              SECTION: String operation functions
- * 1331:     function substr($charset,$string,$start,$len=null)
- * 1384:     function strlen($charset,$string)
- * 1414:     function crop($charset,$string,$len,$crop='')
- * 1467:     function strtrunc($charset,$string,$len)
- * 1501:     function conv_case($charset,$string,$case)
- * 1527:     function specCharsToASCII($charset,$string)
+ *                       SECTION: String operation functions
+ * 1331:        function substr($charset,$string,$start,$len=null)
+ * 1384:        function strlen($charset,$string)
+ * 1414:        function crop($charset,$string,$len,$crop='')
+ * 1467:        function strtrunc($charset,$string,$len)
+ * 1501:        function conv_case($charset,$string,$case)
+ * 1527:        function specCharsToASCII($charset,$string)
  *
- *              SECTION: Internal string operation functions
- * 1567:     function sb_char_mapping($str,$charset,$mode,$opt='')
+ *                       SECTION: Internal string operation functions
+ * 1567:        function sb_char_mapping($str,$charset,$mode,$opt='')
  *
- *              SECTION: Internal UTF-8 string operation functions
- * 1622:     function utf8_substr($str,$start,$len=null)
- * 1655:     function utf8_strlen($str)
- * 1676:     function utf8_strtrunc($str,$len)
- * 1698:     function utf8_strpos($haystack,$needle,$offset=0)
- * 1723:     function utf8_strrpos($haystack,$needle)
- * 1745:     function utf8_char2byte_pos($str,$pos)
- * 1786:     function utf8_byte2char_pos($str,$pos)
- * 1809:     function utf8_char_mapping($str,$mode,$opt='')
+ *                       SECTION: Internal UTF-8 string operation functions
+ * 1622:        function utf8_substr($str,$start,$len=null)
+ * 1655:        function utf8_strlen($str)
+ * 1676:        function utf8_strtrunc($str,$len)
+ * 1698:        function utf8_strpos($haystack,$needle,$offset=0)
+ * 1723:        function utf8_strrpos($haystack,$needle)
+ * 1745:        function utf8_char2byte_pos($str,$pos)
+ * 1786:        function utf8_byte2char_pos($str,$pos)
+ * 1809:        function utf8_char_mapping($str,$mode,$opt='')
  *
- *              SECTION: Internal EUC string operation functions
- * 1885:     function euc_strtrunc($str,$len,$charset)
- * 1914:     function euc_substr($str,$start,$charset,$len=null)
- * 1939:     function euc_strlen($str,$charset)
- * 1966:     function euc_char2byte_pos($str,$pos,$charset)
- * 2007:     function euc_char_mapping($str,$charset,$mode,$opt='')
+ *                       SECTION: Internal EUC string operation functions
+ * 1885:        function euc_strtrunc($str,$len,$charset)
+ * 1914:        function euc_substr($str,$start,$charset,$len=null)
+ * 1939:        function euc_strlen($str,$charset)
+ * 1966:        function euc_char2byte_pos($str,$pos,$charset)
+ * 2007:        function euc_char_mapping($str,$charset,$mode,$opt='')
  *
  * TOTAL FUNCTIONS: 35
  * (This index is automatically created/updated by the extension "extdeveval")
  */
 
 
-
-
-
-
-
-
 /**
  * Notes on UTF-8
  *
 /**
  * Class for conversion between charsets
  *
- * @author     Kasper Skaarhoj <kasperYYYY@typo3.com>
+ * @author     Kasper Skårhøj <kasperYYYY@typo3.com>
  * @author     Martin Kutschker <martin.t.kutschker@blackbox.net>
  * @package TYPO3
  * @subpackage t3lib
  */
 class t3lib_cs {
-       var $noCharByteVal=63;          // ASCII Value for chars with no equivalent.
+       var $noCharByteVal = 63; // ASCII Value for chars with no equivalent.
 
                // This is the array where parsed conversion tables are stored (cached)
-       var $parsedCharsets=array();
+       var $parsedCharsets = array();
 
                // An array where case folding data will be stored (cached)
-       var $caseFolding=array();
+       var $caseFolding = array();
 
                // An array where charset-to-ASCII mappings are stored (cached)
-       var $toASCII=array();
+       var $toASCII = array();
 
                // This tells the converter which charsets has two bytes per char:
-       var $twoByteSets=array(
-               'ucs-2'=>1,     // 2-byte Unicode
+       var $twoByteSets = array(
+               'ucs-2' => 1, // 2-byte Unicode
        );
 
                // This tells the converter which charsets has four bytes per char:
-       var $fourByteSets=array(
-               'ucs-4'=>1,     // 4-byte Unicode
-               'utf-32'=>1,    // 4-byte Unicode (limited to the 21-bits of UTF-16)
+       var $fourByteSets = array(
+               'ucs-4' => 1, // 4-byte Unicode
+               'utf-32' => 1, // 4-byte Unicode (limited to the 21-bits of UTF-16)
        );
 
                // This tells the converter which charsets use a scheme like the Extended Unix Code:
-       var $eucBasedSets=array(
-               'gb2312'=>1,            // Chinese, simplified.
-               'big5'=>1,              // Chinese, traditional.
-               'euc-kr'=>1,            // Korean
-               'shift_jis'=>1,         // Japanese - WARNING: Shift-JIS includes half-width katakana single-bytes characters above 0x80!
+       var $eucBasedSets = array(
+               'gb2312' => 1, // Chinese, simplified.
+               'big5' => 1, // Chinese, traditional.
+               'euc-kr' => 1, // Korean
+               'shift_jis' => 1, // Japanese - WARNING: Shift-JIS includes half-width katakana single-bytes characters above 0x80!
        );
 
                // see  http://developer.apple.com/documentation/macos8/TextIntlSvcs/TextEncodingConversionManager/TEC1.5/TEC.b0.html
                // http://czyborra.com/charsets/iso8859.html
-       var $synonyms=array(
+       var $synonyms = array(
                'us' => 'ascii',
-               'us-ascii'=> 'ascii',
+               'us-ascii' => 'ascii',
                'cp819' => 'iso-8859-1',
                'ibm819' => 'iso-8859-1',
                'iso-ir-100' => 'iso-8859-1',
@@ -252,114 +246,117 @@ class t3lib_cs {
        );
 
                // mapping of iso-639-1 language codes to script names
-       var $lang_to_script=array(
+       var $lang_to_script = array(
                        // iso-639-1 language codes, see http://www.loc.gov/standards/iso639-2/php/code_list.php
                'ar' => 'arabic',
-               'bg' => 'cyrillic',             // Bulgarian
-               'bs' => 'east_european',        // Bosnian
-               'cs' => 'east_european',        // Czech
-               'da' => 'west_european',        // Danish
-               'de' => 'west_european',        // German
-               'es' => 'west_european',        // Spanish
+               'bg' => 'cyrillic', // Bulgarian
+               'bs' => 'east_european', // Bosnian
+               'cs' => 'east_european', // Czech
+               'da' => 'west_european', // Danish
+               'de' => 'west_european', // German
+               'es' => 'west_european', // Spanish
                'et' => 'estonian',
-               'eo' => 'unicode',              // Esperanto
-               'eu' => 'west_european',        // Basque
-               'fa' => 'arabic',       // Persian
-               'fi' => 'west_european',        // Finish
-               'fo' => 'west_european',        // Faroese
-               'fr' => 'west_european',        // French
-               'ga' => 'west_european',        // Galician
-               'ge' => 'unicode',                      // Georgian
+               'eo' => 'unicode', // Esperanto
+               'eu' => 'west_european', // Basque
+               'fa' => 'arabic', // Persian
+               'fi' => 'west_european', // Finish
+               'fo' => 'west_european', // Faroese
+               'fr' => 'west_european', // French
+               'ga' => 'west_european', // Irish
+               'gl' => 'west_european', // Galician
                'gr' => 'greek',
-               'he' => 'hebrew',               // Hebrew (since 1998)
-               'hi' => 'unicode',              // Hindi
-               'hr' => 'east_european',        // Croatian
-               'hu' => 'east_european',        // Hungarian
-               'iw' => 'hebrew',               // Hebrew (til 1998)
-               'is' => 'west_european',        // Icelandic
-               'it' => 'west_european',        // Italian
+               'he' => 'hebrew', // Hebrew (since 1998)
+               'hi' => 'unicode', // Hindi
+               'hr' => 'east_european', // Croatian
+               'hu' => 'east_european', // Hungarian
+               'iw' => 'hebrew', // Hebrew (til 1998)
+               'is' => 'west_european', // Icelandic
+               'it' => 'west_european', // Italian
                'ja' => 'japanese',
-               'kl' => 'west_european',        // Greenlandic
+               'ka' => 'unicode', // Georgian
+               'kl' => 'west_european', // Greenlandic
+               'km' => 'unicode', // Khmer
                'ko' => 'korean',
                'lt' => 'lithuanian',
-               'lv' => 'west_european',        // Latvian/Lettish
-               'nl' => 'west_european',        // Dutch
-               'no' => 'west_european',        // Norwegian
-               'nb' => 'west_european',        // Norwegian Bokmal
-               'nn' => 'west_european',        // Norwegian Nynorsk
-               'pl' => 'east_european',        // Polish
-               'pt' => 'west_european',        // Portuguese
-               'ro' => 'east_european',        // Romanian
-               'ru' => 'cyrillic',             // Russian
-               'sk' => 'east_european',        // Slovak
-               'sl' => 'east_european',        // Slovenian
-               'sr' => 'cyrillic',             // Serbian
-               'sv' => 'west_european',        // Swedish
-               'sq' => 'albanian',             // Albanian
+               'lv' => 'west_european', // Latvian/Lettish
+               'nl' => 'west_european', // Dutch
+               'no' => 'west_european', // Norwegian
+               'nb' => 'west_european', // Norwegian Bokmal
+               'nn' => 'west_european', // Norwegian Nynorsk
+               'pl' => 'east_european', // Polish
+               'pt' => 'west_european', // Portuguese
+               'ro' => 'east_european', // Romanian
+               'ru' => 'cyrillic', // Russian
+               'sk' => 'east_european', // Slovak
+               'sl' => 'east_european', // Slovenian
+               'sr' => 'cyrillic', // Serbian
+               'sv' => 'west_european', // Swedish
+               'sq' => 'albanian', // Albanian
                'th' => 'thai',
-               'uk' => 'cyrillic',             // Ukranian
+               'uk' => 'cyrillic', // Ukranian
                'vi' => 'vietnamese',
                'zh' => 'chinese',
                        // MS language codes, see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_language_strings.asp
                        // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wceinternational5/html/wce50conLanguageIdentifiersandLocales.asp
                'ara' => 'arabic',
-               'bgr' => 'cyrillic',            // Bulgarian
-               'cat' => 'west_european',       // Catalan
+               'bgr' => 'cyrillic', // Bulgarian
+               'cat' => 'west_european', // Catalan
                'chs' => 'simpl_chinese',
                'cht' => 'trad_chinese',
-               'csy' => 'east_european',       // Czech
-               'dan' => 'west_european',       // Danisch
-               'deu' => 'west_european',       // German
-               'dea' => 'west_european',       // German (Austrian)
-               'des' => 'west_european',       // German (Swiss)
-               'ena' => 'west_european',       // English (Australian)
-               'enc' => 'west_european',       // English (Canadian)
-               'eng' => 'west_european',       // English
-               'enz' => 'west_european',       // English (New Zealand)
-               'enu' => 'west_european',       // English (United States)
-               'euq' => 'west_european',       // Basque
-               'fos' => 'west_european',       // Faroese
-               'far' => 'arabic',      // Persian
-               'fin' => 'west_european',       // Finish
-               'fra' => 'west_european',       // French
-               'frb' => 'west_european',       // French (Belgian)
-               'frc' => 'west_european',       // French (Canadian)
-               'frs' => 'west_european',       // French (Swiss)
-               'geo' => 'unicode',                     // Georgian
-               'glg' => 'west_european',       // Galician
+               'csy' => 'east_european', // Czech
+               'dan' => 'west_european', // Danisch
+               'deu' => 'west_european', // German
+               'dea' => 'west_european', // German (Austrian)
+               'des' => 'west_european', // German (Swiss)
+               'ena' => 'west_european', // English (Australian)
+               'enc' => 'west_european', // English (Canadian)
+               'eng' => 'west_european', // English
+               'enz' => 'west_european', // English (New Zealand)
+               'enu' => 'west_european', // English (United States)
+               'euq' => 'west_european', // Basque
+               'fos' => 'west_european', // Faroese
+               'far' => 'arabic', // Persian
+               'fin' => 'west_european', // Finish
+               'fra' => 'west_european', // French
+               'frb' => 'west_european', // French (Belgian)
+               'frc' => 'west_european', // French (Canadian)
+               'frs' => 'west_european', // French (Swiss)
+               'geo' => 'unicode', // Georgian
+               'glg' => 'west_european', // Galician
                'ell' => 'greek',
                'heb' => 'hebrew',
-               'hin' => 'unicode',     // Hindi
-               'hun' => 'east_european',       // Hungarian
-               'isl' => 'west_euorpean',       // Icelandic
-               'ita' => 'west_european',       // Italian
-               'its' => 'west_european',       // Italian (Swiss)
+               'hin' => 'unicode', // Hindi
+               'hun' => 'east_european', // Hungarian
+               'isl' => 'west_euorpean', // Icelandic
+               'ita' => 'west_european', // Italian
+               'its' => 'west_european', // Italian (Swiss)
                'jpn' => 'japanese',
+               'khm' => 'unicode', // Khmer
                'kor' => 'korean',
                'lth' => 'lithuanian',
-               'lvi' => 'west_european',       // Latvian/Lettish
-               'msl' => 'west_european',       // Malay
-               'nlb' => 'west_european',       // Dutch (Belgian)
-               'nld' => 'west_european',       // Dutch
-               'nor' => 'west_european',       // Norwegian (bokmal)
-               'non' => 'west_european',       // Norwegian (nynorsk)
-               'plk' => 'east_european',       // Polish
-               'ptg' => 'west_european',       // Portuguese
-               'ptb' => 'west_european',       // Portuguese (Brazil)
-               'rom' => 'east_european',       // Romanian
-               'rus' => 'cyrillic',            // Russian
-               'slv' => 'east_european',       // Slovenian
-               'sky' => 'east_european',       // Slovak
-               'srl' => 'east_european',       // Serbian (Latin)
-               'srb' => 'cyrillic',            // Serbian (Cyrillic)
-               'esp' => 'west_european',       // Spanish (trad. sort)
-               'esm' => 'west_european',       // Spanish (Mexican)
-               'esn' => 'west_european',       // Spanish (internat. sort)
-               'sve' => 'west_european',       // Swedish
-               'sqi' => 'albanian',            // Albanian
+               'lvi' => 'west_european', // Latvian/Lettish
+               'msl' => 'west_european', // Malay
+               'nlb' => 'west_european', // Dutch (Belgian)
+               'nld' => 'west_european', // Dutch
+               'nor' => 'west_european', // Norwegian (bokmal)
+               'non' => 'west_european', // Norwegian (nynorsk)
+               'plk' => 'east_european', // Polish
+               'ptg' => 'west_european', // Portuguese
+               'ptb' => 'west_european', // Portuguese (Brazil)
+               'rom' => 'east_european', // Romanian
+               'rus' => 'cyrillic', // Russian
+               'slv' => 'east_european', // Slovenian
+               'sky' => 'east_european', // Slovak
+               'srl' => 'east_european', // Serbian (Latin)
+               'srb' => 'cyrillic', // Serbian (Cyrillic)
+               'esp' => 'west_european', // Spanish (trad. sort)
+               'esm' => 'west_european', // Spanish (Mexican)
+               'esn' => 'west_european', // Spanish (internat. sort)
+               'sve' => 'west_european', // Swedish
+               'sqi' => 'albanian', // Albanian
                'tha' => 'thai',
                'trk' => 'turkish',
-               'ukr' => 'cyrillic',    // Ukrainian
+               'ukr' => 'cyrillic', // Ukrainian
                        // English language names
                'albanian' => 'albanian',
                'arabic' => 'arabic',
@@ -388,6 +385,7 @@ class t3lib_cs {
                'hungarian' => 'east_european',
                'icelandic' => 'west_european',
                'italian' => 'west_european',
+               'khmer' => 'unicode',
                'latvian' => 'west_european',
                'lettish' => 'west_european',
                'lithuanian' => 'lithuanian',
@@ -409,7 +407,7 @@ class t3lib_cs {
        );
 
                // mapping of language (family) names to charsets on Unix
-       var $script_to_charset_unix=array(
+       var $script_to_charset_unix = array(
                'west_european' => 'iso-8859-1',
                'estonian' => 'iso-8859-1',
                'east_european' => 'iso-8859-2',
@@ -432,7 +430,7 @@ class t3lib_cs {
        );
 
                // mapping of language (family) names to charsets on Windows
-       var $script_to_charset_windows=array(
+       var $script_to_charset_windows = array(
                'east_european' => 'windows-1250',
                'cyrillic' => 'windows-1251',
                'west_european' => 'windows-1252',
@@ -455,7 +453,7 @@ class t3lib_cs {
        );
 
                // mapping of locale names to charsets
-       var $locale_to_charset=array(
+       var $locale_to_charset = array(
                'japanese.euc' => 'euc-jp',
                'ja_jp.ujis' => 'euc-jp',
                'korean.euc' => 'euc-kr',
@@ -516,6 +514,8 @@ class t3lib_cs {
                'sq' => 'utf-8',
                'ge' => 'utf-8',
                'ga' => '',
+               'km' => 'utf-8',
+               'qc' => '',
        );
 
                // TYPO3 specific: Array with the iso names used for each system language in TYPO3:
@@ -534,7 +534,10 @@ class t3lib_cs {
                'kr' => 'ko',
                'ua' => 'uk',
                'jp' => 'ja',
+               'qc' => 'fr_CA',
                'vn' => 'vi',
+               'ge' => 'ka',
+               'ga' => 'gl',
        );
 
        /**
@@ -544,9 +547,11 @@ class t3lib_cs {
         * @return      string          Normalized charset
         * @author      Martin Kutschker <martin.t.kutschker@blackbox.net>
         */
-       function parse_charset($charset)        {
+       function parse_charset($charset) {
                $charset = trim(strtolower($charset));
-               if (isset($this->synonyms[$charset]))   $charset = $this->synonyms[$charset];
+               if (isset($this->synonyms[$charset])) {
+                       $charset = $this->synonyms[$charset];
+               }
 
                return $charset;
        }
@@ -554,36 +559,44 @@ class t3lib_cs {
        /**
         * Get the charset of a locale.
         *
-        * ln            language
-        * ln_CN         language / country
-        * ln_CN.cs      language / country / charset
+        * ln                   language
+        * ln_CN                 language / country
+        * ln_CN.cs       language / country / charset
         * ln_CN.cs@mod  language / country / charset / modifier
         *
         * @param       string          Locale string
         * @return      string          Charset resolved for locale string
         * @author      Martin Kutschker <martin.t.kutschker@blackbox.net>
         */
-       function get_locale_charset($locale)    {
+       function get_locale_charset($locale) {
                $locale = strtolower($locale);
 
                        // exact locale specific charset?
-               if (isset($this->locale_to_charset[$locale]))   return $this->locale_to_charset[$locale];
+               if (isset($this->locale_to_charset[$locale])) {
+                       return $this->locale_to_charset[$locale];
+               }
 
                        // get modifier
-               list($locale,$modifier) = explode('@',$locale);
+               list($locale, $modifier) = explode('@', $locale);
 
                        // locale contains charset: use it
-               list($locale,$charset) = explode('.',$locale);
-               if ($charset)   return $this->parse_charset($charset);
+               list($locale, $charset) = explode('.', $locale);
+               if ($charset) {
+                       return $this->parse_charset($charset);
+               }
 
                        // modifier is 'euro' (after charset check, because of xx.utf-8@euro)
-               if ($modifier == 'euro')        return 'iso-8859-15';
+               if ($modifier == 'euro') {
+                       return 'iso-8859-15';
+               }
 
                        // get language
-               list($language,$country) = explode('_',$locale);
-               if (isset($this->lang_to_script[$language]))    $script = $this->lang_to_script[$language];
+               list($language, $country) = explode('_', $locale);
+               if (isset($this->lang_to_script[$language])) {
+                       $script = $this->lang_to_script[$language];
+               }
 
-               if (TYPO3_OS == 'WIN')  {
+               if (TYPO3_OS == 'WIN') {
                        $cs = $this->script_to_charset_windows[$script] ? $this->script_to_charset_windows[$script] : 'windows-1252';
                } else {
                        $cs = $this->script_to_charset_unix[$script] ? $this->script_to_charset_unix[$script] : 'iso-8859-1';
@@ -593,13 +606,6 @@ class t3lib_cs {
        }
 
 
-
-
-
-
-
-
-
        /********************************************
         *
         * Charset Conversion functions
@@ -616,37 +622,49 @@ class t3lib_cs {
         * @return      string          Converted string
         * @see convArray()
         */
-       function conv($str,$fromCS,$toCS,$useEntityForNoChar=0) {
-               if ($fromCS==$toCS)     return $str;
+       function conv($str, $fromCS, $toCS, $useEntityForNoChar = 0) {
+               if ($fromCS == $toCS) {
+                       return $str;
+               }
 
                        // PHP-libs don't support fallback to SGML entities, but UTF-8 handles everything
-               if ($toCS=='utf-8' || !$useEntityForNoChar)     {
-                       switch($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod'])       {
-                       case 'mbstring':
-                               $conv_str = mb_convert_encoding($str,$toCS,$fromCS);
-                               if (false !== $conv_str)        return $conv_str; // returns false for unsupported charsets
-                               break;
+               if ($toCS == 'utf-8' || !$useEntityForNoChar) {
+                       switch ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_convMethod']) {
+                               case 'mbstring':
+                                       $conv_str = mb_convert_encoding($str, $toCS, $fromCS);
+                                       if (FALSE !== $conv_str) {
+                                               return $conv_str;
+                                       } // returns false for unsupported charsets
+                                       break;
 
-                       case 'iconv':
-                               $conv_str = iconv($fromCS,$toCS.'//TRANSLIT',$str);
-                               if (false !== $conv_str)        return $conv_str;
-                               break;
+                               case 'iconv':
+                                       $conv_str = iconv($fromCS, $toCS . '//TRANSLIT', $str);
+                                       if (FALSE !== $conv_str) {
+                                               return $conv_str;
+                                       }
+                                       break;
 
-                       case 'recode':
-                               $conv_str = recode_string($fromCS.'..'.$toCS,$str);
-                               if (false !== $conv_str)        return $conv_str;
-                               break;
+                               case 'recode':
+                                       $conv_str = recode_string($fromCS . '..' . $toCS, $str);
+                                       if (FALSE !== $conv_str) {
+                                               return $conv_str;
+                                       }
+                                       break;
                        }
                        // fallback to TYPO3 conversion
                }
 
-               if ($fromCS!='utf-8')   $str=$this->utf8_encode($str,$fromCS);
-               if ($toCS!='utf-8')     $str=$this->utf8_decode($str,$toCS,$useEntityForNoChar);
+               if ($fromCS != 'utf-8') {
+                       $str = $this->utf8_encode($str, $fromCS);
+               }
+               if ($toCS != 'utf-8') {
+                       $str = $this->utf8_decode($str, $toCS, $useEntityForNoChar);
+               }
                return $str;
        }
 
        /**
-        * Convert all elements in ARRAY from one charset to another charset.
+        * Convert all elements in ARRAY with type string from one charset to another charset.
         * NOTICE: Array is passed by reference!
         *
         * @param       string          Input array, possibly multidimensional
@@ -656,12 +674,12 @@ class t3lib_cs {
         * @return      void
         * @see conv()
         */
-       function convArray(&$array,$fromCS,$toCS,$useEntityForNoChar=0) {
-               foreach($array as $key => $value)       {
-                       if (is_array($array[$key]))     {
-                               $this->convArray($array[$key],$fromCS,$toCS,$useEntityForNoChar);
-                       } else {
-                               $array[$key] = $this->conv($array[$key],$fromCS,$toCS,$useEntityForNoChar);
+       function convArray(&$array, $fromCS, $toCS, $useEntityForNoChar = 0) {
+               foreach ($array as $key => $value) {
+                       if (is_array($array[$key])) {
+                               $this->convArray($array[$key], $fromCS, $toCS, $useEntityForNoChar);
+                       } elseif (is_string($array[$key])) {
+                               $array[$key] = $this->conv($array[$key], $fromCS, $toCS, $useEntityForNoChar);
                        }
                }
        }
@@ -673,39 +691,47 @@ class t3lib_cs {
         * @param       string          Charset, lowercase. Must be found in csconvtbl/ folder.
         * @return      string          Output string, converted to UTF-8
         */
-       function utf8_encode($str,$charset)     {
+       function utf8_encode($str, $charset) {
 
-               if ($charset === 'utf-8')       return $str;
+               if ($charset === 'utf-8') {
+                       return $str;
+               }
 
                        // Charset is case-insensitive.
-               if ($this->initCharset($charset))       {       // Parse conv. table if not already...
+               if ($this->initCharset($charset)) { // Parse conv. table if not already...
                        $strLen = strlen($str);
-                       $outStr='';
-
-                       for ($a=0;$a<$strLen;$a++)      {       // Traverse each char in string.
-                               $chr=substr($str,$a,1);
-                               $ord=ord($chr);
-                               if (isset($this->twoByteSets[$charset]))        {       // If the charset has two bytes per char
-                                       $ord2 = ord($str{$a+1});
-                                       $ord = $ord<<8 | $ord2; // assume big endian
-
-                                       if (isset($this->parsedCharsets[$charset]['local'][$ord]))      {       // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
-                                               $outStr.=$this->parsedCharsets[$charset]['local'][$ord];
-                                       } else $outStr.=chr($this->noCharByteVal);      // No char exists
+                       $outStr = '';
+
+                       for ($a = 0; $a < $strLen; $a++) { // Traverse each char in string.
+                               $chr = substr($str, $a, 1);
+                               $ord = ord($chr);
+                               if (isset($this->twoByteSets[$charset])) { // If the charset has two bytes per char
+                                       $ord2 = ord($str{$a + 1});
+                                       $ord = $ord << 8 | $ord2; // assume big endian
+
+                                       if (isset($this->parsedCharsets[$charset]['local'][$ord])) { // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
+                                               $outStr .= $this->parsedCharsets[$charset]['local'][$ord];
+                                       } else {
+                                               $outStr .= chr($this->noCharByteVal);
+                                       } // No char exists
                                        $a++;
-                               } elseif ($ord>127)     {       // If char has value over 127 it's a multibyte char in UTF-8
-                                       if (isset($this->eucBasedSets[$charset]))       {       // EUC uses two-bytes above 127; we get both and advance pointer and make $ord a 16bit int.
-                                               if ($charset != 'shift_jis' || ($ord < 0xA0 || $ord > 0xDF))    {       // Shift-JIS: chars between 160 and 223 are single byte
+                               } elseif ($ord > 127) { // If char has value over 127 it's a multibyte char in UTF-8
+                                       if (isset($this->eucBasedSets[$charset])) { // EUC uses two-bytes above 127; we get both and advance pointer and make $ord a 16bit int.
+                                               if ($charset != 'shift_jis' || ($ord < 0xA0 || $ord > 0xDF)) { // Shift-JIS: chars between 160 and 223 are single byte
                                                        $a++;
-                                                       $ord2=ord(substr($str,$a,1));
-                                                       $ord = $ord*256+$ord2;
+                                                       $ord2 = ord(substr($str, $a, 1));
+                                                       $ord = $ord * 256 + $ord2;
                                                }
                                        }
 
-                                       if (isset($this->parsedCharsets[$charset]['local'][$ord]))      {       // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
-                                               $outStr.= $this->parsedCharsets[$charset]['local'][$ord];
-                                       } else $outStr.= chr($this->noCharByteVal);     // No char exists
-                               } else $outStr.= $chr;  // ... otherwise it's just ASCII 0-127 and one byte. Transparent
+                                       if (isset($this->parsedCharsets[$charset]['local'][$ord])) { // If the local char-number was found in parsed conv. table then we use that, otherwise 127 (no char?)
+                                               $outStr .= $this->parsedCharsets[$charset]['local'][$ord];
+                                       } else {
+                                               $outStr .= chr($this->noCharByteVal);
+                                       } // No char exists
+                               } else {
+                                       $outStr .= $chr;
+                               } // ... otherwise it's just ASCII 0-127 and one byte. Transparent
                        }
                        return $outStr;
                }
@@ -719,42 +745,52 @@ class t3lib_cs {
         * @param       boolean         If set, then characters that are not available in the destination character set will be encoded as numeric entities
         * @return      string          Output string, converted to local charset
         */
-       function utf8_decode($str,$charset,$useEntityForNoChar=0)       {
+       function utf8_decode($str, $charset, $useEntityForNoChar = 0) {
 
                if ($charset === 'utf-8') {
                        return $str;
                }
 
                        // Charset is case-insensitive.
-               if ($this->initCharset($charset))       {       // Parse conv. table if not already...
+               if ($this->initCharset($charset)) { // Parse conv. table if not already...
                        $strLen = strlen($str);
-                       $outStr='';
-                       $buf='';
-                       for ($a=0,$i=0;$a<$strLen;$a++,$i++)    {       // Traverse each char in UTF-8 string.
-                               $chr=substr($str,$a,1);
-                               $ord=ord($chr);
-                               if ($ord>127)   {       // This means multibyte! (first byte!)
-                                       if ($ord & 64)  {       // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
-
-                                               $buf=$chr;      // Add first byte
-                                               for ($b=0;$b<8;$b++)    {       // for each byte in multibyte string...
-                                                       $ord = $ord << 1;       // Shift it left and ...
-                                                       if ($ord & 128) {       // ... and with 8th bit - if that is set, then there are still bytes in sequence.
-                                                               $a++;   // Increase pointer...
-                                                               $buf.=substr($str,$a,1);        // ... and add the next char.
-                                                       } else break;
+                       $outStr = '';
+                       $buf = '';
+                       for ($a = 0, $i = 0; $a < $strLen; $a++, $i++) { // Traverse each char in UTF-8 string.
+                               $chr = substr($str, $a, 1);
+                               $ord = ord($chr);
+                               if ($ord > 127) { // This means multibyte! (first byte!)
+                                       if ($ord & 64) { // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
+
+                                               $buf = $chr; // Add first byte
+                                               for ($b = 0; $b < 8; $b++) { // for each byte in multibyte string...
+                                                       $ord = $ord << 1; // Shift it left and ...
+                                                       if ($ord & 128) { // ... and with 8th bit - if that is set, then there are still bytes in sequence.
+                                                               $a++; // Increase pointer...
+                                                               $buf .= substr($str, $a, 1); // ... and add the next char.
+                                                       } else {
+                                                               break;
+                                                       }
                                                }
 
-                                               if (isset($this->parsedCharsets[$charset]['utf8'][$buf]))       {       // If the UTF-8 char-sequence is found then...
-                                                       $mByte = $this->parsedCharsets[$charset]['utf8'][$buf]; // The local number
-                                                       if ($mByte>255) {       // If the local number is greater than 255 we will need to split the byte (16bit word assumed) in two chars.
-                                                               $outStr.= chr(($mByte >> 8) & 255).chr($mByte & 255);
-                                                       } else $outStr.= chr($mByte);
-                                               } elseif ($useEntityForNoChar) {        // Create num entity:
-                                                       $outStr.='&#'.$this->utf8CharToUnumber($buf,1).';';
-                                               } else $outStr.=chr($this->noCharByteVal);      // No char exists
-                                       } else $outStr.=chr($this->noCharByteVal);      // No char exists (MIDDLE of MB sequence!)
-                               } else $outStr.=$chr;   // ... otherwise it's just ASCII 0-127 and one byte. Transparent
+                                               if (isset($this->parsedCharsets[$charset]['utf8'][$buf])) { // If the UTF-8 char-sequence is found then...
+                                                       $mByte = $this->parsedCharsets[$charset]['utf8'][$buf]; // The local number
+                                                       if ($mByte > 255) { // If the local number is greater than 255 we will need to split the byte (16bit word assumed) in two chars.
+                                                               $outStr .= chr(($mByte >> 8) & 255) . chr($mByte & 255);
+                                                       } else {
+                                                               $outStr .= chr($mByte);
+                                                       }
+                                               } elseif ($useEntityForNoChar) { // Create num entity:
+                                                       $outStr .= '&#' . $this->utf8CharToUnumber($buf, 1) . ';';
+                                               } else {
+                                                       $outStr .= chr($this->noCharByteVal);
+                                               } // No char exists
+                                       } else {
+                                               $outStr .= chr($this->noCharByteVal);
+                                       } // No char exists (MIDDLE of MB sequence!)
+                               } else {
+                                       $outStr .= $chr;
+                               } // ... otherwise it's just ASCII 0-127 and one byte. Transparent
                        }
                        return $outStr;
                }
@@ -766,27 +802,33 @@ class t3lib_cs {
         * @param       string          Input string
         * @return      string          Output string
         */
-       function utf8_to_entities($str) {
+       function utf8_to_entities($str) {
                $strLen = strlen($str);
-               $outStr='';
-               $buf='';
-               for ($a=0;$a<$strLen;$a++)      {       // Traverse each char in UTF-8 string.
-                       $chr=substr($str,$a,1);
-                       $ord=ord($chr);
-                       if ($ord>127)   {       // This means multibyte! (first byte!)
-                               if ($ord & 64)  {       // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
-                                       $buf=$chr;      // Add first byte
-                                       for ($b=0;$b<8;$b++)    {       // for each byte in multibyte string...
-                                               $ord = $ord << 1;       // Shift it left and ...
-                                               if ($ord & 128) {       // ... and with 8th bit - if that is set, then there are still bytes in sequence.
-                                                       $a++;   // Increase pointer...
-                                                       $buf.=substr($str,$a,1);        // ... and add the next char.
-                                               } else break;
+               $outStr = '';
+               $buf = '';
+               for ($a = 0; $a < $strLen; $a++) { // Traverse each char in UTF-8 string.
+                       $chr = substr($str, $a, 1);
+                       $ord = ord($chr);
+                       if ($ord > 127) { // This means multibyte! (first byte!)
+                               if ($ord & 64) { // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
+                                       $buf = $chr; // Add first byte
+                                       for ($b = 0; $b < 8; $b++) { // for each byte in multibyte string...
+                                               $ord = $ord << 1; // Shift it left and ...
+                                               if ($ord & 128) { // ... and with 8th bit - if that is set, then there are still bytes in sequence.
+                                                       $a++; // Increase pointer...
+                                                       $buf .= substr($str, $a, 1); // ... and add the next char.
+                                               } else {
+                                                       break;
+                                               }
                                        }
 
-                                       $outStr.='&#'.$this->utf8CharToUnumber($buf,1).';';
-                               } else $outStr.=chr($this->noCharByteVal);      // No char exists (MIDDLE of MB sequence!)
-                       } else $outStr.=$chr;   // ... otherwise it's just ASCII 0-127 and one byte. Transparent
+                                       $outStr .= '&#' . $this->utf8CharToUnumber($buf, 1) . ';';
+                               } else {
+                                       $outStr .= chr($this->noCharByteVal);
+                               } // No char exists (MIDDLE of MB sequence!)
+                       } else {
+                               $outStr .= $chr;
+                       } // ... otherwise it's just ASCII 0-127 and one byte. Transparent
                }
 
                return $outStr;
@@ -799,30 +841,30 @@ class t3lib_cs {
         * @param       boolean         If set, then all string-HTML entities (like &amp; or &pound; will be converted as well)
         * @return      string          Output string
         */
-       function entities_to_utf8($str,$alsoStdHtmlEnt=0)       {
-               if ($alsoStdHtmlEnt)    {
-                       $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES));             // Getting them in iso-8859-1 - but thats ok since this is observed below.
+       function entities_to_utf8($str, $alsoStdHtmlEnt = 0) {
+               if ($alsoStdHtmlEnt) {
+                       $trans_tbl = array_flip(get_html_translation_table(HTML_ENTITIES)); // Getting them in iso-8859-1 - but thats ok since this is observed below.
                }
 
                $token = md5(microtime());
                $parts = explode($token, preg_replace('/(&([#[:alnum:]]*);)/', $token . '${2}' . $token, $str));
-               foreach($parts as $k => $v)     {
-                       if ($k%2)       {
-                               if (substr($v,0,1)=='#')        {       // Dec or hex entities:
-                                       if (substr($v,1,1)=='x')        {
-                                               $parts[$k] = $this->UnumberToChar(hexdec(substr($v,2)));
+               foreach ($parts as $k => $v) {
+                       if ($k % 2) {
+                               if (substr($v, 0, 1) == '#') { // Dec or hex entities:
+                                       if (substr($v, 1, 1) == 'x') {
+                                               $parts[$k] = $this->UnumberToChar(hexdec(substr($v, 2)));
                                        } else {
-                                               $parts[$k] = $this->UnumberToChar(substr($v,1));
+                                               $parts[$k] = $this->UnumberToChar(substr($v, 1));
                                        }
-                               } elseif ($alsoStdHtmlEnt && $trans_tbl['&'.$v.';']) {  // Other entities:
-                                       $parts[$k] = $this->utf8_encode($trans_tbl['&'.$v.';'],'iso-8859-1');
-                               } else {        // No conversion:
-                                       $parts[$k] ='&'.$v.';';
+                               } elseif ($alsoStdHtmlEnt && $trans_tbl['&' . $v . ';']) { // Other entities:
+                                       $parts[$k] = $this->utf8_encode($trans_tbl['&' . $v . ';'], 'iso-8859-1');
+                               } else { // No conversion:
+                                       $parts[$k] = '&' . $v . ';';
                                }
                        }
                }
 
-               return implode('',$parts);
+               return implode('', $parts);
        }
 
        /**
@@ -833,32 +875,38 @@ class t3lib_cs {
         * @param       boolean         If set, then instead of integer numbers the real UTF-8 char is returned.
         * @return      array           Output array with the char numbers
         */
-       function utf8_to_numberarray($str,$convEntities=0,$retChar=0)   {
+       function utf8_to_numberarray($str, $convEntities = 0, $retChar = 0) {
                        // If entities must be registered as well...:
-               if ($convEntities)      {
-                       $str = $this->entities_to_utf8($str,1);
+               if ($convEntities) {
+                       $str = $this->entities_to_utf8($str, 1);
                }
                        // Do conversion:
                $strLen = strlen($str);
-               $outArr=array();
-               $buf='';
-               for ($a=0;$a<$strLen;$a++)      {       // Traverse each char in UTF-8 string.
-                       $chr=substr($str,$a,1);
-                       $ord=ord($chr);
-                       if ($ord>127)   {       // This means multibyte! (first byte!)
-                               if ($ord & 64)  {       // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
-                                       $buf=$chr;      // Add first byte
-                                       for ($b=0;$b<8;$b++)    {       // for each byte in multibyte string...
-                                               $ord = $ord << 1;       // Shift it left and ...
-                                               if ($ord & 128) {       // ... and with 8th bit - if that is set, then there are still bytes in sequence.
-                                                       $a++;   // Increase pointer...
-                                                       $buf.=substr($str,$a,1);        // ... and add the next char.
-                                               } else break;
+               $outArr = array();
+               $buf = '';
+               for ($a = 0; $a < $strLen; $a++) { // Traverse each char in UTF-8 string.
+                       $chr = substr($str, $a, 1);
+                       $ord = ord($chr);
+                       if ($ord > 127) { // This means multibyte! (first byte!)
+                               if ($ord & 64) { // Since the first byte must have the 7th bit set we check that. Otherwise we might be in the middle of a byte sequence.
+                                       $buf = $chr; // Add first byte
+                                       for ($b = 0; $b < 8; $b++) { // for each byte in multibyte string...
+                                               $ord = $ord << 1; // Shift it left and ...
+                                               if ($ord & 128) { // ... and with 8th bit - if that is set, then there are still bytes in sequence.
+                                                       $a++; // Increase pointer...
+                                                       $buf .= substr($str, $a, 1); // ... and add the next char.
+                                               } else {
+                                                       break;
+                                               }
                                        }
 
-                                       $outArr[]=$retChar?$buf:$this->utf8CharToUnumber($buf);
-                               } else $outArr[]=$retChar?chr($this->noCharByteVal):$this->noCharByteVal;       // No char exists (MIDDLE of MB sequence!)
-                       } else $outArr[]=$retChar?chr($ord):$ord;       // ... otherwise it's just ASCII 0-127 and one byte. Transparent
+                                       $outArr[] = $retChar ? $buf : $this->utf8CharToUnumber($buf);
+                               } else {
+                                       $outArr[] = $retChar ? chr($this->noCharByteVal) : $this->noCharByteVal;
+                               } // No char exists (MIDDLE of MB sequence!)
+                       } else {
+                               $outArr[] = $retChar ? chr($ord) : $ord;
+                       } // ... otherwise it's just ASCII 0-127 and one byte. Transparent
                }
 
                return $outArr;
@@ -872,49 +920,59 @@ class t3lib_cs {
         * The binary representation of the character's integer value is thus simply spread across the bytes and the number of high bits set in the lead byte announces the number of bytes in the multibyte sequence:
         *
         *  bytes | bits | representation
-        *      1 |    7 | 0vvvvvvv
-        *      2 |   11 | 110vvvvv 10vvvvvv
-        *      3 |   16 | 1110vvvv 10vvvvvv 10vvvvvv
-        *      4 |   21 | 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv
-        *      5 |   26 | 111110vv 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv
-        *      6 |   31 | 1111110v 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv
+        *        1 |   7 | 0vvvvvvv
+        *        2 |   11 | 110vvvvv 10vvvvvv
+        *        3 |   16 | 1110vvvv 10vvvvvv 10vvvvvv
+        *        4 |   21 | 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv
+        *        5 |   26 | 111110vv 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv
+        *        6 |   31 | 1111110v 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv 10vvvvvv
         *
         * @param       integer         UNICODE integer
         * @return      string          UTF-8 multibyte character string
         * @see utf8CharToUnumber()
         */
-       function UnumberToChar($cbyte)  {
-               $str='';
+       function UnumberToChar($cbyte) {
+               $str = '';
 
                if ($cbyte < 0x80) {
-                       $str.=chr($cbyte);
-               } else if ($cbyte < 0x800) {
-                       $str.=chr(0xC0 | ($cbyte >> 6));
-                       $str.=chr(0x80 | ($cbyte & 0x3F));
-               } else if ($cbyte < 0x10000) {
-                       $str.=chr(0xE0 | ($cbyte >> 12));
-                       $str.=chr(0x80 | (($cbyte >> 6) & 0x3F));
-                       $str.=chr(0x80 | ($cbyte & 0x3F));
-               } else if ($cbyte < 0x200000) {
-                       $str.=chr(0xF0 | ($cbyte >> 18));
-                       $str.=chr(0x80 | (($cbyte >> 12) & 0x3F));
-                       $str.=chr(0x80 | (($cbyte >> 6) & 0x3F));
-                       $str.=chr(0x80 | ($cbyte & 0x3F));
-               } else if ($cbyte < 0x4000000) {
-                       $str.=chr(0xF8 | ($cbyte >> 24));
-                       $str.=chr(0x80 | (($cbyte >> 18) & 0x3F));
-                       $str.=chr(0x80 | (($cbyte >> 12) & 0x3F));
-                       $str.=chr(0x80 | (($cbyte >> 6) & 0x3F));
-                       $str.=chr(0x80 | ($cbyte & 0x3F));
-               } else if ($cbyte < 0x80000000) {
-                       $str.=chr(0xFC | ($cbyte >> 30));
-                       $str.=chr(0x80 | (($cbyte >> 24) & 0x3F));
-                       $str.=chr(0x80 | (($cbyte >> 18) & 0x3F));
-                       $str.=chr(0x80 | (($cbyte >> 12) & 0x3F));
-                       $str.=chr(0x80 | (($cbyte >> 6) & 0x3F));
-                       $str.=chr(0x80 | ($cbyte & 0x3F));
-               } else { // Cannot express a 32-bit character in UTF-8
-                       $str .= chr($this->noCharByteVal);
+                       $str .= chr($cbyte);
+               } else {
+                       if ($cbyte < 0x800) {
+                               $str .= chr(0xC0 | ($cbyte >> 6));
+                               $str .= chr(0x80 | ($cbyte & 0x3F));
+                       } else {
+                               if ($cbyte < 0x10000) {
+                                       $str .= chr(0xE0 | ($cbyte >> 12));
+                                       $str .= chr(0x80 | (($cbyte >> 6) & 0x3F));
+                                       $str .= chr(0x80 | ($cbyte & 0x3F));
+                               } else {
+                                       if ($cbyte < 0x200000) {
+                                               $str .= chr(0xF0 | ($cbyte >> 18));
+                                               $str .= chr(0x80 | (($cbyte >> 12) & 0x3F));
+                                               $str .= chr(0x80 | (($cbyte >> 6) & 0x3F));
+                                               $str .= chr(0x80 | ($cbyte & 0x3F));
+                                       } else {
+                                               if ($cbyte < 0x4000000) {
+                                                       $str .= chr(0xF8 | ($cbyte >> 24));
+                                                       $str .= chr(0x80 | (($cbyte >> 18) & 0x3F));
+                                                       $str .= chr(0x80 | (($cbyte >> 12) & 0x3F));
+                                                       $str .= chr(0x80 | (($cbyte >> 6) & 0x3F));
+                                                       $str .= chr(0x80 | ($cbyte & 0x3F));
+                                               } else {
+                                                       if ($cbyte < 0x80000000) {
+                                                               $str .= chr(0xFC | ($cbyte >> 30));
+                                                               $str .= chr(0x80 | (($cbyte >> 24) & 0x3F));
+                                                               $str .= chr(0x80 | (($cbyte >> 18) & 0x3F));
+                                                               $str .= chr(0x80 | (($cbyte >> 12) & 0x3F));
+                                                               $str .= chr(0x80 | (($cbyte >> 6) & 0x3F));
+                                                               $str .= chr(0x80 | ($cbyte & 0x3F));
+                                                       } else { // Cannot express a 32-bit character in UTF-8
+                                                               $str .= chr($this->noCharByteVal);
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
                }
                return $str;
        }
@@ -928,33 +986,30 @@ class t3lib_cs {
         * @return      integer         UNICODE integer
         * @see UnumberToChar()
         */
-       function utf8CharToUnumber($str,$hex=0) {
-               $ord=ord(substr($str,0,1));     // First char
-
-               if (($ord & 192) == 192)        {       // This verifyes that it IS a multi byte string
-                       $binBuf='';
-                       for ($b=0;$b<8;$b++)    {       // for each byte in multibyte string...
-                               $ord = $ord << 1;       // Shift it left and ...
-                               if ($ord & 128) {       // ... and with 8th bit - if that is set, then there are still bytes in sequence.
-                                       $binBuf.=substr('00000000'.decbin(ord(substr($str,$b+1,1))),-6);
-                               } else break;
+       function utf8CharToUnumber($str, $hex = 0) {
+               $ord = ord(substr($str, 0, 1)); // First char
+
+               if (($ord & 192) == 192) { // This verifyes that it IS a multi byte string
+                       $binBuf = '';
+                       for ($b = 0; $b < 8; $b++) { // for each byte in multibyte string...
+                               $ord = $ord << 1; // Shift it left and ...
+                               if ($ord & 128) { // ... and with 8th bit - if that is set, then there are still bytes in sequence.
+                                       $binBuf .= substr('00000000' . decbin(ord(substr($str, $b + 1, 1))), -6);
+                               } else {
+                                       break;
+                               }
                        }
-                       $binBuf=substr('00000000'.decbin(ord(substr($str,0,1))),-(6-$b)).$binBuf;
+                       $binBuf = substr('00000000' . decbin(ord(substr($str, 0, 1))), -(6 - $b)) . $binBuf;
 
                        $int = bindec($binBuf);
-               } else $int = $ord;
+               } else {
+                       $int = $ord;
+               }
 
-               return $hex ? 'x'.dechex($int) : $int;
+               return $hex ? 'x' . dechex($int) : $int;
        }
 
 
-
-
-
-
-
-
-
        /********************************************
         *
         * Init functions
@@ -971,57 +1026,63 @@ class t3lib_cs {
         * @return      integer         Returns '1' if already loaded. Returns FALSE if charset conversion table was not found. Returns '2' if the charset conversion table was found and parsed.
         * @access private
         */
-       function initCharset($charset)  {
+       function initCharset($charset) {
                        // Only process if the charset is not yet loaded:
-               if (empty($this->parsedCharsets[$charset]) || !is_array($this->parsedCharsets[$charset]))       {
+               if (empty($this->parsedCharsets[$charset]) || !is_array($this->parsedCharsets[$charset])) {
 
                                // Conversion table filename:
-                       $charsetConvTableFile = PATH_t3lib.'csconvtbl/'.$charset.'.tbl';
+                       $charsetConvTableFile = PATH_t3lib . 'csconvtbl/' . $charset . '.tbl';
 
                                // If the conversion table is found:
-                       if ($charset && t3lib_div::validPathStr($charsetConvTableFile) && @is_file($charsetConvTableFile))      {
+                       if ($charset && t3lib_div::validPathStr($charsetConvTableFile) && @is_file($charsetConvTableFile)) {
                                        // Cache file for charsets:
                                        // Caching brought parsing time for gb2312 down from 2400 ms to 150 ms. For other charsets we are talking 11 ms down to zero.
-                               $cacheFile = t3lib_div::getFileAbsFileName('typo3temp/cs/charset_'.$charset.'.tbl');
-                               if ($cacheFile && @is_file($cacheFile)) {
-                                       $this->parsedCharsets[$charset]=unserialize(t3lib_div::getUrl($cacheFile));
+                               $cacheFile = t3lib_div::getFileAbsFileName('typo3temp/cs/charset_' . $charset . '.tbl');
+                               if ($cacheFile && @is_file($cacheFile)) {
+                                       $this->parsedCharsets[$charset] = unserialize(t3lib_div::getUrl($cacheFile));
                                } else {
                                                // Parse conversion table into lines:
-                                       $lines=t3lib_div::trimExplode(chr(10),t3lib_div::getUrl($charsetConvTableFile),1);
+                                       $lines = t3lib_div::trimExplode(LF, t3lib_div::getUrl($charsetConvTableFile), 1);
                                                // Initialize the internal variable holding the conv. table:
-                                       $this->parsedCharsets[$charset]=array('local'=>array(),'utf8'=>array());
+                                       $this->parsedCharsets[$charset] = array('local' => array(), 'utf8' => array());
                                                // traverse the lines:
-                                       $detectedType='';
-                                       foreach($lines as $value)       {
-                                               if (trim($value) && substr($value,0,1)!='#')    {       // Comment line or blanks are ignored.
+                                       $detectedType = '';
+                                       foreach ($lines as $value) {
+                                               if (trim($value) && substr($value, 0, 1) != '#') { // Comment line or blanks are ignored.
 
                                                                // Detect type if not done yet: (Done on first real line)
                                                                // The "whitespaced" type is on the syntax      "0x0A   0x000A  #LINE FEED"     while   "ms-token" is like              "B9 = U+00B9 : SUPERSCRIPT ONE"
-                                                       if (!$detectedType)             $detectedType = preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/',$value) ? 'whitespaced' : 'ms-token';
+                                                       if (!$detectedType) {
+                                                               $detectedType = preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/', $value) ? 'whitespaced' : 'ms-token';
+                                                       }
 
-                                                       if ($detectedType=='ms-token')  {
+                                                       if ($detectedType == 'ms-token') {
                                                                list($hexbyte, $utf8) = preg_split('/[=:]/', $value, 3);
-                                                       } elseif ($detectedType=='whitespaced') {
-                                                               $regA=array();
-                                                               preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/',$value,$regA);
+                                                       } elseif ($detectedType == 'whitespaced') {
+                                                               $regA = array();
+                                                               preg_match('/[[:space:]]*0x([[:alnum:]]*)[[:space:]]+0x([[:alnum:]]*)[[:space:]]+/', $value, $regA);
                                                                $hexbyte = $regA[1];
-                                                               $utf8 = 'U+'.$regA[2];
+                                                               $utf8 = 'U+' . $regA[2];
                                                        }
                                                        $decval = hexdec(trim($hexbyte));
-                                                       if ($decval>127)        {
-                                                               $utf8decval = hexdec(substr(trim($utf8),2));
-                                                               $this->parsedCharsets[$charset]['local'][$decval]=$this->UnumberToChar($utf8decval);
-                                                               $this->parsedCharsets[$charset]['utf8'][$this->parsedCharsets[$charset]['local'][$decval]]=$decval;
+                                                       if ($decval > 127) {
+                                                               $utf8decval = hexdec(substr(trim($utf8), 2));
+                                                               $this->parsedCharsets[$charset]['local'][$decval] = $this->UnumberToChar($utf8decval);
+                                                               $this->parsedCharsets[$charset]['utf8'][$this->parsedCharsets[$charset]['local'][$decval]] = $decval;
                                                        }
                                                }
                                        }
-                                       if ($cacheFile) {
-                                               t3lib_div::writeFileToTypo3tempDir($cacheFile,serialize($this->parsedCharsets[$charset]));
+                                       if ($cacheFile) {
+                                               t3lib_div::writeFileToTypo3tempDir($cacheFile, serialize($this->parsedCharsets[$charset]));
                                        }
                                }
                                return 2;
-                       } else return false;
-               } else return 1;
+                       } else {
+                               return FALSE;
+                       }
+               } else {
+                       return 1;
+               }
        }
 
        /**
@@ -1033,28 +1094,32 @@ class t3lib_cs {
         * @return      integer         Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
         * @access private
         */
-       function initUnicodeData($mode=null)    {
+       function initUnicodeData($mode = NULL) {
                        // cache files
                $cacheFileCase = t3lib_div::getFileAbsFileName('typo3temp/cs/cscase_utf-8.tbl');
                $cacheFileASCII = t3lib_div::getFileAbsFileName('typo3temp/cs/csascii_utf-8.tbl');
 
                        // Only process if the tables are not yet loaded
-               switch($mode)   {
+               switch ($mode) {
                        case 'case':
-                               if (is_array($this->caseFolding['utf-8']))      return 1;
+                               if (is_array($this->caseFolding['utf-8'])) {
+                                       return 1;
+                               }
 
                                        // Use cached version if possible
-                               if ($cacheFileCase && @is_file($cacheFileCase)) {
+                               if ($cacheFileCase && @is_file($cacheFileCase)) {
                                        $this->caseFolding['utf-8'] = unserialize(t3lib_div::getUrl($cacheFileCase));
                                        return 2;
                                }
                                break;
 
                        case 'ascii':
-                               if (is_array($this->toASCII['utf-8']))  return 1;
+                               if (is_array($this->toASCII['utf-8'])) {
+                                       return 1;
+                               }
 
                                        // Use cached version if possible
-                               if ($cacheFileASCII && @is_file($cacheFileASCII))       {
+                               if ($cacheFileASCII && @is_file($cacheFileASCII)) {
                                        $this->toASCII['utf-8'] = unserialize(t3lib_div::getUrl($cacheFileASCII));
                                        return 2;
                                }
@@ -1062,11 +1127,15 @@ class t3lib_cs {
                }
 
                        // process main Unicode data file
-               $unicodeDataFile = PATH_t3lib.'unidata/UnicodeData.txt';
-               if (!(t3lib_div::validPathStr($unicodeDataFile) && @is_file($unicodeDataFile))) return false;
+               $unicodeDataFile = PATH_t3lib . 'unidata/UnicodeData.txt';
+               if (!(t3lib_div::validPathStr($unicodeDataFile) && @is_file($unicodeDataFile))) {
+                       return FALSE;
+               }
 
-               $fh = fopen($unicodeDataFile,'rb');
-               if (!$fh)       return false;
+               $fh = fopen($unicodeDataFile, 'rb');
+               if (!$fh) {
+                       return FALSE;
+               }
 
                        // key = utf8 char (single codepoint), value = utf8 string (codepoint sequence)
                        // note: we use the UTF-8 characters here and not the Unicode numbers to avoid conversion roundtrip in utf8_strtolower/-upper)
@@ -1076,58 +1145,72 @@ class t3lib_cs {
                $utf8CaseFolding['toLower'] = array();
                $utf8CaseFolding['toTitle'] = array();
 
-               $decomposition = array();       // array of temp. decompositions
-               $mark = array();                // array of chars that are marks (eg. composing accents)
-               $number = array();              // array of chars that are numbers (eg. digits)
-               $omit = array();                // array of chars to be omitted (eg. Russian hard sign)
+               $decomposition = array(); // array of temp. decompositions
+               $mark = array(); // array of chars that are marks (eg. composing accents)
+               $number = array(); // array of chars that are numbers (eg. digits)
+               $omit = array(); // array of chars to be omitted (eg. Russian hard sign)
 
-               while (!feof($fh))      {
-                       $line = fgets($fh,4096);
+               while (!feof($fh)) {
+                       $line = fgets($fh, 4096);
                                // has a lot of info
-                       list($char,$name,$cat,,,$decomp,,,$num,,,,$upper,$lower,$title,) = explode(';', rtrim($line));
+                       list($char, $name, $cat, , , $decomp, , , $num, , , , $upper, $lower, $title,) = explode(';', rtrim($line));
 
                        $ord = hexdec($char);
-                       if ($ord > 0xFFFF)      break;  // only process the BMP
+                       if ($ord > 0xFFFF) {
+                               break;
+                       } // only process the BMP
 
                        $utf8_char = $this->UnumberToChar($ord);
 
-                       if ($upper)     $utf8CaseFolding['toUpper'][$utf8_char] = $this->UnumberToChar(hexdec($upper));
-                       if ($lower)     $utf8CaseFolding['toLower'][$utf8_char] = $this->UnumberToChar(hexdec($lower));
+                       if ($upper) {
+                               $utf8CaseFolding['toUpper'][$utf8_char] = $this->UnumberToChar(hexdec($upper));
+                       }
+                       if ($lower) {
+                               $utf8CaseFolding['toLower'][$utf8_char] = $this->UnumberToChar(hexdec($lower));
+                       }
                                // store "title" only when different from "upper" (only a few)
-                       if ($title && $title != $upper) $utf8CaseFolding['toTitle'][$utf8_char] = $this->UnumberToChar(hexdec($title));
+                       if ($title && $title != $upper) {
+                               $utf8CaseFolding['toTitle'][$utf8_char] = $this->UnumberToChar(hexdec($title));
+                       }
 
-                       switch ($cat{0})        {
-                               case 'M':       // mark (accent, umlaut, ...)
+                       switch ($cat{0}) {
+                               case 'M': // mark (accent, umlaut, ...)
                                        $mark["U+$char"] = 1;
                                        break;
 
-                               case 'N':       // numeric value
-                                       if ($ord > 0x80 && $num != '')  $number["U+$char"] = $num;
+                               case 'N': // numeric value
+                                       if ($ord > 0x80 && $num != '') {
+                                               $number["U+$char"] = $num;
+                                       }
                        }
 
                                // accented Latin letters without "official" decomposition
                        $match = array();
-                       if (preg_match('/^LATIN (SMALL|CAPITAL) LETTER ([A-Z]) WITH/',$name,$match) && !$decomp)        {
+                       if (preg_match('/^LATIN (SMALL|CAPITAL) LETTER ([A-Z]) WITH/', $name, $match) && !$decomp) {
                                $c = ord($match[2]);
-                               if ($match[1] == 'SMALL')       $c += 32;
+                               if ($match[1] == 'SMALL') {
+                                       $c += 32;
+                               }
 
                                $decomposition["U+$char"] = array(dechex($c));
                                continue;
                        }
 
                        $match = array();
-                       if (preg_match('/(<.*>)? *(.+)/',$decomp,$match))       {
-                               switch($match[1])       {
-                                       case '<circle>':        // add parenthesis as circle replacement, eg (1)
-                                               $match[2] = '0028 '.$match[2].' 0029';
+                       if (preg_match('/(<.*>)? *(.+)/', $decomp, $match)) {
+                               switch ($match[1]) {
+                                       case '<circle>': // add parenthesis as circle replacement, eg (1)
+                                               $match[2] = '0028 ' . $match[2] . ' 0029';
                                                break;
 
-                                       case '<square>':        // add square brackets as square replacement, eg [1]
-                                               $match[2] = '005B '.$match[2].' 005D';
+                                       case '<square>': // add square brackets as square replacement, eg [1]
+                                               $match[2] = '005B ' . $match[2] . ' 005D';
                                                break;
 
-                                       case '<compat>':        // ignore multi char decompositions that start with a space
-                                               if (preg_match('/^0020 /',$match[2]))   continue 2;
+                                       case '<compat>': // ignore multi char decompositions that start with a space
+                                               if (preg_match('/^0020 /', $match[2])) {
+                                                       continue 2;
+                                               }
                                                break;
 
                                                // ignore Arabic and vertical layout presentation decomposition
@@ -1144,31 +1227,31 @@ class t3lib_cs {
                fclose($fh);
 
                        // process additional Unicode data for casing (allow folded characters to expand into a sequence)
-               $specialCasingFile = PATH_t3lib.'unidata/SpecialCasing.txt';
-               if (t3lib_div::validPathStr($specialCasingFile) && @is_file($specialCasingFile))        {
-                       $fh = fopen($specialCasingFile,'rb');
-                       if ($fh)        {
-                               while (!feof($fh))      {
-                                       $line = fgets($fh,4096);
-                                       if ($line{0} != '#' && trim($line) != '')       {
-
-                                               list($char,$lower,$title,$upper,$cond) = t3lib_div::trimExplode(';', $line);
-                                               if ($cond == '' || $cond{0} == '#')     {
+               $specialCasingFile = PATH_t3lib . 'unidata/SpecialCasing.txt';
+               if (t3lib_div::validPathStr($specialCasingFile) && @is_file($specialCasingFile)) {
+                       $fh = fopen($specialCasingFile, 'rb');
+                       if ($fh) {
+                               while (!feof($fh)) {
+                                       $line = fgets($fh, 4096);
+                                       if ($line{0} != '#' && trim($line) != '') {
+
+                                               list($char, $lower, $title, $upper, $cond) = t3lib_div::trimExplode(';', $line);
+                                               if ($cond == '' || $cond{0} == '#') {
                                                        $utf8_char = $this->UnumberToChar(hexdec($char));
-                                                       if ($char != $lower)    {
+                                                       if ($char != $lower) {
                                                                $arr = explode(' ', $lower);
-                                                               for ($i=0; isset($arr[$i]); $i++)       $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
-                                                               $utf8CaseFolding['toLower'][$utf8_char] = implode('',$arr);
+                                                               for ($i = 0; isset($arr[$i]); $i++) $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
+                                                               $utf8CaseFolding['toLower'][$utf8_char] = implode('', $arr);
                                                        }
-                                                       if ($char != $title && $title != $upper)        {
+                                                       if ($char != $title && $title != $upper) {
                                                                $arr = explode(' ', $title);
-                                                               for ($i=0; isset($arr[$i]); $i++)       $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
-                                                               $utf8CaseFolding['toTitle'][$utf8_char] = implode('',$arr);
+                                                               for ($i = 0; isset($arr[$i]); $i++) $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
+                                                               $utf8CaseFolding['toTitle'][$utf8_char] = implode('', $arr);
                                                        }
-                                                       if ($char != $upper)    {
-                                                                       $arr = explode(' ', $upper);
-                                                               for ($i=0; isset($arr[$i]); $i++)       $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
-                                                               $utf8CaseFolding['toUpper'][$utf8_char] = implode('',$arr);
+                                                       if ($char != $upper) {
+                                                               $arr = explode(' ', $upper);
+                                                               for ($i = 0; isset($arr[$i]); $i++) $arr[$i] = $this->UnumberToChar(hexdec($arr[$i]));
+                                                               $utf8CaseFolding['toUpper'][$utf8_char] = implode('', $arr);
                                                        }
                                                }
                                        }
@@ -1178,15 +1261,17 @@ class t3lib_cs {
                }
 
                        // process custom decompositions
-               $customTranslitFile = PATH_t3lib.'unidata/Translit.txt';
-               if (t3lib_div::validPathStr($customTranslitFile) && @is_file($customTranslitFile))      {
-                       $fh = fopen($customTranslitFile,'rb');
-                       if ($fh)        {
-                               while (!feof($fh))      {
-                                       $line = fgets($fh,4096);
-                                       if ($line{0} != '#' && trim($line) != '')       {
-                                               list($char,$translit) = t3lib_div::trimExplode(';', $line);
-                                               if (!$translit) $omit["U+$char"] = 1;
+               $customTranslitFile = PATH_t3lib . 'unidata/Translit.txt';
+               if (t3lib_div::validPathStr($customTranslitFile) && @is_file($customTranslitFile)) {
+                       $fh = fopen($customTranslitFile, 'rb');
+                       if ($fh) {
+                               while (!feof($fh)) {
+                                       $line = fgets($fh, 4096);
+                                       if ($line{0} != '#' && trim($line) != '') {
+                                               list($char, $translit) = t3lib_div::trimExplode(';', $line);
+                                               if (!$translit) {
+                                                       $omit["U+$char"] = 1;
+                                               }
                                                $decomposition["U+$char"] = explode(' ', $translit);
 
                                        }
@@ -1196,19 +1281,19 @@ class t3lib_cs {
                }
 
                        // decompose and remove marks; inspired by unac (Loic Dachary <loic@senga.org>)
-               foreach($decomposition as $from => $to) {
+               foreach ($decomposition as $from => $to) {
                        $code_decomp = array();
 
-                       while ($code_value = array_shift($to))  {
-                               if (isset($decomposition["U+$code_value"]))     {       // do recursive decomposition
-                                       foreach(array_reverse($decomposition["U+$code_value"]) as $cv)  {
+                       while ($code_value = array_shift($to)) {
+                               if (isset($decomposition["U+$code_value"])) { // do recursive decomposition
+                                       foreach (array_reverse($decomposition["U+$code_value"]) as $cv) {
                                                array_unshift($to, $cv);
                                        }
-                               } elseif (!isset($mark["U+$code_value"])) {     // remove mark
+                               } elseif (!isset($mark["U+$code_value"])) { // remove mark
                                        array_push($code_decomp, $code_value);
                                }
                        }
-                       if (count($code_decomp) || isset($omit[$from])) {
+                       if (count($code_decomp) || isset($omit[$from])) {
                                $decomposition[$from] = $code_decomp;
                        } else {
                                unset($decomposition[$from]);
@@ -1219,32 +1304,35 @@ class t3lib_cs {
                $this->toASCII['utf-8'] = array();
                $ascii =& $this->toASCII['utf-8'];
 
-               foreach($decomposition as $from => $to) {
+               foreach ($decomposition as $from => $to) {
                        $code_decomp = array();
-                       while ($code_value = array_shift($to))  {
+                       while ($code_value = array_shift($to)) {
                                $ord = hexdec($code_value);
-                               if ($ord > 127)
-                                       continue 2;     // skip decompositions containing non-ASCII chars
+                               if ($ord > 127) {
+                                       continue 2;
+                               } // skip decompositions containing non-ASCII chars
                                else
-                                       array_push($code_decomp,chr($ord));
+                               {
+                                       array_push($code_decomp, chr($ord));
+                               }
                        }
-                       $ascii[$this->UnumberToChar(hexdec($from))] = join('',$code_decomp);
+                       $ascii[$this->UnumberToChar(hexdec($from))] = join('', $code_decomp);
                }
 
                        // add numeric decompositions
-               foreach($number as $from => $to)        {
+               foreach ($number as $from => $to) {
                        $utf8_char = $this->UnumberToChar(hexdec($from));
-                       if (!isset($ascii[$utf8_char])) {
+                       if (!isset($ascii[$utf8_char])) {
                                $ascii[$utf8_char] = $to;
                        }
                }
 
-               if ($cacheFileCase)     {
-                               t3lib_div::writeFileToTypo3tempDir($cacheFileCase,serialize($utf8CaseFolding));
+               if ($cacheFileCase) {
+                       t3lib_div::writeFileToTypo3tempDir($cacheFileCase, serialize($utf8CaseFolding));
                }
 
-               if ($cacheFileASCII)    {
-                               t3lib_div::writeFileToTypo3tempDir($cacheFileASCII,serialize($ascii));
+               if ($cacheFileASCII) {
+                       t3lib_div::writeFileToTypo3tempDir($cacheFileASCII, serialize($ascii));
                }
 
                return 3;
@@ -1258,55 +1346,63 @@ class t3lib_cs {
         * @return      integer         Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
         * @access private
         */
-       function initCaseFolding($charset)      {
+       function initCaseFolding($charset) {
                        // Only process if the case table is not yet loaded:
-               if (is_array($this->caseFolding[$charset]))     return 1;
+               if (is_array($this->caseFolding[$charset])) {
+                       return 1;
+               }
 
                        // Use cached version if possible
-               $cacheFile = t3lib_div::getFileAbsFileName('typo3temp/cs/cscase_'.$charset.'.tbl');
-               if ($cacheFile && @is_file($cacheFile)) {
+               $cacheFile = t3lib_div::getFileAbsFileName('typo3temp/cs/cscase_' . $charset . '.tbl');
+               if ($cacheFile && @is_file($cacheFile)) {
                        $this->caseFolding[$charset] = unserialize(t3lib_div::getUrl($cacheFile));
                        return 2;
                }
 
                        // init UTF-8 conversion for this charset
-               if (!$this->initCharset($charset))      {
-                       return false;
+               if (!$this->initCharset($charset)) {
+                       return FALSE;
                }
 
                        // UTF-8 case folding is used as the base conversion table
-               if (!$this->initUnicodeData('case'))    {
-                       return false;
+               if (!$this->initUnicodeData('case')) {
+                       return FALSE;
                }
 
                $nochar = chr($this->noCharByteVal);
-               foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8)      {
+               foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8) {
                                // reconvert to charset (don't use chr() of numeric value, might be muli-byte)
                        $c = $this->utf8_decode($utf8, $charset);
 
                                // $cc = $this->conv($this->caseFolding['utf-8']['toUpper'][$utf8], 'utf-8', $charset);
                        $cc = $this->utf8_decode($this->caseFolding['utf-8']['toUpper'][$utf8], $charset);
-                       if ($cc != '' && $cc != $nochar)        $this->caseFolding[$charset]['toUpper'][$c] = $cc;
+                       if ($cc != '' && $cc != $nochar) {
+                               $this->caseFolding[$charset]['toUpper'][$c] = $cc;
+                       }
 
                                // $cc = $this->conv($this->caseFolding['utf-8']['toLower'][$utf8], 'utf-8', $charset);
                        $cc = $this->utf8_decode($this->caseFolding['utf-8']['toLower'][$utf8], $charset);
-                       if ($cc != '' && $cc != $nochar)        $this->caseFolding[$charset]['toLower'][$c] = $cc;
+                       if ($cc != '' && $cc != $nochar) {
+                               $this->caseFolding[$charset]['toLower'][$c] = $cc;
+                       }
 
                                // $cc = $this->conv($this->caseFolding['utf-8']['toTitle'][$utf8], 'utf-8', $charset);
                        $cc = $this->utf8_decode($this->caseFolding['utf-8']['toTitle'][$utf8], $charset);
-                       if ($cc != '' && $cc != $nochar)        $this->caseFolding[$charset]['toTitle'][$c] = $cc;
+                       if ($cc != '' && $cc != $nochar) {
+                               $this->caseFolding[$charset]['toTitle'][$c] = $cc;
+                       }
                }
 
                        // add the ASCII case table
-               for ($i=ord('a'); $i<=ord('z'); $i++)   {
-                       $this->caseFolding[$charset]['toUpper'][chr($i)] = chr($i-32);
+               for ($i = ord('a'); $i <= ord('z'); $i++) {
+                       $this->caseFolding[$charset]['toUpper'][chr($i)] = chr($i - 32);
                }
-               for ($i=ord('A'); $i<=ord('Z'); $i++)   {
-                       $this->caseFolding[$charset]['toLower'][chr($i)] = chr($i+32);
+               for ($i = ord('A'); $i <= ord('Z'); $i++) {
+                       $this->caseFolding[$charset]['toLower'][chr($i)] = chr($i + 32);
                }
 
-               if ($cacheFile) {
-                               t3lib_div::writeFileToTypo3tempDir($cacheFile,serialize($this->caseFolding[$charset]));
+               if ($cacheFile) {
+                       t3lib_div::writeFileToTypo3tempDir($cacheFile, serialize($this->caseFolding[$charset]));
                }
 
                return 3;
@@ -1320,59 +1416,47 @@ class t3lib_cs {
         * @return      integer         Returns FALSE on error, a TRUE value on success: 1 table already loaded, 2, cached version, 3 table parsed (and cached).
         * @access private
         */
-       function initToASCII($charset)  {
+       function initToASCII($charset) {
                        // Only process if the case table is not yet loaded:
-               if (is_array($this->toASCII[$charset])) return 1;
+               if (is_array($this->toASCII[$charset])) {
+                       return 1;
+               }
 
                        // Use cached version if possible
-               $cacheFile = t3lib_div::getFileAbsFileName('typo3temp/cs/csascii_'.$charset.'.tbl');
-               if ($cacheFile && @is_file($cacheFile)) {
+               $cacheFile = t3lib_div::getFileAbsFileName('typo3temp/cs/csascii_' . $charset . '.tbl');
+               if ($cacheFile && @is_file($cacheFile)) {
                        $this->toASCII[$charset] = unserialize(t3lib_div::getUrl($cacheFile));
                        return 2;
                }
 
                        // init UTF-8 conversion for this charset
-               if (!$this->initCharset($charset))      {
-                       return false;
+               if (!$this->initCharset($charset)) {
+                       return FALSE;
                }
 
                        // UTF-8/ASCII transliteration is used as the base conversion table
-               if (!$this->initUnicodeData('ascii'))   {
-                       return false;
+               if (!$this->initUnicodeData('ascii')) {
+                       return FALSE;
                }
 
                $nochar = chr($this->noCharByteVal);
-               foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8)      {
+               foreach ($this->parsedCharsets[$charset]['local'] as $ci => $utf8) {
                                // reconvert to charset (don't use chr() of numeric value, might be muli-byte)
                        $c = $this->utf8_decode($utf8, $charset);
 
-                       if (isset($this->toASCII['utf-8'][$utf8]))      {
+                       if (isset($this->toASCII['utf-8'][$utf8])) {
                                $this->toASCII[$charset][$c] = $this->toASCII['utf-8'][$utf8];
                        }
                }
 
-               if ($cacheFile) {
-                               t3lib_div::writeFileToTypo3tempDir($cacheFile,serialize($this->toASCII[$charset]));
+               if ($cacheFile) {
+                       t3lib_div::writeFileToTypo3tempDir($cacheFile, serialize($this->toASCII[$charset]));
                }
 
                return 3;
        }
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
        /********************************************
         *
         * String operation functions
@@ -1391,47 +1475,49 @@ class t3lib_cs {
         * @see substr(), mb_substr()
         * @author      Martin Kutschker <martin.t.kutschker@blackbox.net>
         */
-       function substr($charset,$string,$start,$len=null)      {
-               if ($len===0)   return '';
+       function substr($charset, $string, $start, $len = NULL) {
+               if ($len === 0 || $string === '') {
+                       return '';
+               }
 
-               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'mbstring') {
+               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'mbstring') {
                                // cannot omit $len, when specifying charset
-                       if ($len==null) {
-                               $enc = mb_internal_encoding();  // save internal encoding
+                       if ($len == NULL) {
+                               $enc = mb_internal_encoding(); // save internal encoding
                                mb_internal_encoding($charset);
-                               $str = mb_substr($string,$start);
-                               mb_internal_encoding($enc);     // restore internal encoding
+                               $str = mb_substr($string, $start);
+                               mb_internal_encoding($enc); // restore internal encoding
 
                                return $str;
                        }
                        else {
-                               return mb_substr($string,$start,$len,$charset);
+                               return mb_substr($string, $start, $len, $charset);
                        }
-               } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'iconv')      {
+               } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'iconv') {
                                // cannot omit $len, when specifying charset
-                       if ($len==null) {
-                               $enc = iconv_get_encoding('internal_encoding'); // save internal encoding
-                               iconv_set_encoding('internal_encoding',$charset);
-                               $str = iconv_substr($string,$start);
-                               iconv_set_encoding('internal_encoding',$enc);   // restore internal encoding
+                       if ($len == NULL) {
+                               $enc = iconv_get_encoding('internal_encoding'); // save internal encoding
+                               iconv_set_encoding('internal_encoding', $charset);
+                               $str = iconv_substr($string, $start);
+                               iconv_set_encoding('internal_encoding', $enc); // restore internal encoding
 
                                return $str;
                        }
                        else {
-                               return iconv_substr($string,$start,$len,$charset);
+                               return iconv_substr($string, $start, $len, $charset);
                        }
-               } elseif ($charset == 'utf-8')  {
-                       return $this->utf8_substr($string,$start,$len);
-               } elseif ($this->eucBasedSets[$charset])        {
-                       return $this->euc_substr($string,$start,$charset,$len);
-               } elseif ($this->twoByteSets[$charset]) {
-                       return substr($string,$start*2,$len*2);
-               } elseif ($this->fourByteSets[$charset])        {
-                       return substr($string,$start*4,$len*4);
-               }
-
-               // treat everything else as single-byte encoding
-               return $len === NULL ? substr($string,$start) : substr($string,$start,$len);
+               } elseif ($charset == 'utf-8') {
+                       return $this->utf8_substr($string, $start, $len);
+               } elseif ($this->eucBasedSets[$charset]) {
+                       return $this->euc_substr($string, $start, $charset, $len);
+               } elseif ($this->twoByteSets[$charset]) {
+                       return substr($string, $start * 2, $len * 2);
+               } elseif ($this->fourByteSets[$charset]) {
+                       return substr($string, $start * 4, $len * 4);
+               }
+
+                       // treat everything else as single-byte encoding
+               return $len === NULL ? substr($string, $start) : substr($string, $start, $len);
        }
 
        /**
@@ -1444,21 +1530,21 @@ class t3lib_cs {
         * @see strlen()
         * @author      Martin Kutschker <martin.t.kutschker@blackbox.net>
         */
-       function strlen($charset,$string)       {
-               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'mbstring') {
-                       return mb_strlen($string,$charset);
-               } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'iconv')      {
-                       return iconv_strlen($string,$charset);
-               } elseif ($charset == 'utf-8')  {
+       function strlen($charset, $string) {
+               if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'mbstring') {
+                       return mb_strlen($string, $charset);
+               } elseif ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'iconv') {
+                       return iconv_strlen($string, $charset);
+               } elseif ($charset == 'utf-8') {
                        return $this->utf8_strlen($string);
-               } elseif ($this->eucBasedSets[$charset])        {
-                       return $this->euc_strlen($string,$charset);
-               } elseif ($this->twoByteSets[$charset]) {
-                       return strlen($string)/2;
-               } elseif ($this->fourByteSets[$charset])        {
-                       return strlen($string)/4;
-               }
-               // treat everything else as single-byte encoding
+               } elseif ($this->eucBasedSets[$charset]) {
+                       return $this->euc_strlen($string, $charset);
+               } elseif ($this->twoByteSets[$charset]) {
+                       return strlen($string) / 2;
+               } elseif ($this->fourByteSets[$charset]) {
+                       return strlen($string) / 4;
+               }
+                       // treat everything else as single-byte encoding
                return strlen($string);
        }
 
@@ -1473,7 +1559,7 @@ class t3lib_cs {
         * @see mb_strlen(), mb_substr()
         */
        protected function cropMbstring($charset, $string, $len, $crop = '') {
-               if (intval($len) == 0 || mb_strlen($string) < $len) {
+               if (intval($len) === 0 || mb_strlen($string, $charset) <= abs($len)) {
                        return $string;
                }
 
@@ -1498,49 +1584,53 @@ class t3lib_cs {
         * @see substr(), mb_strimwidth()
         * @author      Martin Kutschker <martin.t.kutschker@blackbox.net>
         */
-       function crop($charset,$string,$len,$crop='')   {
+       function crop($charset, $string, $len, $crop = '') {
                if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['t3lib_cs_utils'] == 'mbstring') {
                        return $this->cropMbstring($charset, $string, $len, $crop);
                }
 
-               if (intval($len) == 0)  return $string;
+               if (intval($len) == 0) {
+                       return $string;
+               }
 
-               if ($charset == 'utf-8')        {
-                       $i = $this->utf8_char2byte_pos($string,$len);
-               } elseif ($this->eucBasedSets[$charset])        {
-                       $i = $this->euc_char2byte_pos($string,$len,$charset);
+               if ($charset == 'utf-8') {
+                       $i = $this->utf8_char2byte_pos($string, $len);
+               } elseif ($this->eucBasedSets[$charset]) {
+                       $i = $this->euc_char2byte_pos($string, $len, $charset);
                } else {
-                       if ($len > 0)   {
+                       if ($len > 0) {
                                $i = $len;
                        } else {
-                               $i = strlen($string)+$len;
-                               if ($i<=0)      $i = false;
+                               $i = strlen($string) + $len;
+                               if ($i <= 0) {
+                                       $i = FALSE;
+                               }
                        }
                }
 
-               if ($i === false)       {       // $len outside actual string length
+               if ($i === FALSE) { // $len outside actual string length
                        return $string;
-               } else  {
-                       if ($len > 0)   {
-                               if (strlen($string{$i}))        {
-                                       return substr($string,0,$i).$crop;
+               } else {
+                       if ($len > 0) {
+                               if (strlen($string{$i})) {
+                                       return substr($string, 0, $i) . $crop;
 
                                }
                        } else {
-                               if (strlen($string{$i-1}))      {
-                                       return $crop.substr($string,$i);
+                               if (strlen($string{$i - 1})) {
+                                       return $crop . substr($string, $i);
                                }
                        }
 
-/*
-                       if (abs($len)<$this->strlen($charset,$string))  {       // Has to use ->strlen() - otherwise multibyte strings ending with a multibyte char will return true here (which is not a catastrophe, but...)
-                               if ($len > 0)   {
-