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