public function alterItems(array &$items) { // Prevent session information from being saved while indexing. drupal_save_session(FALSE); // Force the current user to anonymous to prevent access bypass in search // indexes. $original_user = $GLOBALS['user']; $GLOBALS['user'] = drupal_anonymous_user(); $entity_type = $this->index->getEntityType(); $entity_handler = panelizer_entity_plugin_get_handler($entity_type); foreach ($items as &$item) { $entity_id = entity_id($entity_type, $item); $item->search_api_panelizer_content = NULL; $item->search_api_panelizer_title = NULL; try { if ($render_info = $entity_handler->render_entity($item, 'page_manager')) { $item->search_api_panelizer_content = $render_info['content']; $item->search_api_panelizer_title = !empty($render_info['title']) ? $render_info['title'] : NULL; } } catch (Exception $e) { watchdog_exception('panelizer', $e, 'Error indexing Panelizer content for %entity_type with ID %entity_id', array('%entity_type' => $entity_type, '%entity_id' => $entity_id)); } } // Restore the user. $GLOBALS['user'] = $original_user; drupal_save_session(TRUE); }
public function testCurrentUser() { /** @var \Drupal\service_container\Session\Account $account */ $account_service = $this->container->get('current_user'); $this->assertTrue($account_service instanceof Account); $admin_user = $this->drupalCreateUser(array('access content')); $this->drupalLogin($admin_user); drupal_save_session(FALSE); $GLOBALS['user'] = $admin_user; $account = $this->container->get('current_user'); $this->assertEqual(spl_object_hash($account_service), spl_object_hash($account), 'Ensure that the object in the container stays the same.'); $this->assertEqual($admin_user->uid, $account->id()); $this->assertEqual(array_keys($admin_user->roles), $account->getRoles()); $this->assertEqual(1, count($account->getRoles(TRUE))); $this->assertEqual($admin_user->name, $account->getUsername()); }
/** * Log the user. */ protected function loginUser() { global $user; $account = $this->getAccount(); // Explicitly allow a session to be saved, as it was disabled in // \RestfulAuthenticationManager::getAccount. However this resource is a // special one, in the sense that we want to keep the user authenticated // after login. drupal_save_session(TRUE); // Override the global user. $user = user_load($account->uid); $login_array = array ('name' => $account->name); user_login_finalize($login_array); }
public function alterItems(array &$items) { // Prevent session information from being saved while indexing. drupal_save_session(FALSE); // Force the current user to anonymous to prevent access bypass in search // indexes. $original_user = $GLOBALS['user']; $GLOBALS['user'] = drupal_anonymous_user(); $entity_type = $this->index->getEntityType(); $entity_handler = panelizer_entity_plugin_get_handler($entity_type); foreach ($items as &$item) { $entity_id = entity_id($entity_type, $item); $item->search_api_panelizer_content = NULL; $item->search_api_panelizer_title = NULL; // If Search API specifies a language to view the item in, force the // global language_content to be Search API item language. Fieldable // panel panes will render in the correct language. if (isset($item->search_api_language)) { global $language_content; $original_language_content = $language_content; $languages = language_list(); if (isset($languages[$item->search_api_language])) { $language_content = $languages[$item->search_api_language]; } else { $language_content = language_default(); } } try { if ($render_info = $entity_handler->render_entity($item, 'page_manager')) { $item->search_api_panelizer_content = $render_info['content']; $item->search_api_panelizer_title = !empty($render_info['title']) ? $render_info['title'] : NULL; } } catch (Exception $e) { watchdog_exception('panelizer', $e, 'Error indexing Panelizer content for %entity_type with ID %entity_id', array('%entity_type' => $entity_type, '%entity_id' => $entity_id)); } // Restore the language_content global if it was overridden. if (isset($original_language_content)) { $language_content = $original_language_content; } } // Restore the user. $GLOBALS['user'] = $original_user; drupal_save_session(TRUE); }
function install($config) { global $installDirPath; // create database if does not exists $this->createDatabaseIfNotExists($config['mysql']['server'], $config['mysql']['username'], $config['mysql']['password'], $config['mysql']['database']); global $installDirPath; // Build database require_once $installDirPath . 'civicrm.php'; civicrm_main($config); if (!$this->errors) { global $installType, $installURLPath; $output = NULL; if ($installType == 'drupal' && version_compare(VERSION, '7.0-rc1') >= 0) { // clean output @ob_clean(); $output .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; $output .= '<head>'; $output .= '<title>CiviCRM Installed</title>'; $output .= '<link rel="stylesheet" type="text/css" href="template.css" />'; $output .= '</head>'; $output .= '<body>'; $output .= '<div style="padding: 1em;"><p class="good">CiviCRM has been successfully installed</p>'; $output .= '<ul>'; $docLinkConfig = CRM_Utils_System::docURL2('Configuring a New Site', FALSE, 'here', NULL, NULL, "wiki"); if (!function_exists('ts')) { $docLinkConfig = "<a href=\"{$docLinkConfig}\">here</a>"; } $drupalURL = civicrm_cms_base(); $drupalPermissionsURL = "{$drupalURL}index.php?q=admin/people/permissions"; $drupalURL .= "index.php?q=civicrm/admin/configtask&reset=1"; $registerSiteURL = "http://civicrm.org/civicrm/profile/create?reset=1&gid=15"; $output .= "<li>Drupal user permissions have been automatically set - giving anonymous and authenticated users access to public CiviCRM forms and features. We recommend that you <a target='_blank' href={$drupalPermissionsURL}>review these permissions</a> to ensure that they are appropriate for your requirements (<a target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'>learn more...</a>)</li>\n <li>Use the <a target='_blank' href=\"{$drupalURL}\">Configuration Checklist</a> to review and configure settings for your new site</li>\n <li> Have you registered this site at CiviCRM.org? If not, please help strengthen the CiviCRM ecosystem by taking a few minutes to <a href='{$registerSiteURL}' target='_blank'>fill out the site registration form</a>. The information collected will help us prioritize improvements, target our communications and build the community. If you have a technical role for this site, be sure to check Keep in Touch to receive technical updates (a low volume mailing list).</li>\n <li>We have integrated KCFinder with CKEditor and TinyMCE, which enables user to upload images. Note that all the images uploaded using KCFinder will be public.</li>"; // automatically enable CiviCRM module once it is installed successfully. // so we need to Bootstrap Drupal, so that we can call drupal hooks. global $cmsPath, $crmPath; // relative / abosolute paths are not working for drupal, hence using chdir() chdir($cmsPath); include_once "./includes/bootstrap.inc"; include_once "./includes/unicode.inc"; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // prevent session information from being saved. drupal_save_session(FALSE); // Force the current user to anonymous. $original_user = $GLOBALS['user']; $GLOBALS['user'] = drupal_anonymous_user(); // explicitly setting error reporting, since we cannot handle drupal related notices error_reporting(1); // rebuild modules, so that civicrm is added system_rebuild_module_data(); // now enable civicrm module. module_enable(array('civicrm', 'civicrmtheme')); // clear block and page cache, to make sure civicrm link is present in navigation block cache_clear_all(); //add basic drupal permissions civicrm_install_set_drupal_perms(); // restore the user. $GLOBALS['user'] = $original_user; drupal_save_session(TRUE); $output .= '</ul>'; $output .= '</div>'; $output .= '</body>'; $output .= '</html>'; echo $output; } elseif ($installType == 'drupal' && version_compare(VERSION, '6.0') >= 0) { // clean output @ob_clean(); $output .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; $output .= '<head>'; $output .= '<title>CiviCRM Installed</title>'; $output .= '<link rel="stylesheet" type="text/css" href="template.css" />'; $output .= '</head>'; $output .= '<body>'; $output .= '<div style="padding: 1em;"><p class="good">CiviCRM has been successfully installed</p>'; $output .= '<ul>'; $docLinkConfig = CRM_Utils_System::docURL2('Configuring a New Site', FALSE, 'here', NULL, NULL, "wiki"); if (!function_exists('ts')) { $docLinkConfig = "<a href=\"{$docLinkConfig}\">here</a>"; } $drupalURL = civicrm_cms_base(); $drupalPermissionsURL = "{$drupalURL}index.php?q=admin/user/permissions"; $drupalURL .= "index.php?q=civicrm/admin/configtask&reset=1"; $registerSiteURL = "http://civicrm.org/civicrm/profile/create?reset=1&gid=15"; $output .= "<li>Drupal user permissions have been automatically set - giving anonymous and authenticated users access to public CiviCRM forms and features. We recommend that you <a target='_blank' href={$drupalPermissionsURL}>review these permissions</a> to ensure that they are appropriate for your requirements (<a target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'>learn more...</a>)</li>\n <li>Use the <a target='_blank' href=\"{$drupalURL}\">Configuration Checklist</a> to review and configure settings for your new site</li>\n <li> Have you registered this site at CiviCRM.org? If not, please help strengthen the CiviCRM ecosystem by taking a few minutes to <a href='{$registerSiteURL}' target='_blank'>fill out the site registration form</a>. The information collected will help us prioritize improvements, target our communications and build the community. If you have a technical role for this site, be sure to check Keep in Touch to receive technical updates (a low volume mailing list).</li>\n <li>We have integrated KCFinder with CKEditor and TinyMCE, which enables user to upload images. Note that all the images uploaded using KCFinder will be public.</li>"; // explicitly setting error reporting, since we cannot handle drupal related notices error_reporting(1); // automatically enable CiviCRM module once it is installed successfully. // so we need to Bootstrap Drupal, so that we can call drupal hooks. global $cmsPath, $crmPath; // relative / abosolute paths are not working for drupal, hence using chdir() chdir($cmsPath); include_once "./includes/bootstrap.inc"; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // rebuild modules, so that civicrm is added module_rebuild_cache(); // now enable civicrm module. module_enable(array('civicrm')); // clear block and page cache, to make sure civicrm link is present in navigation block cache_clear_all(); //add basic drupal permissions db_query('UPDATE {permission} SET perm = CONCAT( perm, \', access CiviMail subscribe/unsubscribe pages, access all custom data, access uploaded files, make online contributions, profile create, profile edit, profile view, register for events, view event info\') WHERE rid IN (1, 2)'); echo $output; } elseif ($installType == 'wordpress') { echo '<h1>CiviCRM Installed</h1>'; echo '<div style="padding: 1em;"><p style="background-color: #0C0; border: 1px #070 solid; color: white;">CiviCRM has been successfully installed</p>'; echo '<ul>'; $docLinkConfig = CRM_Utils_System::docURL2('Configuring a New Site', FALSE, 'here', NULL, NULL, "wiki"); if (!function_exists('ts')) { $docLinkConfig = "<a href=\"{$docLinkConfig}\">here</a>"; } $cmsURL = civicrm_cms_base(); $cmsURL .= "wp-admin/admin.php?page=CiviCRM&q=civicrm/admin/configtask&reset=1"; $registerSiteURL = "http://civicrm.org/civicrm/profile/create?reset=1&gid=15"; echo "<li>Use the <a target='_blank' href=\"{$cmsURL}\">Configuration Checklist</a> to review and configure settings for your new site</li>\n <li> Have you registered this site at CiviCRM.org? If not, please help strengthen the CiviCRM ecosystem by taking a few minutes to <a href='{$registerSiteURL}' target='_blank'>fill out the site registration form</a>. The information collected will help us prioritize improvements, target our communications and build the community. If you have a technical role for this site, be sure to check Keep in Touch to receive technical updates (a low volume mailing list).</li>\n <li>We have integrated KCFinder with CKEditor and TinyMCE, which enables user to upload images. Note that all the images uploaded using KCFinder will be public.</li>"; echo '</ul>'; echo '</div>'; } } return $this->errors; }
/** * Delete created files and temporary files directory, delete the tables created by setUp(), * and reset the database prefix. */ protected function tearDown() { global $user, $language; // In case a fatal error occurred that was not in the test process read the // log to pick up any fatal errors. simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE); $emailCount = count(variable_get('drupal_test_email_collector', array())); if ($emailCount) { $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.'); $this->pass($message, t('E-mail')); } // Delete temporary files directory. file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10)); // Remove all prefixed tables (all the tables in the schema). $schema = drupal_get_schema(NULL, TRUE); foreach ($schema as $name => $table) { db_drop_table($name); } // Get back to the original connection. Database::removeConnection('default'); Database::renameConnection('simpletest_original_default', 'default'); // Restore original shutdown callbacks array to prevent original // environment of calling handlers from test run. $callbacks =& drupal_register_shutdown_function(); $callbacks = $this->originalShutdownCallbacks; // Return the user to the original one. $user = $this->originalUser; drupal_save_session(TRUE); // Ensure that internal logged in variable and cURL options are reset. $this->loggedInUser = FALSE; $this->additionalCurlOptions = array(); // Reload module list and implementations to ensure that test module hooks // aren't called after tests. module_list(TRUE); module_implements('', FALSE, TRUE); // Reset the Field API. field_cache_clear(); // Rebuild caches. $this->refreshVariables(); // Reset language. $language = $this->originalLanguage; if ($this->originalLanguageDefault) { $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault; } // Close the CURL handler. $this->curlClose(); }
/** * Delete created files and temporary files directory, delete the tables created by setUp(), * and reset the database prefix. */ protected function tearDown() { global $db_prefix, $user, $language; // In case a fatal error occured that was not in the test process read the // log to pick up any fatal errors. $db_prefix_temp = $db_prefix; $db_prefix = $this->originalPrefix; simpletest_log_read($this->testId, $db_prefix, get_class($this), TRUE); $db_prefix = $db_prefix_temp; $emailCount = count(variable_get('drupal_test_email_collector', array())); if ($emailCount) { $message = format_plural($emailCount, t('!count e-mail was sent during this test.'), t('!count e-mails were sent during this test.'), array('!count' => $emailCount)); $this->pass($message, t('E-mail')); } if (preg_match('/simpletest\\d+/', $db_prefix)) { // Delete temporary files directory. file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($db_prefix, 10)); // Remove all prefixed tables (all the tables in the schema). $schema = drupal_get_schema(NULL, TRUE); $ret = array(); foreach ($schema as $name => $table) { db_drop_table($name); } // Return the database prefix to the original. $db_prefix = $this->originalPrefix; // Return the user to the original one. $user = $this->originalUser; drupal_save_session(TRUE); // Ensure that internal logged in variable and cURL options are reset. $this->loggedInUser = FALSE; $this->additionalCurlOptions = array(); // Reload module list and implementations to ensure that test module hooks // aren't called after tests. module_list(TRUE); module_implements('', FALSE, TRUE); // Reset the Field API. field_cache_clear(); // Rebuild caches. $this->refreshVariables(); // Reset language. $language = $this->originalLanguage; if ($this->originalLanguageDefault) { $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault; } // Close the CURL handler. $this->curlClose(); } }
/** * Check the set of permissions in one forum. * * @param $forum * An associative array describing the forum. * @param $is_default * Set to TRUE if this is the default forum (without any moderator). */ function checkForum($forum, $is_default = FALSE) { $this->drupalLogin($this->user1); $this->drupalGet("admin/structure/forum/edit/forum/{$forum->tid}"); $this->assertResponse(200, "^^^ '{$forum->name}' exists."); foreach ($this->accounts as $key => $account) { // Retrieve the access settings for this account. $account->access = array(); foreach ($account->roles as $rid => $role_name) { foreach ($this->accesses as $access) { if ($this->isFieldChecked("edit-forum-access-grants-checkboxes-{$access}-{$rid}")) { $account->access[$access] = $access; } } } } foreach ($this->accounts as $key => $account) { // Create a topic and a comment for this account to experiment with. $account->node = $this->createForumTopicWithTitle($forum, "Topic for {$account->name}"); $account->comment = $this->createForumCommentWithText($account->node, "Comment for {$account->name}"); } // Show the topic list. $this->drupalGet("forum/{$forum->tid}"); $this->assertResponse(200, "^^^ '{$forum->name}' initial topics."); foreach ($this->accounts as $key => $account) { $is_super_user = user_access('bypass node access', $account) || $account->uid == $this->moderator->uid && !$is_default; if (!empty($account->uid)) { $this->drupalLogin($account); } else { $this->drupalLogout(); } // Check whether we have an 'Add new Forum topic' link. $this->drupalGet('forum'); if (empty($account->access['view']) && !$is_super_user) { $this->assertResponse(403, "^^^ {$account->name} cannot see the Forum Overview"); } elseif ((empty($account->access['create']) || !user_access('create forum content', $account)) && !$is_super_user) { $this->assertResponse(200, 'Forum Overview'); $this->assertNoLink(t('Add new Forum topic'), "^^^ {$account->name} cannot post in the '{$forum->name}'."); } else { $this->assertResponse(200, 'Forum Overview'); $this->assertLink($forum->name, 0, "^^^ {$account->name} can see the '{$forum->name}'."); $this->assertLink(t('Add new Forum topic'), 0, "^^^ {$account->name} can post in the '{$forum->name}'."); } foreach (array('any', 'own') as $test_type) { // Check whether we can View our topic. $comment =& $account->comment; $node =& $account->node; if ((empty($account->access['view']) || !user_access('access content', $account)) && !$is_super_user) { $this->drupalGet("forum/{$forum->tid}"); $this->assertResponse(404, "^^^ {$account->name} cannot access '{$forum->name}'."); $this->drupalGet("node/{$node->nid}"); $this->assertResponse(403, "^^^ {$account->name} cannot access {$test_type} topic."); $this->drupalGet("node/{$node->nid}/edit"); $this->assertResponse(403, "{$account->name} cannot edit {$test_type} topic (not accessible)."); $this->drupalGet("comment/{$comment->cid}"); $this->assertResponse(403, "^^^ {$account->name} cannot access comment '{$comment->subject}'."); } else { $this->drupalGet("forum/{$forum->tid}"); $this->assertResponse(200, "^^^ '{$forum->name}' as {$account->name}."); $this->assertLink($node->title); $this->clickLink($node->title); $this->assertResponse(200, "^^^ {$account->name} can access {$test_type} topic."); $this->assertText($comment->subject, "Comment '{$comment->subject}' found, too."); // Check comment visibility. if (!$is_super_user && (!user_access('access comments', $account) || empty($account->access['view'])) && !user_access('administer comments', $account)) { $this->assertNoLinkByHref("/comment/{$comment->cid}#comment-{$comment->cid}"); $this->drupalGet("comment/{$comment->cid}"); $this->assertResponse(403, "^^^ {$account->name} cannot see comment '{$comment->subject}'."); } else { $this->assertLinkByHref(url("comment/{$comment->cid}", array('fragment' => "comment-{$comment->cid}"))); // Check post comment / reply link. if ((!user_access('post comments', $account) && !user_access('post comments without approval', $account) || empty($account->access['create'])) && !$is_super_user) { if (!$account->uid) { $this->assertLinkByHref("/user/login?destination=node/{$node->nid}#comment-form"); } $this->assertNoLink(t('Add new comment')); $this->assertNoText(t('Add new comment')); $this->assertNoLink(t('reply')); $this->drupalGet("comment/{$comment->cid}"); $this->assertResponse(200, '^^^ ' . "Comment '{$comment->subject}' is visible to {$account->name}'."); $this->drupalGet("comment/reply/{$node->nid}"); $this->assertResponse(403); $this->drupalGet("comment/reply/{$node->nid}/{$comment->cid}"); $this->assertResponse(403); } else { $this->assertText(t('Add new comment')); $this->assertLink(t('reply')); $this->assertLinkByHref("comment/reply/{$node->nid}/{$comment->cid}"); $this->drupalGet("comment/reply/{$node->nid}/{$comment->cid}"); $this->assertResponse(200); } // Check comment edit links. global $user; drupal_save_session(FALSE); $user_save = $user; $user = $account; // We ignore the 'edit own comments' permission! $comment_access_edit = FALSE; // comment_access('edit', $comment); $user = $user_save; drupal_save_session(TRUE); $this->drupalGet("comment/{$comment->cid}"); $this->assertResponse(200); if (empty($account->access['update']) && !$is_super_user && !$comment_access_edit && !user_access('administer comments', $account) && !user_access('edit any forum content', $account) && !($account->uid == $comment->uid && user_access('edit own forum content', $account))) { $this->assertNoLink(t('edit')); $this->drupalGet("comment/{$comment->cid}/edit"); $this->assertResponse(403); } else { $this->assertLink(t('edit')); $this->clickLink(t('edit')); $this->assertResponse(200); $this->drupalGet("comment/{$comment->cid}/edit"); $this->assertResponse(200); $this->assertText($comment->subject); $comment->title .= ' (updated)'; $this->drupalPost("comment/{$comment->cid}/edit", array('subject' => $comment->subject), t('Save')); $this->assertText(t("Your comment has been posted.")); // It ought to say 'updated'! } // Check comment delete links. $this->drupalGet("comment/{$comment->cid}"); if (empty($account->access['delete']) && !$is_super_user && !user_access('administer comments', $account) && !user_access('delete any forum content', $account) && !($account->uid == $comment->uid && user_access('delete own forum content', $account))) { $this->assertNoLink(t('delete')); $this->drupalGet("comment/{$comment->cid}/delete"); $this->assertResponse(403); } else { $this->assertText($comment->subject); $this->assertLink(t('delete')); $this->clickLink(t('delete')); $this->assertResponse(200); $this->drupalGet("comment/{$comment->cid}/delete"); $this->assertResponse(200); $this->drupalPost("comment/{$comment->cid}/delete", array(), t('Delete')); $this->assertText(t('The comment and all its replies have been deleted.')); $this->assertNoText($comment->subject); unset($account->comment); } } // Check whether we can Edit our topic. $this->drupalGet("node/{$node->nid}"); $this->assertResponse(200); if (empty($account->access['update']) && !user_access('edit any forum content', $account) && !(user_access('edit own forum content', $account) && $node->uid == $account->uid) && !$is_super_user) { $this->assertNoLink(t('Edit')); $this->drupalGet("node/{$node->nid}/edit"); $this->assertResponse(403, "{$account->name} cannot edit {$test_type} topic."); } else { $this->assertLink(t('Edit')); $this->clickLink(t('Edit')); $this->assertResponse(200, "^^^ {$account->name} can edit {$test_type} topic."); // Check whether we can Delete our topic. if (empty($account->access['delete']) && !user_access('delete any forum content', $account) && !(user_access('delete own forum content', $account) && $node->uid == $account->uid) && !$is_super_user) { $this->assertNoButton(t('Delete'), 0, $account->name . ' has no Delete button.'); } else { $this->assertButton(t('Delete'), 0, $account->name . ' has a Delete button.'); } // Change the title. $node->title = $node->title . ' (changed)'; $this->drupalPost("node/{$node->nid}/edit", array('title' => $node->title), t('Save')); $this->assertText(t('Forum topic !title has been updated.', array('!title' => $node->title))); } // Check whether we can delete the topic. if (empty($account->access['delete']) && !user_access('delete any forum content', $account) && !(user_access('delete own forum content', $account) && $node->uid == $account->uid) && !$is_super_user) { $this->drupalGet("node/{$node->nid}/delete"); $this->assertResponse(403, "{$account->name} cannot delete {$test_type} topic."); } else { $this->drupalPost("node/{$node->nid}/delete", array(), t('Delete')); $this->assertText(t('Forum topic !title has been deleted.', array('!title' => $node->title))); } } if ($test_type == 'any' && (!empty($account->access['view']) || $is_super_user)) { // Check whether we can create a topic. if ((empty($account->access['create']) || !user_access('create forum content', $account)) && !$is_super_user) { $this->drupalGet('forum'); if (empty($account->uid)) { $this->assertLinkByHref('/user/login?destination=forum'); } else { $this->assertResponse(200, "^^^ {$account->name} can see the Forum Overview, but..."); $this->assertText(t('You are not allowed to post new content in the forum.')); } $this->drupalGet("node/add/forum/{$forum->tid}"); $this->assertResponse(403, "^^^ {$account->name} cannot create a forum topic in '{$forum->name}'."); break; } else { $this->drupalGet('forum'); $this->assertNoText(t('You are not allowed to post new content in the forum.')); $this->assertLink(t('Add new Forum topic')); $this->clickLink(t('Add new Forum topic')); $this->assertResponse(200, "^^^ {$account->name} can create a forum topic."); $this->drupalGet("node/add/forum/{$forum->tid}"); $this->assertResponse(200, "^^^ {$account->name} can create a forum topic in '{$forum->name}'."); $this->drupalGet('forum'); $this->assertLink(t('Add new Forum topic')); $this->drupalPost("node/add/forum/{$forum->tid}", array('title' => "Topic 1 by {$account->name}"), t('Save')); $node = $account->node = $this->createForumTopicWithTitle($forum, "Topic 2 by {$account->name}"); $this->drupalGet('node/' . $node->nid); $account->comment = $this->createForumCommentWithText($node, "Comment by {$account->name}"); $this->drupalGet("forum/{$forum->tid}"); $this->assertResponse(200, "^^^ '{$forum->name}' as {$account->name} (own topic)."); } } } } $this->drupalLogin($this->user1); $this->drupalGet("forum/{$forum->tid}"); $this->assertResponse(200, "^^^ '{$forum->name}' remaining topics."); }
/** * Switch the user to the authenticated user, and back. * * This should be called only for an API call. It should not be used for calls * via the menu system, as it might be a login request, so we avoid switching * back to the anonymous user. */ public function switchUserBack() { global $user; if (!$user_state = $this->getOriginalUserSession()) { return; } $user = $user_state['user']; drupal_save_session($user_state['session']); }
/** * Session handler assigned by session_set_save_handler(). * * Cleans up a specific session. * * @param $sid * Session ID. * @return bool|void */ public function destroy($sid) { global $user; // Nothing to do if we are not allowed to change the session. if (!drupal_save_session()) { return; } // Delete session data. db_delete('sessions')->condition('sid', $sid)->execute(); // Reset $_SESSION and $user to prevent a new session from being started // in drupal_session_commit(). $_SESSION = array(); $user = drupal_anonymous_user(); }
/** * Delete created files and temporary files directory, delete the tables created by setUp(), * and reset the database prefix. */ protected function tearDown() { global $db_prefix, $user; if (preg_match('/simpletest\\d+/', $db_prefix)) { // Delete temporary files directory and reset files directory path. file_unmanaged_delete_recursive(file_directory_path()); variable_set('file_directory_path', $this->originalFileDirectory); // Remove all prefixed tables (all the tables in the schema). $schema = drupal_get_schema(NULL, TRUE); $ret = array(); foreach ($schema as $name => $table) { db_drop_table($ret, $name); } // Return the database prefix to the original. $db_prefix = $this->originalPrefix; // Return the user to the original one. $user = $this->originalUser; drupal_save_session(TRUE); // Ensure that internal logged in variable and cURL options are reset. $this->loggedInUser = FALSE; $this->additionalCurlOptions = array(); // Reload module list and implementations to ensure that test module hooks // aren't called after tests. module_list(TRUE); module_implements(MODULE_IMPLEMENTS_CLEAR_CACHE); // Reset the Field API. field_cache_clear(); // Rebuild caches. $this->refreshVariables(); // Close the CURL handler. $this->curlClose(); } }
/** * Delete created files and temporary files directory, delete the tables created by setUp(), * and reset the database prefix. */ protected function tearDown() { global $db_prefix, $user, $language; $emailCount = count(variable_get('simpletest_emails', array())); if ($emailCount) { $message = format_plural($emailCount, t('!count e-mail was sent during this test.'), t('!count e-mails were sent during this test.'), array('!count' => $emailCount)); $this->pass($message, t('E-mail')); } if (preg_match('/simpletest\\d+/', $db_prefix)) { // Delete temporary files directory and reset files directory path. file_unmanaged_delete_recursive(file_directory_path()); variable_set('file_directory_path', $this->originalFileDirectory); // Remove all prefixed tables (all the tables in the schema). $schema = drupal_get_schema(NULL, TRUE); $ret = array(); foreach ($schema as $name => $table) { db_drop_table($ret, $name); } // Return the database prefix to the original. $db_prefix = $this->originalPrefix; // Return the user to the original one. $user = $this->originalUser; drupal_save_session(TRUE); // Ensure that internal logged in variable and cURL options are reset. $this->loggedInUser = FALSE; $this->additionalCurlOptions = array(); // Reload module list and implementations to ensure that test module hooks // aren't called after tests. module_list(TRUE); module_implements(MODULE_IMPLEMENTS_CLEAR_CACHE); // Reset the Field API. field_cache_clear(); // Rebuild caches. $this->refreshVariables(); // Reset language. $language = $this->originalLanguage; if ($this->originalLanguageDefault) { $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault; } // Close the CURL handler. $this->curlClose(); } }
/** * Helper function that mimics node.module's node_access() function. * * Unfortunately, this needs to be updated manually whenever node.module * changes! * * @param $op * @param $node * @param null $account * @param null $langcode * * @return array * An array suitable for theming with theme_dna_permission(). */ public static function explain_access($op, $node, $account = NULL, $langcode = NULL) { global $user; if (!$node) { return array(FALSE, '???', t('No node passed to node_access(); this should never happen!')); } if (!in_array($op, array('view', 'update', 'delete', 'create'), TRUE)) { return array(FALSE, t('!NO: invalid $op', array('!NO' => t('NO'))), t("'@op' is an invalid operation!", array('@op' => $op))); } if ($op == 'create' && is_object($node)) { $node = $node->bundle(); } if (!empty($account)) { // To try to get the most authentic result we impersonate the given user! // This may reveal bugs in other modules, leading to contradictory // results. $saved_user = $user; drupal_save_session(FALSE); $user = $account; $result = DnaBlockBase::explain_access($op, $node, NULL, $langcode); $user = $saved_user; drupal_save_session(TRUE); $second_opinion = node_access($op, $node, $account); if ($second_opinion != $result[0]) { $result[1] .= '<span class="' . ($second_opinion ? 'ok' : 'error') . '" title="Core seems to disagree on this item. This is a bug in either DNA or Core and should be fixed! Try to look at this node as this user and check whether there is still disagreement.">*</span>'; } return $result; } if (empty($langcode)) { $langcode = is_object($node) && $node->id() ? $node->langcode->value : ''; } $variables = array('!NO' => t('NO'), '!YES' => t('YES'), '!bypass_node_access' => t('bypass node access'), '!access_content' => t('access content')); if (\Drupal::currentUser()->hasPermission('bypass node access')) { return array(TRUE, t('!YES: bypass node access', $variables), t("!YES: This user has the '!bypass_node_access' permission and may do everything with nodes.", $variables)); } if (!\Drupal::currentUser()->hasPermission('access content')) { return array(FALSE, t('!NO: access content', $variables), t("!NO: This user does not have the '!access_content' permission and is denied doing anything with content.", $variables)); } foreach (\Drupal::moduleHandler()->getImplementations('node_access') as $module) { $function = $module . '_node_access'; if (function_exists($function)) { $result = $function($node, $op, $user, $langcode); if ($module == 'node') { $module = 'node (permissions)'; } if (isset($result)) { if ($result === NODE_ACCESS_DENY) { $denied_by[] = $module; } elseif ($result === NODE_ACCESS_ALLOW) { $allowed_by[] = $module; } $access[] = $result; } } } $variables += array('@deniers' => empty($denied_by) ? NULL : implode(', ', $denied_by), '@allowers' => empty($allowed_by) ? NULL : implode(', ', $allowed_by)); if (!empty($denied_by)) { $variables += array('%module' => $denied_by[0] . (count($denied_by) > 1 ? '+' : '')); return array(FALSE, t('!NO: by %module', $variables), empty($allowed_by) ? t("!NO: hook_node_access() of the following module(s) denies this: @deniers.", $variables) : t("!NO: hook_node_access() of the following module(s) denies this: @deniers – even though the following module(s) would allow it: @allowers.", $variables)); } if (!empty($allowed_by)) { $variables += array('%module' => $allowed_by[0] . (count($allowed_by) > 1 ? '+' : ''), '!view_own_unpublished_content' => t('view own unpublished content')); return array(TRUE, t('!YES: by %module', $variables), t("!YES: hook_node_access() of the following module(s) allows this: @allowers.", $variables)); } if ($op == 'view' && !$node->get('status', $langcode) && \Drupal::currentUser()->hasPermission('view own unpublished content') && $user->uid == $node->get('uid', $langcode) && $user->uid != 0) { return array(TRUE, t('!YES: view own unpublished content', $variables), t("!YES: The node is unpublished, but the user has the '!view_own_unpublished_content' permission.", $variables)); } if ($op != 'create' && $node->id()) { if (node_access($op, $node, $user, $langcode)) { // delegate this part $variables['@node_access_table'] = '{node_access}'; return array(TRUE, t('!YES: @node_access_table', $variables), t('!YES: Node access allows this based on one or more records in the @node_access_table table (see the other DNA block!).', $variables)); } } return array(FALSE, t('!NO: no reason', $variables), t("!NO: None of the checks resulted in allowing this, so it's denied.", $variables) . ($op == 'create' ? ' ' . t('This is most likely due to a withheld permission.') : '')); }
/** * Don't create test db via install, instead copy existing db. */ protected function setUp() { // Copy of parent::setUp(); global $user, $language, $conf; // Generate a temporary prefixed database to ensure that tests have a clean starting point. $this->databasePrefix = 'simpletest' . mt_rand(1000, 1000000); db_update('simpletest_test_id')->fields(array('last_prefix' => $this->databasePrefix))->condition('test_id', $this->testId)->execute(); // Store necessary current values before switching to prefixed database. $this->originalLanguage = $language; $this->originalLanguageDefault = variable_get('language_default'); $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files'); $this->originalProfile = drupal_get_profile(); $clean_url_original = variable_get('clean_url', 0); // Save and clean shutdown callbacks array because it static cached and // will be changed by the test run. If we don't, then it will contain // callbacks from both environments. So testing environment will try // to call handlers from original environment. $callbacks =& drupal_register_shutdown_function(); $this->originalShutdownCallbacks = $callbacks; $callbacks = array(); // Create test directory ahead of installation so fatal errors and debug // information can be logged during installation process. // Use temporary files directory with the same prefix as the database. $this->public_files_directory = $this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10); $this->private_files_directory = $this->public_files_directory . '/private'; $this->temp_files_directory = $this->private_files_directory . '/temp'; // Create the directories file_prepare_directory($this->public_files_directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS); file_prepare_directory($this->private_files_directory, FILE_CREATE_DIRECTORY); file_prepare_directory($this->temp_files_directory, FILE_CREATE_DIRECTORY); $this->generatedTestFiles = FALSE; // Log fatal errors. ini_set('log_errors', 1); ini_set('error_log', $this->public_files_directory . '/error.log'); // Set the test information for use in other parts of Drupal. $test_info =& $GLOBALS['drupal_test_info']; $test_info['test_run_id'] = $this->databasePrefix; $test_info['in_child_site'] = FALSE; // Rebuild schema based on prefixed database and such. $schemas = drupal_get_schema(NULL, TRUE); // Create a list of prefixed source table names. $sources = array(); foreach ($schemas as $name => $schema) { $sources[$name] = Database::getConnection()->prefixTables('{' . $name . '}'); } // Clone the current connection and replace the current prefix. $connection_info = Database::getConnectionInfo('default'); Database::renameConnection('default', 'simpletest_original_default'); foreach ($connection_info as $target => $value) { $connection_info[$target]['prefix'] = array('default' => $value['prefix']['default'] . $this->databasePrefix); } Database::addConnectionInfo('default', 'default', $connection_info['default']); // Clone each table into the new database. foreach ($schemas as $name => $schema) { $this->cloneTable($name, $sources[$name], $schema); } // Log in with a clean $user. $this->originalUser = $user; drupal_save_session(FALSE); $user = user_load(1); // Set up English language. unset($GLOBALS['conf']['language_default']); $language = language_default(); // Use the test mail class instead of the default mail handler class. variable_set('mail_system', array('default-system' => 'TestingMailSystem')); drupal_set_time_limit($this->timeLimit); $this->resetAll(); $this->refreshVariables(); $this->setup = TRUE; }
/** * Switch the user back to the original user. * * @param User $original_user_object * Original user object. * @param array $old_state * SESSION values of original user. */ public static function unmasquerade(User $original_user_object, $old_state) { global $user; $user = $original_user_object->getEntity(); drupal_save_session($old_state); }
/** * @param $config * * @return mixed */ public function install($config) { global $installDirPath; // create database if does not exists $this->createDatabaseIfNotExists($config['mysql']['server'], $config['mysql']['username'], $config['mysql']['password'], $config['mysql']['database']); global $installDirPath; // Build database require_once $installDirPath . 'civicrm.php'; civicrm_main($config); if (!$this->errors) { global $installType, $installURLPath; $registerSiteURL = "https://civicrm.org/register-site"; $commonOutputMessage = "<li>" . ts("Have you registered this site at CiviCRM.org? If not, please help strengthen the CiviCRM ecosystem by taking a few minutes to <a %1>fill out the site registration form</a>. The information collected will help us prioritize improvements, target our communications and build the community. If you have a technical role for this site, be sure to check Keep in Touch to receive technical updates (a low volume mailing list).", array(1 => "href='{$registerSiteURL}' target='_blank'")) . "</li>" . "<li>" . ts("We have integrated KCFinder with CKEditor and TinyMCE. This allows a user to upload images. All uploaded images are public.") . "</li>"; $output = NULL; if ($installType == 'drupal' && version_compare(VERSION, '7.0-rc1') >= 0) { // clean output @ob_clean(); $output .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; $output .= '<head>'; $output .= '<title>' . ts('CiviCRM Installed') . '</title>'; $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'; $output .= '<link rel="stylesheet" type="text/css" href="template.css" />'; $output .= '</head>'; $output .= '<body>'; $output .= '<div style="padding: 1em;"><p class="good">' . ts('CiviCRM has been successfully installed') . '</p>'; $output .= '<ul>'; $drupalURL = civicrm_cms_base(); $drupalPermissionsURL = "{$drupalURL}index.php?q=admin/people/permissions"; $drupalURL .= "index.php?q=civicrm/admin/configtask&reset=1"; $output .= "<li>" . ts("Drupal user permissions have been automatically set - giving anonymous and authenticated users access to public CiviCRM forms and features. We recommend that you <a %1>review these permissions</a> to ensure that they are appropriate for your requirements (<a %2>learn more...</a>)", array(1 => "target='_blank' href='{$drupalPermissionsURL}'", 2 => "target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'")) . "</li>"; $output .= "<li>" . ts("Use the <a %1>Configuration Checklist</a> to review and configure settings for your new site", array(1 => "target='_blank' href='{$drupalURL}'")) . "</li>"; $output .= $commonOutputMessage; // automatically enable CiviCRM module once it is installed successfully. // so we need to Bootstrap Drupal, so that we can call drupal hooks. global $cmsPath, $crmPath; // relative / abosolute paths are not working for drupal, hence using chdir() chdir($cmsPath); // Force the re-initialisation of the config singleton on the next call // since so far, we had used the Config object without loading the DB. $c = CRM_Core_Config::singleton(FALSE); $c->free(); include_once "./includes/bootstrap.inc"; include_once "./includes/unicode.inc"; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // prevent session information from being saved. drupal_save_session(FALSE); // Force the current user to anonymous. $original_user = $GLOBALS['user']; $GLOBALS['user'] = drupal_anonymous_user(); // explicitly setting error reporting, since we cannot handle drupal related notices error_reporting(1); // rebuild modules, so that civicrm is added system_rebuild_module_data(); // now enable civicrm module. module_enable(array('civicrm', 'civicrmtheme')); // clear block, page, theme, and hook caches drupal_flush_all_caches(); //add basic drupal permissions civicrm_install_set_drupal_perms(); // restore the user. $GLOBALS['user'] = $original_user; drupal_save_session(TRUE); //change the default language to one chosen if (isset($config['seedLanguage']) && $config['seedLanguage'] != 'en_US') { civicrm_api3('Setting', 'create', array('domain_id' => 'current_domain', 'lcMessages' => $config['seedLanguage'])); } $output .= '</ul>'; $output .= '</div>'; $output .= '</body>'; $output .= '</html>'; echo $output; } elseif ($installType == 'drupal' && version_compare(VERSION, '6.0') >= 0) { // clean output @ob_clean(); $output .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $output .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'; $output .= '<head>'; $output .= '<title>' . ts('CiviCRM Installed') . '</title>'; $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'; $output .= '<link rel="stylesheet" type="text/css" href="template.css" />'; $output .= '</head>'; $output .= '<body>'; $output .= '<div style="padding: 1em;"><p class="good">' . ts("CiviCRM has been successfully installed") . '</p>'; $output .= '<ul>'; $drupalURL = civicrm_cms_base(); $drupalPermissionsURL = "{$drupalURL}index.php?q=admin/user/permissions"; $drupalURL .= "index.php?q=civicrm/admin/configtask&reset=1"; $output .= "<li>" . ts("Drupal user permissions have been automatically set - giving anonymous and authenticated users access to public CiviCRM forms and features. We recommend that you <a %1>review these permissions</a> to ensure that they are appropriate for your requirements (<a %2>learn more...</a>)", array(1 => "target='_blank' href='{$drupalPermissionsURL}'", 2 => "target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'")) . "</li>"; $output .= "<li>" . ts("Use the <a %1>Configuration Checklist</a> to review and configure settings for your new site", array(1 => "target='_blank' href='{$drupalURL}'")) . "</li>"; $output .= $commonOutputMessage; // explicitly setting error reporting, since we cannot handle drupal related notices error_reporting(1); // automatically enable CiviCRM module once it is installed successfully. // so we need to Bootstrap Drupal, so that we can call drupal hooks. global $cmsPath, $crmPath; // relative / abosolute paths are not working for drupal, hence using chdir() chdir($cmsPath); // Force the re-initialisation of the config singleton on the next call // since so far, we had used the Config object without loading the DB. $c = CRM_Core_Config::singleton(FALSE); $c->free(); include_once "./includes/bootstrap.inc"; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); // rebuild modules, so that civicrm is added module_rebuild_cache(); // now enable civicrm module. module_enable(array('civicrm')); // clear block, page, theme, and hook caches drupal_flush_all_caches(); //add basic drupal permissions db_query('UPDATE {permission} SET perm = CONCAT( perm, \', access CiviMail subscribe/unsubscribe pages, access all custom data, access uploaded files, make online contributions, profile create, profile edit, profile view, register for events, view event info\') WHERE rid IN (1, 2)'); echo $output; } elseif ($installType == 'wordpress') { echo '<h1>' . ts('CiviCRM Installed') . '</h1>'; echo '<div style="padding: 1em;"><p style="background-color: #0C0; border: 1px #070 solid; color: white;">' . ts("CiviCRM has been successfully installed") . '</p>'; echo '<ul>'; $cmsURL = civicrm_cms_base(); $cmsURL .= "wp-admin/admin.php?page=CiviCRM&q=civicrm/admin/configtask&reset=1"; $wpPermissionsURL = "wp-admin/admin.php?page=CiviCRM&q=civicrm/admin/access/wp-permissions&reset=1"; $output .= "<li>" . ts("WordPress user permissions have been automatically set - giving Anonymous and Subscribers access to public CiviCRM forms and features. We recommend that you <a %1>review these permissions</a> to ensure that they are appropriate for your requirements (<a %2>learn more...</a>)", array(1 => "target='_blank' href='{$wpPermissionsURL}'", 2 => "target='_blank' href='http://wiki.civicrm.org/confluence/display/CRMDOC/Default+Permissions+and+Roles'")) . "</li>"; $output .= "<li>" . ts("Use the <a %1>Configuration Checklist</a> to review and configure settings for your new site", array(1 => "target='_blank' href='{$cmsURL}'")) . "</li>"; $output .= $commonOutputMessage; echo '</ul>'; echo '</div>'; $c = CRM_Core_Config::singleton(FALSE); $c->free(); $wpInstallRedirect = admin_url("?page=CiviCRM&q=civicrm&reset=1"); echo "<script>\n window.location = '{$wpInstallRedirect}';\n </script>"; } } return $this->errors; }
function restoreUser($u, $o_s) { if ($u) { $GLOABALS['user'] = $u; drupal_save_session($o_s); } }
/** * Delete created files and temporary files directory, delete the tables created by setUp(), * and reset the database prefix. */ protected function tearDown() { global $user, $language; // In case a fatal error occurred that was not in the test process read the // log to pick up any fatal errors. simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE); $emailCount = count(variable_get('drupal_test_email_collector', array())); if ($emailCount) { $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.'); $this->pass($message, t('E-mail')); } // Delete temporary files directory. file_unmanaged_delete_recursive($this->originalFileDirectory . '/simpletest/' . substr($this->databasePrefix, 10)); // Remove all prefixed tables. $tables = db_find_tables($this->databasePrefix . '%'); $connection_info = Database::getConnectionInfo('default'); $tables = db_find_tables($connection_info['default']['prefix']['default'] . '%'); if (empty($tables)) { $this->fail('Failed to find test tables to drop.'); } $prefix_length = strlen($connection_info['default']['prefix']['default']); foreach ($tables as $table) { if (db_drop_table(substr($table, $prefix_length))) { unset($tables[$table]); } } if (!empty($tables)) { $this->fail('Failed to drop all prefixed tables.'); } // Get back to the original connection. Database::removeConnection('default'); Database::renameConnection('simpletest_original_default', 'default'); // Restore original shutdown callbacks array to prevent original // environment of calling handlers from test run. $callbacks =& drupal_register_shutdown_function(); $callbacks = $this->originalShutdownCallbacks; // Return the user to the original one. $user = $this->originalUser; drupal_save_session(TRUE); // Ensure that internal logged in variable and cURL options are reset. $this->loggedInUser = FALSE; $this->additionalCurlOptions = array(); // Reload module list and implementations to ensure that test module hooks // aren't called after tests. module_list(TRUE); module_implements('', FALSE, TRUE); // Reset the Field API. field_cache_clear(); // Rebuild caches. $this->refreshVariables(); // Reset public files directory. $GLOBALS['conf']['file_public_path'] = $this->originalFileDirectory; // Reset language. $language = $this->originalLanguage; if ($this->originalLanguageDefault) { $GLOBALS['conf']['language_default'] = $this->originalLanguageDefault; } // Close the CURL handler and reset the cookies array so test classes // containing multiple tests are not polluted. $this->curlClose(); $this->cookies = array(); }