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