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