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