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