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