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