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