dev/core/1412 CiviMail sent via wp-cli and cron mangles mailing urls on WP
[civicrm-core.git] / CRM / Utils / System / WordPress.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
6b83d5bd 6 | Copyright CiviCRM LLC (c) 2004-2019 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
6b83d5bd 31 * @copyright CiviCRM LLC (c) 2004-2019
6a488035
TO
32 * $Id$
33 *
34 */
35
36/**
37 * WordPress specific stuff goes here
38 */
39class CRM_Utils_System_WordPress extends CRM_Utils_System_Base {
6714d8d2 40
bb3a214a 41 /**
bb3a214a 42 */
00be9182 43 public function __construct() {
4caaa696
EM
44 /**
45 * 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
46 * functions and leave the codebase oblivious to the type of CMS
47 * @deprecated
48 * @var bool
49 */
6a488035 50 $this->is_drupal = FALSE;
fe17e8d1 51 $this->is_wordpress = TRUE;
6a488035
TO
52 }
53
54 /**
17f443df 55 * @inheritDoc
6a488035 56 */
00be9182 57 public function setTitle($title, $pageTitle = NULL) {
6a488035
TO
58 if (!$pageTitle) {
59 $pageTitle = $title;
60 }
1beae3b1 61
17f443df
CW
62 // FIXME: Why is this global?
63 global $civicrm_wp_title;
64 $civicrm_wp_title = $title;
1beae3b1 65
17f443df
CW
66 // yes, set page title, depending on context
67 $context = civi_wp()->civicrm_context_get();
68 switch ($context) {
69 case 'admin':
70 case 'shortcode':
71 $template = CRM_Core_Smarty::singleton();
72 $template->assign('pageTitle', $pageTitle);
6a488035
TO
73 }
74 }
75
7ba2c8ad
KC
76 /**
77 * Moved from CRM_Utils_System_Base
78 */
79 public function getDefaultFileStorage() {
8ce9d9d6
TO
80 $config = CRM_Core_Config::singleton();
81 $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
82 $cmsPath = $this->cmsRootPath();
83 $filesPath = CRM_Utils_File::baseFilePath();
84 $filesRelPath = CRM_Utils_File::relativize($filesPath, $cmsPath);
85 $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /');
be2fb01f 86 return [
8ce9d9d6
TO
87 'url' => CRM_Utils_File::addTrailingSlash($filesURL, '/'),
88 'path' => CRM_Utils_File::addTrailingSlash($filesPath),
be2fb01f 89 ];
8ce9d9d6
TO
90 }
91
92 /**
93 * Determine the location of the CiviCRM source tree.
94 *
95 * @return array
96 * - url: string. ex: "http://example.com/sites/all/modules/civicrm"
97 * - path: string. ex: "/var/www/sites/all/modules/civicrm"
98 */
99 public function getCiviSourceStorage() {
7ba2c8ad 100 global $civicrm_root;
7ba2c8ad 101
8ce9d9d6
TO
102 // Don't use $config->userFrameworkBaseURL; it has garbage on it.
103 // More generally, we shouldn't be using $config here.
104 if (!defined('CIVICRM_UF_BASEURL')) {
105 throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL');
7ba2c8ad 106 }
8ce9d9d6
TO
107
108 $cmsPath = $this->cmsRootPath();
109
110 // $config = CRM_Core_Config::singleton();
111 // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE);
112 $cmsUrl = CIVICRM_UF_BASEURL;
113 if (CRM_Utils_System::isSSL()) {
114 $cmsUrl = str_replace('http://', 'https://', $cmsUrl);
7ba2c8ad 115 }
d8182404 116 $civiRelPath = CRM_Utils_File::relativize(realpath($civicrm_root), realpath($cmsPath));
8ce9d9d6 117 $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /');
be2fb01f 118 return [
8ce9d9d6
TO
119 'url' => CRM_Utils_File::addTrailingSlash($civiUrl, '/'),
120 'path' => CRM_Utils_File::addTrailingSlash($civicrm_root),
be2fb01f 121 ];
7ba2c8ad
KC
122 }
123
6a488035 124 /**
17f443df 125 * @inheritDoc
6a488035 126 */
00be9182 127 public function appendBreadCrumb($breadCrumbs) {
6a488035
TO
128 $breadCrumb = wp_get_breadcrumb();
129
130 if (is_array($breadCrumbs)) {
131 foreach ($breadCrumbs as $crumbs) {
132 if (stripos($crumbs['url'], 'id%%')) {
be2fb01f 133 $args = ['cid', 'mid'];
6a488035
TO
134 foreach ($args as $a) {
135 $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject,
136 FALSE, NULL, $_GET
137 );
138 if ($val) {
139 $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']);
140 }
141 }
142 }
143 $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>";
144 }
145 }
146
147 $template = CRM_Core_Smarty::singleton();
148 $template->assign_by_ref('breadcrumb', $breadCrumb);
149 wp_set_breadcrumb($breadCrumb);
150 }
151
152 /**
17f443df 153 * @inheritDoc
6a488035 154 */
00be9182 155 public function resetBreadCrumb() {
be2fb01f 156 $bc = [];
6a488035
TO
157 wp_set_breadcrumb($bc);
158 }
159
160 /**
17f443df 161 * @inheritDoc
6a488035 162 */
00be9182 163 public function addHTMLHead($head) {
6a488035
TO
164 static $registered = FALSE;
165 if (!$registered) {
166 // front-end view
be2fb01f 167 add_action('wp_head', [__CLASS__, '_showHTMLHead']);
6a488035 168 // back-end views
be2fb01f 169 add_action('admin_head', [__CLASS__, '_showHTMLHead']);
6a488035 170 }
be2fb01f 171 CRM_Core_Region::instance('wp_head')->add([
6a488035 172 'markup' => $head,
be2fb01f 173 ]);
6a488035
TO
174 }
175
17f443df 176 /**
fe482240 177 * WP action callback.
17f443df 178 */
00be9182 179 public static function _showHTMLHead() {
6a488035
TO
180 $region = CRM_Core_Region::instance('wp_head', FALSE);
181 if ($region) {
182 echo $region->render('');
183 }
184 }
185
186 /**
17f443df 187 * @inheritDoc
6a488035 188 */
00be9182 189 public function mapConfigToSSL() {
6a488035
TO
190 global $base_url;
191 $base_url = str_replace('http://', 'https://', $base_url);
192 }
193
194 /**
17f443df 195 * @inheritDoc
6a488035 196 */
408b79bf 197 public function url(
6a488035
TO
198 $path = NULL,
199 $query = NULL,
200 $absolute = FALSE,
201 $fragment = NULL,
6a488035
TO
202 $frontend = FALSE,
203 $forceBackend = FALSE
204 ) {
353ffa53
TO
205 $config = CRM_Core_Config::singleton();
206 $script = '';
c80e2dbf 207 $separator = '&';
353ffa53 208 $wpPageParam = '';
887f5d81 209 $fragment = isset($fragment) ? ('#' . $fragment) : '';
6a488035
TO
210
211 $path = CRM_Utils_String::stripPathChars($path);
df17aa21 212 $basepage = FALSE;
6a488035
TO
213
214 //this means wp function we are trying to use is not available,
215 //so load bootStrap
d8182404 216 // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap
6a488035 217 if (!function_exists('get_option')) {
d8182404 218 $this->loadBootStrap();
6a488035 219 }
df17aa21 220
6a488035 221 if ($config->userFrameworkFrontend) {
df17aa21 222 global $post;
887f5d81 223 if (get_option('permalink_structure') != '') {
6a488035
TO
224 $script = get_permalink($post->ID);
225 }
df17aa21
CW
226 if ($config->wpBasePage == $post->post_name) {
227 $basepage = TRUE;
228 }
01aca362 229 // when shortcode is included in page
6a488035 230 // also make sure we have valid query object
df17aa21 231 // FIXME: $wpPageParam has no effect and is only set on the *basepage*
6a488035 232 global $wp_query;
df17aa21 233 if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) {
6a488035 234 if (get_query_var('page_id')) {
887f5d81 235 $wpPageParam = "page_id=" . get_query_var('page_id');
6a488035
TO
236 }
237 elseif (get_query_var('p')) {
238 // when shortcode is inserted in post
887f5d81 239 $wpPageParam = "p=" . get_query_var('p');
6a488035
TO
240 }
241 }
242 }
243
887f5d81
TO
244 $base = $this->getBaseUrl($absolute, $frontend, $forceBackend);
245
246 if (!isset($path) && !isset($query)) {
247 // FIXME: This short-circuited codepath is the same as the general one below, except
248 // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know
249 // why it's different (and I can only find two obvious use-cases for this codepath,
250 // of which at least one looks gratuitous). A more ambitious person would simply remove
251 // this code.
252 return $base . $fragment;
253 }
254
255 if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) {
256 $base = $script;
6a488035
TO
257 }
258
be2fb01f 259 $queryParts = [];
df17aa21 260
df17aa21
CW
261 if (
262 // not using clean URLs
263 !$config->cleanURL
264 // requesting an admin URL
265 || ((is_admin() && !$frontend) || $forceBackend)
266 // is shortcode
267 || (!$basepage && $script != '')
268 ) {
269
270 // pre-existing logic
271 if (isset($path)) {
272 $queryParts[] = 'page=CiviCRM';
cdef34e0 273 $queryParts[] = 'q=' . rawurlencode($path);
df17aa21
CW
274 }
275 if ($wpPageParam) {
276 $queryParts[] = $wpPageParam;
277 }
ffa62912 278 if (!empty($query)) {
df17aa21
CW
279 $queryParts[] = $query;
280 }
281
282 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
283
887f5d81 284 }
df17aa21
CW
285 else {
286
287 // clean URLs
288 if (isset($path)) {
289 $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/';
290 }
291 if (isset($query)) {
292 $query = ltrim($query, '=?&');
293 $queryParts[] = $query;
294 }
295
296 if (!empty($queryParts)) {
297 $final = $base . '?' . implode($separator, $queryParts) . $fragment;
298 }
299 else {
300 $final = $base . $fragment;
301 }
302
6a488035
TO
303 }
304
df17aa21 305 return $final;
887f5d81
TO
306 }
307
bb3a214a 308 /**
f553d1ea
KC
309 * 27-09-2016
310 * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory
311 * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues
312 * For now leave hard coded wp-admin references.
313 * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url
314 *
bb3a214a
EM
315 * @param $absolute
316 * @param $frontend
317 * @param $forceBackend
318 *
319 * @return mixed|null|string
320 */
887f5d81 321 private function getBaseUrl($absolute, $frontend, $forceBackend) {
353ffa53 322 $config = CRM_Core_Config::singleton();
6a488035 323 if ((is_admin() && !$frontend) || $forceBackend) {
f553d1ea 324 return Civi::paths()->getUrl('[wp.backend]/.', $absolute ? 'absolute' : 'relative');
6a488035 325 }
f553d1ea
KC
326 else {
327 return Civi::paths()->getUrl('[wp.frontend]/.', $absolute ? 'absolute' : 'relative');
36b820ae 328 }
01aca362 329 }
6a488035
TO
330
331 /**
17f443df 332 * @inheritDoc
6a488035 333 */
00be9182 334 public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
6a488035
TO
335 $config = CRM_Core_Config::singleton();
336
337 if ($loadCMSBootstrap) {
9ba02e3e
TO
338 $config->userSystem->loadBootStrap([
339 'name' => $name,
340 'pass' => $password,
341 ]);
6a488035
TO
342 }
343
344 $user = wp_authenticate($name, $password);
345 if (is_a($user, 'WP_Error')) {
346 return FALSE;
347 }
348
17f443df 349 // TODO: need to change this to make sure we matched only one row
6a488035
TO
350
351 CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress');
352 $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID);
353 if (!$contactID) {
354 return FALSE;
355 }
be2fb01f 356 return [$contactID, $user->data->ID, mt_rand()];
6a488035
TO
357 }
358
359 /**
17f443df 360 * FIXME: Do something
ea3ddccf 361 *
362 * @param string $message
6a488035 363 */
00be9182 364 public function setMessage($message) {
6a488035
TO
365 }
366
bb3a214a 367 /**
b596c3e9 368 * @param \string $user
ea3ddccf 369 *
370 * @return bool
bb3a214a 371 */
e7292422 372 public function loadUser($user) {
b596c3e9 373 $userdata = get_user_by('login', $user);
374 if (!$userdata->data->ID) {
7ca9cd52 375 return FALSE;
b596c3e9 376 }
377
378 $uid = $userdata->data->ID;
379 wp_set_current_user($uid);
380 $contactID = CRM_Core_BAO_UFMatch::getContactId($uid);
381
382 // lets store contact id and user id in session
383 $session = CRM_Core_Session::singleton();
384 $session->set('ufID', $uid);
385 $session->set('userID', $contactID);
e7292422 386 return TRUE;
6a488035
TO
387 }
388
17f443df
CW
389 /**
390 * FIXME: Use CMS-native approach
391 */
00be9182 392 public function permissionDenied() {
0499b0ad 393 CRM_Core_Error::fatal(ts('You do not have permission to access this page.'));
6a488035
TO
394 }
395
8ee9bea9
SL
396 /**
397 * Determine the native ID of the CMS user.
398 *
399 * @param string $username
e97c66ff 400 *
401 * @return int|null
8ee9bea9
SL
402 */
403 public function getUfId($username) {
404 $userdata = get_user_by('login', $username);
405 if (!$userdata->data->ID) {
406 return NULL;
407 }
408 return $userdata->data->ID;
409 }
410
17f443df
CW
411 /**
412 * @inheritDoc
413 */
00be9182 414 public function logout() {
6a488035
TO
415 // destroy session
416 if (session_id()) {
417 session_destroy();
418 }
419 wp_logout();
420 wp_redirect(wp_login_url());
421 }
422
6a488035 423 /**
17f443df 424 * @inheritDoc
6a488035 425 */
00be9182 426 public function getUFLocale() {
cba2601a
SV
427 // Polylang plugin
428 if (function_exists('pll_current_language')) {
429 $language = pll_current_language();
430 }
19780d2b 431 // WPML plugin
cba2601a 432 elseif (defined('ICL_LANGUAGE_CODE')) {
19780d2b
DL
433 $language = ICL_LANGUAGE_CODE;
434 }
435
436 // TODO: set language variable for others WordPress plugin
437
5a44748c 438 if (!empty($language)) {
19780d2b 439 return CRM_Core_I18n_PseudoConstant::longForShort(substr($language, 0, 2));
0db6c3e1
TO
440 }
441 else {
19780d2b
DL
442 return NULL;
443 }
6a488035
TO
444 }
445
fd1f3a26
SV
446 /**
447 * @inheritDoc
448 */
449 public function setUFLocale($civicrm_language) {
450 // TODO (probably not possible with WPML?)
451 return TRUE;
452 }
453
6a488035 454 /**
fe482240 455 * Load wordpress bootstrap.
6a488035 456 *
9ba02e3e
TO
457 * @param array $params
458 * Optional credentials
459 * - name: string, cms username
460 * - pass: string, cms password
6714d8d2
SL
461 * @param bool $loadUser
462 * @param bool $throwError
463 * @param mixed $realPath
f4aaa82a
EM
464 *
465 * @return bool
6a488035 466 */
be2fb01f 467 public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) {
05fcde76 468 global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user;
6a488035 469
9ba02e3e
TO
470 $name = CRM_Utils_Array::value('name', $params);
471 $pass = CRM_Utils_Array::value('pass', $params);
9ba02e3e 472
7a44e49f 473 if (!defined('WP_USE_THEMES')) {
c5f77355 474 define('WP_USE_THEMES', FALSE);
7a44e49f 475 }
6a488035
TO
476
477 $cmsRootPath = $this->cmsRootPath();
478 if (!$cmsRootPath) {
479 CRM_Core_Error::fatal("Could not find the install directory for WordPress");
480 }
aaffa79f 481 $path = Civi::settings()->get('wpLoadPhp');
b299b1cc 482 if (!empty($path)) {
35da5d8d 483 require_once $path;
b299b1cc
KC
484 }
485 elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) {
35da5d8d 486 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php';
b299b1cc
KC
487 }
488 else {
489 CRM_Core_Error::fatal("Could not find the bootstrap file for WordPress");
35da5d8d 490 }
6491539b
DL
491 $wpUserTimezone = get_option('timezone_string');
492 if ($wpUserTimezone) {
493 date_default_timezone_set($wpUserTimezone);
494 CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone();
495 }
e7292422 496 require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php';
f25b78a4 497 $uid = CRM_Utils_Array::value('uid', $params);
17763922
WA
498 if (!$uid) {
499 $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST));
500 $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST));
501 if ($name) {
d8182404 502 $uid = wp_authenticate($name, $pass);
17763922
WA
503 if (!$uid) {
504 if ($throwError) {
505 echo '<br />Sorry, unrecognized username or password.';
506 exit();
507 }
508 return FALSE;
509 }
510 }
511 }
fe1e7958 512 if ($uid) {
a4111333
CW
513 if ($uid instanceof WP_User) {
514 $account = wp_set_current_user($uid->ID);
c5f77355
CW
515 }
516 else {
a4111333
CW
517 $account = wp_set_current_user($uid);
518 }
fe1e7958 519 if ($account && $account->data->ID) {
520 global $user;
521 $user = $account;
522 return TRUE;
523 }
524 }
e7292422 525 return TRUE;
6a488035
TO
526 }
527
bb3a214a
EM
528 /**
529 * @param $dir
530 *
531 * @return bool
532 */
00be9182 533 public function validInstallDir($dir) {
dfbcf0b7 534 $includePath = "$dir/wp-includes";
468176f6 535 if (@file_exists("$includePath/version.php")) {
dfbcf0b7
DL
536 return TRUE;
537 }
538 return FALSE;
539 }
540
bb3a214a
EM
541 /**
542 * Determine the location of the CMS root.
543 *
72b3a70c
CW
544 * @return string|NULL
545 * local file system path to CMS root, or NULL if it cannot be determined
bb3a214a 546 */
00be9182 547 public function cmsRootPath() {
a93a0366
TO
548 global $civicrm_paths;
549 if (!empty($civicrm_paths['cms.root']['path'])) {
550 return $civicrm_paths['cms.root']['path'];
551 }
552
6a488035 553 $cmsRoot = $valid = NULL;
dfbcf0b7
DL
554 if (defined('CIVICRM_CMSDIR')) {
555 if ($this->validInstallDir(CIVICRM_CMSDIR)) {
556 $cmsRoot = CIVICRM_CMSDIR;
557 $valid = TRUE;
558 }
6a488035 559 }
dfbcf0b7 560 else {
57811df8
KC
561 $setting = Civi::settings()->get('wpLoadPhp');
562 $path = str_replace('wp-load.php', '', $setting);
563 $cmsRoot = rtrim($path, '/\\');
564 $valid = TRUE;
6a488035
TO
565 }
566
567 return ($valid) ? $cmsRoot : NULL;
568 }
569
bb3a214a 570 /**
17f443df 571 * @inheritDoc
bb3a214a 572 */
00be9182 573 public function createUser(&$params, $mail) {
be2fb01f 574 $user_data = [
6a488035
TO
575 'ID' => '',
576 'user_pass' => $params['cms_pass'],
577 'user_login' => $params['cms_name'],
578 'user_email' => $params[$mail],
579 'nickname' => $params['cms_name'],
580 'role' => get_option('default_role'),
be2fb01f 581 ];
6a488035
TO
582 if (isset($params['contactID'])) {
583 $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']);
584 if ($contactType == 'Individual') {
585 $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
586 $params['contactID'], 'first_name'
587 );
588 $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
589 $params['contactID'], 'last_name'
590 );
591 }
592 }
593
594 $uid = wp_insert_user($user_data);
595
be2fb01f 596 $creds = [];
6a488035
TO
597 $creds['user_login'] = $params['cms_name'];
598 $creds['user_password'] = $params['cms_pass'];
599 $creds['remember'] = TRUE;
600 $user = wp_signon($creds, FALSE);
601
602 wp_new_user_notification($uid, $user_data['user_pass']);
603 return $uid;
604 }
605
f4aaa82a 606 /**
17f443df 607 * @inheritDoc
6a488035 608 */
00be9182 609 public function updateCMSName($ufID, $ufName) {
6a488035
TO
610 // CRM-10620
611 if (function_exists('wp_update_user')) {
353ffa53 612 $ufID = CRM_Utils_Type::escape($ufID, 'Integer');
6a488035
TO
613 $ufName = CRM_Utils_Type::escape($ufName, 'String');
614
be2fb01f 615 $values = ['ID' => $ufID, 'user_email' => $ufName];
481a74f4
TO
616 if ($ufID) {
617 wp_update_user($values);
6a488035
TO
618 }
619 }
620 }
621
bb3a214a 622 /**
c490a46a 623 * @param array $params
bb3a214a
EM
624 * @param $errors
625 * @param string $emailName
626 */
00be9182 627 public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') {
6a488035
TO
628 $config = CRM_Core_Config::singleton();
629
353ffa53
TO
630 $dao = new CRM_Core_DAO();
631 $name = $dao->escape(CRM_Utils_Array::value('name', $params));
6a488035
TO
632 $email = $dao->escape(CRM_Utils_Array::value('mail', $params));
633
a7488080 634 if (!empty($params['name'])) {
6a488035
TO
635 if (!validate_username($params['name'])) {
636 $errors['cms_name'] = ts("Your username contains invalid characters");
637 }
638 elseif (username_exists(sanitize_user($params['name']))) {
be2fb01f 639 $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]);
6a488035
TO
640 }
641 }
642
a7488080 643 if (!empty($params['mail'])) {
6a488035
TO
644 if (!is_email($params['mail'])) {
645 $errors[$emailName] = "Your email is invaid";
646 }
647 elseif (email_exists($params['mail'])) {
db18d815 648 $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>',
be2fb01f 649 [1 => $params['mail'], 2 => wp_lostpassword_url()]
6a488035
TO
650 );
651 }
652 }
653 }
654
655 /**
17f443df 656 * @inheritDoc
6a488035
TO
657 */
658 public function isUserLoggedIn() {
659 $isloggedIn = FALSE;
660 if (function_exists('is_user_logged_in')) {
661 $isloggedIn = is_user_logged_in();
662 }
663
664 return $isloggedIn;
665 }
666
8caad0ce 667 /**
668 * @inheritDoc
669 */
670 public function isUserRegistrationPermitted() {
671 if (!get_option('users_can_register')) {
672 return FALSE;
673 }
674 return TRUE;
675 }
676
63df6889
HD
677 /**
678 * @inheritDoc
679 */
1a6630be 680 public function isPasswordUserGenerated() {
63df6889
HD
681 return TRUE;
682 }
683
bb3a214a
EM
684 /**
685 * @return mixed
686 */
00be9182 687 public function getLoggedInUserObject() {
2b617cb0 688 if (function_exists('is_user_logged_in') &&
353ffa53
TO
689 is_user_logged_in()
690 ) {
2b617cb0
EM
691 global $current_user;
692 }
693 return $current_user;
694 }
353ffa53 695
6a488035 696 /**
17f443df 697 * @inheritDoc
6a488035
TO
698 */
699 public function getLoggedInUfID() {
700 $ufID = NULL;
2b617cb0
EM
701 $current_user = $this->getLoggedInUserObject();
702 return isset($current_user->ID) ? $current_user->ID : NULL;
703 }
704
705 /**
17f443df 706 * @inheritDoc
2b617cb0 707 */
00be9182 708 public function getLoggedInUniqueIdentifier() {
2b617cb0
EM
709 $user = $this->getLoggedInUserObject();
710 return $this->getUniqueIdentifierFromUserObject($user);
6a488035
TO
711 }
712
32998c82
EM
713 /**
714 * Get User ID from UserFramework system (Joomla)
77855840
TO
715 * @param object $user
716 * Object as described by the CMS.
72b3a70c
CW
717 *
718 * @return int|null
32998c82 719 */
00be9182 720 public function getUserIDFromUserObject($user) {
32998c82
EM
721 return !empty($user->ID) ? $user->ID : NULL;
722 }
723
2b617cb0 724 /**
17f443df 725 * @inheritDoc
2b617cb0 726 */
00be9182 727 public function getUniqueIdentifierFromUserObject($user) {
2b617cb0
EM
728 return empty($user->user_email) ? NULL : $user->user_email;
729 }
730
6a488035 731 /**
17f443df 732 * @inheritDoc
6a488035
TO
733 */
734 public function getLoginURL($destination = '') {
735 $config = CRM_Core_Config::singleton();
153155d3 736 $loginURL = wp_login_url();
6a488035
TO
737 return $loginURL;
738 }
739
bb3a214a 740 /**
ad37ac8e 741 * FIXME: Do something.
742 *
743 * @param \CRM_Core_Form $form
744 *
745 * @return NULL|string
bb3a214a 746 */
6a488035 747 public function getLoginDestination(&$form) {
408b79bf 748 return NULL;
6a488035
TO
749 }
750
751 /**
17f443df 752 * @inheritDoc
6a488035 753 */
00be9182 754 public function getVersion() {
6a488035
TO
755 if (function_exists('get_bloginfo')) {
756 return get_bloginfo('version', 'display');
757 }
758 else {
759 return 'Unknown';
760 }
761 }
6491539b
DL
762
763 /**
17f443df 764 * @inheritDoc
6491539b 765 */
00be9182 766 public function getTimeZoneString() {
6491539b
DL
767 return get_option('timezone_string');
768 }
59f97da6
EM
769
770 /**
17f443df 771 * @inheritDoc
59f97da6 772 */
00be9182 773 public function getUserRecordUrl($contactID) {
59f97da6 774 $uid = CRM_Core_BAO_UFMatch::getUFId($contactID);
353ffa53 775 if (CRM_Core_Session::singleton()
6714d8d2 776 ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(['cms:administer users'])
353ffa53 777 ) {
59f97da6
EM
778 return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid;
779 }
780 }
96025800 781
469d8dab
CW
782 /**
783 * Append WP js to coreResourcesList.
ad37ac8e 784 *
303017a1 785 * @param \Civi\Core\Event\GenericHookEvent $e
469d8dab 786 */
303017a1
CW
787 public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) {
788 $e->list[] = 'js/crm.wordpress.js';
469d8dab
CW
789 }
790
03d5592a
CW
791 /**
792 * @inheritDoc
62c20d1e
CW
793 */
794 public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) {
795 // Set menubar breakpoint to match WP admin theme
796 if ($e->asset == 'crm-menubar.css') {
797 $e->params['breakpoint'] = 783;
798 }
799 }
800
801 /**
802 * @inheritDoc
03d5592a
CW
803 */
804 public function synchronizeUsers() {
805 $config = CRM_Core_Config::singleton();
806 if (PHP_SAPI != 'cli') {
807 set_time_limit(300);
808 }
809 $id = 'ID';
810 $mail = 'user_email';
811
812 $uf = $config->userFramework;
813 $contactCount = 0;
814 $contactCreated = 0;
815 $contactMatching = 0;
816
817 global $wpdb;
818 $wpUserIds = $wpdb->get_col("SELECT $wpdb->users.ID FROM $wpdb->users");
819
820 foreach ($wpUserIds as $wpUserId) {
821 $wpUserData = get_userdata($wpUserId);
822 $contactCount++;
823 if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData,
824 $wpUserData->$id,
825 $wpUserData->$mail,
826 $uf,
827 1,
828 'Individual',
829 TRUE
830 )
831 ) {
832 $contactCreated++;
833 }
834 else {
835 $contactMatching++;
836 }
03d5592a
CW
837 }
838
be2fb01f 839 return [
03d5592a
CW
840 'contactCount' => $contactCount,
841 'contactMatching' => $contactMatching,
842 'contactCreated' => $contactCreated,
be2fb01f 843 ];
03d5592a
CW
844 }
845
79dd7fe9 846 /**
46dddc5c
SL
847 * Send an HTTP Response base on PSR HTTP RespnseInterface response.
848 *
849 * @param \Psr\Http\Message\ResponseInterface $response
79dd7fe9 850 */
46dddc5c
SL
851 public function sendResponse(\Psr\Http\Message\ResponseInterface $response) {
852 // use WordPress function status_header to ensure 404 response is sent
853 status_header($response->getStatusCode());
90f6c8df
SL
854 foreach ($response->getHeaders() as $name => $values) {
855 CRM_Utils_System::setHttpHeader($name, implode(', ', (array) $values));
79dd7fe9 856 }
46dddc5c
SL
857 echo $response->getBody();
858 CRM_Utils_System::civiExit();
79dd7fe9
SL
859 }
860
6a488035 861}