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