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