Commit | Line | Data |
---|---|---|
6a488035 TO |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
bc77d7c0 | 4 | | Copyright CiviCRM LLC. All rights reserved. | |
6a488035 | 5 | | | |
bc77d7c0 TO |
6 | | This work is published under the GNU AGPLv3 license with some | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
6a488035 | 9 | +--------------------------------------------------------------------+ |
d25dd0ee | 10 | */ |
6a488035 TO |
11 | |
12 | /** | |
13 | * | |
14 | * @package CRM | |
ca5cec67 | 15 | * @copyright CiviCRM LLC https://civicrm.org/licensing |
6a488035 TO |
16 | */ |
17 | ||
18 | /** | |
19 | * WordPress specific stuff goes here | |
20 | */ | |
21 | class CRM_Utils_System_WordPress extends CRM_Utils_System_Base { | |
6714d8d2 | 22 | |
11eed110 TO |
23 | /** |
24 | * Get a normalized version of the wpBasePage. | |
25 | */ | |
26 | public static function getBasePage() { | |
1e2423ed | 27 | return strtolower(rtrim(Civi::settings()->get('wpBasePage'), '/')); |
11eed110 TO |
28 | } |
29 | ||
bb3a214a | 30 | /** |
bb3a214a | 31 | */ |
00be9182 | 32 | public function __construct() { |
4caaa696 EM |
33 | /** |
34 | * 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 | |
35 | * functions and leave the codebase oblivious to the type of CMS | |
36 | * @deprecated | |
37 | * @var bool | |
38 | */ | |
6a488035 | 39 | $this->is_drupal = FALSE; |
fe17e8d1 | 40 | $this->is_wordpress = TRUE; |
6a488035 TO |
41 | } |
42 | ||
9509977f TO |
43 | public function initialize() { |
44 | parent::initialize(); | |
45 | $this->registerPathVars(); | |
46 | } | |
47 | ||
48 | /** | |
49 | * Specify the default computation for various paths/URLs. | |
50 | */ | |
51 | protected function registerPathVars():void { | |
716bdc94 TO |
52 | $isNormalBoot = function_exists('get_option'); |
53 | if ($isNormalBoot) { | |
54 | // Normal mode - CMS boots first, then calls Civi. "Normal" web pages and newer extern routes. | |
55 | // To simplify the code-paths, some items are re-registered with WP-specific functions. | |
56 | $cmsRoot = function() { | |
9509977f | 57 | return [ |
716bdc94 TO |
58 | 'path' => untrailingslashit(ABSPATH), |
59 | 'url' => home_url(), | |
9509977f | 60 | ]; |
716bdc94 TO |
61 | }; |
62 | Civi::paths()->register('cms', $cmsRoot); | |
63 | Civi::paths()->register('cms.root', $cmsRoot); | |
716bdc94 TO |
64 | Civi::paths()->register('civicrm.root', function () { |
65 | return [ | |
66 | 'path' => CIVICRM_PLUGIN_DIR . 'civicrm' . DIRECTORY_SEPARATOR, | |
67 | 'url' => CIVICRM_PLUGIN_URL . 'civicrm/', | |
68 | ]; | |
69 | }); | |
70 | Civi::paths()->register('wp.frontend.base', function () { | |
71 | return [ | |
72 | 'url' => home_url('/'), | |
73 | ]; | |
74 | }); | |
75 | Civi::paths()->register('wp.frontend', function () { | |
76 | $config = CRM_Core_Config::singleton(); | |
77 | $basepage = get_page_by_path($config->wpBasePage); | |
78 | return [ | |
79 | 'url' => get_permalink($basepage->ID), | |
80 | ]; | |
81 | }); | |
82 | Civi::paths()->register('wp.backend.base', function () { | |
83 | return [ | |
84 | 'url' => admin_url(), | |
85 | ]; | |
86 | }); | |
87 | Civi::paths()->register('wp.backend', function() { | |
88 | return [ | |
89 | 'url' => admin_url('admin.php'), | |
90 | ]; | |
91 | }); | |
ad428bcd SL |
92 | Civi::paths()->register('civicrm.files', function () { |
93 | $upload_dir = wp_get_upload_dir(); | |
94 | ||
95 | $old = CRM_Core_Config::singleton()->userSystem->getDefaultFileStorage(); | |
96 | $new = [ | |
97 | 'path' => $upload_dir['basedir'] . DIRECTORY_SEPARATOR . 'civicrm' . DIRECTORY_SEPARATOR, | |
98 | 'url' => $upload_dir['baseurl'] . '/civicrm/', | |
99 | ]; | |
100 | ||
101 | if ($old['path'] === $new['path']) { | |
102 | return $new; | |
103 | } | |
104 | ||
105 | $oldExists = file_exists($old['path']); | |
106 | $newExists = file_exists($new['path']); | |
107 | ||
108 | if ($oldExists && !$newExists) { | |
109 | return $old; | |
110 | } | |
111 | elseif (!$oldExists && $newExists) { | |
112 | return $new; | |
113 | } | |
114 | elseif (!$oldExists && !$newExists) { | |
115 | // neither exists. but that's ok. we're in one of these two cases: | |
116 | // - we're just starting installation... which will get sorted in a moment | |
117 | // when someone calls mkdir(). | |
118 | // - we're running a bespoke setup... which will get sorted in a moment | |
119 | // by applying $civicrm_paths. | |
120 | return $new; | |
121 | } | |
122 | elseif ($oldExists && $newExists) { | |
123 | // situation ambiguous. encourage admin to set value explicitly. | |
124 | if (!isset($GLOBALS['civicrm_paths']['civicrm.files'])) { | |
125 | \Civi::log()->warning("The system has data from both old+new conventions. Please use civicrm.settings.php to set civicrm.files explicitly."); | |
126 | } | |
127 | return $new; | |
128 | } | |
129 | }); | |
716bdc94 TO |
130 | } |
131 | else { | |
132 | // Legacy support - only relevant for older extern routes. | |
133 | Civi::paths() | |
134 | ->register('wp.frontend.base', function () { | |
135 | return ['url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/']; | |
136 | }) | |
137 | ->register('wp.frontend', function () { | |
138 | $config = \CRM_Core_Config::singleton(); | |
139 | $suffix = defined('CIVICRM_UF_WP_BASEPAGE') ? CIVICRM_UF_WP_BASEPAGE : $config->wpBasePage; | |
140 | return [ | |
141 | 'url' => Civi::paths()->getVariable('wp.frontend.base', 'url') . $suffix, | |
142 | ]; | |
143 | }) | |
144 | ->register('wp.backend.base', function () { | |
145 | return ['url' => rtrim(CIVICRM_UF_BASEURL, '/') . '/wp-admin/']; | |
146 | }) | |
147 | ->register('wp.backend', function () { | |
148 | return [ | |
149 | 'url' => Civi::paths()->getVariable('wp.backend.base', 'url') . 'admin.php', | |
150 | ]; | |
151 | }); | |
152 | } | |
9509977f TO |
153 | } |
154 | ||
6a488035 | 155 | /** |
17f443df | 156 | * @inheritDoc |
6a488035 | 157 | */ |
00be9182 | 158 | public function setTitle($title, $pageTitle = NULL) { |
6a488035 TO |
159 | if (!$pageTitle) { |
160 | $pageTitle = $title; | |
161 | } | |
1beae3b1 | 162 | |
17f443df CW |
163 | // FIXME: Why is this global? |
164 | global $civicrm_wp_title; | |
165 | $civicrm_wp_title = $title; | |
1beae3b1 | 166 | |
17f443df CW |
167 | // yes, set page title, depending on context |
168 | $context = civi_wp()->civicrm_context_get(); | |
169 | switch ($context) { | |
170 | case 'admin': | |
171 | case 'shortcode': | |
172 | $template = CRM_Core_Smarty::singleton(); | |
173 | $template->assign('pageTitle', $pageTitle); | |
6a488035 TO |
174 | } |
175 | } | |
176 | ||
7ba2c8ad KC |
177 | /** |
178 | * Moved from CRM_Utils_System_Base | |
179 | */ | |
180 | public function getDefaultFileStorage() { | |
4db100ce TO |
181 | // NOTE: On WordPress, this will be circumvented in the future. However, |
182 | // should retain it to allow transitional/upgrade code determine the old value. | |
183 | ||
8ce9d9d6 TO |
184 | $config = CRM_Core_Config::singleton(); |
185 | $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE); | |
186 | $cmsPath = $this->cmsRootPath(); | |
187 | $filesPath = CRM_Utils_File::baseFilePath(); | |
188 | $filesRelPath = CRM_Utils_File::relativize($filesPath, $cmsPath); | |
189 | $filesURL = rtrim($cmsUrl, '/') . '/' . ltrim($filesRelPath, ' /'); | |
be2fb01f | 190 | return [ |
8ce9d9d6 TO |
191 | 'url' => CRM_Utils_File::addTrailingSlash($filesURL, '/'), |
192 | 'path' => CRM_Utils_File::addTrailingSlash($filesPath), | |
be2fb01f | 193 | ]; |
8ce9d9d6 TO |
194 | } |
195 | ||
196 | /** | |
197 | * Determine the location of the CiviCRM source tree. | |
198 | * | |
199 | * @return array | |
200 | * - url: string. ex: "http://example.com/sites/all/modules/civicrm" | |
201 | * - path: string. ex: "/var/www/sites/all/modules/civicrm" | |
202 | */ | |
203 | public function getCiviSourceStorage() { | |
7ba2c8ad | 204 | global $civicrm_root; |
7ba2c8ad | 205 | |
8ce9d9d6 TO |
206 | // Don't use $config->userFrameworkBaseURL; it has garbage on it. |
207 | // More generally, we shouldn't be using $config here. | |
208 | if (!defined('CIVICRM_UF_BASEURL')) { | |
209 | throw new RuntimeException('Undefined constant: CIVICRM_UF_BASEURL'); | |
7ba2c8ad | 210 | } |
8ce9d9d6 TO |
211 | |
212 | $cmsPath = $this->cmsRootPath(); | |
213 | ||
214 | // $config = CRM_Core_Config::singleton(); | |
215 | // overkill? // $cmsUrl = CRM_Utils_System::languageNegotiationURL($config->userFrameworkBaseURL, FALSE, TRUE); | |
216 | $cmsUrl = CIVICRM_UF_BASEURL; | |
217 | if (CRM_Utils_System::isSSL()) { | |
218 | $cmsUrl = str_replace('http://', 'https://', $cmsUrl); | |
7ba2c8ad | 219 | } |
d8182404 | 220 | $civiRelPath = CRM_Utils_File::relativize(realpath($civicrm_root), realpath($cmsPath)); |
8ce9d9d6 | 221 | $civiUrl = rtrim($cmsUrl, '/') . '/' . ltrim($civiRelPath, ' /'); |
be2fb01f | 222 | return [ |
8ce9d9d6 TO |
223 | 'url' => CRM_Utils_File::addTrailingSlash($civiUrl, '/'), |
224 | 'path' => CRM_Utils_File::addTrailingSlash($civicrm_root), | |
be2fb01f | 225 | ]; |
7ba2c8ad KC |
226 | } |
227 | ||
6a488035 | 228 | /** |
17f443df | 229 | * @inheritDoc |
6a488035 | 230 | */ |
00be9182 | 231 | public function appendBreadCrumb($breadCrumbs) { |
6a488035 TO |
232 | $breadCrumb = wp_get_breadcrumb(); |
233 | ||
234 | if (is_array($breadCrumbs)) { | |
235 | foreach ($breadCrumbs as $crumbs) { | |
236 | if (stripos($crumbs['url'], 'id%%')) { | |
be2fb01f | 237 | $args = ['cid', 'mid']; |
6a488035 TO |
238 | foreach ($args as $a) { |
239 | $val = CRM_Utils_Request::retrieve($a, 'Positive', CRM_Core_DAO::$_nullObject, | |
240 | FALSE, NULL, $_GET | |
241 | ); | |
242 | if ($val) { | |
243 | $crumbs['url'] = str_ireplace("%%{$a}%%", $val, $crumbs['url']); | |
244 | } | |
245 | } | |
246 | } | |
247 | $breadCrumb[] = "<a href=\"{$crumbs['url']}\">{$crumbs['title']}</a>"; | |
248 | } | |
249 | } | |
250 | ||
251 | $template = CRM_Core_Smarty::singleton(); | |
252 | $template->assign_by_ref('breadcrumb', $breadCrumb); | |
253 | wp_set_breadcrumb($breadCrumb); | |
254 | } | |
255 | ||
256 | /** | |
17f443df | 257 | * @inheritDoc |
6a488035 | 258 | */ |
00be9182 | 259 | public function resetBreadCrumb() { |
be2fb01f | 260 | $bc = []; |
6a488035 TO |
261 | wp_set_breadcrumb($bc); |
262 | } | |
263 | ||
264 | /** | |
17f443df | 265 | * @inheritDoc |
6a488035 | 266 | */ |
00be9182 | 267 | public function addHTMLHead($head) { |
6a488035 TO |
268 | static $registered = FALSE; |
269 | if (!$registered) { | |
270 | // front-end view | |
be2fb01f | 271 | add_action('wp_head', [__CLASS__, '_showHTMLHead']); |
6a488035 | 272 | // back-end views |
be2fb01f | 273 | add_action('admin_head', [__CLASS__, '_showHTMLHead']); |
227d65b7 | 274 | $registered = TRUE; |
6a488035 | 275 | } |
be2fb01f | 276 | CRM_Core_Region::instance('wp_head')->add([ |
6a488035 | 277 | 'markup' => $head, |
be2fb01f | 278 | ]); |
6a488035 TO |
279 | } |
280 | ||
17f443df | 281 | /** |
fe482240 | 282 | * WP action callback. |
17f443df | 283 | */ |
00be9182 | 284 | public static function _showHTMLHead() { |
6a488035 TO |
285 | $region = CRM_Core_Region::instance('wp_head', FALSE); |
286 | if ($region) { | |
287 | echo $region->render(''); | |
288 | } | |
289 | } | |
290 | ||
291 | /** | |
17f443df | 292 | * @inheritDoc |
6a488035 | 293 | */ |
00be9182 | 294 | public function mapConfigToSSL() { |
6a488035 TO |
295 | global $base_url; |
296 | $base_url = str_replace('http://', 'https://', $base_url); | |
297 | } | |
298 | ||
299 | /** | |
17f443df | 300 | * @inheritDoc |
6a488035 | 301 | */ |
408b79bf | 302 | public function url( |
6a488035 TO |
303 | $path = NULL, |
304 | $query = NULL, | |
305 | $absolute = FALSE, | |
306 | $fragment = NULL, | |
6a488035 | 307 | $frontend = FALSE, |
8de2a34e SL |
308 | $forceBackend = FALSE, |
309 | $htmlize = TRUE | |
6a488035 | 310 | ) { |
353ffa53 TO |
311 | $config = CRM_Core_Config::singleton(); |
312 | $script = ''; | |
c80e2dbf | 313 | $separator = '&'; |
353ffa53 | 314 | $wpPageParam = ''; |
887f5d81 | 315 | $fragment = isset($fragment) ? ('#' . $fragment) : ''; |
6a488035 TO |
316 | |
317 | $path = CRM_Utils_String::stripPathChars($path); | |
df17aa21 | 318 | $basepage = FALSE; |
6a488035 TO |
319 | |
320 | //this means wp function we are trying to use is not available, | |
321 | //so load bootStrap | |
d8182404 | 322 | // FIXME: Why bootstrap in url()? Generally want to define 1-2 strategic places to put bootstrap |
6a488035 | 323 | if (!function_exists('get_option')) { |
d8182404 | 324 | $this->loadBootStrap(); |
6a488035 | 325 | } |
df17aa21 | 326 | |
6a488035 | 327 | if ($config->userFrameworkFrontend) { |
df17aa21 | 328 | global $post; |
887f5d81 | 329 | if (get_option('permalink_structure') != '') { |
337df6ce | 330 | $script = $post ? get_permalink($post->ID) : ""; |
6a488035 | 331 | } |
337df6ce | 332 | if ($post && $config->wpBasePage == $post->post_name) { |
df17aa21 CW |
333 | $basepage = TRUE; |
334 | } | |
01aca362 | 335 | // when shortcode is included in page |
6a488035 | 336 | // also make sure we have valid query object |
df17aa21 | 337 | // FIXME: $wpPageParam has no effect and is only set on the *basepage* |
6a488035 | 338 | global $wp_query; |
df17aa21 | 339 | if (get_option('permalink_structure') == '' && method_exists($wp_query, 'get')) { |
6a488035 | 340 | if (get_query_var('page_id')) { |
887f5d81 | 341 | $wpPageParam = "page_id=" . get_query_var('page_id'); |
6a488035 TO |
342 | } |
343 | elseif (get_query_var('p')) { | |
344 | // when shortcode is inserted in post | |
887f5d81 | 345 | $wpPageParam = "p=" . get_query_var('p'); |
6a488035 TO |
346 | } |
347 | } | |
348 | } | |
349 | ||
887f5d81 TO |
350 | $base = $this->getBaseUrl($absolute, $frontend, $forceBackend); |
351 | ||
352 | if (!isset($path) && !isset($query)) { | |
353 | // FIXME: This short-circuited codepath is the same as the general one below, except | |
354 | // in that it ignores "permlink_structure" / $wpPageParam / $script . I don't know | |
355 | // why it's different (and I can only find two obvious use-cases for this codepath, | |
356 | // of which at least one looks gratuitous). A more ambitious person would simply remove | |
357 | // this code. | |
358 | return $base . $fragment; | |
359 | } | |
360 | ||
361 | if (!$forceBackend && get_option('permalink_structure') != '' && ($wpPageParam || $script != '')) { | |
362 | $base = $script; | |
6a488035 TO |
363 | } |
364 | ||
be2fb01f | 365 | $queryParts = []; |
df17aa21 | 366 | |
df17aa21 CW |
367 | if ( |
368 | // not using clean URLs | |
369 | !$config->cleanURL | |
370 | // requesting an admin URL | |
371 | || ((is_admin() && !$frontend) || $forceBackend) | |
372 | // is shortcode | |
373 | || (!$basepage && $script != '') | |
374 | ) { | |
375 | ||
376 | // pre-existing logic | |
377 | if (isset($path)) { | |
25bd5735 CW |
378 | // Admin URLs still need "page=CiviCRM", front-end URLs do not. |
379 | if ((is_admin() && !$frontend) || $forceBackend) { | |
380 | $queryParts[] = 'page=CiviCRM'; | |
381 | } | |
382 | else { | |
383 | $queryParts[] = 'civiwp=CiviCRM'; | |
384 | } | |
cdef34e0 | 385 | $queryParts[] = 'q=' . rawurlencode($path); |
df17aa21 CW |
386 | } |
387 | if ($wpPageParam) { | |
388 | $queryParts[] = $wpPageParam; | |
389 | } | |
ffa62912 | 390 | if (!empty($query)) { |
df17aa21 CW |
391 | $queryParts[] = $query; |
392 | } | |
393 | ||
394 | $final = $base . '?' . implode($separator, $queryParts) . $fragment; | |
395 | ||
887f5d81 | 396 | } |
df17aa21 CW |
397 | else { |
398 | ||
399 | // clean URLs | |
400 | if (isset($path)) { | |
401 | $base = trailingslashit($base) . str_replace('civicrm/', '', $path) . '/'; | |
402 | } | |
403 | if (isset($query)) { | |
404 | $query = ltrim($query, '=?&'); | |
405 | $queryParts[] = $query; | |
406 | } | |
407 | ||
408 | if (!empty($queryParts)) { | |
409 | $final = $base . '?' . implode($separator, $queryParts) . $fragment; | |
410 | } | |
411 | else { | |
412 | $final = $base . $fragment; | |
413 | } | |
414 | ||
6a488035 TO |
415 | } |
416 | ||
df17aa21 | 417 | return $final; |
887f5d81 TO |
418 | } |
419 | ||
bb3a214a | 420 | /** |
f553d1ea KC |
421 | * 27-09-2016 |
422 | * CRM-16421 CRM-17633 WIP Changes to support WP in it's own directory | |
423 | * https://wiki.civicrm.org/confluence/display/CRM/WordPress+installed+in+its+own+directory+issues | |
424 | * For now leave hard coded wp-admin references. | |
425 | * TODO: remove wp-admin references and replace with admin_url() in the future. Look at best way to get path to admin_url | |
426 | * | |
bb3a214a EM |
427 | * @param $absolute |
428 | * @param $frontend | |
429 | * @param $forceBackend | |
430 | * | |
431 | * @return mixed|null|string | |
432 | */ | |
887f5d81 | 433 | private function getBaseUrl($absolute, $frontend, $forceBackend) { |
353ffa53 | 434 | $config = CRM_Core_Config::singleton(); |
6a488035 | 435 | if ((is_admin() && !$frontend) || $forceBackend) { |
f553d1ea | 436 | return Civi::paths()->getUrl('[wp.backend]/.', $absolute ? 'absolute' : 'relative'); |
6a488035 | 437 | } |
f553d1ea KC |
438 | else { |
439 | return Civi::paths()->getUrl('[wp.frontend]/.', $absolute ? 'absolute' : 'relative'); | |
36b820ae | 440 | } |
01aca362 | 441 | } |
6a488035 TO |
442 | |
443 | /** | |
17f443df | 444 | * @inheritDoc |
6a488035 | 445 | */ |
00be9182 | 446 | public function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) { |
6a488035 TO |
447 | $config = CRM_Core_Config::singleton(); |
448 | ||
449 | if ($loadCMSBootstrap) { | |
9ba02e3e TO |
450 | $config->userSystem->loadBootStrap([ |
451 | 'name' => $name, | |
452 | 'pass' => $password, | |
453 | ]); | |
6a488035 TO |
454 | } |
455 | ||
456 | $user = wp_authenticate($name, $password); | |
457 | if (is_a($user, 'WP_Error')) { | |
458 | return FALSE; | |
459 | } | |
460 | ||
17f443df | 461 | // TODO: need to change this to make sure we matched only one row |
6a488035 TO |
462 | |
463 | CRM_Core_BAO_UFMatch::synchronizeUFMatch($user->data, $user->data->ID, $user->data->user_email, 'WordPress'); | |
464 | $contactID = CRM_Core_BAO_UFMatch::getContactId($user->data->ID); | |
465 | if (!$contactID) { | |
466 | return FALSE; | |
467 | } | |
be2fb01f | 468 | return [$contactID, $user->data->ID, mt_rand()]; |
6a488035 TO |
469 | } |
470 | ||
471 | /** | |
17f443df | 472 | * FIXME: Do something |
ea3ddccf | 473 | * |
474 | * @param string $message | |
6a488035 | 475 | */ |
00be9182 | 476 | public function setMessage($message) { |
6a488035 TO |
477 | } |
478 | ||
bb3a214a | 479 | /** |
b596c3e9 | 480 | * @param \string $user |
ea3ddccf | 481 | * |
482 | * @return bool | |
bb3a214a | 483 | */ |
e7292422 | 484 | public function loadUser($user) { |
b596c3e9 | 485 | $userdata = get_user_by('login', $user); |
486 | if (!$userdata->data->ID) { | |
7ca9cd52 | 487 | return FALSE; |
b596c3e9 | 488 | } |
489 | ||
490 | $uid = $userdata->data->ID; | |
491 | wp_set_current_user($uid); | |
492 | $contactID = CRM_Core_BAO_UFMatch::getContactId($uid); | |
493 | ||
494 | // lets store contact id and user id in session | |
495 | $session = CRM_Core_Session::singleton(); | |
496 | $session->set('ufID', $uid); | |
497 | $session->set('userID', $contactID); | |
e7292422 | 498 | return TRUE; |
6a488035 TO |
499 | } |
500 | ||
17f443df CW |
501 | /** |
502 | * FIXME: Use CMS-native approach | |
309310bf | 503 | * @throws \CRM_Core_Exception |
17f443df | 504 | */ |
00be9182 | 505 | public function permissionDenied() { |
309310bf | 506 | throw new CRM_Core_Exception(ts('You do not have permission to access this page.')); |
6a488035 TO |
507 | } |
508 | ||
8ee9bea9 SL |
509 | /** |
510 | * Determine the native ID of the CMS user. | |
511 | * | |
512 | * @param string $username | |
e97c66ff | 513 | * |
514 | * @return int|null | |
8ee9bea9 SL |
515 | */ |
516 | public function getUfId($username) { | |
517 | $userdata = get_user_by('login', $username); | |
518 | if (!$userdata->data->ID) { | |
519 | return NULL; | |
520 | } | |
521 | return $userdata->data->ID; | |
522 | } | |
523 | ||
17f443df CW |
524 | /** |
525 | * @inheritDoc | |
526 | */ | |
00be9182 | 527 | public function logout() { |
6a488035 TO |
528 | // destroy session |
529 | if (session_id()) { | |
530 | session_destroy(); | |
531 | } | |
532 | wp_logout(); | |
533 | wp_redirect(wp_login_url()); | |
534 | } | |
535 | ||
6a488035 | 536 | /** |
17f443df | 537 | * @inheritDoc |
6a488035 | 538 | */ |
00be9182 | 539 | public function getUFLocale() { |
742eb5c6 CW |
540 | // Bail early if method is called when WordPress isn't bootstrapped. |
541 | // Additionally, the function checked here is located in pluggable.php | |
542 | // and is required by wp_get_referer() - so this also bails early if it is | |
543 | // called too early in the request lifecycle. | |
544 | // @see https://core.trac.wordpress.org/ticket/25294 | |
545 | if (!function_exists('wp_validate_redirect')) { | |
546 | return NULL; | |
cba2601a | 547 | } |
742eb5c6 CW |
548 | |
549 | // Default to WordPress User locale. | |
550 | $locale = get_user_locale(); | |
551 | ||
552 | // Is this a "back-end" AJAX call? | |
553 | $is_backend = FALSE; | |
554 | if (wp_doing_ajax() && FALSE !== strpos(wp_get_referer(), admin_url())) { | |
555 | $is_backend = TRUE; | |
19780d2b | 556 | } |
742eb5c6 CW |
557 | |
558 | // Ignore when in WordPress admin or it's a "back-end" AJAX call. | |
559 | if (!(is_admin() || $is_backend)) { | |
560 | ||
561 | // Reaching here means it is very likely to be a front-end context. | |
562 | ||
563 | // Default to WordPress locale. | |
564 | $locale = get_locale(); | |
565 | ||
566 | // Maybe override with the locale that Polylang reports. | |
567 | if (function_exists('pll_current_language')) { | |
568 | $pll_locale = pll_current_language('locale'); | |
569 | if (!empty($pll_locale)) { | |
570 | $locale = $pll_locale; | |
571 | } | |
572 | } | |
573 | ||
574 | // Maybe override with the locale that WPML reports. | |
575 | elseif (defined('ICL_LANGUAGE_CODE')) { | |
576 | $languages = apply_filters('wpml_active_languages', NULL); | |
577 | foreach ($languages as $language) { | |
578 | if ($language['active']) { | |
579 | $locale = $language['default_locale']; | |
580 | break; | |
581 | } | |
582 | } | |
583 | } | |
584 | ||
585 | // TODO: Set locale for other WordPress plugins. | |
586 | // @see https://wordpress.org/plugins/tags/multilingual/ | |
587 | // A hook would be nice here. | |
588 | ||
2c3d151b | 589 | } |
19780d2b | 590 | |
742eb5c6 CW |
591 | if (!empty($locale)) { |
592 | // If for some reason only we get a language code, convert it to a locale. | |
593 | if (2 === strlen($locale)) { | |
594 | $locale = CRM_Core_I18n_PseudoConstant::longForShort($locale); | |
595 | } | |
596 | return $locale; | |
0db6c3e1 TO |
597 | } |
598 | else { | |
19780d2b DL |
599 | return NULL; |
600 | } | |
6a488035 TO |
601 | } |
602 | ||
fd1f3a26 SV |
603 | /** |
604 | * @inheritDoc | |
605 | */ | |
606 | public function setUFLocale($civicrm_language) { | |
607 | // TODO (probably not possible with WPML?) | |
608 | return TRUE; | |
609 | } | |
610 | ||
6a488035 | 611 | /** |
fe482240 | 612 | * Load wordpress bootstrap. |
6a488035 | 613 | * |
9ba02e3e TO |
614 | * @param array $params |
615 | * Optional credentials | |
616 | * - name: string, cms username | |
617 | * - pass: string, cms password | |
6714d8d2 SL |
618 | * @param bool $loadUser |
619 | * @param bool $throwError | |
620 | * @param mixed $realPath | |
f4aaa82a EM |
621 | * |
622 | * @return bool | |
309310bf | 623 | * @throws \CRM_Core_Exception |
6a488035 | 624 | */ |
be2fb01f | 625 | public function loadBootStrap($params = [], $loadUser = TRUE, $throwError = TRUE, $realPath = NULL) { |
05fcde76 | 626 | global $wp, $wp_rewrite, $wp_the_query, $wp_query, $wpdb, $current_site, $current_blog, $current_user; |
6a488035 | 627 | |
9c1bc317 CW |
628 | $name = $params['name'] ?? NULL; |
629 | $pass = $params['pass'] ?? NULL; | |
9ba02e3e | 630 | |
7a44e49f | 631 | if (!defined('WP_USE_THEMES')) { |
c5f77355 | 632 | define('WP_USE_THEMES', FALSE); |
7a44e49f | 633 | } |
6a488035 TO |
634 | |
635 | $cmsRootPath = $this->cmsRootPath(); | |
636 | if (!$cmsRootPath) { | |
309310bf | 637 | throw new CRM_Core_Exception("Could not find the install directory for WordPress"); |
6a488035 | 638 | } |
aaffa79f | 639 | $path = Civi::settings()->get('wpLoadPhp'); |
b299b1cc | 640 | if (!empty($path)) { |
35da5d8d | 641 | require_once $path; |
b299b1cc KC |
642 | } |
643 | elseif (file_exists($cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php')) { | |
35da5d8d | 644 | require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-load.php'; |
b299b1cc KC |
645 | } |
646 | else { | |
309310bf | 647 | throw new CRM_Core_Exception("Could not find the bootstrap file for WordPress"); |
35da5d8d | 648 | } |
6491539b DL |
649 | $wpUserTimezone = get_option('timezone_string'); |
650 | if ($wpUserTimezone) { | |
651 | date_default_timezone_set($wpUserTimezone); | |
652 | CRM_Core_Config::singleton()->userSystem->setMySQLTimeZone(); | |
653 | } | |
e7292422 | 654 | require_once $cmsRootPath . DIRECTORY_SEPARATOR . 'wp-includes/pluggable.php'; |
9c1bc317 | 655 | $uid = $params['uid'] ?? NULL; |
17763922 WA |
656 | if (!$uid) { |
657 | $name = $name ? $name : trim(CRM_Utils_Array::value('name', $_REQUEST)); | |
658 | $pass = $pass ? $pass : trim(CRM_Utils_Array::value('pass', $_REQUEST)); | |
659 | if ($name) { | |
d8182404 | 660 | $uid = wp_authenticate($name, $pass); |
17763922 WA |
661 | if (!$uid) { |
662 | if ($throwError) { | |
663 | echo '<br />Sorry, unrecognized username or password.'; | |
664 | exit(); | |
665 | } | |
666 | return FALSE; | |
667 | } | |
668 | } | |
669 | } | |
fe1e7958 | 670 | if ($uid) { |
a4111333 CW |
671 | if ($uid instanceof WP_User) { |
672 | $account = wp_set_current_user($uid->ID); | |
c5f77355 CW |
673 | } |
674 | else { | |
a4111333 CW |
675 | $account = wp_set_current_user($uid); |
676 | } | |
fe1e7958 | 677 | if ($account && $account->data->ID) { |
678 | global $user; | |
679 | $user = $account; | |
680 | return TRUE; | |
681 | } | |
682 | } | |
e7292422 | 683 | return TRUE; |
6a488035 TO |
684 | } |
685 | ||
bb3a214a EM |
686 | /** |
687 | * @param $dir | |
688 | * | |
689 | * @return bool | |
690 | */ | |
00be9182 | 691 | public function validInstallDir($dir) { |
dfbcf0b7 | 692 | $includePath = "$dir/wp-includes"; |
468176f6 | 693 | if (@file_exists("$includePath/version.php")) { |
dfbcf0b7 DL |
694 | return TRUE; |
695 | } | |
696 | return FALSE; | |
697 | } | |
698 | ||
bb3a214a EM |
699 | /** |
700 | * Determine the location of the CMS root. | |
701 | * | |
72b3a70c CW |
702 | * @return string|NULL |
703 | * local file system path to CMS root, or NULL if it cannot be determined | |
bb3a214a | 704 | */ |
00be9182 | 705 | public function cmsRootPath() { |
02bfbc78 CW |
706 | |
707 | // Return early if the path is already set. | |
a93a0366 TO |
708 | global $civicrm_paths; |
709 | if (!empty($civicrm_paths['cms.root']['path'])) { | |
710 | return $civicrm_paths['cms.root']['path']; | |
711 | } | |
712 | ||
02bfbc78 | 713 | // Return early if constant has been defined. |
dfbcf0b7 DL |
714 | if (defined('CIVICRM_CMSDIR')) { |
715 | if ($this->validInstallDir(CIVICRM_CMSDIR)) { | |
02bfbc78 | 716 | return CIVICRM_CMSDIR; |
dfbcf0b7 | 717 | } |
6a488035 | 718 | } |
02bfbc78 CW |
719 | |
720 | // Return early if path to wp-load.php can be retrieved from settings. | |
721 | $setting = Civi::settings()->get('wpLoadPhp'); | |
722 | if (!empty($setting)) { | |
57811df8 KC |
723 | $path = str_replace('wp-load.php', '', $setting); |
724 | $cmsRoot = rtrim($path, '/\\'); | |
02bfbc78 CW |
725 | if ($this->validInstallDir($cmsRoot)) { |
726 | return $cmsRoot; | |
727 | } | |
728 | } | |
729 | ||
730 | /* | |
731 | * Keep previous logic as fallback of last resort. | |
732 | * | |
733 | * At some point, it would be good to remove this because there are serious | |
734 | * problems in correctly locating WordPress in this manner. In summary, it | |
735 | * is impossible to do so reliably. | |
736 | * | |
737 | * @see https://github.com/civicrm/civicrm-wordpress/pull/63#issuecomment-61792328 | |
738 | * @see https://github.com/civicrm/civicrm-core/pull/11086#issuecomment-335454992 | |
739 | */ | |
740 | $cmsRoot = $valid = NULL; | |
741 | ||
742 | $pathVars = explode('/', str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME'])); | |
743 | ||
744 | // Might be Windows installation. | |
745 | $firstVar = array_shift($pathVars); | |
746 | if ($firstVar) { | |
747 | $cmsRoot = $firstVar; | |
748 | } | |
749 | ||
750 | // Start with CMS dir search. | |
751 | foreach ($pathVars as $var) { | |
752 | $cmsRoot .= "/$var"; | |
753 | if ($this->validInstallDir($cmsRoot)) { | |
754 | // Stop as we found bootstrap. | |
755 | $valid = TRUE; | |
756 | break; | |
757 | } | |
6a488035 TO |
758 | } |
759 | ||
760 | return ($valid) ? $cmsRoot : NULL; | |
761 | } | |
762 | ||
bb3a214a | 763 | /** |
17f443df | 764 | * @inheritDoc |
bb3a214a | 765 | */ |
00be9182 | 766 | public function createUser(&$params, $mail) { |
be2fb01f | 767 | $user_data = [ |
6a488035 TO |
768 | 'ID' => '', |
769 | 'user_pass' => $params['cms_pass'], | |
770 | 'user_login' => $params['cms_name'], | |
771 | 'user_email' => $params[$mail], | |
772 | 'nickname' => $params['cms_name'], | |
773 | 'role' => get_option('default_role'), | |
be2fb01f | 774 | ]; |
6a488035 TO |
775 | if (isset($params['contactID'])) { |
776 | $contactType = CRM_Contact_BAO_Contact::getContactType($params['contactID']); | |
777 | if ($contactType == 'Individual') { | |
778 | $user_data['first_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', | |
779 | $params['contactID'], 'first_name' | |
780 | ); | |
781 | $user_data['last_name'] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', | |
782 | $params['contactID'], 'last_name' | |
783 | ); | |
784 | } | |
785 | } | |
786 | ||
787 | $uid = wp_insert_user($user_data); | |
788 | ||
be2fb01f | 789 | $creds = []; |
6a488035 TO |
790 | $creds['user_login'] = $params['cms_name']; |
791 | $creds['user_password'] = $params['cms_pass']; | |
792 | $creds['remember'] = TRUE; | |
793 | $user = wp_signon($creds, FALSE); | |
794 | ||
795 | wp_new_user_notification($uid, $user_data['user_pass']); | |
796 | return $uid; | |
797 | } | |
798 | ||
f4aaa82a | 799 | /** |
17f443df | 800 | * @inheritDoc |
6a488035 | 801 | */ |
00be9182 | 802 | public function updateCMSName($ufID, $ufName) { |
6a488035 TO |
803 | // CRM-10620 |
804 | if (function_exists('wp_update_user')) { | |
353ffa53 | 805 | $ufID = CRM_Utils_Type::escape($ufID, 'Integer'); |
6a488035 TO |
806 | $ufName = CRM_Utils_Type::escape($ufName, 'String'); |
807 | ||
be2fb01f | 808 | $values = ['ID' => $ufID, 'user_email' => $ufName]; |
481a74f4 TO |
809 | if ($ufID) { |
810 | wp_update_user($values); | |
6a488035 TO |
811 | } |
812 | } | |
813 | } | |
814 | ||
bb3a214a | 815 | /** |
c490a46a | 816 | * @param array $params |
bb3a214a EM |
817 | * @param $errors |
818 | * @param string $emailName | |
819 | */ | |
00be9182 | 820 | public function checkUserNameEmailExists(&$params, &$errors, $emailName = 'email') { |
6a488035 TO |
821 | $config = CRM_Core_Config::singleton(); |
822 | ||
353ffa53 TO |
823 | $dao = new CRM_Core_DAO(); |
824 | $name = $dao->escape(CRM_Utils_Array::value('name', $params)); | |
6a488035 TO |
825 | $email = $dao->escape(CRM_Utils_Array::value('mail', $params)); |
826 | ||
a7488080 | 827 | if (!empty($params['name'])) { |
6a488035 TO |
828 | if (!validate_username($params['name'])) { |
829 | $errors['cms_name'] = ts("Your username contains invalid characters"); | |
830 | } | |
831 | elseif (username_exists(sanitize_user($params['name']))) { | |
be2fb01f | 832 | $errors['cms_name'] = ts('The username %1 is already taken. Please select another username.', [1 => $params['name']]); |
6a488035 TO |
833 | } |
834 | } | |
835 | ||
a7488080 | 836 | if (!empty($params['mail'])) { |
6a488035 TO |
837 | if (!is_email($params['mail'])) { |
838 | $errors[$emailName] = "Your email is invaid"; | |
839 | } | |
840 | elseif (email_exists($params['mail'])) { | |
db18d815 | 841 | $errors[$emailName] = ts('The email address %1 already has an account associated with it. <a href="%2">Have you forgotten your password?</a>', |
be2fb01f | 842 | [1 => $params['mail'], 2 => wp_lostpassword_url()] |
6a488035 TO |
843 | ); |
844 | } | |
845 | } | |
846 | } | |
847 | ||
848 | /** | |
17f443df | 849 | * @inheritDoc |
6a488035 TO |
850 | */ |
851 | public function isUserLoggedIn() { | |
852 | $isloggedIn = FALSE; | |
853 | if (function_exists('is_user_logged_in')) { | |
854 | $isloggedIn = is_user_logged_in(); | |
855 | } | |
856 | ||
857 | return $isloggedIn; | |
858 | } | |
859 | ||
8caad0ce | 860 | /** |
861 | * @inheritDoc | |
862 | */ | |
863 | public function isUserRegistrationPermitted() { | |
864 | if (!get_option('users_can_register')) { | |
865 | return FALSE; | |
866 | } | |
867 | return TRUE; | |
868 | } | |
869 | ||
63df6889 HD |
870 | /** |
871 | * @inheritDoc | |
872 | */ | |
1a6630be | 873 | public function isPasswordUserGenerated() { |
63df6889 HD |
874 | return TRUE; |
875 | } | |
876 | ||
bb3a214a EM |
877 | /** |
878 | * @return mixed | |
879 | */ | |
00be9182 | 880 | public function getLoggedInUserObject() { |
2b617cb0 | 881 | if (function_exists('is_user_logged_in') && |
353ffa53 TO |
882 | is_user_logged_in() |
883 | ) { | |
2b617cb0 EM |
884 | global $current_user; |
885 | } | |
886 | return $current_user; | |
887 | } | |
353ffa53 | 888 | |
6a488035 | 889 | /** |
17f443df | 890 | * @inheritDoc |
6a488035 TO |
891 | */ |
892 | public function getLoggedInUfID() { | |
893 | $ufID = NULL; | |
2b617cb0 | 894 | $current_user = $this->getLoggedInUserObject(); |
2e1f50d6 | 895 | return $current_user->ID ?? NULL; |
2b617cb0 EM |
896 | } |
897 | ||
898 | /** | |
17f443df | 899 | * @inheritDoc |
2b617cb0 | 900 | */ |
00be9182 | 901 | public function getLoggedInUniqueIdentifier() { |
2b617cb0 EM |
902 | $user = $this->getLoggedInUserObject(); |
903 | return $this->getUniqueIdentifierFromUserObject($user); | |
6a488035 TO |
904 | } |
905 | ||
32998c82 EM |
906 | /** |
907 | * Get User ID from UserFramework system (Joomla) | |
77855840 TO |
908 | * @param object $user |
909 | * Object as described by the CMS. | |
72b3a70c CW |
910 | * |
911 | * @return int|null | |
32998c82 | 912 | */ |
00be9182 | 913 | public function getUserIDFromUserObject($user) { |
32998c82 EM |
914 | return !empty($user->ID) ? $user->ID : NULL; |
915 | } | |
916 | ||
2b617cb0 | 917 | /** |
17f443df | 918 | * @inheritDoc |
2b617cb0 | 919 | */ |
00be9182 | 920 | public function getUniqueIdentifierFromUserObject($user) { |
2b617cb0 EM |
921 | return empty($user->user_email) ? NULL : $user->user_email; |
922 | } | |
923 | ||
6a488035 | 924 | /** |
17f443df | 925 | * @inheritDoc |
6a488035 TO |
926 | */ |
927 | public function getLoginURL($destination = '') { | |
928 | $config = CRM_Core_Config::singleton(); | |
153155d3 | 929 | $loginURL = wp_login_url(); |
6a488035 TO |
930 | return $loginURL; |
931 | } | |
932 | ||
bb3a214a | 933 | /** |
ad37ac8e | 934 | * FIXME: Do something. |
935 | * | |
936 | * @param \CRM_Core_Form $form | |
937 | * | |
938 | * @return NULL|string | |
bb3a214a | 939 | */ |
6a488035 | 940 | public function getLoginDestination(&$form) { |
408b79bf | 941 | return NULL; |
6a488035 TO |
942 | } |
943 | ||
944 | /** | |
17f443df | 945 | * @inheritDoc |
6a488035 | 946 | */ |
00be9182 | 947 | public function getVersion() { |
6a488035 TO |
948 | if (function_exists('get_bloginfo')) { |
949 | return get_bloginfo('version', 'display'); | |
950 | } | |
951 | else { | |
952 | return 'Unknown'; | |
953 | } | |
954 | } | |
6491539b DL |
955 | |
956 | /** | |
17f443df | 957 | * @inheritDoc |
6491539b | 958 | */ |
00be9182 | 959 | public function getTimeZoneString() { |
6491539b DL |
960 | return get_option('timezone_string'); |
961 | } | |
59f97da6 EM |
962 | |
963 | /** | |
17f443df | 964 | * @inheritDoc |
59f97da6 | 965 | */ |
00be9182 | 966 | public function getUserRecordUrl($contactID) { |
59f97da6 | 967 | $uid = CRM_Core_BAO_UFMatch::getUFId($contactID); |
353ffa53 | 968 | if (CRM_Core_Session::singleton() |
6714d8d2 | 969 | ->get('userID') == $contactID || CRM_Core_Permission::checkAnyPerm(['cms:administer users']) |
353ffa53 | 970 | ) { |
59f97da6 EM |
971 | return CRM_Core_Config::singleton()->userFrameworkBaseURL . "wp-admin/user-edit.php?user_id=" . $uid; |
972 | } | |
973 | } | |
96025800 | 974 | |
469d8dab CW |
975 | /** |
976 | * Append WP js to coreResourcesList. | |
ad37ac8e | 977 | * |
303017a1 | 978 | * @param \Civi\Core\Event\GenericHookEvent $e |
469d8dab | 979 | */ |
303017a1 CW |
980 | public function appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) { |
981 | $e->list[] = 'js/crm.wordpress.js'; | |
469d8dab CW |
982 | } |
983 | ||
03d5592a CW |
984 | /** |
985 | * @inheritDoc | |
62c20d1e CW |
986 | */ |
987 | public function alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) { | |
988 | // Set menubar breakpoint to match WP admin theme | |
989 | if ($e->asset == 'crm-menubar.css') { | |
990 | $e->params['breakpoint'] = 783; | |
991 | } | |
992 | } | |
993 | ||
994 | /** | |
995 | * @inheritDoc | |
03d5592a CW |
996 | */ |
997 | public function synchronizeUsers() { | |
998 | $config = CRM_Core_Config::singleton(); | |
999 | if (PHP_SAPI != 'cli') { | |
1000 | set_time_limit(300); | |
1001 | } | |
1002 | $id = 'ID'; | |
1003 | $mail = 'user_email'; | |
1004 | ||
1005 | $uf = $config->userFramework; | |
1006 | $contactCount = 0; | |
1007 | $contactCreated = 0; | |
1008 | $contactMatching = 0; | |
1009 | ||
5b4ee130 CW |
1010 | // Previously used the $wpdb global - which means WordPress *must* be bootstrapped. |
1011 | $wpUsers = get_users(array( | |
1012 | 'blog_id' => get_current_blog_id(), | |
1013 | 'number' => -1, | |
1014 | )); | |
03d5592a | 1015 | |
5b4ee130 | 1016 | foreach ($wpUsers as $wpUserData) { |
03d5592a CW |
1017 | $contactCount++; |
1018 | if ($match = CRM_Core_BAO_UFMatch::synchronizeUFMatch($wpUserData, | |
1019 | $wpUserData->$id, | |
1020 | $wpUserData->$mail, | |
1021 | $uf, | |
1022 | 1, | |
1023 | 'Individual', | |
1024 | TRUE | |
1025 | ) | |
1026 | ) { | |
1027 | $contactCreated++; | |
1028 | } | |
1029 | else { | |
1030 | $contactMatching++; | |
1031 | } | |
5b4ee130 CW |
1032 | if (is_object($match)) { |
1033 | $match->free(); | |
1034 | } | |
03d5592a CW |
1035 | } |
1036 | ||
be2fb01f | 1037 | return [ |
03d5592a CW |
1038 | 'contactCount' => $contactCount, |
1039 | 'contactMatching' => $contactMatching, | |
1040 | 'contactCreated' => $contactCreated, | |
be2fb01f | 1041 | ]; |
03d5592a CW |
1042 | } |
1043 | ||
79dd7fe9 | 1044 | /** |
46dddc5c SL |
1045 | * Send an HTTP Response base on PSR HTTP RespnseInterface response. |
1046 | * | |
1047 | * @param \Psr\Http\Message\ResponseInterface $response | |
79dd7fe9 | 1048 | */ |
46dddc5c SL |
1049 | public function sendResponse(\Psr\Http\Message\ResponseInterface $response) { |
1050 | // use WordPress function status_header to ensure 404 response is sent | |
1051 | status_header($response->getStatusCode()); | |
90f6c8df SL |
1052 | foreach ($response->getHeaders() as $name => $values) { |
1053 | CRM_Utils_System::setHttpHeader($name, implode(', ', (array) $values)); | |
79dd7fe9 | 1054 | } |
46dddc5c SL |
1055 | echo $response->getBody(); |
1056 | CRM_Utils_System::civiExit(); | |
79dd7fe9 SL |
1057 | } |
1058 | ||
b07855e9 CW |
1059 | /** |
1060 | * Start a new session if there's no existing session ID. | |
1061 | * | |
1062 | * Checks are needed to prevent sessions being started when not necessary. | |
1063 | */ | |
1064 | public function sessionStart() { | |
1065 | $session_id = session_id(); | |
1066 | ||
1067 | // Check WordPress pseudo-cron. | |
1068 | $wp_cron = FALSE; | |
1069 | if (function_exists('wp_doing_cron') && wp_doing_cron()) { | |
1070 | $wp_cron = TRUE; | |
1071 | } | |
1072 | ||
1073 | // Check WP-CLI. | |
1074 | $wp_cli = FALSE; | |
1075 | if (defined('WP_CLI') && WP_CLI) { | |
1076 | $wp_cli = TRUE; | |
1077 | } | |
1078 | ||
1079 | // Check PHP on the command line - e.g. `cv`. | |
1080 | $php_cli = TRUE; | |
1081 | if (PHP_SAPI !== 'cli') { | |
1082 | $php_cli = FALSE; | |
1083 | } | |
1084 | ||
1085 | // Maybe start session. | |
1086 | if (empty($session_id) && !$wp_cron && !$wp_cli && !$php_cli) { | |
1087 | session_start(); | |
1088 | } | |
1089 | } | |
1090 | ||
bef5923d CW |
1091 | /** |
1092 | * Perform any necessary actions prior to redirecting via POST. | |
1093 | * | |
1094 | * Redirecting via POST means that cookies need to be sent with SameSite=None. | |
1095 | */ | |
1096 | public function prePostRedirect() { | |
1097 | // Get User Agent string. | |
1098 | $rawUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : ''; | |
1099 | $userAgent = mb_convert_encoding($rawUserAgent, 'UTF-8'); | |
1100 | ||
1101 | // Bail early if User Agent does not support `SameSite=None`. | |
1102 | $shouldUseSameSite = CRM_Utils_SameSite::shouldSendSameSiteNone($userAgent); | |
1103 | if (!$shouldUseSameSite) { | |
1104 | return; | |
1105 | } | |
1106 | ||
1107 | // Make sure session cookie is present in header. | |
1108 | $cookie_params = session_name() . '=' . session_id() . '; SameSite=None; Secure'; | |
1109 | CRM_Utils_System::setHttpHeader('Set-Cookie', $cookie_params); | |
1110 | ||
1111 | // Add WordPress auth cookies when user is logged in. | |
1112 | $user = wp_get_current_user(); | |
1113 | if ($user->exists()) { | |
1114 | self::setAuthCookies($user->ID, TRUE, TRUE); | |
1115 | } | |
1116 | } | |
1117 | ||
1118 | /** | |
1119 | * Explicitly set WordPress authentication cookies. | |
1120 | * | |
1121 | * Chrome 84 introduced a cookie policy change which prevents cookies for the | |
1122 | * session and for WordPress user authentication from being indentified when | |
1123 | * a purchaser returns to the site from PayPal using the "Back to Merchant" | |
1124 | * button. | |
1125 | * | |
1126 | * In order to comply with this policy, cookies need to be sent with their | |
1127 | * "SameSite" attribute set to "None" and with the "Secure" flag set, but this | |
1128 | * isn't possible to do via `wp_set_auth_cookie()` as it stands. | |
1129 | * | |
1130 | * This method is a modified clone of `wp_set_auth_cookie()` which satisfies | |
1131 | * the Chrome policy. | |
1132 | * | |
1133 | * @see wp_set_auth_cookie() | |
1134 | * | |
1135 | * The $remember parameter increases the time that the cookie will be kept. The | |
1136 | * default the cookie is kept without remembering is two days. When $remember is | |
1137 | * set, the cookies will be kept for 14 days or two weeks. | |
1138 | * | |
1139 | * @param int $user_id The WordPress User ID. | |
1140 | * @param bool $remember Whether to remember the user. | |
1141 | * @param bool|string $secure Whether the auth cookie should only be sent over | |
1142 | * HTTPS. Default is an empty string which means the | |
1143 | * value of `is_ssl()` will be used. | |
1144 | * @param string $token Optional. User's session token to use for this cookie. | |
1145 | */ | |
1146 | private function setAuthCookies($user_id, $remember = FALSE, $secure = '', $token = '') { | |
1147 | if ($remember) { | |
1148 | /** This filter is documented in wp-includes/pluggable.php */ | |
1149 | $expiration = time() + apply_filters('auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember); | |
1150 | ||
1151 | /* | |
1152 | * Ensure the browser will continue to send the cookie after the expiration time is reached. | |
1153 | * Needed for the login grace period in wp_validate_auth_cookie(). | |
1154 | */ | |
1155 | $expire = $expiration + (12 * HOUR_IN_SECONDS); | |
1156 | } | |
1157 | else { | |
1158 | /** This filter is documented in wp-includes/pluggable.php */ | |
1159 | $expiration = time() + apply_filters('auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember); | |
1160 | $expire = 0; | |
1161 | } | |
1162 | ||
1163 | if ('' === $secure) { | |
1164 | $secure = is_ssl(); | |
1165 | } | |
1166 | ||
1167 | // Front-end cookie is secure when the auth cookie is secure and the site's home URL is forced HTTPS. | |
1168 | $secure_logged_in_cookie = $secure && 'https' === parse_url(get_option('home'), PHP_URL_SCHEME); | |
1169 | ||
1170 | /** This filter is documented in wp-includes/pluggable.php */ | |
1171 | $secure = apply_filters('secure_auth_cookie', $secure, $user_id); | |
1172 | ||
1173 | /** This filter is documented in wp-includes/pluggable.php */ | |
1174 | $secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure); | |
1175 | ||
1176 | if ($secure) { | |
1177 | $auth_cookie_name = SECURE_AUTH_COOKIE; | |
1178 | $scheme = 'secure_auth'; | |
1179 | } | |
1180 | else { | |
1181 | $auth_cookie_name = AUTH_COOKIE; | |
1182 | $scheme = 'auth'; | |
1183 | } | |
1184 | ||
1185 | if ('' === $token) { | |
1186 | $manager = WP_Session_Tokens::get_instance($user_id); | |
1187 | $token = $manager->create($expiration); | |
1188 | } | |
1189 | ||
1190 | $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme, $token); | |
1191 | $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in', $token); | |
1192 | ||
1193 | /** This filter is documented in wp-includes/pluggable.php */ | |
1194 | do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme, $token); | |
1195 | ||
1196 | /** This filter is documented in wp-includes/pluggable.php */ | |
1197 | do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in', $token); | |
1198 | ||
1199 | /** This filter is documented in wp-includes/pluggable.php */ | |
1200 | if (!apply_filters('send_auth_cookies', TRUE)) { | |
1201 | return; | |
1202 | } | |
1203 | ||
1204 | $base_options = [ | |
1205 | 'expires' => $expire, | |
1206 | 'domain' => COOKIE_DOMAIN, | |
1207 | 'httponly' => TRUE, | |
1208 | 'samesite' => 'None', | |
1209 | ]; | |
1210 | ||
1211 | self::setAuthCookie($auth_cookie_name, $auth_cookie, $base_options + ['secure' => $secure, 'path' => PLUGINS_COOKIE_PATH]); | |
1212 | self::setAuthCookie($auth_cookie_name, $auth_cookie, $base_options + ['secure' => $secure, 'path' => ADMIN_COOKIE_PATH]); | |
1213 | self::setAuthCookie(LOGGED_IN_COOKIE, $logged_in_cookie, $base_options + ['secure' => $secure_logged_in_cookie, 'path' => COOKIEPATH]); | |
1214 | if (COOKIEPATH != SITECOOKIEPATH) { | |
1215 | self::setAuthCookie(LOGGED_IN_COOKIE, $logged_in_cookie, $base_options + ['secure' => $secure_logged_in_cookie, 'path' => SITECOOKIEPATH]); | |
1216 | } | |
1217 | } | |
1218 | ||
1219 | /** | |
1220 | * Set cookie with "SameSite" flag. | |
1221 | * | |
1222 | * The method here is compatible with all versions of PHP. Needed because it | |
1223 | * is only as of PHP 7.3.0 that the setcookie() method supports the "SameSite" | |
1224 | * attribute in its options and will accept "None" as a valid value. | |
1225 | * | |
1226 | * @param $name The name of the cookie. | |
1227 | * @param $value The value of the cookie. | |
1228 | * @param array $options The header options for the cookie. | |
1229 | */ | |
1230 | private function setAuthCookie($name, $value, $options) { | |
1231 | $header = 'Set-Cookie: '; | |
1232 | $header .= rawurlencode($name) . '=' . rawurlencode($value) . '; '; | |
1233 | $header .= 'expires=' . gmdate('D, d-M-Y H:i:s T', $options['expires']) . '; '; | |
1234 | $header .= 'Max-Age=' . max(0, (int) ($options['expires'] - time())) . '; '; | |
1235 | $header .= 'path=' . rawurlencode($options['path']) . '; '; | |
1236 | $header .= 'domain=' . rawurlencode($options['domain']) . '; '; | |
1237 | ||
1238 | if (!empty($options['secure'])) { | |
1239 | $header .= 'secure; '; | |
1240 | } | |
1241 | $header .= 'httponly; '; | |
1242 | $header .= 'SameSite=' . rawurlencode($options['samesite']); | |
1243 | ||
1244 | header($header, FALSE); | |
1245 | $_COOKIE[$name] = $value; | |
1246 | } | |
1247 | ||
839834b4 | 1248 | /** |
1249 | * Return the CMS-specific url for its permissions page | |
1250 | * @return array | |
1251 | */ | |
1252 | public function getCMSPermissionsUrlParams() { | |
1253 | return ['ufAccessURL' => CRM_Utils_System::url('civicrm/admin/access/wp-permissions', 'reset=1')]; | |
1254 | } | |
1255 | ||
6a488035 | 1256 | } |