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