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