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