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