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