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