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