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