function validation($data, $files) { global $DB, $CFG; $id = optional_param('id', -1, PARAM_INT); $errors = array(); $errors = parent::validation($data, $files); if ($data['schoolid'] == 0) { $errors['schoolid'] = get_string('schoolrequired', 'local_collegestructure'); } if ($data['id'] < 0) { $examtypes1 = $DB->get_record('local_examtypes', array('schoolid' => $data['schoolid'], 'examtype' => $data['examtype'])); $exam1 = core_text::strtolower($examtypes1->examtype); $exam2 = core_text::strtolower($data['examtype']); if ($exam1 == $exam2) { $errors['examtype'] = get_string('examexits', 'local_examtype'); } } if ($data['id'] > 0) { $exists = $DB->get_field('local_examtypes', 'examtype', array('id' => $id)); if (!($exists === $data['examtype'] )) { $examtypes1 = $DB->get_record('local_examtypes', array('schoolid' => $data['schoolid'], 'examtype' => $data['examtype'])); $exam1 = core_text::strtolower($examtypes1->examtype); $exam2 = core_text::strtolower($data['examtype']); if ($exam1 == $exam2) { $errors['examtype'] = get_string('examexits', 'local_examtype'); } } } return $errors; }
function definition() { global $DB; $mform =& $this->_form; $mform->addElement('hidden', 'username'); $mform->setType('username', PARAM_TEXT); //doi/isbn $select_list = array(); $books = $DB->get_records_sql('SELECT b.*, p.name as publisher FROM {rcommon_books} b JOIN {rcommon_publisher} p ON b.publisherid = p.id ORDER BY p.name, b.name '); foreach ($books as $book) { if (in_array(core_text::strtolower($book->format), rcommon_book::$allowedformats)) { if (!isset($select_list[$book->publisher])) { $select_list[$book->publisher] = array(); } $select_list[$book->publisher][$book->isbn] = $book->name; } } $mform->addElement('selectgroups', 'isbn', 'DOI / ISBN', $select_list); $mform->addRule('isbn', null, 'required', null, 'client'); //key $mform->addElement('text', 'credentials', get_string('key', 'local_rcommon'), array('maxlength' => 255, 'size' => 45)); $mform->setType('credentials', PARAM_TEXT); $mform->addRule('credentials', null, 'required', null, 'client'); //buttons $this->add_action_buttons(); }
/** * Form validation * * @param array $data * @param array $files * @return array $errors An array of validataion errors for the form. */ function validation($data, $files) { global $COURSE, $DB; $errors = parent::validation($data, $files); $name = trim($data['name']); if (isset($data['idnumber'])) { $idnumber = trim($data['idnumber']); } else { $idnumber = ''; } if ($data['id'] and $grouping = $DB->get_record('groupings', array('id' => $data['id']))) { if (core_text::strtolower($grouping->name) != core_text::strtolower($name)) { if (groups_get_grouping_by_name($COURSE->id, $name)) { $errors['name'] = get_string('groupingnameexists', 'group', $name); } } if (!empty($idnumber) && $grouping->idnumber != $idnumber) { if (groups_get_grouping_by_idnumber($COURSE->id, $idnumber)) { $errors['idnumber'] = get_string('idnumbertaken'); } } } else { if (groups_get_grouping_by_name($COURSE->id, $name)) { $errors['name'] = get_string('groupingnameexists', 'group', $name); } else { if (!empty($idnumber) && groups_get_grouping_by_idnumber($COURSE->id, $idnumber)) { $errors['idnumber'] = get_string('idnumbertaken'); } } } return $errors; }
/** * Return the user devices for a specific app. * * @param string $appname the app name . * @param int $userid if empty take the current user. * @return array all the devices */ public function get_user_devices($appname, $userid = null) { global $USER, $DB; if (empty($userid)) { $userid = $USER->id; } $devices = array(); $params = array('appid' => $appname, 'userid' => $userid); // First, we look all the devices registered for this user in the Moodle core. // We are going to allow only ios devices (since these are the ones that supports PUSH notifications). $userdevices = $DB->get_records('user_devices', $params); foreach ($userdevices as $device) { if (core_text::strtolower($device->platform)) { // Check if the device is known by airnotifier. if (!($airnotifierdev = $DB->get_record('message_airnotifier_devices', array('userdeviceid' => $device->id)))) { // We have to create the device token in airnotifier. if (!$this->create_token($device->pushid)) { continue; } $airnotifierdev = new stdClass(); $airnotifierdev->userdeviceid = $device->id; $airnotifierdev->enable = 1; $airnotifierdev->id = $DB->insert_record('message_airnotifier_devices', $airnotifierdev); } $device->id = $airnotifierdev->id; $device->enable = $airnotifierdev->enable; $devices[] = $device; } } return $devices; }
public function definition() { global $CFG; $mform =& $this->_form; // General options. $mform->addElement('header', 'general', get_string('general', 'form')); $mform->addElement('text', 'name', get_string('name'), array('size' => '48', 'maxlength' => '255')); $mform->setType('name', PARAM_TEXT); $mform->addRule('name', null, 'required', null, 'client'); $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'client'); if ($CFG->branch < 29) { $this->add_intro_editor(true, get_string('description')); } else { $this->standard_intro_elements(); } // Advanced options. $mform->addElement('header', 'galleryoptions', get_string('advanced')); $mform->addElement('select', 'perpage', get_string('imagesperpage', 'lightboxgallery'), $this->get_perpage_options()); $mform->setType('perpage', PARAM_INTEGER); $mform->addElement('select', 'perrow', get_string('imagesperrow', 'lightboxgallery'), $this->get_perrow_options()); $mform->setType('perrow', PARAM_INTEGER); $yesno = array(0 => get_string('no'), 1 => get_string('yes')); $mform->addElement('select', 'captionfull', get_string('captionfull', 'lightboxgallery'), $yesno); $captionposopts = array('0' => get_string('position_bottom', 'lightboxgallery'), '1' => get_string('position_top', 'lightboxgallery'), '2' => get_string('hide')); $mform->addElement('select', 'captionpos', get_string('captionpos', 'lightboxgallery'), $captionposopts); $autoresizegroup = array(); $autoresizegroup[] =& $mform->createElement('select', 'autoresize', get_string('autoresize', 'lightboxgallery'), $this->get_autoresize_options()); $autoresizegroup[] =& $mform->createElement('checkbox', 'autoresizedisabled', null, get_string('disable')); $mform->addGroup($autoresizegroup, 'autoresizegroup', get_string('autoresize', 'lightboxgallery'), ' ', false); $mform->setType('autoresize', PARAM_INTEGER); $mform->disabledIf('autoresizegroup', 'autoresizedisabled', 'checked'); $mform->addHelpButton('autoresizegroup', 'autoresize', 'lightboxgallery'); $mform->addElement('select', 'resize', sprintf('%s (%s)', get_string('edit_resize', 'lightboxgallery'), core_text::strtolower(get_string('upload'))), lightboxgallery_resize_options()); $mform->setType('resize', PARAM_INTEGER); $mform->disabledIf('resize', 'autoresize', 'eq', 1); $mform->disabledIf('resize', 'autoresizedisabled', 'checked'); $mform->addElement('select', 'comments', get_string('allowcomments', 'lightboxgallery'), $yesno); $mform->setType('comments', PARAM_INTEGER); $mform->addElement('select', 'ispublic', get_string('makepublic', 'lightboxgallery'), $yesno); $mform->setType('ispublic', PARAM_INTEGER); if (lightboxgallery_rss_enabled()) { $mform->addElement('select', 'rss', get_string('allowrss', 'lightboxgallery'), $yesno); $mform->setType('rss', PARAM_INTEGER); } else { $mform->addElement('static', 'rssdisabled', get_string('allowrss', 'lightboxgallery'), get_string('rssglobaldisabled', 'admin')); } $mform->addElement('select', 'extinfo', get_string('extendedinfo', 'lightboxgallery'), $yesno); $mform->setType('extinfo', PARAM_INTEGER); // Module options. $features = array('groups' => false, 'groupings' => false, 'groupmembersonly' => false, 'outcomes' => false, 'gradecat' => false, 'idnumber' => false); $this->standard_coursemodule_elements($features); $this->add_action_buttons(); }
function get_books_structure_publisher($publisher, $isbn = false) { global $OUTPUT; set_time_limit(0); $books = get_books($publisher); try { if (!empty($books)) { // Fix bug, when there is just one received book if (!is_array($books) || !isset($books[0])) { $books = array($books); } echo '<ol>'; foreach ($books as $book) { // Disable scorm import $bookformat = core_text::strtolower($book['formato']); if (!in_array($bookformat, rcommon_book::$allowedformats)) { continue; } $codisbn = $book['isbn']; // Si se ha especificado un isbn guarda el libro if (!$isbn || $codisbn == $isbn) { $message = 'ISBN: ' . $codisbn; // Obtiene los datos del indice del libro try { $instance = new StdClass(); $instance->isbn = $codisbn; $instance->name = $book['titulo']; $instance->summary = $book['titulo']; $instance->format = $bookformat; $instance->levelid = isset($book['nivel']) ? $book['nivel'] : false; $instance->publisherid = $publisher->id; rcommon_book::add_update($instance); get_book_structure($publisher, $codisbn); echo '<li>' . $OUTPUT->notification($message, 'notifysuccess') . '</li>'; } catch (Exception $e) { $message .= " - Error: " . $e->getMessage(); echo '<li>' . $OUTPUT->notification($message) . '</li>'; } } } echo '</ol>'; return true; } else { echo get_string('nobooks', 'local_rcommon'); return true; } } catch (Exception $fault) { $message = rcommon_ws_error('get_books_structure_publisher', $fault->getMessage()); throw new Exception($message); } return false; }
/** * Returns list of children which are either files matching the specified extensions * or folders that contain at least one such file. * * @param string|array $extensions, either '*' or array of lowercase extensions, i.e. array('.gif','.jpg') * @return array of file_info instances */ public function get_non_empty_children($extensions = '*') { $items = $this->gallery->get_items(); $result = array(); foreach ($items as $item) { $file = $item->get_file(); $extension = core_text::strtolower(pathinfo($file->get_filename(), PATHINFO_EXTENSION)); if ($file->is_directory() || $extensions === '*' || !empty($extension) && in_array('.' . $extension, $extensions)) { $fileinfo = new file_info_stored($this->browser, $this->context, $file, $this->urlbase, $this->topvisiblename, $this->itemidused, $this->readaccess, $this->writeaccess, false); if (!$file->is_directory() || $fileinfo->count_non_empty_children($extensions)) { $result[] = $fileinfo; } } } return $result; }
/** * Custom form validation * * @param array $data * @param array $files * @return array */ public function validation($data, $files) { $errors = parent::validation($data, $files); if (isset($data['rawname'])) { $newname = core_text::strtolower($data['rawname']); $tag = $this->_customdata['tag']; if ($tag->name != $newname) { // The name has changed, let's make sure it's not another existing tag. if (core_tag_tag::get_by_name($tag->tagcollid, $newname)) { // Something exists already, so flag an error. $errors['rawname'] = get_string('namesalreadybeeingused', 'tag'); } } } return $errors; }
/** * Checks if $query is one of the available subplugins. * * @param string $query The string to search for * @return bool Returns true if found, false if not */ public function is_related($query) { if (parent::is_related($query)) { return true; } $subplugins = core_component::get_plugin_list('tinymce'); foreach ($subplugins as $name => $dir) { if (stripos($name, $query) !== false) { return true; } $namestr = get_string('pluginname', 'tinymce_' . $name); if (strpos(core_text::strtolower($namestr), core_text::strtolower($query)) !== false) { return true; } } return false; }
/** * Checks if $query is one of the available log plugins. * * @param string $query The string to search for * @return bool Returns true if found, false if not */ public function is_related($query) { if (parent::is_related($query)) { return true; } $query = core_text::strtolower($query); $plugins = \tool_log\log\manager::get_store_plugins(); foreach ($plugins as $plugin => $fulldir) { if (strpos(core_text::strtolower($plugin), $query) !== false) { return true; } $localised = get_string('pluginname', $plugin); if (strpos(core_text::strtolower($localised), $query) !== false) { return true; } } return false; }
/** * Check if this is $query is related to a choice * * @param string $query * @return bool true if related, false if not */ public function is_related($query) { if (parent::is_related($query)) { return true; } if (!$this->load_choices()) { return false; } foreach ($this->choices as $key => $value) { if (strpos(core_text::strtolower($key), $query) !== false) { return true; } if (strpos(core_text::strtolower($value), $query) !== false) { return true; } } return false; }
/** * Checks if $query is one of the available dataformfield plugins. * * @param string $query The string to search for * @return bool Returns true if found, false if not */ public function is_related($query) { if (parent::is_related($query)) { return true; } $query = \core_text::strtolower($query); $plugins = \core_component::get_plugin_list('dataformfield'); foreach ($plugins as $plugin => $fulldir) { if (strpos(\core_text::strtolower($plugin), $query) !== false) { return true; } $localised = get_string('pluginname', "dataformfield_{$plugin}"); if (strpos(\core_text::strtolower($localised), $query) !== false) { return true; } } return false; }
/** * Creates a user * * @param stdClass $user user to create * @param bool $updatepassword if true, authentication plugin will update password. * @return int id of the newly created user */ function user_create_user($user, $updatepassword = true) { global $DB; // Set the timecreate field to the current time. if (!is_object($user)) { $user = (object) $user; } // Check username. if ($user->username !== core_text::strtolower($user->username)) { throw new moodle_exception('usernamelowercase'); } else { if ($user->username !== clean_param($user->username, PARAM_USERNAME)) { throw new moodle_exception('invalidusername'); } } // Save the password in a temp value for later. if ($updatepassword && isset($user->password)) { // Check password toward the password policy. if (!check_password_policy($user->password, $errmsg)) { throw new moodle_exception($errmsg); } $userpassword = $user->password; unset($user->password); } $user->timecreated = time(); $user->timemodified = $user->timecreated; // Insert the user into the database. $newuserid = $DB->insert_record('user', $user); // Create USER context for this user. $usercontext = context_user::instance($newuserid); // Update user password if necessary. if (isset($userpassword)) { // Get full database user row, in case auth is default. $newuser = $DB->get_record('user', array('id' => $newuserid)); $authplugin = get_auth_plugin($newuser->auth); $authplugin->user_update_password($newuser, $userpassword); } // Trigger event. $event = \core\event\user_created::create(array('objectid' => $newuserid, 'context' => $usercontext)); $event->trigger(); return $newuserid; }
public function output() { global $CFG, $OUTPUT; $stradd = get_string('add'); $fs = get_file_storage(); $storedfile = $fs->get_file($this->context->id, 'mod_lightboxgallery', 'gallery_images', '0', '/', $this->image); $image = new lightboxgallery_image($storedfile, $this->gallery, $this->cm); $manualform = '<input type="text" name="tag" /><input type="submit" value="' . $stradd . '" />'; $manualform = $this->enclose_in_form($manualform); $iptcform = ''; $deleteform = ''; $path = $storedfile->copy_content_to_temp(); $tags = $image->get_tags(); $size = getimagesize($path, $info); if (isset($info['APP13'])) { $iptc = iptcparse($info['APP13']); if (isset($iptc['2#025'])) { $iptcform = '<input type="hidden" name="iptc" value="1" />'; sort($iptc['2#025']); foreach ($iptc['2#025'] as $tag) { $tag = core_text::strtolower($tag); $exists = $tags && in_array($tag, array_values($tags)); $tag = htmlentities($tag); $iptcform .= '<label ' . ($exists ? 'class="tag-exists"' : '') . '><input type="checkbox" name="iptctags[]" value="' . $tag . '" />' . $tag . '</label><br />'; } $iptcform .= '<input type="submit" value="' . $stradd . '" />'; $iptcform = '<span class="tag-head"> ' . get_string('tagsiptc', 'lightboxgallery') . '</span>' . $this->enclose_in_form($iptcform); } } $iptcaddurl = new moodle_url('/mod/lightboxgallery/edit/tag/import.php', array('id' => $this->gallery->id)); $iptcform .= $OUTPUT->single_button($iptcaddurl, get_string('tagsimport', 'lightboxgallery')); if ($tags = $image->get_tags()) { $deleteform = '<input type="hidden" name="delete" value="1" />'; foreach ($tags as $tag) { $deleteform .= '<label><input type="checkbox" name="deletetags[]" value="' . $tag->id . '" /> ' . htmlentities(utf8_decode($tag->description)) . '</label><br />'; } $deleteform .= '<input type="submit" value="' . get_string('remove') . '" />'; $deleteform = '<span class="tag-head"> ' . get_string('tagscurrent', 'lightboxgallery') . '</span>' . $this->enclose_in_form($deleteform); } return $manualform . $iptcform . $deleteform; }
protected static function replace_callback($langblock) { global $CFG; static $parentcache; if (!isset($parentcache)) { $parentcache = array(); } $mylang = current_language(); if (!array_key_exists($mylang, $parentcache)) { $parentlang = get_parent_language($mylang); $parentcache[$mylang] = $parentlang; } else { $parentlang = $parentcache[$mylang]; } $blocklang = trim(core_text::strtolower($langblock[1])); $blocktext = $langblock[2]; if ($mylang === $blocklang || $parentlang === $blocklang) { return $blocktext; } return ''; }
/** * Search plugins for the specified string * * @param string $query The string to search for * @return array */ public function search($query) { if ($result = parent::search($query)) { return $result; } $found = false; foreach (core_component::get_plugin_list($this->subtype) as $name => $notused) { if (strpos(core_text::strtolower(get_string('pluginname', $this->subtype . '_' . $name)), $query) !== false) { $found = true; break; } } if ($found) { $result = new stdClass(); $result->page = $this; $result->settings = array(); return array($this->name => $result); } else { return array(); } }
/** * Checks if $query is one of the available webservices * * @param string $query The string to search for * @return bool Returns true if found, false if not */ public function is_related($query) { if (parent::is_related($query)) { return true; } $protocols = core_component::get_plugin_list('webservice'); foreach ($protocols as $protocol => $location) { if (strpos($protocol, $query) !== false) { return true; } $protocolstr = get_string('pluginname', 'webservice_' . $protocol); if (strpos(core_text::strtolower($protocolstr), $query) !== false) { return true; } } return false; }
if (function_exists('weblink_auth')) { $user = weblink_auth($SESSION->wantsurl); } if ($user) { $frm->username = $user->username; } else { $frm = data_submitted(); } } else { $frm = data_submitted(); } } /// Check if the user has actually submitted login data to us if ($frm and isset($frm->username)) { // Login WITH cookies $frm->username = trim(core_text::strtolower($frm->username)); if (is_enabled_auth('none')) { if ($frm->username !== clean_param($frm->username, PARAM_USERNAME)) { $errormsg = get_string('username') . ': ' . get_string("invalidusername"); $errorcode = 2; $user = null; } } if ($user) { //user already supplied by aut plugin prelogin hook } else { if ($frm->username == 'guest' and empty($CFG->guestloginbutton)) { $user = false; /// Can't log in as guest if guest button is disabled $frm = false; } else {
/** * Update a user with a user object (will compare against the ID) * * @param stdClass $user the user to update * @param bool $updatepassword if true, authentication plugin will update password. * @param bool $triggerevent set false if user_updated event should not be triggred. */ function user_update_user($user, $updatepassword = true, $triggerevent = true) { global $DB; // set the timecreate field to the current time if (!is_object($user)) { $user = (object) $user; } //check username if (isset($user->username)) { if ($user->username !== core_text::strtolower($user->username)) { throw new moodle_exception('usernamelowercase'); } else { if ($user->username !== clean_param($user->username, PARAM_USERNAME)) { throw new moodle_exception('invalidusername'); } } } // Unset password here, for updating later, if password update is required. if ($updatepassword && isset($user->password)) { //check password toward the password policy if (!check_password_policy($user->password, $errmsg)) { throw new moodle_exception($errmsg); } $passwd = $user->password; unset($user->password); } // Make sure calendartype, if set, is valid. if (!empty($user->calendartype)) { $availablecalendartypes = \core_calendar\type_factory::get_list_of_calendar_types(); // If it doesn't exist, then unset this value, we do not want to update the user's value. if (empty($availablecalendartypes[$user->calendartype])) { unset($user->calendartype); } } else { // Unset this variable, must be an empty string, which we do not want to update the calendartype to. unset($user->calendartype); } $user->timemodified = time(); $DB->update_record('user', $user); if ($updatepassword) { // Get full user record. $updateduser = $DB->get_record('user', array('id' => $user->id)); // if password was set, then update its hash if (isset($passwd)) { $authplugin = get_auth_plugin($updateduser->auth); if ($authplugin->can_change_password()) { $authplugin->user_update_password($updateduser, $passwd); } } } // Trigger event if required. if ($triggerevent) { \core\event\user_updated::create_from_userid($user->id)->trigger(); } }
</option> </select> </p> </fieldset> </form> </div> </div> <script type="text/javascript"> function change(e){ multipdfs = e; } </script> <?php } if (has_capability("mod/emarking:downloadexam", $context)) { $buttontext = $exam->status < EMARKING_EXAM_BEING_PROCESSED ? get_string('exam', 'mod_emarking') . ' ' . core_text::strtolower(get_string('examstatusbeingprocessed', 'mod_emarking')) : get_string('downloadexam', 'mod_emarking'); $disabled = $exam->status < EMARKING_EXAM_BEING_PROCESSED ? 'disabled' : ''; $downloadexambutton = "<input type='button' class='downloademarking' examid ='{$exam->id}' value='" . $buttontext . "' {$disabled}>"; echo $downloadexambutton; } if ($issupervisor) { // Active types tab. $urlscan = new moodle_url("/mod/emarking/print/enablefeatures.php", array("id" => $cm->id, "type" => EMARKING_TYPE_PRINT_SCAN)); $urlosm = new moodle_url("/mod/emarking/print/enablefeatures.php", array("id" => $cm->id, "type" => EMARKING_TYPE_ON_SCREEN_MARKING)); echo html_writer::start_tag('div'); if ($emarking->type == EMARKING_TYPE_PRINT_ONLY) { echo $OUTPUT->single_button($urlscan, get_string("enablescan", "mod_emarking"), 'GET', array('class' => 'form-submit')); } else { if ($emarking->type == EMARKING_TYPE_PRINT_SCAN) { echo $OUTPUT->single_button($urlosm, get_string("enableosm", "mod_emarking"), 'GET', array('class' => 'form-submit')); }
/** * Construct a user menu, returning HTML that can be echoed out by a * layout file. * * @param stdClass $user A user object, usually $USER. * @param bool $withlinks true if a dropdown should be built. * @return string HTML fragment. */ public function user_menu($user = null, $withlinks = null) { global $USER, $CFG; require_once($CFG->dirroot . '/user/lib.php'); if (is_null($user)) { $user = $USER; } // Note: this behaviour is intended to match that of core_renderer::login_info, // but should not be considered to be good practice; layout options are // intended to be theme-specific. Please don't copy this snippet anywhere else. if (is_null($withlinks)) { $withlinks = empty($this->page->layout_options['nologinlinks']); } // Add a class for when $withlinks is false. $usermenuclasses = 'usermenu'; if (!$withlinks) { $usermenuclasses .= ' withoutlinks'; } $returnstr = ""; // If during initial install, return the empty return string. if (during_initial_install()) { return $returnstr; } $loginpage = $this->is_login_page(); $loginurl = get_login_url(); // If not logged in, show the typical not-logged-in string. if (!isloggedin()) { $returnstr = get_string('loggedinnot', 'moodle'); if (!$loginpage) { $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)'; } return html_writer::div( html_writer::span( $returnstr, 'login' ), $usermenuclasses ); } // If logged in as a guest user, show a string to that effect. if (isguestuser()) { $returnstr = get_string('loggedinasguest'); if (!$loginpage && $withlinks) { $returnstr .= " (<a href=\"$loginurl\">".get_string('login').'</a>)'; } return html_writer::div( html_writer::span( $returnstr, 'login' ), $usermenuclasses ); } // Get some navigation opts. $opts = user_get_user_navigation_info($user, $this->page); $avatarclasses = "avatars"; $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current'); $usertextcontents = $opts->metadata['userfullname']; // Other user. if (!empty($opts->metadata['asotheruser'])) { $avatarcontents .= html_writer::span( $opts->metadata['realuseravatar'], 'avatar realuser' ); $usertextcontents = $opts->metadata['realuserfullname']; $usertextcontents .= html_writer::tag( 'span', get_string( 'loggedinas', 'moodle', html_writer::span( $opts->metadata['userfullname'], 'value' ) ), array('class' => 'meta viewingas') ); } // Role. if (!empty($opts->metadata['asotherrole'])) { $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename']))); $usertextcontents .= html_writer::span( $opts->metadata['rolename'], 'meta role role-' . $role ); } // User login failures. if (!empty($opts->metadata['userloginfail'])) { $usertextcontents .= html_writer::span( $opts->metadata['userloginfail'], 'meta loginfailures' ); } // MNet. if (!empty($opts->metadata['asmnetuser'])) { $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername']))); $usertextcontents .= html_writer::span( $opts->metadata['mnetidprovidername'], 'meta mnet mnet-' . $mnet ); } $returnstr .= html_writer::span( html_writer::span($usertextcontents, 'usertext') . html_writer::span($avatarcontents, $avatarclasses), 'userbutton' ); // Create a divider (well, a filler). $divider = new action_menu_filler(); $divider->primary = false; $am = new action_menu(); $am->initialise_js($this->page); $am->set_menu_trigger( $returnstr ); $am->set_alignment(action_menu::TR, action_menu::BR); $am->set_nowrap_on_items(); if ($withlinks) { $navitemcount = count($opts->navitems); $idx = 0; foreach ($opts->navitems as $key => $value) { switch ($value->itemtype) { case 'divider': // If the nav item is a divider, add one and skip link processing. $am->add($divider); break; case 'invalid': // Silently skip invalid entries (should we post a notification?). break; case 'link': // Process this as a link item. $pix = null; if (isset($value->pix) && !empty($value->pix)) { $pix = new pix_icon($value->pix, $value->title, null, array('class' => 'iconsmall')); } else if (isset($value->imgsrc) && !empty($value->imgsrc)) { $value->title = html_writer::img( $value->imgsrc, $value->title, array('class' => 'iconsmall') ) . $value->title; } $al = new action_menu_link_secondary( $value->url, $pix, $value->title, array('class' => 'icon') ); $am->add($al); break; } $idx++; // Add dividers after the first item and before the last item. if ($idx == 1 || $idx == $navitemcount - 1) { $am->add($divider); } } } return html_writer::div( $this->render($am), $usermenuclasses ); }
/** * Rename old backup files to current backup files. * * When added the setting 'backup_shortname' (MDL-28657) the backup file names did not contain the id of the course. * Further we fixed that behaviour by forcing the id to be always present in the file name (MDL-33812). * This function will explore the backup directory and attempt to rename the previously created files to include * the id in the name. Doing this will put them back in the process of deleting the excess backups for each course. * * This function manually recreates the file name, instead of using * {@link backup_plan_dbops::get_default_backup_filename()}, use it carefully if you're using it outside of the * usual upgrade process. * * @see backup_cron_automated_helper::remove_excess_backups() * @link http://tracker.moodle.org/browse/MDL-35116 * @return void * @since Moodle 2.4 */ function upgrade_rename_old_backup_files_using_shortname() { global $CFG; $dir = get_config('backup', 'backup_auto_destination'); $useshortname = get_config('backup', 'backup_shortname'); if (empty($dir) || !is_dir($dir) || !is_writable($dir)) { return; } require_once($CFG->dirroot.'/backup/util/includes/backup_includes.php'); $backupword = str_replace(' ', '_', core_text::strtolower(get_string('backupfilename'))); $backupword = trim(clean_filename($backupword), '_'); $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-'; $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#'; $thirtyapril = strtotime('30 April 2012 00:00'); // Reading the directory. if (!$files = scandir($dir)) { return; } foreach ($files as $file) { // Skip directories and files which do not start with the common prefix. // This avoids working on files which are not related to this issue. if (!is_file($dir . '/' . $file) || !preg_match($regex, $file)) { continue; } // Extract the information from the XML file. try { $bcinfo = backup_general_helper::get_backup_information_from_mbz($dir . '/' . $file); } catch (backup_helper_exception $e) { // Some error while retrieving the backup informations, skipping... continue; } // Make sure this a course backup. if ($bcinfo->format !== backup::FORMAT_MOODLE || $bcinfo->type !== backup::TYPE_1COURSE) { continue; } // Skip the backups created before the short name option was initially introduced (MDL-28657). // This was integrated on the 2nd of May 2012. Let's play safe with timezone and use the 30th of April. if ($bcinfo->backup_date < $thirtyapril) { continue; } // Let's check if the file name contains the ID where it is supposed to be, if it is the case then // we will skip the file. Of course it could happen that the course ID is identical to the course short name // even though really unlikely, but then renaming this file is not necessary. If the ID is not found in the // file name then it was probably the short name which was used. $idfilename = $filename . $bcinfo->original_course_id . '-'; $idregex = '#^'.preg_quote($idfilename, '#').'.*\.mbz$#'; if (preg_match($idregex, $file)) { continue; } // Generating the file name manually. We do not use backup_plan_dbops::get_default_backup_filename() because // it will query the database to get some course information, and the course could not exist any more. $newname = $filename . $bcinfo->original_course_id . '-'; if ($useshortname) { $shortname = str_replace(' ', '_', $bcinfo->original_course_shortname); $shortname = core_text::strtolower(trim(clean_filename($shortname), '_')); $newname .= $shortname . '-'; } $backupdateformat = str_replace(' ', '_', get_string('backupnameformat', 'langconfig')); $date = userdate($bcinfo->backup_date, $backupdateformat, 99, false); $date = core_text::strtolower(trim(clean_filename($date), '_')); $newname .= $date; if (isset($bcinfo->root_settings['users']) && !$bcinfo->root_settings['users']) { $newname .= '-nu'; } else if (isset($bcinfo->root_settings['anonymize']) && $bcinfo->root_settings['anonymize']) { $newname .= '-an'; } $newname .= '.mbz'; // Final check before attempting the renaming. if ($newname == $file || file_exists($dir . '/' . $newname)) { continue; } @rename($dir . '/' . $file, $dir . '/' . $newname); } }
/** * This function will highlight instances of $needle in $haystack * * It's faster that the above function {@link highlight()} and doesn't care about * HTML or anything. * * @param string $needle The string to search for * @param string $haystack The string to search for $needle in * @return string The highlighted HTML */ function highlightfast($needle, $haystack) { if (empty($needle) or empty($haystack)) { return $haystack; } $parts = explode(core_text::strtolower($needle), core_text::strtolower($haystack)); if (count($parts) === 1) { return $haystack; } $pos = 0; foreach ($parts as $key => $part) { $parts[$key] = substr($haystack, $pos, strlen($part)); $pos += strlen($part); $parts[$key] .= '<span class="highlight">' . substr($haystack, $pos, strlen($needle)) . '</span>'; $pos += strlen($needle); } return str_replace('<span class="highlight"></span>', '', join('', $parts)); }
/** * Perform a file format conversion on the specified document. * * @param stored_file $file the file we want to preview * @param string $format The desired format - e.g. 'pdf'. Formats are specified by file extension. * @return stored_file|bool false if unable to create the conversion, stored file otherwise */ protected function create_converted_document(stored_file $file, $format) { global $CFG; if (empty($CFG->pathtounoconv) || !file_is_executable(trim($CFG->pathtounoconv))) { // No conversions are possible, sorry. return false; } $fileextension = core_text::strtolower(pathinfo($file->get_filename(), PATHINFO_EXTENSION)); if (!self::is_format_supported_by_unoconv($fileextension)) { return false; } if (!self::is_format_supported_by_unoconv($format)) { return false; } // Copy the file to the tmp dir. $uniqdir = "core_file/conversions/" . uniqid($file->get_id() . "-", true); $tmp = make_temp_directory($uniqdir); $localfilename = $file->get_filename(); // Safety. $localfilename = clean_param($localfilename, PARAM_FILE); $filename = $tmp . '/' . $localfilename; try { // This function can either return false, or throw an exception so we need to handle both. if ($file->copy_content_to($filename) === false) { throw new file_exception('storedfileproblem', 'Could not copy file contents to temp file.'); } } catch (file_exception $fe) { remove_dir($uniqdir); throw $fe; } $newtmpfile = pathinfo($filename, PATHINFO_FILENAME) . '.' . $format; // Safety. $newtmpfile = $tmp . '/' . clean_param($newtmpfile, PARAM_FILE); $cmd = escapeshellcmd(trim($CFG->pathtounoconv)) . ' ' . escapeshellarg('-f') . ' ' . escapeshellarg($format) . ' ' . escapeshellarg('-o') . ' ' . escapeshellarg($newtmpfile) . ' ' . escapeshellarg($filename); $output = null; $currentdir = getcwd(); chdir($tmp); $result = exec($cmd, $output); chdir($currentdir); if (!file_exists($newtmpfile)) { remove_dir($uniqdir); // Cleanup. return false; } $context = context_system::instance(); $record = array('contextid' => $context->id, 'component' => 'core', 'filearea' => 'documentconversion', 'itemid' => 0, 'filepath' => '/' . $format . '/', 'filename' => $file->get_contenthash()); $convertedfile = $this->create_file_from_pathname($record, $newtmpfile); // Cleanup. remove_dir($uniqdir); return $convertedfile; }
/** * @todo Document this function * @param array $linkarray * @return array */ function filter_remove_duplicates($linkarray) { $concepts = array(); // keep a record of concepts as we cycle through $lconcepts = array(); // a lower case version for case insensitive $cleanlinks = array(); foreach ($linkarray as $key => $filterobject) { if ($filterobject->casesensitive) { $exists = in_array($filterobject->phrase, $concepts); } else { $exists = in_array(core_text::strtolower($filterobject->phrase), $lconcepts); } if (!$exists) { $cleanlinks[] = $filterobject; $concepts[] = $filterobject->phrase; $lconcepts[] = core_text::strtolower($filterobject->phrase); } } return $cleanlinks; }
/** * Test the function date_format_string(). */ public function test_date_format_string() { global $CFG; // Forcing locale and timezone. $oldlocale = setlocale(LC_TIME, '0'); if ($CFG->ostype == 'WINDOWS') { setlocale(LC_TIME, 'English_Australia.1252'); } else { setlocale(LC_TIME, 'en_AU.UTF-8'); } $systemdefaulttimezone = date_default_timezone_get(); date_default_timezone_set('Australia/Perth'); $tests = array(array('tz' => 99, 'str' => '%A, %d %B %Y, %I:%M %p', 'expected' => 'Saturday, 01 January 2011, 06:00 PM'), array('tz' => 0, 'str' => '%A, %d %B %Y, %I:%M %p', 'expected' => 'Saturday, 01 January 2011, 10:00 AM'), array('tz' => -12, 'str' => '%A, %d %B %Y, %I:%M %p', 'expected' => 'Saturday, 01 January 2011, 10:00 AM'), array('tz' => 99, 'str' => 'Žluťoučký koníček %A', 'expected' => 'Žluťoučký koníček Saturday'), array('tz' => 99, 'str' => '言語設定言語 %A', 'expected' => '言語設定言語 Saturday'), array('tz' => 99, 'str' => '简体中文简体 %A', 'expected' => '简体中文简体 Saturday')); // Note: date_format_string() uses the timezone only to differenciate // the server time from the UTC time. It does not modify the timestamp. // Hence similar results for timezones <= 13. // On different systems case of AM PM changes so compare case insensitive. foreach ($tests as $test) { $str = date_format_string(1293876000, $test['str'], $test['tz']); $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str)); } // Restore system default values. date_default_timezone_set($systemdefaulttimezone); setlocale(LC_TIME, $oldlocale); }
/** * Saves the setting(s) provided in $data * * @param array $data An array of data, if not array returns empty str * @return mixed empty string on useless data or success, error string if failed */ public function write_setting($data) { if (!is_array($data)) { return ''; // ignore it } $result = ''; foreach ($data as $roleid => $data) { if (!$this->config_write('contexts_role' . $roleid, trim($data['contexts']))) { $return = get_string('errorsetting', 'admin'); } if (!$this->config_write('memberattribute_role' . $roleid, core_text::strtolower(trim($data['memberattribute'])))) { $return = get_string('errorsetting', 'admin'); } } return $result; }
/** * 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 * @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 = '...') { // If the plain text is shorter than the maximum length, return the whole text. if (core_text::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); $totallength = core_text::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 $linematchings) { // If there is any html-tag in this line, handle it and add it (uncounted) to the output. if (!empty($linematchings[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', $linematchings[1])) { if (preg_match('/^<\\s*\\/([^\\s]+?)\\s*>$/s', $linematchings[1], $tagmatchings)) { // Record closing tag. $tagdetails[] = (object) array('open' => false, 'tag' => core_text::strtolower($tagmatchings[1]), 'pos' => core_text::strlen($truncate)); } else { if (preg_match('/^<\\s*([^\\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) { // Record opening tag. $tagdetails[] = (object) array('open' => true, 'tag' => core_text::strtolower($tagmatchings[1]), 'pos' => core_text::strlen($truncate)); } else { if (preg_match('/^<!--\\[if\\s.*?\\]>$/s', $linematchings[1], $tagmatchings)) { $tagdetails[] = (object) array('open' => true, 'tag' => core_text::strtolower('if'), 'pos' => core_text::strlen($truncate)); } else { if (preg_match('/^<!--<!\\[endif\\]-->$/s', $linematchings[1], $tagmatchings)) { $tagdetails[] = (object) array('open' => false, 'tag' => core_text::strtolower('if'), 'pos' => core_text::strlen($truncate)); } } } } } // Add html-tag to $truncate'd text. $truncate .= $linematchings[1]; } // Calculate the length of the plain text part of the line; handle entities as one character. $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2])); if ($totallength + $contentlength > $ideal) { // The number of characters which are left. $left = $ideal - $totallength; $entitieslength = 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', $linematchings[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 - $entitieslength <= $left) { $left--; $entitieslength += core_text::strlen($entity[0]); } else { // No more characters left. break; } } } $breakpos = $left + $entitieslength; // 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 = core_text::substr($linematchings[2], $breakpos, 1)) { if ($char === '.' or $char === ' ') { $breakpos += 1; break; } else { if (strlen($char) > 2) { // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary. $breakpos += 1; break; } } } } } if ($breakpos == 0) { // This deals with the test_shorten_text_no_spaces case. $breakpos = $left + $entitieslength; } else { if ($breakpos > $left + $entitieslength) { // This deals with the previous for loop breaking on the first char. $breakpos = $left + $entitieslength; } } $truncate .= core_text::substr($linematchings[2], 0, $breakpos); // Maximum length is reached, so get off the loop. break; } else { $truncate .= $linematchings[2]; $totallength += $contentlength; } // If the maximum length is reached, get off the loop. if ($totallength >= $ideal) { break; } } // Add the defined ending to the text. $truncate .= $ending; // Now calculate the list of open html tags based on the truncate position. $opentags = array(); foreach ($tagdetails as $taginfo) { if ($taginfo->open) { // Add tag to the beginning of $opentags list. array_unshift($opentags, $taginfo->tag); } else { // Can have multiple exact same open tags, close the last one. $pos = array_search($taginfo->tag, array_reverse($opentags, true)); if ($pos !== false) { unset($opentags[$pos]); } } } // Close all unclosed html-tags. foreach ($opentags as $tag) { if ($tag === 'if') { $truncate .= '<!--<![endif]-->'; } else { $truncate .= '</' . $tag . '>'; } } return $truncate; }
message_send($eventdata); message_paypal_error_to_admin("Payment pending", $data); die; } // If our status is not completed or not pending on an echeck clearance then ignore and die // This check is redundant at present but may be useful if paypal extend the return codes in the future if (!($data->payment_status == "Completed" or $data->payment_status == "Pending" and $data->pending_reason == "echeck")) { die; } // At this point we only proceed with a status of completed or pending with a reason of echeck if ($existing = $DB->get_record("enrol_paypal", array("txn_id" => $data->txn_id))) { // Make sure this transaction doesn't exist already message_paypal_error_to_admin("Transaction {$data->txn_id} is being repeated!", $data); die; } if (core_text::strtolower($data->business) !== core_text::strtolower($plugin->get_config('paypalbusiness'))) { // Check that the email is the one we want it to be message_paypal_error_to_admin("Business email is {$data->business} (not " . $plugin->get_config('paypalbusiness') . ")", $data); die; } if (!($user = $DB->get_record('user', array('id' => $data->userid)))) { // Check that user exists message_paypal_error_to_admin("User {$data->userid} doesn't exist", $data); die; } if (!($course = $DB->get_record('course', array('id' => $data->courseid)))) { // Check that course exists message_paypal_error_to_admin("Course {$data->courseid} doesn't exist", $data); die; } $coursecontext = context_course::instance($course->id, IGNORE_MISSING);
/** * Processes and stores configuration data for this authentication plugin. */ function process_config($config) { // Set to defaults if undefined if (!isset($config->host_url)) { $config->host_url = ''; } if (!isset($config->start_tls)) { $config->start_tls = false; } if (empty($config->ldapencoding)) { $config->ldapencoding = 'utf-8'; } if (!isset($config->pagesize)) { $config->pagesize = LDAP_DEFAULT_PAGESIZE; } if (!isset($config->contexts)) { $config->contexts = ''; } if (!isset($config->user_type)) { $config->user_type = 'default'; } if (!isset($config->user_attribute)) { $config->user_attribute = ''; } if (!isset($config->search_sub)) { $config->search_sub = ''; } if (!isset($config->opt_deref)) { $config->opt_deref = LDAP_DEREF_NEVER; } if (!isset($config->preventpassindb)) { $config->preventpassindb = 0; } if (!isset($config->bind_dn)) { $config->bind_dn = ''; } if (!isset($config->bind_pw)) { $config->bind_pw = ''; } if (!isset($config->ldap_version)) { $config->ldap_version = '3'; } if (!isset($config->objectclass)) { $config->objectclass = ''; } if (!isset($config->memberattribute)) { $config->memberattribute = ''; } if (!isset($config->memberattribute_isdn)) { $config->memberattribute_isdn = ''; } if (!isset($config->creators)) { $config->creators = ''; } if (!isset($config->create_context)) { $config->create_context = ''; } if (!isset($config->expiration)) { $config->expiration = ''; } if (!isset($config->expiration_warning)) { $config->expiration_warning = '10'; } if (!isset($config->expireattr)) { $config->expireattr = ''; } if (!isset($config->gracelogins)) { $config->gracelogins = ''; } if (!isset($config->graceattr)) { $config->graceattr = ''; } if (!isset($config->auth_user_create)) { $config->auth_user_create = ''; } if (!isset($config->forcechangepassword)) { $config->forcechangepassword = 0; } if (!isset($config->stdchangepassword)) { $config->stdchangepassword = 0; } if (!isset($config->passtype)) { $config->passtype = 'plaintext'; } if (!isset($config->changepasswordurl)) { $config->changepasswordurl = ''; } if (!isset($config->removeuser)) { $config->removeuser = AUTH_REMOVEUSER_KEEP; } if (!isset($config->ntlmsso_enabled)) { $config->ntlmsso_enabled = 0; } if (!isset($config->ntlmsso_subnet)) { $config->ntlmsso_subnet = ''; } if (!isset($config->ntlmsso_ie_fastpath)) { $config->ntlmsso_ie_fastpath = 0; } if (!isset($config->ntlmsso_type)) { $config->ntlmsso_type = 'ntlm'; } if (!isset($config->ntlmsso_remoteuserformat)) { $config->ntlmsso_remoteuserformat = ''; } // Try to remove duplicates before storing the contexts (to avoid problems in sync_users()). $config->contexts = explode(';', $config->contexts); $config->contexts = array_map(create_function('$x', 'return core_text::strtolower(trim($x));'), $config->contexts); $config->contexts = implode(';', array_unique($config->contexts)); // Save settings set_config('host_url', trim($config->host_url), $this->pluginconfig); set_config('start_tls', $config->start_tls, $this->pluginconfig); set_config('ldapencoding', trim($config->ldapencoding), $this->pluginconfig); set_config('pagesize', (int) trim($config->pagesize), $this->pluginconfig); set_config('contexts', $config->contexts, $this->pluginconfig); set_config('user_type', core_text::strtolower(trim($config->user_type)), $this->pluginconfig); set_config('user_attribute', core_text::strtolower(trim($config->user_attribute)), $this->pluginconfig); set_config('search_sub', $config->search_sub, $this->pluginconfig); set_config('opt_deref', $config->opt_deref, $this->pluginconfig); set_config('preventpassindb', $config->preventpassindb, $this->pluginconfig); set_config('bind_dn', trim($config->bind_dn), $this->pluginconfig); set_config('bind_pw', $config->bind_pw, $this->pluginconfig); set_config('ldap_version', $config->ldap_version, $this->pluginconfig); set_config('objectclass', trim($config->objectclass), $this->pluginconfig); set_config('memberattribute', core_text::strtolower(trim($config->memberattribute)), $this->pluginconfig); set_config('memberattribute_isdn', $config->memberattribute_isdn, $this->pluginconfig); set_config('creators', trim($config->creators), $this->pluginconfig); set_config('create_context', trim($config->create_context), $this->pluginconfig); set_config('expiration', $config->expiration, $this->pluginconfig); set_config('expiration_warning', trim($config->expiration_warning), $this->pluginconfig); set_config('expireattr', core_text::strtolower(trim($config->expireattr)), $this->pluginconfig); set_config('gracelogins', $config->gracelogins, $this->pluginconfig); set_config('graceattr', core_text::strtolower(trim($config->graceattr)), $this->pluginconfig); set_config('auth_user_create', $config->auth_user_create, $this->pluginconfig); set_config('forcechangepassword', $config->forcechangepassword, $this->pluginconfig); set_config('stdchangepassword', $config->stdchangepassword, $this->pluginconfig); set_config('passtype', $config->passtype, $this->pluginconfig); set_config('changepasswordurl', trim($config->changepasswordurl), $this->pluginconfig); set_config('removeuser', $config->removeuser, $this->pluginconfig); set_config('ntlmsso_enabled', (int) $config->ntlmsso_enabled, $this->pluginconfig); set_config('ntlmsso_subnet', trim($config->ntlmsso_subnet), $this->pluginconfig); set_config('ntlmsso_ie_fastpath', (int) $config->ntlmsso_ie_fastpath, $this->pluginconfig); set_config('ntlmsso_type', $config->ntlmsso_type, 'auth/ldap'); set_config('ntlmsso_remoteuserformat', trim($config->ntlmsso_remoteuserformat), 'auth/ldap'); return true; }