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