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