First commit

This commit is contained in:
Theodotos Andreou 2018-01-14 13:10:16 +00:00
commit c6e2478c40
13918 changed files with 2303184 additions and 0 deletions

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,935 @@
<?php
/**
* Base class for UF system integrations
*/
abstract class CRM_Utils_System_Base {
/**
* Deprecated property to check if this is a drupal install.
*
* The correct method is to have functions on the UF classes for all UF specific
* functions and leave the codebase oblivious to the type of CMS
*
* @deprecated
* @var bool
* TRUE, if the CMS is Drupal.
*/
var $is_drupal = FALSE;
/**
* Deprecated property to check if this is a joomla install. The correct method is to have functions on the UF classes for all UF specific
* functions and leave the codebase oblivious to the type of CMS
*
* @deprecated
* @var bool
* TRUE, if the CMS is Joomla!.
*/
var $is_joomla = FALSE;
/**
* deprecated property to check if this is a wordpress install. The correct method is to have functions on the UF classes for all UF specific
* functions and leave the codebase oblivious to the type of CMS
*
* @deprecated
* @var bool
* TRUE, if the CMS is WordPress.
*/
var $is_wordpress = FALSE;
/**
* Does this CMS / UF support a CMS specific logging mechanism?
* @todo - we should think about offering up logging mechanisms in a way that is also extensible by extensions
* @var bool
*/
var $supports_UF_Logging = FALSE;
/**
* @var bool
* TRUE, if the CMS allows CMS forms to be extended by hooks.
*/
var $supports_form_extensions = FALSE;
public function initialize() {
if (\CRM_Utils_System::isSSL()) {
$this->mapConfigToSSL();
}
}
/**
* Append an additional breadcrumb tag to the existing breadcrumb.
*
* @param array $breadCrumbs
*/
public function appendBreadCrumb($breadCrumbs) {
}
/**
* Reset an additional breadcrumb tag to the existing breadcrumb.
*/
public function resetBreadCrumb() {
}
/**
* Append a string to the head of the html file.
*
* @param string $head
* The new string to be appended.
*/
public function addHTMLHead($head) {
}
/**
* Rewrite various system urls to https.
*/
public function mapConfigToSSL() {
// dont need to do anything, let CMS handle their own switch to SSL
}
/**
* Figure out the post url for QuickForm.
*
* @param string $action
* The default url if one is pre-specified.
*
* @return string
* The url to post the form.
*/
public function postURL($action) {
$config = CRM_Core_Config::singleton();
if (!empty($action)) {
return $action;
}
return $this->url(CRM_Utils_Array::value($config->userFrameworkURLVar, $_GET),
NULL, TRUE, NULL, FALSE
);
}
/**
* Generate the url string to a CiviCRM path.
*
* @param string $path
* The path being linked to, such as "civicrm/add".
* @param string $query
* A query string to append to the link.
* @param bool $absolute
* Whether to force the output to be an absolute link (beginning with http).
* Useful for links that will be displayed outside the site, such as in an RSS feed.
* @param string $fragment
* A fragment identifier (named anchor) to append to the link.
* @param bool $frontend
* This link should be to the CMS front end (applies to WP & Joomla).
* @param bool $forceBackend
* This link should be to the CMS back end (applies to WP & Joomla).
*
* @return string
*/
public function url(
$path = NULL,
$query = NULL,
$absolute = FALSE,
$fragment = NULL,
$frontend = FALSE,
$forceBackend = FALSE
) {
return NULL;
}
/**
* Authenticate the user against the CMS db.
*
* @param string $name
* The user name.
* @param string $password
* The password for the above user.
* @param bool $loadCMSBootstrap
* Load cms bootstrap?.
* @param string $realPath
* Filename of script
*
* @return array|bool
* [contactID, ufID, unique string] else false if no auth
*/
public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
return FALSE;
}
/**
* Set a message in the CMS to display to a user.
*
* @param string $message
* The message to set.
*/
public function setMessage($message) {
}
/**
* Load user into session.
*
* @param obj $user
*
* @return bool
*/
public function loadUser($user) {
return TRUE;
}
/**
* Immediately stop script execution and display a 401 "Access Denied" page.
*/
public function permissionDenied() {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
/**
* Immediately stop script execution, log out the user and redirect to the home page.
*
* @deprecated
* This function should be removed in favor of linking to the CMS's logout page
*/
public function logout() {
}
/**
* Clear CMS caches related to the user registration/profile forms.
* Used when updating/embedding profiles on CMS user forms.
* @see CRM-3600
*/
public function updateCategories() {
}
/**
* Get the locale set in the CMS.
*
* @return string|null
* Locale or null for none
*/
public function getUFLocale() {
return NULL;
}
/**
* If we are using a theming system, invoke theme, else just print the content.
*
* @param string $content
* The content that will be themed.
* @param bool $print
* Are we displaying to the screen or bypassing theming?.
* @param bool $maintenance
* For maintenance mode.
*
* @throws Exception
* @return string|null
* NULL, If $print is FALSE, and some other criteria match up.
* The themed string, otherwise.
*
* @todo The return value is inconsistent.
* @todo Better to always return, and never print.
*/
public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
$ret = FALSE;
// TODO: Split up; this was copied verbatim from CiviCRM 4.0's multi-UF theming function
// but the parts should be copied into cleaner subclass implementations
$config = CRM_Core_Config::singleton();
if (
$config->userSystem->is_drupal &&
function_exists('theme') &&
!$print
) {
if ($maintenance) {
drupal_set_breadcrumb('');
drupal_maintenance_theme();
if ($region = CRM_Core_Region::instance('html-header', FALSE)) {
CRM_Utils_System::addHTMLHead($region->render(''));
}
print theme('maintenance_page', array('content' => $content));
exit();
}
// TODO: Figure out why D7 returns but everyone else prints
$ret = TRUE;
}
$out = $content;
$config = &CRM_Core_Config::singleton();
if (
!$print &&
$config->userFramework == 'WordPress'
) {
if (!function_exists('is_admin')) {
throw new \Exception('Function "is_admin()" is missing, even though WordPress is the user framework.');
}
if (!defined('ABSPATH')) {
throw new \Exception('Constant "ABSPATH" is not defined, even though WordPress is the user framework.');
}
if (is_admin()) {
require_once ABSPATH . 'wp-admin/admin-header.php';
}
else {
// FIXME: we need to figure out to replace civicrm content on the frontend pages
}
}
if ($ret) {
return $out;
}
else {
print $out;
return NULL;
}
}
/**
* @return string
*/
public function getDefaultBlockLocation() {
return 'left';
}
/**
* Get the absolute path to the site's base url.
*
* @return bool|mixed|string
*/
public function getAbsoluteBaseURL() {
if (!defined('CIVICRM_UF_BASEURL')) {
return FALSE;
}
$url = CRM_Utils_File::addTrailingSlash(CIVICRM_UF_BASEURL, '/');
//format url for language negotiation, CRM-7803
$url = $this->languageNegotiationURL($url);
if (CRM_Utils_System::isSSL()) {
$url = str_replace('http://', 'https://', $url);
}
return $url;
}
/**
* Get the relative path to the sites base url.
*
* @return bool
*/
public function getRelativeBaseURL() {
$absoluteBaseURL = $this->getAbsoluteBaseURL();
if ($absoluteBaseURL === FALSE) {
return FALSE;
}
$parts = parse_url($absoluteBaseURL);
return $parts['path'];
//$this->useFrameworkRelativeBase = empty($base['path']) ? '/' : $base['path'];
}
/**
* Get CMS Version.
*
* @return string
*/
public function getVersion() {
return 'Unknown';
}
/**
* Format the url as per language Negotiation.
*
* @param string $url
* @param bool $addLanguagePart
* @param bool $removeLanguagePart
*
* @return string
* Formatted url.
*/
public function languageNegotiationURL(
$url,
$addLanguagePart = TRUE,
$removeLanguagePart = FALSE
) {
return $url;
}
/**
* Determine the location of the CMS root.
*
* @return string|null
* Local file system path to CMS root, or NULL if it cannot be determined
*/
public function cmsRootPath() {
return NULL;
}
/**
* Create a user in the CMS.
*
* @param array $params
* @param string $mail
* Email id for cms user.
*
* @return int|bool
* uid if user exists, false otherwise
*/
public function createUser(&$params, $mail) {
return FALSE;
}
/**
* Update a user's email address in the CMS.
*
* @param int $ufID
* User ID in CMS.
* @param string $email
* Primary contact email address.
*/
public function updateCMSName($ufID, $email) {
}
/**
* Check if user is logged in to the CMS.
*
* @return bool
*/
public function isUserLoggedIn() {
return FALSE;
}
/**
* Check if user registration is permitted.
*
* @return bool
*/
public function isUserRegistrationPermitted() {
return FALSE;
}
/**
* Check if user can create passwords or is initially assigned a system-generated one.
*
* @return bool
*/
public function isPasswordUserGenerated() {
return FALSE;
}
/**
* Get user login URL for hosting CMS (method declared in each CMS system class)
*
* @param string $destination
* If present, add destination to querystring (works for Drupal only).
*
* @return string
* loginURL for the current CMS
*/
public abstract function getLoginURL($destination = '');
/**
* Get the login destination string.
*
* When this is passed in the URL the user will be directed to it after filling in the CMS form.
*
* @param CRM_Core_Form $form
* Form object representing the 'current' form - to which the user will be returned.
*
* @return string|NULL
* destination value for URL
*/
public function getLoginDestination(&$form) {
return NULL;
}
/**
* Determine the native ID of the CMS user.
*
* @param string $username
*
* @throws CRM_Core_Exception
*/
public function getUfId($username) {
$className = get_class($this);
throw new CRM_Core_Exception("Not implemented: {$className}->getUfId");
}
/**
* Set the localisation from the user framework.
*
* @param string $civicrm_language
*
* @return bool
*/
public function setUFLocale($civicrm_language) {
return TRUE;
}
/**
* Set a init session with user object.
*
* @param array $data
* Array with user specific data
*/
public function setUserSession($data) {
list($userID, $ufID) = $data;
$session = CRM_Core_Session::singleton();
$session->set('ufID', $ufID);
$session->set('userID', $userID);
}
/**
* Reset any system caches that may be required for proper CiviCRM integration.
*/
public function flush() {
// nullop by default
}
/**
* Flush css/js caches.
*/
public function clearResourceCache() {
// nullop by default
}
/**
* Add a script file.
*
* Note: This function is not to be called directly
* @see CRM_Core_Region::render()
*
* @param string $url absolute path to file
* @param string $region
* location within the document: 'html-header', 'page-header', 'page-footer'.
*
* @return bool
* TRUE if we support this operation in this CMS, FALSE otherwise
*/
public function addScriptUrl($url, $region) {
return FALSE;
}
/**
* Add an inline script.
*
* Note: This function is not to be called directly
* @see CRM_Core_Region::render()
*
* @param string $code javascript code
* @param string $region
* location within the document: 'html-header', 'page-header', 'page-footer'.
*
* @return bool
* TRUE if we support this operation in this CMS, FALSE otherwise
*/
public function addScript($code, $region) {
return FALSE;
}
/**
* Add a css file.
*
* Note: This function is not to be called directly
* @see CRM_Core_Region::render()
*
* @param string $url absolute path to file
* @param string $region
* location within the document: 'html-header', 'page-header', 'page-footer'.
*
* @return bool
* TRUE if we support this operation in this CMS, FALSE otherwise
*/
public function addStyleUrl($url, $region) {
return FALSE;
}
/**
* Add an inline style.
*
* Note: This function is not to be called directly
* @see CRM_Core_Region::render()
*
* @param string $code css code
* @param string $region
* location within the document: 'html-header', 'page-header', 'page-footer'.
*
* @return bool
* TRUE if we support this operation in this CMS, FALSE otherwise
*/
public function addStyle($code, $region) {
return FALSE;
}
/**
* Sets the title of the page.
*
* @param string $title
* Title to set in html header
* @param string|null $pageTitle
* Title to set in html body (if different)
*/
public function setTitle($title, $pageTitle = NULL) {
}
/**
* Return default Site Settings.
*
* @param string $dir
*
* @return array
* - $url, (Joomla - non admin url)
* - $siteName,
* - $siteRoot
*/
public function getDefaultSiteSettings($dir) {
$config = CRM_Core_Config::singleton();
$url = $config->userFrameworkBaseURL;
return array($url, NULL, NULL);
}
/**
* Determine the default location for file storage.
*
* FIXME:
* 1. This was pulled out from a bigger function. It should be split
* into even smaller pieces and marked abstract.
* 2. This would be easier to compute by a calling a CMS API, but
* for whatever reason Civi gets it from config data.
*
* @return array
* - url: string. ex: "http://example.com/sites/foo.com/files/civicrm"
* - path: string. ex: "/var/www/sites/foo.com/files/civicrm"
*/
public function getDefaultFileStorage() {
global $civicrm_root;
$config = CRM_Core_Config::singleton();
$baseURL = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
$filesURL = NULL;
$filesPath = NULL;
if ($config->userFramework == 'Joomla') {
// gross hack
// we need to remove the administrator/ from the end
$tempURL = str_replace("/administrator/", "/", $baseURL);
$filesURL = $tempURL . "media/civicrm/";
}
elseif ($config->userFramework == 'UnitTests') {
$filesURL = $baseURL . "sites/default/files/civicrm/";
}
else {
throw new CRM_Core_Exception("Failed to locate default file storage ($config->userFramework)");
}
return array(
'url' => $filesURL,
'path' => CRM_Utils_File::baseFilePath(),
);
}
/**
* Determine the location of the CiviCRM source tree.
*
* FIXME:
* 1. This was pulled out from a bigger function. It should be split
* into even smaller pieces and marked abstract.
* 2. This would be easier to compute by a calling a CMS API, but
* for whatever reason we take the hard way.
*
* @return array
* - url: string. ex: "http://example.com/sites/all/modules/civicrm"
* - path: string. ex: "/var/www/sites/all/modules/civicrm"
*/
public function getCiviSourceStorage() {
global $civicrm_root;
$config = CRM_Core_Config::singleton();
// Don't use $config->userFrameworkBaseURL; it has garbage on it.
// More generally, w shouldn't be using $config here.
if (!defined('CIVICRM_UF_BASEURL')) {
throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
}
$baseURL = CRM_Utils_File::addTrailingSlash(CIVICRM_UF_BASEURL, '/');
if (CRM_Utils_System::isSSL()) {
$baseURL = str_replace('http://', 'https://', $baseURL);
}
if ($config->userFramework == 'Joomla') {
$userFrameworkResourceURL = $baseURL . "components/com_civicrm/civicrm/";
}
elseif ($config->userFramework == 'WordPress') {
$userFrameworkResourceURL = CIVICRM_PLUGIN_URL . "civicrm/";
}
elseif ($this->is_drupal) {
// Drupal setting
// check and see if we are installed in sites/all (for D5 and above)
// we dont use checkURL since drupal generates an error page and throws
// the system for a loop on lobo's macosx box
// or in modules
$cmsPath = $config->userSystem->cmsRootPath();
$userFrameworkResourceURL = $baseURL . str_replace("$cmsPath/", '',
str_replace('\\', '/', $civicrm_root)
);
$siteName = $config->userSystem->parseDrupalSiteNameFromRoot($civicrm_root);
if ($siteName) {
$civicrmDirName = trim(basename($civicrm_root));
$userFrameworkResourceURL = $baseURL . "sites/$siteName/modules/$civicrmDirName/";
}
}
else {
$userFrameworkResourceURL = NULL;
}
return array(
'url' => CRM_Utils_File::addTrailingSlash($userFrameworkResourceURL),
'path' => CRM_Utils_File::addTrailingSlash($civicrm_root),
);
}
/**
* Perform any post login activities required by the CMS.
*
* e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
* calls hook_user op 'login' and generates a new session.
*
* @param array $params
*
* FIXME: Document values accepted/required by $params
*/
public function userLoginFinalize($params = array()) {
}
/**
* Set timezone in mysql so that timestamp fields show the correct time.
*/
public function setMySQLTimeZone() {
$timeZoneOffset = $this->getTimeZoneOffset();
if ($timeZoneOffset) {
$sql = "SET time_zone = '$timeZoneOffset'";
CRM_Core_DAO::executequery($sql);
}
}
/**
* Get timezone from CMS.
*
* @return string|false|null
*/
public function getTimeZoneOffset() {
$timezone = $this->getTimeZoneString();
if ($timezone) {
if ($timezone == 'UTC' || $timezone == 'Etc/UTC') {
// CRM-17072 Let's short-circuit all the zero handling & return it here!
return '+00:00';
}
$tzObj = new DateTimeZone($timezone);
$dateTime = new DateTime("now", $tzObj);
$tz = $tzObj->getOffset($dateTime);
if (empty($tz)) {
return FALSE;
}
$timeZoneOffset = sprintf("%02d:%02d", $tz / 3600, abs(($tz / 60) % 60));
if ($timeZoneOffset > 0) {
$timeZoneOffset = '+' . $timeZoneOffset;
}
return $timeZoneOffset;
}
return NULL;
}
/**
* Get timezone as a string.
* @return string
* Timezone string e.g. 'America/Los_Angeles'
*/
public function getTimeZoneString() {
return date_default_timezone_get();
}
/**
* Get Unique Identifier from UserFramework system (CMS).
*
* @param object $user
* Object as described by the User Framework.
*
* @return mixed
* Unique identifier from the user Framework system
*/
public function getUniqueIdentifierFromUserObject($user) {
return NULL;
}
/**
* Get User ID from UserFramework system (CMS).
*
* @param object $user
*
* Object as described by the User Framework.
* @return null|int
*/
public function getUserIDFromUserObject($user) {
return NULL;
}
/**
* Get an array of user details for a contact, containing at minimum the user ID & name.
*
* @param int $contactID
*
* @return array
* CMS user details including
* - id
* - name (ie the system user name.
*/
public function getUser($contactID) {
$ufMatch = civicrm_api3('UFMatch', 'getsingle', array(
'contact_id' => $contactID,
'domain_id' => CRM_Core_Config::domainID(),
));
return array(
'id' => $ufMatch['uf_id'],
'name' => $ufMatch['uf_name'],
);
}
/**
* Get currently logged in user uf id.
*
* @return int|null
* logged in user uf id.
*/
public function getLoggedInUfID() {
return NULL;
}
/**
* Get currently logged in user unique identifier - this tends to be the email address or user name.
*
* @return string|null
* logged in user unique identifier
*/
public function getLoggedInUniqueIdentifier() {
return NULL;
}
/**
* Return a UFID (user account ID from the UserFramework / CMS system.
*
* ID is based on the user object passed, defaulting to the logged in user if not passed.
*
* Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would
* seem to be resolving the user id before calling the function.
*
* Note there is already a function getUFId which takes $username as a param - we could add $user
* as a second param to it but it seems messy - just overloading it because the name is taken.
*
* @param object $user
*
* @return int
* User ID of UF System
*/
public function getBestUFID($user = NULL) {
if ($user) {
return $this->getUserIDFromUserObject($user);
}
return $this->getLoggedInUfID();
}
/**
* Return a unique identifier (usually an email address or username) from the UserFramework / CMS system.
*
* This is based on the user object passed, defaulting to the logged in user if not passed.
*
* Note that ambiguous situation occurs in CRM_Core_BAO_UFMatch::synchronize - a cleaner approach would seem to be
* resolving the unique identifier before calling the function.
*
* @param object $user
*
* @return string
* unique identifier from the UF System
*/
public function getBestUFUniqueIdentifier($user = NULL) {
if ($user) {
return $this->getUniqueIdentifierFromUserObject($user);
}
return $this->getLoggedInUniqueIdentifier();
}
/**
* List modules installed in the CMS, including enabled and disabled ones.
*
* @return array
* [CRM_Core_Module]
*/
public function getModules() {
return array();
}
/**
* Get Url to view user record.
*
* @param int $contactID
* Contact ID.
*
* @return string|null
*/
public function getUserRecordUrl($contactID) {
return NULL;
}
/**
* Is the current user permitted to add a user.
*
* @return bool
*/
public function checkPermissionAddUser() {
return FALSE;
}
/**
* Output code from error function.
*
* @param string $content
*/
public function outputError($content) {
echo CRM_Utils_System::theme($content);
}
/**
* Log error to CMS.
*
* @param string $message
*/
public function logger($message) {
}
/**
* Append to coreResourcesList.
*
* @param array $list
*/
public function appendCoreResources(&$list) {
}
/**
* @param string $name
* @param string $value
*/
public function setHttpHeader($name, $value) {
header("$name: $value");
}
/**
* Create CRM contacts for all existing CMS users
*
* @return array
* @throws \Exception
*/
public function synchronizeUsers() {
throw new Exception('CMS user creation not supported for this framework');
return array();
}
}

View file

@ -0,0 +1,851 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Drupal specific stuff goes here
*/
class CRM_Utils_System_Drupal extends CRM_Utils_System_DrupalBase {
/**
* @inheritDoc
*/
public function createUser(&$params, $mail) {
$form_state = form_state_defaults();
$form_state['input'] = array(
'name' => $params['cms_name'],
'mail' => $params[$mail],
'op' => 'Create new account',
);
$admin = user_access('administer users');
if (!variable_get('user_email_verification', TRUE) || $admin) {
$form_state['input']['pass'] = array('pass1' => $params['cms_pass'], 'pass2' => $params['cms_pass']);
}
if (!empty($params['notify'])) {
$form_state['input']['notify'] = $params['notify'];
}
$form_state['rebuild'] = FALSE;
$form_state['programmed'] = TRUE;
$form_state['complete form'] = FALSE;
$form_state['method'] = 'post';
$form_state['build_info']['args'] = array();
/*
* if we want to submit this form more than once in a process (e.g. create more than one user)
* we must force it to validate each time for this form. Otherwise it will not validate
* subsequent submissions and the manner in which the password is passed in will be invalid
*/
$form_state['must_validate'] = TRUE;
$config = CRM_Core_Config::singleton();
// we also need to redirect b
$config->inCiviCRM = TRUE;
$form = drupal_retrieve_form('user_register_form', $form_state);
$form_state['process_input'] = 1;
$form_state['submitted'] = 1;
$form['#array_parents'] = array();
$form['#tree'] = FALSE;
drupal_process_form('user_register_form', $form, $form_state);
$config->inCiviCRM = FALSE;
if (form_get_errors()) {
return FALSE;
}
return $form_state['user']->uid;
}
/**
* @inheritDoc
*/
public function updateCMSName($ufID, $ufName) {
// CRM-5555
if (function_exists('user_load')) {
$user = user_load($ufID);
if ($user->mail != $ufName) {
user_save($user, array('mail' => $ufName));
$user = user_load($ufID);
}
}
}
/**
* Check if username and email exists in the drupal db.
*
* @param array $params
* Array of name and mail values.
* @param array $errors
* Array of errors.
* @param string $emailName
* Field label for the 'email'.
*/
public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
$config = CRM_Core_Config::singleton();
$dao = new CRM_Core_DAO();
$name = $dao->escape(CRM_Utils_Array::value('name', $params));
$email = $dao->escape(CRM_Utils_Array::value('mail', $params));
$errors = form_get_errors();
if ($errors) {
// unset drupal messages to avoid twice display of errors
unset($_SESSION['messages']);
}
if (!empty($params['name'])) {
if ($nameError = user_validate_name($params['name'])) {
$errors['cms_name'] = $nameError;
}
else {
$uid = db_query(
"SELECT uid FROM {users} WHERE name = :name",
array(':name' => $params['name'])
)->fetchField();
if ((bool) $uid) {
$errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
}
}
}
if (!empty($params['mail'])) {
if ($emailError = user_validate_mail($params['mail'])) {
$errors[$emailName] = $emailError;
}
else {
$uid = db_query(
"SELECT uid FROM {users} WHERE mail = :mail",
array(':mail' => $params['mail'])
)->fetchField();
if ((bool) $uid) {
$resetUrl = url('user/password');
$errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
array(1 => $params['mail'], 2 => $resetUrl)
);
}
}
}
}
/**
* @inheritDoc
*/
public function getLoginURL($destination = '') {
$query = $destination ? array('destination' => $destination) : NULL;
return CRM_Utils_System::url('user', $query, TRUE);
}
/**
* @inheritDoc
*/
public function setTitle($title, $pageTitle = NULL) {
if (arg(0) == 'civicrm') {
if (!$pageTitle) {
$pageTitle = $title;
}
drupal_set_title($pageTitle, PASS_THROUGH);
}
}
/**
* @inheritDoc
*/
public function appendBreadCrumb($breadCrumbs) {
$breadCrumb = drupal_get_breadcrumb();
if (is_array($breadCrumbs)) {
foreach ($breadCrumbs as $crumbs) {
if (stripos($crumbs['url'], 'id%%')) {
$args = array('cid', 'mid');
foreach ($args as $a) {
$val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
FALSE, NULL, $_GET
);
if ($val) {
$crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
}
}
}
$breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
}
}
drupal_set_breadcrumb($breadCrumb);
}
/**
* @inheritDoc
*/
public function resetBreadCrumb() {
$bc = array();
drupal_set_breadcrumb($bc);
}
/**
* @inheritDoc
*/
public function addHTMLHead($header) {
static $count = 0;
if (!empty($header)) {
$key = 'civi_' . ++$count;
$data = array(
'#type' => 'markup',
'#markup' => $header,
);
drupal_add_html_head($data, $key);
}
}
/**
* @inheritDoc
*/
public function addScriptUrl($url, $region) {
$params = array('group' => JS_LIBRARY, 'weight' => 10);
switch ($region) {
case 'html-header':
case 'page-footer':
$params['scope'] = substr($region, 5);
break;
default:
return FALSE;
}
// If the path is within the drupal directory we can use the more efficient 'file' setting
$params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
drupal_add_js($url, $params);
return TRUE;
}
/**
* @inheritDoc
*/
public function addScript($code, $region) {
$params = array('type' => 'inline', 'group' => JS_LIBRARY, 'weight' => 10);
switch ($region) {
case 'html-header':
case 'page-footer':
$params['scope'] = substr($region, 5);
break;
default:
return FALSE;
}
drupal_add_js($code, $params);
return TRUE;
}
/**
* @inheritDoc
*/
public function addStyleUrl($url, $region) {
if ($region != 'html-header') {
return FALSE;
}
$params = array();
// If the path is within the drupal directory we can use the more efficient 'file' setting
$params['type'] = $this->formatResourceUrl($url) ? 'file' : 'external';
drupal_add_css($url, $params);
return TRUE;
}
/**
* @inheritDoc
*/
public function addStyle($code, $region) {
if ($region != 'html-header') {
return FALSE;
}
$params = array('type' => 'inline');
drupal_add_css($code, $params);
return TRUE;
}
/**
* @inheritDoc
*/
public function mapConfigToSSL() {
global $base_url;
$base_url = str_replace('http://', 'https://', $base_url);
}
/**
* Get the name of the users table.
*
* @return string
*/
protected function getUsersTableName() {
$userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
if (empty($userFrameworkUsersTableName)) {
$userFrameworkUsersTableName = 'users';
}
return $userFrameworkUsersTableName;
}
/**
* @inheritDoc
*/
public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
require_once 'DB.php';
$config = CRM_Core_Config::singleton();
$dbDrupal = DB::connect($config->userFrameworkDSN);
if (DB::isError($dbDrupal)) {
CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
}
$account = $userUid = $userMail = NULL;
if ($loadCMSBootstrap) {
$bootStrapParams = array();
if ($name && $password) {
$bootStrapParams = array(
'name' => $name,
'pass' => $password,
);
}
CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
global $user;
if ($user) {
$userUid = $user->uid;
$userMail = $user->mail;
}
}
else {
// CRM-8638
// SOAP cannot load drupal bootstrap and hence we do it the old way
// Contact CiviSMTP folks if we run into issues with this :)
$cmsPath = $config->userSystem->cmsRootPath($realPath);
require_once "$cmsPath/includes/bootstrap.inc";
require_once "$cmsPath/includes/password.inc";
$strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
$name = $dbDrupal->escapeSimple($strtolower($name));
$userFrameworkUsersTableName = $this->getUsersTableName();
// LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
$sql = "
SELECT u.*
FROM {$userFrameworkUsersTableName} u
WHERE LOWER(u.name) = '$name'
AND u.status = 1
";
$query = $dbDrupal->query($sql);
$row = $query->fetchRow(DB_FETCHMODE_ASSOC);
if ($row) {
$fakeDrupalAccount = drupal_anonymous_user();
$fakeDrupalAccount->name = $name;
$fakeDrupalAccount->pass = $row['pass'];
$passwordCheck = user_check_password($password, $fakeDrupalAccount);
if ($passwordCheck) {
$userUid = $row['uid'];
$userMail = $row['mail'];
}
}
}
if ($userUid && $userMail) {
CRM_Core_BAO_UFMatch::synchronizeUFMatch($account, $userUid, $userMail, 'Drupal');
$contactID = CRM_Core_BAO_UFMatch::getContactId($userUid);
if (!$contactID) {
return FALSE;
}
return array($contactID, $userUid, mt_rand());
}
return FALSE;
}
/**
* @inheritDoc
*/
public function loadUser($username) {
global $user;
$user = user_load_by_name($username);
if (empty($user->uid)) {
return FALSE;
}
$uid = $user->uid;
$contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
// lets store contact id and user id in session
$session = CRM_Core_Session::singleton();
$session->set('ufID', $uid);
$session->set('userID', $contact_id);
return TRUE;
}
/**
* Perform any post login activities required by the UF -
* e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
* calls hook_user op 'login' and generates a new session.
*
* @param array $params
*
* FIXME: Document values accepted/required by $params
*/
public function userLoginFinalize($params = array()) {
user_login_finalize($params);
}
/**
* Determine the native ID of the CMS user.
*
* @param string $username
* @return int|NULL
*/
public function getUfId($username) {
$user = user_load_by_name($username);
if (empty($user->uid)) {
return NULL;
}
return $user->uid;
}
/**
* @inheritDoc
*/
public function logout() {
module_load_include('inc', 'user', 'user.pages');
return user_logout();
}
/**
* Get the default location for CiviCRM blocks.
*
* @return string
*/
public function getDefaultBlockLocation() {
return 'sidebar_first';
}
/**
* Load drupal bootstrap.
*
* @param array $params
* Either uid, or name & pass.
* @param bool $loadUser
* Boolean Require CMS user load.
* @param bool $throwError
* If true, print error on failure and exit.
* @param bool|string $realPath path to script
*
* @return bool
*/
public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
//take the cms root path.
$cmsPath = $this->cmsRootPath($realPath);
if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
if ($throwError) {
throw new Exception('Sorry, could not locate bootstrap.inc');
}
return FALSE;
}
// load drupal bootstrap
chdir($cmsPath);
define('DRUPAL_ROOT', $cmsPath);
// For drupal multi-site CRM-11313
if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
if (!empty($matches[1])) {
$_SERVER['HTTP_HOST'] = $matches[1];
}
}
require_once 'includes/bootstrap.inc';
// @ to suppress notices eg 'DRUPALFOO already defined'.
@drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// explicitly setting error reporting, since we cannot handle drupal related notices
// @todo 1 = E_ERROR, but more to the point setting error reporting deep in code
// causes grief with debugging scripts
error_reporting(1);
if (!function_exists('module_exists')) {
if ($throwError) {
throw new Exception('Sorry, could not load drupal bootstrap.');
}
return FALSE;
}
if (!module_exists('civicrm')) {
if ($throwError) {
throw new Exception('Sorry, drupal cannot find CiviCRM');
}
return FALSE;
}
// seems like we've bootstrapped drupal
$config = CRM_Core_Config::singleton();
// lets also fix the clean url setting
// CRM-6948
$config->cleanURL = (int) variable_get('clean_url', '0');
// we need to call the config hook again, since we now know
// all the modules that are listening on it, does not apply
// to J! and WP as yet
// CRM-8655
CRM_Utils_Hook::config($config);
if (!$loadUser) {
return TRUE;
}
$uid = CRM_Utils_Array::value('uid', $params);
if (!$uid) {
//load user, we need to check drupal permissions.
$name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
$pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
if ($name) {
$uid = user_authenticate($name, $pass);
if (!$uid) {
if ($throwError) {
throw new Exception('Sorry, unrecognized username or password.');
}
return FALSE;
}
}
}
if ($uid) {
$account = user_load($uid);
if ($account && $account->uid) {
global $user;
$user = $account;
return TRUE;
}
}
if ($throwError) {
throw new Exception('Sorry, can not load CMS user account.');
}
// CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
// which means that define(CIVICRM_CLEANURL) was correctly set.
// So we correct it
$config = CRM_Core_Config::singleton();
$config->cleanURL = (int) variable_get('clean_url', '0');
// CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
CRM_Utils_Hook::config($config);
return FALSE;
}
/**
* Get CMS root path.
*
* @param string $scriptFilename
*
* @return null|string
*/
public function cmsRootPath($scriptFilename = NULL) {
$cmsRoot = $valid = NULL;
if (!is_null($scriptFilename)) {
$path = $scriptFilename;
}
else {
$path = $_SERVER['SCRIPT_FILENAME'];
}
if (function_exists('drush_get_context')) {
// drush anyway takes care of multisite install etc
return drush_get_context('DRUSH_DRUPAL_ROOT');
}
global $civicrm_paths;
if (!empty($civicrm_paths['cms.root']['path'])) {
return $civicrm_paths['cms.root']['path'];
}
// CRM-7582
$pathVars = explode('/',
str_replace('//', '/',
str_replace('\\', '/', $path)
)
);
//lets store first var,
//need to get back for windows.
$firstVar = array_shift($pathVars);
//lets remove sript name to reduce one iteration.
array_pop($pathVars);
// CRM-7429 -- do check for uppermost 'includes' dir, which would
// work for multisite installation.
do {
$cmsRoot = $firstVar . '/' . implode('/', $pathVars);
$cmsIncludePath = "$cmsRoot/includes";
// Stop if we find bootstrap.
if (file_exists("$cmsIncludePath/bootstrap.inc")) {
$valid = TRUE;
break;
}
//remove one directory level.
array_pop($pathVars);
} while (count($pathVars));
return ($valid) ? $cmsRoot : NULL;
}
/**
* @inheritDoc
*/
public function isUserLoggedIn() {
$isloggedIn = FALSE;
if (function_exists('user_is_logged_in')) {
$isloggedIn = user_is_logged_in();
}
return $isloggedIn;
}
/**
* @inheritDoc
*/
public function getLoggedInUfID() {
$ufID = NULL;
if (function_exists('user_is_logged_in') &&
user_is_logged_in() &&
function_exists('user_uid_optional_to_arg')
) {
$ufID = user_uid_optional_to_arg(array());
}
return $ufID;
}
/**
* @inheritDoc
*/
public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
if (empty($url)) {
return $url;
}
//CRM-7803 -from d7 onward.
$config = CRM_Core_Config::singleton();
if (function_exists('variable_get') &&
module_exists('locale') &&
function_exists('language_negotiation_get')
) {
global $language;
//does user configuration allow language
//support from the URL (Path prefix or domain)
if (language_negotiation_get('language') == 'locale-url') {
$urlType = variable_get('locale_language_negotiation_url_part');
//url prefix
if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
if (isset($language->prefix) && $language->prefix) {
if ($addLanguagePart) {
$url .= $language->prefix . '/';
}
if ($removeLanguagePart) {
$url = str_replace("/{$language->prefix}/", '/', $url);
}
}
}
//domain
if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
if (isset($language->domain) && $language->domain) {
if ($addLanguagePart) {
$cleanedUrl = preg_replace('#^https?://#', '', $language->domain);
// drupal function base_path() adds a "/" to the beginning and end of the returned path
if (substr($cleanedUrl, -1) == '/') {
$cleanedUrl = substr($cleanedUrl, 0, -1);
}
$url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $cleanedUrl . base_path();
}
if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
$url = str_replace('\\', '/', $url);
$parseUrl = parse_url($url);
//kinda hackish but not sure how to do it right
//hope http_build_url() will help at some point.
if (is_array($parseUrl) && !empty($parseUrl)) {
$urlParts = explode('/', $url);
$hostKey = array_search($parseUrl['host'], $urlParts);
$ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
$urlParts[$hostKey] = $ufUrlParts['host'];
$url = implode('/', $urlParts);
}
}
}
}
}
}
return $url;
}
/**
* Find any users/roles/security-principals with the given permission
* and replace it with one or more permissions.
*
* @param string $oldPerm
* @param array $newPerms
* Array, strings.
*/
public function replacePermission($oldPerm, $newPerms) {
$roles = user_roles(FALSE, $oldPerm);
if (!empty($roles)) {
foreach (array_keys($roles) as $rid) {
user_role_revoke_permissions($rid, array($oldPerm));
user_role_grant_permissions($rid, $newPerms);
}
}
}
/**
* Wrapper for og_membership creation.
*
* @param int $ogID
* Organic Group ID.
* @param int $drupalID
* Drupal User ID.
*/
public function og_membership_create($ogID, $drupalID) {
if (function_exists('og_entity_query_alter')) {
// sort-of-randomly chose a function that only exists in the // 7.x-2.x branch
//
// @TODO Find more solid way to check - try system_get_info('module', 'og').
//
// Also, since we don't know how to get the entity type of the // group, we'll assume it's 'node'
og_group('node', $ogID, array('entity' => user_load($drupalID)));
}
else {
// Works for the OG 7.x-1.x branch
og_group($ogID, array('entity' => user_load($drupalID)));
}
}
/**
* Wrapper for og_membership deletion.
*
* @param int $ogID
* Organic Group ID.
* @param int $drupalID
* Drupal User ID.
*/
public function og_membership_delete($ogID, $drupalID) {
if (function_exists('og_entity_query_alter')) {
// sort-of-randomly chose a function that only exists in the 7.x-2.x branch
// TODO: Find a more solid way to make this test
// Also, since we don't know how to get the entity type of the group, we'll assume it's 'node'
og_ungroup('node', $ogID, 'user', user_load($drupalID));
}
else {
// Works for the OG 7.x-1.x branch
og_ungroup($ogID, 'user', user_load($drupalID));
}
}
/**
* @inheritDoc
*/
public function getTimeZoneString() {
global $user;
// Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
$timezone = $user->timezone;
}
else {
$timezone = variable_get('date_default_timezone', NULL);
}
if (!$timezone) {
$timezone = parent::getTimeZoneString();
}
return $timezone;
}
/**
* @inheritDoc
*/
public function setHttpHeader($name, $value) {
drupal_add_http_header($name, $value);
}
/**
* @inheritDoc
*/
public function synchronizeUsers() {
$config = CRM_Core_Config::singleton();
if (PHP_SAPI != 'cli') {
set_time_limit(300);
}
$id = 'uid';
$mail = 'mail';
$name = 'name';
$result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
$user = new StdClass();
$uf = $config->userFramework;
$contactCount = 0;
$contactCreated = 0;
$contactMatching = 0;
foreach ($result as $row) {
$user->$id = $row->$id;
$user->$mail = $row->$mail;
$user->$name = $row->$name;
$contactCount++;
if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row->$id, $row->$mail, $uf, 1, 'Individual', TRUE)) {
$contactCreated++;
}
else {
$contactMatching++;
}
if (is_object($match)) {
$match->free();
}
}
return array(
'contactCount' => $contactCount,
'contactMatching' => $contactMatching,
'contactCreated' => $contactCreated,
);
}
}

View file

@ -0,0 +1,821 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Drupal specific stuff goes here.
*/
class CRM_Utils_System_Drupal6 extends CRM_Utils_System_DrupalBase {
/**
* Theme output.
*
* If we are using a theming system, invoke theme, else just print the content.
*
* @param string $content
* The content that will be themed.
* @param bool $print
* Are we displaying to the screen or bypassing theming?.
* @param bool $maintenance
* For maintenance mode.
*
* @return null|string
* prints content on stdout
*/
public function theme(&$content, $print = FALSE, $maintenance = FALSE) {
// TODO: Simplify; this was copied verbatim from CiviCRM 3.4's multi-UF theming function, but that's more complex than necessary
if (function_exists('theme') && !$print) {
if ($maintenance) {
drupal_set_breadcrumb('');
drupal_maintenance_theme();
}
// Arg 3 for D6 theme() is "show_blocks". Previously, we passed
// through a badly named variable ("$args") which was almost always
// TRUE (except on fatal error screen). However, this feature is
// non-functional on D6 default themes, was purposefully removed from
// D7, has no analog in other our other CMS's, and clutters the code.
// Hard-wiring to TRUE should be OK.
$out = theme('page', $content, TRUE);
}
else {
$out = $content;
}
print $out;
return NULL;
}
/**
* Create user.
*
* @inheritDoc
*/
public function createUser(&$params, $mail) {
$form_state = array();
$form_state['values'] = array(
'name' => $params['cms_name'],
'mail' => $params[$mail],
'op' => 'Create new account',
);
$admin = user_access('administer users');
if (!variable_get('user_email_verification', TRUE) || $admin) {
$form_state['values']['pass']['pass1'] = $params['cms_pass'];
$form_state['values']['pass']['pass2'] = $params['cms_pass'];
}
$config = CRM_Core_Config::singleton();
// we also need to redirect b
$config->inCiviCRM = TRUE;
$form = drupal_retrieve_form('user_register', $form_state);
$form['#post'] = $form_state['values'];
drupal_prepare_form('user_register', $form, $form_state);
// remove the captcha element from the form prior to processing
unset($form['captcha']);
drupal_process_form('user_register', $form, $form_state);
$config->inCiviCRM = FALSE;
if (form_get_errors() || !isset($form_state['user'])) {
return FALSE;
}
return $form_state['user']->uid;
}
/**
* @inheritDoc
*/
public function updateCMSName($ufID, $ufName) {
// CRM-5555
if (function_exists('user_load')) {
$user = user_load(array('uid' => $ufID));
if ($user->mail != $ufName) {
user_save($user, array('mail' => $ufName));
$user = user_load(array('uid' => $ufID));
}
}
}
/**
* Check if username and email exists in the drupal db.
*
* @param array $params
* Array of name and mail values.
* @param array $errors
* Array of errors.
* @param string $emailName
* Field label for the 'email'.
*/
public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
$config = CRM_Core_Config::singleton();
$dao = new CRM_Core_DAO();
$name = $dao->escape(CRM_Utils_Array::value('name', $params));
$email = $dao->escape(CRM_Utils_Array::value('mail', $params));
_user_edit_validate(NULL, $params);
$errors = form_get_errors();
if ($errors) {
if (!empty($errors['name'])) {
$errors['cms_name'] = $errors['name'];
}
if (!empty($errors['mail'])) {
$errors[$emailName] = $errors['mail'];
}
// also unset drupal messages to avoid twice display of errors
unset($_SESSION['messages']);
}
// Do the name check manually.
$nameError = user_validate_name($params['name']);
if ($nameError) {
$errors['cms_name'] = $nameError;
}
// LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
$sql = "
SELECT name, mail
FROM {users}
WHERE (LOWER(name) = LOWER('$name')) OR (LOWER(mail) = LOWER('$email'))
";
$result = db_query($sql);
$row = db_fetch_array($result);
if (!$row) {
return;
}
$user = NULL;
if (!empty($row)) {
$dbName = CRM_Utils_Array::value('name', $row);
$dbEmail = CRM_Utils_Array::value('mail', $row);
if (strtolower($dbName) == strtolower($name)) {
$errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
array(1 => $name)
);
}
if (strtolower($dbEmail) == strtolower($email)) {
if (empty($email)) {
$errors[$emailName] = ts('You cannot create an email account for a contact with no email',
array(1 => $email)
);
}
else {
$errors[$emailName] = ts('This email %1 already has an account associated with it. Please select another email.',
array(1 => $email)
);
}
}
}
}
/**
* @inheritDoc
*/
public function setTitle($title, $pageTitle = NULL) {
if (!$pageTitle) {
$pageTitle = $title;
}
if (arg(0) == 'civicrm') {
//set drupal title
drupal_set_title($pageTitle);
}
}
/**
* @inheritDoc
*/
public function appendBreadCrumb($breadCrumbs) {
$breadCrumb = drupal_get_breadcrumb();
if (is_array($breadCrumbs)) {
foreach ($breadCrumbs as $crumbs) {
if (stripos($crumbs['url'], 'id%%')) {
$args = array('cid', 'mid');
foreach ($args as $a) {
$val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
FALSE, NULL, $_GET
);
if ($val) {
$crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
}
}
}
$breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
}
}
drupal_set_breadcrumb($breadCrumb);
}
/**
* @inheritDoc
*/
public function resetBreadCrumb() {
$bc = array();
drupal_set_breadcrumb($bc);
}
/**
* Append a string to the head of the html file.
*
* @param string $head
* The new string to be appended.
*/
public function addHTMLHead($head) {
drupal_set_html_head($head);
}
/**
* Add a css file.
*
* @param $url : string, absolute path to file
* @param string $region
* location within the document: 'html-header', 'page-header', 'page-footer'.
*
* Note: This function is not to be called directly
* @see CRM_Core_Region::render()
*
* @return bool
* TRUE if we support this operation in this CMS, FALSE otherwise
*/
public function addStyleUrl($url, $region) {
if ($region != 'html-header' || !$this->formatResourceUrl($url)) {
return FALSE;
}
drupal_add_css($url);
return TRUE;
}
/**
* @inheritDoc
*/
public function mapConfigToSSL() {
global $base_url;
$base_url = str_replace('http://', 'https://', $base_url);
}
/**
* Get the name of the table that stores the user details.
*
* @return string
*/
protected function getUsersTableName() {
$userFrameworkUsersTableName = Civi::settings()->get('userFrameworkUsersTableName');
if (empty($userFrameworkUsersTableName)) {
$userFrameworkUsersTableName = 'users';
}
return $userFrameworkUsersTableName;
}
/**
* @inheritDoc
*/
public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
//@todo this 'PEAR-y' stuff is only required when bookstrap is not being loaded which is rare
// if ever now.
// probably if bootstrap is loaded this call
// CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath); would be
// sufficient to do what this fn does. It does exist as opposed to return which might need some hanky-panky to make
// safe in the unknown situation where authenticate might be called & it is important that
// false is returned
require_once 'DB.php';
$config = CRM_Core_Config::singleton();
$dbDrupal = DB::connect($config->userFrameworkDSN);
if (DB::isError($dbDrupal)) {
CRM_Core_Error::fatal("Cannot connect to drupal db via $config->userFrameworkDSN, " . $dbDrupal->getMessage());
}
$strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
$dbpassword = md5($password);
$name = $dbDrupal->escapeSimple($strtolower($name));
$userFrameworkUsersTableName = $this->getUsersTableName();
$sql = 'SELECT u.* FROM ' . $userFrameworkUsersTableName . " u WHERE LOWER(u.name) = '$name' AND u.pass = '$dbpassword' AND u.status = 1";
$query = $dbDrupal->query($sql);
$user = NULL;
// need to change this to make sure we matched only one row
while ($row = $query->fetchRow(DB_FETCHMODE_ASSOC)) {
CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row['uid'], $row['mail'], 'Drupal');
$contactID = CRM_Core_BAO_UFMatch::getContactId($row['uid']);
if (!$contactID) {
return FALSE;
}
else {
//success
if ($loadCMSBootstrap) {
$bootStrapParams = array();
if ($name && $password) {
$bootStrapParams = array(
'name' => $name,
'pass' => $password,
);
}
CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, $realPath);
}
return array($contactID, $row['uid'], mt_rand());
}
}
return FALSE;
}
/**
* @inheritDoc
*/
public function loadUser($username) {
global $user;
$user = user_load(array('name' => $username));
if (empty($user->uid)) {
return FALSE;
}
$uid = $user->uid;
$contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
// lets store contact id and user id in session
$session = CRM_Core_Session::singleton();
$session->set('ufID', $uid);
$session->set('userID', $contact_id);
return TRUE;
}
/**
* Perform any post login activities required by the UF -
* e.g. for drupal : records a watchdog message about the new session,
* saves the login timestamp, calls hook_user op 'login' and generates a new session.
*
* @param array $params
*
* FIXME: Document values accepted/required by $params
*/
public function userLoginFinalize($params = array()) {
user_authenticate_finalize($params);
}
/**
* Determine the native ID of the CMS user.
*
* @param string $username
* @return int|NULL
*/
public function getUfId($username) {
$user = user_load(array('name' => $username));
if (empty($user->uid)) {
return NULL;
}
return $user->uid;
}
/**
* @inheritDoc
*/
public function logout() {
module_load_include('inc', 'user', 'user.pages');
return user_logout();
}
/**
* Load drupal bootstrap.
*
* @param array $params
* Either uid, or name & pass.
* @param bool $loadUser
* Boolean Require CMS user load.
* @param bool $throwError
* If true, print error on failure and exit.
* @param bool|string $realPath path to script
*
* @return bool
*/
public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
//take the cms root path.
$cmsPath = $this->cmsRootPath($realPath);
if (!file_exists("$cmsPath/includes/bootstrap.inc")) {
if ($throwError) {
echo '<br />Sorry, could not locate bootstrap.inc\n';
exit();
}
return FALSE;
}
// load drupal bootstrap
chdir($cmsPath);
define('DRUPAL_ROOT', $cmsPath);
// For drupal multi-site CRM-11313
if ($realPath && strpos($realPath, 'sites/all/modules/') === FALSE) {
preg_match('@sites/([^/]*)/modules@s', $realPath, $matches);
if (!empty($matches[1])) {
$_SERVER['HTTP_HOST'] = $matches[1];
}
}
require_once 'includes/bootstrap.inc';
// @ to suppress notices eg 'DRUPALFOO already defined'.
@drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// explicitly setting error reporting, since we cannot handle drupal related notices
error_reporting(1);
if (!function_exists('module_exists') || !module_exists('civicrm')) {
if ($throwError) {
echo '<br />Sorry, could not load drupal bootstrap.';
exit();
}
return FALSE;
}
// seems like we've bootstrapped drupal
$config = CRM_Core_Config::singleton();
// lets also fix the clean url setting
// CRM-6948
$config->cleanURL = (int) variable_get('clean_url', '0');
// we need to call the config hook again, since we now know
// all the modules that are listening on it, does not apply
// to J! and WP as yet
// CRM-8655
CRM_Utils_Hook::config($config);
if (!$loadUser) {
return TRUE;
}
global $user;
// If $uid is passed in, authentication has been done already.
$uid = CRM_Utils_Array::value('uid', $params);
if (!$uid) {
//load user, we need to check drupal permissions.
$name = CRM_Utils_Array::value('name', $params, FALSE) ? $params['name'] : trim(CRM_Utils_Array::value('name', $_REQUEST));
$pass = CRM_Utils_Array::value('pass', $params, FALSE) ? $params['pass'] : trim(CRM_Utils_Array::value('pass', $_REQUEST));
if ($name) {
$user = user_authenticate(array('name' => $name, 'pass' => $pass));
if (!$user->uid) {
if ($throwError) {
echo '<br />Sorry, unrecognized username or password.';
exit();
}
return FALSE;
}
else {
return TRUE;
}
}
}
if ($uid) {
$account = user_load($uid);
if ($account && $account->uid) {
$user = $account;
return TRUE;
}
}
if ($throwError) {
echo '<br />Sorry, can not load CMS user account.';
exit();
}
// CRM-6948: When using loadBootStrap, it's implicit that CiviCRM has already loaded its settings
// which means that define(CIVICRM_CLEANURL) was correctly set.
// So we correct it
$config = CRM_Core_Config::singleton();
$config->cleanURL = (int) variable_get('clean_url', '0');
// CRM-8655: Drupal wasn't available during bootstrap, so hook_civicrm_config never executes
CRM_Utils_Hook::config($config);
return FALSE;
}
/**
* Get CMS root path.
*
* @param string $scriptFilename
*
* @return null|string
*/
public function cmsRootPath($scriptFilename = NULL) {
$cmsRoot = $valid = NULL;
if (!is_null($scriptFilename)) {
$path = $scriptFilename;
}
else {
$path = $_SERVER['SCRIPT_FILENAME'];
}
if (function_exists('drush_get_context')) {
// drush anyway takes care of multisite install etc
return drush_get_context('DRUSH_DRUPAL_ROOT');
}
global $civicrm_paths;
if (!empty($civicrm_paths['cms.root']['path'])) {
return $civicrm_paths['cms.root']['path'];
}
// CRM-7582
$pathVars = explode('/',
str_replace('//', '/',
str_replace('\\', '/', $path)
)
);
//lets store first var,
//need to get back for windows.
$firstVar = array_shift($pathVars);
//lets remove sript name to reduce one iteration.
array_pop($pathVars);
//CRM-7429 --do check for upper most 'includes' dir,
//which would effectually work for multisite installation.
do {
$cmsRoot = $firstVar . '/' . implode('/', $pathVars);
$cmsIncludePath = "$cmsRoot/includes";
// Stop if we found bootstrap.
if (file_exists("$cmsIncludePath/bootstrap.inc")) {
$valid = TRUE;
break;
}
//remove one directory level.
array_pop($pathVars);
} while (count($pathVars));
return ($valid) ? $cmsRoot : NULL;
}
/**
* @inheritDoc
*/
public function isUserLoggedIn() {
$isloggedIn = FALSE;
if (function_exists('user_is_logged_in')) {
$isloggedIn = user_is_logged_in();
}
return $isloggedIn;
}
/**
* @inheritDoc
*/
public function getLoggedInUfID() {
$ufID = NULL;
if (function_exists('user_is_logged_in') &&
user_is_logged_in() &&
function_exists('user_uid_optional_to_arg')
) {
$ufID = user_uid_optional_to_arg(array());
}
return $ufID;
}
/**
* @inheritDoc
*/
public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
if (empty($url)) {
return $url;
}
//up to d6 only, already we have code in place for d7
$config = CRM_Core_Config::singleton();
if (function_exists('variable_get') &&
module_exists('locale')
) {
global $language;
//get the mode.
$mode = variable_get('language_negotiation', LANGUAGE_NEGOTIATION_NONE);
//url prefix / path.
if (isset($language->prefix) &&
$language->prefix &&
in_array($mode, array(
LANGUAGE_NEGOTIATION_PATH,
LANGUAGE_NEGOTIATION_PATH_DEFAULT,
))
) {
if ($addLanguagePart) {
$url .= $language->prefix . '/';
}
if ($removeLanguagePart) {
$url = str_replace("/{$language->prefix}/", '/', $url);
}
}
if (isset($language->domain) &&
$language->domain &&
$mode == LANGUAGE_NEGOTIATION_DOMAIN
) {
if ($addLanguagePart) {
$url = CRM_Utils_File::addTrailingSlash($language->domain, '/');
}
if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
$url = str_replace('\\', '/', $url);
$parseUrl = parse_url($url);
//kinda hackish but not sure how to do it right
//hope http_build_url() will help at some point.
if (is_array($parseUrl) && !empty($parseUrl)) {
$urlParts = explode('/', $url);
$hostKey = array_search($parseUrl['host'], $urlParts);
$ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
$urlParts[$hostKey] = $ufUrlParts['host'];
$url = implode('/', $urlParts);
}
}
}
}
return $url;
}
/**
* Find any users/roles/security-principals with the given permission
* and replace it with one or more permissions.
*
* @param string $oldPerm
* @param array $newPerms
* Array, strings.
*/
public function replacePermission($oldPerm, $newPerms) {
$roles = user_roles(FALSE, $oldPerm);
foreach ($roles as $rid => $roleName) {
$permList = db_result(db_query('SELECT perm FROM {permission} WHERE rid = %d', $rid));
$perms = drupal_map_assoc(explode(', ', $permList));
unset($perms[$oldPerm]);
$perms = $perms + drupal_map_assoc($newPerms);
$permList = implode(', ', $perms);
db_query('UPDATE {permission} SET perm = "%s" WHERE rid = %d', $permList, $rid);
/* @codingStandardsIgnoreStart
if ( ! empty( $roles ) ) {
$rids = implode(',', array_keys($roles));
db_query( 'UPDATE {permission} SET perm = CONCAT( perm, \', edit all events\') WHERE rid IN (' . implode(',', array_keys($roles)) . ')' );
db_query( "UPDATE {permission} SET perm = REPLACE( perm, '%s', '%s' ) WHERE rid IN ($rids)",
$oldPerm, implode(', ', $newPerms) );
@codingStandardsIgnoreEnd */
}
}
/**
* @inheritDoc
*/
public function getModules() {
$result = array();
$q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
while ($row = db_fetch_object($q)) {
$result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
}
return $result;
}
/**
* @inheritDoc
*/
public function getLoginURL($destination = '') {
$config = CRM_Core_Config::singleton();
$loginURL = $config->userFrameworkBaseURL;
$loginURL .= 'user';
if (!empty($destination)) {
// append destination so user is returned to form they came from after login
$loginURL .= '?destination=' . urlencode($destination);
}
return $loginURL;
}
/**
* Wrapper for og_membership creation.
*
* @param int $ogID
* Organic Group ID.
* @param int $drupalID
* Drupal User ID.
*/
public function og_membership_create($ogID, $drupalID) {
og_save_subscription($ogID, $drupalID, array('is_active' => 1));
}
/**
* Wrapper for og_membership deletion.
*
* @param int $ogID
* Organic Group ID.
* @param int $drupalID
* Drupal User ID.
*/
public function og_membership_delete($ogID, $drupalID) {
og_delete_subscription($ogID, $drupalID);
}
/**
* @inheritDoc
*/
public function getTimeZoneString() {
global $user;
// Note that 0 is a valid timezone (GMT) so we use strlen not empty to check.
if (variable_get('configurable_timezones', 1) && $user->uid && isset($user->timezone) && strlen($user->timezone)) {
$timezone = $user->timezone;
}
else {
$timezone = variable_get('date_default_timezone', NULL);
}
if (!$timezone) {
$timezone = parent::getTimeZoneString();
}
return $timezone;
}
/**
* @inheritDoc
*/
public function setHttpHeader($name, $value) {
drupal_set_header("$name: $value");
}
/**
* @inheritDoc
*/
public function synchronizeUsers() {
$config = CRM_Core_Config::singleton();
if (PHP_SAPI != 'cli') {
set_time_limit(300);
}
$rows = array();
$id = 'uid';
$mail = 'mail';
$name = 'name';
$result = db_query("SELECT uid, mail, name FROM {users} where mail != ''");
while ($row = db_fetch_array($result)) {
$rows[] = $row;
}
$user = new StdClass();
$uf = $config->userFramework;
$contactCount = 0;
$contactCreated = 0;
$contactMatching = 0;
foreach ($rows as $row) {
$user->$id = $row[$id];
$user->$mail = $row[$mail];
$user->$name = $row[$name];
$contactCount++;
if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $row[$id], $row[$mail], $uf, 1, 'Individual', TRUE)) {
$contactCreated++;
}
else {
$contactMatching++;
}
if (is_object($match)) {
$match->free();
}
}
return array(
'contactCount' => $contactCount,
'contactMatching' => $contactMatching,
'contactCreated' => $contactCreated,
);
}
}

View file

@ -0,0 +1,662 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Drupal specific stuff goes here.
*/
class CRM_Utils_System_Drupal8 extends CRM_Utils_System_DrupalBase {
/**
* @inheritDoc
*/
public function createUser(&$params, $mail) {
$user = \Drupal::currentUser();
$user_register_conf = \Drupal::config('user.settings')->get('register');
$verify_mail_conf = \Drupal::config('user.settings')->get('verify_mail');
// Don't create user if we don't have permission to.
if (!$user->hasPermission('administer users') && $user_register_conf == 'admin_only') {
return FALSE;
}
$account = entity_create('user');
$account->setUsername($params['cms_name'])->setEmail($params[$mail]);
// Allow user to set password only if they are an admin or if
// the site settings don't require email verification.
if (!$verify_mail_conf || $user->hasPermission('administer users')) {
// @Todo: do we need to check that passwords match or assume this has already been done for us?
$account->setPassword($params['cms_pass']);
}
// Only activate account if we're admin or if anonymous users don't require
// approval to create accounts.
if ($user_register_conf != 'visitors' && !$user->hasPermission('administer users')) {
$account->block();
}
// Validate the user object
$violations = $account->validate();
if (count($violations)) {
return FALSE;
}
try {
$account->save();
}
catch (\Drupal\Core\Entity\EntityStorageException $e) {
return FALSE;
}
// Send off any emails as required.
// Possible values for $op:
// - 'register_admin_created': Welcome message for user created by the admin.
// - 'register_no_approval_required': Welcome message when user
// self-registers.
// - 'register_pending_approval': Welcome message, user pending admin
// approval.
// @Todo: Should we only send off emails if $params['notify'] is set?
switch (TRUE) {
case $user_register_conf == 'admin_only' || $user->isAuthenticated():
_user_mail_notify('register_admin_created', $account);
break;
case $user_register_conf == 'visitors':
_user_mail_notify('register_no_approval_required', $account);
break;
case 'visitors_admin_approval':
_user_mail_notify('register_pending_approval', $account);
break;
}
return $account->id();
}
/**
* @inheritDoc
*/
public function updateCMSName($ufID, $email) {
$user = entity_load('user', $ufID);
if ($user && $user->getEmail() != $email) {
$user->setEmail($email);
if (!count($user->validate())) {
$user->save();
}
}
}
/**
* Check if username and email exists in the drupal db.
*
* @param array $params
* Array of name and mail values.
* @param array $errors
* Errors.
* @param string $emailName
* Field label for the 'email'.
*/
public static function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
// If we are given a name, let's check to see if it already exists.
if (!empty($params['name'])) {
$name = $params['name'];
$user = entity_create('user');
$user->setUsername($name);
// This checks for both username uniqueness and validity.
$violations = iterator_to_array($user->validate());
// We only care about violations on the username field; discard the rest.
$violations = array_filter($violations, function ($v) {
return $v->getPropertyPath() == 'name.0.value';
});
if (count($violations) > 0) {
$errors['cms_name'] = $violations[0]->getMessage();
}
}
// And if we are given an email address, let's check to see if it already exists.
if (!empty($params[$emailName])) {
$mail = $params[$emailName];
$user = entity_create('user');
$user->setEmail($mail);
// This checks for both email uniqueness.
$violations = iterator_to_array($user->validate());
// We only care about violations on the email field; discard the rest.
$violations = array_filter($violations, function ($v) {
return $v->getPropertyPath() == 'mail.0.value';
});
if (count($violations) > 0) {
$errors[$emailName] = $violations[0]->getMessage();
}
}
}
/**
* @inheritDoc
*/
public function getLoginURL($destination = '') {
$query = $destination ? array('destination' => $destination) : array();
return \Drupal::url('user.page', array(), array('query' => $query));
}
/**
* @inheritDoc
*/
public function setTitle($title, $pageTitle = NULL) {
if (!$pageTitle) {
$pageTitle = $title;
}
\Drupal::service('civicrm.page_state')->setTitle($pageTitle);
}
/**
* @inheritDoc
*/
public function appendBreadCrumb($breadcrumbs) {
$civicrmPageState = \Drupal::service('civicrm.page_state');
foreach ($breadcrumbs as $breadcrumb) {
$civicrmPageState->addBreadcrumb($breadcrumb['title'], $breadcrumb['url']);
}
}
/**
* @inheritDoc
*/
public function resetBreadCrumb() {
\Drupal::service('civicrm.page_state')->resetBreadcrumbs();
}
/**
* @inheritDoc
*/
public function addHTMLHead($header) {
\Drupal::service('civicrm.page_state')->addHtmlHeader($header);
}
/**
* @inheritDoc
*/
public function addScriptUrl($url, $region) {
static $weight = 0;
switch ($region) {
case 'html-header':
break;
default:
return FALSE;
}
$script = array(
'#tag' => 'script',
'#attributes' => array(
'src' => $url,
),
'#weight' => $weight,
);
$weight++;
\Drupal::service('civicrm.page_state')->addJS($script);
return TRUE;
}
/**
* @inheritDoc
*/
public function addScript($code, $region) {
switch ($region) {
case 'html-header':
break;
default:
return FALSE;
}
$script = array(
'#tag' => 'script',
'#value' => $code,
);
\Drupal::service('civicrm.page_state')->addJS($script);
return TRUE;
}
/**
* @inheritDoc
*/
public function addStyleUrl($url, $region) {
if ($region != 'html-header') {
return FALSE;
}
$css = array(
'#tag' => 'link',
'#attributes' => array(
'href' => $url,
'rel' => 'stylesheet',
),
);
\Drupal::service('civicrm.page_state')->addCSS($css);
return TRUE;
}
/**
* @inheritDoc
*/
public function addStyle($code, $region) {
if ($region != 'html-header') {
return FALSE;
}
$css = array(
'#tag' => 'style',
'#value' => $code,
);
\Drupal::service('civicrm.page_state')->addCSS($css);
return TRUE;
}
/**
* Check if a resource url is within the drupal directory and format appropriately.
*
* This seems to be a legacy function. We assume all resources are within the drupal
* directory and always return TRUE. As well, we clean up the $url.
*
* FIXME: This is not a legacy function and the above is not a safe assumption.
* External urls are allowed by CRM_Core_Resources and this needs to return the correct value.
*
* @param $url
*
* @return bool
*/
public function formatResourceUrl(&$url) {
// Remove leading slash if present.
$url = ltrim($url, '/');
// Remove query string — presumably added to stop intermediary caching.
if (($pos = strpos($url, '?')) !== FALSE) {
$url = substr($url, 0, $pos);
}
// FIXME: Should not unconditionally return true
return TRUE;
}
/**
* This function does nothing in Drupal 8. Changes to the base_url should be made
* in settings.php directly.
*/
public function mapConfigToSSL() {
}
/**
* @inheritDoc
*/
public function url(
$path = '',
$query = '',
$absolute = FALSE,
$fragment = NULL,
$frontend = FALSE,
$forceBackend = FALSE
) {
$query = html_entity_decode($query);
$url = \Drupal\civicrm\CivicrmHelper::parseURL("{$path}?{$query}");
// Not all links that CiviCRM generates are Drupal routes, so we use the weaker ::fromUri method.
try {
$url = \Drupal\Core\Url::fromUri("base:{$url['path']}", array(
'query' => $url['query'],
'fragment' => $fragment,
'absolute' => $absolute,
))->toString();
}
catch (Exception $e) {
// @Todo: log to watchdog
$url = '';
}
// Special case: CiviCRM passes us "*path*?*query*" as a skeleton, but asterisks
// are invalid and Drupal will attempt to escape them. We unescape them here:
if ($path == '*path*') {
// First remove trailing equals sign that has been added since the key '?*query*' has no value.
$url = rtrim($url, '=');
$url = urldecode($url);
}
return $url;
}
/**
* @inheritDoc
*/
public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
$system = new CRM_Utils_System_Drupal8();
$system->loadBootStrap(array(), FALSE);
$uid = \Drupal::service('user.auth')->authenticate($name, $password);
$contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
return array($contact_id, $uid, mt_rand());
}
/**
* @inheritDoc
*/
public function loadUser($username) {
$user = user_load_by_name($username);
if (!$user) {
return FALSE;
}
// Set Drupal's current user to the loaded user.
\Drupal::currentUser()->setAccount($user);
$uid = $user->id();
$contact_id = CRM_Core_BAO_UFMatch::getContactId($uid);
// Store the contact id and user id in the session
$session = CRM_Core_Session::singleton();
$session->set('ufID', $uid);
$session->set('userID', $contact_id);
return TRUE;
}
/**
* Determine the native ID of the CMS user.
*
* @param string $username
* @return int|NULL
*/
public function getUfId($username) {
if ($id = user_load_by_name($username)->id()) {
return $id;
}
}
/**
* @inheritDoc
*/
public function permissionDenied() {
\Drupal::service('civicrm.page_state')->setAccessDenied();
}
/**
* In previous versions, this function was the controller for logging out. In Drupal 8, we rewrite the route
* to hand off logout to the standard Drupal logout controller. This function should therefore never be called.
*/
public function logout() {
// Pass
}
/**
* Load drupal bootstrap.
*
* @param array $params
* Either uid, or name & pass.
* @param bool $loadUser
* Boolean Require CMS user load.
* @param bool $throwError
* If true, print error on failure and exit.
* @param bool|string $realPath path to script
*
* @return bool
* @Todo Handle setting cleanurls configuration for CiviCRM?
*/
public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
static $run_once = FALSE;
if ($run_once) {
return TRUE;
}
else {
$run_once = TRUE;
}
if (!($root = $this->cmsRootPath())) {
return FALSE;
}
chdir($root);
// Create a mock $request object
$autoloader = require_once $root . '/vendor/autoload.php';
if ($autoloader === TRUE) {
$autoloader = ComposerAutoloaderInitDrupal8::getLoader();
}
// @Todo: do we need to handle case where $_SERVER has no HTTP_HOST key, ie. when run via cli?
$request = new \Symfony\Component\HttpFoundation\Request(array(), array(), array(), array(), array(), $_SERVER);
// Create a kernel and boot it.
\Drupal\Core\DrupalKernel::createFromRequest($request, $autoloader, 'prod')->prepareLegacyRequest($request);
// Initialize Civicrm
\Drupal::service('civicrm');
// We need to call the config hook again, since we now know
// all the modules that are listening on it (CRM-8655).
CRM_Utils_Hook::config($config);
if ($loadUser) {
if (!empty($params['uid']) && $username = \Drupal\user\Entity\User::load($uid)->getUsername()) {
$this->loadUser($username);
}
elseif (!empty($params['name']) && !empty($params['pass']) && $this->authenticate($params['name'], $params['pass'])) {
$this->loadUser($params['name']);
}
}
return TRUE;
}
/**
* Determine the location of the CMS root.
*
* @param string $path
*
* @return NULL|string
*/
public function cmsRootPath($path = NULL) {
global $civicrm_paths;
if (!empty($civicrm_paths['cms.root']['path'])) {
return $civicrm_paths['cms.root']['path'];
}
if (defined('DRUPAL_ROOT')) {
return DRUPAL_ROOT;
}
// It looks like Drupal hasn't been bootstrapped.
// We're going to attempt to discover the root Drupal path
// by climbing out of the folder hierarchy and looking around to see
// if we've found the Drupal root directory.
if (!$path) {
$path = $_SERVER['SCRIPT_FILENAME'];
}
// Normalize and explode path into its component paths.
$paths = explode(DIRECTORY_SEPARATOR, realpath($path));
// Remove script filename from array of directories.
array_pop($paths);
while (count($paths)) {
$candidate = implode('/', $paths);
if (file_exists($candidate . "/core/includes/bootstrap.inc")) {
return $candidate;
}
array_pop($paths);
}
}
/**
* @inheritDoc
*/
public function isUserLoggedIn() {
return \Drupal::currentUser()->isAuthenticated();
}
/**
* @inheritDoc
*/
public function isUserRegistrationPermitted() {
if (\Drupal::config('user.settings')->get('register') == 'admin_only') {
return FALSE;
}
return TRUE;
}
/**
* @inheritDoc
*/
public function isPasswordUserGenerated() {
if (\Drupal::config('user.settings')->get('verify_mail') == TRUE) {
return FALSE;
}
return TRUE;
}
/**
* @inheritDoc
*/
public function getLoggedInUfID() {
if ($id = \Drupal::currentUser()->id()) {
return $id;
}
}
/**
* @inheritDoc
*/
public function getDefaultBlockLocation() {
return 'sidebar_first';
}
/**
* @inheritDoc
*/
public function flush() {
// CiviCRM and Drupal both provide (different versions of) Symfony (and possibly share other classes too).
// If we call drupal_flush_all_caches(), Drupal will attempt to rediscover all of its classes, use Civicrm's
// alternatives instead and then die. Instead, we only clear cache bins and no more.
foreach (Drupal\Core\Cache\Cache::getBins() as $service_id => $cache_backend) {
$cache_backend->deleteAll();
}
}
/**
* @inheritDoc
*/
public function getModules() {
$modules = array();
$module_data = system_rebuild_module_data();
foreach ($module_data as $module_name => $extension) {
if (!isset($extension->info['hidden']) && $extension->origin != 'core') {
$extension->schema_version = drupal_get_installed_schema_version($module_name);
$modules[] = new CRM_Core_Module('drupal.' . $module_name, ($extension->status == 1 ? TRUE : FALSE));
}
}
return $modules;
}
/**
* @inheritDoc
*/
public function getUniqueIdentifierFromUserObject($user) {
return $user->get('mail')->value;
}
/**
* @inheritDoc
*/
public function getUserIDFromUserObject($user) {
return $user->get('uid')->value;
}
/**
* @inheritDoc
*/
public function synchronizeUsers() {
$config = CRM_Core_Config::singleton();
if (PHP_SAPI != 'cli') {
set_time_limit(300);
}
$users = array();
$users = \Drupal::entityTypeManager()->getStorage('user')->loadByProperties();
$uf = $config->userFramework;
$contactCount = 0;
$contactCreated = 0;
$contactMatching = 0;
foreach ($users as $user) {
$mail = $user->get('mail')->value;
if (empty($mail)) {
continue;
}
$uid = $user->get('uid')->value;
$contactCount++;
if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $uid, $mail, $uf, 1, 'Individual', TRUE)) {
$contactCreated++;
}
else {
$contactMatching++;
}
if (is_object($match)) {
$match->free();
}
}
return array(
'contactCount' => $contactCount,
'contactMatching' => $contactMatching,
'contactCreated' => $contactCreated,
);
}
/**
* Drupal 8 has a different function to get current path, hence
* overriding the postURL function
*
* @param string $action
*
* @return string
*/
public function postURL($action) {
if (!empty($action)) {
return $action;
}
$current_path = \Drupal::service('path.current')->getPath();
return $this->url($current_path);
}
}

View file

@ -0,0 +1,667 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* Drupal specific stuff goes here
*/
abstract class CRM_Utils_System_DrupalBase extends CRM_Utils_System_Base {
/**
* Does this CMS / UF support a CMS specific logging mechanism?
* @todo - we should think about offering up logging mechanisms in a way that is also extensible by extensions
* @var bool
*/
var $supports_UF_Logging = TRUE;
/**
*/
public function __construct() {
/**
* deprecated property to check if this is a drupal install. The correct method is to have functions on the UF classes for all UF specific
* functions and leave the codebase oblivious to the type of CMS
* @deprecated
* @var bool
*/
$this->is_drupal = TRUE;
$this->supports_form_extensions = TRUE;
}
/**
* @inheritdoc
*/
public function getDefaultFileStorage() {
$config = CRM_Core_Config::singleton();
$baseURL = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
$siteName = $this->parseDrupalSiteNameFromRequest('/files/civicrm');
if ($siteName) {
$filesURL = $baseURL . "sites/$siteName/files/civicrm/";
}
else {
$filesURL = $baseURL . "sites/default/files/civicrm/";
}
return array(
'url' => $filesURL,
'path' => CRM_Utils_File::baseFilePath(),
);
}
/**
* @inheritDoc
*/
public function getDefaultSiteSettings($dir) {
$config = CRM_Core_Config::singleton();
$siteName = $siteRoot = NULL;
$matches = array();
if (preg_match(
'|/sites/([\w\.\-\_]+)/|',
$config->templateCompileDir,
$matches
)) {
$siteName = $matches[1];
if ($siteName) {
$siteName = "/sites/$siteName/";
$siteNamePos = strpos($dir, $siteName);
if ($siteNamePos !== FALSE) {
$siteRoot = substr($dir, 0, $siteNamePos);
}
}
}
$url = $config->userFrameworkBaseURL;
return array($url, $siteName, $siteRoot);
}
/**
* Check if a resource url is within the drupal directory and format appropriately.
*
* @param $url (reference)
*
* @return bool
* TRUE for internal paths, FALSE for external. The drupal_add_js fn is able to add js more
* efficiently if it is known to be in the drupal site
*/
public function formatResourceUrl(&$url) {
$internal = FALSE;
$base = CRM_Core_Config::singleton()->resourceBase;
global $base_url;
// Handle absolute urls
// compares $url (which is some unknown/untrusted value from a third-party dev) to the CMS's base url (which is independent of civi's url)
// to see if the url is within our drupal dir, if it is we are able to treated it as an internal url
if (strpos($url, $base_url) === 0) {
$file = trim(str_replace($base_url, '', $url), '/');
// CRM-18130: Custom CSS URL not working if aliased or rewritten
if (file_exists(DRUPAL_ROOT . $file)) {
$url = $file;
$internal = TRUE;
}
}
// Handle relative urls that are within the CiviCRM module directory
elseif (strpos($url, $base) === 0) {
$internal = TRUE;
$url = $this->appendCoreDirectoryToResourceBase(dirname(drupal_get_path('module', 'civicrm')) . '/') . trim(substr($url, strlen($base)), '/');
}
// Strip query string
$q = strpos($url, '?');
if ($q && $internal) {
$url = substr($url, 0, $q);
}
return $internal;
}
/**
* In instance where civicrm folder has a drupal folder & a civicrm core folder @ the same level append the
* civicrm folder name to the url
* See CRM-13737 for discussion of how this allows implementers to alter the folder structure
* @todo - this only provides a limited amount of flexiblity - it still expects a 'civicrm' folder with a 'drupal' folder
* and is only flexible as to the name of the civicrm folder.
*
* @param string $url
* Potential resource url based on standard folder assumptions.
* @return string
* with civicrm-core directory appended if not standard civi dir
*/
public function appendCoreDirectoryToResourceBase($url) {
global $civicrm_root;
$lastDirectory = basename($civicrm_root);
if ($lastDirectory != 'civicrm') {
return $url .= $lastDirectory . '/';
}
return $url;
}
/**
* Generate an internal CiviCRM URL (copied from DRUPAL/includes/common.inc#url)
*
* @inheritDoc
*/
public function url(
$path = NULL,
$query = NULL,
$absolute = FALSE,
$fragment = NULL,
$frontend = FALSE,
$forceBackend = FALSE
) {
$config = CRM_Core_Config::singleton();
$script = 'index.php';
$path = CRM_Utils_String::stripPathChars($path);
if (isset($fragment)) {
$fragment = '#' . $fragment;
}
$base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
$separator = '&';
if (!$config->cleanURL) {
if (isset($path)) {
if (isset($query)) {
return $base . $script . '?q=' . $path . $separator . $query . $fragment;
}
else {
return $base . $script . '?q=' . $path . $fragment;
}
}
else {
if (isset($query)) {
return $base . $script . '?' . $query . $fragment;
}
else {
return $base . $fragment;
}
}
}
else {
if (isset($path)) {
if (isset($query)) {
return $base . $path . '?' . $query . $fragment;
}
else {
return $base . $path . $fragment;
}
}
else {
if (isset($query)) {
return $base . $script . '?' . $query . $fragment;
}
else {
return $base . $fragment;
}
}
}
}
/**
* @inheritDoc
*/
public function getUserIDFromUserObject($user) {
return !empty($user->uid) ? $user->uid : NULL;
}
/**
* @inheritDoc
*/
public function setMessage($message) {
drupal_set_message($message);
}
/**
* @inheritDoc
*/
public function getUniqueIdentifierFromUserObject($user) {
return empty($user->mail) ? NULL : $user->mail;
}
/**
* @inheritDoc
*/
public function getLoggedInUniqueIdentifier() {
global $user;
return $this->getUniqueIdentifierFromUserObject($user);
}
/**
* @inheritDoc
*/
public function permissionDenied() {
drupal_access_denied();
}
/**
* @inheritDoc
*/
public function getUserRecordUrl($contactID) {
$uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
if (CRM_Core_Session::singleton()
->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array(
'cms:administer users',
'cms:view user account',
))
) {
return $this->url('user/' . $uid);
};
}
/**
* @inheritDoc
*/
public function checkPermissionAddUser() {
return CRM_Core_Permission::check('administer users');
}
/**
* @inheritDoc
*/
public function logger($message) {
if (CRM_Core_Config::singleton()->userFrameworkLogging && function_exists('watchdog')) {
watchdog('civicrm', '%message', array('%message' => $message), NULL, WATCHDOG_DEBUG);
}
}
/**
* @inheritDoc
*/
public function clearResourceCache() {
_drupal_flush_css_js();
}
/**
* Append Drupal js to coreResourcesList.
*
* @param array $list
*/
public function appendCoreResources(&$list) {
$list[] = 'js/crm.drupal.js';
}
/**
* @inheritDoc
*/
public function flush() {
drupal_flush_all_caches();
}
/**
* @inheritDoc
*/
public function getModules() {
$result = array();
$q = db_query('SELECT name, status FROM {system} WHERE type = \'module\' AND schema_version <> -1');
foreach ($q as $row) {
$result[] = new CRM_Core_Module('drupal.' . $row->name, ($row->status == 1) ? TRUE : FALSE);
}
return $result;
}
/**
* Find any users/roles/security-principals with the given permission
* and replace it with one or more permissions.
*
* @param string $oldPerm
* @param array $newPerms
* Array, strings.
*
* @return void
*/
public function replacePermission($oldPerm, $newPerms) {
$roles = user_roles(FALSE, $oldPerm);
if (!empty($roles)) {
foreach (array_keys($roles) as $rid) {
user_role_revoke_permissions($rid, array($oldPerm));
user_role_grant_permissions($rid, $newPerms);
}
}
}
/**
* @inheritDoc
*/
public function languageNegotiationURL($url, $addLanguagePart = TRUE, $removeLanguagePart = FALSE) {
if (empty($url)) {
return $url;
}
//CRM-7803 -from d7 onward.
$config = CRM_Core_Config::singleton();
if (function_exists('variable_get') &&
module_exists('locale') &&
function_exists('language_negotiation_get')
) {
global $language;
//does user configuration allow language
//support from the URL (Path prefix or domain)
if (language_negotiation_get('language') == 'locale-url') {
$urlType = variable_get('locale_language_negotiation_url_part');
//url prefix
if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX) {
if (isset($language->prefix) && $language->prefix) {
if ($addLanguagePart) {
$url .= $language->prefix . '/';
}
if ($removeLanguagePart) {
$url = str_replace("/{$language->prefix}/", '/', $url);
}
}
}
//domain
if ($urlType == LOCALE_LANGUAGE_NEGOTIATION_URL_DOMAIN) {
if (isset($language->domain) && $language->domain) {
if ($addLanguagePart) {
$url = (CRM_Utils_System::isSSL() ? 'https' : 'http') . '://' . $language->domain . base_path();
}
if ($removeLanguagePart && defined('CIVICRM_UF_BASEURL')) {
$url = str_replace('\\', '/', $url);
$parseUrl = parse_url($url);
//kinda hackish but not sure how to do it right
//hope http_build_url() will help at some point.
if (is_array($parseUrl) && !empty($parseUrl)) {
$urlParts = explode('/', $url);
$hostKey = array_search($parseUrl['host'], $urlParts);
$ufUrlParts = parse_url(CIVICRM_UF_BASEURL);
$urlParts[$hostKey] = $ufUrlParts['host'];
$url = implode('/', $urlParts);
}
}
}
}
}
}
return $url;
}
/**
* @inheritDoc
*/
public function getVersion() {
return defined('VERSION') ? VERSION : 'Unknown';
}
/**
* @inheritDoc
*/
public function isUserRegistrationPermitted() {
if (!variable_get('user_register', TRUE)) {
return FALSE;
}
return TRUE;
}
/**
* @inheritDoc
*/
public function isPasswordUserGenerated() {
if (variable_get('user_email_verification', TRUE)) {
return FALSE;
}
return TRUE;
}
/**
* @inheritDoc
*/
public function updateCategories() {
// copied this from profile.module. Seems a bit inefficient, but i don't know a better way
cache_clear_all();
menu_rebuild();
}
/**
* @inheritDoc
*/
public function getUFLocale() {
// return CiviCRMs xx_YY locale that either matches Drupals Chinese locale
// (for CRM-6281), Drupals xx_YY or is retrieved based on Drupals xx
// sometimes for CLI based on order called, this might not be set and/or empty
global $language;
if (empty($language)) {
return NULL;
}
if ($language->language == 'zh-hans') {
return 'zh_CN';
}
if ($language->language == 'zh-hant') {
return 'zh_TW';
}
if (preg_match('/^.._..$/', $language->language)) {
return $language->language;
}
return CRM_Core_I18n_PseudoConstant::longForShort(substr($language->language, 0, 2));
}
/**
* @inheritDoc
*/
public function setUFLocale($civicrm_language) {
global $language;
$langcode = substr($civicrm_language, 0, 2);
$languages = language_list();
if (isset($languages[$langcode])) {
$language = $languages[$langcode];
// Config must be re-initialized to reset the base URL
// otherwise links will have the wrong language prefix/domain.
$config = CRM_Core_Config::singleton();
$config->free();
return TRUE;
}
return FALSE;
}
/**
* Perform any post login activities required by the UF -
* e.g. for drupal: records a watchdog message about the new session, saves the login timestamp,
* calls hook_user op 'login' and generates a new session.
*
* @param array $params
*
* FIXME: Document values accepted/required by $params
*/
public function userLoginFinalize($params = array()) {
user_login_finalize($params);
}
/**
* @inheritDoc
*/
public function getLoginDestination(&$form) {
$args = NULL;
$id = $form->get('id');
if ($id) {
$args .= "&id=$id";
}
else {
$gid = $form->get('gid');
if ($gid) {
$args .= "&gid=$gid";
}
else {
// Setup Personal Campaign Page link uses pageId
$pageId = $form->get('pageId');
if ($pageId) {
$component = $form->get('component');
$args .= "&pageId=$pageId&component=$component&action=add";
}
}
}
$destination = NULL;
if ($args) {
// append destination so user is returned to form they came from after login
$destination = CRM_Utils_System::currentPath() . '?reset=1' . $args;
}
return $destination;
}
/**
* Fixme: Why are we overriding the parent function? Seems inconsistent.
* This version supplies slightly different params to $this->url (not absolute and html encoded) but why?
*
* @param string $action
*
* @return string
*/
public function postURL($action) {
if (!empty($action)) {
return $action;
}
return $this->url($_GET['q']);
}
/**
* Get an array of user details for a contact, containing at minimum the user ID & name.
*
* @param int $contactID
*
* @return array
* CMS user details including
* - id
* - name (ie the system user name.
*/
public function getUser($contactID) {
$userDetails = parent::getUser($contactID);
$user = $this->getUserObject($userDetails['id']);
$userDetails['name'] = $user->name;
$userDetails['email'] = $user->mail;
return $userDetails;
}
/**
* Load the user object.
*
* Note this function still works in drupal 6, 7 & 8 but is deprecated in Drupal 8.
*
* @param $userID
*
* @return object
*/
public function getUserObject($userID) {
return user_load($userID);
}
/**
* Parse the name of the drupal site.
*
* @param string $civicrm_root
*
* @return null|string
* @deprecated
*/
public function parseDrupalSiteNameFromRoot($civicrm_root) {
$siteName = NULL;
if (strpos($civicrm_root,
DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . 'all' . DIRECTORY_SEPARATOR . 'modules'
) === FALSE
) {
$startPos = strpos($civicrm_root,
DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR
);
$endPos = strpos($civicrm_root,
DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR
);
if ($startPos && $endPos) {
// if component is in sites/SITENAME/modules
$siteName = substr($civicrm_root,
$startPos + 7,
$endPos - $startPos - 7
);
}
}
return $siteName;
}
/**
* Determine if Drupal multi-site applies to the current request -- and,
* specifically, determine the name of the multisite folder.
*
* @param string $flagFile
* Check if $flagFile exists inside the site dir.
* @return null|string
* string, e.g. `bar.example.com` if using multisite.
* NULL if using the default site.
*/
private function parseDrupalSiteNameFromRequest($flagFile = '') {
$phpSelf = array_key_exists('PHP_SELF', $_SERVER) ? $_SERVER['PHP_SELF'] : '';
$httpHost = array_key_exists('HTTP_HOST', $_SERVER) ? $_SERVER['HTTP_HOST'] : '';
if (empty($httpHost)) {
$httpHost = parse_url(CIVICRM_UF_BASEURL, PHP_URL_HOST);
if (parse_url(CIVICRM_UF_BASEURL, PHP_URL_PORT)) {
$httpHost .= ':' . parse_url(CIVICRM_UF_BASEURL, PHP_URL_PORT);
}
}
$confdir = $this->cmsRootPath() . '/sites';
if (file_exists($confdir . "/sites.php")) {
include $confdir . "/sites.php";
}
else {
$sites = array();
}
$uri = explode('/', $phpSelf);
$server = explode('.', implode('.', array_reverse(explode(':', rtrim($httpHost, '.')))));
for ($i = count($uri) - 1; $i > 0; $i--) {
for ($j = count($server); $j > 0; $j--) {
$dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
if (file_exists("$confdir/$dir" . $flagFile)) {
\Civi::$statics[__CLASS__]['drupalSiteName'] = $dir;
return \Civi::$statics[__CLASS__]['drupalSiteName'];
}
// check for alias
if (isset($sites[$dir]) && file_exists("$confdir/{$sites[$dir]}" . $flagFile)) {
\Civi::$statics[__CLASS__]['drupalSiteName'] = $sites[$dir];
return \Civi::$statics[__CLASS__]['drupalSiteName'];
}
}
}
}
}

View file

@ -0,0 +1,891 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Joomla specific stuff goes here.
*/
class CRM_Utils_System_Joomla extends CRM_Utils_System_Base {
/**
* Class constructor.
*/
public function __construct() {
/**
* deprecated property to check if this is a drupal install. The correct method is to have functions on the UF classes for all UF specific
* functions and leave the codebase oblivious to the type of CMS
* @deprecated
* @var bool
*/
$this->is_drupal = FALSE;
}
/**
* @inheritDoc
*/
public function createUser(&$params, $mail) {
$baseDir = JPATH_SITE;
require_once $baseDir . '/components/com_users/models/registration.php';
$userParams = JComponentHelper::getParams('com_users');
$model = new UsersModelRegistration();
$ufID = NULL;
// get the default usertype
$userType = $userParams->get('new_usertype');
if (!$userType) {
$userType = 2;
}
if (isset($params['name'])) {
$fullname = trim($params['name']);
}
elseif (isset($params['contactID'])) {
$fullname = trim(CRM_Contact_BAO_Contact::displayName($params['contactID']));
}
else {
$fullname = trim($params['cms_name']);
}
// Prepare the values for a new Joomla user.
$values = array();
$values['name'] = $fullname;
$values['username'] = trim($params['cms_name']);
$values['password1'] = $values['password2'] = $params['cms_pass'];
$values['email1'] = $values['email2'] = trim($params[$mail]);
$lang = JFactory::getLanguage();
$lang->load('com_users', $baseDir);
$register = $model->register($values);
$ufID = JUserHelper::getUserId($values['username']);
return $ufID;
}
/**
* @inheritDoc
*/
public function updateCMSName($ufID, $ufName) {
$ufID = CRM_Utils_Type::escape($ufID, 'Integer');
$ufName = CRM_Utils_Type::escape($ufName, 'String');
$values = array();
$user = JUser::getInstance($ufID);
$values['email'] = $ufName;
$user->bind($values);
$user->save();
}
/**
* Check if username and email exists in the Joomla db.
*
* @param array $params
* Array of name and mail values.
* @param array $errors
* Array of errors.
* @param string $emailName
* Field label for the 'email'.
*/
public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
$config = CRM_Core_Config::singleton();
$dao = new CRM_Core_DAO();
$name = $dao->escape(CRM_Utils_Array::value('name', $params));
$email = $dao->escape(CRM_Utils_Array::value('mail', $params));
//don't allow the special characters and min. username length is two
//regex \\ to match a single backslash would become '/\\\\/'
$isNotValid = (bool) preg_match('/[\<|\>|\"|\'|\%|\;|\(|\)|\&|\\\\|\/]/im', $name);
if ($isNotValid || strlen($name) < 2) {
$errors['cms_name'] = ts('Your username contains invalid characters or is too short');
}
$JUserTable = &JTable::getInstance('User', 'JTable');
$db = $JUserTable->getDbo();
$query = $db->getQuery(TRUE);
$query->select('username, email');
$query->from($JUserTable->getTableName());
// LOWER in query below roughly translates to 'hurt my database without deriving any benefit' See CRM-19811.
$query->where('(LOWER(username) = LOWER(\'' . $name . '\')) OR (LOWER(email) = LOWER(\'' . $email . '\'))');
$db->setQuery($query, 0, 10);
$users = $db->loadAssocList();
$row = array();
if (count($users)) {
$row = $users[0];
}
if (!empty($row)) {
$dbName = CRM_Utils_Array::value('username', $row);
$dbEmail = CRM_Utils_Array::value('email', $row);
if (strtolower($dbName) == strtolower($name)) {
$errors['cms_name'] = ts('The username %1 is already taken. Please select another username.',
array(1 => $name)
);
}
if (strtolower($dbEmail) == strtolower($email)) {
$resetUrl = str_replace('administrator/', '', $config->userFrameworkBaseURL) . 'index.php?option=com_users&view=reset';
$errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
array(1 => $email, 2 => $resetUrl)
);
}
}
}
/**
* @inheritDoc
*/
public function setTitle($title, $pageTitle = NULL) {
if (!$pageTitle) {
$pageTitle = $title;
}
$template = CRM_Core_Smarty::singleton();
$template->assign('pageTitle', $pageTitle);
$document = JFactory::getDocument();
$document->setTitle($title);
}
/**
* @inheritDoc
*/
public function appendBreadCrumb($breadCrumbs) {
$template = CRM_Core_Smarty::singleton();
$bc = $template->get_template_vars('breadcrumb');
if (is_array($breadCrumbs)) {
foreach ($breadCrumbs as $crumbs) {
if (stripos($crumbs['url'], 'id%%')) {
$args = array('cid', 'mid');
foreach ($args as $a) {
$val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
FALSE, NULL, $_GET
);
if ($val) {
$crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
}
}
}
$bc[] = $crumbs;
}
}
$template->assign_by_ref('breadcrumb', $bc);
}
/**
* @inheritDoc
*/
public function resetBreadCrumb() {
}
/**
* @inheritDoc
*/
public function addHTMLHead($string = NULL) {
if ($string) {
$document = JFactory::getDocument();
$document->addCustomTag($string);
}
}
/**
* @inheritDoc
*/
public function addStyleUrl($url, $region) {
if ($region == 'html-header') {
$document = JFactory::getDocument();
$document->addStyleSheet($url);
return TRUE;
}
return FALSE;
}
/**
* @inheritDoc
*/
public function addStyle($code, $region) {
if ($region == 'html-header') {
$document = JFactory::getDocument();
$document->addStyleDeclaration($code);
return TRUE;
}
return FALSE;
}
/**
* @inheritDoc
*/
public function url(
$path = NULL,
$query = NULL,
$absolute = FALSE,
$fragment = NULL,
$frontend = FALSE,
$forceBackend = FALSE
) {
$config = CRM_Core_Config::singleton();
$separator = '&';
$Itemid = '';
$script = '';
$path = CRM_Utils_String::stripPathChars($path);
if ($config->userFrameworkFrontend) {
$script = 'index.php';
if (JRequest::getVar("Itemid")) {
$Itemid = "{$separator}Itemid=" . JRequest::getVar("Itemid");
}
}
if (isset($fragment)) {
$fragment = '#' . $fragment;
}
$base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
if (!empty($query)) {
$url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$separator}{$query}{$fragment}";
}
else {
$url = "{$base}{$script}?option=com_civicrm{$separator}task={$path}{$Itemid}{$fragment}";
}
// gross hack for joomla, we are in the backend and want to send a frontend url
if ($frontend && $config->userFramework == 'Joomla') {
// handle both joomla v1.5 and v1.6, CRM-7939
$url = str_replace('/administrator/index2.php', '/index.php', $url);
$url = str_replace('/administrator/index.php', '/index.php', $url);
// CRM-8215
$url = str_replace('/administrator/', '/index.php', $url);
}
elseif ($forceBackend) {
if (defined('JVERSION')) {
$joomlaVersion = JVERSION;
}
else {
$jversion = new JVersion();
$joomlaVersion = $jversion->getShortVersion();
}
if (version_compare($joomlaVersion, '1.6') >= 0) {
$url = str_replace('/index.php', '/administrator/index.php', $url);
}
}
return $url;
}
/**
* Set the email address of the user.
*
* @param object $user
* Handle to the user object.
*/
public function setEmail(&$user) {
global $database;
$query = $db->getQuery(TRUE);
$query->select($db->quoteName('email'))
->from($db->quoteName('#__users'))
->where($db->quoteName('id') . ' = ' . $user->id);
$database->setQuery($query);
$user->email = $database->loadResult();
}
/**
* @inheritDoc
*/
public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
require_once 'DB.php';
$config = CRM_Core_Config::singleton();
$user = NULL;
if ($loadCMSBootstrap) {
$bootStrapParams = array();
if ($name && $password) {
$bootStrapParams = array(
'name' => $name,
'pass' => $password,
);
}
CRM_Utils_System::loadBootStrap($bootStrapParams, TRUE, TRUE, FALSE);
}
jimport('joomla.application.component.helper');
jimport('joomla.database.table');
jimport('joomla.user.helper');
$JUserTable = JTable::getInstance('User', 'JTable');
$db = $JUserTable->getDbo();
$query = $db->getQuery(TRUE);
$query->select('id, name, username, email, password');
$query->from($JUserTable->getTableName());
$query->where('(LOWER(username) = LOWER(\'' . $name . '\')) AND (block = 0)');
$db->setQuery($query, 0, 0);
$users = $db->loadObjectList();
$row = array();
if (count($users)) {
$row = $users[0];
}
$joomlaBase = self::getBasePath();
self::getJVersion($joomlaBase);
if (!empty($row)) {
$dbPassword = $row->password;
$dbId = $row->id;
$dbEmail = $row->email;
if (version_compare(JVERSION, '2.5.18', 'lt') ||
(version_compare(JVERSION, '3.0', 'ge') && version_compare(JVERSION, '3.2.1', 'lt'))
) {
// now check password
list($hash, $salt) = explode(':', $dbPassword);
$cryptpass = md5($password . $salt);
if ($hash != $cryptpass) {
return FALSE;
}
}
else {
if (!JUserHelper::verifyPassword($password, $dbPassword, $dbId)) {
return FALSE;
}
if (version_compare(JVERSION, '3.8.0', 'ge')) {
jimport('joomla.application.helper');
jimport('joomla.application.cms');
jimport('joomla.application.administrator');
}
//include additional files required by Joomla 3.2.1+
elseif (version_compare(JVERSION, '3.2.1', 'ge')) {
require_once $joomlaBase . '/libraries/cms/application/helper.php';
require_once $joomlaBase . '/libraries/cms/application/cms.php';
require_once $joomlaBase . '/libraries/cms/application/administrator.php';
}
}
CRM_Core_BAO_UFMatch::synchronizeUFMatch($row, $dbId, $dbEmail, 'Joomla');
$contactID = CRM_Core_BAO_UFMatch::getContactId($dbId);
if (!$contactID) {
return FALSE;
}
return array($contactID, $dbId, mt_rand());
}
return FALSE;
}
/**
* Set a init session with user object.
*
* @param array $data
* Array with user specific data.
*/
public function setUserSession($data) {
list($userID, $ufID) = $data;
$user = new JUser($ufID);
$session = JFactory::getSession();
$session->set('user', $user);
parent::setUserSession($data);
}
/**
* FIXME: Do something
*
* @param string $message
*/
public function setMessage($message) {
}
/**
* @param \string $username
* @param \string $password
*
* @return bool
*/
public function loadUser($username, $password = NULL) {
$uid = JUserHelper::getUserId($username);
if (empty($uid)) {
return FALSE;
}
$contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
if (!empty($password)) {
$instance = JFactory::getApplication('site');
$params = array(
'username' => $username,
'password' => $password,
);
//perform the login action
$instance->login($params);
}
$session = CRM_Core_Session::singleton();
$session->set('ufID', $uid);
$session->set('userID', $contactID);
return TRUE;
}
/**
* FIXME: Use CMS-native approach
*/
public function permissionDenied() {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
/**
* @inheritDoc
*/
public function logout() {
session_destroy();
CRM_Utils_System::setHttpHeader("Location", "index.php");
}
/**
* @inheritDoc
*/
public function getUFLocale() {
if (defined('_JEXEC')) {
$conf = JFactory::getConfig();
$locale = $conf->get('language');
return str_replace('-', '_', $locale);
}
return NULL;
}
/**
* @inheritDoc
*/
public function setUFLocale($civicrm_language) {
// TODO
return TRUE;
}
/**
* @inheritDoc
*/
public function getVersion() {
if (class_exists('JVersion')) {
$version = new JVersion();
return $version->getShortVersion();
}
else {
return 'Unknown';
}
}
public function getJVersion($joomlaBase) {
// Files may be in different places depending on Joomla version
if (!defined('JVERSION')) {
// Joomla 3.8.0+
$versionPhp = $joomlaBase . '/libraries/src/Version.php';
if (!file_exists($versionPhp)) {
// Joomla < 3.8.0
$versionPhp = $joomlaBase . '/libraries/cms/version/version.php';
}
require $versionPhp;
$jversion = new JVersion();
define('JVERSION', $jversion->getShortVersion());
}
}
/**
* Setup the base path related constant.
* @return mixed
*/
public function getBasePath() {
global $civicrm_root;
$joomlaPath = explode('/administrator', $civicrm_root);
$joomlaBase = $joomlaPath[0];
return $joomlaBase;
}
/**
* Load joomla bootstrap.
*
* @param array $params
* with uid or name and password.
* @param bool $loadUser
* load cms user?.
* @param bool|\throw $throwError throw error on failure?
* @param null $realPath
* @param bool $loadDefines
*
* @return bool
*/
public function loadBootStrap($params = array(), $loadUser = TRUE, $throwError = TRUE, $realPath = NULL, $loadDefines = TRUE) {
$joomlaBase = self::getBasePath();
// load BootStrap here if needed
// We are a valid Joomla entry point.
if (!defined('_JEXEC') && $loadDefines) {
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
define('JPATH_BASE', $joomlaBase . '/administrator');
require $joomlaBase . '/administrator/includes/defines.php';
require $joomlaBase . '/administrator/includes/framework.php';
}
// Get the framework.
if (file_exists($joomlaBase . '/libraries/import.legacy.php')) {
require $joomlaBase . '/libraries/import.legacy.php';
}
require $joomlaBase . '/libraries/cms.php';
require $joomlaBase . '/libraries/import.php';
require $joomlaBase . '/libraries/joomla/event/dispatcher.php';
require_once $joomlaBase . '/configuration.php';
self::getJVersion($joomlaBase);
if (version_compare(JVERSION, '3.0', 'lt')) {
require $joomlaBase . '/libraries/joomla/environment/uri.php';
require $joomlaBase . '/libraries/joomla/application/component/helper.php';
}
else {
jimport('joomla.environment.uri');
}
jimport('joomla.application.cli');
if (!defined('JDEBUG')) {
define('JDEBUG', FALSE);
}
// CRM-14281 Joomla wasn't available during bootstrap, so hook_civicrm_config never executes.
$config = CRM_Core_Config::singleton();
CRM_Utils_Hook::config($config);
return TRUE;
}
/**
* @inheritDoc
*/
public function isUserLoggedIn() {
$user = JFactory::getUser();
return ($user->guest) ? FALSE : TRUE;
}
/**
* @inheritDoc
*/
public function isUserRegistrationPermitted() {
$userParams = JComponentHelper::getParams('com_users');
if (!$userParams->get('allowUserRegistration')) {
return FALSE;
}
return TRUE;
}
/**
* @inheritDoc
*/
public function isPasswordUserGenerated() {
return TRUE;
}
/**
* @inheritDoc
*/
public function getLoggedInUfID() {
$user = JFactory::getUser();
return ($user->guest) ? NULL : $user->id;
}
/**
* @inheritDoc
*/
public function getLoggedInUniqueIdentifier() {
$user = JFactory::getUser();
return $this->getUniqueIdentifierFromUserObject($user);
}
/**
* @inheritDoc
*/
public function getUserIDFromUserObject($user) {
return !empty($user->id) ? $user->id : NULL;
}
/**
* @inheritDoc
*/
public function getUniqueIdentifierFromUserObject($user) {
return ($user->guest) ? NULL : $user->email;
}
/**
* @inheritDoc
*/
public function getTimeZoneString() {
$timezone = JFactory::getConfig()->get('offset');
return !$timezone ? date_default_timezone_get() : $timezone;
}
/**
* Get a list of all installed modules, including enabled and disabled ones
*
* @return array
* CRM_Core_Module
*/
public function getModules() {
$result = array();
$db = JFactory::getDbo();
$query = $db->getQuery(TRUE);
$query->select('type, folder, element, enabled')
->from('#__extensions')
->where('type =' . $db->Quote('plugin'));
$plugins = $db->setQuery($query)->loadAssocList();
foreach ($plugins as $plugin) {
// question: is the folder really a critical part of the plugin's name?
$name = implode('.', array('joomla', $plugin['type'], $plugin['folder'], $plugin['element']));
$result[] = new CRM_Core_Module($name, $plugin['enabled'] ? TRUE : FALSE);
}
return $result;
}
/**
* @inheritDoc
*/
public function getLoginURL($destination = '') {
$config = CRM_Core_Config::singleton();
$loginURL = $config->userFrameworkBaseURL;
$loginURL = str_replace('administrator/', '', $loginURL);
$loginURL .= 'index.php?option=com_users&view=login';
//CRM-14872 append destination
if (!empty($destination)) {
$loginURL .= '&return=' . urlencode(base64_encode($destination));
}
return $loginURL;
}
/**
* @inheritDoc
*/
public function getLoginDestination(&$form) {
$args = NULL;
$id = $form->get('id');
if ($id) {
$args .= "&id=$id";
}
else {
$gid = $form->get('gid');
if ($gid) {
$args .= "&gid=$gid";
}
else {
// Setup Personal Campaign Page link uses pageId
$pageId = $form->get('pageId');
if ($pageId) {
$component = $form->get('component');
$args .= "&pageId=$pageId&component=$component&action=add";
}
}
}
$destination = NULL;
if ($args) {
// append destination so user is returned to form they came from after login
$args = 'reset=1' . $args;
$destination = CRM_Utils_System::url(CRM_Utils_System::currentPath(), $args, TRUE, NULL, FALSE, TRUE);
}
return $destination;
}
/**
* Determine the location of the CMS root.
*
* @return string|NULL
* local file system path to CMS root, or NULL if it cannot be determined
*/
public function cmsRootPath() {
global $civicrm_paths;
if (!empty($civicrm_paths['cms.root']['path'])) {
return $civicrm_paths['cms.root']['path'];
}
list($url, $siteName, $siteRoot) = $this->getDefaultSiteSettings();
if (file_exists("$siteRoot/administrator/index.php")) {
return $siteRoot;
}
return NULL;
}
/**
* @inheritDoc
*/
public function getDefaultSiteSettings($dir = NULL) {
$config = CRM_Core_Config::singleton();
$url = preg_replace(
'|/administrator|',
'',
$config->userFrameworkBaseURL
);
// CRM-19453 revisited. Under Windows, the pattern wasn't recognised.
// This is the original pattern, but it doesn't work under Windows.
// By setting the pattern to the one used before the change first and only
// changing it means that the change code only affects Windows users.
$pattern = '|/media/civicrm/.*$|';
if (DIRECTORY_SEPARATOR == '\\') {
// This regular expression will handle Windows as well as Linux
// and any combination of forward and back slashes in directory
// separators. We only apply it if the directory separator is the one
// used by Windows.
$pattern = '|[\\\\/]media[\\\\/]civicrm[\\\\/].*$|';
}
$siteRoot = preg_replace(
$pattern,
'',
$config->imageUploadDir
);
return array($url, NULL, $siteRoot);
}
/**
* @inheritDoc
*/
public function getUserRecordUrl($contactID) {
$uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
$userRecordUrl = NULL;
// if logged in user has user edit access, then allow link to other users joomla profile
if (JFactory::getUser()->authorise('core.edit', 'com_users')) {
return CRM_Core_Config::singleton()->userFrameworkBaseURL . "index.php?option=com_users&view=user&task=user.edit&id=" . $uid;
}
elseif (CRM_Core_Session::singleton()->get('userID') == $contactID) {
return CRM_Core_Config::singleton()->userFrameworkBaseURL . "index.php?option=com_admin&view=profile&layout=edit&id=" . $uid;
}
}
/**
* @inheritDoc
*/
public function checkPermissionAddUser() {
if (JFactory::getUser()->authorise('core.create', 'com_users')) {
return TRUE;
}
}
/**
* Output code from error function.
* @param string $content
*/
public function outputError($content) {
if (class_exists('JErrorPage')) {
$error = new Exception($content);
JErrorPage::render($error);
}
elseif (class_exists('JError')) {
JError::raiseError('CiviCRM-001', $content);
}
else {
parent::outputError($content);
}
}
/**
* Append Joomla js to coreResourcesList.
*
* @param array $list
*/
public function appendCoreResources(&$list) {
$list[] = 'js/crm.joomla.js';
}
/**
* @inheritDoc
*/
public function synchronizeUsers() {
$config = CRM_Core_Config::singleton();
if (PHP_SAPI != 'cli') {
set_time_limit(300);
}
$id = 'id';
$mail = 'email';
$name = 'name';
$JUserTable = &JTable::getInstance('User', 'JTable');
$db = $JUserTable->getDbo();
$query = $db->getQuery(TRUE);
$query->select($id . ', ' . $mail . ', ' . $name);
$query->from($JUserTable->getTableName());
$query->where($mail != '');
$db->setQuery($query);
$users = $db->loadObjectList();
$user = new StdClass();
$uf = $config->userFramework;
$contactCount = 0;
$contactCreated = 0;
$contactMatching = 0;
for ($i = 0; $i < count($users); $i++) {
$user->$id = $users[$i]->$id;
$user->$mail = $users[$i]->$mail;
$user->$name = $users[$i]->$name;
$contactCount++;
if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($user,
$users[$i]->$id,
$users[$i]->$mail,
$uf,
1,
'Individual',
TRUE
)
) {
$contactCreated++;
}
else {
$contactMatching++;
}
if (is_object($match)) {
$match->free();
}
}
return array(
'contactCount' => $contactCount,
'contactMatching' => $contactMatching,
'contactCreated' => $contactCreated,
);
}
}

View file

@ -0,0 +1,127 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
*/
/**
* Soap specific stuff goes here.
*/
class CRM_Utils_System_Soap extends CRM_Utils_System_Base {
/**
* UF container variables.
*/
static $uf = NULL;
static $ufClass = NULL;
/**
* Given a permission string, check for access requirements
*
* @param string $str
* The permission to check.
*
* @return bool
* true if yes, else false
*/
public function checkPermission($str) {
return TRUE;
}
/**
* @inheritDoc
*/
public function url($path = NULL, $query = NULL, $absolute = TRUE, $fragment = NULL) {
if (isset(self::$ufClass)) {
$className = self::$ufClass;
$url = $className::url($path, $query, $absolute, $fragment);
return $url;
}
else {
return NULL;
}
}
/**
* FIXME: Can this override be removed in favor of the parent?
* @inheritDoc
*/
public function postURL($action) {
return NULL;
}
/**
* Set the email address of the user.
*
* @param object $user
* Handle to the user object.
*/
public function setEmail(&$user) {
}
/**
* @inheritDoc
*/
public function authenticate($name, $pass) {
if (isset(self::$ufClass)) {
$className = self::$ufClass;
$result =& $className::authenticate($name, $pass);
return $result;
}
else {
return NULL;
}
}
/**
* Swap the current UF for soap.
*/
public function swapUF() {
$config = CRM_Core_Config::singleton();
self::$uf = $config->userFramework;
$config->userFramework = 'Soap';
self::$ufClass = $config->userFrameworkClass;
$config->userFrameworkClass = 'CRM_Utils_System_Soap';
}
/**
* Get user login URL for hosting CMS (method declared in each CMS system class)
*
* @param string $destination
*
* @throws Exception
*/
public function getLoginURL($destination = '') {
throw new Exception("Method not implemented: getLoginURL");
}
}

View file

@ -0,0 +1,175 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* Helper authentication class for unit tests
*/
class CRM_Utils_System_UnitTests extends CRM_Utils_System_Base {
/**
*/
public function __construct() {
$this->is_drupal = FALSE;
$this->supports_form_extensions = FALSE;
}
/**
* @inheritDoc
*/
public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
$retVal = array(1, 1, 12345);
return $retVal;
}
/**
* Bootstrap the phony CMS.
*
* @param string $name
* Optional username for login.
* @param string $pass
* Optional password for login.
*
* @return bool
*/
public function loadBootStrap($name = NULL, $pass = NULL) {
return TRUE;
}
/**
* @inheritDoc
*/
public function mapConfigToSSL() {
global $base_url;
$base_url = str_replace('http://', 'https://', $base_url);
}
/**
* @inheritDoc
*/
public function postURL($action) {
return NULL;
}
/**
* @inheritDoc
*/
public function url(
$path = NULL,
$query = NULL,
$absolute = FALSE,
$fragment = NULL,
$htmlize = TRUE,
$frontend = FALSE,
$forceBackend = FALSE
) {
$config = CRM_Core_Config::singleton();
static $script = 'index.php';
if (isset($fragment)) {
$fragment = '#' . $fragment;
}
if (!isset($config->useFrameworkRelativeBase)) {
$base = parse_url($config->userFrameworkBaseURL);
$config->useFrameworkRelativeBase = $base['path'];
}
$base = $absolute ? $config->userFrameworkBaseURL : $config->useFrameworkRelativeBase;
$separator = $htmlize ? '&amp;' : '&';
if (!$config->cleanURL) {
if (isset($path)) {
if (isset($query)) {
return $base . $script . '?q=' . $path . $separator . $query . $fragment;
}
else {
return $base . $script . '?q=' . $path . $fragment;
}
}
else {
if (isset($query)) {
return $base . $script . '?' . $query . $fragment;
}
else {
return $base . $fragment;
}
}
}
else {
if (isset($path)) {
if (isset($query)) {
return $base . $path . '?' . $query . $fragment;
}
else {
return $base . $path . $fragment;
}
}
else {
if (isset($query)) {
return $base . $script . '?' . $query . $fragment;
}
else {
return $base . $fragment;
}
}
}
}
/**
* @param $user
*/
public function getUserID($user) {
//FIXME: look here a bit closer when testing UFMatch
// this puts the appropriate values in the session, so
// no need to return anything
CRM_Core_BAO_UFMatch::synchronize($user, TRUE, 'Standalone', 'Individual');
}
/**
* @inheritDoc
*/
public function logout() {
session_destroy();
CRM_Utils_System::setHttpHeader("Location", "index.php");
}
/**
* @inheritDoc
*/
public function getLoginURL($destination = '') {
throw new Exception("Method not implemented: getLoginURL");
}
}

View file

@ -0,0 +1,798 @@
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.7 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2017 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2017
* $Id$
*
*/
/**
* WordPress specific stuff goes here
*/
class CRM_Utils_System_WordPress extends CRM_Utils_System_Base {
/**
*/
public function __construct() {
/**
* deprecated property to check if this is a drupal install. The correct method is to have functions on the UF classes for all UF specific
* functions and leave the codebase oblivious to the type of CMS
* @deprecated
* @var bool
*/
$this->is_drupal = FALSE;
$this->is_wordpress = TRUE;
}
/**
* @inheritDoc
*/
public function setTitle($title, $pageTitle = NULL) {
if (!$pageTitle) {
$pageTitle = $title;
}
// FIXME: Why is this global?
global $civicrm_wp_title;
$civicrm_wp_title = $title;
// yes, set page title, depending on context
$context = civi_wp()->civicrm_context_get();
switch ($context) {
case 'admin':
case 'shortcode':
$template = CRM_Core_Smarty::singleton();
$template->assign('pageTitle', $pageTitle);
}
}
/**
* Moved from CRM_Utils_System_Base
*/
public function getDefaultFileStorage() {
$config = CRM_Core_Config::singleton();
$cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
$cmsPath = $this->cmsRootPath();
$filesPath = CRM_Utils_File::baseFilePath();
$filesRelPath = CRM_Utils_File::relativize($filesPath, $cmsPath);
$filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
return array(
'url' => CRM_Utils_File::addTrailingSlash($filesURL, '/'),
'path' => CRM_Utils_File::addTrailingSlash($filesPath),
);
}
/**
* Determine the location of the CiviCRM source tree.
*
* @return array
* - url: string. ex: "http://example.com/sites/all/modules/civicrm"
* - path: string. ex: "/var/www/sites/all/modules/civicrm"
*/
public function getCiviSourceStorage() {
global $civicrm_root;
// Don't use $config->userFrameworkBaseURL; it has garbage on it.
// More generally, we shouldn't be using $config here.
if (!defined('CIVICRM_UF_BASEURL')) {
throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
}
$cmsPath = $this->cmsRootPath();
// $config = CRM_Core_Config::singleton();
// overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
$cmsUrl = CIVICRM_UF_BASEURL;
if (CRM_Utils_System::isSSL()) {
$cmsUrl = str_replace('http://', 'https://', $cmsUrl);
}
$civiRelPath = CRM_Utils_File::relativize(realpath($civicrm_root), realpath($cmsPath));
$civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
return array(
'url' => CRM_Utils_File::addTrailingSlash($civiUrl, '/'),
'path' => CRM_Utils_File::addTrailingSlash($civicrm_root),
);
}
/**
* @inheritDoc
*/
public function appendBreadCrumb($breadCrumbs) {
$breadCrumb = wp_get_breadcrumb();
if (is_array($breadCrumbs)) {
foreach ($breadCrumbs as $crumbs) {
if (stripos($crumbs['url'], 'id%%')) {
$args = array('cid', 'mid');
foreach ($args as $a) {
$val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
FALSE, NULL, $_GET
);
if ($val) {
$crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
}
}
}
$breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
}
}
$template = CRM_Core_Smarty::singleton();
$template->assign_by_ref('breadcrumb', $breadCrumb);
wp_set_breadcrumb($breadCrumb);
}
/**
* @inheritDoc
*/
public function resetBreadCrumb() {
$bc = array();
wp_set_breadcrumb($bc);
}
/**
* @inheritDoc
*/
public function addHTMLHead($head) {
static $registered = FALSE;
if (!$registered) {
// front-end view
add_action('wp_head', array(__CLASS__, '_showHTMLHead'));
// back-end views
add_action('admin_head', array(__CLASS__, '_showHTMLHead'));
}
CRM_Core_Region::instance('wp_head')->add(array(
'markup' => $head,
));
}
/**
* WP action callback.
*/
public static function _showHTMLHead() {
$region = CRM_Core_Region::instance('wp_head', FALSE);
if ($region) {
echo $region->render('');
}
}
/**
* @inheritDoc
*/
public function mapConfigToSSL() {
global $base_url;
$base_url = str_replace('http://', 'https://', $base_url);
}
/**
* @inheritDoc
*/
public function url(
$path = NULL,
$query = NULL,
$absolute = FALSE,
$fragment = NULL,
$frontend = FALSE,
$forceBackend = FALSE
) {
$config = CRM_Core_Config::singleton();
$script = '';
$separator = '&';
$wpPageParam = '';
$fragment = isset($fragment) ? ('#' . $fragment) : '';
$path = CRM_Utils_String::stripPathChars($path);
//this means wp function we are trying to use is not available,
//so load bootStrap
// FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
if (!function_exists('get_option')) {
$this->loadBootStrap();
}
if ($config->userFrameworkFrontend) {
if (get_option('permalink_structure') != '') {
global $post;
$script = get_permalink($post->ID);
}
// when shortcode is included in page
// also make sure we have valid query object
global $wp_query;
if (method_exists($wp_query, 'get')) {
if (get_query_var('page_id')) {
$wpPageParam = "page_id=" . get_query_var('page_id');
}
elseif (get_query_var('p')) {
// when shortcode is inserted in post
$wpPageParam = "p=" . get_query_var('p');
}
}
}
$base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
if (!isset($path) && !isset($query)) {
// FIXME: This short-circuited codepath is the same as the general one below, except
// in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
// why it's different (and I can only find two obvious use-cases for this codepath,
// of which at least one looks gratuitous). A more ambitious person would simply remove
// this code.
return $base . $fragment;
}
if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) {
$base = $script;
}
$queryParts = array();
if (isset($path)) {
$queryParts[] = 'page=CiviCRM';
$queryParts[] = "q={$path}";
}
if ($wpPageParam) {
$queryParts[] = $wpPageParam;
}
if (isset($query)) {
$queryParts[] = $query;
}
return $base . '?' . implode($separator, $queryParts) . $fragment;
}
/**
* 27-09-2016
* CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
* https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
* For now leave hard coded wp-admin references.
* TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
*
* @param $absolute
* @param $frontend
* @param $forceBackend
*
* @return mixed|null|string
*/
private function getBaseUrl($absolute, $frontend, $forceBackend) {
$config = CRM_Core_Config::singleton();
if ((is_admin() && !$frontend) || $forceBackend) {
return Civi::paths()->getUrl('[wp.backend]/.', $absolute ? 'absolute' : 'relative');
}
else {
return Civi::paths()->getUrl('[wp.frontend]/.', $absolute ? 'absolute' : 'relative');
}
}
/**
* @inheritDoc
*/
public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
$config = CRM_Core_Config::singleton();
if ($loadCMSBootstrap) {
$config->userSystem->loadBootStrap($name, $password);
}
$user = wp_authenticate($name, $password);
if (is_a($user, 'WP_Error')) {
return FALSE;
}
// TODO: need to change this to make sure we matched only one row
CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
$contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
if (!$contactID) {
return FALSE;
}
return array($contactID, $user->data->ID, mt_rand());
}
/**
* FIXME: Do something
*
* @param string $message
*/
public function setMessage($message) {
}
/**
* @param \string $user
*
* @return bool
*/
public function loadUser($user) {
$userdata = get_user_by('login', $user);
if (!$userdata->data->ID) {
return FALSE;
}
$uid = $userdata->data->ID;
wp_set_current_user($uid);
$contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
// lets store contact id and user id in session
$session = CRM_Core_Session::singleton();
$session->set('ufID', $uid);
$session->set('userID', $contactID);
return TRUE;
}
/**
* FIXME: Use CMS-native approach
*/
public function permissionDenied() {
CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
}
/**
* Determine the native ID of the CMS user.
*
* @param string $username
* @return int|NULL
*/
public function getUfId($username) {
$userdata = get_user_by('login', $username);
if (!$userdata->data->ID) {
return NULL;
}
return $userdata->data->ID;
}
/**
* @inheritDoc
*/
public function logout() {
// destroy session
if (session_id()) {
session_destroy();
}
wp_logout();
wp_redirect(wp_login_url());
}
/**
* @inheritDoc
*/
public function getUFLocale() {
// WPML plugin
if (defined('ICL_LANGUAGE_CODE')) {
$language = ICL_LANGUAGE_CODE;
}
// TODO: set language variable for others WordPress plugin
if (isset($language)) {
return CRM_Core_I18n_PseudoConstant::longForShort(substr($language, 0, 2));
}
else {
return NULL;
}
}
/**
* @inheritDoc
*/
public function setUFLocale($civicrm_language) {
// TODO (probably not possible with WPML?)
return TRUE;
}
/**
* Load wordpress bootstrap.
*
* @param string $name
* optional username for login.
* @param string $pass
* optional password for login.
*
* @return bool
*/
public function loadBootStrap($name = NULL, $pass = NULL) {
global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
if (!defined('WP_USE_THEMES')) {
define('WP_USE_THEMES', FALSE);
}
$cmsRootPath = $this->cmsRootPath();
if (!$cmsRootPath) {
CRM_Core_Error::fatal("Could not find the install directory for WordPress");
}
$path = Civi::settings()->get('wpLoadPhp');
if (!empty($path)) {
require_once $path;
}
elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
}
else {
CRM_Core_Error::fatal("Could not find the bootstrap file for WordPress");
}
$wpUserTimezone = get_option('timezone_string');
if ($wpUserTimezone) {
date_default_timezone_set($wpUserTimezone);
CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
}
require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
$uid = CRM_Utils_Array::value('uid', $name);
if (!$uid) {
$name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
$pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
if ($name) {
$uid = wp_authenticate($name, $pass);
if (!$uid) {
if ($throwError) {
echo '<br />Sorry, unrecognized username or password.';
exit();
}
return FALSE;
}
}
}
if ($uid) {
if ($uid instanceof WP_User) {
$account = wp_set_current_user($uid->ID);
}
else {
$account = wp_set_current_user($uid);
}
if ($account && $account->data->ID) {
global $user;
$user = $account;
return TRUE;
}
}
return TRUE;
}
/**
* @param $dir
*
* @return bool
*/
public function validInstallDir($dir) {
$includePath = "$dir/wp-includes";
if (file_exists("$includePath/version.php")) {
return TRUE;
}
return FALSE;
}
/**
* Determine the location of the CMS root.
*
* @return string|NULL
* local file system path to CMS root, or NULL if it cannot be determined
*/
public function cmsRootPath() {
global $civicrm_paths;
if (!empty($civicrm_paths['cms.root']['path'])) {
return $civicrm_paths['cms.root']['path'];
}
$cmsRoot = $valid = NULL;
if (defined('CIVICRM_CMSDIR')) {
if ($this->validInstallDir(CIVICRM_CMSDIR)) {
$cmsRoot = CIVICRM_CMSDIR;
$valid = TRUE;
}
}
else {
$pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME']));
//might be windows installation.
$firstVar = array_shift($pathVars);
if ($firstVar) {
$cmsRoot = $firstVar;
}
//start w/ csm dir search.
foreach ($pathVars as $var) {
$cmsRoot .= "/$var";
if ($this->validInstallDir($cmsRoot)) {
//stop as we found bootstrap.
$valid = TRUE;
break;
}
}
}
return ($valid) ? $cmsRoot : NULL;
}
/**
* @inheritDoc
*/
public function createUser(&$params, $mail) {
$user_data = array(
'ID' => '',
'user_pass' => $params['cms_pass'],
'user_login' => $params['cms_name'],
'user_email' => $params[$mail],
'nickname' => $params['cms_name'],
'role' => get_option('default_role'),
);
if (isset($params['contactID'])) {
$contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
if ($contactType == 'Individual') {
$user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$params['contactID'], 'first_name'
);
$user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
$params['contactID'], 'last_name'
);
}
}
$uid = wp_insert_user($user_data);
$creds = array();
$creds['user_login'] = $params['cms_name'];
$creds['user_password'] = $params['cms_pass'];
$creds['remember'] = TRUE;
$user = wp_signon($creds, FALSE);
wp_new_user_notification($uid, $user_data['user_pass']);
return $uid;
}
/**
* @inheritDoc
*/
public function updateCMSName($ufID, $ufName) {
// CRM-10620
if (function_exists('wp_update_user')) {
$ufID = CRM_Utils_Type::escape($ufID, 'Integer');
$ufName = CRM_Utils_Type::escape($ufName, 'String');
$values = array('ID' => $ufID, 'user_email' => $ufName);
if ($ufID) {
wp_update_user($values);
}
}
}
/**
* @param array $params
* @param $errors
* @param string $emailName
*/
public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
$config = CRM_Core_Config::singleton();
$dao = new CRM_Core_DAO();
$name = $dao->escape(CRM_Utils_Array::value('name', $params));
$email = $dao->escape(CRM_Utils_Array::value('mail', $params));
if (!empty($params['name'])) {
if (!validate_username($params['name'])) {
$errors['cms_name'] = ts("Your username contains invalid characters");
}
elseif (username_exists(sanitize_user($params['name']))) {
$errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', array(1 => $params['name']));
}
}
if (!empty($params['mail'])) {
if (!is_email($params['mail'])) {
$errors[$emailName] = "Your email is invaid";
}
elseif (email_exists($params['mail'])) {
$errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
array(1 => $params['mail'], 2 => wp_lostpassword_url())
);
}
}
}
/**
* @inheritDoc
*/
public function isUserLoggedIn() {
$isloggedIn = FALSE;
if (function_exists('is_user_logged_in')) {
$isloggedIn = is_user_logged_in();
}
return $isloggedIn;
}
/**
* @inheritDoc
*/
public function isUserRegistrationPermitted() {
if (!get_option('users_can_register')) {
return FALSE;
}
return TRUE;
}
/**
* @inheritDoc
*/
public function isPasswordUserGenerated() {
return TRUE;
}
/**
* @return mixed
*/
public function getLoggedInUserObject() {
if (function_exists('is_user_logged_in') &&
is_user_logged_in()
) {
global $current_user;
}
return $current_user;
}
/**
* @inheritDoc
*/
public function getLoggedInUfID() {
$ufID = NULL;
$current_user = $this->getLoggedInUserObject();
return isset($current_user->ID) ? $current_user->ID : NULL;
}
/**
* @inheritDoc
*/
public function getLoggedInUniqueIdentifier() {
$user = $this->getLoggedInUserObject();
return $this->getUniqueIdentifierFromUserObject($user);
}
/**
* Get User ID from UserFramework system (Joomla)
* @param object $user
* Object as described by the CMS.
*
* @return int|null
*/
public function getUserIDFromUserObject($user) {
return !empty($user->ID) ? $user->ID : NULL;
}
/**
* @inheritDoc
*/
public function getUniqueIdentifierFromUserObject($user) {
return empty($user->user_email) ? NULL : $user->user_email;
}
/**
* @inheritDoc
*/
public function getLoginURL($destination = '') {
$config = CRM_Core_Config::singleton();
$loginURL = wp_login_url();
return $loginURL;
}
/**
* FIXME: Do something.
*
* @param \CRM_Core_Form $form
*
* @return NULL|string
*/
public function getLoginDestination(&$form) {
return NULL;
}
/**
* @inheritDoc
*/
public function getVersion() {
if (function_exists('get_bloginfo')) {
return get_bloginfo('version', 'display');
}
else {
return 'Unknown';
}
}
/**
* @inheritDoc
*/
public function getTimeZoneString() {
return get_option('timezone_string');
}
/**
* @inheritDoc
*/
public function getUserRecordUrl($contactID) {
$uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
if (CRM_Core_Session::singleton()
->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(array('cms:administer users'))
) {
return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
}
}
/**
* Append WP js to coreResourcesList.
*
* @param array $list
*/
public function appendCoreResources(&$list) {
$list[] = 'js/crm.wordpress.js';
}
/**
* @inheritDoc
*/
public function synchronizeUsers() {
$config = CRM_Core_Config::singleton();
if (PHP_SAPI != 'cli') {
set_time_limit(300);
}
$id = 'ID';
$mail = 'user_email';
$uf = $config->userFramework;
$contactCount = 0;
$contactCreated = 0;
$contactMatching = 0;
global $wpdb;
$wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
foreach ($wpUserIds as $wpUserId) {
$wpUserData = get_userdata($wpUserId);
$contactCount++;
if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData,
$wpUserData->$id,
$wpUserData->$mail,
$uf,
1,
'Individual',
TRUE
)
) {
$contactCreated++;
}
else {
$contactMatching++;
}
if (is_object($match)) {
$match->free();
}
}
return array(
'contactCount' => $contactCount,
'contactMatching' => $contactMatching,
'contactCreated' => $contactCreated,
);
}
}