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