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