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