-
-
Notifications
You must be signed in to change notification settings - Fork 825
/
Copy pathSystem.php
1985 lines (1791 loc) · 57.1 KB
/
System.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC https://civicrm.org/licensing
*/
use GuzzleHttp\Psr7\Response;
/**
* System wide utilities.
*
* Provides a collection of Civi utilities + access to the CMS-dependant utilities
*
* FIXME: This is a massive and random collection that could be split into smaller services
*
* @method static void getCMSPermissionsUrlParams() Immediately stop script execution and display a 401 "Access Denied" page.
* @method static mixed permissionDenied() Show access denied screen.
* @method static string getContentTemplate(int|string $print = 0) Get the template path to render whole content.
* @method static mixed logout() Log out the current user.
* @method static mixed updateCategories() Clear CMS caches related to the user registration/profile forms.
* @method static void appendBreadCrumb(array $breadCrumbs) Append an additional breadcrumb link to the existing breadcrumbs.
* @method static void resetBreadCrumb() Reset an additional breadcrumb tag to the existing breadcrumb.
* @method static void addHTMLHead(string $head) Append a string to the head of the HTML file.
* @method static string postURL(int $action) Determine the post URL for a form.
* @method static string|null getUFLocale() Get the locale of the CMS.
* @method static bool setUFLocale(string $civicrm_language) Set the locale of the CMS.
* @method static bool isUserLoggedIn() Check if user is logged in.
* @method static int getLoggedInUfID() Get current logged in user id.
* @method static void setHttpHeader(string $name, string $value) Set http header.
* @method static array synchronizeUsers() Create CRM contacts for all existing CMS users.
* @method static void appendCoreResources(\Civi\Core\Event\GenericHookEvent $e) Callback for hook_civicrm_coreResourceList.
* @method static void alterAssetUrl(\Civi\Core\Event\GenericHookEvent $e) Callback for hook_civicrm_getAssetUrl.
* @method static bool shouldExitAfterFatal() Should the current execution exit after a fatal error?
* @method static string|null currentPath() Path of the current page e.g. 'civicrm/contact/view'
*/
class CRM_Utils_System {
public static $_callbacks = NULL;
/**
* @var string
* Page title
*/
public static $title = '';
/**
* Access methods in the appropriate CMS class
*
* @param $name
* @param $arguments
* @return mixed
*/
public static function __callStatic($name, $arguments) {
$userSystem = CRM_Core_Config::singleton()->userSystem;
return call_user_func_array([$userSystem, $name], $arguments);
}
/**
* Compose a new URL string from the current URL string.
*
* Used by all the framework components, specifically,
* pager, sort and qfc
*
* @param string $urlVar
* The url variable being considered (i.e. crmPageID, crmSortID etc).
* @param bool $includeReset
* (optional) Whether to include the reset GET string (if present).
* @param bool $includeForce
* (optional) Whether to include the force GET string (if present).
* @param string $path
* (optional) The path to use for the new url.
* @param bool|string $absolute
* (optional) Whether to return an absolute URL.
*
* @return string
* The URL fragment.
*/
public static function makeURL($urlVar, $includeReset = FALSE, $includeForce = TRUE, $path = NULL, $absolute = FALSE) {
$path = $path ?: CRM_Utils_System::currentPath();
if (!$path) {
return '';
}
return self::url(
$path,
CRM_Utils_System::getLinksUrl($urlVar, $includeReset, $includeForce),
$absolute
);
}
/**
* Get the query string and clean it up.
*
* Strips some variables that should not be propagated, specifically variables
* like 'reset'. Also strips any side-affect actions (e.g. export).
*
* This function is copied mostly verbatim from Pager.php (_getLinksUrl)
*
* @param string $urlVar
* The URL variable being considered (e.g. crmPageID, crmSortID etc).
* @param bool $includeReset
* (optional) By default this is FALSE, meaning that the reset parameter
* is skipped. Set to TRUE to leave the reset parameter as-is.
* @param bool $includeForce
* (optional)
* @param bool $skipUFVar
* (optional)
*
* @return string
*/
public static function getLinksUrl($urlVar, $includeReset = FALSE, $includeForce = TRUE, $skipUFVar = TRUE) {
// Sort out query string to prevent messy urls
$querystring = [];
$qs = [];
$arrays = [];
if (!empty($_SERVER['QUERY_STRING'])) {
$qs = explode('&', str_replace('&', '&', $_SERVER['QUERY_STRING']));
for ($i = 0, $cnt = count($qs); $i < $cnt; $i++) {
// check first if exist a pair
if (str_contains($qs[$i], '=')) {
[$name, $value] = explode('=', $qs[$i]);
if ($name != $urlVar) {
$name = rawurldecode($name);
// check for arrays in parameters: site.php?foo[]=1&foo[]=2&foo[]=3
if ((strpos($name, '[') !== FALSE) &&
(strpos($name, ']') !== FALSE)
) {
$arrays[] = $qs[$i];
}
else {
$qs[$name] = $value;
}
}
}
else {
$qs[$qs[$i]] = '';
}
unset($qs[$i]);
}
}
if ($includeForce) {
$qs['force'] = 1;
}
// Ok this is a big assumption but usually works
// If we are in snippet mode, retain the 'section' param, if not, get rid
// of it.
if (!empty($qs['snippet'])) {
unset($qs['snippet']);
}
else {
unset($qs['section']);
}
if ($skipUFVar) {
$config = CRM_Core_Config::singleton();
unset($qs[$config->userFrameworkURLVar]);
}
foreach ($qs as $name => $value) {
if ($name != 'reset' || $includeReset) {
$querystring[] = $name . '=' . $value;
}
}
$querystring = array_merge($querystring, array_unique($arrays));
$url = implode('&', $querystring);
if ($urlVar) {
$url .= (!empty($querystring) ? '&' : '') . $urlVar . '=';
}
return $url;
}
/**
* 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
* (optional) Are we displaying to the screen or bypassing theming?
* @param bool $maintenance
* (optional) For maintenance mode.
*
* @return string
*/
public static function theme(
&$content,
$print = FALSE,
$maintenance = FALSE
) {
return CRM_Core_Config::singleton()->userSystem->theme($content, $print, $maintenance);
}
/**
* Generate a query string if input is an array.
*
* @param array|string $query
*
* @return string|null
*/
public static function makeQueryString($query) {
if (is_array($query)) {
$buf = '';
foreach ($query as $key => $value) {
$buf .= ($buf ? '&' : '') . urlencode($key ?? '') . '=' . urlencode($value ?? '');
}
$query = $buf;
}
return $query;
}
/**
* Generate an internal CiviCRM URL.
*
* @param string $path
* The path being linked to, such as "civicrm/add".
* @param array|string $query
* A query string to append to the link, or an array of key-value pairs.
* @param bool $absolute
* Whether to force the output to be an absolute link (beginning with a
* URI-scheme such as '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 $htmlize
* Whether to encode special html characters such as &.
* @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
* An HTML string containing a link to the given path.
*/
public static function url(
$path = '',
$query = '',
$absolute = FALSE,
$fragment = NULL,
$htmlize = TRUE,
$frontend = FALSE,
$forceBackend = FALSE
) {
// handle legacy null params
$path ??= '';
$query ??= '';
$query = self::makeQueryString($query);
// Legacy handling for when the system passes around html escaped strings
if (str_contains($query, '&')) {
$query = html_entity_decode($query);
}
// Extract fragment from path or query if munged together
if ($query && str_contains($query, '#')) {
[$path, $fragment] = explode('#', $query);
}
if ($path && str_contains($path, '#')) {
[$path, $fragment] = explode('#', $path);
}
// Extract query from path if munged together
if ($path && str_contains($path, '?')) {
[$path, $extraQuery] = explode('?', $path);
$query = $extraQuery . ($query ? "&$query" : '');
}
if ($frontend === FALSE && $forceBackend === FALSE && !empty($GLOBALS['civicrm_url_defaults'])) {
// Caller appears to want the "current://" scheme. For newer environments (eg web-service/iframe;
// not frontend/backend), we need
$urlObj = \Civi::url('current://' . $path)
->addQuery($query)
->addFragment($fragment)
->setPreferFormat($absolute ? 'absolute' : 'relative')
->setHtmlEscape($htmlize);
return (string) $urlObj;
}
$config = CRM_Core_Config::singleton();
$url = $config->userSystem->url($path, $query, $absolute, $fragment, $frontend, $forceBackend);
if ($htmlize) {
$url = htmlentities($url);
}
return $url;
}
/**
* Return the Notification URL for Payments.
*
* @param string $path
* The path being linked to, such as "civicrm/add".
* @param array|string $query
* A query string to append to the link, or an array of key-value pairs.
* @param bool $absolute
* Whether to force the output to be an absolute link (beginning with a
* URI-scheme such as '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 $htmlize
* Unused param
* @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
* The Notification URL.
*/
public static function getNotifyUrl(
$path = NULL,
$query = NULL,
$absolute = FALSE,
$fragment = NULL,
$htmlize = NULL,
$frontend = FALSE,
$forceBackend = FALSE
) {
$config = CRM_Core_Config::singleton();
$query = self::makeQueryString($query);
return $config->userSystem->getNotifyUrl($path, $query, $absolute, $fragment, $frontend, $forceBackend);
}
/**
* Generates an extern url.
*
* @param string $path
* The extern path, such as "extern/url".
* @param string $query
* A query string to append to the link.
* @param string $fragment
* A fragment identifier (named anchor) to append to the link.
* @param bool $absolute
* Whether to force the output to be an absolute link (beginning with a
* URI-scheme such as 'http:').
* @param bool $isSSL
* NULL to autodetect. TRUE to force to SSL.
*
* @return string rawencoded URL.
*/
public static function externUrl($path = NULL, $query = NULL, $fragment = NULL, $absolute = TRUE, $isSSL = NULL) {
$query = self::makeQueryString($query);
$url = Civi::paths()->getUrl("[civicrm.root]/{$path}.php", $absolute ? 'absolute' : 'relative', $isSSL)
. ($query ? "?$query" : "")
. ($fragment ? "#$fragment" : "");
$parsedUrl = CRM_Utils_Url::parseUrl($url);
$event = \Civi\Core\Event\GenericHookEvent::create([
'url' => &$parsedUrl,
'path' => $path,
'query' => $query,
'fragment' => $fragment,
'absolute' => $absolute,
'isSSL' => $isSSL,
]);
Civi::dispatcher()->dispatch('hook_civicrm_alterExternUrl', $event);
return urldecode(CRM_Utils_Url::unparseUrl($event->url));
}
/**
* Perform any current conversions/migrations on the extern URL.
*
* @param \Civi\Core\Event\GenericHookEvent $e
* @see CRM_Utils_Hook::alterExternUrl
*/
public static function migrateExternUrl(\Civi\Core\Event\GenericHookEvent $e) {
/**
* $mkRouteUri is a small adapter to return generated URL as a "UriInterface".
* @param string $path
* @param string $query
* @return \Psr\Http\Message\UriInterface
*/
$mkRouteUri = function ($path, $query) use ($e) {
$urlTxt = CRM_Utils_System::url($path, $query, $e->absolute, $e->fragment, FALSE, TRUE);
if ($e->isSSL || ($e->isSSL === NULL && \CRM_Utils_System::isSSL())) {
$urlTxt = str_replace('http://', 'https://', $urlTxt);
}
return CRM_Utils_Url::parseUrl($urlTxt);
};
switch (Civi::settings()->get('defaultExternUrl') . ':' . $e->path) {
case 'router:extern/open':
$e->url = $mkRouteUri('civicrm/mailing/open', preg_replace('/(^|&)q=/', '\1qid=', $e->query));
break;
case 'router:extern/url':
$e->url = $mkRouteUri('civicrm/mailing/url', $e->query);
break;
case 'router:extern/widget':
$e->url = $mkRouteUri('civicrm/contribute/widget', $e->query);
break;
// Otherwise, keep the default.
}
}
/**
* @deprecated
* @see \CRM_Utils_System::currentPath
*
* @return string|null
*/
public static function getUrlPath() {
CRM_Core_Error::deprecatedFunctionWarning('CRM_Utils_System::currentPath');
return self::currentPath();
}
/**
* Get href.
*
* @param string $text
* @param string $path
* @param string|array $query
* @param bool $absolute
* @param string $fragment
* @param bool $htmlize
* @param bool $frontend
* @param bool $forceBackend
*
* @return string
*/
public static function href(
$text, $path = NULL, $query = NULL, $absolute = TRUE,
$fragment = NULL, $htmlize = TRUE, $frontend = FALSE, $forceBackend = FALSE
) {
$url = self::url($path, $query, $absolute, $fragment, $htmlize, $frontend, $forceBackend);
return "<a href=\"$url\">$text</a>";
}
/**
* Compose a URL. This is a wrapper for `url()` which is optimized for use in Smarty.
*
* @see \smarty_function_crmURL()
* @param array $params
* URL properties. Keys are abbreviated ("p"<=>"path").
* See Smarty doc for full details.
* @return string
* URL
*/
public static function crmURL($params) {
$p = $params['p'] ?? NULL;
if (!isset($p)) {
$p = self::currentPath();
}
return self::url(
$p,
$params['q'] ?? NULL,
$params['a'] ?? FALSE,
$params['f'] ?? NULL,
$params['h'] ?? TRUE,
$params['fe'] ?? FALSE,
$params['fb'] ?? FALSE
);
}
/**
* Sets the title of the page.
*
* @param string $title
* Document title - plain text only
* @param string $pageTitle
* Page title (if different) - may include html
*/
public static function setTitle($title, $pageTitle = NULL) {
self::$title = $title;
$config = CRM_Core_Config::singleton();
return $config->userSystem->setTitle(CRM_Utils_String::purifyHtml($title), CRM_Utils_String::purifyHtml($pageTitle));
}
/**
* Figures and sets the userContext.
*
* Uses the referrer if valid else uses the default.
*
* @param array $names
* Referrer should match any str in this array.
* @param string $default
* (optional) The default userContext if no match found.
*/
public static function setUserContext($names, $default = NULL) {
$url = $default;
$session = CRM_Core_Session::singleton();
$referer = $_SERVER['HTTP_REFERER'] ?? NULL;
if ($referer && !empty($names)) {
foreach ($names as $name) {
if (str_contains($referer, $name)) {
$url = $referer;
break;
}
}
}
if ($url) {
$session->pushUserContext($url);
}
}
/**
* Gets a class name for an object.
*
* @param object $object
* Object whose class name is needed.
*
* @return string
* The class name of the object.
*/
public static function getClassName($object) {
return get_class($object);
}
/**
* Redirect to another URL.
*
* @param string $url
* The URL to provide to the browser via the Location header.
* @param array $context
* Optional additional information for the hook.
*/
public static function redirect($url = NULL, $context = []) {
if (!$url) {
$url = self::url('civicrm/dashboard', 'reset=1');
}
// replace the & characters with &
// this is kinda hackish but not sure how to do it right
$url = str_replace('&', '&', $url);
$context['output'] = $_GET['snippet'] ?? NULL;
if ($context['noindex'] ?? FALSE) {
self::setHttpHeader('X-Robots-Tag', 'noindex');
}
$parsedUrl = CRM_Utils_Url::parseUrl($url);
CRM_Utils_Hook::alterRedirect($parsedUrl, $context);
$url = CRM_Utils_Url::unparseUrl($parsedUrl);
// If we are in a json context, respond appropriately
if ($context['output'] === 'json') {
CRM_Core_Page_AJAX::returnJsonResponse([
'status' => 'redirect',
'userContext' => $url,
]);
}
self::setHttpHeader('Location', $url);
self::civiExit(0, ['url' => $url, 'context' => 'redirect']);
}
/**
* Redirect to another URL using JavaScript.
*
* Use an html based file with javascript embedded to redirect to another url
* This prevent the too many redirect errors emitted by various browsers
*
* @param string $url
* (optional) The destination URL.
* @param string $title
* (optional) The page title to use for the redirect page.
* @param string $message
* (optional) The message to provide in the body of the redirect page.
*/
public static function jsRedirect(
$url = NULL,
$title = NULL,
$message = NULL
) {
if (!$url) {
$url = self::url('civicrm/dashboard', 'reset=1');
}
if (!$title) {
$title = ts('CiviCRM task in progress');
}
if (!$message) {
$message = ts('A long running CiviCRM task is currently in progress. This message will be refreshed till the task is completed');
}
// replace the & characters with &
// this is kinda hackish but not sure how to do it right
$url = str_replace('&', '&', $url);
$template = CRM_Core_Smarty::singleton();
$template->assign('redirectURL', $url);
$template->assign('title', $title);
$template->assign('message', $message);
$html = $template->fetch('CRM/common/redirectJS.tpl');
echo $html;
self::civiExit();
}
/**
* Get the base URL of the system.
*
* @return string
*/
public static function baseURL() {
$config = CRM_Core_Config::singleton();
return $config->userFrameworkBaseURL;
}
/**
* Authenticate or abort.
*
* @param string $message
* @param bool $abort
*
* @return bool
*/
public static function authenticateAbort($message, $abort) {
if ($abort) {
echo $message;
self::civiExit(0);
}
else {
return FALSE;
}
}
/**
* Authenticate key.
*
* @param bool $abort
* (optional) Whether to exit; defaults to true.
*
* @return bool
*/
public static function authenticateKey($abort = TRUE) {
// also make sure the key is sent and is valid
$key = trim($_REQUEST['key'] ?? '');
$docAdd = "More info at: " . CRM_Utils_System::docURL2('sysadmin/setup/jobs', TRUE);
if (!$key) {
return self::authenticateAbort(
"ERROR: You need to send a valid key to execute this file. " . $docAdd . "\n",
$abort
);
}
$siteKey = defined('CIVICRM_SITE_KEY') ? CIVICRM_SITE_KEY : NULL;
if (!$siteKey || empty($siteKey)) {
return self::authenticateAbort(
"ERROR: You need to set a valid site key in civicrm.settings.php. " . $docAdd . "\n",
$abort
);
}
if (strlen($siteKey) < 8) {
return self::authenticateAbort(
"ERROR: Site key needs to be greater than 7 characters in civicrm.settings.php. " . $docAdd . "\n",
$abort
);
}
if (!hash_equals($siteKey, $key)) {
return self::authenticateAbort(
"ERROR: Invalid key value sent. " . $docAdd . "\n",
$abort
);
}
return TRUE;
}
/**
* Authenticate script.
*
* @param bool $abort
* @param string $name
* @param string $pass
* @param bool $storeInSession
* @param bool $loadCMSBootstrap
* @param bool $requireKey
*
* @return bool
*/
public static function authenticateScript($abort = TRUE, $name = NULL, $pass = NULL, $storeInSession = TRUE, $loadCMSBootstrap = TRUE, $requireKey = TRUE) {
// auth to make sure the user has a login/password to do a shell operation
// later on we'll link this to acl's
if (!$name) {
$name = trim($_REQUEST['name'] ?? '');
$pass = trim($_REQUEST['pass'] ?? '');
}
// its ok to have an empty password
if (!$name) {
return self::authenticateAbort(
"ERROR: You need to send a valid user name and password to execute this file\n",
$abort
);
}
if ($requireKey && !self::authenticateKey($abort)) {
return FALSE;
}
$result = CRM_Utils_System::authenticate($name, $pass, $loadCMSBootstrap);
if (!$result) {
return self::authenticateAbort(
"ERROR: Invalid username and/or password\n",
$abort
);
}
elseif ($storeInSession) {
// lets store contact id and user id in session
[$userID, $ufID, $randomNumber] = $result;
if ($userID && $ufID) {
$config = CRM_Core_Config::singleton();
$config->userSystem->setUserSession([$userID, $ufID]);
}
else {
return self::authenticateAbort(
"ERROR: Unexpected error, could not match userID and contactID",
$abort
);
}
}
return $result;
}
/**
* Authenticate the user against the uf db.
*
* In case of successful authentication, returns an array consisting of
* (contactID, ufID, unique string). Returns FALSE if authentication is
* unsuccessful.
*
* @param string $name
* The username.
* @param string $password
* The password.
* @param bool $loadCMSBootstrap
* @param string $realPath
*
* @return false|array
*/
public static function authenticate($name, $password, $loadCMSBootstrap = FALSE, $realPath = NULL) {
$config = CRM_Core_Config::singleton();
return $config->userSystem->authenticate($name, $password, $loadCMSBootstrap, $realPath);
}
/**
* Set a message in the UF to display to a user.
*
* @param string $message
* The message to set.
*/
public static function setUFMessage($message) {
$config = CRM_Core_Config::singleton();
return $config->userSystem->setMessage($message);
}
/**
* Determine whether a value is null-ish.
*
* @param mixed $value
* The value to check for null.
*
* @return bool
*/
public static function isNull($value) {
// FIXME: remove $value = 'null' string test when we upgrade our DAO code to handle passing null in a better way.
if (!isset($value) || $value === NULL || $value === '' || $value === 'null') {
return TRUE;
}
if (is_array($value)) {
// @todo Reuse of the $value variable = asking for trouble.
foreach ($value as $key => $value) {
if (in_array($key, CRM_Core_DAO::acceptedSQLOperators(), TRUE) || !self::isNull($value)) {
return FALSE;
}
}
return TRUE;
}
return FALSE;
}
/**
* Obscure all but the last few digits of a credit card number.
*
* @param string $number
* The credit card number to obscure.
* @param int $keep
* (optional) The number of digits to preserve unmodified.
*
* @return string
* The obscured credit card number.
*/
public static function mungeCreditCard($number, $keep = 4) {
$number = trim($number ?? '');
if (empty($number)) {
return NULL;
}
$replace = str_repeat('*', strlen($number) - $keep);
return substr_replace($number, $replace, 0, -$keep);
}
/**
* Determine which PHP modules are loaded.
*
* @return array
*/
private static function parsePHPModules() {
ob_start();
phpinfo(INFO_MODULES);
$s = ob_get_contents();
ob_end_clean();
$s = strip_tags($s, '<h2><th><td>');
$s = preg_replace('/<th[^>]*>([^<]+)<\/th>/', "<info>\\1</info>", $s);
$s = preg_replace('/<td[^>]*>([^<]+)<\/td>/', "<info>\\1</info>", $s);
$vTmp = preg_split('/(<h2>[^<]+<\/h2>)/', $s, -1, PREG_SPLIT_DELIM_CAPTURE);
$vModules = [];
for ($i = 1; $i < count($vTmp); $i++) {
if (preg_match('/<h2>([^<]+)<\/h2>/', $vTmp[$i], $vMat)) {
$vName = trim($vMat[1]);
$vTmp2 = explode("\n", $vTmp[$i + 1]);
foreach ($vTmp2 as $vOne) {
$vPat = '<info>([^<]+)<\/info>';
$vPat3 = "/$vPat\s*$vPat\s*$vPat/";
$vPat2 = "/$vPat\s*$vPat/";
// 3cols
if (preg_match($vPat3, $vOne, $vMat)) {
$vModules[$vName][trim($vMat[1])] = [trim($vMat[2]), trim($vMat[3])];
// 2cols
}
elseif (preg_match($vPat2, $vOne, $vMat)) {
$vModules[$vName][trim($vMat[1])] = trim($vMat[2]);
}
}
}
}
return $vModules;
}
/**
* Get a setting from a loaded PHP module.
*
* @param string $pModuleName
* @param string $pSetting
*
* @return mixed
*/
public static function getModuleSetting($pModuleName, $pSetting) {
$vModules = self::parsePHPModules();
return $vModules[$pModuleName][$pSetting];
}
/**
* Do something no-one bothered to document.
*
* @param string $title
* (optional)
*
* @return mixed|string
*/
public static function memory($title = NULL) {
static $pid = NULL;
if (!$pid) {
$pid = posix_getpid();
}
$memory = str_replace("\n", '', shell_exec("ps -p" . $pid . " -o rss="));
$memory .= ", " . time();
if ($title) {
CRM_Core_Error::debug_var($title, $memory);
}
return $memory;
}
/**
* Download something or other.
*
* @param string $name
* @param string $mimeType
* @param string $buffer
* @param string $ext
* @param bool $output
* @param string $disposition
*/
public static function download(
$name, $mimeType, &$buffer,
$ext = NULL,
$output = TRUE,
$disposition = 'attachment'
) {
$now = gmdate('D, d M Y H:i:s') . ' GMT';
self::setHttpHeader('Content-Type', $mimeType);
self::setHttpHeader('Expires', $now);
// lem9 & loic1: IE needs specific headers
$isIE = empty($_SERVER['HTTP_USER_AGENT']) ? FALSE : strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE');
if ($ext) {
$fileString = "filename=\"{$name}.{$ext}\"";
}
else {
$fileString = "filename=\"{$name}\"";
}
if ($isIE) {
self::setHttpHeader("Content-Disposition", "inline; $fileString");
self::setHttpHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
self::setHttpHeader('Pragma', 'public');
}
else {
self::setHttpHeader("Content-Disposition", "$disposition; $fileString");
self::setHttpHeader('Pragma', 'no-cache');
}
if ($output) {
print $buffer;
self::civiExit();
}
}
/**
* Gather and print (and possibly log) amount of used memory.
*
* @param string $title
* @param bool $log
* (optional) Whether to log the memory usage information.
*/
public static function xMemory($title = NULL, $log = FALSE) {
$mem = (float) xdebug_memory_usage() / (float) (1024);
$mem = number_format($mem, 5) . ", " . time();
if ($log) {
echo "<p>$title: $mem<p>";
flush();
CRM_Core_Error::debug_var($title, $mem);
}
else {
echo "<p>$title: $mem<p>";
flush();
}
}
/**
* Take a URL (or partial URL) and make it better.
*
* Currently, URLs pass straight through unchanged unless they are "seriously
* malformed" (see http://us2.php.net/parse_url).
*
* @param string $url
* The URL to operate on.
*
* @return string
* The fixed URL.
*/
public static function fixURL($url) {
$components = parse_url($url);
if (!$components) {
return NULL;
}
// at some point we'll add code here to make sure the url is not
// something that will mess up, so we need to clean it up here
return $url;
}
/**
* Make sure a callback is valid in the current context.
*
* @param string $callback
* Name of the function to check.
*
* @return bool
*/
public static function validCallback($callback) {
if (self::$_callbacks === NULL) {
self::$_callbacks = [];