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