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