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