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