function definition() { global $CFG, $DB; $mform = $this->_form; $course = $this->_customdata; $coursecontext = context_course::instance($course->id); $enrol = enrol_get_plugin('cohort'); $cohorts = array('' => get_string('choosedots')); list($sqlparents, $params) = $DB->get_in_or_equal(get_parent_contexts($coursecontext)); $sql = "SELECT id, name, contextid\n FROM {cohort}\n WHERE contextid {$sqlparents}\n ORDER BY name ASC"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $c) { $context = get_context_instance_by_id($c->contextid); if (!has_capability('moodle/cohort:view', $context)) { continue; } $cohorts[$c->id] = format_string($c->name); } $rs->close(); $roles = get_assignable_roles($coursecontext); $roles[0] = get_string('none'); $roles = array_reverse($roles, true); // descending default sortorder $mform->addElement('header', 'general', get_string('pluginname', 'enrol_cohort')); $mform->addElement('select', 'cohortid', get_string('cohort', 'cohort'), $cohorts); $mform->addRule('cohortid', get_string('required'), 'required', null, 'client'); $mform->addElement('select', 'roleid', get_string('role'), $roles); $mform->addRule('roleid', get_string('required'), 'required', null, 'client'); $mform->setDefault('roleid', $enrol->get_config('roleid')); $mform->addElement('hidden', 'id', null); $mform->setType('id', PARAM_INT); $this->add_action_buttons(true, get_string('addinstance', 'enrol')); $this->set_data(array('id' => $course->id)); }
/** * Tests the attachment UI. */ public function testAttachmentUI() { $this->drupalGet('admin/structure/views/view/test_attachment_ui/edit/attachment_1'); $this->assertText(t('Not defined'), 'The right text appears if there is no attachment selection yet.'); $attachment_display_url = 'admin/structure/views/nojs/display/test_attachment_ui/attachment_1/displays'; $this->drupalGet($attachment_display_url); // Display labels should be escaped. $this->assertEscaped('<em>Page</em>'); foreach (array('default', 'page-1') as $display_id) { $this->assertNoFieldChecked("edit-displays-{$display_id}", format_string('Make sure the @display_id can be marked as attached', array('@display_id' => $display_id))); } // Save the attachments and test the value on the view. $this->drupalPostForm($attachment_display_url, array('displays[page_1]' => 1), t('Apply')); // Options summary should be escaped. $this->assertEscaped('<em>Page</em>'); $this->assertNoRaw('<em>Page</em>'); $result = $this->xpath('//a[@id = :id]', array(':id' => 'views-attachment-1-displays')); $this->assertEqual($result[0]->attributes()->title, t('Page')); $this->drupalPostForm(NULL, array(), t('Save')); $view = Views::getView('test_attachment_ui'); $view->initDisplay(); $this->assertEqual(array_keys(array_filter($view->displayHandlers->get('attachment_1')->getOption('displays'))), array('page_1'), 'The attached displays got saved as expected'); $this->drupalPostForm($attachment_display_url, array('displays[default]' => 1, 'displays[page_1]' => 1), t('Apply')); $result = $this->xpath('//a[@id = :id]', array(':id' => 'views-attachment-1-displays')); $this->assertEqual($result[0]->attributes()->title, t('Multiple displays')); $this->drupalPostForm(NULL, array(), t('Save')); $view = Views::getView('test_attachment_ui'); $view->initDisplay(); $this->assertEqual(array_keys($view->displayHandlers->get('attachment_1')->getOption('displays')), array('default', 'page_1'), 'The attached displays got saved as expected'); }
function definition() { global $DB, $USER; $mform =& $this->_form; if ($pending = $DB->get_records('course_request', array('requester' => $USER->id))) { $mform->addElement('header', 'pendinglist', get_string('coursespending')); $list = array(); foreach ($pending as $cp) { $list[] = format_string($cp->fullname); } $list = implode(', ', $list); $mform->addElement('static', 'pendingcourses', get_string('courses'), $list); } $mform->addElement('header', 'coursedetails', get_string('courserequestdetails')); $mform->addElement('text', 'fullname', get_string('fullname'), 'maxlength="254" size="50"'); $mform->setHelpButton('fullname', array('coursefullname', get_string('fullname')), true); $mform->addRule('fullname', get_string('missingfullname'), 'required', null, 'client'); $mform->setType('fullname', PARAM_MULTILANG); $mform->addElement('text', 'shortname', get_string('shortname'), 'maxlength="100" size="20"'); $mform->setHelpButton('shortname', array('courseshortname', get_string('shortname')), true); $mform->addRule('shortname', get_string('missingshortname'), 'required', null, 'client'); $mform->setType('shortname', PARAM_MULTILANG); $mform->addElement('htmleditor', 'summary', get_string('summary'), array('rows' => '15', 'cols' => '50')); $mform->setHelpButton('summary', array('text2', get_string('helptext')), true); $mform->setType('summary', PARAM_RAW); $mform->addElement('passwordunmask', 'password', get_string('enrolmentkey'), 'size="25"'); $mform->setHelpButton('password', array('enrolmentkey', get_string('enrolmentkey')), true); $mform->setDefault('password', ''); $mform->setType('password', PARAM_RAW); $mform->addElement('header', 'requestreason', get_string('courserequestreason')); $mform->addElement('textarea', 'reason', get_string('courserequestsupport'), array('rows' => '15', 'cols' => '50')); $mform->addRule('reason', get_string('missingreqreason'), 'required', null, 'client'); $mform->setType('reason', PARAM_TEXT); $this->add_action_buttons(true, get_string('requestcourse')); }
public function print_header($title, $morebreadcrumbs = null, $navigation = '') { global $USER, $CFG; $this->init_full(); $replacements = array('%fullname%' => format_string($this->activityrecord->name)); foreach ($replacements as $search => $replace) { $title = str_replace($search, $replace, $title); } if ($this->courserecord->id == SITEID) { $breadcrumbs = array(); } else { $breadcrumbs = array($this->courserecord->shortname => $CFG->wwwroot . '/course/view.php?id=' . $this->courserecord->id); } $breadcrumbs[get_string('modulenameplural', 'game')] = $CFG->wwwroot . '/mod/game/index.php?id=' . $this->courserecord->id; $breadcrumbs[format_string($this->activityrecord->name)] = $CFG->wwwroot . '/mod/game/view.php?id=' . $this->modulerecord->id; if (!empty($morebreadcrumbs)) { $breadcrumbs = array_merge($breadcrumbs, $morebreadcrumbs); } if (empty($morebreadcrumbs) && $this->user_allowed_editing()) { $buttons = '<table><tr><td>' . update_module_button($this->modulerecord->id, $this->courserecord->id, get_string('modulename', 'game')) . '</td>'; if (!empty($CFG->showblocksonmodpages)) { $buttons .= '<td><form ' . $CFG->frametarget . ' method="get" action="view.php">' . '<div>' . '<input type="hidden" name="id" value="' . $this->modulerecord->id . '" />' . '<input type="hidden" name="edit" value="' . ($this->user_is_editing() ? 'off' : 'on') . '" />' . '<input type="submit" value="' . get_string($this->user_is_editing() ? 'blockseditoff' : 'blocksediton') . '" />' . '</div></form></td>'; } $buttons .= '</tr></table>'; } else { $buttons = ' '; } print_header($title, $this->courserecord->fullname, $navigation); }
/** * Parent theme: Bootstrapbase by Bas Brands * Built on: Essential by Julian Ridden * * @package theme_lambda * @copyright 2014 redPIthemes * */ function theme_lambda_get_setting($setting, $format = false) { global $CFG; require_once $CFG->dirroot . '/lib/weblib.php'; static $theme; if (empty($theme)) { $theme = theme_config::load('lambda'); } if (empty($theme->settings->{$setting})) { return false; } else { if (!$format) { return $theme->settings->{$setting}; } else { if ($format === 'format_text') { return format_text($theme->settings->{$setting}, FORMAT_PLAIN); } else { if ($format === 'format_html') { return format_text($theme->settings->{$setting}, FORMAT_HTML, array('trusted' => true, 'noclean' => true)); } else { return format_string($theme->settings->{$setting}); } } } } }
/** * Tests that files in different directories take precedence as expected. */ function testDirectoryPrecedence() { // Define the module files we will search for, and the directory precedence // we expect. $expected_directories = array('drupal_system_listing_compatible_test' => array('core/profiles/testing/modules', 'core/modules/system/tests/modules')); // This test relies on two versions of the same module existing in // different places in the filesystem. Without that, the test has no // meaning, so assert their presence first. foreach ($expected_directories as $module => $directories) { foreach ($directories as $directory) { $filename = "{$directory}/{$module}/{$module}.info.yml"; $this->assertTrue(file_exists(\Drupal::root() . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename))); } } // Now scan the directories and check that the files take precedence as // expected. $listing = new ExtensionDiscovery(\Drupal::root()); $listing->setProfileDirectories(array('core/profiles/testing')); $files = $listing->scan('module'); foreach ($expected_directories as $module => $directories) { $expected_directory = array_shift($directories); $expected_uri = "{$expected_directory}/{$module}/{$module}.info.yml"; $this->assertEqual($files[$module]->getPathname(), $expected_uri, format_string('Module @actual was found at @expected.', array('@actual' => $files[$module]->getPathname(), '@expected' => $expected_uri))); } }
function print_filter(&$mform) { global $remoteDB; $reportclassname = 'report_' . $this->report->type; $reportclass = new $reportclassname($this->report); if ($this->report->type != 'sql') { $components = cr_unserialize($this->report->components); $conditions = $components['conditions']; $userslist = $reportclass->elements_by_conditions($conditions); } else { $userslist = array_keys($remoteDB->get_records('user')); } $usersoptions = array(); $usersoptions[0] = get_string('filter_all', 'block_cobalt_reports'); if (!empty($userslist)) { list($usql, $params) = $remoteDB->get_in_or_equal($userslist); $users = $remoteDB->get_records_select('user', "id $usql", $params); foreach ($users as $c) { $usersoptions[$c->id] = format_string($c->lastname . ' ' . $c->firstname); } } $mform->addElement('select', 'filter_users', get_string('users'), $usersoptions); $mform->setType('filter_users', PARAM_INT); }
/** * Assert that the extension handler returns the expected values. * * @param array $expected_values * The expected values, sorted by weight and module name. * @param $condition */ protected function assertModuleList(array $expected_values, $condition) { $expected_values = array_values(array_unique($expected_values)); $enabled_modules = array_keys($this->container->get('module_handler')->getModuleList()); $enabled_modules = sort($enabled_modules); $this->assertEqual($expected_values, $enabled_modules, format_string('@condition: extension handler returns correct results', array('@condition' => $condition))); }
/** * Tests the hooks. */ public function testHooks() { $view = Views::getView('test_view'); $view->setDisplay(); // Test each hook is found in the implementations array and is invoked. foreach (static::$hooks as $hook => $type) { $this->assertTrue($this->moduleHandler->implementsHook('views_test_data', $hook), format_string('The hook @hook was registered.', array('@hook' => $hook))); if ($hook == 'views_post_render') { $this->moduleHandler->invoke('views_test_data', $hook, array($view, &$view->display_handler->output, $view->display_handler->getPlugin('cache'))); continue; } switch ($type) { case 'view': $this->moduleHandler->invoke('views_test_data', $hook, array($view)); break; case 'alter': $data = array(); $this->moduleHandler->invoke('views_test_data', $hook, array($data)); break; default: $this->moduleHandler->invoke('views_test_data', $hook); } $this->assertTrue($this->container->get('state')->get('views_hook_test_' . $hook), format_string('The %hook hook was invoked.', array('%hook' => $hook))); // Reset the module implementations cache, so we ensure that the // .views.inc file is loaded actively. $this->moduleHandler->resetImplementations(); } }
function get_costcenter_parent($costcenters, $selected = array(), $inctop = true, $all = false) { $out = array(); //if an integer has been sent, convert to an array if (!is_array($selected)) { $selected = ($selected) ? array(intval($selected)) : array(); } if ($inctop) { $out[null] = '---Select---'; } if ($all) { $out[0] = get_string('all'); } if (is_array($costcenters)) { foreach ($costcenters as $parent) { // An item cannot be its own parent and cannot be moved inside itself or one of its own children // what we have in $selected is an array of the ids of the parent nodes of selected branches // so we must exclude these parents and all their children //add using same spacing style as the bulkitems->move available & selected multiselects foreach ($selected as $key => $selectedid) { if (preg_match("@/$selectedid(/|$)@", $parent->path)) { continue 2; } } if ($parent->id != null) { $out[$parent->id] = format_string($parent->fullname); } } } return $out; }
/** * Creates four nodes and ensures that they are loaded correctly. */ function testNodeMultipleLoad() { $node1 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); $node2 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1)); $node3 = $this->drupalCreateNode(array('type' => 'article', 'promote' => 0)); $node4 = $this->drupalCreateNode(array('type' => 'page', 'promote' => 0)); // Confirm that promoted nodes appear in the default node listing. $this->drupalGet('node'); $this->assertText($node1->label(), 'Node title appears on the default listing.'); $this->assertText($node2->label(), 'Node title appears on the default listing.'); $this->assertNoText($node3->label(), 'Node title does not appear in the default listing.'); $this->assertNoText($node4->label(), 'Node title does not appear in the default listing.'); // Load nodes with only a condition. Nodes 3 and 4 will be loaded. $nodes = entity_load_multiple_by_properties('node', array('promote' => 0)); $this->assertEqual($node3->label(), $nodes[$node3->id()]->label(), 'Node was loaded.'); $this->assertEqual($node4->label(), $nodes[$node4->id()]->label(), 'Node was loaded.'); $count = count($nodes); $this->assertTrue($count == 2, format_string('@count nodes loaded.', array('@count' => $count))); // Load nodes by nid. Nodes 1, 2 and 4 will be loaded. $nodes = Node::loadMultiple(array(1, 2, 4)); $count = count($nodes); $this->assertTrue(count($nodes) == 3, format_string('@count nodes loaded', array('@count' => $count))); $this->assertTrue(isset($nodes[$node1->id()]), 'Node is correctly keyed in the array'); $this->assertTrue(isset($nodes[$node2->id()]), 'Node is correctly keyed in the array'); $this->assertTrue(isset($nodes[$node4->id()]), 'Node is correctly keyed in the array'); foreach ($nodes as $node) { $this->assertTrue(is_object($node), 'Node is an object'); } }
/** * Tests that the default 'comment_body' field is correctly added. */ function testCommentDefaultFields() { // Do not make assumptions on default node types created by the test // installation profile, and create our own. $this->drupalCreateContentType(array('type' => 'test_node_type')); $this->container->get('comment.manager')->addDefaultField('node', 'test_node_type'); // Check that the 'comment_body' field is present on the comment bundle. $field = FieldConfig::loadByName('comment', 'comment', 'comment_body'); $this->assertTrue(!empty($field), 'The comment_body field is added when a comment bundle is created'); $field->delete(); // Check that the 'comment_body' field is deleted. $field_storage = FieldStorageConfig::loadByName('comment', 'comment_body'); $this->assertTrue(empty($field_storage), 'The comment_body field was deleted'); // Create a new content type. $type_name = 'test_node_type_2'; $this->drupalCreateContentType(array('type' => $type_name)); $this->container->get('comment.manager')->addDefaultField('node', $type_name); // Check that the 'comment_body' field exists and has an instance on the // new comment bundle. $field_storage = FieldStorageConfig::loadByName('comment', 'comment_body'); $this->assertTrue($field_storage, 'The comment_body field exists'); $field = FieldConfig::loadByName('comment', 'comment', 'comment_body'); $this->assertTrue(isset($field), format_string('The comment_body field is present for comments on type @type', array('@type' => $type_name))); // Test adding a field that defaults to CommentItemInterface::CLOSED. $this->container->get('comment.manager')->addDefaultField('node', 'test_node_type', 'who_likes_ponies', CommentItemInterface::CLOSED, 'who_likes_ponies'); $field = entity_load('field_config', 'node.test_node_type.who_likes_ponies'); $this->assertEqual($field->default_value[0]['status'], CommentItemInterface::CLOSED); }
public function test_format_string() { global $CFG; // Ampersands. $this->assertSame("& &&&&& &&", format_string("& &&&&& &&")); $this->assertSame("ANother & &&&&& Category", format_string("ANother & &&&&& Category")); $this->assertSame("ANother & &&&&& Category", format_string("ANother & &&&&& Category", true)); $this->assertSame("Nick's Test Site & Other things", format_string("Nick's Test Site & Other things", true)); // String entities. $this->assertSame(""", format_string(""")); // Digital entities. $this->assertSame("&11234;", format_string("&11234;")); // Unicode entities. $this->assertSame("ᅻ", format_string("ᅻ")); // < and > signs. $originalformatstringstriptags = $CFG->formatstringstriptags; $CFG->formatstringstriptags = false; $this->assertSame('x < 1', format_string('x < 1')); $this->assertSame('x > 1', format_string('x > 1')); $this->assertSame('x < 1 and x > 0', format_string('x < 1 and x > 0')); $CFG->formatstringstriptags = true; $this->assertSame('x < 1', format_string('x < 1')); $this->assertSame('x > 1', format_string('x > 1')); $this->assertSame('x < 1 and x > 0', format_string('x < 1 and x > 0')); $CFG->formatstringstriptags = $originalformatstringstriptags; }
/** * Generates the public properties configuration array from the mappings. * * @param string $view_mode * The view mode. * @param array $field_map * Associative array that maps field names to public properties. * * @throws \RestfulServerConfigurationException * * @return array * The public properties info array. */ public function mapFields($view_mode, $field_map) { $displayed_fields = $this->displayedFieldsList($view_mode); // Set the mappings from the field name to the output key. $public_fields = array(); foreach ($displayed_fields as $field_name) { if (empty($field_map[$field_name])) { throw new \RestfulServerConfigurationException(format_string('No mapping was found for @field_name.', array( '@field_name' => $field_name, ))); } // Add it to the public fields array with a special callback function. $public_fields[$field_map[$field_name]] = array( 'callback' => array( array($this, 'renderField'), array($field_name, $view_mode), ), ); } if (empty($public_fields)) { throw new \RestfulServerConfigurationException('No fields shown rendering entity view mode.'); } return $public_fields; }
/** * Tests the normal formatter display on node display. */ function testUploadPath() { $field_name = strtolower($this->randomMachineName()); $type_name = 'article'; $this->createFileField($field_name, 'node', $type_name); $test_file = $this->getTestFile('text'); // Create a new node. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded to the file root. $node = node_load($nid, TRUE); $node_file = file_load($node->{$field_name}->target_id); $this->assertPathMatch('public://' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri()))); // Change the path to contain multiple subdirectories. $this->updateFileField($field_name, $type_name, array('file_directory' => 'foo/bar/baz')); // Upload a new file into the subdirectories. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded into the subdirectory. $node = node_load($nid, TRUE); $node_file = file_load($node->{$field_name}->target_id, TRUE); $this->assertPathMatch('public://foo/bar/baz/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path.', array('%file' => $node_file->getFileUri()))); // Check the path when used with tokens. // Change the path to contain multiple token directories. $this->updateFileField($field_name, $type_name, array('file_directory' => '[current-user:uid]/[current-user:name]')); // Upload a new file into the token subdirectories. $nid = $this->uploadNodeFile($test_file, $field_name, $type_name); // Check that the file was uploaded into the subdirectory. $node = node_load($nid, TRUE); $node_file = file_load($node->{$field_name}->target_id); // Do token replacement using the same user which uploaded the file, not // the user running the test case. $data = array('user' => $this->admin_user); $subdirectory = \Drupal::token()->replace('[user:uid]/[user:name]', $data); $this->assertPathMatch('public://' . $subdirectory . '/' . $test_file->getFilename(), $node_file->getFileUri(), format_string('The file %file was uploaded to the correct path with token replacements.', array('%file' => $node_file->getFileUri()))); }
/** * Assert that a trail exists in the internal browser. * * @param array $trail * An associative array whose keys are expected breadcrumb link paths and * whose values are expected breadcrumb link texts (not sanitized). */ protected function assertBreadcrumbParts($trail) { // Compare paths with actual breadcrumb. $parts = $this->getBreadcrumbParts(); $pass = TRUE; // There may be more than one breadcrumb on the page. If $trail is empty // this test would go into an infinite loop, so we need to check that too. while ($trail && !empty($parts)) { foreach ($trail as $path => $title) { // If the path is empty, generate the path from the <front> route. If // the path does not start with a leading slash, then run it through // Url::fromUri('base:')->toString() to get the correct base // prepended. if ($path == '') { $url = Url::fromRoute('<front>')->toString(); } elseif ($path[0] != '/') { $url = Url::fromUri('base:' . $path)->toString(); } else { $url = $path; } $part = array_shift($parts); $pass = $pass && $part['href'] === $url && $part['text'] === SafeMarkup::checkPlain($title); } } // No parts must be left, or an expected "Home" will always pass. $pass = $pass && empty($parts); $this->assertTrue($pass, format_string('Breadcrumb %parts found on @path.', array('%parts' => implode(' » ', $trail), '@path' => $this->getUrl()))); }
/** * Constructor. * * @param stdClass $cohort */ public function __construct($cohort) { $cohortcontext = \context::instance_by_id($cohort->contextid); $editable = has_capability('moodle/cohort:manage', $cohortcontext); $displayvalue = format_string($cohort->name, true, array('context' => $cohortcontext)); parent::__construct('core_cohort', 'cohortname', $cohort->id, $editable, $displayvalue, $cohort->name, new lang_string('editcohortname', 'cohort'), new lang_string('newnamefor', 'cohort', $displayvalue)); }
function edit_field_add($mform) { /// Create the form field $mform->addElement('editor', $this->inputname, format_string($this->field->name), null, null); $mform->setType($this->inputname, PARAM_RAW); // we MUST clean this before display! }
function testSimple() { $view = Views::getView('test_view'); $view->setDisplay(); $view->displayHandlers->get('default')->overrideOption('fields', array('counter' => array('id' => 'counter', 'table' => 'views', 'field' => 'counter', 'relationship' => 'none'), 'name' => array('id' => 'name', 'table' => 'views_test_data', 'field' => 'name', 'relationship' => 'none'))); $view->preview(); $counter = $view->style_plugin->getField(0, 'counter'); $this->assertEqual($counter, '1', format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => 1, '@counter' => $counter))); $counter = $view->style_plugin->getField(1, 'counter'); $this->assertEqual($counter, '2', format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => 2, '@counter' => $counter))); $counter = $view->style_plugin->getField(2, 'counter'); $this->assertEqual($counter, '3', format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => 3, '@counter' => $counter))); $view->destroy(); $view->storage->invalidateCaches(); $view->setDisplay(); $rand_start = rand(5, 10); $view->displayHandlers->get('default')->overrideOption('fields', array('counter' => array('id' => 'counter', 'table' => 'views', 'field' => 'counter', 'relationship' => 'none', 'counter_start' => $rand_start), 'name' => array('id' => 'name', 'table' => 'views_test_data', 'field' => 'name', 'relationship' => 'none'))); $view->preview(); $counter = $view->style_plugin->getField(0, 'counter'); $expected_number = 0 + $rand_start; $this->assertEqual($counter, (string) $expected_number, format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => $expected_number, '@counter' => $counter))); $counter = $view->style_plugin->getField(1, 'counter'); $expected_number = 1 + $rand_start; $this->assertEqual($counter, (string) $expected_number, format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => $expected_number, '@counter' => $counter))); $counter = $view->style_plugin->getField(2, 'counter'); $expected_number = 2 + $rand_start; $this->assertEqual($counter, (string) $expected_number, format_string('Make sure the expected number (@expected) patches with the rendered number (@counter)', array('@expected' => $expected_number, '@counter' => $counter))); }
/** * Creates a node, then tests the statistics tokens generated from it. */ function testStatisticsTokenReplacement() { $language_interface = \Drupal::languageManager()->getCurrentLanguage(); // Create user and node. $user = $this->drupalCreateUser(array('create page content')); $this->drupalLogin($user); $node = $this->drupalCreateNode(array('type' => 'page', 'uid' => $user->id())); // Hit the node. $this->drupalGet('node/' . $node->id()); // Manually calling statistics.php, simulating ajax behavior. $nid = $node->id(); $post = http_build_query(array('nid' => $nid)); $headers = array('Content-Type' => 'application/x-www-form-urlencoded'); global $base_url; $stats_path = $base_url . '/' . drupal_get_path('module', 'statistics') . '/statistics.php'; $client = \Drupal::service('http_client_factory')->fromOptions(['config/curl' => [CURLOPT_TIMEOUT => 10]]); $client->post($stats_path, array('headers' => $headers, 'body' => $post)); $statistics = statistics_get($node->id()); // Generate and test tokens. $tests = array(); $tests['[node:total-count]'] = 1; $tests['[node:day-count]'] = 1; $tests['[node:last-view]'] = format_date($statistics['timestamp']); $tests['[node:last-view:short]'] = format_date($statistics['timestamp'], 'short'); // Test to make sure that we generated something for each token. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.'); foreach ($tests as $input => $expected) { $output = \Drupal::token()->replace($input, array('node' => $node), array('langcode' => $language_interface->getId())); $this->assertEqual($output, $expected, format_string('Statistics token %token replaced.', array('%token' => $input))); } }
/** * Tests the term validation constraints. */ public function testValidation() { $this->entityManager->getStorage('taxonomy_vocabulary')->create(array('vid' => 'tags', 'name' => 'Tags'))->save(); $term = $this->entityManager->getStorage('taxonomy_term')->create(array('name' => 'test', 'vid' => 'tags')); $violations = $term->validate(); $this->assertEqual(count($violations), 0, 'No violations when validating a default term.'); $term->set('name', $this->randomString(256)); $violations = $term->validate(); $this->assertEqual(count($violations), 1, 'Violation found when name is too long.'); $this->assertEqual($violations[0]->getPropertyPath(), 'name.0.value'); $field_label = $term->get('name')->getFieldDefinition()->getLabel(); $this->assertEqual($violations[0]->getMessage(), t('%name: may not be longer than @max characters.', array('%name' => $field_label, '@max' => 255))); $term->set('name', NULL); $violations = $term->validate(); $this->assertEqual(count($violations), 1, 'Violation found when name is NULL.'); $this->assertEqual($violations[0]->getPropertyPath(), 'name'); $this->assertEqual($violations[0]->getMessage(), t('This value should not be null.')); $term->set('name', 'test'); $term->set('parent', 9999); $violations = $term->validate(); $this->assertEqual(count($violations), 1, 'Violation found when term parent is invalid.'); $this->assertEqual($violations[0]->getMessage(), format_string('The referenced entity (%type: %id) does not exist.', array('%type' => 'taxonomy_term', '%id' => 9999))); $term->set('parent', 0); $violations = $term->validate(); $this->assertEqual(count($violations), 0, 'No violations for parent id 0.'); }
function definition() { $mform =& $this->_form; $contextid = $this->_customdata['contextid']; $export = $mform->addElement('hidden', 'export', ''); // Will be overwritten below $table = new html_table(); /* Styling done using HTML table and CSS */ $table->attributes['class'] = 'export_form_table'; $table->align = array('left', 'left', 'left', 'center'); $table->wrap = array('nowrap', '', 'nowrap', 'nowrap'); $table->data = array(); $table->head = array(get_string('name'), get_string('description'), get_string('shortname'), get_string('export', 'report_rolesmigration')); $roles = get_all_roles(); foreach ($roles as $role) { $row = array(); $roleurl = new moodle_url('/admin/roles/define.php', array('roleid' => $role->id, 'action' => 'view')); $row[0] = '<a href="'.$roleurl.'">'.format_string($role->name).'</a>'; $row[1] = format_text($role->description, FORMAT_HTML); $row[2] = ($role->shortname); /* Export values are added from role checkboxes */ $row[3] = '<input type="checkbox" name="export[]" value="'.$role->shortname.'" />'; $table->data[] = $row; } $mform->addElement('html', html_writer::table($table)); $mform->addElement('hidden', 'contextid', $contextid); $this->add_action_buttons(false, get_string('submitexport', 'report_rolesmigration')); }
function label_restore_mods($mod, $restore) { global $CFG; $status = true; //Get record from backup_ids $data = backup_getid($restore->backup_unique_code, $mod->modtype, $mod->id); if ($data) { //Now get completed xmlized object $info = $data->info; //traverse_xmlize($info); //Debug //print_object ($GLOBALS['traverse_array']); //Debug //$GLOBALS['traverse_array']=""; //Debug //Now, build the LABEL record structure $label->course = $restore->course_id; $label->name = backup_todb($info['MOD']['#']['NAME']['0']['#']); $label->content = backup_todb($info['MOD']['#']['CONTENT']['0']['#']); $label->timemodified = $info['MOD']['#']['TIMEMODIFIED']['0']['#']; //The structure is equal to the db, so insert the label $newid = insert_record("label", $label); //Do some output if (!defined('RESTORE_SILENTLY')) { echo "<li>" . get_string("modulename", "label") . " \"" . format_string(stripslashes($label->name), true) . "\"</li>"; } backup_flush(300); if ($newid) { //We have the newid, update backup_ids backup_putid($restore->backup_unique_code, $mod->modtype, $mod->id, $newid); } else { $status = false; } } else { $status = false; } return $status; }
/** * Tests the settings form to ensure the correct default values are used. */ public function testSettingsPage() { $this->drupalGet('admin/config'); $this->clickLink('Aggregator'); $this->clickLink('Settings'); // Make sure that test plugins are present. $this->assertText('Test fetcher'); $this->assertText('Test parser'); $this->assertText('Test processor'); // Set new values and enable test plugins. $edit = array('aggregator_allowed_html_tags' => '<a>', 'aggregator_summary_items' => 10, 'aggregator_clear' => 3600, 'aggregator_teaser_length' => 200, 'aggregator_fetcher' => 'aggregator_test_fetcher', 'aggregator_parser' => 'aggregator_test_parser', 'aggregator_processors[aggregator_test_processor]' => 'aggregator_test_processor'); $this->drupalPostForm('admin/config/services/aggregator/settings', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); foreach ($edit as $name => $value) { $this->assertFieldByName($name, $value, format_string('"@name" has correct default value.', array('@name' => $name))); } // Check for our test processor settings form. $this->assertText(t('Dummy length setting')); // Change its value to ensure that settingsSubmit is called. $edit = array('dummy_length' => 100); $this->drupalPostForm('admin/config/services/aggregator/settings', $edit, t('Save configuration')); $this->assertText(t('The configuration options have been saved.')); $this->assertFieldByName('dummy_length', 100, '"dummy_length" has correct default value.'); // Make sure settings form is still accessible even after uninstalling a module // that provides the selected plugins. $this->container->get('module_installer')->uninstall(array('aggregator_test')); $this->resetAll(); $this->drupalGet('admin/config/services/aggregator/settings'); $this->assertResponse(200); }
/** * Gets the name for the provided section. * * @param stdClass $course * @param stdClass $section * @return string */ function callback_weeks_get_section_name($course, $section) { // We can't add a node without text if (!empty($section->name)) { // Return the name the user set return format_string($section->name, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))); } else { if ($section->section == 0) { // Return the section0name return get_string('section0name', 'format_weeks'); } else { // Got to work out the date of the week so that we can show it $sections = get_all_sections($course->id); $weekdate = $course->startdate + 7200; foreach ($sections as $sec) { if ($sec->id == $section->id) { break; } else { if ($sec->section != 0) { $weekdate += 604800; } } } $strftimedateshort = ' ' . get_string('strftimedateshort'); $weekday = userdate($weekdate, $strftimedateshort); $endweekday = userdate($weekdate + 518400, $strftimedateshort); return $weekday . ' - ' . $endweekday; } } }
/** * Returns localised name of enrol instance * * @param object|null $instance enrol_mnet instance * @return string */ public function get_instance_name($instance) { global $DB; if (empty($instance)) { $enrol = $this->get_name(); return get_string('pluginname', 'enrol_' . $enrol); } else { if (empty($instance->name)) { $enrol = $this->get_name(); if ($role = $DB->get_record('role', array('id' => $instance->roleid))) { $role = role_get_name($role, get_context_instance(CONTEXT_COURSE, $instance->courseid)); } else { $role = get_string('error'); } if (empty($instance->customint1)) { $host = get_string('remotesubscribersall', 'enrol_mnet'); } else { $host = $DB->get_field('mnet_host', 'name', array('id' => $instance->customint1)); } return get_string('pluginname', 'enrol_' . $enrol) . ' (' . format_string($host) . ' - ' . $role . ')'; } else { return format_string($instance->name); } } }
/** * Returns localised name of enrol instance. * * @param stdClass $instance (null is accepted too) * @return string */ public function get_instance_name($instance) { global $DB; if (empty($instance)) { $enrol = $this->get_name(); return get_string('pluginname', 'enrol_' . $enrol); } else { if (empty($instance->name)) { $enrol = $this->get_name(); $cohort = $DB->get_record('cohort', array('id' => $instance->customint1)); if (!$cohort) { return get_string('pluginname', 'enrol_' . $enrol); } $cohortname = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid))); if ($role = $DB->get_record('role', array('id' => $instance->roleid))) { $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)); return get_string('pluginname', 'enrol_' . $enrol) . ' (' . $cohortname . ' - ' . $role . ')'; } else { return get_string('pluginname', 'enrol_' . $enrol) . ' (' . $cohortname . ')'; } } else { return format_string($instance->name, true, array('context' => context_course::instance($instance->courseid))); } } }
/** * Controls the block title based on instance configuration * * @return bool */ public function specialization() { $title = isset($this->config->ranking_title) ? trim($this->config->ranking_title) : ''; if (!empty($title)) { $this->title = format_string($this->config->ranking_title); } }
/** * Tests the views_ui_autocomplete_tag function. */ public function testViewsUiAutocompleteTag() { \Drupal::moduleHandler()->loadInclude('views_ui', 'inc', 'admin'); // Save 15 views with a tag. $tags = array(); for ($i = 0; $i < 16; $i++) { $suffix = $i % 2 ? 'odd' : 'even'; $tag = 'autocomplete_tag_test_' . $suffix . $this->randomMachineName(); $tags[] = $tag; entity_create('view', array('tag' => $tag, 'id' => $this->randomMachineName()))->save(); } // Make sure just ten results are returns. $controller = ViewsUIController::create($this->container); $request = $this->container->get('request_stack')->getCurrentRequest(); $request->query->set('q', 'autocomplete_tag_test'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 10, 'Make sure the maximum amount of tag results is 10.'); // Make sure that matching by a certain prefix works. $request->query->set('q', 'autocomplete_tag_test_even'); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 8, 'Make sure that only a subset is returned.'); foreach ($matches as $tag) { $this->assertTrue(array_search($tag, $tags) !== FALSE, format_string('Make sure the returned tag @tag actually exists.', array('@tag' => $tag))); } // Make sure an invalid result doesn't return anything. $request->query->set('q', $this->randomMachineName()); $result = $controller->autocompleteTag($request); $matches = (array) json_decode($result->getContent()); $this->assertEqual(count($matches), 0, "Make sure an invalid tag doesn't return anything."); }
/** * Create a vocabulary and some taxonomy terms, ensuring they're loaded * correctly using entity_load_multiple(). */ function testTaxonomyTermMultipleLoad() { // Create a vocabulary. $vocabulary = $this->createVocabulary(); // Create five terms in the vocabulary. $i = 0; while ($i < 5) { $i++; $this->createTerm($vocabulary); } // Load the terms from the vocabulary. $terms = entity_load_multiple_by_properties('taxonomy_term', array('vid' => $vocabulary->id())); $count = count($terms); $this->assertEqual($count, 5, format_string('Correct number of terms were loaded. @count terms.', array('@count' => $count))); // Load the same terms again by tid. $terms2 = Term::loadMultiple(array_keys($terms)); $this->assertEqual($count, count($terms2), 'Five terms were loaded by tid.'); $this->assertEqual($terms, $terms2, 'Both arrays contain the same terms.'); // Remove one term from the array, then delete it. $deleted = array_shift($terms2); $deleted->delete(); $deleted_term = Term::load($deleted->id()); $this->assertFalse($deleted_term); // Load terms from the vocabulary by vid. $terms3 = entity_load_multiple_by_properties('taxonomy_term', array('vid' => $vocabulary->id())); $this->assertEqual(count($terms3), 4, 'Correct number of terms were loaded.'); $this->assertFalse(isset($terms3[$deleted->id()])); // Create a single term and load it by name. $term = $this->createTerm($vocabulary); $loaded_terms = entity_load_multiple_by_properties('taxonomy_term', array('name' => $term->getName())); $this->assertEqual(count($loaded_terms), 1, 'One term was loaded.'); $loaded_term = reset($loaded_terms); $this->assertEqual($term->id(), $loaded_term->id(), 'Term loaded by name successfully.'); }