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