<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
* $accessdata[ra][$contextpath]= array($roleid)
* [$contextpath]= array($roleid)
* [$contextpath]= array($roleid)
- * </code>
+ * </code>
*
* Role definitions are stored like this
* (no cap merge is done - so it's compact)
define('ROLENAME_ALIAS_RAW', 4);
/** size limit for context cache */
-if (!defined('MAX_CONTEXT_CACHE_SIZE')) {
+if (!defined('MAX_CONTEXT_CACHE_SIZE')) {
define('MAX_CONTEXT_CACHE_SIZE', 5000);
}
/**
- * Although this looks like a global variable, it isn't really.
+ * Although this looks like a global variable, it isn't really.
*
- * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
- * It is used to cache various bits of data between function calls for performance reasons.
+ * It is just a private implementation detail to accesslib that MUST NOT be used elsewhere.
+ * It is used to cache various bits of data between function calls for performance reasons.
* Sadly, a PHP global variale is the only way to impleemnt this, withough rewriting everything
* as methods of a class, instead of functions.
*
/**
* Clears accesslib's private caches. ONLY BE USED BY UNIT TESTS
- *
+ *
* This method should ONLY BE USED BY UNIT TESTS. It clears all of
* accesslib's private caches. You need to do this before setting up test data,
* and also at the end fo the tests.
/**
* Get the default guest role
- *
+ *
* @global object
* @global object
* @return object role
* By default checks the capabilties of the current user, but you can pass a
* different userid. By default will return true for admin-like users who have the
* moodle/site:doanything capability, but you can override that with the fourth argument.
- *
+ *
* @param string $capability the name of the capability to check. For example mod/forum:view
* @param object $context the context to check the capability in. You normally get this with {@link get_context_instance}.
* @param integer $userid A user id. By default (null) checks the permissions of the current user.
if ($limit > 0 && $cc >= $limit) {
break;
}
-
+
$courses[] = $c;
$cc++;
}
* for example. Call it only _after_ you've setup $USER and called
* check_enrolment_plugins();
* @see check_enrolment_plugins()
- *
+ *
* @global object
* @global object
* @global object
/**
* Unassign a capability from a role.
- *
+ *
* @global object
* @param int $roleid the role id
* @param string $capability the name of the capability
/**
* This function makes a role-assignment (a role for a user or group in a particular context)
- *
+ *
* @global object
* @global object
* @global object
}
/**
- * Get a URL for a context, if there is a natural one. For example, for
+ * Get a URL for a context, if there is a natural one. For example, for
* CONTEXT_COURSE, this is the course page. For CONTEXT_USER it is the
* user profile page.
*
- * First three parameters as for
+ * First three parameters as for
*
* @global object
* @global object
/**
* Returns an array of all the known types of risk
- * The array keys can be used, for example as CSS class names, or in calls to
+ * The array keys can be used, for example as CSS class names, or in calls to
* print_risk_icon. The values are the corresponding RISK_ constants.
*
- * @return array all the known types of risk.
+ * @return array all the known types of risk.
*/
function get_all_risks() {
return array(
include_once($modfile);
$modfunction = $module->name.'_get_extra_capabilities';
if (function_exists($modfunction)) {
- $extracaps = $modfunction();
+ $extracaps = $modfunction();
}
}
if(empty($extracaps)) {
* otherwise false.
*
* @param object $context a context object.
- * @return bool
+ * @return bool
*/
function is_inside_frontpage($context) {
$frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
case 'webservice':
$string = get_string($stringname, 'webservice_'.$componentname);
break;
-
+
default:
$string = get_string($stringname);
break;
if (has_capability('moodle/site:doanything', get_context_instance(CONTEXT_SYSTEM))) {
// show all roles allowed in this context to admins
$raafrom = "";
- $raawhere = "";
+ $raawhere = "";
}
$params['userid'] = $USER->id;
SELECT ro.id, ro.name$extrafields
FROM {role} ro
ORDER BY ro.sortorder ASC", $params);
-
+
} else {
$roles = $DB->get_records_sql("
SELECT ro.id, ro.name$extrafields
/**
* Counts all the users assigned this role in this context or higher
- *
+ *
* @global object
* @param mixed $roleid either int or an array of ints
* @param object $context
/**
* Simple function returning a boolean true if roles exist, otherwise false
- *
+ *
* @global object
* @param int $userid
* @param int $roleid
*
* @param string $cap component string a
* @param string $comp component string b
- * @param mixed $contextlevel
+ * @param mixed $contextlevel
* @return bool whether 2 component are in different "sections"
*/
function component_level_changed($cap, $comp, $contextlevel) {
*
* Different code for each database - mostly for performance reasons
*/
- $dbfamily = $DB->get_dbfamily();
+ $dbfamily = $DB->get_dbfamily();
if ($dbfamily == 'mysql') {
$updatesql = "UPDATE {context} ct, {context_temp} temp
SET ct.path = temp.path,
/**
* Do some basic, quick checks to see whether $rec->context looks like a valid context object.
*
- * @param object $rec a think that has a context, for example a course,
+ * @param object $rec a think that has a context, for example a course,
* course category, course modules, etc.
* @param int $contextlevel the type of thing $rec is, one of the CONTEXT_... constants.
* @return bool whether $rec->context looks like the correct context object
$DB->insert_record('role_capabilities', $cap);
}
}
-
-?>
$requires->skip_link_to('maincontent', get_string('tocontent', 'access'));
- // Note that, as a short-cut, the code
+ // Note that, as a short-cut, the code
// $js = "document.body.className += ' jsenabled';\n";
// is hard-coded in {@link page_requirements_manager::get_top_of_body_code)
$requires->yui_lib('container');
$requires->string_for_js('confirmation', 'admin');
$requires->string_for_js('cancel', 'moodle');
$requires->string_for_js('yes', 'moodle');
- $requires->js_function_call('init_help_icons');
+ $requires->js_function_call('init_help_icons');
}
/**
* Make a language string available to JavaScript.
- *
+ *
* All the strings will be available in a mstr object in the global namespace.
* So, for example, after a call to $PAGE->requires->string_for_js('course', 'moodle');
* then the JavaScript variable mstr.moodle.course will be 'Course', or the
/**
* Make some data from PHP available to JavaScript code.
- *
+ *
* For example, if you call
* <pre>
* $PAGE->requires->data_for_js('mydata', array('name' => 'Moodle'));
$this->variablesinitialised[$variable] = 1;
return $requirement;
}
-
+
/**
* Creates a YUI event handler.
*
}
/**
- * This class represents a Javascript event handler, listening for a
+ * This class represents a Javascript event handler, listening for a
* specific Event to occur on a DOM element identified by a given id.
- * By default the data will be output at the end of the page, but you
+ * By default the data will be output at the end of the page, but you
* can change that using the {@link asap()}, {@link in_head()}, etc. methods.
*
* @copyright 2009 Nicolas Connault
}
}
-
-?>
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="utf-8"?>';
// Convert and output the branch as XML
-echo $converter->convert($branch);
\ No newline at end of file
+echo $converter->convert($branch);
-<?php // $Id$
+<?php
///////////////////////////////////////////////////////////////////////////
// //
}
echo 'OK';
-?>
\ No newline at end of file
$this->assertTrue(ajaxenabled($tested_browsers));
}
}
-
-?>
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
* Multiple plugin authentication Support library
*
* 2006-08-28 File created, AUTH return values defined.
- *
+ *
* @package moodlecore
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
/**
* This is the primary method that is used by the authenticate_user_login()
- * function in moodlelib.php.
+ * function in moodlelib.php.
*
* This method should return a boolean indicating
* whether or not the username and password authenticate successfully.
/**
* Returns the URL for changing the users' passwords, or empty if the default
- * URL can be used.
+ * URL can be used.
*
* This method is used if can_change_password() returns true.
* This method is called only when user is logged in, it may use global $USER.
}
/**
- * Updates the user's password.
+ * Updates the user's password.
*
* In previous versions of Moodle, the function
* auth_user_update_password accepted a username as the first parameter. The
}
return $authdescription;
}
-
+
/**
* Returns whether or not the captcha element is enabled, and the admin settings fulfil its requirements.
*
}
-
-?>
\r
return $outString;\r
}\r
-\r
-?>
\ No newline at end of file
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
* by students ('completion')
*
* Completion top-level options (admin setting enablecompletion)
- *
+ *
* @package moodlecore
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
/**
* Determines whether completion is enabled across entire site.
- *
- * Static function.
+ *
+ * Static function.
*
* @global object
* @return int COMPLETION_ENABLED (true) if completion is enabled for the site,
/**
* Deletes completion state related to an activity for all users.
- *
+ *
* Intended for use only when the activity itself is deleted.
*
* @global object
/**
* Recalculates completion state related to an activity for all users.
- *
+ *
* Intended for use if completion conditions change. (This should be avoided
* as it may cause some things to become incomplete when they were previously
* complete, with the effect - for example - of hiding a later activity that
* was previously available.)
- *
+ *
* Resetting state of manual tickbox has same result as deleting state for
* it.
*
* fill the cache, retrieves information from the entire course not just for
* this one activity
* @param int $userid User ID or 0 (default) for current user
- * @param array $modinfo Supply the value here - this is used for unit
- * testing and so that it can be called recursively from within
+ * @param array $modinfo Supply the value here - this is used for unit
+ * testing and so that it can be called recursively from within
* get_fast_modinfo. (Needs only list of all CMs with IDs.)
* Otherwise the method calls get_fast_modinfo itself.
* @return object Completion data (record from course_modules_completion)
/**
* Updates completion data for a particular coursemodule and user (user is
* determined from $data).
- *
+ *
* (Internal function. Not private, so we can unit-test it.)
*
* @global object
/**
* Obtains progress information across a course for all users on that course, or
* for all users in a specific group. Intended for use when displaying progress.
- *
+ *
* This includes only users who, in course context, have one of the roles for
* which progress is tracked (the progresstrackedroles admin option).
- *
+ *
* Users are included (in the first array) even if they do not have
* completion progress for any course-module.
*
* Calculates the completion state that would result from a graded item
* (where grade-based completion is turned on) based on the actual grade
* and settings.
- *
+ *
* Internal function. Not private, so we can unit-test it.
*
* @uses COMPLETION_INCOMPLETE
$CFG->wwwroot.'/course/view.php?id='.$this->course->id,null,$error);
}
- /**
- * For testing only. Wipes information cached in user session.
+ /**
+ * For testing only. Wipes information cached in user session.
*
* @global object
*/
unset($SESSION->completioncacheuserid);
}
}
-
-
-?>
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
* @copyright (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
-
+
/**
* @global object $CFG
* @name $CFG
/**
* This class is used to check, download and install items from
- * download.moodle.org to the moodledata directory.
+ * download.moodle.org to the moodledata directory.
*
* It always return true/false in all their public methods to say if
* execution has ended succesfuly or not. If there is any problem
}
} /// End of component_installer class
-
-?>
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Used for tracking conditions that apply before activities are displayed
* to students ('conditional availability').
- *
+ *
* @package moodlecore
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
/** The $cm variable is expected to contain all completion-related data */
define('CONDITION_MISSING_NOTHING',0);
-/** The $cm variable is expected to contain the fields from course_modules but
+/** The $cm variable is expected to contain the fields from course_modules but
not the course_modules_availability data */
define('CONDITION_MISSING_EXTRATABLE',1);
/** The $cm variable is expected to contain nothing except the ID */
* @uses DEBUG_DEVELOPER
* @uses CONDITION_MISSING_EXTRATABLE
* @param object $cm Moodle course-module object. May have extra fields
- * ->conditionsgrade, ->conditionscompletion which should come from
- * get_fast_modinfo. Should have ->availablefrom, ->availableuntil,
+ * ->conditionsgrade, ->conditionscompletion which should come from
+ * get_fast_modinfo. Should have ->availablefrom, ->availableuntil,
* and ->showavailability, ->course; but the only required thing is ->id.
* @param int $expectingmissing Used to control whether or not a developer
- * debugging message (performance warning) will be displayed if some of
- * the above data is missing and needs to be retrieved; a
+ * debugging message (performance warning) will be displayed if some of
+ * the above data is missing and needs to be retrieved; a
* CONDITION_MISSING_xx constant
* @param bool $loaddata If you need a 'write-only' object, set this value
* to false to prevent database access from constructor
}
// Missing basic data from course_modules
- if (!isset($cm->availablefrom) || !isset($cm->availableuntil) ||
+ if (!isset($cm->availablefrom) || !isset($cm->availableuntil) ||
!isset($cm->showavailability) || !isset($cm->course)) {
if ($expectingmissing<CONDITION_MISSING_EVERYTHING) {
- debugging('Performance warning: condition_info constructor is
- faster if you pass in $cm with at least basic fields
- (availablefrom,availableuntil,showavailability,course).
+ debugging('Performance warning: condition_info constructor is
+ faster if you pass in $cm with at least basic fields
+ (availablefrom,availableuntil,showavailability,course).
[This warning can be disabled, see phpdoc.]',
DEBUG_DEVELOPER);
}
// Missing extra data
if (!isset($cm->conditionsgrade) || !isset($cm->conditionscompletion)) {
if ($expectingmissing<CONDITION_MISSING_EXTRATABLE) {
- debugging('Performance warning: condition_info constructor is
+ debugging('Performance warning: condition_info constructor is
faster if you pass in a $cm from get_fast_modinfo.
[This warning can be disabled, see phpdoc.]',
DEBUG_DEVELOPER);
}
/**
- * Adds the extra availability conditions (if any) into the given
+ * Adds the extra availability conditions (if any) into the given
* course-module object.
*
* @global object
global $DB, $CFG;
$conditions = $DB->get_records_sql($sql="
-SELECT
+SELECT
cma.id as cmaid, gi.*,cma.sourcecmid,cma.requiredcompletion,cma.gradeitemid,
cma.grademin as conditiongrademin, cma.grademax as conditiongrademax
FROM
if (isset($gradeitemobj->id)) {
require_once($CFG->libdir.'/gradelib.php');
$item = new grade_item;
- grade_object::set_properties($item, $gradeitemobj);
+ grade_object::set_properties($item, $gradeitemobj);
return $item->get_name();
} else {
return '!missing'; // Ooops, missing grade
* @global object
* @global object
* @param object $modinfo Usually leave as null for default. Specify when
- * calling recursively from inside get_fast_modinfo. The value supplied
+ * calling recursively from inside get_fast_modinfo. The value supplied
* here must include list of all CMs with 'id' and 'name'
- * @return string Information string (for admin) about all restrictions on
+ * @return string Information string (for admin) about all restrictions on
* this item
*/
public function get_full_information($modinfo=null) {
/**
* Determines whether this particular course-module is currently available
- * according to these criteria.
- *
- * - This does not include the 'visible' setting (i.e. this might return
+ * according to these criteria.
+ *
+ * - This does not include the 'visible' setting (i.e. this might return
* true even if visible is false); visible is handled independently.
* - This does not take account of the viewhiddenactivities capability.
* That should apply later.
* @uses COMPLETION_COMPLETE_FAIL
* @uses COMPLETION_COMPLETE_PASS
* @param string $information If the item has availability restrictions,
- * a string that describes the conditions will be stored in this variable;
+ * a string that describes the conditions will be stored in this variable;
* if this variable is set blank, that means don't display anything
- * @param bool $grabthelot Performance hint: if true, caches information
+ * @param bool $grabthelot Performance hint: if true, caches information
* required for all course-modules, to make the front page and similar
* pages work more quickly (works only for current user)
* @param int $userid If set, specifies a different user ID to check availability for
* @param object $modinfo Usually leave as null for default. Specify when
- * calling recursively from inside get_fast_modinfo. The value supplied
+ * calling recursively from inside get_fast_modinfo. The value supplied
* here must include list of all CMs with 'id' and 'name'
* @return bool True if this item is available to the user, false otherwise
*/
foreach ($this->cm->conditionsgrade as $gradeitemid=>$minmax) {
$score = $this->get_cached_grade_score($gradeitemid, $grabthelot, $userid);
if ($score===false ||
- (!is_null($minmax->min) && $score<$minmax->min) ||
+ (!is_null($minmax->min) && $score<$minmax->min) ||
(!is_null($minmax->max) && $score>=$minmax->max)) {
// Grade fail
$available = false;
}
/**
- * Shows a time either as a date (if it falls exactly on the day) or
+ * Shows a time either as a date (if it falls exactly on the day) or
* a full date and time, according to user's timezone.
*
* @param int $time Time
$this->require_data();
return $this->cm->showavailability;
}
-
+
/**
* Internal function cheks that data was loaded.
*
}
/**
- * Obtains a grade score. Note that this score should not be displayed to
- * the user, because gradebook rules might prohibit that. It may be a
+ * Obtains a grade score. Note that this score should not be displayed to
+ * the user, because gradebook rules might prohibit that. It may be a
* non-final score subject to adjustment later.
*
* @global object
* @global object
* @global object
* @param int $gradeitemid Grade item ID we're interested in
- * @param bool $grabthelot If true, grabs all scores for current user on
+ * @param bool $grabthelot If true, grabs all scores for current user on
* this course, so that later ones come from cache
- * @param int $userid Set if requesting grade for a different user (does
+ * @param int $userid Set if requesting grade for a different user (does
* not use cache)
- * @return float Grade score as a percentage in range 0-100 (e.g. 100.0
+ * @return float Grade score as a percentage in range 0-100 (e.g. 100.0
* or 37.21), or false if user does not have a grade yet
*/
private function get_cached_grade_score($gradeitemid, $grabthelot=false, $userid=0) {
if (empty($SESSION->gradescorecache) || $SESSION->gradescorecacheuserid!=$USER->id) {
$SESSION->gradescorecache = array();
$SESSION->gradescorecacheuserid = $USER->id;
- }
+ }
if (!array_key_exists($gradeitemid, $SESSION->gradescorecache)) {
if ($grabthelot) {
// Get all grades for the current course
$rs = $DB->get_recordset_sql("
SELECT
- gi.id,gg.finalgrade,gg.rawgrademin,gg.rawgrademax
-FROM
+ gi.id,gg.finalgrade,gg.rawgrademin,gg.rawgrademax
+FROM
{grade_items} gi
LEFT JOIN {grade_grades} gg ON gi.id=gg.itemid AND gg.userid=?
WHERE
$SESSION->gradescorecache[$record->id] =
is_null($record->finalgrade)
// No grade = false
- ? false
+ ? false
// Otherwise convert grade to percentage
: (($record->finalgrade - $record->rawgrademin) * 100) /
($record->rawgrademax - $record->rawgrademin);
}
}
- /**
- * For testing only. Wipes information cached in user session.
+ /**
+ * For testing only. Wipes information cached in user session.
*
* @global object
*/
}
/**
- * Utility function called by modedit.php; updates the
+ * Utility function called by modedit.php; updates the
* course_modules_availability table based on the module form data.
*
* @param object $cm Course-module with as much data as necessary, min id
return array_key_exists($cm->id, $CONDITIONLIB_PRIVATE->usedincondition[$course->id]);
}
}
-?>
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
- /**
+ /**
* The maximum courses in a category
- * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
+ * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
*/
define('MAX_COURSES_IN_CATEGORY', 10000);
-/**
+/**
* The maximum number of course categories
- * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
+ * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
*/
define('MAX_COURSE_CATEGORIES', 10000);
- /**
+ /**
* Number of seconds to wait before updating lastaccess information in DB.
*/
- define('LASTACCESS_UPDATE_SECS', 60);
+ define('LASTACCESS_UPDATE_SECS', 60);
/**
* Returns $user object of the main admin user
* @param string $page The page or records to return
* @param string $recordsperpage The number of records to return per page
* @param string $fields A comma separated list of fields to be returned from the chosen table.
- * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
+ * @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
* False is returned if an error is encountered.
*/
function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
* @param int $totalcount Reference for the number of courses
* @param string $limitfrom The course to start from
* @param string $limitnum The number of courses to limit to
- * @return array Array of courses
+ * @return array Array of courses
*/
function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
&$totalcount, $limitfrom="", $limitnum="") {
if ($limit > 0 && $cc >= $limit) {
break;
}
-
+
$courses[$c->id] = $c;
$cc++;
}
/**
* Return specified category, default if given does not exist
- *
+ *
* @global object
* @uses MAX_COURSES_IN_CATEGORY
* @uses CONTEXT_COURSECAT
* is visible or not, groupmembersonly visibility not tested
*
* @global object
-
+
* @param $moduletype Name of the module eg 'forum'
* @param $module Object which is the instance of the module
* @return bool Success
if ($CFG->enableavailability) {
require_once($CFG->libdir.'/conditionlib.php');
$ci=new condition_info($cm,CONDITION_MISSING_EXTRATABLE);
- if(!$ci->is_available($cm->availableinfo,false,$userid) and
- !has_capability('moodle/course:viewhiddenactivities',
+ if(!$ci->is_available($cm->availableinfo,false,$userid) and
+ !has_capability('moodle/course:viewhiddenactivities',
get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
return false;
}
$catsrs->close();
return false;
}
-
-?>
-<?php // $Id$
+<?php
//
// Capability definitions for Moodle core.
//
)
)
);
-
-
-?>
-<?php // $Id$
+<?php
///////////////////////////////////////////////////////////////////////////
// Defines core event handlers //
$handlers = array (
/* Messaging required parameters (object):
- * modulename -
+ * modulename -
* userfrom
* userto
* subject
* fullmessage - the full message in a given format
* fullmessageformat - the format if the full message (FORMAT_MOODLE, FORMAT_HTML, ..)
- * fullmessagehtml - the full version (the message processor will choose with one to use)
+ * fullmessagehtml - the full version (the message processor will choose with one to use)
* smallmessage - the small version of the message
*/
'message_send' => array (
'handlerfile' => '/lib/messagelib.php',
- 'handlerfunction' => 'message_send_handler',
+ 'handlerfunction' => 'message_send_handler',
'schedule' => 'instant'
),
role_unassigned - object role_assignments table record
*/
-
-?>
-<?php //$Id$
+<?php
// This file is executed right after the install.xml
//
set_role_contextlevels($guestrole, get_default_contextlevels('guest'));
set_role_contextlevels($userrole, get_default_contextlevels('user'));
-}
\ No newline at end of file
+}
-<?php // $Id$
+<?php
///////////////////////////////////////////////////////////////////////////
// Defines message providers (types of messages being sent) //
-<?PHP //$Id$
+<?PHP
// This file keeps track of upgrades to Moodle.
//
/// Main savepoint reached
upgrade_main_savepoint($result, 2009103000);
}
-
+
return $result;
}
-<?php //$Id$
+<?php
/*
* This file is used for special upgrade functions - for example groups and gradebook.
* before doing this I checked that the blocks did not override the
* {@link block_base::instance_delete()} method. Should this function ever
* be repeated check this again
- *
+ *
* @link lib/db/upgrade.php
*
* @since navigation upgrade 20090828
return ($outcome1 && $outcome2 && $outcome4 && $outcome4);
}
-
-?>
}
/**
- * This function will generate all the needed SQL statements, specific for each
+ * This function will generate all the needed SQL statements, specific for each
* RDBMS type and, finally, it will execute all those statements against the DB.
*
* @param object $structure xmldb_structure object
}
return $schema;
}
-
+
/**
* Checks the database schema against a schema specified by an xmldb_structure object
* @param xmldb_structure $schema export schema describing all known tables
- * @return array keyed by table name with array of difference messages as values
+ * @return array keyed by table name with array of difference messages as values
*/
public function check_database_schema(xmldb_structure $schema) {
$errors = array();
return $errors;
}
}
-
-
-?>
return $reserved_words;
}
}
-
-?>
return $reserved_words;
}
}
-
-?>
return $reserved_words;
}
}
-
-?>
return $reserved_words;
}
}
-
-?>
*/
/**
- * Abstract sql generator class, base for all bd specific implementations.
+ * Abstract sql generator class, base for all bd specific implementations.
*/
abstract class sql_generator {
return $s;
}
}
-
-?>
$results[] = 'COMMIT';
return $results;
}
-
+
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needded to alter the field in the table
*/
public function getAlterFieldSQL($xmldb_table, $xmldb_field, $skip_type_clause = NULL, $skip_default_clause = NULL, $skip_notnull_clause = NULL) {
return $this->getAlterTableSchema($xmldb_table, $xmldb_field, $xmldb_field);
}
-
+
/**
* Given one xmldb_table and one xmldb_key, return the SQL statements needded to add the key to the table
* note that undelying indexes will be added as parametrised by $xxxx_keys and $xxxx_index parameters
$xmldb_table->deleteKey($xmldb_key->getName());
return $this->getAlterTableSchema($xmldb_table);
}
-
+
/**
* Given one xmldb_table and one xmldb_field, return the SQL statements needded to drop its default
* (usually invoked from getModifyDefaultSQL()
}
$dberr = ob_get_contents();
ob_end_clean();
-
+
$status = pg_connection_status($this->pgsql);
if ($status === false or $status === PGSQL_CONNECTION_BAD) {
public $sql;
/** @var array */
public $params;
-
+
/**
* Constructor
* @param string $error
public $sql;
/** @var array */
public $params;
-
+
/**
* Constructor
* @param string $table table name if known, '' if unknown
public $sql;
/** @var array */
public $params;
-
+
/**
* Constructor
* @param string $table table name if known, '' if unknown
$this->tablename = $tablename;
$this->sql = $sql;
$this->params = $params;
-
+
switch ($tablename) {
case null:
$errcode = 'invalidrecordunknown';
/// Process restrict, modifying $result if needed.
process_environment_restrict($element, $result);
}
-?>
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Library of functions for events manipulation.
- *
+ *
* The public API is all at the end of this file.
*
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
WHERE qh.handlerid = h.id AND h.eventname=?";
return $DB->count_records_sql($sql, array($eventname));
}
-?>
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* excellib.class.php
- *
+ *
* @copyright (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
* @package moodlecore
*/
function MoodleExcelWorksheet($name, &$workbook, $latin_output=false) {
- /// Internally, add one sheet to the workbook
+ /// Internally, add one sheet to the workbook
$this->pear_excel_worksheet =& $workbook->addWorksheet($name);
$this->latin_output = $latin_output;
- /// Set encoding to UTF-16LE
+ /// Set encoding to UTF-16LE
if (!$this->latin_output) { /// Only if don't want to use latin (win1252) stronger output
$this->pear_excel_worksheet->setInputEncoding('UTF-16LE');
}
function hide_screen_gridlines() {
$this->pear_excel_worksheet->hideScreenGridlines();
}
-
+
/**
* Insert a 24bit bitmap image in a worksheet.
*
* @param array $properties
*/
function MoodleExcelFormat(&$workbook, $properties = array()) {
- /// Internally, add one sheet to the workbook
+ /// Internally, add one sheet to the workbook
$this->pear_excel_format =& $workbook->addFormat();
/// If we have something in the array of properties, compute them
foreach($properties as $property => $value) {
}
}
-
-?>
}
/**
- *
+ *
* @global object
* @global object
* @param string $file The file to put the CSV content into
/** @var string */
public $info;
public $error;
-
+
/** @var array */
private $options;
/** @var string */
/**
* HTTP HEAD method
*
- * @see request()
+ * @see request()
*
* @param string $url
* @param array $options
* HTTP POST method
*
* @param string $url
- * @param array|string $params
+ * @param array|string $params
* @param array $options
* @return bool
*/
* HTTP GET method
*
* @param string $url
- * @param array $params
+ * @param array $params
* @param array $options
* @return bool
*/
* HTTP PUT method
*
* @param string $url
- * @param array $params
+ * @param array $params
* @param array $options
* @return bool
*/
* HTTP DELETE method
*
* @param string $url
- * @param array $params
+ * @param array $params
* @param array $options
* @return bool
*/
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class filter_manager {
- /**
+ /**
* @var array This list of active filters, by context, for filtering content.
- * An array contextid => array of filter objects.
+ * An array contextid => array of filter objects.
*/
protected $textfilters = array();
/**
* @var array This list of active filters, by context, for filtering strings.
- * An array contextid => array of filter objects.
+ * An array contextid => array of filter objects.
*/
protected $stringfilters = array();
return self::$singletoninstance;
}
- /**
- * Load all the filters required by this context.
+ /**
+ * Load all the filters required by this context.
*
* @param object $context
* @param int $courseid
}
/**
- * @todo Document this function
+ * @todo Document this function
* @param string $text
* @param array $filterchain
* @return string $text
}
/**
- * @todo Document this function
+ * @todo Document this function
* @param object $context
* @param int $courseid
* @return object A text filter
}
/**
- * @todo Document this function
+ * @todo Document this function
* @param object $context
* @param int $courseid
* @return object A string filter
}
/**
- * @todo Document this function
+ * @todo Document this function
* @param object $context
* @param int $courseid
* @return object A string filter
define('EXCL_SEPARATOR', '-%-');
/**
- * This is just a little object to define a phrase and some instructions
- * for how to process it. Filters can create an array of these to pass
+ * This is just a little object to define a phrase and some instructions
+ * for how to process it. Filters can create an array of these to pass
* to the filter_phrases function below.
*
* @package moodlecore
* @param bool $fullmatch
* @param mixed $replacementphrase
*/
- function filterobject($phrase, $hreftagbegin='<span class="highlight">',
- $hreftagend='</span>',
- $casesensitive=false,
+ function filterobject($phrase, $hreftagbegin='<span class="highlight">',
+ $hreftagend='</span>',
+ $casesensitive=false,
$fullmatch=false,
$replacementphrase=NULL) {
$ignoretagsopen = array('<a\s[^>]+?>');
$ignoretagsclose = array('</a>');
}
-
+
if ( is_array($ignoretagsopen) ) {
foreach ($ignoretagsopen as $open) $filterignoretagsopen[] = $open;
foreach ($ignoretagsclose as $close) $filterignoretagsclose[] = $close;
$text = preg_replace('/([#*%])/','\1\1',$text);
-////Remove everything enclosed by the ignore tags from $text
+////Remove everything enclosed by the ignore tags from $text
filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
/// Remove tags from $text
/// Work calculated
$linkobject->work_calculated = true;
-
+
}
/// If $CFG->filtermatchoneperpage, avoid previously (request) linked phrases
/// Finally we do our highlighting
if (!empty($CFG->filtermatchonepertext) || !empty($CFG->filtermatchoneperpage)) {
- $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
+ $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
$linkobject->work_hreftagbegin.
$linkobject->work_replacementphrase.
$linkobject->work_hreftagend, $text, 1);
} else {
- $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
+ $resulttext = preg_replace('/('.$linkobject->work_phrase.')/'.$modifiers,
$linkobject->work_hreftagbegin.
$linkobject->work_replacementphrase.
$linkobject->work_hreftagend, $text);
if ($resulttext != $text) {
/// Set $text to $resulttext
$text = $resulttext;
- /// Remove everything enclosed by the ignore tags from $text
+ /// Remove everything enclosed by the ignore tags from $text
filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);
/// Remove tags from $text
filter_save_tags($text,$tags);
$text = str_replace(array_keys($ignoretags),$ignoretags,$text);
}
- //// Remove the protective doubleups
+ //// Remove the protective doubleups
$text = preg_replace('/([#*%])(\1)/','\1',$text);
/// Add missing javascript for popus
$lconcepts = array(); // a lower case version for case insensitive
$cleanlinks = array();
-
+
foreach ($linkarray as $key=>$filterobject) {
if ($filterobject->casesensitive) {
$exists = in_array($filterobject->phrase, $concepts);
} else {
$exists = in_array(moodle_strtolower($filterobject->phrase), $lconcepts);
}
-
+
if (!$exists) {
$cleanlinks[] = $filterobject;
$concepts[] = $filterobject->phrase;
*
* @param string $text the text that we are filtering (in/out)
* @param array $filterignoretagsopen an array of open tags to start searching
- * @param array $filterignoretagsclose an array of close tags to end searching
+ * @param array $filterignoretagsclose an array of close tags to end searching
* @param array $ignoretags an array of saved strings useful to rebuild the original text (in/out)
**/
function filter_save_ignore_tags(&$text,$filterignoretagsopen,$filterignoretagsclose,&$ignoretags) {
$opentag = str_replace('/','\/',$opentag); // delimit forward slashes
$closetag = str_replace('/','\/',$closetag); // delimit forward slashes
$pregexp = '/'.$opentag.'(.*?)'.$closetag.'/is';
-
+
preg_match_all($pregexp, $text, $list_of_ignores);
foreach (array_unique($list_of_ignores[0]) as $key=>$value) {
$prefix = (string)(count($ignoretags) + 1);
* Extract tags (any text enclosed by < and > to avoid being processed by filters.
* It returns the text converted with some <%xEXCL_SEPARATORx%> codes replacing the extracted text. Such extracted
* texts are returned in the tags array (as values), with codes as keys.
- *
+ *
* @param string $text the text that we are filtering (in/out)
* @param array $tags an array of saved strings useful to rebuild the original text (in/out)
**/
if (strpos($text, 'onclick="return openpopup') === FALSE) {
return $text; // no popup - no need to add javascript
}
- $js ="
+ $js ="
<script type=\"text/javascript\">
<!--
function openpopup(url,name,options,fullscreen) {
//last chance - try adding head element
return preg_replace("/<html.*?>/is", "\\0<head>".$js.'</head>', $text);
}
-?>
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
}
/**
- *
+ *
* @staticvar bool $done
*/
function form_init_date_js() {
/**
* Internal method. Validates all old-style uploaded files.
- *
+ *
* @global object
* @global object
* @param array $files
function getReqHTML(){
return $this->_reqHTML;
}
-
+
/**
* @return string
*/
}
-
+
/**
* @param object $group Passed by reference
* @param mixed $required
$PAGE->requires->string_for_js('showadvanced', 'form');
$PAGE->requires->string_for_js('hideadvanced', 'form');
$PAGE->requires->js_function_call('showAdvancedInit', Array($elementName.(string)$advformcount, $elementName, $buttonlabel));
-
+
$advformcount++;
$header_html = str_replace('{button}', $button_nojs, $header_html);
} else {
MoodleQuickForm::registerElementType('textarea', "$CFG->libdir/form/textarea.php", 'MoodleQuickForm_textarea');
MoodleQuickForm::registerElementType('url', "$CFG->libdir/form/url.php", 'MoodleQuickForm_url');
MoodleQuickForm::registerElementType('warning', "$CFG->libdir/form/warning.php", 'MoodleQuickForm_warning');
-?>
require_once($CFG->libdir.'/filelib.php');
/**
- * Base class for google authenticated http requests
- *
- * Most Google API Calls required that requests are sent with an
+ * Base class for google authenticated http requests
+ *
+ * Most Google API Calls required that requests are sent with an
* Authorization header + token. This class extends the curl class
* to aid this
*
}
/*******
- * The following two classes are usd to implement AuthSub google
+ * The following two classes are usd to implement AuthSub google
* authtentication, as documented here:
* http://code.google.com/apis/accounts/docs/AuthSub.html
*******/
const AUTHSESSION_URL = 'https://www.google.com/accounts/AuthSubSessionToken';
/**
- * Constructor. Calls constructor of its parents
+ * Constructor. Calls constructor of its parents
*
* @param string $authtoken The token to upgrade to a session token
*/
}
/**
- * Requests a long-term session token from google based on the
+ * Requests a long-term session token from google based on the
*
- * @return string Sub-Auth token
+ * @return string Sub-Auth token
*/
public function get_session_token(){
$content = $this->get(google_authsub_request::AUTHSESSION_URL);
const REVOKE_TOKEN_URL = 'https://www.google.com/accounts/AuthSubRevokeToken';
/**
- * Constructor, allows subauth requests using the response from an initial
+ * Constructor, allows subauth requests using the response from an initial
* AuthSubRequest or with the subauth long-term token. Note that constructing
* this object without a valid token will cause an exception to be thrown.
*
* Creates a login url for subauth request
*
* @param string $returnaddr The address which the user should be redirected to recieve the token
- * @param string $realm The google realm which is access is being requested
+ * @param string $realm The google realm which is access is being requested
* @return string URL to bounce the user to
*/
public static function login_url($returnaddr, $realm){
$files = array();
foreach($xml->entry as $gdoc){
- // there doesn't seem to to be cleaner way of getting the id/type
+ // there doesn't seem to to be cleaner way of getting the id/type
// than spliting this..
if (preg_match('/^http:\/\/docs.google.com\/feeds\/documents\/private\/full\/([^%]*)%3A(.*)$/', $gdoc->id, $matches)){
$docid = $matches[2];
- // FIXME: We're making hard-coded choices about format here.
- // If the repo api can support it, we could let the user
+ // FIXME: We're making hard-coded choices about format here.
+ // If the repo api can support it, we could let the user
// chose.
switch($matches[1]){
- case 'document':
+ case 'document':
$title = $gdoc->title.'.rtf';
$source = 'http://docs.google.com/feeds/download/documents/Export?docID='.$docid.'&exportFormat=rtf';
break;
break;
}
- $files[] = array( 'title' => $title,
+ $files[] = array( 'title' => $title,
'url' => "{$gdoc->link[0]->attributes()->href}",
- 'source' => $source,
+ 'source' => $source,
'date' => usertime(strtotime($gdoc->updated)),
'thumbnail' => $CFG->wwwroot.'/pix/f/'.mimeinfo('icon32', $title)
);
}
/**
- * Does text search on the users photos and returns
+ * Does text search on the users photos and returns
* matches in format for picasa api
*
* @param string $query Search terms
}
/**
- * Beginings of an implementation of Clientogin authenticaton for google
+ * Beginings of an implementation of Clientogin authenticaton for google
* accounts as documented here:
* {@link http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html#ClientLogin}
*
- * With this authentication we have to accept a username and password and to post
+ * With this authentication we have to accept a username and password and to post
* it to google. Retrieving a token for use afterwards.
*
* @package moodlecore
return 'GoogleLogin auth=';
}
}
-
-?>
<?php
-// This file is part of Moodle - http://moodle.org/
-//
+// This file is part of Moodle - http://moodle.org/
+//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
-//
+//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
}
/**
- * @todo Document this function
+ * @todo Document this function
*/
function grade_format_gradevalue_real($value, $grade_item, $decimals, $localized) {
if ($grade_item->gradetype == GRADE_TYPE_SCALE) {
}
}
/**
- * @todo Document this function
+ * @todo Document this function
*/
function grade_format_gradevalue_percentage($value, $grade_item, $decimals, $localized) {
$min = $grade_item->grademin;
return format_float($percentage, $decimals, $localized).' %';
}
/**
- * @todo Document this function
+ * @todo Document this function
*/
function grade_format_gradevalue_letter($value, $grade_item) {
$context = get_context_instance(CONTEXT_COURSE, $grade_item->courseid);
}
} // class graph
-
-
-?>
$result = array();
$allgroups = array();
-
+
foreach ($rs as $group) {
$allgroups[$group->id] = $group->id;
if (is_null($group->groupingid)) {
/**
* Gets array of all groupings in a specified course.
- *
+ *
* @global object
* @global object
* @param int $courseid return only groupings in this with this courseid
/**
* Returns effective groupmode used in course
- *
+ *
* @return integer group mode
*/
function groups_get_course_groupmode($course) {
$select = html_select::make_popup_form($urlroot, 'group', $groupsmenu, 'selectgroup', $activegroup);
$select->nothinglabel = false;
$select->set_label($grouplabel);
- $output = $OUTPUT->select($select);
+ $output = $OUTPUT->select($select);
}
$output = '<div class="groupselector">'.$output.'</div>';
$select = html_select::make_popup_form($urlroot, 'group', $groupsmenu, 'selectgroup', $activegroup);
$select->nothinglabel = false;
$select->set_label($grouplabel);
- $output = $OUTPUT->select($select);
+ $output = $OUTPUT->select($select);
}
$output = '<div class="groupselector">'.$output.'</div>';
}
return false;
}
-
-?>
return strtoupper($str);
}
}
-
-?>
$lifetime = '86400';
- @header('Content-type: text/javascript');
- @header('Content-length: '.strlen($output));
+ @header('Content-type: text/javascript');
+ @header('Content-length: '.strlen($output));
@header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
@header('Cache-control: max-age='.$lifetime);
@header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .'GMT');
"zh" => "Chinese",
"zu" => "Zulu");
-
-
-
-?>
\ No newline at end of file
$this->parentlist =& $parent;
}
}
-?>
/**
* Similar to unformat_float, converts floats and lists to PHP standards.
* @param string $formula localised formula
- * @return string
+ * @return string
*/
function unlocalize($formula) {
$formula = str_replace(get_string('decsep'), '$', $formula);
return $formula;
}
}
-
-?>
\ No newline at end of file
/**
* This class abstracts PHP's PECL memcached
* API to provide
- *
+ *
* - get()
* - set()
* - delete()
*
* Author: Martin Langhoff <martin@catalyst.net.nz>
*
- * Note: do NOT store booleans here. With memcached, a false value
+ * Note: do NOT store booleans here. With memcached, a false value
* is indistinguisable from a "not found in cache" response.
*
* @package moodlecore
if (count($hosts) === 1 && !empty($CFG->memcachedpconn)) {
// the faster pconnect is only available
// for single-server setups
- // NOTE: PHP-PECL client is buggy and pconnect()
+ // NOTE: PHP-PECL client is buggy and pconnect()
// will segfault if the server is unavailable
$this->_cache->pconnect($hosts[0]);
} else {
function get($key) {
$rec = $this->_cache->get($this->prefix . $key);
return $rec;
- }
-
+ }
+
function delete($key) {
return $this->_cache->delete($this->prefix . $key);
}
/**
- * In the simple case, this function will
+ * In the simple case, this function will
* get the cached value if available. If the entry
* is not cached, it will try to get an exclusive
* lock that announces that this process will
* populate the cache.
*
* If we fail to get the lock -- this means another
- * process is doing it.
+ * process is doing it.
* so we wait (block) for a few microseconds while we wait for
* the cache to be filled or the lock to timeout.
- *
+ *
* If you get a false from this call, you _must_
* populate the cache ASAP or indicate that
* you won't by calling releaseforfill().
*
- * This technique forces serialisation and so helps deal
- * with thundering herd scenarios where a lot of clients
- * ask the for the same idempotent (and costly) operation.
+ * This technique forces serialisation and so helps deal
+ * with thundering herd scenarios where a lot of clients
+ * ask the for the same idempotent (and costly) operation.
* The implementation is based on suggestions in this message
* http://marc.theaimsgroup.com/?l=git&m=116562052506776&w=2
*
* @return mixed on cache hit, NULL otherwise
*/
function getforfill ($key) {
-
+
$rec = $this->_cache->get($this->prefix . $key);
if ($rec) {
return $rec;
}
/**
- * Release the exclusive lock obtained by
+ * Release the exclusive lock obtained by
* getforfill(). See getforfill()
* for more details.
*
return $this->_cache->delete($this->prefix . $key . '_forfill');
}
}
-
-?>
\ No newline at end of file
/** TIMETOSHOWUSERS = 300 */
define('TIMETOSHOWUSERS', 300);
-
+
/**
* Triggered when a message provider wants to send a message.
* This functions checks the user's processor configuration to send the given type of message,
} else {
$userstate = 'loggedin';
}
-
+
/// Create the message object
$savemessage = new object();
$savemessage->useridfrom = $eventdata->userfrom->id;
$savemessage->timecreated = time();
/// Find out what processors are defined currently
-/// When a user doesn't have settings none gets return, if he doesn't want contact "" gets returned
+/// When a user doesn't have settings none gets return, if he doesn't want contact "" gets returned
$processor = get_user_preferences('message_provider_'.$eventdata->component.'_'.$eventdata->name.'_'.$userstate, NULL, $eventdata->userto->id);
-
- if ($processor == NULL){ //this user never had a preference, save default
+
+ if ($processor == NULL){ //this user never had a preference, save default
if (!message_set_default_message_preferences( $eventdata->userto )){
print_error('cannotsavemessageprefs', 'message');
}
//if we are suposed to do something with this message
// No processor for this message, mark it as read
if ($processor == "") { //this user cleared all the preferences
- $savemessage->timeread = time();
+ $savemessage->timeread = time();
$messageid = $message->id;
unset($message->id);
$DB->insert_record('message_read', $savemessage);
} else { // Process the message
/// Store unread message just in case we can not send it
- $savemessage->id = $DB->insert_record('message', $savemessage);
-
+ $savemessage->id = $DB->insert_record('message', $savemessage);
+
/// Try to deliver the message to each processor
$processorlist = explode(',', $processor);
foreach ($processorlist as $procname) {
$processorfile = $CFG->dirroot. '/message/output/'.$procname.'/message_output_'.$procname.'.php';
- if (is_readable($processorfile)) {
+ if (is_readable($processorfile)) {
include_once( $processorfile ); // defines $module with version etc
$processclass = 'message_output_' . $procname;
-
- if (class_exists($processclass)) {
+
+ if (class_exists($processclass)) {
$pclass = new $processclass();
if (! $pclass->send_message($savemessage)) {
debugging('Error calling message processor '.$procname);
return false;
- }
+ }
}
} else {
debugging('Error calling message processor '.$procname);
foreach ($fileproviders as $messagename => $fileprovider) {
if (!empty($dbproviders[$messagename])) { // Already exists in the database
-
+
if ($dbproviders[$messagename]->capability == $fileprovider['capability']) { // Same, so ignore
// exact same message provider already present in db, ignore this entry
unset($dbproviders[$messagename]);
function message_get_providers_from_db($component) {
global $DB;
- if ($dbproviders = $DB->get_records('message_providers', array('component'=>$component), '',
+ if ($dbproviders = $DB->get_records('message_providers', array('component'=>$component), '',
'name, id, component, capability')) { // Name is unique per component
return $dbproviders;
}
}
/**
- * Remove all message providers
+ * Remove all message providers
* @param $component - examples: 'moodle', 'mod/forum', 'block/quiz_results'
*/
function message_uninstall($component) {
*/
function message_set_default_message_preferences( $user ) {
global $DB;
-
+
$providers = $DB->get_records('message_providers');
$preferences = array();
foreach ( $providers as $providerid => $provider){
$preferences[ 'message_provider_'.$provider->component.'_'.$provider->name.'_loggedin' ] = 'popup';
$preferences[ 'message_provider_'.$provider->component.'_'.$provider->name.'_loggedoff' ] = 'email';
- }
+ }
return set_user_preferences( $preferences, $user->id );
}
-
-?>
note_delete_all($data->courseid);
$status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotes', 'notes'), 'error'=>false);
}
-
+
if (!empty($data->delete_blog_associations)) {
require_once($CFG->dirroot.'/blog/lib.php');
blog_remove_associations_for_course($data->courseid);
// This array stores information about open and close tags and their position
// in the truncated string. Each item in the array is an object with fields
- // ->open (true if open), ->tag (tag name in lower case), and ->pos
+ // ->open (true if open), ->tag (tag name in lower case), and ->pos
// (byte position in truncated text)
$tagdetails = array();
// if tag is a closing tag (f.e. </b>)
} else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
// record closing tag
- $tagdetails[] = (object)array('open'=>false,
+ $tagdetails[] = (object)array('open'=>false,
'tag'=>strtolower($tag_matchings[1]), 'pos'=>strlen($truncate));
// if tag is an opening tag (f.e. <b>)
} else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
// record opening tag
- $tagdetails[] = (object)array('open'=>true,
+ $tagdetails[] = (object)array('open'=>true,
'tag'=>strtolower($tag_matchings[1]), 'pos'=>strlen($truncate));
}
// add html-tag to $truncate'd text
/**
* This function overrides the active URL that is used to compare new nodes
* to find out if they are active.
- *
+ *
* If null is passed then $fullmeurl will be regenerated when the next node
* is created/added
*/
/**
* Add a css class to this particular node
- *
+ *
* @param string $class The css class to add
* @return bool Returns true
*/
}
return $content;
}
-
+
/**
* Get the CSS type for this node
- *
+ *
* @return string
*/
public function get_css_type() {
}
return parent::content();
}
-
+
/**
* Initialise the navigation object, calling it to auto generate
*
$this->cache->volatile();
$depth = $this->load_for_category(false);
break;
- case CONTEXT_COURSECAT:
+ case CONTEXT_COURSECAT:
$depth = $this->load_for_category();
break;
case CONTEXT_BLOCK:
- case CONTEXT_COURSE:
+ case CONTEXT_COURSE:
$depth = $this->load_for_course();
break;
case CONTEXT_MODULE:
$depth = $this->load_for_activity();
break;
- case CONTEXT_USER:
+ case CONTEXT_USER:
$depth = $this->load_for_user();
break;
}
*/
protected function format_display_course_content($format, $default=true) {
global $CFG;
- //
- //
+ //
+ //
$formatlib = $CFG->dirroot.'/course/format/'.$format.'/lib.php';
if (file_exists($formatlib)) {
require_once($formatlib);
$this->cache->canviewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->context);
}
$viewhiddenactivities = $this->cache->canviewhiddenactivities;
-
+
foreach ($modinfo->cms as $module) {
if ($module->sectionnum!='0' || (!$viewhiddenactivities && !$module->visible)) {
continue;
}
/**
* Internal function to load the activities within sections
- *
+ *
* @param array $keys By reference
*/
protected function load_section_activities(&$keys, $singlesectionid=false, $course=null) {
}
$module = $DB->get_record('modules', array('id'=>$PAGE->cm->module));
-
+
if (!$module) {
debugging('Invalid Module ID picked up while attempting to load the activity for the navigation', DEBUG_DEVELOPER);
return;
$function = $module->name.'_extend_navigation';
if (file_exists($file)) {
require_once($file);
- if (function_exists($function)) {
+ if (function_exists($function)) {
$function($node, $PAGE->course, $module, $PAGE->cm);
}
}
/**
* This function adds a category to the nav tree based on the categories path
- *
+ *
* @param stdClass $category
*/
protected function add_category_by_path($category) {
$blogsurls = new moodle_url($CFG->wwwroot.'/blog/index.php', array('courseid' => $filterselect));
$participants->add(get_string('blogs','blog'), $blogsurls->out());
}
-
+
if (!empty($CFG->enablenotes) && (has_capability('moodle/notes:manage', $this->context) || has_capability('moodle/notes:view', $this->context))) {
$participants->add(get_string('notes','notes'), new moodle_url($CFG->wwwroot.'/notes/index.php', array('filtertype'=>'course', 'filterselect'=>$filterselect)));
}
} else {
$sections = $this->cache->$coursesecstr;
}
-
+
if (!$this->cache->compare('modinfo'.$course->id, $course->modinfo, false)) {
$this->cache->{'modinfo'.$course->id} = get_fast_modinfo($course);
}
$this->add_category_by_path($category);
}
}
- }
+ }
$categories = $DB->get_records('course_categories', array('parent' => $categoryid), 'sortorder ASC');
$this->add_categories($keys, $categories);
- #$courses = $DB->get_records('course', array('category' => $categoryid), 'sortorder ASC', 'id,fullname,shortname,visible,category');
+ #$courses = $DB->get_records('course', array('category' => $categoryid), 'sortorder ASC', 'id,fullname,shortname,visible,category');
$this->add_courses($courses, $categoryid);
}
return 0;
}
$depth = 0;
switch ($type) {
- case self::TYPE_CATEGORY:
+ case self::TYPE_CATEGORY:
$depth = $this->load_category($instanceid);
break;
- case self::TYPE_COURSE:
+ case self::TYPE_COURSE:
$depth = $this->load_course($instanceid);
break;
- case self::TYPE_SECTION:
+ case self::TYPE_SECTION:
$depth = $this->load_section($instanceid);
break;
- case self::TYPE_ACTIVITY:
+ case self::TYPE_ACTIVITY:
$depth = $this->load_activity($instanceid);
break;
}
/**
* Use the instance id to load a course
- *
+ *
* {@link global_navigation::load_course()}
* @param int $instanceid
*/
protected function load_section($instanceid=0) {
global $DB, $PAGE, $CFG;
$section = $DB->get_record('course_sections', array('id'=>$instanceid));
-
+
if (!$section) {
echo "Invalid Course Section ID";
}
}
$modinfo = get_fast_modinfo($course);
-
+
$resources = array('resource', 'label');
if (!$this->cache->cached('canviewhiddenactivities')) {
$this->cache->canviewhiddenactivities = has_capability('moodle/course:viewhiddenactivities', $this->context);
}
$viewhiddenactivities = $this->cache->canviewhiddenactivities;
-
+
foreach ($modinfo->cms as $module) {
if ((!$viewhiddenactivities && !$module->visible) || $module->sectionnum != $section->section) {
continue;
// For screen readers
$output = get_accesshide(get_string('youarehere','access'), 'h2')."<ul>\n";
-
+
$customchildren = (count($this->children) > 0);
// Check if navigation contains the active node
if (!$this->ignoreactive) {
* root node class against all first level element
*
* It does this by first calling the parent's add method {@link navigation_node::add()}
- * and then proceeds to use the key to set class and hr
+ * and then proceeds to use the key to set class and hr
*
* @param string $text
* @param sting|moodle_url $url
}
$coursenode = $this->page->navigation->find_child($course->id, global_navigation::TYPE_COURSE);
-
+
$coursenodekey = $this->add(get_string('courseadministration'), null, $coursenode->type, null, 'courseadmin');
$coursenode = $this->get($coursenodekey);
-
+
if (has_capability('moodle/course:update', $course->context)) {
// Add the turn on/off settings
$url = new moodle_url($CFG->wwwroot.'/course/view.php', array('id'=>$course->id, 'sesskey'=>sesskey()));
$this->cache->{'coursesections'.$course->id} = get_all_sections($course->id);
}
$sections = $this->cache->{'coursesections'.$course->id};
-
+
$addresource = $this->get($this->add(get_string('addresource')));
$addactivity = $this->get($this->add(get_string('addactivity')));
if ($formatidentifier!==0) {
}
$resources = $this->cache->{'course'.$course->id.'resources'};
$activities = $this->cache->{'course'.$course->id.'activities'};
-
+
foreach ($sections as $section) {
if ($formatidentifier !== 0 && $section->section != $formatidentifier) {
continue;
$url = new moodle_url($CFG->wwwroot.'/course/edit.php', array('id'=>$course->id));
$coursenode->add(get_string('settings'), $url, self::TYPE_SETTING, null, null, $OUTPUT->old_icon_url('i/settings'));
}
-
+
// Add assign or override roles if allowed
if (has_capability('moodle/role:assign', $course->context)) {
$url = new moodle_url($CFG->wwwroot.'/'.$CFG->admin.'/roles/assign.php', array('contextid'=>$course->context->id));
$file = $CFG->dirroot.'/mod/'.$module->name.'/lib.php';
$function = $module->name.'_extend_settings_navigation';
-
+
if (file_exists($file)) {
require_once($file);
}
/**
* Loads the user settings block of the settings nav
- *
+ *
* This function is simply works out the userid and whether we need to load
- * just the current users profile settings, or the current user and the user the
+ * just the current users profile settings, or the current user and the user the
* current user is viewing.
- *
+ *
* This function has some very ugly code to work out the user, if anyone has
* any bright ideas please feel free to intervene.
*
const CACHEVALUE = 2;
/** @var null|array An array of navigation cache areas to expire on shutdown */
public static $volatilecaches;
-
+
/**
* Contructor for the cache. Requires two arguments
*
}
}
}
-}
\ No newline at end of file
+}
* Major Contributors:
* - Eloy Lafuente (stronk7) {@link http://contiento.com}
* - Petr Skoda (skodak)
- *
+ *
* @package moodlecore
* @copyright (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
function hide_screen_gridlines() {
// not implement
}
-
+
/**
* Insert a 24bit bitmap image in a worksheet.
*
<manifest:file-entry manifest:media-type="text/xml" manifest:full-path="meta.xml"/>
</manifest:manifest>';
}
-?>
*** To translate the combined Zone & Rule changes
*** in the Olson files to the Moodle single ruleset
*** format, we need to trasverse every year and see
- *** if either the Zone or the relevant Rule has a
+ *** if either the Zone or the relevant Rule has a
*** change. It's yuck but it yields a rationalized
*** set of data, which is arguably simpler.
***
*** Also note that I am starting at the epoch (1970)
*** because I don't think we'll see many events scheduled
- *** before that, anyway.
+ *** before that, anyway.
***
**/
$maxyear = localtime(time(), true);
*** Loop over years, only adding a rule when zone or rule
*** have changed. All loops preserver the last seen vars
*** until there's an explicit decision to delete them
- ***
- **/
+ ***
+ **/
// clean the slate for a new zone
$zone = NULL;
$rule = NULL;
-
+
//
// Find the pre 1970 zone rule entries
//
if (!empty($zone['rule']) && array_key_exists($zone['rule'], $rules)) {
$rule = NULL;
for ($y = 1970 ; $y > 0 ; $y--) {
- if (array_key_exists((string)$y, $rules[$zone['rule']] )) { // we have a rule entry for the year
+ if (array_key_exists((string)$y, $rules[$zone['rule']] )) { // we have a rule entry for the year
$rule = $rules[$zone['rule']][$y];
//print_object("Rule $rule[name] pre1970 is $y\n");
break; // Perl's last -- get outta here
}
-
- }
+
+ }
if (empty($rule)) {
- // Colombia and a few others refer to rules before they exist
- // Perhaps we should comment out this warning...
+ // Colombia and a few others refer to rules before they exist
+ // Perhaps we should comment out this warning...
// trigger_error("Cannot find rule in $zone[rule] <= 1970");
$rule = array();
}
// no DST this year!
$rule = array();
}
-
- // Prepare to insert the base 1970 zone+rule
+
+ // Prepare to insert the base 1970 zone+rule
if (!empty($rule) && array_key_exists($zone['rule'], $rules)) {
// merge the two arrays into the moodle rule
- unset($rule['name']); // warning: $rule must NOT be a reference!
+ unset($rule['name']); // warning: $rule must NOT be a reference!
unset($rule['year']);
$mdl_tz = array_merge($zone, $rule);
$mdl_tz = $zone;
// TODO: Add other default values here!
$mdl_tz['dstoff'] = 0;
- }
+ }
// Fix the from year to 1970
$mdl_tz['year'] = 1970;
///
/// 1971 onwards
- ///
+ ///
for ($y = 1971; $y < $maxyear ; $y++) {
$changed = false;
///
$changed = true;
$zone = $zbyyear[(string)$y];
}
- if (!empty($zone['rule']) && array_key_exists($zone['rule'], $rules)) {
+ if (!empty($zone['rule']) && array_key_exists($zone['rule'], $rules)) {
if (array_key_exists((string)$y, $rules[$zone['rule']])) {
$changed = true;
$rule = $rules[$zone['rule']][(string)$y];
//print_object("CHANGE YEAR $y Zone $zone[name] Rule $zone[rule]\n");
if (!empty($rule)) {
// merge the two arrays into the moodle rule
- unset($rule['name']);
+ unset($rule['name']);
unset($rule['year']);
$mdl_tz = array_merge($zone, $rule);
} else {
// just a simple zone
$mdl_tz = $zone;
- }
+ }
/*
if(isset($mdl_tz['dst_time']) && !strpos($mdl_tz['dst_time'], ':') || isset($mdl_tz['std_time']) && !strpos($mdl_tz['std_time'], ':')) {
$mdl_zones[] = $lasttimezone = $mdl_tz;
}
}
- }
-
+ }
+
}
- /*
+ /*
if (function_exists('memory_get_usage')) {
trigger_error("We are consuming this much memory: " . get_memory_usage());
}
/// Since Moodle 1.7, rule is tzrule in DB (reserved words problem), so change it here
/// after everything is calculated to be properly loaded to the timezone table.
/// Pre 1.7 users won't have the old rule if updating this from moodle.org but it
-/// seems that such field isn't used at all by the rest of Moodle (at least I haven't
+/// seems that such field isn't used at all by the rest of Moodle (at least I haven't
/// found any use when looking for it).
foreach($mdl_zones as $key=>$mdl_zone) {
$mdl_zones[$key]['tzrule'] = $mdl_zones[$key]['rule'];
}
-
+
return $mdl_zones;
}
*/
function olson_simple_rule_parser ($filename) {
- $file = fopen($filename, 'r', 0);
+ $file = fopen($filename, 'r', 0);
if (empty($file)) {
return false;
}
-
+
// determine the maximum year for this zone
$maxyear = array();
-
+
while ($line = fgets($file)) {
// only pay attention to rules lines
if(!preg_match('/^Rule\s/', $line)){
} else {
$maxyear[$name] = $from;
}
-
+
}
-
+
fseek($file, 0);
-
+
$rules = array();
while ($line = fgets($file)) {
// only pay attention to rules lines
fclose($file);
- $months = array('jan' => 1, 'feb' => 2,
- 'mar' => 3, 'apr' => 4,
+ $months = array('jan' => 1, 'feb' => 2,
+ 'mar' => 3, 'apr' => 4,
'may' => 5, 'jun' => 6,
- 'jul' => 7, 'aug' => 8,
- 'sep' => 9, 'oct' => 10,
+ 'jul' => 7, 'aug' => 8,
+ 'sep' => 9, 'oct' => 10,
'nov' => 11, 'dec' => 12);
$at,
$save,
$letter) = $rulesthisyear['set'];
-
+
$moodle_rule = array();
-
+
// $save is sometimes just minutes
// and othertimes HH:MM -- only
// parse if relevant
- if (!preg_match('/^\d+$/', $save)) {
+ if (!preg_match('/^\d+$/', $save)) {
list($hours, $mins) = explode(':', $save);
$save = $hours * 60 + $mins;
}
// we'll parse $at later
- // $at = olson_parse_at($at);
+ // $at = olson_parse_at($at);
$in = strtolower($in);
if(!isset($months[$in])) {
trigger_error('Unknown month: '.$in);
}
-
+
$moodle_rule['name'] = $name;
$moodle_rule['year'] = $year;
$moodle_rule['dstoff'] = $save; // time offset
$moodle_rule['dst_startday'] = $on['startday'];
$moodle_rule['dst_weekday'] = $on['weekday'];
$moodle_rule['dst_skipweeks'] = $on['skipweeks'];
-
+
// and now the "deactivate" data
list($discard,
$name,
$at,
$save,
$letter) = $rulesthisyear['reset'];
-
+
// we'll parse $at later
// $at = olson_parse_at($at);
$in = strtolower($in);
$moodle_rule['std_month'] = $months[$in]; // the month
$moodle_rule['std_time'] = $at; // the time
-
+
// Encode index and day as per Moodle's specs
$on = olson_parse_on($on);
$moodle_rule['std_startday'] = $on['startday'];
$moodle_rule['std_weekday'] = $on['weekday'];
$moodle_rule['std_skipweeks'] = $on['skipweeks'];
-
+
$moodle_rules[$moodle_rule['name']][$moodle_rule['year']] = $moodle_rule;
//print_object($moodle_rule);
// then we have to deal with closing the last rule
//trigger_error("Rule $name ending to $to");
if (!empty($to) && $to !== 'max') {
- // We can handle two cases for TO:
+ // We can handle two cases for TO:
// a year, or "only"
$reset_rule = $moodle_rule;
$reset_rule['dstoff'] = '00';
*/
function olson_simple_zone_parser ($filename) {
- $file = fopen($filename, 'r', 0);
+ $file = fopen($filename, 'r', 0);
if (empty($file)) {
return false;
}
-
+
$zones = array();
$lastzone = NULL;
***
*** We are transforming "until" fields into "from" fields
*** which make more sense from the Moodle perspective, so
- *** each initial Zone entry is "from" the year 0, and for the
+ *** each initial Zone entry is "from" the year 0, and for the
*** continuation lines, we shift the "until" from the previous field
*** into this line's "from".
***
*** I have no idea of how to create a DST rule out of that
*** (what are the start/end times?)
***
- *** We remove "until" from the data we keep, but preserve
+ *** We remove "until" from the data we keep, but preserve
*** it in $lastzone.
*/
if (preg_match('/^Zone/', $line)) { // a new zone
$discard // format
) = $line;
// the things we do to avoid warnings
- if (!empty($line[5])) {
+ if (!empty($line[5])) {
$zone['until'] = $line[5];
}
$zone['year'] = '0';
-
+
$zones[$zone['name']] = array();
- } else if (!empty($lastzone) && preg_match('/^\s+/', $line)){
- // looks like a credible continuation line
+ } else if (!empty($lastzone) && preg_match('/^\s+/', $line)){
+ // looks like a credible continuation line
$line = trim($line);
$line = preg_split('/\s+/', $line);
if (count($line) < 3) {
$discard // format
) = $line;
// the things we do to avoid warnings
- if (!empty($line[3])) {
+ if (!empty($line[3])) {
$zone['until'] = $line[3];
}
continue;
}
- // tidy up, we're done
+ // tidy up, we're done
// perhaps we should insert in the DB at this stage?
$lastzone = $zone;
unset($zone['until']);
if ($zone['rule'] === '-') { // cleanup empty rules
$zone['rule'] = '';
}
- if (preg_match('/:/',$zone['rule'])) {
+ if (preg_match('/:/',$zone['rule'])) {
// we are not handling direct SAVE rules here
// discard it
$zone['rule'] = '';
}
-
+
$zones[$zone['name']][(string)$zone['year']] = $zone;
}
*/
function olson_parse_offset ($offset) {
$offset = trim($offset);
-
+
// perhaps it's just minutes
if (preg_match('/^(-?)(\d*)$/', $offset)) {
return intval($offset);
}
- // (-)hours:minutes(:seconds)
+ // (-)hours:minutes(:seconds)
if (preg_match('/^(-?)(\d*):(\d+)/', $offset, $matches)) {
// we are happy to discard the seconds
$sign = $matches[1];
$seconds = intval($matches[3]);
$offset = $sign . ($hours*60 + $seconds);
return intval($offset);
- }
+ }
trigger_error('Strange time format in olson_parse_offset() ' .$offset);
return 0;
/**
* olson_parse_on_($on)
*
- * see `man zic`. This function translates the following formats
+ * see `man zic`. This function translates the following formats
* 5 the fifth of the month
* lastSun the last Sunday in the month
* lastMon the last Monday in the month
function olson_parse_on ($on) {
$rule = array();
- $days = array('sun' => 0, 'mon' => 1,
- 'tue' => 2, 'wed' => 3,
- 'thu' => 4, 'fri' => 5,
+ $days = array('sun' => 0, 'mon' => 1,
+ 'tue' => 2, 'wed' => 3,
+ 'thu' => 4, 'fri' => 5,
'sat' => 6);
if(is_numeric($on)) {
else {
trigger_error('unknown on '.$on);
}
- }
+ }
return $rule;
}
*
* @return string a moodle friendly $at, in GMT, which is what Moodle wants
*
- *
+ *
*/
function olson_parse_at ($at, $set = 'set', $gmtoffset) {
}
// Wall clock
- if (empty($sig) || $sig === 'w') {
+ if (empty($sig) || $sig === 'w') {
if ($set !== 'set'){ // wall clock is on DST, assume by 1hr
$hours = $hours-1;
- }
+ }
$sig = 's';
}
trigger_error('unhandled case - AT flag is ' . $matches[0]);
}
-
-
-?>
global $CFG;
parent::__construct('click', 'frame_breakout', array('framename'=>$CFG->framename));
}
-}
\ No newline at end of file
+}
* has been guessed, it will contain dangerous block-related actions.
* Therefore, the blocks code calls this function to clean up such parameters
* before doing any redirect.
- *
+ *
* @param string $param the name of the parameter to make sure is not in the
* page URL.
*/
echo $OUTPUT->header();
}
}
-
-?>
events_trigger('message_send', $eventdata);
}
}
-
-?>
var $c_stimes;
var $c_utimes;
var $mem;
-
+
/**
* Concatenates all the pprof files generated by apd_set_pprof_trace()
- * and returns the resulting string, which can then be processed by
+ * and returns the resulting string, which can then be processed by
* get_profiling();
* It also deletes these files once finished, in order to limit
* cluttering of the filesystem. This can be switched off by
* providing "false" as the only argument to this function.
- *
+ *
* WARNING: If you switch cleanup off, profiling data will
* accumulate from one pageload to the next.
*
{
global $CFG, $USER;
// List all files under our temporary directory
- $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
+ $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
if ($files = scandir($tempdir)) {
// Concatenate the files
- print_r($files);
+ print_r($files);
} else {
print "Error: Profiler could not read the directory $tempdir.";
return false;
}
-
+
// Return a handle to the resulting file
-
-
+
+
if(($DATA = fopen($dataFile, "r")) == FALSE) {
return "Failed to open $dataFile for reading\n";
}
/**
* Returns profiling information gathered using APD functions.
* Accepts a numerical array of command-line arguments.
- *
+ *
* Profiler::get_profiling($args)
* Sort options
* -a Sort by alphabetic names of subroutines.
* -T Display uncompressed call tree.
*
* Example array: array('-a', '-l');
- *
+ *
* @param Array $args
* @return String Profiling info
*/
function get_profiling($args)
- {
+ {
$con = new Console_Getopt;
array_shift($args);
-
+
$shortoptions = 'acg:hiIlmMrRsStTuUO:vzZ';
$retval = $con->getopt( $args, $shortoptions);
if(is_object($retval)) {
usage();
}
-
+
$opt['O'] = 20;
foreach ($retval[0] as $kv_array) {
$opt[$kv_array[0]] = $kv_array[1];
}
-
+
$DATA = Profiler::_get_pprofp();
$cfg = array();
Total System Time = %4.2f
Total User Time = %4.2f
", $cfg['caller'], $rtotal/1000000, $stotal/1000000, $utotal/1000000);
-
+
$retstring .= "\n
Real User System secs/ cumm
%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name
$cpercall = ($c_usecs)/$ncalls;
if($utotal) {
$pcnt = 100*$this->utimes[$j]/$utotal;
- }
+ }
else {
$pcnt = 100;
}
// $cpercall = ($c_usecs + $c_ssecs)/$ncalls;
$mem_usage = $this->mem[$j];
$name = $symbol_hash[$j];
- $retstring .= sprintf("%3.01f %2.02f %2.02f %2.02f %2.02f %2.02f %2.02f %4d %2.04f %2.04f %12d %s\n",
+ $retstring .= sprintf("%3.01f %2.02f %2.02f %2.02f %2.02f %2.02f %2.02f %4d %2.04f %2.04f %12d %s\n",
$pcnt, $rsecs, $c_rsecs, $usecs, $c_usecs, $ssecs, $c_ssecs, $ncalls, $percall, $cpercall, $mem_usage, $name);
return $retstring;
}
function by_calls($a, $b) {
return $this->num_cmp($this->calls[$b], $this->calls[$a]);
}
-
- function by_rtime($a,$b) {
+
+ function by_rtime($a,$b) {
return $this->num_cmp($this->rtimes[$b], $this->rtimes[$a]);
}
-
- function by_c_rtime($a,$b) {
- return $this->num_cmp($this->c_rtimes[$b], $this->c_rtimes[$a]);
+
+ function by_c_rtime($a,$b) {
+ return $this->num_cmp($this->c_rtimes[$b], $this->c_rtimes[$a]);
+ }
+
+ function by_stime($a,$b) {
+ return $this->num_cmp($this->stimes[$b], $this->stimes[$a]);
}
-
- function by_stime($a,$b) {
- return $this->num_cmp($this->stimes[$b], $this->stimes[$a]);
+
+ function by_c_stime($a,$b) {
+ return $this->num_cmp($this->c_stimes[$b], $this->c_stimes[$a]);
}
-
- function by_c_stime($a,$b) {
- return $this->num_cmp($this->c_stimes[$b], $this->c_stimes[$a]);
+
+ function by_utime($a,$b) {
+ return $this->num_cmp($this->utimes[$b], $this->utimes[$a]);
}
-
- function by_utime($a,$b) {
- return $this->num_cmp($this->utimes[$b], $this->utimes[$a]);
+
+ function by_c_utime($a,$b) {
+ return $this->num_cmp($this->c_utimes[$b], $this->c_utimes[$a]);
}
-
- function by_c_utime($a,$b) {
- return $this->num_cmp($this->c_utimes[$b], $this->c_utimes[$a]);
+
+ function by_mem($a, $b) {
+ return $this->num_cmp($this->mem[$b], $this->mem[$a]);
}
-
- function by_mem($a, $b) {
- return $this->num_cmp($this->mem[$b], $this->mem[$a]);
- }
}
-?>
/**
* Move one question type in a list of question types. If you try to move one element
* off of the end, nothing will change.
- *
+ *
* @param array $sortedqtypes An array $qtype => anything.
* @param string $tomove one of the keys from $sortedqtypes
* @param integer $direction +1 or -1
}
/**
- * Load the basic state information for
+ * Load the basic state information for
*
* @global object
* @param integer $attemptid the attempt id to load the states for.
* @return array an array of state data from the database, you will subsequently
* need to call question_load_states to get fully loaded states that can be
- * used by the question types. The states here should be sufficient for
+ * used by the question types. The states here should be sufficient for
* basic tasks like rendering navigation.
*/
function question_preload_states($attemptid) {
} else if ($states[$j]->grade > $question->maxgrade) {
$states[$j]->grade = $question->maxgrade;
$changed = true;
-
+
}
if (!$dryrun){
$error = question_process_comment($question, $replaystate, $attempt,
} else {
require_once($CFG->libdir .'/filelib.php');
$img = get_file_url("$coursefilesdir/{$question->image}");
- }
+ }
}
return $img;
}
// ULPGc ecastro
function question_get_random_guess_score($question) {
global $QTYPES;
-
+
$r = $QTYPES[$question->qtype]->get_random_guess_score($question);
return $r;
}
case CONTEXT_MODULE:
return $baseurl . 'cmid=' . $context->instanceid;
}
-
+
}
/**
return $returnstring;
}
-?>
function search_token($type,$value){
$this->type = $type;
$this->value = $this->sanitize($value);
-
+
}
// Try to clean up user input to avoid potential security issues.
- // Need to think about this some more.
+ // Need to think about this some more.
function sanitize($userstring){
return htmlspecialchars($userstring);
}
- function getValue(){
+ function getValue(){
return $this->value;
}
function getType(){
/**
* This class does the heavy lifting of lexing the search string into tokens.
- * Using a full-blown lexer is probably overkill for this application, but
+ * Using a full-blown lexer is probably overkill for this application, but
* might be useful for other tasks.
*
* @package moodlecore
// Patterns to handle strings of the form meta:foo
-
+
// If we see the string meta: while in the base accept state, start
// parsing a username and go to the inmeta state.
$this->addEntryPattern("subject:\S+","accept","inmeta");
// back to the base accept state.
$this->addExitPattern("\s","inmeta");
-
+
// Patterns to handle required exact match strings (+foo) .
// If we see a + sign while in the base accept state, start
// If we see a quote while in the base accept state, start
// parsing a quoted string and enter the inquotedstring state.
// Grab everything until we see the closing quote.
-
+
$this->addEntryPattern("\"[^\"]+","accept","inquotedstring");
// When we see a closing quote, reenter the base accept state.
$this->addExitPattern("\"","inquotedstring");
-
+
// Patterns to handle ordinary, nonquoted words.
-
+
// When we see non-whitespace, snarf everything into the nonquoted word
// until we see whitespace again.
$this->addEntryPattern("\S+","accept","plainstring");
// Once we see whitespace, reenter the base accept state.
$this->addExitPattern("\s","plainstring");
-
+
}
-}
+}
// State for handling meta:foo constructs. Potentially emits a token.
- function inmeta($content){
+ function inmeta($content){
if (strlen($content) < 9) { // Missing parameter.
return true;
}
// Strip off the + sign and add the reminder to the parsed token array.
$this->tokens[] = new search_token(TOKEN_EXACT,substr($content,1));
return true;
- }
+ }
- // State entered when we've seen an excluded string (-foo). Potentially
+ // State entered when we've seen an excluded string (-foo). Potentially
// emits a token.
function inexcluded($content){
if (strlen($content) < 2) { // State exit or missing parameter.
// Strip off the -sign and add the reminder to the parsed token array.
$this->tokens[] = new search_token(TOKEN_NEGATE,substr($content,1));
return true;
- }
+ }
// State entered when we've seen a quoted string. Potentially emits a token.
// Strip off the opening quote and add the reminder to the parsed token array.
$this->tokens[] = new search_token(TOKEN_STRING,substr($content,1));
return true;
- }
+ }
// State entered when we've seen an ordinary, non-quoted word. Potentially
// emits a token.
// Add the string to the parsed token array.
$this->tokens[] = new search_token(TOKEN_STRING,$content);
return true;
- }
+ }
}
/**
* Primitive function to generate a SQL string from a parse tree
* using TEXT indexes. If searches aren't suitable to use TEXT
* this function calls the default search_generate_SQL() one.
- *
- * $parsetree should be a parse tree generated by a
- * search_lexer/search_parser combination.
+ *
+ * $parsetree should be a parse tree generated by a
+ * search_lexer/search_parser combination.
* Other fields are database table names to search.
*
* @global object
}
/**
- * Primitive function to generate a SQL string from a parse tree.
- * Parameters:
+ * Primitive function to generate a SQL string from a parse tree.
+ * Parameters:
*
- * $parsetree should be a parse tree generated by a
- * search_lexer/search_parser combination.
+ * $parsetree should be a parse tree generated by a
+ * search_lexer/search_parser combination.
* Other fields are database table names to search.
*
* @global object
$name2 = 'sq'.$p++;
switch($type){
- case TOKEN_STRING:
+ case TOKEN_STRING:
$SQLString .= "(($datafield $LIKE :$name1) OR ($metafield $LIKE :$name2))";
$params[$name1] = "%$value%";
$params[$name2] = "%$value%";
break;
- case TOKEN_EXACT:
+ case TOKEN_EXACT:
$SQLString .= "(($datafield $REGEXP :$name1) OR ($metafield $REGEXP :$name2))";
$params[$name1] = "[[:<:]]".$value."[[:>:]]";
$params[$name2] = "[[:<:]]".$value."[[:>:]]";
- break;
- case TOKEN_META:
+ break;
+ case TOKEN_META:
if ($metafield != '') {
$SQLString .= "($metafield $LIKE :$name1)";
$params[$name1] = "%$value%";
}
break;
- case TOKEN_USER:
+ case TOKEN_USER:
$SQLString .= "(($mainidfield = $useridfield) AND (($userfirstnamefield $LIKE :$name1) OR ($userlastnamefield $LIKE :$name2)))";
$params[$name1] = "%$value%";
$params[$name2] = "%$value%";
- break;
- case TOKEN_USERID:
+ break;
+ case TOKEN_USERID:
$SQLString .= "($useridfield = :$name1)";
$params[$name1] = $value;
- break;
- case TOKEN_INSTANCE:
+ break;
+ case TOKEN_INSTANCE:
$SQLString .= "($instancefield = :$name1)";
$params[$name1] = $value;
- break;
- case TOKEN_DATETO:
+ break;
+ case TOKEN_DATETO:
$SQLString .= "($timefield <= :$name1)";
$params[$name1] = $value;
- break;
- case TOKEN_DATEFROM:
+ break;
+ case TOKEN_DATEFROM:
$SQLString .= "($timefield >= :$name1)";
$params[$name1] = $value;
- break;
- case TOKEN_NEGATE:
+ break;
+ case TOKEN_NEGATE:
$SQLString .= "(NOT (($datafield $LIKE :$name1) OR ($metafield $LIKE :$name2)))";
$params[$name1] = "%$value%";
$params[$name2] = "%$value%";
- break;
+ break;
default:
return '';
- }
- }
+ }
+ }
return array($SQLString, $params);
}
-
-
-?>
error('session test not reimplemented yet'); //DO NOT localize or use print_error()!
//
-//TODO: add code that actually tests moodle sessions, the old one only tested PHP sessions used from installer, not the real moodle sessions
+//TODO: add code that actually tests moodle sessions, the old one only tested PHP sessions used from installer, not the real moodle sessions
return (object)array('classes' => $classes, 'functions' => $functions);
}
-
-?>
function test($html) {
$parser = $this->load_xml($html);
$list = $parser->getElementsByTagName($this->tag);
-
+
foreach ($list as $node) {
if ($node->attributes->getNamedItem($this->attribute)->nodeValue == $this->value) {
return true;
return true;
}
}
-
+
return false;
}
return true;
}
}
-
+
return false;
}
/**
* Overriding update_record: If we are updating a record that was NOT inserted by unit tests,
* throw an exception and cancel update.
- *
+ *
* throws moodle_exception If trying to update a record not inserted by unit tests.
*/
public function update_record($table, $dataobject, $bulk=false) {
return UnitTestDB::$DB->get_field($table, $return, $conditions);
}
}
-?>
echo $wsdl;
exit;
}
-
-?>
/**
* Print daily cron progress
- * @param string $ident
+ * @param string $ident
*/
function stats_daily_progress($ident) {
static $start = 0;
) activity
INNER JOIN
(
- SELECT courseid, max(stat1) AS highest_enrolments
+ SELECT courseid, max(stat1) AS highest_enrolments
FROM {stats_'.$param->table.'}
- WHERE stattype=\'enrolments\' AND timeend >= '.$param->timeafter.' AND stat1 > '.$threshold.'
+ WHERE stattype=\'enrolments\' AND timeend >= '.$param->timeafter.' AND stat1 > '.$threshold.'
GROUP BY courseid
) enrolments
ON (activity.courseid = enrolments.courseid)
//return error as string
return get_string('statscatchupmode','error',$a);
}
-
-?>
}
return $this->download;
}
-
+
function export_class_instance(&$exportclass=null){
if (!is_null($exportclass)){
$this->started_output = true;
}
return $this->exportclass;
}
-
-
+
+
/**
* Probably don't need to call this directly. Calling is_downloading with a
* param automatically sets table as downloadable.
* This function is not part of the public api.
*/
function print_initials_bar(){
- if ((!empty($this->sess->i_last) || !empty($this->sess->i_first) || $this->use_initials)
+ if ((!empty($this->sess->i_last) || !empty($this->sess->i_first) || $this->use_initials)
&& isset($this->columns['fullname'])) {
$strall = get_string('all');
* object from which to export data.
*/
var $table;
-
+
/**
* @var boolean output started. Keeps track of whether any output has been
* started yet.
function table_default_export_format_parent(&$table){
$this->table =& $table;
}
-
+
function set_table(&$table){
$this->table =& $table;
}
$this->table->start_html();
}
-
+
function output_headers($headers){
$this->table->print_headers();
}
return format_text($text, $format, $options);
}
}
-?>
return implode(' ', $words);
}
}
-?>
<?php
-//
-// NOTICE OF COPYRIGHT
-//
-// Original code:
-//
-// Drupal - The copyright of both the Drupal software and the
-// "Druplicon" logo belongs to all the original authors,
-// though both are licensed under the GPL.
-// http://drupal.org
-//
-// Modifications:
-//
-// Moodle - Modular Object-Oriented Dynamic Learning Environment
-// http://moodle.com
-//
+//
+// NOTICE OF COPYRIGHT
+//
+// Original code:
+//
+// Drupal - The copyright of both the Drupal software and the
+// "Druplicon" logo belongs to all the original authors,
+// though both are licensed under the GPL.
+// http://drupal.org
+//
+// Modifications:
+//
+// Moodle - Modular Object-Oriented Dynamic Learning Environment
+// http://moodle.com
+//
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
-//
+//
/**
* Based on Drupal's search.module version 1.224
* This function process the text passed at input, extracting all the tokens
* and scoring each one based in their number of ocurrences and relation with
* some well-known html tags
- *
+ *
* @param string $text the text to be tokenised.
- * @param array $stop_words array of utf-8 words than can be ignored in
+ * @param array $stop_words array of utf-8 words than can be ignored in
* the text being processed. There are some cool lists of
* stop words at http://snowball.tartarus.org/
* @param boolean $overlap_cjk option to split CJK text into some overlapping
$textlib = textlib_get_instance();
$text = $textlib->substr($text, 0, MAXIMUM_WORD_SIZE);
}
-
-?>
/**
* Array to hold local copies of stuff in $_FILES
- * @var array $files
+ * @var array $files
*/
var $files;
/**
* Holds all configuration stuff
- * @var array $config
+ * @var array $config
*/
var $config;
/**
/**
* The course this file has been uploaded for. {@link $COURSE}
* (for logging and virus notifications)
- * @var course $course
+ * @var course $course
*/
var $course;
/**
* If we're only getting one file.
* (for logging and virus notifications)
- * @var string $inputname
+ * @var string $inputname
*/
var $inputname;
/**
- * If we're given silent=true in the constructor, this gets built
+ * If we're given silent=true in the constructor, this gets built
* up to hold info about the process.
- * @var string $notify
+ * @var string $notify
*/
var $notify;
* @param boolean $allownullmultiple Whether we care if there's no files AT ALL when we've got multiples. This won't complain if we have file 1 and file 3 but not file 2, only for NO FILES AT ALL.
*/
function upload_manager($inputname='', $deleteothers=false, $handlecollisions=false, $course=null, $recoverifmultiple=false, $modbytes=0, $silent=false, $allownull=false, $allownullmultiple=true) {
-
+
global $CFG, $SITE;
if (empty($course->id)) {
$course = $SITE;
}
-
+
$this->config->deleteothers = $deleteothers;
$this->config->handlecollisions = $handlecollisions;
$this->config->recoverifmultiple = $recoverifmultiple;
$this->config->silent = $silent;
$this->config->allownull = $allownull;
$this->files = array();
- $this->status = false;
+ $this->status = false;
$this->course = $course;
$this->inputname = $inputname;
if (empty($this->inputname)) {
$this->config->allownull = $allownullmultiple;
}
}
-
- /**
+
+ /**
* Gets all entries out of $_FILES and stores them locally in $files and then
- * checks each one against {@link get_max_upload_file_size()} and calls {@link cleanfilename()}
+ * checks each one against {@link get_max_upload_file_size()} and calls {@link cleanfilename()}
* and scans them for viruses etc.
* @uses $CFG
* @uses $_FILES
$this->status = $this->validate_file($this->files[$name]); // default to only allowing empty on multiple uploads.
if (!$this->status && ($this->files[$name]['error'] == 0 || $this->files[$name]['error'] == 4) && ($this->config->allownull || empty($this->inputname))) {
// this shouldn't cause everything to stop.. modules should be responsible for knowing which if any are compulsory.
- continue;
+ continue;
}
if ($this->status && !empty($CFG->runclamonupload)) {
$this->status = clam_scan_moodle_file($this->files[$name],$this->course);
return true;
}
- /**
+ /**
* Moves all the files to the destination directory.
*
* @uses $CFG
*/
function save_files($destination) {
global $CFG, $USER, $OUTPUT;
-
+
if (!$this->status) { // preprocess_files hasn't been run
$this->preprocess_files();
}
$this->status = false;
return false;
}
-
+
$destination = $CFG->dataroot .'/'. $destination; // now add it back in so we have a full path
$exceptions = array(); //need this later if we're deleting other files.
}
return $this->status;
}
-
+
/**
* Wrapper function that calls {@link preprocess_files()} and {@link viruscheck_files()} and then {@link save_files()}
* Modules that require the insert id in the filepath should not use this and call these functions seperately in the required order.
* @parameter string $destination Where to save the uploaded files to.
* @return boolean
- */
+ */
function process_file_uploads($destination) {
if ($this->preprocess_files()) {
return $this->save_files($destination);
return false;
}
- /**
+ /**
* Deletes all the files in a given directory except for the files in $exceptions (full paths)
*
* @param string $destination The directory to clean up.
}
}
}
-
+
/**
* Handles filename collisions - if the desired filename exists it will rename it according to the pattern in $format
* @param string $destination Destination directory (to check existing files against)
$a->newname = $file['name'];
$file['uploadlog'] .= "\n". get_string('uploadrenamedcollision','moodle', $a);
}
-
+
/**
* This function checks a potential filename against what's on the filesystem already and what's been saved already.
* @param string $destination Destination directory (to check existing files against)
* @todo Finish documenting this function
*/
function get_file_upload_error(&$file) {
-
+
switch ($file['error']) {
case 0: // UPLOAD_ERR_OK
if ($file['size'] > 0) {
$errmessage = get_string('uploadnofilefound'); /// probably a dud file name
}
break;
-
+
case 1: // UPLOAD_ERR_INI_SIZE
$errmessage = get_string('uploadserverlimit');
break;
-
+
case 2: // UPLOAD_ERR_FORM_SIZE
$errmessage = get_string('uploadformlimit');
break;
-
+
case 3: // UPLOAD_ERR_PARTIAL
$errmessage = get_string('uploadpartialfile');
break;
-
+
case 4: // UPLOAD_ERR_NO_FILE
$errmessage = get_string('uploadnofilefound');
break;
-
+
// Note: there is no error with a value of 5
case 6: // UPLOAD_ERR_NO_TMP_DIR
}
return $errmessage;
}
-
+
/**
* prints a log of everything that happened (of interest) to each file in _FILES
* @param $return - optional, defaults to false (log is echoed)
return false;
}
- /**
+ /**
* If we're only handling one file (if input name was given in the constructor) this will return the full path to the saved file.
* @return boolean
*/
return false;
}
- /**
+ /**
* If we're only handling one file (if inputname was given in the constructor) this will return the ORIGINAL filename of the file.
* @return boolean
*/
return false;
}
- /**
+ /**
* This function returns any errors wrapped up in red.
* @return string
*/
* @param int $modbytes $coursebytes and $maxbytes are used to calculate upload max size ( using {@link get_max_upload_file_size})
* @param boolean $return -Whether to return the string (defaults to false - string is echoed)
* @return string Form returned as string if $return is true
- */
+ */
function upload_print_form_fragment($numfiles=1, $names=null, $descriptions=null, $uselabels=false, $labelnames=null, $coursebytes=0, $modbytes=0, $return=false) {
global $CFG;
$maxbytes = get_max_upload_file_size($CFG->maxbytes, $coursebytes, $modbytes);
/**
- * Deals with an infected file - either moves it to a quarantinedir
+ * Deals with an infected file - either moves it to a quarantinedir
* (specified in CFG->quarantinedir) or deletes it.
*
* If moving it fails, it deletes it.
* @return string Details of what the function did.
*/
function clam_handle_infected_file($file, $userid=0, $basiconly=false) {
-
+
global $CFG, $USER;
if ($USER && !$userid) {
$userid = $USER->id;
$delete = true;
if (file_exists($CFG->quarantinedir) && is_dir($CFG->quarantinedir) && is_writable($CFG->quarantinedir)) {
$now = date('YmdHis');
- if (rename($file, $CFG->quarantinedir .'/'. $now .'-user-'. $userid .'-infected')) {
+ if (rename($file, $CFG->quarantinedir .'/'. $now .'-user-'. $userid .'-infected')) {
$delete = false;
clam_log_infected($file, $CFG->quarantinedir.'/'. $now .'-user-'. $userid .'-infected', $userid);
if ($basiconly) {
*
* The replacement string is used to notify that the original file had a virus
* This is to avoid missing files but could result in the wrong content-type.
- *
+ *
* @param string $file Full path to the file.
* @return boolean
*/
* @param mixed $file The file to scan from $files. or an absolute path to a file.
* @param course $course {@link $COURSE}
* @return int 1 if good, 0 if something goes wrong (opposite from actual error code from clam)
- */
+ */
function clam_scan_moodle_file(&$file, $course) {
global $CFG, $USER;
if (is_array($file) && is_uploaded_file($file['tmp_name'])) { // it's from $_FILES
- $appendlog = true;
+ $appendlog = true;
$fullpath = $file['tmp_name'];
}
else if (file_exists($file)) { // it's a path to somewhere on the filesystem!
if ($CFG->clamfailureonupload == 'actlikevirus') {
$notice .= "\n". get_string('clamlostandactinglikevirus');
$notice .= "\n". clam_handle_infected_file($fullpath);
- $newreturn = false;
+ $newreturn = false;
}
clam_message_admins($notice);
if ($appendlog) {
}
return $newreturn; // return 1 if we're allowing clam failures
}
-
+
$cmd = $CFG->pathtoclam .' '. $fullpath ." 2>&1";
-
+
// before we do anything we need to change perms so that clamscan can read the file (clamdscan won't work otherwise)
chmod($fullpath,0644);
-
+
exec($cmd, $output, $return);
-
-
+
+
switch ($return) {
case 0: // glee! we're ok.
return 1; // translate clam return code into reasonable return code consistent with everything else.
$info->user = fullname($USER);
$notice = get_string('virusfound', 'moodle', $info);
$notice .= "\n\n". implode("\n", $output);
- $notice .= "\n\n". clam_handle_infected_file($fullpath);
+ $notice .= "\n\n". clam_handle_infected_file($fullpath);
clam_message_admins($notice);
if ($appendlog) {
$info->filename = $file['originalname'];
$file['virus'] = 1;
}
return false; // in this case, 0 means bad.
- default:
+ default:
// error - clam failed to run or something went wrong
$notice .= get_string('clamfailed', 'moodle', get_clam_error_code($return));
$notice .= "\n\n". implode("\n", $output);
* @param string $notice The body of the email to be sent.
*/
function clam_message_admins($notice) {
-
+
$site = get_site();
-
+
$subject = get_string('clamemailsubject', 'moodle', format_string($site->fullname));
$admins = get_admins();
foreach ($admins as $admin) {
$returncodes[58] = 'I/O error, please check your filesystem.';
$returncodes[59] = 'Can\'t get information about current user from /etc/passwd.';
$returncodes[60] = 'Can\'t get information about user \'clamav\' (default name) from /etc/passwd.';
- $returncodes[61] = 'Can\'t fork.';
+ $returncodes[61] = 'Can\'t fork.';
$returncodes[63] = 'Can\'t create temporary files/directories (check permissions).';
$returncodes[64] = 'Can\'t write to temporary directory (please specify another one).';
$returncodes[70] = 'Can\'t allocate and clear memory (calloc).';
global $DB;
add_to_log(0, 'upload', 'infected', $_SERVER['HTTP_REFERER'], $oldfilepath, 0, $userid);
-
+
$user = $DB->get_record('user', array('id'=>$userid));
-
+
$errorstr = 'Clam AV has found a file that is infected with a virus. It was uploaded by '
. ((empty($user)) ? ' an unknown user ' : fullname($user))
- . ((empty($oldfilepath)) ? '. The infected file was caught on upload ('.$oldfilepath.')'
+ . ((empty($oldfilepath)) ? '. The infected file was caught on upload ('.$oldfilepath.')'
: '. The original file path of the infected file was '. $oldfilepath)
. ((empty($newfilepath)) ? '. The file has been deleted ' : '. The file has been moved to a quarantine directory and the new path is '. $newfilepath);
*
* @global object
* @param string $oldpath The old path to the file (should be in the log)
- * @param string $newpath The new path to the file
+ * @param string $newpath The new path to the file
* @param boolean $update If true this function will overwrite old record (used for forum moving etc).
*/
function clam_change_log($oldpath, $newpath, $update=true) {
global $DB;
-
+
if (!$record = $DB->get_record('log', array('info'=>$oldpath, 'module'=>'upload'))) {
return false;
}
$DB->insert_record('log', $record);
}
}
-?>
*
* I used rfc #2396 URI: Generic Syntax as my guide when creating the
* regular expression. For all the details see the comments below.
- *
+ *
* Usage:
* validateUrlSyntax( url_to_check[, options])
- *
+ *
* url_to_check - string - The url to check
*
* options - string - A optional string of options to set which parts of
$aOptions[$key] = '';
}
}
-
+
// DEBUGGING - Unescape following line to display to screen current option values
// echo '<pre>'; print_r($aOptions); echo '</pre>';
$unreserved = '[a-zA-Z0-9_.!~*' . '\'' . '()-]';
$escaped = '(%[0-9a-fA-F]{2})'; // Escape sequence - In Hex - %6d would be a 'm'
$reserved = '[;/?:@&=+$,]'; // Special characters in the URI
-
+
// Beginning Regular Expression
// Scheme - Allows for 'http://', 'https://', 'mailto:', or 'ftp://'
$scheme = '(';
}
$scheme .= ')' . $aOptions['s'];
// End setting scheme
-
+
// User Info - Allows for 'username@' or 'username:password@'. Note: contrary to rfc, I removed ':' from username section, allowing it only in password.
// /---------------- Username -----------------------\ /-------------------------------- Password ------------------------------\
$userinfo = '((' . $unreserved . '|' . $escaped . '|[;&=+$,]' . ')+(:(' . $unreserved . '|' . $escaped . '|[;:&=+$,]' . ')+)' . $aOptions['P'] . '@)' . $aOptions['u'];
-
+
// IP ADDRESS - Allows 0.0.0.0 to 255.255.255.255
$ipaddress = '((((2(([0-4][0-9])|(5[0-5])))|([01]?[0-9]?[0-9]))\.){3}((2(([0-4][0-9])|(5[0-5])))|([01]?[0-9]?[0-9])))';
-
+
// Tertiary Domain(s) - Optional - Multi - Although some sites may use other characters, the RFC says tertiary domains have the same naming restrictions as second level domains
$domain_tertiary = '(' . $alphanum . '(([a-zA-Z0-9-]{0,62})' . $alphanum . ')?\.)*';
$domain_toplevel = '([a-zA-Z](([a-zA-Z0-9-]*)[a-zA-Z0-9])?)';
/* // Top Level Domain - Required - Domain List Current As Of December 2004. Use above escaped line to be forgiving of possible future TLD's
$domain_toplevel = '(aero|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|post|pro|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ax|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)';
-*/
+*/
// Address can be IP address or Domain
if ($aOptions['I'] === '{0}') { // IP Address Not Allowed
$address = '((' . $ipaddress . ')|(' . $domain_tertiary . /* MDL-9295 $domain_secondary . */ $domain_toplevel . '))';
}
$address = $address . $aOptions['a'];
-
+
// Port Number - :80 or :8080 or :65534 Allows range of :0 to :65535
// (0-59999) |(60000-64999) |(65000-65499) |(65500-65529) |(65530-65535)
$port_number = '(:(([0-5]?[0-9]{1,4})|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5])))' . $aOptions['p'];
-
+
// Path - Can be as simple as '/' or have multiple folders and filenames
$path = '(/((;)?(' . $unreserved . '|' . $escaped . '|' . '[:@&=+$,]' . ')+(/)?)*)' . $aOptions['f'];
-
+
// Query Section - Accepts ?var1=value1&var2=value2 or ?2393,1221 and much more
$querystring = '(\?(' . $reserved . '|' . $unreserved . '|' . $escaped . ')*)' . $aOptions['q'];
-
+
// Fragment Section - Accepts anchors such as #top
$fragment = '(#(' . $reserved . '|' . $unreserved . '|' . $escaped . ')*)' . $aOptions['r'];
-
-
+
+
// Building Regular Expression
$regexp = '^' . $scheme . $userinfo . $address . $port_number . $path . $querystring . $fragment . '$';
-
+
// DEBUGGING - Uncomment Line Below To Display The Regular Expression Built
// echo '<pre>' . htmlentities(wordwrap($regexp,70,"\n",1)) . '</pre>';
return validateUrlSyntax( $ftpaddr, $newoptions);
} // END Function validateFtpSyntax()
-
-?>
*/
/**#@+
- * state defines
+ * state defines
*/
define( "STATE_NONE",1 ); // blank line has been detected, so looking for first line on next para
define( "STATE_PARAGRAPH",2 ); // currently processing vanilla paragraph
function close_block( $state ) {
// provide appropriate closure for block according to state
-
+
// if in list close this first
$lclose = "";
if ($this->list_state != LIST_NONE) {
break;
case STATE_NOTIKI:
$sclose = "\n";
- break;
+ break;
}
return $lclose . $sclose;
function do_list( $line, $blank=false ) {
// handle line with list character on it
// if blank line implies drop to level 0
-
+
// get magic character and then delete it from the line if not blank
if ($blank) {
$listchar="";
$count = strspn( $line, $listchar );
$line = eregi_replace( "^[".$listchar."]+ ", "", $line );
}
-
+
// find what sort of list this character represents
$list_tag = "";
$list_close_tag = "";
$item_tag = "<dt>";
$item_close_tag = "</dt>";
$list_style = LIST_DEFINITION;
- break;
- }
+ break;
+ }
// tag opening/closing regime now - fun bit :-)
$tags = "";
// get indent
$indent = substr( " ",1,$count-1 );
-
+
if ($blank) {
$newline = $tags;
}
- else {
+ else {
$newline = $tags . $indent . "$item_tag " . $line . "$item_close_tag";
}
return $newline;
- }
+ }
function line_replace( $line ) {
// return line after various formatting replacements
// have been made - order is vital to stop them interfering with each other
-
+
global $CFG;
-
+
// ---- (at least) means a <hr />
// MARKDOWN: no change so leave
- // is this a list line (starts with * # ; :)
+ // is this a list line (starts with * # ; :)
if (eregi( "^([*]+|[#]+|[;]+|[:]+) ", $line )) {
- $line = $this->do_list( $line );
- }
+ $line = $this->do_list( $line );
+ }
// typographic conventions
// MARKDOWN: no equiv. so convert to entity as before
$line = str_replace( "1/4", "¼", $line );
$line = str_replace( "1/2", "½", $line );
$line = str_replace( "3/4", "¾", $line );
- $line = eregi_replace( "([[:digit:]]+[[:space:]]*)x([[:space:]]*[[:digit:]]+)", "\\1×\\2", $line ); // (digits) x (digits) - multiply
+ $line = eregi_replace( "([[:digit:]]+[[:space:]]*)x([[:space:]]*[[:digit:]]+)", "\\1×\\2", $line ); // (digits) x (digits) - multiply
// do formatting tags
- // NOTE: The / replacement *has* to be first, or it will screw the
+ // NOTE: The / replacement *has* to be first, or it will screw the
// HTML tags that are added by the other ones
// MARKDOWN: only bold and italic change, rest are just HTML
$line = $this->do_replace_markdown( $line, "\*", "**" );
$line = $this->do_replace_sub( $line, "\^", "sup" );
$line = $this->do_replace( $line, "%", "code" );
$line = $this->do_replace( $line, "@", "cite" );
-
+
// convert urls into proper link with optional link text URL(text)
// MARDOWN: HTML conversion should work fine
$line = eregi_replace("([[:space:]]|^)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])\(([^)]+)\)",
"\\1[\\5](\\2://\\3\\4)", $line);
- $line = eregi_replace("([[:space:]])www\.([^[:space:]]*)([[:alnum:]#?/&=])\(([^)]+)\)",
+ $line = eregi_replace("([[:space:]])www\.([^[:space:]]*)([[:alnum:]#?/&=])\(([^)]+)\)",
"\\1[\\5](http://www.\\2\\3)", $line);
// make urls (with and without httpd) into proper links
$line = eregi_replace("([[:space:]]|^)([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])",
"\\1<\\2://\\3\\4>", $line);
- $line = eregi_replace("([[:space:]])www\.([^[:space:]]*)([[:alnum:]#?/&=])",
+ $line = eregi_replace("([[:space:]])www\.([^[:space:]]*)([[:alnum:]#?/&=])",
"\\1<http://www.\\2\\3\>", $line);
// make email addresses into mailtos....
require_once($CFG->libdir.'/filelib.php');
$coursefileurl = get_file_url($this->courseid);
- // Replace picture resource link
+ // Replace picture resource link
$line = eregi_replace( "/([a-zA-Z0-9./_-]+)(png|gif|jpg)\(([^)]+)\)",
"", $line );
$buffer = $buffer . $this->line_replace($line) . "\n";
$this->block_state = STATE_PREFORM;
}
- else
+ else
if (eregi("^\% ",$line) ) {
// preformatted text - no processing
// MARKDOWN: this is MD code form of a paragraph
else {
// ordinary paragraph
$buffer = $buffer . $this->line_replace($line) . "\n";
- $this->block_state = STATE_PARAGRAPH;
+ $this->block_state = STATE_PARAGRAPH;
}
continue;
}
// close off any block level tags
$buffer = $buffer . $this->close_block( $this->block_state );
- //return $buffer;
+ //return $buffer;
return $buffer;
}
}
-?>