Add Serialize key to payment_processor field for Event & ContributionPage
[civicrm-core.git] / CRM / Core / DAO.php
CommitLineData
6a488035
TO
1<?php
2/*
bc77d7c0
TO
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 |
9 +--------------------------------------------------------------------+
ced9bfed 10 */
6a488035
TO
11
12/**
44ce4aa3
CW
13 * Base Database Access Object class.
14 *
15 * All DAO classes should inherit from this class.
6a488035
TO
16 *
17 * @package CRM
ca5cec67 18 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
19 */
20
b3029f89
SL
21if (!defined('DB_DSN_MODE')) {
22 define('DB_DSN_MODE', 'auto');
23}
24
6a488035
TO
25require_once 'PEAR.php';
26require_once 'DB/DataObject.php';
27
28require_once 'CRM/Core/I18n.php';
28518c90
EM
29
30/**
31 * Class CRM_Core_DAO
32 */
6a488035
TO
33class CRM_Core_DAO extends DB_DataObject {
34
ffcc1d11 35 /**
36 * How many times has this instance been cloned.
37 *
38 * @var int
39 */
40 protected $resultCopies = 0;
41
6a488035 42 /**
1273d77c
CW
43 * @var null
44 * @deprecated
6a488035 45 */
518fa0ee 46 public static $_nullObject = NULL;
449c4e6b
CW
47
48 /**
49 * Icon associated with this entity.
50 *
51 * @var string
52 */
53 public static $_icon = NULL;
54
1273d77c
CW
55 /**
56 * @var array
57 * @deprecated
58 */
518fa0ee 59 public static $_nullArray = [];
6a488035 60
518fa0ee 61 public static $_dbColumnValueCache = NULL;
7da04cde 62 const NOT_NULL = 1, IS_NULL = 2,
353ffa53
TO
63 DB_DAO_NOTNULL = 128,
64 VALUE_SEPARATOR = "\ 1",
65 BULK_INSERT_COUNT = 200,
66 BULK_INSERT_HIGH_COUNT = 200,
353ffa53 67 QUERY_FORMAT_WILDCARD = 1,
2a5c9b4d 68 QUERY_FORMAT_NO_QUOTES = 2,
168c8704
CW
69
70 /**
71 * Serialized string separated by and bookended with VALUE_SEPARATOR
72 */
2a5c9b4d 73 SERIALIZE_SEPARATOR_BOOKEND = 1,
168c8704
CW
74 /**
75 * @deprecated format separated by VALUE_SEPARATOR
76 */
2a5c9b4d 77 SERIALIZE_SEPARATOR_TRIMMED = 2,
168c8704
CW
78 /**
79 * Recommended serialization format
80 */
81 SERIALIZE_JSON = 3,
82 /**
83 * @deprecated format using php serialize()
84 */
dd3ec98b
CW
85 SERIALIZE_PHP = 4,
86 /**
87 * Comma separated string, no quotes, no spaces
88 */
89 SERIALIZE_COMMA = 5;
887a4028 90
d424ffde 91 /**
6a488035 92 * Define entities that shouldn't be created or deleted when creating/ deleting
d424ffde
CW
93 * test objects - this prevents world regions, countries etc from being added / deleted
94 * @var array
6a488035 95 */
518fa0ee 96 public static $_testEntitiesToSkip = [];
6a488035 97 /**
fe482240 98 * The factory class for this application.
6a488035
TO
99 * @var object
100 */
518fa0ee 101 public static $_factory = NULL;
6a488035 102
518fa0ee 103 public static $_checkedSqlFunctionsExist = FALSE;
aca2de91 104
33092c89
SB
105 /**
106 * https://issues.civicrm.org/jira/browse/CRM-17748
107 * internal variable for DAO to hold per-query settings
518fa0ee 108 * @var array
33092c89 109 */
be2fb01f 110 protected $_options = [];
33092c89 111
6a488035 112 /**
fe482240 113 * Class constructor.
6a488035 114 *
77b97be7 115 * @return \CRM_Core_DAO
6a488035 116 */
00be9182 117 public function __construct() {
6a488035
TO
118 $this->initialize();
119 $this->__table = $this->getTableName();
120 }
121
449c4e6b
CW
122 /**
123 * Returns localized title of this entity.
124 * @return string
125 */
126 public static function getEntityTitle() {
127 $className = static::class;
128 Civi::log()->warning("$className needs to be regeneraged. Missing getEntityTitle method.", ['civi.tag' => 'deprecated']);
129 return CRM_Core_DAO_AllCoreTables::getBriefName($className);
130 }
131
ffcc1d11 132 public function __clone() {
133 if (!empty($this->_DB_resultid)) {
134 $this->resultCopies++;
135 }
136 }
137
138 /**
139 * Class destructor.
140 */
141 public function __destruct() {
142 if ($this->resultCopies === 0) {
143 $this->free();
144 }
145 $this->resultCopies--;
146 }
147
6a488035 148 /**
fe482240 149 * Empty definition for virtual function.
6a488035 150 */
00be9182 151 public static function getTableName() {
6a488035
TO
152 return NULL;
153 }
154
155 /**
fe482240 156 * Initialize the DAO object.
6a488035 157 *
6a0b768e
TO
158 * @param string $dsn
159 * The database connection string.
6a488035 160 */
00be9182 161 public static function init($dsn) {
3a036b15 162 Civi::$statics[__CLASS__]['init'] = 1;
6a488035
TO
163 $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
164 $options['database'] = $dsn;
078428c7 165 $options['quote_identifiers'] = TRUE;
6f738dbf 166 if (self::isSSLDSN($dsn)) {
167 // There are two different options arrays.
168 $other_options = &PEAR::getStaticProperty('DB', 'options');
169 $other_options['ssl'] = TRUE;
170 }
6a488035
TO
171 if (defined('CIVICRM_DAO_DEBUG')) {
172 self::DebugLevel(CIVICRM_DAO_DEBUG);
173 }
f720cdf0 174 $factory = new CRM_Contact_DAO_Factory();
175 CRM_Core_DAO::setFactory($factory);
712e729f 176 $currentModes = CRM_Utils_SQL::getSqlModes();
635f0b86 177 if (CRM_Utils_Constant::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System::isDevelopment())) {
a2ed62b3 178 if (CRM_Utils_SQL::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) {
403b1c11
SL
179 $currentModes[] = 'ONLY_FULL_GROUP_BY';
180 }
907995af 181 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
be2fb01f 182 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
9b065dcf 183 }
be2fb01f 184 CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
635f0b86 185 }
d10ba6cb 186 CRM_Core_DAO::executeQuery('SET NAMES utf8mb4');
be2fb01f 187 CRM_Core_DAO::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request::id(), 'String']]);
6a488035
TO
188 }
189
e95fbe72
TO
190 /**
191 * @return DB_common
192 */
193 public static function getConnection() {
194 global $_DB_DATAOBJECT;
195 $dao = new CRM_Core_DAO();
196 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5];
197 }
198
84cb7d10
SL
199 /**
200 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
201 */
202 public static function disableFullGroupByMode() {
203 $currentModes = CRM_Utils_SQL::getSqlModes();
63dc1f23 204 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) {
84cb7d10
SL
205 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
206 unset($currentModes[$key]);
be2fb01f 207 CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
84cb7d10
SL
208 }
209 }
210
211 /**
2f68ef20 212 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
84cb7d10 213 */
2f68ef20 214 public static function reenableFullGroupByMode() {
84cb7d10 215 $currentModes = CRM_Utils_SQL::getSqlModes();
63dc1f23 216 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL::isGroupByModeInDefault()) {
84cb7d10 217 $currentModes[] = 'ONLY_FULL_GROUP_BY';
be2fb01f 218 CRM_Core_DAO::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
84cb7d10
SL
219 }
220 }
221
e1b64aab 222 /**
100fef9d 223 * @param string $fieldName
e1b64aab 224 * @param $fieldDef
c490a46a 225 * @param array $params
e1b64aab 226 */
e79cd558 227 protected function assignTestFK($fieldName, $fieldDef, $params) {
9c1bc317
CW
228 $required = $fieldDef['required'] ?? NULL;
229 $FKClassName = $fieldDef['FKClassName'] ?? NULL;
e1b64aab 230 $dbName = $fieldDef['name'];
2444854d 231 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
e1b64aab
TO
232
233 // skip the FK if it is not required
234 // if it's contact id we should create even if not required
235 // we'll have a go @ fetching first though
236 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
237 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
238 $required = TRUE;
239 }
240 if (!$required && $dbName != 'contact_id') {
795492f3 241 $fkDAO = new $FKClassName();
e1b64aab 242 if ($fkDAO->find(TRUE)) {
e79cd558 243 $this->$dbName = $fkDAO->id;
e1b64aab 244 }
e1b64aab
TO
245 }
246
247 elseif (in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)) {
248 $depObject = new $FKClassName();
249 $depObject->find(TRUE);
e79cd558 250 $this->$dbName = $depObject->id;
e1b64aab
TO
251 }
252 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
253 // FIXME: the fields() metadata is not specific enough
be2fb01f 254 $depObject = CRM_Core_DAO::createTestObject($FKClassName, ['contact_type' => 'Organization']);
e79cd558 255 $this->$dbName = $depObject->id;
e1b64aab
TO
256 }
257 else {
258 //if it is required we need to generate the dependency object first
259 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
e79cd558 260 $this->$dbName = $depObject->id;
e1b64aab
TO
261 }
262 }
263
264 /**
e79cd558
TO
265 * Generate and assign an arbitrary value to a field of a test object.
266 *
267 * @param string $fieldName
268 * @param array $fieldDef
6a0b768e
TO
269 * @param int $counter
270 * The globally-unique ID of the test object.
7c58994a 271 *
272 * @throws \CRM_Core_Exception
e1b64aab 273 */
e79cd558
TO
274 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
275 $dbName = $fieldDef['name'];
276 $daoName = get_class($this);
e1b64aab
TO
277 $handled = FALSE;
278
e79cd558 279 if (!$handled && $dbName == 'contact_sub_type') {
e1b64aab
TO
280 //coming up with a rule to set this is too complex let's not set it
281 $handled = TRUE;
282 }
283
284 // Pick an option value if needed
285 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type::T_BOOLEAN) {
286 $options = $daoName::buildOptions($dbName, 'create');
287 if ($options) {
e79cd558 288 $this->$dbName = key($options);
e1b64aab
TO
289 $handled = TRUE;
290 }
291 }
292
293 if (!$handled) {
294 switch ($fieldDef['type']) {
295 case CRM_Utils_Type::T_INT:
296 case CRM_Utils_Type::T_FLOAT:
297 case CRM_Utils_Type::T_MONEY:
298 if (isset($fieldDef['precision'])) {
299 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
e79cd558 300 $this->$dbName = CRM_Utils_Number::createTruncatedDecimal($counter, $fieldDef['precision']);
e1b64aab
TO
301 }
302 else {
e79cd558 303 $this->$dbName = $counter;
e1b64aab
TO
304 }
305 break;
306
307 case CRM_Utils_Type::T_BOOLEAN:
308 if (isset($fieldDef['default'])) {
e79cd558 309 $this->$dbName = $fieldDef['default'];
e1b64aab
TO
310 }
311 elseif ($fieldDef['name'] == 'is_deleted' || $fieldDef['name'] == 'is_test') {
e79cd558 312 $this->$dbName = 0;
e1b64aab
TO
313 }
314 else {
e79cd558 315 $this->$dbName = 1;
e1b64aab
TO
316 }
317 break;
318
319 case CRM_Utils_Type::T_DATE:
e1b64aab 320 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
e79cd558 321 $this->$dbName = '19700101';
e1b64aab
TO
322 if ($dbName == 'end_date') {
323 // put this in the future
e79cd558 324 $this->$dbName = '20200101';
e1b64aab
TO
325 }
326 break;
327
2149f4bd 328 case CRM_Utils_Type::T_TIMESTAMP:
329 $this->$dbName = '19700201000000';
330 break;
331
e1b64aab 332 case CRM_Utils_Type::T_TIME:
7c58994a 333 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
334
e1b64aab 335 case CRM_Utils_Type::T_CCNUM:
e79cd558 336 $this->$dbName = '4111 1111 1111 1111';
e1b64aab
TO
337 break;
338
339 case CRM_Utils_Type::T_URL:
e79cd558 340 $this->$dbName = 'http://www.civicrm.org';
e1b64aab
TO
341 break;
342
343 case CRM_Utils_Type::T_STRING:
344 case CRM_Utils_Type::T_BLOB:
345 case CRM_Utils_Type::T_MEDIUMBLOB:
346 case CRM_Utils_Type::T_TEXT:
347 case CRM_Utils_Type::T_LONGTEXT:
348 case CRM_Utils_Type::T_EMAIL:
349 default:
350 // WAS: if (isset($value['enumValues'])) {
351 // TODO: see if this works with all pseudoconstants
352 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
353 if (isset($fieldDef['default'])) {
e79cd558 354 $this->$dbName = $fieldDef['default'];
e1b64aab
TO
355 }
356 else {
357 $options = CRM_Core_PseudoConstant::get($daoName, $fieldName);
358 if (is_array($options)) {
e79cd558 359 $this->$dbName = $options[0];
e1b64aab
TO
360 }
361 else {
362 $defaultValues = explode(',', $options);
e79cd558 363 $this->$dbName = $defaultValues[0];
e1b64aab
TO
364 }
365 }
366 }
367 else {
e79cd558 368 $this->$dbName = $dbName . '_' . $counter;
9c1bc317 369 $maxlength = $fieldDef['maxlength'] ?? NULL;
e79cd558
TO
370 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
371 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
e1b64aab
TO
372 }
373 }
374 }
375 }
376 }
377
6a488035 378 /**
8eedd10a 379 * Reset the DAO object.
6a488035 380 *
8eedd10a 381 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
382 *
383 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
6a488035 384 */
00be9182 385 public function reset() {
6a488035
TO
386
387 foreach (array_keys($this->table()) as $field) {
388 unset($this->$field);
389 }
390
391 /**
392 * reset the various DB_DAO structures manually
393 */
be2fb01f 394 $this->_query = [];
6a488035
TO
395 $this->whereAdd();
396 $this->selectAdd();
397 $this->joinAdd();
398 }
399
a0ee3941 400 /**
100fef9d 401 * @param string $tableName
a0ee3941
EM
402 *
403 * @return string
404 */
00be9182 405 public static function getLocaleTableName($tableName) {
6a488035
TO
406 global $dbLocale;
407 if ($dbLocale) {
408 $tables = CRM_Core_I18n_Schema::schemaStructureTables();
409 if (in_array($tableName, $tables)) {
410 return $tableName . $dbLocale;
411 }
412 }
413 return $tableName;
414 }
415
416 /**
417 * Execute a query by the current DAO, localizing it along the way (if needed).
418 *
6a0b768e
TO
419 * @param string $query
420 * The SQL query for execution.
421 * @param bool $i18nRewrite
422 * Whether to rewrite the query.
6a488035 423 *
a6c01b45
CW
424 * @return object
425 * the current DAO object after the query execution
6a488035 426 */
00be9182 427 public function query($query, $i18nRewrite = TRUE) {
6a488035 428 // rewrite queries that should use $dbLocale-based views for multi-language installs
33092c89
SB
429 global $dbLocale, $_DB_DATAOBJECT;
430
96f346f8 431 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5])) {
432 // Will force connection to be populated per CRM-20541.
433 new CRM_Core_DAO();
434 }
435
33092c89
SB
436 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
437 $orig_options = $conn->options;
438 $this->_setDBOptions($this->_options);
439
6a488035
TO
440 if ($i18nRewrite and $dbLocale) {
441 $query = CRM_Core_I18n_Schema::rewriteQuery($query);
442 }
443
33092c89
SB
444 $ret = parent::query($query);
445
446 $this->_setDBOptions($orig_options);
447 return $ret;
6a488035
TO
448 }
449
450 /**
451 * Static function to set the factory instance for this class.
452 *
6a0b768e
TO
453 * @param object $factory
454 * The factory application object.
6a488035 455 */
00be9182 456 public static function setFactory(&$factory) {
6a488035
TO
457 self::$_factory = &$factory;
458 }
459
460 /**
461 * Factory method to instantiate a new object from a table name.
462 *
da6b46f4 463 * @param string $table
44ce4aa3 464 * @return \DataObject|\PEAR_Error
6a488035 465 */
00be9182 466 public function factory($table = '') {
6a488035
TO
467 if (!isset(self::$_factory)) {
468 return parent::factory($table);
469 }
470
471 return self::$_factory->create($table);
472 }
473
474 /**
475 * Initialization for all DAO objects. Since we access DB_DO programatically
476 * we need to set the links manually.
6a488035 477 */
00be9182 478 public function initialize() {
6a488035 479 $this->_connect();
3a036b15
TO
480 if (empty(Civi::$statics[__CLASS__]['init'])) {
481 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
482 // This occurs very early in bootstrap - error handlers may not be wired up.
483 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
484 CRM_Utils_System::civiExit();
485 }
6a488035
TO
486 }
487
488 /**
489 * Defines the default key as 'id'.
490 *
6a488035
TO
491 * @return array
492 */
00be9182 493 public function keys() {
6a488035
TO
494 static $keys;
495 if (!isset($keys)) {
be2fb01f 496 $keys = ['id'];
6a488035
TO
497 }
498 return $keys;
499 }
500
501 /**
502 * Tells DB_DataObject which keys use autoincrement.
503 * 'id' is autoincrementing by default.
504 *
6a488035
TO
505 *
506 * @return array
507 */
00be9182 508 public function sequenceKey() {
6a488035
TO
509 static $sequenceKeys;
510 if (!isset($sequenceKeys)) {
be2fb01f 511 $sequenceKeys = ['id', TRUE];
6a488035
TO
512 }
513 return $sequenceKeys;
514 }
515
516 /**
fe482240 517 * Returns list of FK relationships.
6a488035 518 *
6a488035 519 *
a6c01b45 520 * @return array
16b10e64 521 * Array of CRM_Core_Reference_Interface
6a488035 522 */
00be9182 523 public static function getReferenceColumns() {
be2fb01f 524 return [];
6a488035
TO
525 }
526
527 /**
fe482240 528 * Returns all the column names of this table.
6a488035 529 *
6a488035
TO
530 *
531 * @return array
532 */
795492f3 533 public static function &fields() {
6a488035
TO
534 $result = NULL;
535 return $result;
536 }
537
2ca7273b
CW
538 /**
539 * Returns all usable fields, indexed by name.
540 *
541 * This function differs from fields() in that it indexes by name rather than unique_name.
542 *
543 * It excludes fields not added yet by pending upgrades.
544 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
545 *
546 * @param bool $checkPermissions
547 * Filter by field permissions.
548 * @return array
549 */
550 public static function getSupportedFields($checkPermissions = FALSE) {
551 $fields = array_column((array) static::fields(), NULL, 'name');
552
553 // Exclude fields yet not added by pending upgrades
554 $dbVer = \CRM_Core_BAO_Domain::version();
555 if ($fields && version_compare($dbVer, \CRM_Utils_System::version()) < 0) {
556 $fields = array_filter($fields, function($field) use ($dbVer) {
557 $add = $field['add'] ?? '1.0.0';
558 if (substr_count($add, '.') < 2) {
559 $add .= '.alpha1';
560 }
561 return version_compare($dbVer, $add, '>=');
562 });
563 }
564
565 // Exclude fields the user does not have permission for
566 if ($checkPermissions) {
567 $fields = array_filter($fields, function($field) {
568 return empty($field['permission']) || CRM_Core_Permission::check($field['permission']);
569 });
570 }
571
572 return $fields;
573 }
574
b5c2afd0 575 /**
100fef9d 576 * Get/set an associative array of table columns
b5c2afd0 577 *
a6c01b45
CW
578 * @return array
579 * (associative)
b5c2afd0 580 */
00be9182 581 public function table() {
44ce4aa3 582 $fields = $this->fields();
6a488035 583
be2fb01f 584 $table = [];
6a488035
TO
585 if ($fields) {
586 foreach ($fields as $name => $value) {
587 $table[$value['name']] = $value['type'];
a7488080 588 if (!empty($value['required'])) {
6a488035
TO
589 $table[$value['name']] += self::DB_DAO_NOTNULL;
590 }
591 }
592 }
593
6a488035
TO
594 return $table;
595 }
596
a0ee3941 597 /**
ea3ddccf 598 * Save DAO object.
599 *
600 * @param bool $hook
601 *
14069c56 602 * @return CRM_Core_DAO
a0ee3941 603 */
9f35e05d 604 public function save($hook = TRUE) {
6a488035 605 if (!empty($this->id)) {
e232c68f
CW
606 if ($hook) {
607 $preEvent = new \Civi\Core\DAO\Event\PreUpdate($this);
4162ab6f 608 \Civi::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
e232c68f
CW
609 }
610
611 $result = $this->update();
8498c2b7 612
9f35e05d 613 if ($hook) {
e232c68f 614 $event = new \Civi\Core\DAO\Event\PostUpdate($this, $result);
4162ab6f 615 \Civi::dispatcher()->dispatch("civi.dao.postUpdate", $event);
9f35e05d 616 }
10cac951 617 $this->clearDbColumnValueCache();
6a488035
TO
618 }
619 else {
e232c68f
CW
620 if ($hook) {
621 $preEvent = new \Civi\Core\DAO\Event\PreUpdate($this);
4162ab6f 622 \Civi::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
e232c68f
CW
623 }
624
625 $result = $this->insert();
8498c2b7 626
9f35e05d 627 if ($hook) {
e232c68f 628 $event = new \Civi\Core\DAO\Event\PostUpdate($this, $result);
4162ab6f 629 \Civi::dispatcher()->dispatch("civi.dao.postInsert", $event);
9f35e05d 630 }
6a488035
TO
631 }
632 $this->free();
633
9f35e05d
TO
634 if ($hook) {
635 CRM_Utils_Hook::postSave($this);
636 }
6a488035
TO
637
638 return $this;
639 }
640
1cd3ffa9 641 /**
fe482240 642 * Deletes items from table which match current objects variables.
1cd3ffa9
EM
643 *
644 * Returns the true on success
645 *
646 * for example
647 *
648 * Designed to be extended
649 *
650 * $object = new mytable();
651 * $object->ID=123;
652 * echo $object->delete(); // builds a conditon
653 *
654 * $object = new mytable();
655 * $object->whereAdd('age > 12');
656 * $object->limit(1);
657 * $object->orderBy('age DESC');
658 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
659 *
660 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
661 * we will build the condition only using the whereAdd's. Default is to
662 * build the condition only using the object parameters.
663 *
664 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
665 */
00be9182 666 public function delete($useWhere = FALSE) {
7b83ea83 667 $preEvent = new \Civi\Core\DAO\Event\PreDelete($this);
4162ab6f 668 \Civi::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
7b83ea83 669
97c4fe76 670 $result = parent::delete($useWhere);
8498c2b7 671
48d849b1 672 $event = new \Civi\Core\DAO\Event\PostDelete($this, $result);
4162ab6f 673 \Civi::dispatcher()->dispatch("civi.dao.postDelete", $event);
37eb13b2 674 $this->free();
8498c2b7 675
10cac951
CW
676 $this->clearDbColumnValueCache();
677
97c4fe76 678 return $result;
679 }
680
a0ee3941
EM
681 /**
682 * @param bool $created
683 */
00be9182 684 public function log($created = FALSE) {
6a488035
TO
685 static $cid = NULL;
686
687 if (!$this->getLog()) {
688 return;
689 }
690
691 if (!$cid) {
692 $session = CRM_Core_Session::singleton();
693 $cid = $session->get('userID');
694 }
695
696 // return is we dont have handle to FK
697 if (!$cid) {
698 return;
699 }
700
353ffa53
TO
701 $dao = new CRM_Core_DAO_Log();
702 $dao->entity_table = $this->getTableName();
703 $dao->entity_id = $this->id;
704 $dao->modified_id = $cid;
6a488035
TO
705 $dao->modified_date = date("YmdHis");
706 $dao->insert();
707 }
708
709 /**
710 * Given an associative array of name/value pairs, extract all the values
711 * that belong to this object and initialize the object with said values
712 *
6a0b768e 713 * @param array $params
fc944198 714 * Array of name/value pairs to save.
6a488035 715 *
795492f3
TO
716 * @return bool
717 * Did we copy all null values into the object
6a488035 718 */
fc944198 719 public function copyValues($params) {
6a488035 720 $allNull = TRUE;
fc944198
CW
721 foreach ($this->fields() as $uniqueName => $field) {
722 $dbName = $field['name'];
6a488035 723 if (array_key_exists($dbName, $params)) {
fc944198 724 $value = $params[$dbName];
6a488035
TO
725 $exists = TRUE;
726 }
fc944198
CW
727 elseif (array_key_exists($uniqueName, $params)) {
728 $value = $params[$uniqueName];
6a488035
TO
729 $exists = TRUE;
730 }
731 else {
732 $exists = FALSE;
733 }
734
735 // if there is no value then make the variable NULL
736 if ($exists) {
fc944198 737 if ($value === '') {
6a488035
TO
738 $this->$dbName = 'null';
739 }
fc944198
CW
740 elseif (is_array($value) && !empty($field['serialize'])) {
741 $this->$dbName = CRM_Core_DAO::serializeField($value, $field['serialize']);
30208fab 742 $allNull = FALSE;
743 }
6a488035 744 else {
9c1bc317 745 $maxLength = $field['maxlength'] ?? NULL;
fc944198
CW
746 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
747 Civi::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type::escape($value, 'String')]));
809e1a83 748 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
fc944198 749 $value = CRM_Utils_String::ellipsify($value, $maxLength);
809e1a83 750 }
fc944198 751 $this->$dbName = $value;
6a488035
TO
752 $allNull = FALSE;
753 }
754 }
755 }
756 return $allNull;
757 }
758
759 /**
760 * Store all the values from this object in an associative array
761 * this is a destructive store, calling function is responsible
762 * for keeping sanity of id's.
763 *
6a0b768e
TO
764 * @param object $object
765 * The object that we are extracting data from.
766 * @param array $values
767 * (reference ) associative array of name/value pairs.
6a488035 768 */
00be9182 769 public static function storeValues(&$object, &$values) {
44ce4aa3 770 $fields = $object->fields();
6a488035
TO
771 foreach ($fields as $name => $value) {
772 $dbName = $value['name'];
773 if (isset($object->$dbName) && $object->$dbName !== 'null') {
774 $values[$dbName] = $object->$dbName;
775 if ($name != $dbName) {
776 $values[$name] = $object->$dbName;
777 }
778 }
779 }
780 }
781
782 /**
100fef9d 783 * Create an attribute for this specific field. We only do this for strings and text
6a488035 784 *
6a0b768e
TO
785 * @param array $field
786 * The field under task.
6a488035 787 *
72b3a70c
CW
788 * @return array|null
789 * the attributes for the object
6a488035 790 */
00be9182 791 public static function makeAttribute($field) {
6a488035
TO
792 if ($field) {
793 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
9c1bc317
CW
794 $maxLength = $field['maxlength'] ?? NULL;
795 $size = $field['size'] ?? NULL;
6a488035 796 if ($maxLength || $size) {
be2fb01f 797 $attributes = [];
6a488035
TO
798 if ($maxLength) {
799 $attributes['maxlength'] = $maxLength;
800 }
801 if ($size) {
802 $attributes['size'] = $size;
803 }
804 return $attributes;
805 }
806 }
807 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) {
9c1bc317 808 $rows = $field['rows'] ?? NULL;
6a488035
TO
809 if (!isset($rows)) {
810 $rows = 2;
811 }
9c1bc317 812 $cols = $field['cols'] ?? NULL;
6a488035
TO
813 if (!isset($cols)) {
814 $cols = 80;
815 }
816
be2fb01f 817 $attributes = [];
6a488035
TO
818 $attributes['rows'] = $rows;
819 $attributes['cols'] = $cols;
820 return $attributes;
821 }
822 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_INT || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_FLOAT || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_MONEY) {
823 $attributes['size'] = 6;
824 $attributes['maxlength'] = 14;
825 return $attributes;
826 }
827 }
828 return NULL;
829 }
830
831 /**
d09edf64 832 * Get the size and maxLength attributes for this text field.
6a488035
TO
833 * (or for all text fields) in the DAO object.
834 *
6a0b768e
TO
835 * @param string $class
836 * Name of DAO class.
837 * @param string $fieldName
838 * Field that i'm interested in or null if.
6a488035
TO
839 * you want the attributes for all DAO text fields
840 *
a6c01b45
CW
841 * @return array
842 * assoc array of name => attribute pairs
6a488035 843 */
00be9182 844 public static function getAttribute($class, $fieldName = NULL) {
353ffa53 845 $object = new $class();
44ce4aa3 846 $fields = $object->fields();
6a488035 847 if ($fieldName != NULL) {
9c1bc317 848 $field = $fields[$fieldName] ?? NULL;
6a488035
TO
849 return self::makeAttribute($field);
850 }
851 else {
be2fb01f 852 $attributes = [];
6a488035
TO
853 foreach ($fields as $name => $field) {
854 $attribute = self::makeAttribute($field);
855 if ($attribute) {
856 $attributes[$name] = $attribute;
857 }
858 }
859
860 if (!empty($attributes)) {
861 return $attributes;
862 }
863 }
864 return NULL;
865 }
866
2ee9afab
CW
867 /**
868 * Create or update a record from supplied params.
869 *
870 * If 'id' is supplied, an existing record will be updated
871 * Otherwise a new record will be created.
872 *
873 * @param array $record
874 * @return CRM_Core_DAO
875 * @throws CRM_Core_Exception
876 */
877 public static function writeRecord(array $record) {
878 $hook = empty($record['id']) ? 'create' : 'edit';
879 $className = CRM_Core_DAO_AllCoreTables::getCanonicalClassName(static::class);
880 if ($className === 'CRM_Core_DAO') {
881 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
882 }
883 $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($className);
884
885 \CRM_Utils_Hook::pre($hook, $entityName, $record['id'] ?? NULL, $record);
886 $instance = new $className();
887 $instance->copyValues($record);
888 $instance->save();
889 \CRM_Utils_Hook::post($hook, $entityName, $instance->id, $instance);
890
891 return $instance;
892 }
893
894 /**
895 * Delete a record from supplied params.
896 *
897 * @param array $record
898 * 'id' is required.
899 * @return CRM_Core_DAO
900 * @throws CRM_Core_Exception
901 */
902 public static function deleteRecord(array $record) {
903 $className = CRM_Core_DAO_AllCoreTables::getCanonicalClassName(static::class);
904 if ($className === 'CRM_Core_DAO') {
905 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
906 }
907 $entityName = CRM_Core_DAO_AllCoreTables::getBriefName($className);
908 if (empty($record['id'])) {
909 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
910 }
911
912 CRM_Utils_Hook::pre('delete', $entityName, $record['id'], $record);
913 $instance = new $className();
914 $instance->id = $record['id'];
915 if (!$instance->delete()) {
916 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
917 }
918 CRM_Utils_Hook::post('delete', $entityName, $record['id'], $instance);
919
920 return $instance;
921 }
922
6a488035 923 /**
fe482240 924 * Check if there is a record with the same name in the db.
6a488035 925 *
6a0b768e
TO
926 * @param string $value
927 * The value of the field we are checking.
928 * @param string $daoName
929 * The dao object name.
930 * @param string $daoID
931 * The id of the object being updated. u can change your name.
6a488035 932 * as long as there is no conflict
6a0b768e
TO
933 * @param string $fieldName
934 * The name of the field in the DAO.
6a488035 935 *
35b63106
DS
936 * @param string $domainID
937 * The id of the domain. Object exists only for the given domain.
938 *
795492f3 939 * @return bool
a6c01b45 940 * true if object exists
6a488035 941 */
35b63106 942 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
353ffa53 943 $object = new $daoName();
6a488035 944 $object->$fieldName = $value;
35b63106
DS
945 if ($domainID) {
946 $object->domain_id = $domainID;
947 }
6a488035
TO
948
949 if ($object->find(TRUE)) {
63d76404 950 return $daoID && $object->id == $daoID;
6a488035
TO
951 }
952 else {
953 return TRUE;
954 }
955 }
956
957 /**
fe482240 958 * Check if there is a given column in a specific table.
6a488035 959 *
eed7e803
CW
960 * @deprecated
961 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
962 *
6a488035
TO
963 * @param string $tableName
964 * @param string $columnName
6a0b768e
TO
965 * @param bool $i18nRewrite
966 * Whether to rewrite the query on multilingual setups.
6a488035 967 *
795492f3 968 * @return bool
a6c01b45 969 * true if exists, else false
6a488035 970 */
00be9182 971 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
fdc2e63a 972 CRM_Core_Error::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
eed7e803 973 return CRM_Core_BAO_SchemaHandler::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
6a488035
TO
974 }
975
976 /**
3fa9688a 977 * Scans all the tables using a slow query and table name.
2a6da8d7 978 *
6a488035 979 * @return array
6a488035 980 */
3fa9688a 981 public static function getTableNames() {
982 $dao = CRM_Core_DAO::executeQuery(
983 "SELECT TABLE_NAME
984 FROM information_schema.TABLES
985 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO::getDatabaseName() . "'
986 AND TABLE_NAME LIKE 'civicrm_%'
987 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
2475b550 988 AND TABLE_NAME NOT LIKE '%_temp%'
3fa9688a 989 ");
6a488035 990
6a488035 991 while ($dao->fetch()) {
3fa9688a 992 $values[] = $dao->TABLE_NAME;
6a488035 993 }
6a488035
TO
994 return $values;
995 }
996
a0ee3941
EM
997 /**
998 * @param int $maxTablesToCheck
999 *
1000 * @return bool
1001 */
00be9182 1002 public static function isDBMyISAM($maxTablesToCheck = 10) {
3fa9688a 1003 return CRM_Core_DAO::singleValueQuery(
1004 "SELECT count(*)
1005 FROM information_schema.TABLES
1006 WHERE ENGINE = 'MyISAM'
1007 AND TABLE_SCHEMA = '" . CRM_Core_DAO::getDatabaseName() . "'
1008 AND TABLE_NAME LIKE 'civicrm_%'
1009 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
2475b550 1010 AND TABLE_NAME NOT LIKE '%_temp%'
0cb1aeab 1011 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
3fa9688a 1012 ");
1013 }
1014
1015 /**
1016 * Get the name of the CiviCRM database.
1017 *
1018 * @return string
1019 */
1020 public static function getDatabaseName() {
1021 $daoObj = new CRM_Core_DAO();
1022 return $daoObj->database();
6a488035
TO
1023 }
1024
1025 /**
1026 * Checks if a constraint exists for a specified table.
1027 *
1028 * @param string $tableName
1029 * @param string $constraint
1030 *
795492f3 1031 * @return bool
a6c01b45 1032 * true if constraint exists, false otherwise
7c58994a 1033 *
1034 * @throws \CRM_Core_Exception
6a488035 1035 */
00be9182 1036 public static function checkConstraintExists($tableName, $constraint) {
be2fb01f 1037 static $show = [];
6a488035
TO
1038
1039 if (!array_key_exists($tableName, $show)) {
1040 $query = "SHOW CREATE TABLE $tableName";
220d454c 1041 $dao = CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
6a488035
TO
1042
1043 if (!$dao->fetch()) {
7c58994a 1044 throw new CRM_Core_Exception('query failed');
6a488035
TO
1045 }
1046
6a488035
TO
1047 $show[$tableName] = $dao->Create_Table;
1048 }
1049
63d76404 1050 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
6a488035
TO
1051 }
1052
1053 /**
1054 * Checks if CONSTRAINT keyword exists for a specified table.
1055 *
2a6da8d7
EM
1056 * @param array $tables
1057 *
7c58994a 1058 * @throws CRM_Core_Exception
6a488035 1059 *
795492f3 1060 * @return bool
a6c01b45 1061 * true if CONSTRAINT keyword exists, false otherwise
6a488035 1062 */
be2fb01f
CW
1063 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1064 $show = [];
9b873358 1065 foreach ($tables as $tableName) {
6a488035
TO
1066 if (!array_key_exists($tableName, $show)) {
1067 $query = "SHOW CREATE TABLE $tableName";
220d454c 1068 $dao = CRM_Core_DAO::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
6a488035
TO
1069
1070 if (!$dao->fetch()) {
7c58994a 1071 throw new CRM_Core_Exception('Show create table failed.');
6a488035
TO
1072 }
1073
6a488035
TO
1074 $show[$tableName] = $dao->Create_Table;
1075 }
1076
63d76404 1077 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
9b873358 1078 if ($result == TRUE) {
6a488035
TO
1079 continue;
1080 }
c490a46a 1081 else {
6a488035
TO
1082 return FALSE;
1083 }
1084 }
1085 return TRUE;
1086 }
1087
1088 /**
1089 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1090 * for a specified column of a table.
1091 *
1092 * @param string $tableName
1093 * @param string $columnName
1094 *
795492f3 1095 * @return bool
a6c01b45 1096 * true if in format, false otherwise
7c58994a 1097 *
1098 * @throws \CRM_Core_Exception
6a488035 1099 */
00be9182 1100 public static function checkFKConstraintInFormat($tableName, $columnName) {
be2fb01f 1101 static $show = [];
6a488035
TO
1102
1103 if (!array_key_exists($tableName, $show)) {
1104 $query = "SHOW CREATE TABLE $tableName";
1105 $dao = CRM_Core_DAO::executeQuery($query);
1106
1107 if (!$dao->fetch()) {
7c58994a 1108 throw new CRM_Core_Exception('query failed');
6a488035
TO
1109 }
1110
6a488035
TO
1111 $show[$tableName] = $dao->Create_Table;
1112 }
1113 $constraint = "`FK_{$tableName}_{$columnName}`";
1114 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
63d76404 1115 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
6a488035
TO
1116 }
1117
1118 /**
fe482240 1119 * Check whether a specific column in a specific table has always the same value.
6a488035
TO
1120 *
1121 * @param string $tableName
1122 * @param string $columnName
1123 * @param string $columnValue
1124 *
795492f3 1125 * @return bool
a6c01b45 1126 * true if the value is always $columnValue, false otherwise
6a488035 1127 */
00be9182 1128 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
353ffa53
TO
1129 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1130 $dao = CRM_Core_DAO::executeQuery($query);
6a488035 1131 $result = $dao->fetch() ? FALSE : TRUE;
6a488035
TO
1132 return $result;
1133 }
1134
1135 /**
fe482240 1136 * Check whether a specific column in a specific table is always NULL.
6a488035
TO
1137 *
1138 * @param string $tableName
1139 * @param string $columnName
1140 *
795492f3 1141 * @return bool
a6c01b45 1142 * true if if the value is always NULL, false otherwise
6a488035 1143 */
00be9182 1144 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
353ffa53
TO
1145 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1146 $dao = CRM_Core_DAO::executeQuery($query);
6a488035 1147 $result = $dao->fetch() ? FALSE : TRUE;
6a488035
TO
1148 return $result;
1149 }
1150
1151 /**
fe482240 1152 * Check if there is a given table in the database.
6a488035
TO
1153 *
1154 * @param string $tableName
1155 *
795492f3 1156 * @return bool
a6c01b45 1157 * true if exists, else false
6a488035 1158 */
00be9182 1159 public static function checkTableExists($tableName) {
6a488035
TO
1160 $query = "
1161SHOW TABLES
1162LIKE %1
1163";
be2fb01f 1164 $params = [1 => [$tableName, 'String']];
6a488035
TO
1165
1166 $dao = CRM_Core_DAO::executeQuery($query, $params);
63d76404 1167 return (bool) $dao->fetch();
6a488035
TO
1168 }
1169
66f5e240
TO
1170 /**
1171 * Check if a given table has data.
1172 *
1173 * @param string $tableName
1174 * @return bool
1175 * TRUE if $tableName has at least one record.
1176 */
1177 public static function checkTableHasData($tableName) {
1178 $c = CRM_Core_DAO::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1179 return $c > 0;
1180 }
1181
a0ee3941
EM
1182 /**
1183 * @param $version
1184 *
1185 * @return bool
1186 */
00be9182 1187 public function checkVersion($version) {
6a488035
TO
1188 $query = "
1189SELECT version
1190FROM civicrm_domain
1191";
1192 $dbVersion = CRM_Core_DAO::singleValueQuery($query);
63d76404 1193 return trim($version) == trim($dbVersion);
6a488035
TO
1194 }
1195
47ff2df7
AN
1196 /**
1197 * Find a DAO object for the given ID and return it.
1198 *
6a0b768e
TO
1199 * @param int $id
1200 * Id of the DAO object being searched for.
47ff2df7 1201 *
44ce4aa3 1202 * @return CRM_Core_DAO
a6c01b45 1203 * Object of the type of the class that called this function.
44ce4aa3
CW
1204 *
1205 * @throws Exception
47ff2df7 1206 */
00be9182 1207 public static function findById($id) {
47ff2df7
AN
1208 $object = new static();
1209 $object->id = $id;
1210 if (!$object->find(TRUE)) {
1211 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1212 }
1213 return $object;
1214 }
1215
63782ba4
TO
1216 /**
1217 * Returns all results as array-encoded records.
1218 *
1219 * @return array
1220 */
2fabb51b 1221 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
be2fb01f 1222 $result = [];
63782ba4
TO
1223 while ($this->fetch()) {
1224 $result[] = $this->toArray();
1225 }
1226 return $result;
1227 }
b5bbb074 1228
41d41c91
TO
1229 /**
1230 * Return the results as PHP generator.
1231 *
1232 * @param string $type
1233 * Whether the generator yields 'dao' objects or 'array's.
1234 */
1235 public function fetchGenerator($type = 'dao') {
1236 while ($this->fetch()) {
1237 switch ($type) {
1238 case 'dao':
1239 yield $this;
1240 break;
1241
1242 case 'array':
1243 yield $this->toArray();
1244 break;
1245
1246 default:
1247 throw new \RuntimeException("Invalid record type ($type)");
1248 }
1249 }
1250 }
1251
77e74ae1
TO
1252 /**
1253 * Returns a singular value.
1254 *
1255 * @return mixed|NULL
1256 */
1257 public function fetchValue() {
1258 $result = $this->getDatabaseResult();
1259 $row = $result->fetchRow();
1260 $ret = NULL;
1261 if ($row) {
1262 $ret = $row[0];
1263 }
1264 $this->free();
1265 return $ret;
1266 }
1267
b5bbb074
TO
1268 /**
1269 * Get all the result records as mapping between columns.
1270 *
1271 * @param string $keyColumn
1272 * Ex: "name"
1273 * @param string $valueColumn
1274 * Ex: "label"
1275 * @return array
1276 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1277 */
1278 public function fetchMap($keyColumn, $valueColumn) {
be2fb01f 1279 $result = [];
b5bbb074
TO
1280 while ($this->fetch()) {
1281 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1282 }
1283 return $result;
1284 }
63782ba4 1285
6a488035
TO
1286 /**
1287 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1288 *
6a0b768e
TO
1289 * @param string $daoName
1290 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1291 * @param int $searchValue
1292 * Value of the column you want to search by.
1293 * @param string $returnColumn
1294 * Name of the column you want to GET the value of.
1295 * @param string $searchColumn
1296 * Name of the column you want to search by.
1297 * @param bool $force
1298 * Skip use of the cache.
6a488035 1299 *
f4b8bef7 1300 * @return string|int|null
72b3a70c 1301 * Value of $returnColumn in the retrieved record
7c58994a 1302 *
1303 * @throws \CRM_Core_Exception
6a488035 1304 */
00be9182 1305 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
6a488035
TO
1306 if (
1307 empty($searchValue) ||
1308 trim(strtolower($searchValue)) == 'null'
1309 ) {
cf79ac58 1310 // adding this here since developers forget to check for an id
6a488035
TO
1311 // or for the 'null' (which is a bad DAO kludge)
1312 // and hence we get the first value in the db
7c58994a 1313 throw new CRM_Core_Exception('getFieldValue failed');
6a488035
TO
1314 }
1315
10cac951
CW
1316 self::$_dbColumnValueCache = self::$_dbColumnValueCache ?? [];
1317
1318 while (strpos($daoName, '_BAO_') !== FALSE) {
1319 $daoName = get_parent_class($daoName);
6a488035
TO
1320 }
1321
10cac951
CW
1322 if ($force ||
1323 empty(self::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1324 !array_key_exists($returnColumn, self::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1325 ) {
353ffa53 1326 $object = new $daoName();
6a488035
TO
1327 $object->$searchColumn = $searchValue;
1328 $object->selectAdd();
1329 $object->selectAdd($returnColumn);
1330
1331 $result = NULL;
1332 if ($object->find(TRUE)) {
1333 $result = $object->$returnColumn;
1334 }
6a488035 1335
10cac951 1336 self::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
6a488035 1337 }
10cac951 1338 return self::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
6a488035
TO
1339 }
1340
1341 /**
1342 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1343 *
6a0b768e
TO
1344 * @param string $daoName
1345 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1346 * @param int $searchValue
1347 * Value of the column you want to search by.
1348 * @param string $setColumn
1349 * Name of the column you want to SET the value of.
1350 * @param string $setValue
1351 * SET the setColumn to this value.
1352 * @param string $searchColumn
1353 * Name of the column you want to search by.
6a488035 1354 *
795492f3 1355 * @return bool
a6c01b45 1356 * true if we found and updated the object, else false
6a488035 1357 */
00be9182 1358 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
353ffa53 1359 $object = new $daoName();
6a488035
TO
1360 $object->selectAdd();
1361 $object->selectAdd("$searchColumn, $setColumn");
1362 $object->$searchColumn = $searchValue;
1363 $result = FALSE;
1364 if ($object->find(TRUE)) {
1365 $object->$setColumn = $setValue;
1366 if ($object->save()) {
1367 $result = TRUE;
1368 }
1369 }
1370 $object->free();
1371 return $result;
1372 }
1373
1374 /**
fe482240 1375 * Get sort string.
6a488035
TO
1376 *
1377 * @param array|object $sort either array or CRM_Utils_Sort
6a0b768e
TO
1378 * @param string $default
1379 * Default sort value.
6a488035 1380 *
a6c01b45 1381 * @return string
6a488035 1382 */
00be9182 1383 public static function getSortString($sort, $default = NULL) {
6a488035
TO
1384 // check if sort is of type CRM_Utils_Sort
1385 if (is_a($sort, 'CRM_Utils_Sort')) {
1386 return $sort->orderBy();
1387 }
1388
44ce4aa3
CW
1389 $sortString = '';
1390
6a488035
TO
1391 // is it an array specified as $field => $sortDirection ?
1392 if ($sort) {
1393 foreach ($sort as $k => $v) {
1394 $sortString .= "$k $v,";
1395 }
1396 return rtrim($sortString, ',');
1397 }
1398 return $default;
1399 }
1400
1401 /**
fe482240 1402 * Fetch object based on array of properties.
6a488035 1403 *
6a0b768e
TO
1404 * @param string $daoName
1405 * Name of the dao object.
1406 * @param array $params
1407 * (reference ) an assoc array of name/value pairs.
1408 * @param array $defaults
1409 * (reference ) an assoc array to hold the flattened values.
1410 * @param array $returnProperities
1411 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
6a488035 1412 *
a6c01b45
CW
1413 * @return object
1414 * an object of type referenced by daoName
6a488035 1415 */
00be9182 1416 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
353ffa53 1417 $object = new $daoName();
6a488035
TO
1418 $object->copyValues($params);
1419
1420 // return only specific fields if returnproperties are sent
1421 if (!empty($returnProperities)) {
1422 $object->selectAdd();
1423 $object->selectAdd(implode(',', $returnProperities));
1424 }
1425
1426 if ($object->find(TRUE)) {
1427 self::storeValues($object, $defaults);
1428 return $object;
1429 }
1430 return NULL;
1431 }
1432
1433 /**
fe482240 1434 * Delete the object records that are associated with this contact.
6a488035 1435 *
6a0b768e
TO
1436 * @param string $daoName
1437 * Name of the dao object.
1438 * @param int $contactId
1439 * Id of the contact to delete.
6a488035 1440 */
00be9182 1441 public static function deleteEntityContact($daoName, $contactId) {
353ffa53 1442 $object = new $daoName();
6a488035
TO
1443
1444 $object->entity_table = 'civicrm_contact';
1445 $object->entity_id = $contactId;
1446 $object->delete();
1447 }
1448
67cae873 1449 /**
bf48aa29 1450 * Execute an unbuffered query.
1451 *
1452 * This is a wrapper around new functionality exposed with CRM-17748.
67cae873
SB
1453 *
1454 * @param string $query query to be executed
3a8ce9d6 1455 *
bf48aa29 1456 * @param array $params
1457 * @param bool $abort
1458 * @param null $daoName
1459 * @param bool $freeDAO
1460 * @param bool $i18nRewrite
1461 * @param bool $trapException
1462 *
1463 * @return CRM_Core_DAO
1464 * Object that points to an unbuffered result set
67cae873 1465 */
518fa0ee 1466 public static function executeUnbufferedQuery(
67cae873 1467 $query,
be2fb01f 1468 $params = [],
3a8ce9d6
SB
1469 $abort = TRUE,
1470 $daoName = NULL,
1471 $freeDAO = FALSE,
1472 $i18nRewrite = TRUE,
67cae873
SB
1473 $trapException = FALSE
1474 ) {
67cae873 1475
4d1368d8 1476 return self::executeQuery(
1477 $query,
1478 $params,
1479 $abort,
1480 $daoName,
1481 $freeDAO,
1482 $i18nRewrite,
1483 $trapException,
be2fb01f 1484 ['result_buffering' => 0]
4d1368d8 1485 );
67cae873
SB
1486 }
1487
6a488035 1488 /**
fe482240 1489 * Execute a query.
6a488035 1490 *
6a0b768e
TO
1491 * @param string $query
1492 * Query to be executed.
6a488035 1493 *
2a6da8d7
EM
1494 * @param array $params
1495 * @param bool $abort
1496 * @param null $daoName
1497 * @param bool $freeDAO
1498 * @param bool $i18nRewrite
1499 * @param bool $trapException
4d1368d8 1500 * @param array $options
2a6da8d7 1501 *
5f1ebaec 1502 * @return CRM_Core_DAO|object
16b10e64 1503 * object that holds the results of the query
5f1ebaec
EM
1504 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1505 * out all the properties that are not part of the DAO
6a488035 1506 */
795492f3 1507 public static function &executeQuery(
6a488035 1508 $query,
be2fb01f 1509 $params = [],
353ffa53
TO
1510 $abort = TRUE,
1511 $daoName = NULL,
1512 $freeDAO = FALSE,
1513 $i18nRewrite = TRUE,
4d1368d8 1514 $trapException = FALSE,
be2fb01f 1515 $options = []
6a488035
TO
1516 ) {
1517 $queryStr = self::composeQuery($query, $params, $abort);
6a488035
TO
1518
1519 if (!$daoName) {
1520 $dao = new CRM_Core_DAO();
1521 }
1522 else {
353ffa53 1523 $dao = new $daoName();
6a488035
TO
1524 }
1525
1526 if ($trapException) {
6a4257d4 1527 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
1528 }
1529
4d1368d8 1530 if ($dao->isValidOption($options)) {
1531 $dao->setOptions($options);
1532 }
1533
6a488035
TO
1534 $result = $dao->query($queryStr, $i18nRewrite);
1535
4d1368d8 1536 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1537 if (CRM_Utils_Array::value('result_buffering', $options) === 0) {
1538 $dao->N = TRUE;
1539 }
1540
6a488035
TO
1541 if (is_a($result, 'DB_Error')) {
1542 return $result;
1543 }
1544
6a488035
TO
1545 return $dao;
1546 }
1547
4d1368d8 1548 /**
1549 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1550 *
1551 * @param array $options
1552 *
1553 * @return bool
1554 * Provided options are valid
1555 */
1556 public function isValidOption($options) {
1557 $isValid = FALSE;
be2fb01f 1558 $validOptions = [
4d1368d8 1559 'result_buffering',
1560 'persistent',
1561 'ssl',
1562 'portability',
be2fb01f 1563 ];
4d1368d8 1564
1565 if (empty($options)) {
1566 return $isValid;
1567 }
1568
1569 foreach (array_keys($options) as $option) {
1570 if (!in_array($option, $validOptions)) {
1571 return FALSE;
1572 }
1573 $isValid = TRUE;
1574 }
1575
1576 return $isValid;
1577 }
1578
6a488035 1579 /**
fe482240 1580 * Execute a query and get the single result.
6a488035 1581 *
6a0b768e
TO
1582 * @param string $query
1583 * Query to be executed.
e869b07d
CW
1584 * @param array $params
1585 * @param bool $abort
1586 * @param bool $i18nRewrite
72b3a70c
CW
1587 * @return string|null
1588 * the result of the query if any
6a488035 1589 *
6a488035 1590 */
795492f3 1591 public static function &singleValueQuery(
f9f40af3 1592 $query,
be2fb01f 1593 $params = [],
353ffa53 1594 $abort = TRUE,
6a488035
TO
1595 $i18nRewrite = TRUE
1596 ) {
1597 $queryStr = self::composeQuery($query, $params, $abort);
1598
1599 static $_dao = NULL;
1600
1601 if (!$_dao) {
1602 $_dao = new CRM_Core_DAO();
1603 }
1604
1605 $_dao->query($queryStr, $i18nRewrite);
1606
1607 $result = $_dao->getDatabaseResult();
1608 $ret = NULL;
1609 if ($result) {
1610 $row = $result->fetchRow();
1611 if ($row) {
1612 $ret = $row[0];
1613 }
1614 }
1615 $_dao->free();
1616 return $ret;
1617 }
1618
a0ee3941 1619 /**
edc8adfc 1620 * Compose the query by merging the parameters into it.
1621 *
1622 * @param string $query
c490a46a 1623 * @param array $params
a0ee3941
EM
1624 * @param bool $abort
1625 *
1626 * @return string
22b4a080 1627 * @throws CRM_Core_Exception
a0ee3941 1628 */
a954b445 1629 public static function composeQuery($query, $params = [], $abort = TRUE) {
be2fb01f 1630 $tr = [];
6a488035
TO
1631 foreach ($params as $key => $item) {
1632 if (is_numeric($key)) {
1633 if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) {
1634 $item[0] = self::escapeString($item[0]);
1635 if ($item[1] == 'String' ||
1636 $item[1] == 'Memo' ||
1637 $item[1] == 'Link'
1638 ) {
887a4028
A
1639 // Support class constants stipulating wildcard characters and/or
1640 // non-quoting of strings. Also support legacy code which may be
1641 // passing in TRUE or 1 for $item[2], which used to indicate the
1642 // use of wildcard characters.
1643 if (!empty($item[2])) {
1644 if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) {
1645 $item[0] = "'%{$item[0]}%'";
1646 }
1647 elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) {
1648 $item[0] = "'{$item[0]}'";
1649 }
6a488035
TO
1650 }
1651 else {
1652 $item[0] = "'{$item[0]}'";
1653 }
1654 }
1655
1656 if (($item[1] == 'Date' || $item[1] == 'Timestamp') &&
1657 strlen($item[0]) == 0
1658 ) {
1659 $item[0] = 'null';
1660 }
1661
1662 $tr['%' . $key] = $item[0];
1663 }
1664 elseif ($abort) {
d8bf477d 1665 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
6a488035
TO
1666 }
1667 }
1668 }
1669
e2508c90 1670 return strtr($query, $tr);
6a488035
TO
1671 }
1672
a0ee3941
EM
1673 /**
1674 * @param null $ids
1675 */
00be9182 1676 public static function freeResult($ids = NULL) {
6a488035
TO
1677 global $_DB_DATAOBJECT;
1678
6a488035
TO
1679 if (!$ids) {
1680 if (!$_DB_DATAOBJECT ||
1681 !isset($_DB_DATAOBJECT['RESULTS'])
1682 ) {
1683 return;
1684 }
1685 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1686 }
1687
1688 foreach ($ids as $id) {
1689 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
8f56d1f5 1690 $_DB_DATAOBJECT['RESULTS'][$id]->free();
6a488035
TO
1691 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1692 }
1693
1694 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1695 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1696 }
1697 }
1698 }
1699
1700 /**
44ce4aa3 1701 * Make a shallow copy of an object and all the fields in the object.
6a488035 1702 *
6a0b768e
TO
1703 * @param string $daoName
1704 * Name of the dao.
1705 * @param array $criteria
1706 * Array of all the fields & values.
44ce4aa3 1707 * on which basis to copy
6a0b768e
TO
1708 * @param array $newData
1709 * Array of all the fields & values.
44ce4aa3 1710 * to be copied besides the other fields
6a0b768e
TO
1711 * @param string $fieldsFix
1712 * Array of fields that you want to prefix/suffix/replace.
1713 * @param string $blockCopyOfDependencies
1714 * Fields that you want to block from.
44ce4aa3 1715 * getting copied
8c605c27
MD
1716 * @param bool $blockCopyofCustomValues
1717 * Case when you don't want to copy the custom values set in a
1718 * template as it will override/ignore the submitted custom values
6a488035 1719 *
3fec1adc 1720 * @return CRM_Core_DAO|bool
1721 * the newly created copy of the object. False if none created.
6a488035 1722 */
8c605c27 1723 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
353ffa53 1724 $object = new $daoName();
3fec1adc 1725 $newObject = FALSE;
6a488035
TO
1726 if (!$newData) {
1727 $object->id = $criteria['id'];
1728 }
1729 else {
1730 foreach ($criteria as $key => $value) {
1731 $object->$key = $value;
1732 }
1733 }
1734
1735 $object->find();
1736 while ($object->fetch()) {
1737
1738 // all the objects except with $blockCopyOfDependencies set
1739 // be copied - addresses #CRM-1962
1740
1741 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1742 break;
1743 }
1744
353ffa53 1745 $newObject = new $daoName();
6a488035 1746
44ce4aa3 1747 $fields = $object->fields();
6a488035 1748 if (!is_array($fieldsFix)) {
be2fb01f
CW
1749 $fieldsToPrefix = [];
1750 $fieldsToSuffix = [];
1751 $fieldsToReplace = [];
6a488035 1752 }
a7488080 1753 if (!empty($fieldsFix['prefix'])) {
6a488035
TO
1754 $fieldsToPrefix = $fieldsFix['prefix'];
1755 }
a7488080 1756 if (!empty($fieldsFix['suffix'])) {
6a488035
TO
1757 $fieldsToSuffix = $fieldsFix['suffix'];
1758 }
a7488080 1759 if (!empty($fieldsFix['replace'])) {
6a488035
TO
1760 $fieldsToReplace = $fieldsFix['replace'];
1761 }
1762
1763 foreach ($fields as $name => $value) {
1764 if ($name == 'id' || $value['name'] == 'id') {
1765 // copy everything but the id!
1766 continue;
1767 }
1768
1769 $dbName = $value['name'];
a1305c92 1770 $type = CRM_Utils_Type::typeToString($value['type']);
6a488035
TO
1771 $newObject->$dbName = $object->$dbName;
1772 if (isset($fieldsToPrefix[$dbName])) {
1773 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1774 }
1775 if (isset($fieldsToSuffix[$dbName])) {
1776 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1777 }
1778 if (isset($fieldsToReplace[$dbName])) {
1779 $newObject->$dbName = $fieldsToReplace[$dbName];
1780 }
1781
6c71f6c7 1782 if ($type == 'Timestamp' || $type == 'Date') {
6a488035
TO
1783 $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName);
1784 }
1785
1786 if ($newData) {
2e45b2f8 1787 $newObject->copyValues($newData);
6a488035
TO
1788 }
1789 }
1790 $newObject->save();
8c605c27
MD
1791 if (!$blockCopyofCustomValues) {
1792 $newObject->copyCustomFields($object->id, $newObject->id);
1793 }
3d182a04 1794 CRM_Utils_Hook::post('create', CRM_Core_DAO_AllCoreTables::getBriefName($daoName), $newObject->id, $newObject);
6a488035 1795 }
ae70f47e 1796
6a488035
TO
1797 return $newObject;
1798 }
1799
50182f0e 1800 /**
e60bcca6 1801 * Method that copies custom fields values from an old entity to a new one.
1802 *
1803 * Fixes bug CRM-19302,
50182f0e 1804 * where if a custom field of File type was present, left both events using the same file,
1805 * breaking download URL's for the old event.
1806 *
1807 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
e60bcca6 1808 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
50182f0e 1809 *
e60bcca6 1810 * @param int $entityID
1811 * @param int $newEntityID
50182f0e 1812 */
e60bcca6 1813 public function copyCustomFields($entityID, $newEntityID) {
1814 $entity = CRM_Core_DAO_AllCoreTables::getBriefName(get_class($this));
1815 $tableName = CRM_Core_DAO_AllCoreTables::getTableForClass(get_class($this));
50182f0e 1816 // Obtain custom values for old event
1817 $customParams = $htmlType = [];
e60bcca6 1818 $customValues = CRM_Core_BAO_CustomValueTable::getEntityValues($entityID, $entity);
50182f0e 1819
1820 // If custom values present, we copy them
1821 if (!empty($customValues)) {
1822 // Get Field ID's and identify File type attributes, to handle file copying.
1823 $fieldIds = implode(', ', array_keys($customValues));
1824 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1825 $result = CRM_Core_DAO::executeQuery($sql);
1826
1827 // Build array of File type fields
1828 while ($result->fetch()) {
1829 $htmlType[] = $result->id;
1830 }
1831
1832 // Build params array of custom values
1833 foreach ($customValues as $field => $value) {
1834 if ($value !== NULL) {
1835 // Handle File type attributes
1836 if (in_array($field, $htmlType)) {
e60bcca6 1837 $fileValues = CRM_Core_BAO_File::path($value, $entityID);
50182f0e 1838 $customParams["custom_{$field}_-1"] = [
1839 'name' => CRM_Utils_File::duplicate($fileValues[0]),
1840 'type' => $fileValues[1],
1841 ];
1842 }
1843 // Handle other types
1844 else {
1845 $customParams["custom_{$field}_-1"] = $value;
1846 }
1847 }
1848 }
1849
1850 // Save Custom Fields for new Event
e60bcca6 1851 CRM_Core_BAO_CustomValueTable::postProcess($customParams, $tableName, $newEntityID, $entity);
50182f0e 1852 }
1853
1854 // copy activity attachments ( if any )
e60bcca6 1855 CRM_Core_BAO_File::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
50182f0e 1856 }
1857
7a9ab499
EM
1858 /**
1859 * Cascade update through related entities.
1860 *
1861 * @param string $daoName
1862 * @param $fromId
1863 * @param $toId
1864 * @param array $newData
1865 *
1273d77c 1866 * @return CRM_Core_DAO|null
7a9ab499 1867 */
be2fb01f 1868 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
353ffa53 1869 $object = new $daoName();
62933949 1870 $object->id = $fromId;
1871
1872 if ($object->find(TRUE)) {
353ffa53 1873 $newObject = new $daoName();
62933949 1874 $newObject->id = $toId;
1875
1876 if ($newObject->find(TRUE)) {
44ce4aa3 1877 $fields = $object->fields();
62933949 1878 foreach ($fields as $name => $value) {
1879 if ($name == 'id' || $value['name'] == 'id') {
1880 // copy everything but the id!
1881 continue;
1882 }
1883
1884 $colName = $value['name'];
1885 $newObject->$colName = $object->$colName;
1886
1887 if (substr($name, -5) == '_date' ||
1888 substr($name, -10) == '_date_time'
1889 ) {
1890 $newObject->$colName = CRM_Utils_Date::isoToMysql($newObject->$colName);
1891 }
1892 }
1893 foreach ($newData as $k => $v) {
1894 $newObject->$k = $v;
1895 }
1896 $newObject->save();
1897 return $newObject;
1898 }
1899 }
1273d77c 1900 return NULL;
62933949 1901 }
1902
6a488035
TO
1903 /**
1904 * Given the component id, compute the contact id
1905 * since its used for things like send email
b3342109
EM
1906 *
1907 * @param $componentIDs
100fef9d 1908 * @param string $tableName
d94a02b4 1909 * @param string $idField
6e3090fb 1910 *
b3342109 1911 * @return array
6a488035 1912 */
d94a02b4 1913 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
be2fb01f 1914 $contactIDs = [];
6a488035
TO
1915
1916 if (empty($componentIDs)) {
1917 return $contactIDs;
1918 }
1919
1920 $IDs = implode(',', $componentIDs);
1921 $query = "
1922SELECT contact_id
1923 FROM $tableName
d94a02b4 1924 WHERE $idField IN ( $IDs )
6a488035
TO
1925";
1926
1927 $dao = CRM_Core_DAO::executeQuery($query);
1928 while ($dao->fetch()) {
1929 $contactIDs[] = $dao->contact_id;
1930 }
1931 return $contactIDs;
1932 }
1933
1934 /**
fe482240 1935 * Fetch object based on array of properties.
6a488035 1936 *
6a0b768e
TO
1937 * @param string $daoName
1938 * Name of the dao object.
dd244018 1939 * @param string $fieldIdName
100fef9d 1940 * @param int $fieldId
dd244018 1941 * @param $details
6a0b768e
TO
1942 * @param array $returnProperities
1943 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
dd244018 1944 *
a6c01b45
CW
1945 * @return object
1946 * an object of type referenced by daoName
6a488035 1947 */
00be9182 1948 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
795492f3 1949 require_once str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php";
353ffa53 1950 $object = new $daoName();
6a488035
TO
1951 $object->$fieldIdName = $fieldId;
1952
1953 // return only specific fields if returnproperties are sent
1954 if (!empty($returnProperities)) {
1955 $object->selectAdd();
1956 $object->selectAdd('id');
1957 $object->selectAdd(implode(',', $returnProperities));
1958 }
1959
1960 $object->find();
1961 while ($object->fetch()) {
be2fb01f 1962 $defaults = [];
6a488035
TO
1963 self::storeValues($object, $defaults);
1964 $details[$object->id] = $defaults;
1965 }
1966
1967 return $details;
1968 }
1969
44ce4aa3
CW
1970 /**
1971 * Drop all CiviCRM tables.
1972 *
ff48e573 1973 * @throws \CRM_Core_Exception
44ce4aa3 1974 */
00be9182 1975 public static function dropAllTables() {
6a488035
TO
1976
1977 // first drop all the custom tables we've created
1978 CRM_Core_BAO_CustomGroup::dropAllTables();
1979
1980 // drop all multilingual views
1981 CRM_Core_I18n_Schema::dropAllViews();
1982
1983 CRM_Utils_File::sourceSQLFile(CIVICRM_DSN,
1984 dirname(__FILE__) . DIRECTORY_SEPARATOR .
1985 '..' . DIRECTORY_SEPARATOR .
1986 '..' . DIRECTORY_SEPARATOR .
1987 'sql' . DIRECTORY_SEPARATOR .
1988 'civicrm_drop.mysql'
1989 );
1990 }
1991
a0ee3941
EM
1992 /**
1993 * @param $string
1994 *
1995 * @return string
1996 */
00be9182 1997 public static function escapeString($string) {
6a488035 1998 static $_dao = NULL;
6a488035 1999 if (!$_dao) {
8f56d1f5
MM
2000 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2001 // has been installed), then we fallback DB-less str_replace escaping, as
2002 // we can't use mysqli_real_escape_string, as there is no DB connection.
2003 // Note: In typical usage, escapeString() will only check one conditional
2004 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
74032946 2005 if (!defined('CIVICRM_DSN')) {
8f56d1f5
MM
2006 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2007 // list of characters mysqli_real_escape_string escapes.
be2fb01f
CW
2008 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2009 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
8f56d1f5 2010 return str_replace($search, $replace, $string);
74032946 2011 }
6a488035
TO
2012 $_dao = new CRM_Core_DAO();
2013 }
6a488035
TO
2014 return $_dao->escape($string);
2015 }
2016
2017 /**
2018 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2019 *
5a4f6742
CW
2020 * @param array $strings
2021 * @param string $default
2022 * the value to use if $strings has no elements.
a6c01b45
CW
2023 * @return string
2024 * eg "abc","def","ghi"
6a488035 2025 */
00be9182 2026 public static function escapeStrings($strings, $default = NULL) {
6a488035
TO
2027 static $_dao = NULL;
2028 if (!$_dao) {
2029 $_dao = new CRM_Core_DAO();
2030 }
2031
2032 if (empty($strings)) {
2033 return $default;
2034 }
2035
be2fb01f 2036 $escapes = array_map([$_dao, 'escape'], $strings);
6a488035
TO
2037 return '"' . implode('","', $escapes) . '"';
2038 }
2039
a0ee3941
EM
2040 /**
2041 * @param $string
2042 *
2043 * @return string
2044 */
00be9182 2045 public static function escapeWildCardString($string) {
6a488035
TO
2046 // CRM-9155
2047 // ensure we escape the single characters % and _ which are mysql wild
2048 // card characters and could come in via sortByCharacter
2049 // note that mysql does not escape these characters
2050 if ($string && in_array($string,
be2fb01f 2051 ['%', '_', '%%', '_%']
353ffa53
TO
2052 )
2053 ) {
6a488035
TO
2054 return '\\' . $string;
2055 }
2056
2057 return self::escapeString($string);
2058 }
2059
92b83508
EM
2060 /**
2061 * Creates a test object, including any required objects it needs via recursion
b3342109
EM
2062 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2063 * ONLY USE FOR TESTING
2064 *
c490a46a 2065 * @param string $daoName
b3342109
EM
2066 * @param array $params
2067 * @param int $numObjects
2068 * @param bool $createOnly
2069 *
795492f3
TO
2070 * @return object|array|NULL
2071 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
92b83508 2072 */
795492f3 2073 public static function createTestObject(
6a488035 2074 $daoName,
be2fb01f 2075 $params = [],
6a488035
TO
2076 $numObjects = 1,
2077 $createOnly = FALSE
2078 ) {
b6262a4c
EM
2079 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2080 // so we re-set here in case
2081 $config = CRM_Core_Config::singleton();
2082 $config->backtrace = TRUE;
2083
6a488035 2084 static $counter = 0;
be2fb01f 2085 CRM_Core_DAO::$_testEntitiesToSkip = [
6a488035
TO
2086 'CRM_Core_DAO_Worldregion',
2087 'CRM_Core_DAO_StateProvince',
2088 'CRM_Core_DAO_Country',
2089 'CRM_Core_DAO_Domain',
795492f3 2090 'CRM_Financial_DAO_FinancialType',
353ffa53 2091 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
be2fb01f 2092 ];
6a488035 2093
2069d1b7
TO
2094 // Prefer to instantiate BAO's instead of DAO's (when possible)
2095 // so that assignTestValue()/assignTestFK() can be overloaded.
2096 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
a494d7a3 2097 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2098 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2099 // @todo create a new class called what the BAO SHOULD be
2100 // that extends BAO-crazy-name.... migrate.
2101 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2102 }
2069d1b7
TO
2103 if (class_exists($baoName)) {
2104 $daoName = $baoName;
2105 }
2106
6a488035
TO
2107 for ($i = 0; $i < $numObjects; ++$i) {
2108
2109 ++$counter;
e79cd558 2110 /** @var CRM_Core_DAO $object */
ab9aa379 2111 $object = new $daoName();
6a488035 2112
44ce4aa3 2113 $fields = $object->fields();
e1b64aab
TO
2114 foreach ($fields as $fieldName => $fieldDef) {
2115 $dbName = $fieldDef['name'];
9c1bc317 2116 $FKClassName = $fieldDef['FKClassName'] ?? NULL;
f290b6ef 2117
015ba54e 2118 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
6a488035
TO
2119 $object->$dbName = $params[$dbName];
2120 }
2121
2122 elseif ($dbName != 'id') {
f290b6ef 2123 if ($FKClassName != NULL) {
e79cd558 2124 $object->assignTestFK($fieldName, $fieldDef, $params);
6a488035 2125 continue;
0db6c3e1
TO
2126 }
2127 else {
f290b6ef 2128 $object->assignTestValue($fieldName, $fieldDef, $counter);
6a488035 2129 }
6a488035
TO
2130 }
2131 }
b3342109 2132
6a488035
TO
2133 $object->save();
2134
2135 if (!$createOnly) {
6a488035 2136 $objects[$i] = $object;
6a488035 2137 }
f290b6ef
TO
2138 else {
2139 unset($object);
2140 }
6a488035
TO
2141 }
2142
2143 if ($createOnly) {
795492f3 2144 return NULL;
6a488035 2145 }
f290b6ef
TO
2146 elseif ($numObjects == 1) {
2147 return $objects[0];
2148 }
2149 else {
2150 return $objects;
2151 }
6a488035
TO
2152 }
2153
92b83508 2154 /**
fe482240 2155 * Deletes the this object plus any dependent objects that are associated with it.
92b83508 2156 * ONLY USE FOR TESTING
b3342109 2157 *
c490a46a 2158 * @param string $daoName
b3342109 2159 * @param array $params
92b83508 2160 */
be2fb01f 2161 public static function deleteTestObjects($daoName, $params = []) {
b6262a4c
EM
2162 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2163 // so we re-set here in case
2164 $config = CRM_Core_Config::singleton();
2165 $config->backtrace = TRUE;
6a488035 2166
b6262a4c 2167 $object = new $daoName();
9c1bc317 2168 $object->id = $params['id'] ?? NULL;
6a488035 2169
518fa0ee
SL
2170 // array(array(0 => $daoName, 1 => $daoParams))
2171 $deletions = [];
6a488035
TO
2172 if ($object->find(TRUE)) {
2173
44ce4aa3 2174 $fields = $object->fields();
6a488035
TO
2175 foreach ($fields as $name => $value) {
2176
2177 $dbName = $value['name'];
2178
9c1bc317
CW
2179 $FKClassName = $value['FKClassName'] ?? NULL;
2180 $required = $value['required'] ?? NULL;
6a488035
TO
2181 if ($FKClassName != NULL
2182 && $object->$dbName
2183 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
806e9b71
EM
2184 && ($required || $dbName == 'contact_id')
2185 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2186 // to make this test process pass - line below makes pass for now
353ffa53
TO
2187 && $dbName != 'member_of_contact_id'
2188 ) {
518fa0ee
SL
2189 // x
2190 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
6a488035
TO
2191 }
2192 }
2193 }
2194
2195 $object->delete();
2196
2197 foreach ($deletions as $deletion) {
2198 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
353ffa53 2199 }
6a488035
TO
2200 }
2201
64d24a64 2202 /**
fe482240 2203 * Set defaults when creating new entity.
64d24a64
EM
2204 * (don't call this set defaults as already in use with different signature in some places)
2205 *
c490a46a 2206 * @param array $params
64d24a64
EM
2207 * @param $defaults
2208 */
00be9182 2209 public static function setCreateDefaults(&$params, $defaults) {
16e268ad 2210 if (!empty($params['id'])) {
64d24a64
EM
2211 return;
2212 }
2213 foreach ($defaults as $key => $value) {
2214 if (!array_key_exists($key, $params) || $params[$key] === NULL) {
2215 $params[$key] = $value;
2216 }
2217 }
2218 }
2219
a0ee3941
EM
2220 /**
2221 * @param string $prefix
2222 * @param bool $addRandomString
2223 * @param null $string
2224 *
2225 * @return string
00f8d61b
TO
2226 * @deprecated
2227 * @see CRM_Utils_SQL_TempTable
a0ee3941 2228 */
00be9182 2229 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
5b508244 2230 CRM_Core_Error::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
6a488035
TO
2231 $tableName = $prefix . "_temp";
2232
2233 if ($addRandomString) {
2234 if ($string) {
2235 $tableName .= "_" . $string;
2236 }
2237 else {
2238 $tableName .= "_" . md5(uniqid('', TRUE));
2239 }
2240 }
2241 return $tableName;
2242 }
2243
a0ee3941
EM
2244 /**
2245 * @param bool $view
2246 * @param bool $trigger
2247 *
2248 * @return bool
2249 */
00be9182 2250 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
344b05bc 2251 if (\Civi::settings()->get('logging_no_trigger_permission')) {
2252 return TRUE;
2253 }
6a488035
TO
2254 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2255 // and logging
2256 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
344b05bc 2257 CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
2258 $dao = new CRM_Core_DAO();
2259 if ($view) {
cc7762c0 2260 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2261 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
6a488035
TO
2262 return FALSE;
2263 }
2264 }
2265
2266 if ($trigger) {
2267 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2268 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
6a488035
TO
2269 if ($view) {
2270 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2271 }
2272 return FALSE;
2273 }
2274
2275 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2276 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
2277 if ($view) {
2278 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2279 }
2280 return FALSE;
2281 }
2282 }
2283
2284 if ($view) {
2285 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2286 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
2287 return FALSE;
2288 }
2289 }
6a488035
TO
2290
2291 return TRUE;
2292 }
2293
a0ee3941
EM
2294 /**
2295 * @param null $message
2296 * @param bool $printDAO
2297 */
00be9182 2298 public static function debugPrint($message = NULL, $printDAO = TRUE) {
6a488035
TO
2299 CRM_Utils_System::xMemory("{$message}: ");
2300
2301 if ($printDAO) {
2302 global $_DB_DATAOBJECT;
be2fb01f 2303 $q = [];
6a488035
TO
2304 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2305 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
2306 }
2307 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
2308 }
2309 }
2310
77b97be7
EM
2311 /**
2312 * Build a list of triggers via hook and add them to (err, reconcile them
2313 * with) the database.
2314 *
5a4f6742
CW
2315 * @param string $tableName
2316 * the specific table requiring a rebuild; or NULL to rebuild all tables.
77b97be7 2317 * @param bool $force
4ed867e0 2318 * @deprecated
77b97be7
EM
2319 *
2320 * @see CRM-9716
2321 */
00be9182 2322 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
4ed867e0 2323 Civi::service('sql_triggers')->rebuild($tableName, $force);
6a488035
TO
2324 }
2325
aca2de91
CW
2326 /**
2327 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2328 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2329 * TODO: Alternative solutions might be
2330 * * Stop using functions and find another way to strip numeric characters from phones
2331 * * Give better error messages (currently a missing fn fatals with "unknown error")
2332 */
00be9182 2333 public static function checkSqlFunctionsExist() {
aca2de91
CW
2334 if (!self::$_checkedSqlFunctionsExist) {
2335 self::$_checkedSqlFunctionsExist = TRUE;
2336 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2337 if (!$dao->fetch()) {
2338 self::triggerRebuild();
2339 }
2340 }
2341 }
2342
6a488035 2343 /**
fe482240 2344 * Wrapper function to drop triggers.
6a488035 2345 *
5a4f6742
CW
2346 * @param string $tableName
2347 * the specific table requiring a rebuild; or NULL to rebuild all tables.
4ed867e0 2348 * @deprecated
6a488035 2349 */
00be9182 2350 public static function dropTriggers($tableName = NULL) {
4ed867e0 2351 Civi::service('sql_triggers')->dropTriggers($tableName);
6a488035
TO
2352 }
2353
2354 /**
5a4f6742
CW
2355 * @param array $info
2356 * per hook_civicrm_triggerInfo.
2357 * @param string $onlyTableName
2358 * the specific table requiring a rebuild; or NULL to rebuild all tables.
4ed867e0 2359 * @deprecated
6a488035 2360 */
00be9182 2361 public static function createTriggers(&$info, $onlyTableName = NULL) {
4ed867e0 2362 Civi::service('sql_triggers')->createTriggers($info, $onlyTableName);
6a488035
TO
2363 }
2364
ffcef054
TO
2365 /**
2366 * Given a list of fields, create a list of references.
2367 *
6a0b768e
TO
2368 * @param string $className
2369 * BAO/DAO class name.
ffcef054
TO
2370 * @return array<CRM_Core_Reference_Interface>
2371 */
00be9182 2372 public static function createReferenceColumns($className) {
be2fb01f 2373 $result = [];
ffcef054
TO
2374 $fields = $className::fields();
2375 foreach ($fields as $field) {
2376 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2377 $result[] = new CRM_Core_Reference_OptionValue(
2378 $className::getTableName(),
2379 $field['name'],
2380 'civicrm_option_value',
2381 CRM_Utils_Array::value('keyColumn', $field['pseudoconstant'], 'value'),
2382 $field['pseudoconstant']['optionGroupName']
2383 );
2384 }
2385 }
2386 return $result;
2387 }
2388
6a488035 2389 /**
71e5aa5c
ARW
2390 * Find all records which refer to this entity.
2391 *
a6c01b45 2392 * @return array
16b10e64 2393 * Array of objects referencing this
71e5aa5c 2394 */
00be9182 2395 public function findReferences() {
71e5aa5c
ARW
2396 $links = self::getReferencesToTable(static::getTableName());
2397
be2fb01f 2398 $occurrences = [];
71e5aa5c 2399 foreach ($links as $refSpec) {
11626cf1 2400 /** @var $refSpec CRM_Core_Reference_Interface */
31bed28c 2401 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
de49f39c 2402 $result = $refSpec->findReferences($this);
ffcef054
TO
2403 if ($result) {
2404 while ($result->fetch()) {
2405 $obj = new $daoName();
2406 $obj->id = $result->id;
2407 $occurrences[] = $obj;
2408 }
71e5aa5c
ARW
2409 }
2410 }
2411
2412 return $occurrences;
2413 }
2414
a0ee3941 2415 /**
a6c01b45
CW
2416 * @return array
2417 * each item has keys:
16b10e64
CW
2418 * - name: string
2419 * - type: string
2420 * - count: int
2421 * - table: string|null SQL table name
2422 * - key: string|null SQL column name
a0ee3941 2423 */
00be9182 2424 public function getReferenceCounts() {
1256c139
TO
2425 $links = self::getReferencesToTable(static::getTableName());
2426
be2fb01f 2427 $counts = [];
1256c139
TO
2428 foreach ($links as $refSpec) {
2429 /** @var $refSpec CRM_Core_Reference_Interface */
2430 $count = $refSpec->getReferenceCount($this);
2431 if ($count['count'] != 0) {
2432 $counts[] = $count;
2433 }
2434 }
2435
91dee34b
TO
2436 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
2437 /** @var $component CRM_Core_Component_Info */
2438 $counts = array_merge($counts, $component->getReferenceCounts($this));
2439 }
2440 CRM_Utils_Hook::referenceCounts($this, $counts);
2441
1256c139
TO
2442 return $counts;
2443 }
2444
71e5aa5c
ARW
2445 /**
2446 * List all tables which have hard foreign keys to this table.
6a488035 2447 *
71e5aa5c
ARW
2448 * For now, this returns a description of every entity_id/entity_table
2449 * reference.
2450 * TODO: filter dynamic entity references on the $tableName, based on
2451 * schema metadata in dynamicForeignKey which enumerates a restricted
2452 * set of possible entity_table's.
6a488035 2453 *
6a0b768e
TO
2454 * @param string $tableName
2455 * Table referred to.
6a488035 2456 *
a6c01b45
CW
2457 * @return array
2458 * structure of table and column, listing every table with a
16b10e64 2459 * foreign key reference to $tableName, and the column where the key appears.
6a488035 2460 */
00be9182 2461 public static function getReferencesToTable($tableName) {
be2fb01f 2462 $refsFound = [];
31bed28c 2463 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
71e5aa5c 2464 $links = $daoClassName::getReferenceColumns();
71e5aa5c
ARW
2465
2466 foreach ($links as $refSpec) {
11626cf1
TO
2467 /** @var $refSpec CRM_Core_Reference_Interface */
2468 if ($refSpec->matchesTargetTable($tableName)) {
71e5aa5c
ARW
2469 $refsFound[] = $refSpec;
2470 }
6a488035
TO
2471 }
2472 }
71e5aa5c 2473 return $refsFound;
6a488035 2474 }
032c9d10 2475
e3e87c73 2476 /**
2477 * Get all references to contact table.
2478 *
2479 * This includes core tables, custom group tables, tables added by the merge
2480 * hook and the entity_tag table.
2481 *
2482 * Refer to CRM-17454 for information on the danger of querying the information
2483 * schema to derive this.
eca28463 2484 *
2485 * @throws \CiviCRM_API3_Exception
e3e87c73 2486 */
2487 public static function getReferencesToContactTable() {
2488 if (isset(\Civi::$statics[__CLASS__]) && isset(\Civi::$statics[__CLASS__]['contact_references'])) {
2489 return \Civi::$statics[__CLASS__]['contact_references'];
2490 }
2491 $contactReferences = [];
2492 $coreReferences = CRM_Core_DAO::getReferencesToTable('civicrm_contact');
2493 foreach ($coreReferences as $coreReference) {
2494 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2495 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2496 }
2497 }
2498 self::appendCustomTablesExtendingContacts($contactReferences);
4c7e5001 2499 self::appendCustomContactReferenceFields($contactReferences);
e3e87c73 2500 \Civi::$statics[__CLASS__]['contact_references'] = $contactReferences;
2501 return \Civi::$statics[__CLASS__]['contact_references'];
2502 }
2503
eca28463 2504 /**
2505 * Get all dynamic references to the given table.
2506 *
2507 * @param string $tableName
2508 *
2509 * @return array
2510 */
2511 public static function getDynamicReferencesToTable($tableName) {
2512 if (!isset(\Civi::$statics[__CLASS__]['contact_references_dynamic'][$tableName])) {
2513 \Civi::$statics[__CLASS__]['contact_references_dynamic'][$tableName] = [];
2514 $coreReferences = CRM_Core_DAO::getReferencesToTable($tableName);
2515 foreach ($coreReferences as $coreReference) {
2516 if ($coreReference instanceof \CRM_Core_Reference_Dynamic) {
9811efd4 2517 \Civi::$statics[__CLASS__]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
eca28463 2518 }
2519 }
2520 }
2521 return \Civi::$statics[__CLASS__]['contact_references_dynamic'][$tableName];
2522 }
2523
e3e87c73 2524 /**
2525 * Add custom tables that extend contacts to the list of contact references.
2526 *
2527 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2528 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2529 * - the down side is it is not cached.
2530 *
2531 * Further changes should be include tests in the CRM_Core_MergerTest class
2532 * to ensure that disabled, subtype, multiple etc groups are still captured.
2533 *
2534 * @param array $cidRefs
2535 */
2536 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2537 $customValueTables = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity('Contact');
2538 $customValueTables->find();
2539 while ($customValueTables->fetch()) {
4c7e5001
PF
2540 $cidRefs[$customValueTables->table_name][] = 'entity_id';
2541 }
2542 }
2543
2544 /**
2545 * Add custom ContactReference fields to the list of contact references
2546 *
2547 * This includes active and inactive fields/groups
2548 *
2549 * @param array $cidRefs
2550 *
2551 * @throws \CiviCRM_API3_Exception
2552 */
2553 public static function appendCustomContactReferenceFields(&$cidRefs) {
2554 $fields = civicrm_api3('CustomField', 'get', [
2555 'return' => ['column_name', 'custom_group_id.table_name'],
2556 'data_type' => 'ContactReference',
fe3b8caf 2557 'options' => ['limit' => 0],
4c7e5001
PF
2558 ])['values'];
2559 foreach ($fields as $field) {
2560 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
e3e87c73 2561 }
2562 }
2563
032c9d10
TO
2564 /**
2565 * Lookup the value of a MySQL global configuration variable.
2566 *
6a0b768e
TO
2567 * @param string $name
2568 * E.g. "thread_stack".
032c9d10
TO
2569 * @param mixed $default
2570 * @return mixed
2571 */
2572 public static function getGlobalSetting($name, $default = NULL) {
2573 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2574 // that has been reported to fail under MySQL 5.0 for OS X
2575 $escapedName = self::escapeString($name);
2576 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2577 if ($dao->fetch()) {
2578 return $dao->Value;
ab00f69d
DL
2579 }
2580 else {
032c9d10
TO
2581 return $default;
2582 }
2583 }
dc86f881 2584
9d5c7f14 2585 /**
2586 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2587 *
2588 * This is relevant where we want to offer both the ID field and the label field
2589 * as an option, e.g. search builder.
2590 *
b55d81b4 2591 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
9d5c7f14 2592 * change small, but is appropriate for other sorts of pseudoconstants.
2593 *
2594 * @param array $fields
2595 */
a0090e6b 2596 public static function appendPseudoConstantsToFields(&$fields) {
6b051312 2597 foreach ($fields as $fieldUniqueName => $field) {
b55d81b4 2598 if (!empty($field['pseudoconstant'])) {
2599 $pseudoConstant = $field['pseudoconstant'];
2600 if (!empty($pseudoConstant['optionGroupName'])) {
2601 $fields[$pseudoConstant['optionGroupName']] = [
2602 'title' => CRM_Core_BAO_OptionGroup::getTitleByName($pseudoConstant['optionGroupName']),
2603 'name' => $pseudoConstant['optionGroupName'],
2604 'data_type' => CRM_Utils_Type::T_STRING,
6b051312 2605 'is_pseudofield_for' => $fieldUniqueName,
b55d81b4 2606 ];
2607 }
2608 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2609 elseif (
2610 !empty($field['FKClassName'])
2611 && CRM_Utils_Array::value('keyColumn', $pseudoConstant) === 'id'
2612 && CRM_Utils_Array::value('labelColumn', $pseudoConstant) === 'name'
2613 ) {
2614 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2615 // This if is just an extra caution when adding change.
2616 if (!isset($fields[$pseudoFieldName])) {
2617 $daoName = $field['FKClassName'];
2618 $fkFields = $daoName::fields();
2619 foreach ($fkFields as $fkField) {
2620 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2621 $fields[$pseudoFieldName] = [
2622 'name' => $pseudoFieldName,
2623 'is_pseudofield_for' => $field['name'],
2624 'title' => $fkField['title'],
2625 'data_type' => $fkField['type'],
2626 'where' => $field['where'],
2627 ];
2628 }
2629 }
2630 }
2631 }
9d5c7f14 2632 }
2633 }
2634 }
2635
dc86f881
CW
2636 /**
2637 * Get options for the called BAO object's field.
167bcb5f 2638 *
dc86f881 2639 * This function can be overridden by each BAO to add more logic related to context.
2158332a 2640 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
dc86f881 2641 *
2a3f958d 2642 * @param string $fieldName
6a0b768e 2643 * @param string $context
795492f3 2644 * @see CRM_Core_DAO::buildOptionsContext
6a0b768e 2645 * @param array $props
39868387
CW
2646 * Raw field values; whatever is known about this bao object.
2647 *
2648 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
9a1b1948 2649 *
795492f3 2650 * @return array|bool
dc86f881 2651 */
be2fb01f 2652 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2158332a 2653 // If a given bao does not override this function
dc86f881 2654 $baoName = get_called_class();
39868387 2655 return CRM_Core_PseudoConstant::get($baoName, $fieldName, [], $context);
dc86f881 2656 }
786ad6e1 2657
2a3f958d
CW
2658 /**
2659 * Populate option labels for this object's fields.
2660 *
2661 * @throws exception if called directly on the base class
2662 */
2663 public function getOptionLabels() {
2664 $fields = $this->fields();
2665 if ($fields === NULL) {
795492f3 2666 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2a3f958d
CW
2667 }
2668 foreach ($fields as $field) {
9c1bc317 2669 $name = $field['name'] ?? NULL;
2a3f958d 2670 if ($name && isset($this->$name)) {
a8c23526 2671 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
2a3f958d
CW
2672 if ($label !== FALSE) {
2673 // Append 'label' onto the field name
2674 $labelName = $name . '_label';
2675 $this->$labelName = $label;
2676 }
2677 }
2678 }
2679 }
2680
786ad6e1
CW
2681 /**
2682 * Provides documentation and validation for the buildOptions $context param
2683 *
6a0b768e 2684 * @param string $context
77b97be7 2685 *
d1d108ee 2686 * @throws CRM_Core_Exception
77b97be7 2687 * @return array
786ad6e1
CW
2688 */
2689 public static function buildOptionsContext($context = NULL) {
be2fb01f 2690 $contexts = [
a2407bc0
CW
2691 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2692 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2693 'search' => "search: searchable options are returned; labels are translated.",
2694 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2695 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2696 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
be2fb01f 2697 ];
786ad6e1
CW
2698 // Validation: enforce uniformity of this param
2699 if ($context !== NULL && !isset($contexts[$context])) {
d1d108ee 2700 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
786ad6e1
CW
2701 }
2702 return $contexts;
2703 }
2704
5fafc9b0 2705 /**
100fef9d 2706 * @param string $fieldName
5fafc9b0
CW
2707 * @return bool|array
2708 */
00be9182 2709 public function getFieldSpec($fieldName) {
5fafc9b0
CW
2710 $fields = $this->fields();
2711 $fieldKeys = $this->fieldKeys();
2712
2713 // Support "unique names" as well as sql names
2714 $fieldKey = $fieldName;
2715 if (empty($fields[$fieldKey])) {
9c1bc317 2716 $fieldKey = $fieldKeys[$fieldName] ?? NULL;
5fafc9b0
CW
2717 }
2718 // If neither worked then this field doesn't exist. Return false.
2719 if (empty($fields[$fieldKey])) {
2720 return FALSE;
2721 }
2722 return $fields[$fieldKey];
2723 }
2724
faf8c53b 2725 /**
bb05da0c 2726 * Get SQL where clause for SQL filter syntax input parameters.
2727 *
faf8c53b 2728 * SQL version of api function to assign filters to the DAO based on the syntax
2729 * $field => array('IN' => array(4,6,9))
2730 * OR
2731 * $field => array('LIKE' => array('%me%))
2732 * etc
2733 *
6a0b768e
TO
2734 * @param string $fieldName
2735 * Name of fields.
5a4f6742
CW
2736 * @param array $filter
2737 * filter to be applied indexed by operator.
2738 * @param string $type
2739 * type of field (not actually used - nor in api @todo ).
2740 * @param string $alias
2741 * alternative field name ('as') @todo- not actually used.
6a0b768e
TO
2742 * @param bool $returnSanitisedArray
2743 * Return a sanitised array instead of a clause.
16b10e64 2744 * this is primarily so we can add filters @ the api level to the Query object based fields
9a1b1948
EM
2745 *
2746 * @throws Exception
c490a46a 2747 *
72b3a70c
CW
2748 * @return NULL|string|array
2749 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
06f48f96 2750 * depending on whether it is supported as yet
9a1b1948 2751 */
e47bcddb 2752 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
faf8c53b 2753 foreach ($filter as $operator => $criteria) {
6e23130a 2754 if (in_array($operator, self::acceptedSQLOperators(), TRUE)) {
faf8c53b 2755 switch ($operator) {
2756 // unary operators
faf8c53b 2757 case 'IS NULL':
2758 case 'IS NOT NULL':
c490a46a 2759 if (!$returnSanitisedArray) {
78c0bfc0 2760 return (sprintf('%s %s', $fieldName, $operator));
2761 }
c490a46a 2762 else {
a75c13cc 2763 return (sprintf('%s %s ', $fieldName, $operator));
06f48f96 2764 }
faf8c53b 2765 break;
2766
2767 // ternary operators
2768 case 'BETWEEN':
2769 case 'NOT BETWEEN':
d03a02d9 2770 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))|| (empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
395d8dc6 2771 throw new Exception("invalid criteria for $operator");
faf8c53b 2772 }
c490a46a 2773 if (!$returnSanitisedArray) {
78c0bfc0 2774 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
2775 }
c490a46a 2776 else {
518fa0ee
SL
2777 // not yet implemented (tests required to implement)
2778 return NULL;
06f48f96 2779 }
faf8c53b 2780 break;
2781
2782 // n-ary operators
2783 case 'IN':
2784 case 'NOT IN':
2785 if (empty($criteria)) {
395d8dc6 2786 throw new Exception("invalid criteria for $operator");
faf8c53b 2787 }
be2fb01f 2788 $escapedCriteria = array_map([
faf8c53b 2789 'CRM_Core_DAO',
795492f3 2790 'escapeString',
be2fb01f 2791 ], $criteria);
c490a46a 2792 if (!$returnSanitisedArray) {
78c0bfc0 2793 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2794 }
2795 return $escapedCriteria;
faf8c53b 2796
2797 // binary operators
6a488035 2798
faf8c53b 2799 default:
c490a46a 2800 if (!$returnSanitisedArray) {
353ffa53 2801 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
78c0bfc0 2802 }
c490a46a 2803 else {
518fa0ee
SL
2804 // not yet implemented (tests required to implement)
2805 return NULL;
06f48f96 2806 }
faf8c53b 2807 }
2808 }
2809 }
2810 }
6842bb53 2811
e4176358
CW
2812 /**
2813 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2814 * support for other syntaxes is discussed in ticket but being put off for now
2815 * @return array
2816 */
2817 public static function acceptedSQLOperators() {
be2fb01f 2818 return [
353ffa53
TO
2819 '=',
2820 '<=',
2821 '>=',
2822 '>',
2823 '<',
2824 'LIKE',
2825 "<>",
2826 "!=",
2827 "NOT LIKE",
2828 'IN',
2829 'NOT IN',
2830 'BETWEEN',
2831 'NOT BETWEEN',
2832 'IS NOT NULL',
795492f3 2833 'IS NULL',
be2fb01f 2834 ];
e4176358
CW
2835 }
2836
6842bb53
DL
2837 /**
2838 * SQL has a limit of 64 characters on various names:
2839 * table name, trigger name, column name ...
2840 *
2841 * For custom groups and fields we generated names from user entered input
2842 * which can be longer than this length, this function helps with creating
2843 * strings that meet various criteria.
2844 *
6a0b768e
TO
2845 * @param string $string
2846 * The string to be shortened.
2847 * @param int $length
2848 * The max length of the string.
9a1b1948
EM
2849 *
2850 * @param bool $makeRandom
2851 *
2852 * @return string
6842bb53
DL
2853 */
2854 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2855 // early return for strings that meet the requirements
2856 if (strlen($string) <= $length) {
2857 return $string;
2858 }
2859
2860 // easy return for calls that dont need a randomized uniq string
c490a46a 2861 if (!$makeRandom) {
6842bb53
DL
2862 return substr($string, 0, $length);
2863 }
2864
2865 // the string is longer than the length and we need a uniq string
b44e3f84 2866 // for the same tablename we need the same uniq string every time
6842bb53 2867 // hence we use md5 on the string, which is not random
a8dd306e
DL
2868 // we'll append 8 characters to the end of the tableName
2869 $md5string = substr(md5($string), 0, 8);
2870 return substr($string, 0, $length - 8) . "_{$md5string}";
6842bb53
DL
2871 }
2872
a0ee3941 2873 /**
33092c89
SB
2874 * https://issues.civicrm.org/jira/browse/CRM-17748
2875 * Sets the internal options to be used on a query
2876 *
2877 * @param array $options
2878 *
2879 */
6232119d 2880 public function setOptions($options) {
33092c89
SB
2881 if (is_array($options)) {
2882 $this->_options = $options;
2883 }
2884 }
2885
2886 /**
2887 * https://issues.civicrm.org/jira/browse/CRM-17748
2888 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2889 *
2890 * @param array $options
2891 *
2892 */
2893 protected function _setDBOptions($options) {
2894 global $_DB_DATAOBJECT;
2895
2896 if (is_array($options) && count($options)) {
2897 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5];
2898 foreach ($options as $option_name => $option_value) {
2899 $conn->setOption($option_name, $option_value);
2900 }
2901 }
2902 }
2903
6232119d 2904 /**
d343069c 2905 * @deprecated
c490a46a 2906 * @param array $params
a0ee3941 2907 */
353ffa53
TO
2908 public function setApiFilter(&$params) {
2909 }
6e1bb60c 2910
d343069c 2911 /**
20e41014 2912 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
d343069c 2913 *
b53bcc5d 2914 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
0b882a86 2915 * ```
b53bcc5d
CW
2916 * array(
2917 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2918 * )
0b882a86 2919 * ```
b53bcc5d
CW
2920 *
2921 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2922 *
2923 * @return array
d343069c 2924 */
20e41014 2925 public function addSelectWhereClause() {
be2fb01f 2926 $clauses = [];
c6835264
CW
2927 $fields = $this->fields();
2928 foreach ($fields as $fieldName => $field) {
2929 // Clause for contact-related entities like Email, Relationship, etc.
0b80f0b4 2930 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
d1d3c04a 2931 $clauses[$fieldName] = CRM_Utils_SQL::mergeSubquery('Contact');
0b80f0b4 2932 }
c6835264
CW
2933 // Clause for an entity_table/entity_id combo
2934 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
be2fb01f 2935 $relatedClauses = [];
c6835264
CW
2936 $relatedEntities = $this->buildOptions('entity_table', 'get');
2937 foreach ((array) $relatedEntities as $table => $ent) {
fb1c6b2c
SL
2938 if (!empty($ent)) {
2939 $ent = CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($table));
2940 $subquery = CRM_Utils_SQL::mergeSubquery($ent);
2941 if ($subquery) {
2942 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2943 }
2944 else {
2945 $relatedClauses[] = "(entity_table = '$table')";
2946 }
c6835264
CW
2947 }
2948 }
2949 if ($relatedClauses) {
2950 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2951 }
2952 }
d343069c 2953 }
032346cc
CW
2954 CRM_Utils_Hook::selectWhereClause($this, $clauses);
2955 return $clauses;
d343069c
CW
2956 }
2957
6c051493 2958 /**
0b80f0b4
CW
2959 * This returns the final permissioned query string for this entity
2960 *
2961 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2962 *
6c051493
CW
2963 * @param string $tableAlias
2964 * @return array
2965 */
20e41014 2966 public static function getSelectWhereClause($tableAlias = NULL) {
6c051493
CW
2967 $bao = new static();
2968 if ($tableAlias === NULL) {
2969 $tableAlias = $bao->tableName();
2970 }
be2fb01f 2971 $clauses = [];
20e41014 2972 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
6c051493
CW
2973 $clauses[$field] = NULL;
2974 if ($vals) {
8db05db8 2975 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
6c051493
CW
2976 }
2977 }
2978 return $clauses;
2979 }
2980
a00fe575 2981 /**
ee17d64d
MM
2982 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2983 * and dashes, and contains at least one [a-z] case insenstive.
a00fe575
PN
2984 *
2985 * @param $database
a00fe575
PN
2986 *
2987 * @return bool
2988 */
ee17d64d 2989 public static function requireSafeDBName($database) {
be2fb01f 2990 $matches = [];
a00fe575 2991 preg_match(
ee17d64d 2992 "/^[\w\-]*[a-z]+[\w\-]*$/i",
a00fe575
PN
2993 $database,
2994 $matches
2995 );
2996 if (empty($matches)) {
a00fe575
PN
2997 return FALSE;
2998 }
a00fe575
PN
2999 return TRUE;
3000 }
3001
2a5c9b4d
CW
3002 /**
3003 * Transform an array to a serialized string for database storage.
3004 *
e97c66ff 3005 * @param array|null $value
3006 * @param int $serializationType
3007 * @return string|null
3008 *
dd3ec98b 3009 * @throws \Exception
2a5c9b4d
CW
3010 */
3011 public static function serializeField($value, $serializationType) {
3012 if ($value === NULL) {
3013 return NULL;
3014 }
3015 switch ($serializationType) {
3016 case self::SERIALIZE_SEPARATOR_BOOKEND:
be2fb01f 3017 return $value === [] ? '' : CRM_Utils_Array::implodePadded($value);
2a5c9b4d
CW
3018
3019 case self::SERIALIZE_SEPARATOR_TRIMMED:
3020 return is_array($value) ? implode(self::VALUE_SEPARATOR, $value) : $value;
3021
2a5c9b4d
CW
3022 case self::SERIALIZE_JSON:
3023 return is_array($value) ? json_encode($value) : $value;
3024
3025 case self::SERIALIZE_PHP:
3026 return is_array($value) ? serialize($value) : $value;
dd3ec98b
CW
3027
3028 case self::SERIALIZE_COMMA:
3029 return is_array($value) ? implode(',', $value) : $value;
3030
3031 default:
3032 throw new Exception('Unknown serialization method for field.');
2a5c9b4d
CW
3033 }
3034 }
3035
3036 /**
3037 * Transform a serialized string from the database into an array.
3038 *
3039 * @param string|null $value
3040 * @param $serializationType
8cec96dc 3041 *
2a5c9b4d 3042 * @return array|null
8cec96dc 3043 * @throws CRM_Core_Exception
2a5c9b4d
CW
3044 */
3045 public static function unSerializeField($value, $serializationType) {
3046 if ($value === NULL) {
3047 return NULL;
3048 }
3049 if ($value === '') {
be2fb01f 3050 return [];
2a5c9b4d
CW
3051 }
3052 switch ($serializationType) {
3053 case self::SERIALIZE_SEPARATOR_BOOKEND:
3054 return (array) CRM_Utils_Array::explodePadded($value);
3055
3056 case self::SERIALIZE_SEPARATOR_TRIMMED:
3057 return explode(self::VALUE_SEPARATOR, trim($value));
3058
2a5c9b4d 3059 case self::SERIALIZE_JSON:
be2fb01f 3060 return strlen($value) ? json_decode($value, TRUE) : [];
2a5c9b4d
CW
3061
3062 case self::SERIALIZE_PHP:
f24846d5 3063 return strlen($value) ? CRM_Utils_String::unserialize($value) : [];
dd3ec98b
CW
3064
3065 case self::SERIALIZE_COMMA:
3066 return explode(',', trim(str_replace(', ', '', $value)));
3067
3068 default:
8cec96dc 3069 throw new CRM_Core_Exception('Unknown serialization method for field.');
2a5c9b4d
CW
3070 }
3071 }
3072
1d6f94ab
CW
3073 /**
3074 * @return array
3075 */
3076 public static function getEntityRefFilters() {
3077 return [];
3078 }
3079
304dc580 3080 /**
3081 * Get exportable fields with pseudoconstants rendered as an extra field.
3082 *
3083 * @param string $baoClass
3084 *
3085 * @return array
3086 */
3087 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3088 if (method_exists($baoClass, 'exportableFields')) {
3089 $fields = $baoClass::exportableFields();
3090 }
3091 else {
3092 $fields = $baoClass::export();
3093 }
3094 CRM_Core_DAO::appendPseudoConstantsToFields($fields);
3095 return $fields;
3096 }
3097
10cac951
CW
3098 /**
3099 * Remove item from static cache during update/delete operations
3100 */
3101 private function clearDbColumnValueCache() {
3102 $daoName = get_class($this);
3103 while (strpos($daoName, '_BAO_') !== FALSE) {
3104 $daoName = get_parent_class($daoName);
3105 }
3106 if (isset($this->id)) {
3107 unset(self::$_dbColumnValueCache[$daoName]['id'][$this->id]);
3108 }
3109 if (isset($this->name)) {
3110 unset(self::$_dbColumnValueCache[$daoName]['name'][$this->name]);
3111 }
3112 }
3113
6f738dbf 3114 /**
3115 * Does the DSN indicate the connection should use ssl.
3116 *
3117 * @param string $dsn
3118 *
3119 * @return bool
3120 */
3121 public static function isSSLDSN(string $dsn):bool {
3122 // Note that ssl= below is not an official PEAR::DB option. It doesn't know
3123 // what to do with it. We made it up because it's not required
3124 // to have client-side certificates to use ssl, so here you can specify
3125 // you want that by putting ssl=1 in the DSN string.
3126 //
3127 // Cast to bool in case of error which we interpret as no ssl.
3128 return (bool) preg_match('/[\?&](key|cert|ca|capath|cipher|ssl)=/', $dsn);
3129 }
3130
232624b1 3131}