"; $ALLOWED_PROTOCOLS = array('http', 'https', 'ftp', 'news', 'mailto', 'rtsp', 'teamspeak', 'gopher', 'color'); /// Functions function s($var) { /// returns $var with HTML characters (like "<", ">", etc.) properly quoted, if (empty($var)) { return ""; } return htmlSpecialChars(stripslashes_safe($var)); } function p($var) { /// prints $var with HTML characters (like "<", ">", etc.) properly quoted, if (empty($var)) { echo ""; } echo htmlSpecialChars(stripslashes_safe($var)); } function nvl(&$var, $default="") { /// if $var is undefined, return $default, otherwise return $var return isset($var) ? $var : $default; } function strip_querystring($url) { /// takes a URL and returns it without the querystring portion if ($commapos = strpos($url, '?')) { return substr($url, 0, $commapos); } else { return $url; } } function get_referer() { /// returns the URL of the HTTP_REFERER, less the querystring portion return strip_querystring(nvl($_SERVER["HTTP_REFERER"])); } function me() { /// returns the name of the current script, WITH the querystring portion. /// this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME /// return different things depending on a lot of things like your OS, Web /// server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.) if (!empty($_SERVER["REQUEST_URI"])) { return $_SERVER["REQUEST_URI"]; } else if (!empty($_SERVER["PHP_SELF"])) { if (!empty($_SERVER["QUERY_STRING"])) { return $_SERVER["PHP_SELF"]."?".$_SERVER["QUERY_STRING"]; } return $_SERVER["PHP_SELF"]; } else if (!empty($_SERVER["SCRIPT_NAME"])) { if (!empty($_SERVER["QUERY_STRING"])) { return $_SERVER["SCRIPT_NAME"]."?".$_SERVER["QUERY_STRING"]; } return $_SERVER["SCRIPT_NAME"]; } else if (!empty($_SERVER["URL"])) { // May help IIS (not well tested) if (!empty($_SERVER["QUERY_STRING"])) { return $_SERVER["URL"]."?".$_SERVER["QUERY_STRING"]; } return $_SERVER["URL"]; } else { notify("Warning: Could not find any of these web server variables: \$REQUEST_URI, \$PHP_SELF, \$SCRIPT_NAME or \$URL"); return false; } } function qualified_me() { /// like me() but returns a full URL if (!empty($_SERVER["HTTP_HOST"])) { $hostname = $_SERVER["HTTP_HOST"]; } else if (!empty($_ENV["HTTP_HOST"])) { $hostname = $_ENV["HTTP_HOST"]; } else if (!empty($_SERVER["SERVER_NAME"])) { $hostname = $_SERVER["SERVER_NAME"]; } else if (!empty($_ENV["SERVER_NAME"])) { $hostname = $_ENV["SERVER_NAME"]; } else { notify("Warning: could not find the name of this server!"); return false; } $protocol = (isset($_SERVER["HTTPS"]) and $_SERVER["HTTPS"] == "on") ? "https://" : "http://"; $url_prefix = $protocol.$hostname; return $url_prefix . me(); } function match_referer($goodreferer = "") { /// returns true if the referer is the same as the goodreferer. If /// goodreferer is not specified, use qualified_me as the goodreferer global $CFG; if (empty($CFG->secureforms)) { // Don't bother checking referer return true; } if ($goodreferer == "nomatch") { // Don't bother checking referer return true; } if (empty($goodreferer)) { $goodreferer = qualified_me(); } $referer = get_referer(); return (($referer == $goodreferer) or ($referer == "$CFG->wwwroot/")); } function data_submitted($url="") { /// Used on most forms in Moodle to check for data /// Returns the data as an object, if it's found. /// This object can be used in foreach loops without /// casting because it's cast to (array) automatically /// /// Checks that submitted POST data exists, and also /// checks the referer against the given url (it uses /// the current page if none was specified. global $CFG; if (empty($_POST)) { return false; } else { if (match_referer($url)) { return (object)$_POST; } else { if ($CFG->debug > 10) { notice("The form did not come from this page! (referer = ".get_referer().")"); } return false; } } } function stripslashes_safe($string) { /// stripslashes() removes ALL backslashes even from strings /// so C:\temp becomes C:temp ... this isn't good. /// The following should work as a fairly safe replacement /// to be called on quoted AND unquoted strings (to be sure) $string = str_replace("\\'", "'", $string); $string = str_replace('\\"', '"', $string); //$string = str_replace('\\\\', '\\', $string); // why? return $string; } function break_up_long_words($string, $maxsize=20, $cutchar=' ') { /// Given some normal text, this function will break up any /// long words to a given size, by inserting the given character if (in_array(current_language(), array('ja', 'zh_cn', 'zh_tw', 'zh_tw_utf8'))) { // Multibyte languages return $string; } $output = ''; $length = strlen($string); $wordlength = 0; for ($i=0; $i<$length; $i++) { $char = $string[$i]; if ($char == ' ' or $char == "\t" or $char == "\n" or $char == "\r") { $wordlength = 0; } else { $wordlength++; if ($wordlength > $maxsize) { $output .= $cutchar; $wordlength = 0; } } $output .= $char; } return $output; } if (!function_exists('str_ireplace')) { /// Only exists in PHP 5 function str_ireplace($find, $replace, $string) { /// This does a search and replace, ignoring case /// This function is only used for versions of PHP older than version 5 /// which do not have a native version of this function. /// Taken from the PHP manual, by bradhuizenga @ softhome.net if (!is_array($find)) { $find = array($find); } if(!is_array($replace)) { if (!is_array($find)) { $replace = array($replace); } else { // this will duplicate the string into an array the size of $find $c = count($find); $rString = $replace; unset($replace); for ($i = 0; $i < $c; $i++) { $replace[$i] = $rString; } } } foreach ($find as $fKey => $fItem) { $between = explode(strtolower($fItem),strtolower($string)); $pos = 0; foreach($between as $bKey => $bItem) { $between[$bKey] = substr($string,$pos,strlen($bItem)); $pos += strlen($bItem) + strlen($fItem); } $string = implode($replace[$fKey],$between); } return ($string); } } if (!function_exists('stripos')) { /// Only exists in PHP 5 function stripos($haystack, $needle, $offset=0) { /// This function is only used for versions of PHP older than version 5 /// which do not have a native version of this function. /// Taken from the PHP manual, by dmarsh @ spscc.ctc.edu return strpos(strtoupper($haystack), strtoupper($needle), $offset); } } function read_template($filename, &$var) { /// return a (big) string containing the contents of a template file with all /// the variables interpolated. all the variables must be in the $var[] array or /// object (whatever you decide to use). /// /// WARNING: do not use this on big files!! $temp = str_replace("\\", "\\\\", implode(file($filename), "")); $temp = str_replace('"', '\"', $temp); eval("\$template = \"$temp\";"); return $template; } function checked(&$var, $set_value = 1, $unset_value = 0) { /// if variable is set, set it to the set_value otherwise set it to the /// unset_value. used to handle checkboxes when you are expecting them from /// a form if (empty($var)) { $var = $unset_value; } else { $var = $set_value; } } function frmchecked(&$var, $true_value = "checked", $false_value = "") { /// prints the word "checked" if a variable is true, otherwise prints nothing, /// used for printing the word "checked" in a checkbox form input if ($var) { echo $true_value; } else { echo $false_value; } } function link_to_popup_window ($url, $name="popup", $linkname="click here", $height=400, $width=500, $title="Popup window", $options="none", $return=false) { /// This will create a HTML link that will work on both /// Javascript and non-javascript browsers. /// Relies on the Javascript function openpopup in javascript.php /// $url must be relative to home page eg /mod/survey/stuff.php global $CFG; if ($options == "none") { $options = "menubar=0,location=0,scrollbars,resizable,width=$width,height=$height"; } $fullscreen = 0; $link = "wwwroot$url\" ". "onClick=\"return openpopup('$url', '$name', '$options', $fullscreen);\">$linkname\n"; if ($return) { return $link; } else { echo $link; } } function button_to_popup_window ($url, $name="popup", $linkname="click here", $height=400, $width=500, $title="Popup window", $options="none") { /// This will create a HTML link that will work on both /// Javascript and non-javascript browsers. /// Relies on the Javascript function openpopup in javascript.php /// $url must be relative to home page eg /mod/survey/stuff.php global $CFG; if ($options == "none") { $options = "menubar=0,location=0,scrollbars,resizable,width=$width,height=$height"; } $fullscreen = 0; echo "\n"; } function close_window_button() { /// Prints a simple button to close a window echo "\n"; echo "\n"; echo "\n"; echo "<---\n"; echo "\n"; echo "\n"; } function choose_from_menu ($options, $name, $selected="", $nothing="choose", $script="", $nothingvalue="0", $return=false) { /// Given an array of value, creates a popup menu to be part of a form /// $options["value"]["label"] if ($nothing == "choose") { $nothing = get_string("choose")."..."; } if ($script) { $javascript = "onChange=\"$script\""; } else { $javascript = ""; } $output = "\n"; if ($nothing) { $output .= " $label) { $output .= " has to go for example) // * Code it in a way that doesn't require JS to be on. Example code: // $selector .= ''; // $selector .= ''; // if(!empty($morevars)) { // $getarray = explode('&', $morevars); // foreach($getarray as $thisvar) { // $selector .= ''; // } // } // $selector .= ''; // foreach($options as $id => $text) { // $selector .= "\nid == $selected) { // $selector .= ' selected'; // } // $selector .= '>'.$text."\n"; // } // $selector .= ''; // $selector .= ' '; // $selector .= ''; // $selector .= ''; // global $CFG; if (empty($options)) { return ''; } if ($nothing == "choose") { $nothing = get_string("choose")."..."; } $startoutput = "framename}\" name=\"$formname\">"; $output = "\n"; if ($nothing != "") { $output .= " $nothing\n"; } foreach ($options as $value => $label) { if (substr($label,0,2) == "--") { $output .= " "; // Plain labels continue; } else { $output .= " $error"; } } function validate_email ($address) { /// Validates an email to make sure it makes sense. return (ereg('^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+'. '@'. '[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.'. '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$', $address)); } function get_file_argument($scriptname) { /// returns file argument global $_SERVER; $relativepath = FALSE; // first try normal parameter (compatible method == no relative links!) $relativepath = optional_param('file', FALSE, PARAM_PATH); // then try extract file from PATH_INFO (slasharguments method) if (!$relativepath and !empty($_SERVER['PATH_INFO'])) { $path_info = $_SERVER['PATH_INFO']; // check that PATH_INFO works == must not contain the script name if (!strpos($path_info, $scriptname)) { $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH); if ($relativepath === '/test') { print_header(); notice ('Slasharguments work - using PATH_INFO parameter :-D'); print_footer(); die; } } } // now if both fail try the old way // (for compatibility with misconfigured or older buggy php implementations) if (!$relativepath) { $arr = explode($scriptname, me()); if (!empty($arr[1])) { $path_info = strip_querystring($arr[1]); $relativepath = clean_param(rawurldecode($path_info), PARAM_PATH); if ($relativepath === '/test') { print_header(); notice ('Slasharguments work - using compatibility hack :-|'); print_footer(); die; } } } return $relativepath; } function detect_munged_arguments($string, $allowdots=1) { if (substr_count($string, '..') > $allowdots) { // Sometimes we allow dots in references return true; } if (ereg('[\|\`]', $string)) { // check for other bad characters return true; } if (empty($string) or $string == '/') { return true; } return false; } function get_slash_arguments($file="file.php") { /// Searches the current environment variables for some slash arguments if (!$string = me()) { return false; } $pathinfo = explode($file, $string); if (!empty($pathinfo[1])) { return addslashes($pathinfo[1]); } else { return false; } } function parse_slash_arguments($string, $i=0) { /// Extracts arguments from "/foo/bar/something" /// eg http://mysite.com/script.php/foo/bar/something if (detect_munged_arguments($string)) { return false; } $args = explode("/", $string); if ($i) { // return just the required argument return $args[$i]; } else { // return the whole array array_shift($args); // get rid of the empty first one return $args; } } function format_text_menu() { /// Just returns an array of formats suitable for a popup menu return array (FORMAT_MOODLE => get_string("formattext"), FORMAT_HTML => get_string("formathtml"), FORMAT_PLAIN => get_string("formatplain"), FORMAT_WIKI => get_string("formatwiki"), FORMAT_MARKDOWN => get_string("formatmarkdown")); } function format_text($text, $format=FORMAT_MOODLE, $options=NULL, $courseid=NULL ) { /// Given text in a variety of format codings, this function returns /// the text as safe HTML. /// /// $text is raw text (originally from a user) /// $format is one of the format constants, defined above global $CFG, $course; if (!empty($CFG->cachetext)) { $time = time() - $CFG->cachetext; $md5key = md5($text); if ($cacheitem = get_record_select('cache_text', "md5key = '$md5key' AND timemodified > '$time'")) { return $cacheitem->formattedtext; } } if (empty($courseid)) { if (!empty($course->id)) { // An ugly hack for better compatibility $courseid = $course->id; } } $CFG->currenttextiscacheable = true; // Default status - can be changed by any filter switch ($format) { case FORMAT_HTML: replace_smilies($text); if (!isset($options->noclean)) { $text = clean_text($text, $format); } $text = filter_text($text, $courseid); break; case FORMAT_PLAIN: $text = htmlentities($text); $text = rebuildnolinktag($text); $text = str_replace(" ", " ", $text); $text = nl2br($text); break; case FORMAT_WIKI: $text = wiki_to_html($text,$courseid); $text = rebuildnolinktag($text); if (!isset($options->noclean)) { $text = clean_text($text, $format); } $text = filter_text($text, $courseid); break; case FORMAT_MARKDOWN: $text = markdown_to_html($text); if (!isset($options->noclean)) { $text = clean_text($text, $format); } replace_smilies($text); $text = filter_text($text, $courseid); break; default: // FORMAT_MOODLE or anything else if (!isset($options->smiley)) { $options->smiley=true; } if (!isset($options->para)) { $options->para=true; } if (!isset($options->newlines)) { $options->newlines=true; } $text = text_to_html($text, $options->smiley, $options->para, $options->newlines); if (!isset($options->noclean)) { $text = clean_text($text, $format); } $text = filter_text($text, $courseid); break; } if (!empty($CFG->cachetext) and $CFG->currenttextiscacheable) { $newrecord->md5key = $md5key; $newrecord->formattedtext = addslashes($text); $newrecord->timemodified = time(); @insert_record('cache_text', $newrecord); } return $text; } function format_text_email($text, $format) { /// Given text in a variety of format codings, this function returns /// the text as plain text suitable for plain email. /// /// $text is raw text (originally from a user) /// $format is one of the format constants, defined above switch ($format) { case FORMAT_PLAIN: return $text; break; case FORMAT_WIKI: $text = wiki_to_html($text); /// This expression turns links into something nice in a text format. (Russell Jungwirth) /// From: http://php.net/manual/en/function.eregi-replace.php and simplified $text = eregi_replace('(]*>([^<]*))','\\3 [ \\2 ]', $text); return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES))); break; case FORMAT_HTML: return html_to_text($text); break; case FORMAT_MOODLE: case FORMAT_MARKDOWN: default: $text = eregi_replace('(]*>([^<]*))','\\3 [ \\2 ]', $text); return strtr(strip_tags($text), array_flip(get_html_translation_table(HTML_ENTITIES))); break; } } function filter_text($text, $courseid=NULL) { /// Given some text in HTML format, this function will pass it /// through any filters that have been defined in $CFG->textfilterx /// The variable defines a filepath to a file containing the /// filter function. The file must contain a variable called /// $textfilter_function which contains the name of the function /// with $courseid and $text parameters global $CFG; if (!empty($CFG->textfilters)) { $textfilters = explode(',', $CFG->textfilters); foreach ($textfilters as $textfilter) { if (is_readable("$CFG->dirroot/$textfilter/filter.php")) { include_once("$CFG->dirroot/$textfilter/filter.php"); $functionname = basename($textfilter).'_filter'; if (function_exists($functionname)) { $text = $functionname($courseid, $text); } } } } return $text; } function clean_text($text, $format=FORMAT_MOODLE) { /// Given raw text (eg typed in by a user), this function cleans it up /// and removes any nasty tags that could mess up Moodle pages. global $ALLOWED_TAGS; switch ($format) { case FORMAT_PLAIN: return $text; default: /// Remove tags that are not allowed $text = strip_tags($text, $ALLOWED_TAGS); /// Remove script events $text = eregi_replace("([^a-z])language([[:space:]]*)=", "\\1Xlanguage=", $text); $text = eregi_replace("([^a-z])on([a-z]+)([[:space:]]*)=", "\\1Xon\\2=", $text); /// Clean up embedded scripts and , using kses $text = cleanAttributes($text); return $text; } } function cleanAttributes($str){ /// This function takes a string and examines it for html tags. /// If tags are detected it passes the string to a helper function cleanAttributes2 /// which checks for attributes and filters them for malicious content /// 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie $result = preg_replace( '%(<[^>]*(>|$)|>)%me', #search for html tags "cleanAttributes2('\\1')", $str ); return $result; } function cleanAttributes2($htmlTag){ /// This function takes a string with an html tag and strips out any unallowed /// protocols e.g. javascript: /// It calls ancillary functions in kses which are prefixed by kses /// 17/08/2004 :: Eamon DOT Costello AT dcu DOT ie global $CFG, $ALLOWED_PROTOCOLS; require_once("$CFG->libdir/kses.php"); $htmlTag = kses_stripslashes($htmlTag); if (substr($htmlTag, 0, 1) != '<') { return '>'; //a single character ">" detected } if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $htmlTag, $matches)) { return ''; // It's seriously malformed } $slash = trim($matches[1]); //trailing xhtml slash $elem = $matches[2]; //the element name $attrlist = $matches[3]; // the list of attributes as a string $attrArray = kses_hair($attrlist, $ALLOWED_PROTOCOLS); $attStr = ''; foreach ($attrArray as $arreach) { $attStr .= ' '.strtolower($arreach['name']).'="'.$arreach['value'].'" '; } $xhtml_slash = ''; if (preg_match('%/\s*$%', $attrlist)) { $xhtml_slash = ' /'; } return "<$slash$elem$attStr$xhtml_slash>"; } function replace_smilies(&$text) { /// Replaces all known smileys in the text with image equivalents global $CFG; /// this builds the mapping array only once static $runonce = false; static $e = array(); static $img = array(); static $emoticons = array( ':-)' => 'smiley', ':)' => 'smiley', ':-D' => 'biggrin', ';-)' => 'wink', ':-/' => 'mixed', 'V-.' => 'thoughtful', ':-P' => 'tongueout', 'B-)' => 'cool', '^-)' => 'approve', '8-)' => 'wideeyes', ':o)' => 'clown', ':-(' => 'sad', ':(' => 'sad', '8-.' => 'shy', ':-I' => 'blush', ':-X' => 'kiss', '8-o' => 'surprise', 'P-|' => 'blackeye', '8-[' => 'angry', 'xx-P' => 'dead', '|-.' => 'sleepy', '}-]' => 'evil', ); if ($runonce == false) { /// After the first time this is not run again foreach ($emoticons as $emoticon => $image){ $alttext = get_string($image, 'pix'); $e[] = $emoticon; $img[] = "pixpath/s/$image.gif\" />"; } $runonce = true; } // Exclude from transformations all the code inside \n"; } else { echo "\n"; } echo "\n"; echo "\n"; echo "\n"; if ($rows < 10) { $rows = 10; } if ($cols < 65) { $cols = 65; } } echo ""; p($value); echo "\n"; } function print_richedit_javascript($form, $name, $source="no") { /// Legacy function, provided for backward compatability use_html_editor($name); } function use_html_editor($name="") { /// Sets up the HTML editor on textareas in the current page. /// If a field name is provided, then it will only be /// applied to that field - otherwise it will be used /// on every textarea in the page. /// /// In most cases no arguments need to be supplied echo "\n"; } function update_course_icon($courseid) { // Used to be an icon, but it's now a simple form button global $CFG, $USER; if (isteacheredit($courseid)) { if (!empty($USER->editing)) { $string = get_string("turneditingoff"); $edit = "off"; } else { $string = get_string("turneditingon"); $edit = "on"; } return "framename\" method=\"get\" action=\"$CFG->wwwroot/course/view.php\">". "". "". ""; } } function update_module_button($moduleid, $courseid, $string) { // Prints the editing button on a module "view" page global $CFG, $USER; if (isteacheredit($courseid)) { $string = get_string("updatethis", "", $string); return "framename\" method=\"get\" action=\"$CFG->wwwroot/course/mod.php\">". "". "". "sesskey\" />". ""; } else { return ""; } } function update_category_button($categoryid) { // Prints the editing button on a category page global $CFG, $USER; if (iscreator()) { if (!empty($USER->categoryediting)) { $string = get_string("turneditingoff"); $edit = "off"; } else { $string = get_string("turneditingon"); $edit = "on"; } return "framename\" method=\"get\" action=\"$CFG->wwwroot/course/category.php\">". "". "". "sesskey\" />". ""; } } function update_categories_button() { // Prints the editing button on categories listing global $CFG, $USER; if (isadmin()) { if (!empty($USER->categoriesediting)) { $string = get_string("turneditingoff"); $edit = "off"; } else { $string = get_string("turneditingon"); $edit = "on"; } return "framename\" method=\"get\" action=\"$CFG->wwwroot/course/index.php\">". "". "sesskey\" />". ""; } } function update_group_button($courseid, $groupid) { // Prints the editing button on group page global $CFG, $USER; if (isteacheredit($courseid)) { $string = get_string('editgroupprofile'); return "framename\" method=\"get\" action=\"$CFG->wwwroot/course/group.php\">". "". "". "". ""; } } function update_groups_button($courseid) { // Prints the editing button on groups page global $CFG, $USER; if (isteacheredit($courseid)) { if (!empty($USER->groupsediting)) { $string = get_string("turneditingoff"); $edit = "off"; } else { $string = get_string("turneditingon"); $edit = "on"; } return "framename\" method=\"get\" action=\"$CFG->wwwroot/course/groups.php\">". "". "". ""; } } function print_group_menu($groups, $groupmode, $currentgroup, $urlroot) { /// Prints an appropriate group selection menu /// Add an "All groups" to the start of the menu $groupsmenu[0] = get_string("allparticipants"); foreach ($groups as $key => $groupname) { $groupsmenu[$key] = $groupname; } echo ''; if ($groupmode == VISIBLEGROUPS) { print_string('groupsvisible'); } else { print_string('groupsseparate'); } echo ':'; echo ''; popup_form($urlroot.'&group=', $groupsmenu, 'selectgroup', $currentgroup, "", "", "", false, "self"); echo ''; } function navmenu($course, $cm=NULL, $targetwindow="self") { // Given a course and a (current) coursemodule // This function returns a small popup menu with all the // course activity modules in it, as a navigation menu // The data is taken from the serialised array stored in // the course record global $CFG; if ($cm) { $cm = $cm->id; } if ($course->format == 'weeks') { $strsection = get_string("week"); } else { $strsection = get_string("topic"); } if (!$modinfo = unserialize($course->modinfo)) { return ""; } $isteacher = isteacher($course->id); $section = -1; $selected = ""; $url = ""; $previousmod = NULL; $backmod = NULL; $nextmod = NULL; $selectmod = NULL; $logslink = NULL; $flag = false; $menu = array(); $strjumpto = get_string('jumpto'); $sections = get_records('course_sections','course',$course->id,'section',"section,visible,summary"); foreach ($modinfo as $mod) { if ($mod->mod == "label") { continue; } if ($mod->section > $course->numsections) { /// Don't show excess hidden sections break; } if ($mod->section > 0 and $section <> $mod->section) { $thissection = $sections[$mod->section]; if ($thissection->visible or !$course->hiddensections or $isteacher) { $thissection->summary = strip_tags($thissection->summary); if ($course->format == 'weeks' or empty($thissection->summary)) { $menu[] = "-------------- $strsection $mod->section --------------"; } else { if (strlen($thissection->summary) < 47) { $menu[] = '-- '.$thissection->summary; } else { $menu[] = '-- '.substr($thissection->summary, 0, 50).'...'; } } } } $section = $mod->section; //Only add visible or teacher mods to jumpmenu if ($mod->visible or $isteacher) { $url = "$mod->mod/view.php?id=$mod->cm"; if ($flag) { // the current mod is the "next" mod $nextmod = $mod; $flag = false; } if ($cm == $mod->cm) { $selected = $url; $selectmod = $mod; $backmod = $previousmod; $flag = true; // set flag so we know to use next mod for "next" $mod->name = $strjumpto; $strjumpto = ''; } else { $mod->name = strip_tags(urldecode($mod->name)); if (strlen($mod->name) > 55) { $mod->name = substr($mod->name, 0, 50)."..."; } if (!$mod->visible) { $mod->name = "(".$mod->name.")"; } } $menu[$url] = $mod->name; $previousmod = $mod; } } if ($selectmod and $isteacher) { $logslink = "framename\" href=". "\"$CFG->wwwroot/course/log.php?chooselog=1&user=0&date=0&id=$course->id&modid=$selectmod->cm\">". "pixpath/i/log.gif\">"; } if ($backmod) { $backmod = "wwwroot/mod/$backmod->mod/view.php\" target=\"$CFG->framename\">". "cm\">". ""; } if ($nextmod) { $nextmod = "wwwroot/mod/$nextmod->mod/view.php\" target=\"$CFG->framename\">". "cm\">". ""; } return "$logslink$backmod" . popup_form("$CFG->wwwroot/mod/", $menu, "navmenu", $selected, $strjumpto, "", "", true, $targetwindow). "$nextmod"; } function print_date_selector($day, $month, $year, $currenttime=0) { // Currenttime is a default timestamp in GMT // Prints form items with the names $day, $month and $year if (!$currenttime) { $currenttime = time(); } $currentdate = usergetdate($currenttime); for ($i=1; $i<=31; $i++) { $days[$i] = "$i"; } for ($i=1; $i<=12; $i++) { $months[$i] = userdate(gmmktime(12,0,0,$i,1,2000), "%B"); } for ($i=2000; $i<=2010; $i++) { $years[$i] = $i; } choose_from_menu($days, $day, $currentdate['mday'], ""); choose_from_menu($months, $month, $currentdate['mon'], ""); choose_from_menu($years, $year, $currentdate['year'], ""); } function print_time_selector($hour, $minute, $currenttime=0, $step=5) { // Currenttime is a default timestamp in GMT // Prints form items with the names $hour and $minute if (!$currenttime) { $currenttime = time(); } $currentdate = usergetdate($currenttime); if ($step != 1) { $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step; } for ($i=0; $i<=23; $i++) { $hours[$i] = sprintf("%02d",$i); } for ($i=0; $i<=59; $i+=$step) { $minutes[$i] = sprintf("%02d",$i); } choose_from_menu($hours, $hour, $currentdate['hours'], ""); choose_from_menu($minutes, $minute, $currentdate['minutes'], ""); } function print_timer_selector($timelimit = 0, $unit = "") { /// Prints time limit value selector global $CFG; if ($unit) { $unit = ' '.$unit; } // Max timelimit is sessiontimeout - 10 minutes. $maxvalue = ($CFG->sessiontimeout / 60) - 10; for ($i=1; $i<=$maxvalue; $i++) { $minutes[$i] = $i.$unit; } choose_from_menu($minutes, "timelimit", $timelimit, get_string("none")); } function print_grade_menu($courseid, $name, $current, $includenograde=true) { /// Prints a grade menu (as part of an existing form) with help /// Showing all possible numerical grades and scales global $CFG; $strscale = get_string("scale"); $strscales = get_string("scales"); $scales = get_scales_menu($courseid); foreach ($scales as $i => $scalename) { $grades[-$i] = "$strscale: $scalename"; } if ($includenograde) { $grades[0] = get_string("nograde"); } for ($i=100; $i>=1; $i--) { $grades[$i] = $i; } choose_from_menu($grades, "$name", "$current", ""); $helpicon = "$CFG->pixpath/help.gif"; $linkobject = ""; link_to_popup_window ("/course/scales.php?id=$courseid&list=true", "ratingscales", $linkobject, 400, 500, $strscales); } function print_scale_menu($courseid, $name, $current) { /// Prints a scale menu (as part of an existing form) including help button /// Just like print_grade_menu but without the numerical grades global $CFG; $strscales = get_string("scales"); choose_from_menu(get_scales_menu($courseid), "$name", $current, ""); $helpicon = "$CFG->pixpath/help.gif"; $linkobject = ""; link_to_popup_window ("/course/scales.php?id=$courseid&list=true", "ratingscales", $linkobject, 400, 500, $strscales); } function print_scale_menu_helpbutton($courseid, $scale) { /// Prints a help button about a scale /// scale is an object global $CFG; $strscales = get_string("scales"); $helpicon = "$CFG->pixpath/help.gif"; $linkobject = "name\" src=\"$helpicon\" />"; link_to_popup_window ("/course/scales.php?id=$courseid&list=true&scale=$scale->id", "ratingscale", $linkobject, 400, 500, $scale->name); } function error ($message, $link="") { global $CFG, $SESSION; print_header(get_string("error")); echo ""; $message = clean_text($message); // In case nasties are in here print_simple_box($message, "center", "", "#FFBBBB"); if (!$link) { if ( !empty($SESSION->fromurl) ) { $link = "$SESSION->fromurl"; unset($SESSION->fromurl); } else { $link = "$CFG->wwwroot/"; } } print_continue($link); print_footer(); die; } function helpbutton ($page, $title="", $module="moodle", $image=true, $linktext=false, $text="", $return=false) { // $page = the keyword that defines a help page // $title = the title of links, rollover tips, alt tags etc // $module = which module is the page defined in // $image = use a help image for the link? (true/false/"both") // $text = if defined then this text is used in the page, and // the $page variable is ignored. global $CFG, $THEME; if ($module == "") { $module = "moodle"; } if ($image) { $icon = "$CFG->pixpath/help.gif"; if ($linktext) { $linkobject = "$title"; } else { $linkobject = ""; } } else { $linkobject = "$title"; } if ($text) { $url = "/help.php?module=$module&text=".htmlentities(urlencode($text)); } else { $url = "/help.php?module=$module&file=$page.html"; } $link = link_to_popup_window ($url, "popup", $linkobject, 400, 500, $title, 'none', true); if ($return) { return $link; } else { echo $link; } } function emoticonhelpbutton($form, $field) { /// Prints a special help button that is a link to the "live" emoticon popup global $CFG, $SESSION; $SESSION->inserttextform = $form; $SESSION->inserttextfield = $field; helpbutton("emoticons", get_string("helpemoticons"), "moodle", false, true); echo " "; link_to_popup_window ("/help.php?module=moodle&file=emoticons.html", "popup", "pixpath/s/smiley.gif\" border=\"0\" align=\"absmiddle\" width=\"15\" height=\"15\" />", 400, 500, get_string("helpemoticons")); echo ""; } function notice ($message, $link="") { global $CFG, $THEME; $message = clean_text($message); $link = clean_text($link); if (!$link) { if (!empty($_SERVER["HTTP_REFERER"])) { $link = $_SERVER["HTTP_REFERER"]; } else { $link = "$CFG->wwwroot/"; } } echo ""; print_simple_box($message, "center", "50%", "$THEME->cellheading", "20", "noticebox"); print_heading("".get_string("continue").""); print_footer(get_site()); die; } function notice_yesno ($message, $linkyes, $linkno) { global $THEME; $message = clean_text($message); $linkyes = clean_text($linkyes); $linkno = clean_text($linkno); print_simple_box_start("center", "60%", "$THEME->cellheading"); echo "$message"; echo ""; echo "".get_string("yes").""; echo " "; echo "".get_string("no").""; echo ""; print_simple_box_end(); } function redirect($url, $message="", $delay="0") { // Redirects the user to another page, after printing a notice $url = clean_text($url); $message = clean_text($message); if (empty($message)) { echo ""; echo ""; // To cope with Mozilla bug } else { if (empty($delay)) { $delay = 3; // There's no point having a message with no delay } print_header("", "", "", "", ""); echo ""; echo "$message"; echo "( ".get_string("continue")." )"; echo ""; flush(); sleep($delay); echo ""; // To cope with Mozilla bug } die; } function notify ($message, $color="red", $align="center") { $message = clean_text($message); echo "$message\n"; } function obfuscate_email($email) { /// Given an email address, this function will return an obfuscated version of it $i = 0; $length = strlen($email); $obfuscated = ""; while ($i < $length) { if (rand(0,2)) { $obfuscated.='%'.dechex(ord($email{$i})); } else { $obfuscated.=$email{$i}; } $i++; } return $obfuscated; } function obfuscate_text($plaintext) { /// This function takes some text and replaces about half of the characters /// with HTML entity equivalents. Return string is obviously longer. $i=0; $length = strlen($plaintext); $obfuscated=""; $prev_obfuscated = false; while ($i < $length) { $c = ord($plaintext{$i}); $numerical = ($c >= ord('0')) && ($c <= ord('9')); if ($prev_obfuscated and $numerical ) { $obfuscated.=''.ord($plaintext{$i}); } else if (rand(0,2)) { $obfuscated.=''.ord($plaintext{$i}); $prev_obfuscated = true; } else { $obfuscated.=$plaintext{$i}; $prev_obfuscated = false; } $i++; } return $obfuscated; } function obfuscate_mailto($email, $label="", $dimmed=false) { /// This function uses the above two functions to generate a fully /// obfuscated email link, ready to use. if (empty($label)) { $label = $email; } if ($dimmed) { $title = get_string('emaildisable'); $dimmed = ' class="dimmed"'; } else { $title = ''; $dimmed = ''; } return sprintf("%s", obfuscate_text('mailto'), obfuscate_email($email), obfuscate_text($label)); } function print_paging_bar($totalcount, $page, $perpage, $baseurl) { /// Prints a single paging bar to provide access to other pages (usually in a search) $maxdisplay = 18; if ($totalcount > $perpage) { echo ""; echo "".get_string("page").":"; if ($page > 0) { $pagenum=$page-1; echo " (".get_string("previous").") "; } $lastpage = ceil($totalcount / $perpage); if ($page > 15) { $startpage = $page - 10; echo " 1 ..."; } else { $startpage = 0; } $currpage = $startpage; $displaycount = 0; while ($displaycount < $maxdisplay and $currpage < $lastpage) { $displaypage = $currpage+1; if ($page == $currpage) { echo " $displaypage"; } else { echo " $displaypage"; } $displaycount++; $currpage++; } if ($currpage < $lastpage) { $lastpageactual = $lastpage - 1; echo " ...$lastpage "; } $pagenum = $page + 1; if ($pagenum != $displaypage) { echo " (".get_string("next").")"; } echo ""; echo ""; } } //This function is used to rebuild the tag because some formats (PLAIN and WIKI) //will transform it to html entities function rebuildnolinktag($text) { $text = preg_replace('/<(\/*nolink)>/i','<$1>',$text); return $text; } // ================================================ // THREE FUNCTIONS MOVED HERE FROM course/lib.php // ================================================ function print_side_block($heading='', $content='', $list=NULL, $icons=NULL, $footer='', $attributes = array()) { // Prints a nice side block with an optional header. The content can either // be a block of HTML or a list of text with optional icons. global $THEME; print_side_block_start($heading, $attributes); if ($content) { echo $content; if ($footer) { echo "$footer"; } } else { echo ""; if ($list) { foreach ($list as $key => $string) { echo "cellcontent2\">"; if ($icons) { echo "".$icons[$key].""; } echo "$string"; echo ""; } } if ($footer) { echo "cellcontent2\">"; echo "'; echo "$footer"; echo ""; } echo ""; } print_side_block_end(); } function print_side_block_start($heading='', $attributes = array()) { // Starts a nice side block with an optional header. global $THEME; // If there are no special attributes, give a default CSS class if(empty($attributes) || !is_array($attributes)) { $attributes = array('class' => 'sideblock'); } else if(!isset($attributes['class'])) { $attributes['class'] = 'sideblock'; } else if(!strpos($attributes['class'], 'sideblock')) { $attributes['class'] .= ' sideblock'; } // OK, the class is surely there and in addition to anything // else, it's tagged as a sideblock $attrtext = ''; foreach($attributes as $attr => $val) { $attrtext .= ' '.$attr.'="'.$val.'"'; } // [pj] UGLY UGLY UGLY! I hate myself for doing this! // When the Lord Moodle 2.0 cometh, his mercy shalt move all this mess // to CSS and banish the evil to the abyss from whence it came. echo ''; if ($heading) { echo ''.$heading.''; } echo ''; } function print_side_block_end() { echo ''; echo "\n"; } function print_editor_config() { /// prints out the editor config. global $CFG; // print new config echo "var config = new HTMLArea.Config();\n"; echo "config.pageStyle = \"body {"; if(!(empty($CFG->editorbackgroundcolor))) { echo " background-color: $CFG->editorbackgroundcolor;"; } if(!(empty($CFG->editorfontfamily))) { echo " font-family: $CFG->editorfontfamily;"; } if(!(empty($CFG->editorfontsize))) { echo " font-size: $CFG->editorfontsize;"; } echo " }\";\n"; echo "config.killWordOnPaste = "; echo(empty($CFG->editorkillword)) ? "false":"true"; echo ";\n"; echo "config.fontname = {\n"; $fontlist = isset($CFG->editorfontlist) ? explode(';', $CFG->editorfontlist) : array(); $i = 1; // Counter is used to get rid of the last comma. $count = count($fontlist); // Otherwise IE doesn't load the editor. foreach($fontlist as $fontline) { if(!empty($fontline)) { list($fontkey, $fontvalue) = split(":", $fontline); echo "\"". $fontkey ."\":\t'". $fontvalue ."'"; if($i < $count) { echo ",\n"; } } $i++; } echo "};"; if(!empty($CFG->editorspelling) && !empty($CFG->aspellpath)) { print_speller_code($usehtmleditor=true); } } function print_speller_code ($usehtmleditor=false) { /// Prints out code needed for spellchecking. /// Original idea by Ludo (Marc Alier). global $CFG; if(!$usehtmleditor) { echo "\n\n"; } else { echo "\nfunction spellClickHandler(editor, buttonId) {\n"; echo "\teditor._textArea.value = editor.getHTML();\n"; echo "\tvar speller = new spellChecker( editor._textArea );\n"; echo "\tspeller.popUpUrl = \"" . $CFG->wwwroot ."/lib/speller/spellchecker.html\";\n"; echo "\tspeller.spellCheckScript = \"". $CFG->wwwroot ."/lib/speller/server-scripts/spellchecker.php\";\n"; echo "\tspeller._moogle_edit=1;\n"; echo "\tspeller._editor=editor;\n"; echo "\tspeller.openChecker();\n"; echo "}\n"; } } function print_speller_button () { // print button for spellchecking // when editor is disabled echo "\n"; } // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: ?>
$message
"; echo "".get_string("yes").""; echo " "; echo "".get_string("no").""; echo "
( ".get_string("continue")." )
".get_string("page").":"; if ($page > 0) { $pagenum=$page-1; echo " (".get_string("previous").") "; } $lastpage = ceil($totalcount / $perpage); if ($page > 15) { $startpage = $page - 10; echo " 1 ..."; } else { $startpage = 0; } $currpage = $startpage; $displaycount = 0; while ($displaycount < $maxdisplay and $currpage < $lastpage) { $displaypage = $currpage+1; if ($page == $currpage) { echo " $displaypage"; } else { echo " $displaypage"; } $displaycount++; $currpage++; } if ($currpage < $lastpage) { $lastpageactual = $lastpage - 1; echo " ...$lastpage "; } $pagenum = $page + 1; if ($pagenum != $displaypage) { echo " (".get_string("next").")"; } echo "