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