/** * @uses LABEL_MAX_NAME_LENGTH * @param object $label * @return string */ function get_label_name($label) { $name = strip_tags(format_string($label->intro,true)); if (textlib::strlen($name) > LABEL_MAX_NAME_LENGTH) { $name = textlib::substr($name, 0, LABEL_MAX_NAME_LENGTH)."..."; } if (empty($name)) { // arbitrary name $name = get_string('modulename','label'); } return $name; }
protected function action($message, $level, $options = null) { $columns = $this->columns; if ($this->datecol) { $columns[$this->datecol] = time(); } if ($this->levelcol) { $columns[$this->levelcol] = $level; } $message = clean_param($message, PARAM_NOTAGS); // Check if the message exceeds the 255 character limit in the database, // if it does, shorten it so that it can be inserted successfully. if (textlib::strlen($message) > 255) { $message = textlib::substr($message, 0, 252) . '...'; } $columns[$this->messagecol] = $message; return $this->insert_log_record($this->logtable, $columns); }
public function validation($data, $files) { global $DB, $CFG; $errors = parent::validation($data, $files); $instance = $this->instance; if ($instance->password !== '') { if ($data['guestpassword'] !== $instance->password) { $plugin = enrol_get_plugin('guest'); if ($plugin->get_config('showhint')) { $hint = textlib::substr($instance->password, 0, 1); $errors['guestpassword'] = get_string('passwordinvalidhint', 'enrol_guest', $hint); } else { $errors['guestpassword'] = get_string('passwordinvalid', 'enrol_guest'); } } } return $errors; }
function rfc2445_fold($string) { if (textlib::strlen($string, 'utf-8') <= RFC2445_FOLDED_LINE_LENGTH) { return $string; } $retval = ''; $i = 0; $len_count = 0; //multi-byte string, get the correct length $section_len = textlib::strlen($string, 'utf-8'); while ($len_count < $section_len) { //get the current portion of the line $section = textlib::substr($string, $i * RFC2445_FOLDED_LINE_LENGTH, RFC2445_FOLDED_LINE_LENGTH, 'utf-8'); //increment the length we've processed by the length of the new portion $len_count += textlib::strlen($section, 'utf-8'); /* Add the portion to the return value, terminating with CRLF.HTAB As per RFC 2445, CRLF.HTAB will be replaced by the processor of the data */ $retval .= $section . RFC2445_CRLF . RFC2445_WSP; $i++; } return $retval; }
/** * Prints the page list tab content * * */ private function print_page_list_content() { global $OUTPUT; $page = $this->page; if ($page->timerendered + WIKI_REFRESH_CACHE_TIME < time()) { $fresh = wiki_refresh_cachedcontent($page); $page = $fresh['page']; } $pages = wiki_get_page_list($this->subwiki->id); $stdaux = new stdClass(); $strspecial = get_string('special', 'wiki'); foreach ($pages as $page) { // We need to format the title here to account for any filtering $letter = format_string($page->title, true, array('context' => $this->modcontext)); $letter = textlib::substr($letter, 0, 1); if (preg_match('/^[a-zA-Z]$/', $letter)) { $letter = textlib::strtoupper($letter); $stdaux->{$letter}[] = wiki_parser_link($page); } else { $stdaux->{$strspecial}[] = wiki_parser_link($page); } } $table = new html_table(); $table->head = array(get_string('pagelist', 'wiki') . $OUTPUT->help_icon('pagelist', 'wiki')); $table->attributes['class'] = 'wiki_editor generalbox'; $table->align = array('center'); foreach ($stdaux as $key => $elem) { $table->data[] = array($key); foreach ($elem as $e) { $table->data[] = array(html_writer::link($e['url'], format_string($e['content'], true, array('context' => $this->modcontext)))); } } echo html_writer::table($table); }
/** * Truncate a string in the center * @param string $string The string to truncate * @param int $length The length to truncate to * @return string The truncated string */ protected function trim_center($string, $length) { $trimlength = ceil($length / 2); $start = textlib::substr($string, 0, $trimlength); $end = textlib::substr($string, textlib::strlen($string) - $trimlength); $string = $start . '...' . $end; return $string; }
/** * Prints an individual user box * * @param user_object $user (contains the following fields: id, firstname, lastname and picture) * @param bool $return if true return html string * @return string|null a HTML string or null if this function does the output */ function tag_print_user_box($user, $return = false) { global $CFG, $OUTPUT; $usercontext = get_context_instance(CONTEXT_USER, $user->id); $profilelink = ''; if ($usercontext and has_capability('moodle/user:viewdetails', $usercontext) || has_coursecontact_role($user->id)) { $profilelink = $CFG->wwwroot . '/user/view.php?id=' . $user->id; } $output = $OUTPUT->box_start('user-box', 'user' . $user->id); $fullname = fullname($user); $alt = ''; if (!empty($profilelink)) { $output .= '<a href="' . $profilelink . '">'; $alt = $fullname; } $output .= $OUTPUT->user_picture($user, array('size' => 100)); $output .= '<br />'; if (!empty($profilelink)) { $output .= '</a>'; } //truncate name if it's too big if (textlib::strlen($fullname) > 26) { $fullname = textlib::substr($fullname, 0, 26) . '...'; } $output .= '<strong>' . $fullname . '</strong>'; $output .= $OUTPUT->box_end(); if ($return) { return $output; } else { echo $output; } }
/** * Generate the name of the mod instance from the name of the file * (remove the extension and convert underscore => space * * @param string $filename the filename of the uploaded file * @return string the display name to use */ protected function display_name_from_file($filename) { $pos = textlib::strrpos($filename, '.'); if ($pos) { // Want to skip if $pos === 0 OR $pos === false. $filename = textlib::substr($filename, 0, $pos); } return str_replace('_', ' ', $filename); }
/** * Given a record in the {blog_external} table, checks the blog's URL * for new entries not yet copied into Moodle. * Also attempts to identify and remove deleted blog entries * * @param object $externalblog * @return boolean False if the Feed is invalid */ function blog_sync_external_entries($externalblog) { global $CFG, $DB; require_once $CFG->libdir . '/simplepie/moodle_simplepie.php'; $rssfile = new moodle_simplepie_file($externalblog->url); $filetest = new SimplePie_Locator($rssfile); if (!$filetest->is_feed($rssfile)) { $externalblog->failedlastsync = 1; $DB->update_record('blog_external', $externalblog); return false; } else { if (!empty($externalblog->failedlastsync)) { $externalblog->failedlastsync = 0; $DB->update_record('blog_external', $externalblog); } } $rss = new moodle_simplepie($externalblog->url); if (empty($rss->data)) { return null; } //used to identify blog posts that have been deleted from the source feed $oldesttimestamp = null; $uniquehashes = array(); foreach ($rss->get_items() as $entry) { // If filtertags are defined, use them to filter the entries by RSS category if (!empty($externalblog->filtertags)) { $containsfiltertag = false; $categories = $entry->get_categories(); $filtertags = explode(',', $externalblog->filtertags); $filtertags = array_map('trim', $filtertags); $filtertags = array_map('strtolower', $filtertags); foreach ($categories as $category) { if (in_array(trim(strtolower($category->term)), $filtertags)) { $containsfiltertag = true; } } if (!$containsfiltertag) { continue; } } $uniquehashes[] = $entry->get_permalink(); $newentry = new stdClass(); $newentry->userid = $externalblog->userid; $newentry->module = 'blog_external'; $newentry->content = $externalblog->id; $newentry->uniquehash = $entry->get_permalink(); $newentry->publishstate = 'site'; $newentry->format = FORMAT_HTML; // Clean subject of html, just in case $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT); // Observe 128 max chars in DB // TODO: +1 to raise this to 255 if (textlib::strlen($newentry->subject) > 128) { $newentry->subject = textlib::substr($newentry->subject, 0, 125) . '...'; } $newentry->summary = $entry->get_description(); //used to decide whether to insert or update //uses enty permalink plus creation date if available $existingpostconditions = array('uniquehash' => $entry->get_permalink()); //our DB doesnt allow null creation or modified timestamps so check the external blog supplied one $entrydate = $entry->get_date('U'); if (!empty($entrydate)) { $existingpostconditions['created'] = $entrydate; } //the post ID or false if post not found in DB $postid = $DB->get_field('post', 'id', $existingpostconditions); $timestamp = null; if (empty($entrydate)) { $timestamp = time(); } else { $timestamp = $entrydate; } //only set created if its a new post so we retain the original creation timestamp if the post is edited if ($postid === false) { $newentry->created = $timestamp; } $newentry->lastmodified = $timestamp; if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) { //found an older post $oldesttimestamp = $timestamp; } if (textlib::strlen($newentry->uniquehash) > 255) { // The URL for this item is too long for the field. Rather than add // the entry without the link we will skip straight over it. // RSS spec says recommended length 500, we use 255. debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER); continue; } if ($postid === false) { $id = $DB->insert_record('post', $newentry); // Set tags if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) { tag_set('post', $id, $tags); } } else { $newentry->id = $postid; $DB->update_record('post', $newentry); } } // Look at the posts we have in the database to check if any of them have been deleted from the feed. // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or // may just not be returned anymore. We can't tell the difference so we leave older posts alone. $sql = "SELECT id, uniquehash\n FROM {post}\n WHERE module = 'blog_external'\n AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "\n AND created > :ts"; $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp)); $todelete = array(); foreach ($dbposts as $dbpost) { if (!in_array($dbpost->uniquehash, $uniquehashes)) { $todelete[] = $dbpost->id; } } $DB->delete_records_list('post', 'id', $todelete); $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time())); }
/** * Create a shorten filename * * @param string $str filename * @param int $maxlength max file name length * @return string short filename */ public function get_short_filename($str, $maxlength) { if (textlib::strlen($str) >= $maxlength) { return trim(textlib::substr($str, 0, $maxlength)) . '...'; } else { return $str; } }
public function save_usage($preferredbehaviour, $attempt, $qas, $quizlayout) { $missing = array(); $layout = explode(',', $attempt->layout); $questionkeys = array_combine(array_values($layout), array_keys($layout)); $this->set_quba_preferred_behaviour($attempt->uniqueid, $preferredbehaviour); $i = 0; foreach (explode(',', $quizlayout) as $questionid) { if ($questionid == 0) { continue; } $i++; if (!array_key_exists($questionid, $qas)) { $missing[] = $questionid; $layout[$questionkeys[$questionid]] = $questionid; continue; } $qa = $qas[$questionid]; $qa->questionusageid = $attempt->uniqueid; $qa->slot = $i; if (textlib::strlen($qa->questionsummary) > question_bank::MAX_SUMMARY_LENGTH) { // It seems some people write very long quesions! MDL-30760 $qa->questionsummary = textlib::substr($qa->questionsummary, 0, question_bank::MAX_SUMMARY_LENGTH - 3) . '...'; } $this->insert_record('question_attempts', $qa); $layout[$questionkeys[$questionid]] = $qa->slot; foreach ($qa->steps as $step) { $step->questionattemptid = $qa->id; $this->insert_record('question_attempt_steps', $step); foreach ($step->data as $name => $value) { $datum = new stdClass(); $datum->attemptstepid = $step->id; $datum->name = $name; $datum->value = $value; $this->insert_record('question_attempt_step_data', $datum, false); } } } $this->set_quiz_attempt_layout($attempt->uniqueid, implode(',', $layout)); if ($missing) { notify("Question sessions for questions " . implode(', ', $missing) . " were missing when upgrading question usage {$attempt->uniqueid}."); } }
exit; } // Output the file as a valid Excel spreadsheet if required if ($type == "xls") { require_once("$CFG->libdir/excellib.class.php"); /// Calculate file name $downloadfilename = clean_filename(strip_tags($courseshortname.' '.format_string($survey->name,true))).'.xls'; /// Creating a workbook $workbook = new MoodleExcelWorkbook("-"); /// Sending HTTP headers $workbook->send($downloadfilename); /// Creating the first worksheet $myxls = $workbook->add_worksheet(textlib::substr(strip_tags(format_string($survey->name,true)), 0, 31)); $header = array("surveyid","surveyname","userid","firstname","lastname","email","idnumber","time", "notes"); $col=0; foreach ($header as $item) { $myxls->write_string(0,$col++,$item); } foreach ($nestedorder as $key => $nestedquestions) { foreach ($nestedquestions as $key2 => $qid) { $question = $questions[$qid]; if ($question->type == "0" || $question->type == "1" || $question->type == "3" || $question->type == "-1") { $myxls->write_string(0,$col++,"$question->text"); } if ($question->type == "2" || $question->type == "3") {
$site = $DB->get_record("course", array("id"=>1)); echo '<p style="text-align:right"><span style="font-size:0.75em">' . userdate(time()) . '</span></p>'; echo get_string("site") . ': <strong>' . format_string($site->fullname) . '</strong><br />'; echo get_string("course") . ': <strong>' . format_string($course->fullname) . ' ('. format_string($course->shortname) . ')</strong><br />'; echo get_string("modulename","glossary") . ': <strong>' . format_string($glossary->name, true) . '</strong>'; if ( $allentries ) { foreach ($allentries as $entry) { // Setting the pivot for the current entry $pivot = $entry->glossarypivot; $upperpivot = textlib::strtoupper($pivot); $pivottoshow = textlib::strtoupper(format_string($pivot, true, $fmtoptions)); // Reduce pivot to 1cc if necessary if ( !$fullpivot ) { $upperpivot = textlib::substr($upperpivot, 0, 1); $pivottoshow = textlib::substr($pivottoshow, 0, 1); } // If there's group break if ( $currentpivot != $upperpivot ) { // print the group break if apply if ( $printpivot ) { $currentpivot = $upperpivot; if ( isset($entry->userispivot) ) { // printing the user icon if defined (only when browsing authors) $user = $DB->get_record("user", array("id"=>$entry->userid)); $pivottoshow = fullname($user); }
/** * Returns a popup menu with course activity modules * * Given a course * This function returns a small popup menu with all the * course activity modules in it, as a navigation menu * outputs a simple list structure in XHTML * The data is taken from the serialised array stored in * the course record * * @todo Finish documenting this function * * @global object * @uses CONTEXT_COURSE * @param course $course A {@link $COURSE} object. * @param string $sections * @param string $modinfo * @param string $strsection * @param string $strjumpto * @param int $width * @param string $cmid * @return string The HTML block */ function navmenulist($course, $sections, $modinfo, $strsection, $strjumpto, $width=50, $cmid=0) { global $CFG, $OUTPUT; $section = -1; $url = ''; $menu = array(); $doneheading = false; $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id); $menu[] = '<ul class="navmenulist"><li class="jumpto section"><span>'.$strjumpto.'</span><ul>'; foreach ($modinfo->cms as $mod) { if (!$mod->has_view()) { // Don't show modules which you can't link to! continue; } if ($mod->sectionnum > $course->numsections) { /// Don't show excess hidden sections break; } if (!$mod->uservisible) { // do not icnlude empty sections at all continue; } if ($mod->sectionnum >= 0 and $section != $mod->sectionnum) { $thissection = $sections[$mod->sectionnum]; if ($thissection->visible or !$course->hiddensections or has_capability('moodle/course:viewhiddensections', $coursecontext)) { $thissection->summary = strip_tags(format_string($thissection->summary,true)); if (!$doneheading) { $menu[] = '</ul></li>'; } if ($course->format == 'weeks' or empty($thissection->summary)) { $item = $strsection ." ". $mod->sectionnum; } else { if (textlib::strlen($thissection->summary) < ($width-3)) { $item = $thissection->summary; } else { $item = textlib::substr($thissection->summary, 0, $width).'...'; } } $menu[] = '<li class="section"><span>'.$item.'</span>'; $menu[] = '<ul>'; $doneheading = true; $section = $mod->sectionnum; } else { // no activities from this hidden section shown continue; } } $url = $mod->modname .'/view.php?id='. $mod->id; $mod->name = strip_tags(format_string($mod->name ,true)); if (textlib::strlen($mod->name) > ($width+5)) { $mod->name = textlib::substr($mod->name, 0, $width).'...'; } if (!$mod->visible) { $mod->name = '('.$mod->name.')'; } $class = 'activity '.$mod->modname; $class .= ($cmid == $mod->id) ? ' selected' : ''; $menu[] = '<li class="'.$class.'">'. '<img src="'.$OUTPUT->pix_url('icon', $mod->modname) . '" alt="" />'. '<a href="'.$CFG->wwwroot.'/mod/'.$url.'">'.$mod->name.'</a></li>'; } if ($doneheading) { $menu[] = '</ul></li>'; } $menu[] = '</ul></li></ul>'; return implode("\n", $menu); }
/** * Given some text (which may contain HTML) and an ideal length, * this function truncates the text neatly on a word boundary if possible * * @category string * @global stdClass $CFG * @param string $text text to be shortened * @param int $ideal ideal string length * @param boolean $exact if false, $text will not be cut mid-word * @param string $ending The string to append if the passed string is truncated * @return string $truncate shortened string */ function shorten_text($text, $ideal = 30, $exact = false, $ending = '...') { global $CFG; // If the plain text is shorter than the maximum length, return the whole text. if (textlib::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) { return $text; } // Splits on HTML tags. Each open/close/empty tag will be the first thing // and only tag in its 'line'. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER); $total_length = textlib::strlen($ending); $truncate = ''; // 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 // (byte position in truncated text). $tagdetails = array(); foreach ($lines as $line_matchings) { // If there is any html-tag in this line, handle it and add it (uncounted) to the output. if (!empty($line_matchings[1])) { // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>). if (preg_match('/^<(\\s*.+?\\/\\s*|\\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\\s.+?)?)>$/is', $line_matchings[1])) { // Do nothing. } else { if (preg_match('/^<\\s*\\/([^\\s]+?)\\s*>$/s', $line_matchings[1], $tag_matchings)) { // Record closing tag. $tagdetails[] = (object) array('open' => false, 'tag' => textlib::strtolower($tag_matchings[1]), 'pos' => textlib::strlen($truncate)); } else { if (preg_match('/^<\\s*([^\\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) { // Record opening tag. $tagdetails[] = (object) array('open' => true, 'tag' => textlib::strtolower($tag_matchings[1]), 'pos' => textlib::strlen($truncate)); } } } // Add html-tag to $truncate'd text. $truncate .= $line_matchings[1]; } // Calculate the length of the plain text part of the line; handle entities as one character. $content_length = textlib::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2])); if ($total_length + $content_length > $ideal) { // The number of characters which are left. $left = $ideal - $total_length; $entities_length = 0; // Search for html entities. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) { // calculate the real length of all entities in the legal range foreach ($entities[0] as $entity) { if ($entity[1] + 1 - $entities_length <= $left) { $left--; $entities_length += textlib::strlen($entity[0]); } else { // no more characters left break; } } } $breakpos = $left + $entities_length; // if the words shouldn't be cut in the middle... if (!$exact) { // ...search the last occurence of a space... for (; $breakpos > 0; $breakpos--) { if ($char = textlib::substr($line_matchings[2], $breakpos, 1)) { if ($char === '.' or $char === ' ') { $breakpos += 1; break; } else { if (strlen($char) > 2) { // Chinese/Japanese/Korean text $breakpos += 1; // can be truncated at any UTF-8 break; // character boundary. } } } } } if ($breakpos == 0) { // This deals with the test_shorten_text_no_spaces case. $breakpos = $left + $entities_length; } else { if ($breakpos > $left + $entities_length) { // This deals with the previous for loop breaking on the first char. $breakpos = $left + $entities_length; } } $truncate .= textlib::substr($line_matchings[2], 0, $breakpos); // maximum length is reached, so get off the loop break; } else { $truncate .= $line_matchings[2]; $total_length += $content_length; } // If the maximum length is reached, get off the loop. if ($total_length >= $ideal) { break; } } // Add the defined ending to the text. $truncate .= $ending; // Now calculate the list of open html tags based on the truncate position. $open_tags = array(); foreach ($tagdetails as $taginfo) { if ($taginfo->open) { // Add tag to the beginning of $open_tags list. array_unshift($open_tags, $taginfo->tag); } else { // Can have multiple exact same open tags, close the last one. $pos = array_search($taginfo->tag, array_reverse($open_tags, true)); if ($pos !== false) { unset($open_tags[$pos]); } } } // Close all unclosed html-tags. foreach ($open_tags as $tag) { $truncate .= '</' . $tag . '>'; } return $truncate; }
/** * Print a select box allowing the user to choose to view new messages, course participants etc. * * Called by message_print_contact_selector() * @param int $viewing What page is the user viewing ie MESSAGE_VIEW_UNREAD_MESSAGES, MESSAGE_VIEW_RECENT_CONVERSATIONS etc * @param array $courses array of course objects. The courses the user is enrolled in. * @param array $coursecontexts array of course contexts. Keyed on course id. * @param int $countunreadtotal how many unread messages does the user have? * @param int $countblocked how many users has the current user blocked? * @param string $strunreadmessages a preconstructed message about the number of unread messages the user has * @return void */ function message_print_usergroup_selector($viewing, $courses, $coursecontexts, $countunreadtotal, $countblocked, $strunreadmessages) { $options = array(); if ($countunreadtotal>0) { //if there are unread messages $options[MESSAGE_VIEW_UNREAD_MESSAGES] = $strunreadmessages; } $str = get_string('mycontacts', 'message'); $options[MESSAGE_VIEW_CONTACTS] = $str; $options[MESSAGE_VIEW_RECENT_CONVERSATIONS] = get_string('mostrecentconversations', 'message'); $options[MESSAGE_VIEW_RECENT_NOTIFICATIONS] = get_string('mostrecentnotifications', 'message'); if (!empty($courses)) { $courses_options = array(); foreach($courses as $course) { if (has_capability('moodle/course:viewparticipants', $coursecontexts[$course->id])) { //Not using short_text() as we want the end of the course name. Not the beginning. $shortname = format_string($course->shortname, true, array('context' => $coursecontexts[$course->id])); if (textlib::strlen($shortname) > MESSAGE_MAX_COURSE_NAME_LENGTH) { $courses_options[MESSAGE_VIEW_COURSE.$course->id] = '...'.textlib::substr($shortname, -MESSAGE_MAX_COURSE_NAME_LENGTH); } else { $courses_options[MESSAGE_VIEW_COURSE.$course->id] = $shortname; } } } if (!empty($courses_options)) { $options[] = array(get_string('courses') => $courses_options); } } if ($countblocked>0) { $str = get_string('blockedusers','message', $countblocked); $options[MESSAGE_VIEW_BLOCKED] = $str; } echo html_writer::start_tag('form', array('id' => 'usergroupform','method' => 'get','action' => '')); echo html_writer::start_tag('fieldset'); echo html_writer::label(get_string('messagenavigation', 'message'), 'viewing'); echo html_writer::select($options, 'viewing', $viewing, false, array('id' => 'viewing','onchange' => 'this.form.submit()')); echo html_writer::end_tag('fieldset'); echo html_writer::end_tag('form'); }
/** * This function trims any given text and returns it with some dots at the end * * @param string $text * @param string $limit * * @return string */ function wiki_trim_string($text, $limit = 25) { if (textlib::strlen($text) > $limit) { $text = textlib::substr($text, 0, $limit) . '...'; } return $text; }
public function survey_copy($owner) { global $DB; // Clear the sid, clear the creation date, change the name, and clear the status. // Since we're copying a data record, addslashes. // 2.0 - don't need to do this now, since its handled by the $DB-> functions. $survey = clone $this->survey; unset($survey->id); $survey->owner = $owner; // Make sure that the survey name is not larger than the field size (CONTRIB-2999). Leave room for extra chars. $survey->name = textlib::substr($survey->name, 0, 64 - 10); $survey->name .= '_copy'; $survey->status = 0; // Check for 'name' conflict, and resolve. $i = 0; $name = $survey->name; while ($DB->count_records('questionnaire_survey', array('name' => $name)) > 0) { $name = $survey->name . ++$i; } if ($i) { $survey->name .= $i; } // Create new survey. if (!($newsid = $DB->insert_record('questionnaire_survey', $survey))) { return false; } // Make copies of all the questions. $pos = 1; // Skip logic: some changes needed here for dependencies down below. $qidarray = array(); $cidarray = array(); foreach ($this->questions as $question) { // Fix some fields first. $oldid = $question->id; unset($question->id); $question->survey_id = $newsid; $question->position = $pos++; $question->name = addslashes($question->name); $question->content = addslashes($question->content); // Copy question to new survey. if (!($newqid = $DB->insert_record('questionnaire_question', $question))) { return false; } $qidarray[$oldid] = $newqid; foreach ($question->choices as $key => $choice) { $oldcid = $key; unset($choice->id); $choice->question_id = $newqid; $choice->content = addslashes($choice->content); $choice->value = addslashes($choice->value); if (!($newcid = $DB->insert_record('questionnaire_quest_choice', $choice))) { return false; } $cidarray[$oldcid] = $newcid; } } // Skip logic: now we need to set the new values for dependencies. if ($newquestions = $DB->get_records('questionnaire_question', array('survey_id' => $newsid), 'id')) { foreach ($newquestions as $question) { if ($question->dependquestion != 0) { $dependqtypeid = $this->questions[$question->dependquestion]->type_id; $record = new object(); $record->id = $question->id; $record->dependquestion = $qidarray[$question->dependquestion]; if ($dependqtypeid != 1) { $record->dependchoice = $cidarray[$question->dependchoice]; } $DB->update_record('questionnaire_question', $record); } } } return $newsid; }
/** * Internal callback function. */ function uu_process_template_callback($username, $firstname, $lastname, $block) { switch ($block[3]) { case 'u': $repl = $username; break; case 'f': $repl = $firstname; break; case 'l': $repl = $lastname; break; default: return $block[0]; } switch ($block[1]) { case '+': $repl = textlib::strtoupper($repl); break; case '-': $repl = textlib::strtolower($repl); break; case '~': $repl = textlib::strtotitle($repl); break; } if (!empty($block[2])) { $repl = textlib::substr($repl, 0, $block[2]); } return $repl; }
/** * Writes the common <question> data and re-dispateches the whole grouped * <QUESTION> data to the qtype for appending its qtype specific data processing * * @param array $data * @param array $raw * @return array */ public function process_question(array $data, array $raw) { global $CFG; // firstly make sure that the category data and the <questions> wrapper are written // note that because of MDL-27693 we can't use {@link self::process_question_category()} // and {@link self::on_questions_start()} to do so if (empty($this->currentcategorywritten)) { $this->xmlwriter->begin_tag('question_category', array('id' => $this->currentcategory['id'])); foreach ($this->currentcategory as $name => $value) { if ($name === 'id') { continue; } $this->xmlwriter->full_tag($name, $value); } $this->currentcategorywritten = true; } if (empty($this->questionswrapperwritten)) { $this->xmlwriter->begin_tag('questions'); $this->questionswrapperwritten = true; } $qtype = $data['qtype']; // replay the upgrade step 2008050700 {@see question_fix_random_question_parents()} if ($qtype == 'random' and $data['parent'] != $data['id']) { $data['parent'] = $data['id']; } // replay the upgrade step 2010080900 and part of 2010080901 $data['generalfeedbackformat'] = $data['questiontextformat']; $data['oldquestiontextformat'] = $data['questiontextformat']; if ($CFG->texteditors !== 'textarea') { $data['questiontext'] = text_to_html($data['questiontext'], false, false, true); $data['questiontextformat'] = FORMAT_HTML; $data['generalfeedback'] = text_to_html($data['generalfeedback'], false, false, true); $data['generalfeedbackformat'] = FORMAT_HTML; } // Migrate files in questiontext. $this->fileman->contextid = $this->currentcategory['contextid']; $this->fileman->component = 'question'; $this->fileman->filearea = 'questiontext'; $this->fileman->itemid = $data['id']; $data['questiontext'] = moodle1_converter::migrate_referenced_files($data['questiontext'], $this->fileman); // Migrate files in generalfeedback. $this->fileman->filearea = 'generalfeedback'; $data['generalfeedback'] = moodle1_converter::migrate_referenced_files($data['generalfeedback'], $this->fileman); // replay the upgrade step 2010080901 - updating question image if (!empty($data['image'])) { if (textlib::substr(textlib::strtolower($data['image']), 0, 7) == 'http://') { // it is a link, appending to existing question text $data['questiontext'] .= ' <img src="' . $data['image'] . '" />'; } else { // it is a file in course_files $filename = basename($data['image']); $filepath = dirname($data['image']); if (empty($filepath) or $filepath == '.' or $filepath == '/') { $filepath = '/'; } else { // append / $filepath = '/' . trim($filepath, './@#$ ') . '/'; } if (file_exists($this->converter->get_tempdir_path() . '/course_files' . $filepath . $filename)) { $this->fileman->contextid = $this->currentcategory['contextid']; $this->fileman->component = 'question'; $this->fileman->filearea = 'questiontext'; $this->fileman->itemid = $data['id']; $this->fileman->migrate_file('course_files' . $filepath . $filename, '/', $filename); // note this is slightly different from the upgrade code as we put the file into the // root folder here. this makes our life easier as we do not need to create all the // directories within the specified filearea/itemid $data['questiontext'] .= ' <img src="@@PLUGINFILE@@/' . $filename . '" />'; } else { $this->log('question file not found', backup::LOG_WARNING, array($data['id'], $filepath . $filename)); } } } unset($data['image']); // replay the upgrade step 2011060301 - Rename field defaultgrade on table question to defaultmark $data['defaultmark'] = $data['defaultgrade']; // write the common question data $this->xmlwriter->begin_tag('question', array('id' => $data['id'])); foreach (array('parent', 'name', 'questiontext', 'questiontextformat', 'generalfeedback', 'generalfeedbackformat', 'defaultmark', 'penalty', 'qtype', 'length', 'stamp', 'version', 'hidden', 'timecreated', 'timemodified', 'createdby', 'modifiedby') as $fieldname) { if (!array_key_exists($fieldname, $data)) { throw new moodle1_convert_exception('missing_common_question_field', $fieldname); } $this->xmlwriter->full_tag($fieldname, $data[$fieldname]); } // unless we know that the given qtype does not append any own structures, // give the handler a chance to do so now if (!in_array($qtype, array('description', 'random'))) { $handler = $this->get_qtype_handler($qtype); if ($handler === false) { $this->log('question type converter not found', backup::LOG_ERROR, $qtype); } else { $this->xmlwriter->begin_tag('plugin_qtype_' . $qtype . '_question'); $handler->use_xml_writer($this->xmlwriter); $handler->process_question($data, $raw); $this->xmlwriter->end_tag('plugin_qtype_' . $qtype . '_question'); } } $this->xmlwriter->end_tag('question'); }
/** * Add an entry to the log table. * * Add an entry to the log table. These are "action" focussed rather * than web server hits, and provide a way to easily reconstruct what * any particular student has been doing. * * @package core * @category log * @global moodle_database $DB * @global stdClass $CFG * @global stdClass $USER * @uses SITEID * @uses DEBUG_DEVELOPER * @uses DEBUG_ALL * @param int $courseid The course id * @param string $module The module name e.g. forum, journal, resource, course, user etc * @param string $action 'view', 'update', 'add' or 'delete', possibly followed by another word to clarify. * @param string $url The file and parameters used to see the results of the action * @param string $info Additional description information * @param string $cm The course_module->id if there is one * @param string $user If log regards $user other than $USER * @return void */ function add_to_log($courseid, $module, $action, $url = '', $info = '', $cm = 0, $user = 0) { // Note that this function intentionally does not follow the normal Moodle DB access idioms. // This is for a good reason: it is the most frequently used DB update function, // so it has been optimised for speed. global $DB, $CFG, $USER; if ($cm === '' || is_null($cm)) { // postgres won't translate empty string to its default $cm = 0; } if ($user) { $userid = $user; } else { if (session_is_loggedinas()) { // Don't log return; } $userid = empty($USER->id) ? '0' : $USER->id; } if (isset($CFG->logguests) and !$CFG->logguests) { if (!$userid or isguestuser($userid)) { return; } } $REMOTE_ADDR = getremoteaddr(); $timenow = time(); $info = $info; if (!empty($url)) { // could break doing html_entity_decode on an empty var. $url = html_entity_decode($url, ENT_QUOTES, 'UTF-8'); } else { $url = ''; } // Restrict length of log lines to the space actually available in the // database so that it doesn't cause a DB error. Log a warning so that // developers can avoid doing things which are likely to cause this on a // routine basis. if (!empty($info) && textlib::strlen($info) > 255) { $info = textlib::substr($info, 0, 252) . '...'; debugging('Warning: logged very long info', DEBUG_DEVELOPER); } // If the 100 field size is changed, also need to alter print_log in course/lib.php if (!empty($url) && textlib::strlen($url) > 100) { $url = textlib::substr($url, 0, 97) . '...'; debugging('Warning: logged very long URL', DEBUG_DEVELOPER); } if (defined('MDL_PERFDB')) { global $PERF; $PERF->logwrites++; } $log = array('time' => $timenow, 'userid' => $userid, 'course' => $courseid, 'ip' => $REMOTE_ADDR, 'module' => $module, 'cmid' => $cm, 'action' => $action, 'url' => $url, 'info' => $info); try { $DB->insert_record_raw('log', $log, false); } catch (dml_exception $e) { debugging('Error: Could not insert a new entry to the Moodle log. ' . $e->error, DEBUG_ALL); // MDL-11893, alert $CFG->supportemail if insert into log failed if ($CFG->supportemail and empty($CFG->noemailever)) { // email_to_user is not usable because email_to_user tries to write to the logs table, // and this will get caught in an infinite loop, if disk is full $site = get_site(); $subject = 'Insert into log failed at your moodle site ' . $site->fullname; $message = "Insert into log table failed at " . date('l dS \\of F Y h:i:s A') . ".\n It is possible that your disk is full.\n\n"; $message .= "The failed query parameters are:\n\n" . var_export($log, true); $lasttime = get_config('admin', 'lastloginserterrormail'); if (empty($lasttime) || time() - $lasttime > 60 * 60 * 24) { // limit to 1 email per day //using email directly rather than messaging as they may not be able to log in to access a message mail($CFG->supportemail, $subject, $message); set_config('lastloginserterrormail', time(), 'admin'); } } } }
/** * This function is used to generate and display selector form * * @global stdClass $USER * @global stdClass $CFG * @global moodle_database $DB * @global core_renderer $OUTPUT * @global stdClass $SESSION * @uses CONTEXT_SYSTEM * @uses COURSE_MAX_COURSES_PER_DROPDOWN * @uses CONTEXT_COURSE * @uses SEPARATEGROUPS * @param stdClass $course course instance * @param int $selecteduser id of the selected user * @param string $selecteddate Date selected * @param string $modname course_module->id * @param string $modid number or 'site_errors' * @param string $modaction an action as recorded in the logs * @param int $selectedgroup Group to display * @param int $showcourses whether to show courses if we're over our limit. * @param int $showusers whether to show users if we're over our limit. * @param string $logformat Format of the logs (downloadascsv, showashtml, downloadasods, downloadasexcel) * @return void */ function report_log_print_selector_form($course, $selecteduser = 0, $selecteddate = 'today', $modname = "", $modid = 0, $modaction = '', $selectedgroup = -1, $showcourses = 0, $showusers = 0, $logformat = 'showashtml') { global $USER, $CFG, $DB, $OUTPUT, $SESSION; // first check to see if we can override showcourses and showusers $numcourses = $DB->count_records("course"); if ($numcourses < COURSE_MAX_COURSES_PER_DROPDOWN && !$showcourses) { $showcourses = 1; } $sitecontext = get_context_instance(CONTEXT_SYSTEM); $context = get_context_instance(CONTEXT_COURSE, $course->id); /// Setup for group handling. if ($course->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) { $selectedgroup = -1; $showgroups = false; } else { if ($course->groupmode) { $showgroups = true; } else { $selectedgroup = 0; $showgroups = false; } } if ($selectedgroup === -1) { if (isset($SESSION->currentgroup[$course->id])) { $selectedgroup = $SESSION->currentgroup[$course->id]; } else { $selectedgroup = groups_get_all_groups($course->id, $USER->id); if (is_array($selectedgroup)) { $selectedgroup = array_shift(array_keys($selectedgroup)); $SESSION->currentgroup[$course->id] = $selectedgroup; } else { $selectedgroup = 0; } } } // Get all the possible users $users = array(); // Define limitfrom and limitnum for queries below // If $showusers is enabled... don't apply limitfrom and limitnum $limitfrom = empty($showusers) ? 0 : ''; $limitnum = empty($showusers) ? COURSE_MAX_USERS_PER_DROPDOWN + 1 : ''; $courseusers = get_enrolled_users($context, '', $selectedgroup, 'u.id, u.firstname, u.lastname', 'lastname ASC, firstname ASC', $limitfrom, $limitnum); if (count($courseusers) < COURSE_MAX_USERS_PER_DROPDOWN && !$showusers) { $showusers = 1; } if ($showusers) { if ($courseusers) { foreach ($courseusers as $courseuser) { $users[$courseuser->id] = fullname($courseuser, has_capability('moodle/site:viewfullnames', $context)); } } $users[$CFG->siteguest] = get_string('guestuser'); } if (has_capability('report/log:view', $sitecontext) && $showcourses) { if ($ccc = $DB->get_records("course", null, "fullname", "id,shortname,fullname,category")) { foreach ($ccc as $cc) { if ($cc->category) { $courses["{$cc->id}"] = format_string(get_course_display_name_for_list($cc)); } else { $courses["{$cc->id}"] = format_string($cc->fullname) . ' (Site)'; } } } asort($courses); } $activities = array(); $selectedactivity = ""; /// Casting $course->modinfo to string prevents one notice when the field is null if ($modinfo = unserialize((string) $course->modinfo)) { $section = 0; $sections = get_all_sections($course->id); foreach ($modinfo as $mod) { if ($mod->mod == "label") { continue; } if ($mod->section > 0 and $section != $mod->section) { $activities["section/{$mod->section}"] = '--- ' . get_section_name($course, $sections[$mod->section]) . ' ---'; } $section = $mod->section; $mod->name = strip_tags(format_string($mod->name, true)); if (textlib::strlen($mod->name) > 55) { $mod->name = textlib::substr($mod->name, 0, 50) . "..."; } if (!$mod->visible) { $mod->name = "(" . $mod->name . ")"; } $activities["{$mod->cm}"] = $mod->name; if ($mod->cm == $modid) { $selectedactivity = "{$mod->cm}"; } } } if (has_capability('report/log:view', $sitecontext) && $course->id == SITEID) { $activities["site_errors"] = get_string("siteerrors"); if ($modid === "site_errors") { $selectedactivity = "site_errors"; } } $strftimedate = get_string("strftimedate"); $strftimedaydate = get_string("strftimedaydate"); asort($users); // Prepare the list of action options. $actions = array('view' => get_string('view'), 'add' => get_string('add'), 'update' => get_string('update'), 'delete' => get_string('delete'), '-view' => get_string('allchanges')); // Get all the possible dates // Note that we are keeping track of real (GMT) time and user time // User time is only used in displays - all calcs and passing is GMT $timenow = time(); // GMT // What day is it now for the user, and when is midnight that day (in GMT). $timemidnight = $today = usergetmidnight($timenow); // Put today up the top of the list $dates = array("{$timemidnight}" => get_string("today") . ", " . userdate($timenow, $strftimedate)); if (!$course->startdate or $course->startdate > $timenow) { $course->startdate = $course->timecreated; } $numdates = 1; while ($timemidnight > $course->startdate and $numdates < 365) { $timemidnight = $timemidnight - 86400; $timenow = $timenow - 86400; $dates["{$timemidnight}"] = userdate($timenow, $strftimedaydate); $numdates++; } if ($selecteddate == "today") { $selecteddate = $today; } echo "<form class=\"logselectform\" action=\"{$CFG->wwwroot}/report/log/index.php\" method=\"get\">\n"; echo "<div>\n"; echo "<input type=\"hidden\" name=\"chooselog\" value=\"1\" />\n"; echo "<input type=\"hidden\" name=\"showusers\" value=\"{$showusers}\" />\n"; echo "<input type=\"hidden\" name=\"showcourses\" value=\"{$showcourses}\" />\n"; if (has_capability('report/log:view', $sitecontext) && $showcourses) { echo html_writer::label(get_string('selectacourse'), 'menuid', false, array('class' => 'accesshide')); echo html_writer::select($courses, "id", $course->id, false); } else { // echo '<input type="hidden" name="id" value="'.$course->id.'" />'; $courses = array(); $courses[$course->id] = get_course_display_name_for_list($course) . ($course->id == SITEID ? ' (' . get_string('site') . ') ' : ''); echo html_writer::label(get_string('selectacourse'), 'menuid', false, array('class' => 'accesshide')); echo html_writer::select($courses, "id", $course->id, false); if (has_capability('report/log:view', $sitecontext)) { $a = new stdClass(); $a->url = "{$CFG->wwwroot}/report/log/index.php?chooselog=0&group={$selectedgroup}&user={$selecteduser}" . "&id={$course->id}&date={$selecteddate}&modid={$selectedactivity}&showcourses=1&showusers={$showusers}"; print_string('logtoomanycourses', 'moodle', $a); } } if ($showgroups) { if ($cgroups = groups_get_all_groups($course->id)) { foreach ($cgroups as $cgroup) { $groups[$cgroup->id] = $cgroup->name; } } else { $groups = array(); } echo html_writer::label(get_string('selectagroup'), 'menugroup', false, array('class' => 'accesshide')); echo html_writer::select($groups, "group", $selectedgroup, get_string("allgroups")); } if ($showusers) { echo html_writer::label(get_string('selctauser'), 'menuuser', false, array('class' => 'accesshide')); echo html_writer::select($users, "user", $selecteduser, get_string("allparticipants")); } else { $users = array(); if (!empty($selecteduser)) { $user = $DB->get_record('user', array('id' => $selecteduser)); $users[$selecteduser] = fullname($user); } else { $users[0] = get_string('allparticipants'); } echo html_writer::label(get_string('selctauser'), 'menuuser', false, array('class' => 'accesshide')); echo html_writer::select($users, "user", $selecteduser, false); $a = new stdClass(); $a->url = "{$CFG->wwwroot}/report/log/index.php?chooselog=0&group={$selectedgroup}&user={$selecteduser}" . "&id={$course->id}&date={$selecteddate}&modid={$selectedactivity}&showusers=1&showcourses={$showcourses}"; print_string('logtoomanyusers', 'moodle', $a); } echo html_writer::label(get_string('date'), 'menudate', false, array('class' => 'accesshide')); echo html_writer::select($dates, "date", $selecteddate, get_string("alldays")); echo html_writer::label(get_string('activities'), 'menumodid', false, array('class' => 'accesshide')); echo html_writer::select($activities, "modid", $selectedactivity, get_string("allactivities")); echo html_writer::label(get_string('actions'), 'menumodaction', false, array('class' => 'accesshide')); echo html_writer::select($actions, 'modaction', $modaction, get_string("allactions")); $logformats = array('showashtml' => get_string('displayonpage'), 'downloadascsv' => get_string('downloadtext'), 'downloadasods' => get_string('downloadods'), 'downloadasexcel' => get_string('downloadexcel')); echo html_writer::label(get_string('logsformat', 'report_log'), 'menulogformat', false, array('class' => 'accesshide')); echo html_writer::select($logformats, 'logformat', $logformat, false); echo '<input type="submit" value="' . get_string('gettheselogs') . '" />'; echo '</div>'; echo '</form>'; }
/** * given a course object with shortname & fullname, this function will * truncate the the number of chars allowed and add ... if it was too long */ function course_format_name($course, $max = 100) { $context = get_context_instance(CONTEXT_COURSE, $course->id); $shortname = format_string($course->shortname, true, array('context' => $context)); $fullname = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))); $str = $shortname . ': ' . $fullname; if (textlib::strlen($str) <= $max) { return $str; } else { return textlib::substr($str, 0, $max - 3) . '...'; } }
/** * Trim inputted text to the given maximum length. * @param string $text * @param int $length * @return string The trimmed string with a '...' appended for display. */ function lightboxgallery_resize_text($text, $length) { $textlib = new textlib(); return $textlib->strlen($text) > $length ? $textlib->substr($text, 0, $length) . '...' : $text; }
/** * Strips a large title to size and adds ... if title too long * * @param string title to shorten * @param int max character length of title * @return string title s() quoted and shortened if necessary */ function format_title($title, $max = 64) { if (textlib::strlen($title) <= $max) { return s($title); } else { return s(textlib::substr($title, 0, $max - 3) . '...'); } }
/** * Tests the static sub string method * @return void */ public function test_substr() { $str = "Žluťoučký koníček"; $this->assertSame(textlib::substr($str, 0), $str); $this->assertSame(textlib::substr($str, 1), 'luťoučký koníček'); $this->assertSame(textlib::substr($str, 1, 3), 'luť'); $this->assertSame(textlib::substr($str, 0, 100), $str); $this->assertSame(textlib::substr($str, -3, 2), 'če'); $iso2 = pack("H*", "ae6c75bb6f75e86bfd206b6f6eede8656b"); $this->assertSame(textlib::substr($iso2, 1, 3, 'iso-8859-2'), textlib::convert('luť', 'utf-8', 'iso-8859-2')); $this->assertSame(textlib::substr($iso2, 0, 100, 'iso-8859-2'), textlib::convert($str, 'utf-8', 'iso-8859-2')); $this->assertSame(textlib::substr($iso2, -3, 2, 'iso-8859-2'), textlib::convert('če', 'utf-8', 'iso-8859-2')); $win = pack("H*", "8e6c759d6f75e86bfd206b6f6eede8656b"); $this->assertSame(textlib::substr($win, 1, 3, 'cp1250'), textlib::convert('luť', 'utf-8', 'cp1250')); $this->assertSame(textlib::substr($win, 0, 100, 'cp1250'), textlib::convert($str, 'utf-8', 'cp1250')); $this->assertSame(textlib::substr($win, -3, 2, 'cp1250'), textlib::convert('če', 'utf-8', 'cp1250')); $str = pack("H*", "b8c0b8ecc0dfc4ea"); //EUC-JP $s = pack("H*", "b8ec"); //EUC-JP $this->assertSame(textlib::substr($str, 1, 1, 'EUC-JP'), $s); $str = pack("H*", "1b24423840386c405f446a1b2842"); //ISO-2022-JP $s = pack("H*", "1b2442386c1b2842"); //ISO-2022-JP $this->assertSame(textlib::substr($str, 1, 1, 'ISO-2022-JP'), $s); $str = pack("H*", "8cbe8cea90dd92e8"); //SHIFT-JIS $s = pack("H*", "8cea"); //SHIFT-JIS $this->assertSame(textlib::substr($str, 1, 1, 'SHIFT-JIS'), $s); $str = pack("H*", "bcf2cce5d6d0cec4"); //GB2312 $s = pack("H*", "cce5"); //GB2312 $this->assertSame(textlib::substr($str, 1, 1, 'GB2312'), $s); $str = pack("H*", "bcf2cce5d6d0cec4"); //GB18030 $s = pack("H*", "cce5"); //GB18030 $this->assertSame(textlib::substr($str, 1, 1, 'GB18030'), $s); }
/** * Add a link to the session to the courses calendar. * * @param class $session Record from the facetoface_sessions table * @param class $eventname Name to display for this event * @param string $calendartype Which calendar to add the event to (user, course, site) * @param int $userid Optional param for user calendars * @param string $eventtype Optional param for user calendar (booking/session) */ function facetoface_add_session_to_calendar($session, $facetoface, $calendartype = 'none', $userid = 0, $eventtype = 'session') { global $CFG, $DB; if (empty($session->datetimeknown)) { return true; //date unkown, can't add to calendar } if (empty($facetoface->showoncalendar) && empty($facetoface->usercalentry)) { return true; //facetoface calendar settings prevent calendar } $description = ''; if (!empty($facetoface->description)) { $description .= html_writer::tag('p', clean_param($facetoface->description, PARAM_CLEANHTML)); } $description .= facetoface_print_session($session, false, true, true); $linkurl = new moodle_url('/mod/facetoface/signup.php', array('s' => $session->id)); $linktext = get_string('signupforthissession', 'facetoface'); if ($calendartype == 'site' && $facetoface->showoncalendar == F2F_CAL_SITE) { $courseid = SITEID; $description .= html_writer::link($linkurl, $linktext); } else if ($calendartype == 'course' && $facetoface->showoncalendar == F2F_CAL_COURSE) { $courseid = $facetoface->course; $description .= html_writer::link($linkurl, $linktext); } else if ($calendartype == 'user' && $facetoface->usercalentry) { $courseid = 0; $urlvar = ($eventtype == 'session') ? 'attendees' : 'signup'; $linkurl = $CFG->wwwroot . "/mod/facetoface/" . $urlvar . ".php?s=$session->id"; $description .= get_string("calendareventdescription{$eventtype}", 'facetoface', $linkurl); } else { return true; } $shortname = $facetoface->shortname; if (empty($shortname)) { $shortname = textlib::substr($facetoface->name, 0, CALENDAR_MAX_NAME_LENGTH); } $result = true; foreach ($session->sessiondates as $date) { $newevent = new stdClass(); $newevent->name = $shortname; $newevent->description = $description; $newevent->format = FORMAT_HTML; $newevent->courseid = $courseid; $newevent->groupid = 0; $newevent->userid = $userid; $newevent->uuid = "{$session->id}"; $newevent->instance = $session->facetoface; $newevent->modulename = 'facetoface'; $newevent->eventtype = "facetoface{$eventtype}"; $newevent->timestart = $date->timestart; $newevent->timeduration = $date->timefinish - $date->timestart; $newevent->visible = 1; $newevent->timemodified = time(); if ($calendartype == 'user' && $eventtype == 'booking') { //Check for and Delete the 'created' calendar event to reduce multiple entries for the same event $DB->delete_records('event', array('userid' => $userid, 'instance' => $session->facetoface, 'eventtype' => 'facetofacesession')); } $result = $result && $DB->insert_record('event', $newevent); } return $result; }
/** * If new messages are waiting for the current user, then insert * JavaScript to pop up the messaging window into the page * * @global moodle_page $PAGE * @return void */ function message_popup_window() { global $USER, $DB, $PAGE, $CFG, $SITE; if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) { return; } if (!isloggedin() || isguestuser()) { return; } if (!isset($USER->message_lastpopup)) { $USER->message_lastpopup = 0; } else { if ($USER->message_lastpopup > time() - 120) { //dont run the query to check whether to display a popup if its been run in the last 2 minutes return; } } //a quick query to check whether the user has new messages $messagecount = $DB->count_records('message', array('useridto' => $USER->id)); if ($messagecount < 1) { return; } //got unread messages so now do another query that joins with the user table $messagesql = "SELECT m.id, m.smallmessage, m.fullmessageformat, m.notification, u.firstname, u.lastname\n FROM {message} m\n JOIN {message_working} mw ON m.id=mw.unreadmessageid\n JOIN {message_processors} p ON mw.processorid=p.id\n JOIN {user} u ON m.useridfrom=u.id\n WHERE m.useridto = :userid\n AND p.name='popup'"; //if the user was last notified over an hour ago we can renotify them of old messages //so don't worry about when the new message was sent $lastnotifiedlongago = $USER->message_lastpopup < time() - 3600; if (!$lastnotifiedlongago) { $messagesql .= 'AND m.timecreated > :lastpopuptime'; } $message_users = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup)); //if we have new messages to notify the user about if (!empty($message_users)) { $strmessages = ''; if (count($message_users) > 1) { $strmessages = get_string('unreadnewmessages', 'message', count($message_users)); } else { $message_users = reset($message_users); //show who the message is from if its not a notification if (!$message_users->notification) { $strmessages = get_string('unreadnewmessage', 'message', fullname($message_users)); } //try to display the small version of the message $smallmessage = null; if (!empty($message_users->smallmessage)) { //display the first 200 chars of the message in the popup $smallmessage = null; if (textlib::strlen($message_users->smallmessage) > 200) { $smallmessage = textlib::substr($message_users->smallmessage, 0, 200) . '...'; } else { $smallmessage = $message_users->smallmessage; } //prevent html symbols being displayed if ($message_users->fullmessageformat == FORMAT_HTML) { $smallmessage = html_to_text($smallmessage); } else { $smallmessage = s($smallmessage); } } else { if ($message_users->notification) { //its a notification with no smallmessage so just say they have a notification $smallmessage = get_string('unreadnewnotification', 'message'); } } if (!empty($smallmessage)) { $strmessages .= '<div id="usermessage">' . s($smallmessage) . '</div>'; } } $strgomessage = get_string('gotomessages', 'message'); $strstaymessage = get_string('ignore', 'admin'); $url = $CFG->wwwroot . '/message/index.php'; $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')) . html_writer::start_tag('div', array('id' => 'newmessagetext')) . $strmessages . html_writer::end_tag('div') . html_writer::start_tag('div', array('id' => 'newmessagelinks')) . html_writer::link($url, $strgomessage, array('id' => 'notificationyes')) . ' ' . html_writer::link('', $strstaymessage, array('id' => 'notificationno')) . html_writer::end_tag('div'); html_writer::end_tag('div'); $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url)); $USER->message_lastpopup = time(); } }
/** * Adds branches and links to the settings navigation to add course activities * and resources. * * @param stdClass $course */ protected function add_course_editing_links($course) { global $CFG; require_once $CFG->dirroot . '/course/lib.php'; // Add `add` resources|activities branches $structurefile = $CFG->dirroot . '/course/format/' . $course->format . '/lib.php'; if (file_exists($structurefile)) { require_once $structurefile; $requestkey = call_user_func('callback_' . $course->format . '_request_key'); $formatidentifier = optional_param($requestkey, 0, PARAM_INT); } else { $requestkey = get_string('section'); $formatidentifier = optional_param($requestkey, 0, PARAM_INT); } $modinfo = get_fast_modinfo($course); $sections = $modinfo->get_section_info_all(); $addresource = $this->add(get_string('addresource')); $addactivity = $this->add(get_string('addactivity')); if ($formatidentifier !== 0) { $addresource->force_open(); $addactivity->force_open(); } $this->get_course_modules($course); foreach ($sections as $section) { if ($formatidentifier !== 0 && $section->section != $formatidentifier) { continue; } $sectionurl = new moodle_url('/course/view.php', array('id' => $course->id, $requestkey => $section->section)); if ($section->section == 0) { $sectionresources = $addresource->add(get_string('course'), $sectionurl, self::TYPE_SETTING); $sectionactivities = $addactivity->add(get_string('course'), $sectionurl, self::TYPE_SETTING); } else { $sectionname = get_section_name($course, $section); $sectionresources = $addresource->add($sectionname, $sectionurl, self::TYPE_SETTING); $sectionactivities = $addactivity->add($sectionname, $sectionurl, self::TYPE_SETTING); } foreach ($resources as $value => $resource) { $url = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey(), 'section' => $section->section)); $pos = strpos($value, '&type='); if ($pos !== false) { $url->param('add', textlib::substr($value, 0, $pos)); $url->param('type', textlib::substr($value, $pos + 6)); } else { $url->param('add', $value); } $sectionresources->add($resource, $url, self::TYPE_SETTING); } $subbranch = false; foreach ($activities as $activityname => $activity) { if ($activity === '--') { $subbranch = false; continue; } if (strpos($activity, '--') === 0) { $subbranch = $sectionactivities->add(trim($activity, '-')); continue; } $url = new moodle_url('/course/mod.php', array('id' => $course->id, 'sesskey' => sesskey(), 'section' => $section->section)); $pos = strpos($activityname, '&type='); if ($pos !== false) { $url->param('add', textlib::substr($activityname, 0, $pos)); $url->param('type', textlib::substr($activityname, $pos + 6)); } else { $url->param('add', $activityname); } if ($subbranch !== false) { $subbranch->add($activity, $url, self::TYPE_SETTING); } else { $sectionactivities->add($activity, $url, self::TYPE_SETTING); } } } }
/** * Splits the custom parameters field to the various parameters * * @param string $customstr String containing the parameters * * @return Array of custom parameters */ function lti_split_custom_parameters($customstr) { $lines = preg_split("/[\n;]/", $customstr); $retval = array(); foreach ($lines as $line) { $pos = strpos($line, "="); if ( $pos === false || $pos < 1 ) { continue; } $key = trim(textlib::substr($line, 0, $pos)); $val = trim(textlib::substr($line, $pos+1, strlen($line))); $key = lti_map_keyname($key); $retval['custom_'.$key] = $val; } return $retval; }