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