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