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