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