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