Source for file general.php
Documentation is available at general.php
* Sloodle general library.
* Provides various utility functionality for general Sloodle purposes.
* @copyright Copyright (c) 2007-8 Sloodle (various contributors)
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU GPL v3
* @contributor Edmund Edgar
* @contributor Peter R. Bloomfield
// This library expects that the Sloodle config file has already been included
// (along with the Moodle libraries)
/** Include our email functionality. */
require_once(SLOODLE_LIBROOT.
'/mail.php');
* Sets a Sloodle configuration value.
* This data will be stored in Moodle's "config" table, so it will persist even after Sloodle is uninstalled.
* After being set, it will be available (read-only) as a named member of Moodle's $CFG variable.
* <b>NOTE:</b> in Sloodle debug mode, this function will terminate the script with an error if the name is not prefixed with "sloodle_".
* @param string $name The name of the value to be stored (should be prefixed with "sloodle_")
* @param string $value The string representation of the value to be stored
* @return bool True on success, or false on failure (may fail if database query encountered an error)
* @see sloodle_get_config()
// If in debug mode, ensure the name is prefixed appropriately for Sloodle
exit ("ERROR: sloodle_set_config(..) called with invalid value name \"$name\". Expected \"sloodle_\" prefix.");
// Use the standard Moodle config function, ignoring the 3rd parameter ("plugin", which defaults to NULL)
* Gets a Sloodle configuration value from Moodle's "config" table.
* This function does not necessarily need to be used.
* All configuration data is available as named members of Moodle's $CFG global variable.
* <b>NOTE:</b> in Sloodle debug mode, this function will terminate the script with an error if the name is not prefixed with "sloodle_".
* @param string $name The name of the value to be stored (should be prefixed with "sloodle_")
* @return mixed A string containing the configuration value, or false if the query failed (e.g. if the named value didn't exist)
* @see sloodle_set_config()
// If in debug mode, ensure the name is prefixed appropriately for Sloodle
exit ("ERROR: sloodle_get_config(..) called with invalid value name \"$name\". Expected \"sloodle_\" prefix.");
// Use the Moodle config function, ignoring the plugin parameter
// Older Moodle versions return a database record object instead of the value itself
* Determines whether or not auto-registration is allowed for the site.
* @return bool True if auto-reg is allowed on the site, or false otherwise.
* Determines whether or not auto-enrolment is allowed for the site.
* @return bool True if auto-enrolment is allowed on the site, or false otherwise.
* Sends an XMLRPC message into Second Life.
* @param string $channel A string containing a UUID identifying the XMLRPC channel in SL to be used
* @param int $intval An integer value to be sent in the message
* @param string $strval A string value to be sent in the message
* @return bool True if successful, or false if an error occurs
// Include our XMLRPC library
// Instantiate a new client object for communicating with Second Life
$client =
new xmlrpc_client("http://xmlrpc.secondlife.com/cgi-bin/xmlrpc.cgi");
// Construct the content of the RPC
$content =
'<?xml version="1.0"?><methodCall><methodName>llRemoteData</methodName><params><param><value><struct><member><name>Channel</name><value><string>'.
$channel.
'</string></value></member><member><name>IntValue</name><value><int>'.
$intval.
'</int></value></member><member><name>StringValue</name><value><string>'.
$strval.
'</string></value></member></struct></value></param></params></methodCall>';
// Attempt to send the data via http
$response =
$client->send(
//var_dump($response); // Debug output
// Make sure we got a response value
if (!isset
($response->val) ||
empty($response->val) ||
is_null($response->val)) {
// Report an error if we are in debug mode
print
'<p align="left">Not getting the expected XMLRPC response. Is Second Life broken again?<br/>';
if (isset
($response->errstr)) print
"XMLRPC Error - ".
$response->errstr;
// Check the contents of the response value
//if (defined('SLOODLE_DEBUG') && SLOODLE_DEBUG) {
// print_r($response->val);
//TODO: Check the details of the response to see if this was successful or not...
* @todo <b>May require update?</b>
function sloodle_add_to_log($courseid =
null, $module =
null, $action =
null, $url =
null, $cmid =
null, $info =
null)
// TODO: Make sure we set this in the calling function, then remove this bit
$courseid =
optional_param('sloodle_courseid',0,PARAM_RAW);
// if no action is specified, use the object name
$action =
$_SERVER['X-SecondLife-Object-Name'];
$region =
$_SERVER['X-SecondLife-Region'];
if (preg_match('/^(.*)\(.*?\)$/',$region,$matches)) { // strip the coordinates, eg. Cicero (123,123)
$xyz =
$_SERVER['X-SecondLife-Local-Position'];
if (preg_match('/^\((.*?),(.*?),(.*?)\)$/',$xyz,$matches)) {
$xyz =
$matches[1].
'/'.
$matches[2].
'/'.
$matches[3];
return add_to_log($courseid, null, $action, $CFG->wwwroot.
'/mod/sloodle/toslurl.php?region='.
urlencode($region).
'&xyz='.
$xyz, $userid, $info );
//return add_to_log($courseid, null, "ok", "ok", $userid, "ok");
* Determines whether or not Sloodle is installed.
* Queries Moodle's modules table for a Sloodle entry.
* <b>NOTE:</b> does not check for the presence of the Sloodle files.
* @return bool True if Sloodle is installed, or false otherwise.
// Is there a Sloodle entry in the modules table?
return record_exists('modules', 'name', 'sloodle');
* Generates a random login security token.
* Uses mixed-case letters and numbers to generate a random 16-character string.
* @see sloodle_random_web_password()
// Define the characters we can use in our token, and get the length of it
$str =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Prepare the token variable
// Loop once for each output character
for($length =
0; $length <
16; $length++
) {
// Shuffle the string, then pick and store a random character
* Generates a random web password
* Uses mixed-case letters and numbers to generate a random 8-character string.
* @see sloodle_random_security_token()
// Define the characters we can use in our token, and get the length of it
$str =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Prepare the password string
// Loop once for each output character
for($length =
0; $length <
8; $length++
) {
// Shuffle the string, then pick and store a random character
* Generates a random prim password (7 to 9 digit number).
* @return string The password as a string
return (string)
mt_rand(1000000, 999999999);
* Converts a string vector to an array vector.
* String vector should be of format "<x,y,z>".
* Converts to associative array with members 'x', 'y', and 'z'.
* Returns false if input parameter was not of correct format.
* @param string $vector A string vector of format "<x,y,z>".
* @see sloodle_array_to_vector()
* @see sloodle_round_vector()
if (preg_match('/<(.*?),(.*?),(.*?)>/',$vector,$vectorbits)) {
$arr['x'] =
$vectorbits[1];
$arr['y'] =
$vectorbits[2];
$arr['z'] =
$vectorbits[3];
* Converts an array vector to a string vector.
* Array vector should be associative, containing elements 'x', 'y', and 'z'.
* Converts to a string vector of format "<x,y,z>".
* @see sloodle_vector_to_array()
* @see sloodle_round_vector()
$ret =
'<'.
$arr['x'].
','.
$arr['y'].
','.
$arr['z'].
'>';
* Obtains the identified course module instance database record.
* @param int $id The integer ID of a course module instance
* @return mixed A database record if successful, or false if it could not be found
return get_record('course_modules', 'id', $id);
* Determines whether or not the specified course module instance is visible.
* Checks that the instance itself and the course section are both valid.
* @param int $id The integer ID of a course module instance.
* @return bool True if visible, or false if invisible or not found
// Get the course module instance record, whether directly from the parameter, or from the database
$course_module_instance =
$id;
if (!($course_module_instance =
get_record('course_modules', 'id', $id))) return FALSE;
// Make sure the instance itself is visible
if ((int)
$course_module_instance->visible ==
0) return FALSE;
// Find out which section it is in, and if that section is valid
if (!($section =
get_record('course_sections', 'id', $course_module_instance->section))) return FALSE;
if ((int)
$section->visible ==
0) return FALSE;
// Looks like the module is visible
* Determines if the specified course module instance is of the named type.
* For example, this can check if a particular instance is a "forum" or a "chat".
* @param int $id The integer ID of a course module instance
* @param string $module_name Module type to check (must be the exact name of an installed module, e.g. 'sloodle' or 'quiz')
* @return bool True if the module is of the specified type, or false otherwise
// Get the record for the module type
if (!($module_record =
get_record('modules', 'name', $module_name))) return FALSE;
// Get the course module instance record, whether directly from the parameter, or from the database
$course_module_instance =
$id;
if (!($course_module_instance =
get_record('course_modules', 'id', $id))) return FALSE;
// Check the type of the instance
return ($course_module_instance->module ==
$module_record->id);
* Obtains the ID number of the specified module (type not instance).
* @param string $name The name of the module type to check, e.g. 'sloodle' or 'forum'
* @return mixed Integer containing module ID, or false if it is not installed
// Ensure the name is a non-empty string
if (!is_string($name) ||
empty($name)) return FALSE;
// Obtain the module record
if (!($module_record =
get_record('modules', 'name', $module_name))) return FALSE;
return $module_record->id;
* Checks if the specified position is in the current (site-wide) loginzone.
* @param mixed $pos A string vector or an associated array vector
* @return bool True if position is in LoginZone, or false if not
* @see sloodle_login_zone_coordinates()
* @todo Update or remove... no longer valid
// Get a position array from the parameter
// Fetch the loginzone boundaries
list
($maxarr,$minarr) =
sloodle_login_zone_coordinates();
// Make sure the position is not past the maximum bounds
if ( ($posarr['x'] >
$maxarr['x']) ||
($posarr['y'] >
$maxarr['y']) ||
($posarr['z'] >
$maxarr['z']) ) {
// Make sure the position is not past the minimum bounds
if ( ($posarr['x'] <
$minarr['x']) ||
($posarr['y'] <
$minarr['y']) ||
($posarr['z'] <
$minarr['z']) ) {
* Generates teleport coordinates for a user who has already finished the LoginZone process.
* @param string $pos A string vector giving the position of the LoginZone
* @param string $size A string vector giving the size of the LoginZone
* @return array, bool An associative array vector containing a teleport location, or false if the operation fails.
// Make sure the parameters are valid types
// Convert both to arrays
// Calculate a position just below the loginzone
$coord['x'] =
round($posarr['x'],0);
$coord['y'] =
round($posarr['y'],0);
$coord['z'] =
round(($posarr['z']-
(($sizearr['z'])/
2)-
2),0);
* Generates a random position within a cuboid zone of the specified size.
* (Note: leaves a 2 metre margin round the outside)
* @param array $size Associative array giving the size of the zone
* @return array An associative vector array
// Construct the half-size array
$halfsize =
array('x'=>
($size['x'] /
2.0) -
2.0, 'y'=>
($size['y'] /
2.0) -
2.0, 'z'=>
($size['z'] /
2.0) -
2.0);
$pos['x'] =
mt_rand(0.0, $size['x'] -
4.0) -
$halfsize['x'];
$pos['y'] =
mt_rand(0.0, $size['y'] -
4.0) -
$halfsize['y'];
$pos['z'] =
mt_rand(0.0, $size['z'] -
4.0) -
$halfsize['z'];
// Round the specified 3d vector to integer values
// $pos should be a vector string "<x,y,z>" or an associative array {x,y,z}
// Return is the same as the type passed-in
// If the input type is unrecognised, it simply returns it back out unchanged
* Rounds the specified 3d vector integer values.
* Can handle/return a string vector, or an array vector.
* (Output type matches input type).
* @param mixed $pos Either a string vector or an array vector
// We will work with an array, but allow for conversion to/from string
// Construct an output array
foreach ($arrayvec as $key =>
$val) {
$output[$key] =
round($val, 0);
// If we need to convert it back to a string, then do so
* Calculates the maximum and minimum bounds of the specified LoginZone
* Returns the bounds as a numeric array of two associate array vectors: ($max, $min).
* (Or returns false if no LoginZone position/size could be found in the Moodle configuration table).
* @param string $pos A string vector giving the position of the LoginZone
* @param string $size A string vector giving the size of the LoginZone
// Make sure the parameters are valid types
if (($pos ==
FALSE) ||
($size ==
FALSE)) {
// Convert both to arrays
$max['x'] =
$posarr['x']+
(($sizearr['x'])/
2)-
2;
$max['y'] =
$posarr['y']+
(($sizearr['y'])/
2)-
2;
$max['z'] =
$posarr['z']+
(($sizearr['z'])/
2)-
2;
$min['x'] =
$posarr['x']-
(($sizearr['x'])/
2)+
2;
$min['y'] =
$posarr['y']-
(($sizearr['y'])/
2)+
2;
$min['z'] =
$posarr['z']-
(($sizearr['z'])/
2)+
2;
* Checks if the given prim password is valid.
* @param string $password The password string to check
* @return bool True if it is valid, or false otherwise.
// Check that it's a string
if ($len <
5 ||
$len >
9) return false;
// Check that it's all numbers
// Check that it doesn't start with a 0
if ($password[0] ==
'0') return false;
* Checks if the given prim password is valid, and provides feedback.
* An array is written to by reference, each element containing error codes.
* Each error code is a word. The full text of the error message may be obtained
* from the string file by looking for "primpass:errorcode".
* @param string $password The password to validate
* @param array &$errors An array (passed by reference) which will contain any error messages
* @return bool True if the prim password is valid, or false otherwise
// Check that it's a string
$errors[] =
'invalidtype';
// Check that it's all numbers
// Check that it doesn't start with a 0
if ($password[0] ==
'0') {
$errors[] =
'leadingzero';
* Stores a pending login notification for an auto-registered user.
* A cron job will process the pending notification queue.
* @param string $destination Identifies the destination of the notification (for SL, this will be the object UUID. The send function will construct the email address)
* @param string $avatar Identifier for the avatar being notified
* @param string $username The username to notify the user of
* @param string $password The (plaintext) password to notify the user of
* @return bool True if successful, or false otherwise
// If another pending notification already exists for the same username, then delete it
delete_records('sloodle_login_notifications', 'username', $username);
$notification =
new stdClass();
$notification->destination =
$destination;
$notification->avatar =
$avatar;
$notification->username =
$username;
$notification->password =
$password;
if (!insert_record('sloodle_login_notifications', $notification)) {
* Send a login notification.
* @param string $destination Identifies the destination of the notification (for SL, this will be the object UUID. The target email address will be constructed)
* @param string $avatar Identifier for the avatar being notified
* @param string $username The username to notify the user of
* @param string $password The (plaintext) password to notify the user of
* @return bool True if successful, or false otherwise
return sloodle_text_email_sl($destination, 'SLOODLE_LOGIN', "$avatar|{$CFG->wwwroot}|
$username|
$password");
* Processes pending login notifications, up to a certain limit.
* Retrieves the requests one-at-a-time for processing.
* This is slower, but ensures minimal damage if the process is terminated, e.g. due to server timeout.
* @param int $limit The maximum number of pending requests to process.
for ($i =
0; $i <
$limit; $i++
) {
// Obtain the first record
$recs =
get_records('sloodle_login_notifications', '', '', 'id', '*', 0, $limit);
if (!$recs) return false;
// Determine the user ID of the person who requested this
if (!($sloodleuser =
get_record('sloodle_users', 'uuid', $rec->avatar))) {
// Failed to the user - get the guest user instead
$guestdata =
guest_user();
$userid =
$guestdata->id;
// Got the data - store the user ID
$userid =
$sloodleuser->userid;
add_to_log(SITEID, 'sloodle', 'view', '', 'Sent login details by email to avatar in-world', 0, $userid);
// Log the failed notification (but don't keep trying the same one)
add_to_log(SITEID, 'sloodle', 'view failed', '', 'Failed to send login details by email to avatar in-world', 0, $userid);
// Delete the record from the data
delete_records('sloodle_login_notifications', 'id', $rec->id);
* Extracts a value from a name-value associative array if it is set.
* (The array should associate name to value).
* @param array $settings The array of names and values
* @param string $name The name of the value to retrieve
* @param mixed $default The default value to return if the specified value was not found
* @return mixed The value from the input array, or the $default parameter
if (is_array($settings) && isset
($settings[$name])) return $settings[$name];
* Outputs the standard form elements for access levels in object configuration.
* Each part can be optionally hidden, and default values can be provided.
* (Note: the server access level must be communicated from the object back to Moodle... rubbish implementation, but it works!)
* @param array $current_config An associative array of setting names to values, containing defaults. (Ignored if null).
* @param bool $show_use_object Determines whether or not the "Use Object" setting is shown
* @param bool $show_control_object Determines whether or not the "Control Object" setting is shown
* @param bool $show_server Determines whether or not the server access setting is shown
// Quick-escape: if everything is being suppressed, then do nothing
if (!($show_use_object ||
$show_control_object ||
$show_server)) return;
// Fetch default values from the configuration, if possible
// Define our object access level array
// Define our server access level array
// Display box and a heading
print_box_start('generalbox boxaligncenter');
echo
'<h3>'.
get_string('accesslevel','sloodle').
'</h3>';
// Print the object settings
if ($show_use_object ||
$show_control_object) {
echo
'<b>'.
get_string('accesslevelobject','sloodle').
'</b><br><i>'.
get_string('accesslevelobject:desc','sloodle').
'</i><br><br>';
echo
get_string('accesslevelobject:use','sloodle').
': ';
choose_from_menu($object_access_levels, 'sloodleobjectaccessleveluse', $sloodleobjectaccessleveluse, '');
if ($show_control_object) {
echo
get_string('accesslevelobject:control','sloodle').
': ';
choose_from_menu($object_access_levels, 'sloodleobjectaccesslevelctrl', $sloodleobjectaccesslevelctrl, '');
// Print the server settings
echo
'<b>'.
get_string('accesslevelserver','sloodle').
'</b><br><i>'.
get_string('accesslevelserver:desc','sloodle').
'</i><br><br>';
echo
get_string('accesslevel','sloodle').
': ';
choose_from_menu($server_access_levels, 'sloodleserveraccesslevel', $sloodleserveraccesslevel, '');
Documentation generated on Mon, 16 Jun 2008 15:56:21 +0100 by phpDocumentor 1.4.0