Merge pull request #1089 from eileenmcnaughton/e-notice
[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 // CRM-11582
1008 foreach($tr as $key => $value) {
1009 $key = preg_quote($key);
1010 $value = preg_quote($value);
1011 $query = preg_replace("/$key\b/", $value, $query);
1012 }
1013 return $query;
1014 }
1015
1016 static function freeResult($ids = NULL) {
1017 global $_DB_DATAOBJECT;
1018
1019 /***
1020 $q = array( );
1021 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1022 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1023 }
1024 CRM_Core_Error::debug( 'k', $q );
1025 return;
1026 ***/
1027
1028 if (!$ids) {
1029 if (!$_DB_DATAOBJECT ||
1030 !isset($_DB_DATAOBJECT['RESULTS'])
1031 ) {
1032 return;
1033 }
1034 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1035 }
1036
1037 foreach ($ids as $id) {
1038 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1039 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result)) {
1040 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result);
1041 }
1042 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1043 }
1044
1045 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1046 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1047 }
1048 }
1049 }
1050
1051 /**
1052 * This function is to make a shallow copy of an object
1053 * and all the fields in the object
1054 *
1055 * @param string $daoName name of the dao
1056 * @param array $criteria array of all the fields & values
1057 * on which basis to copy
1058 * @param array $newData array of all the fields & values
1059 * to be copied besides the other fields
1060 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1061 * @param string $blockCopyOfDependencies fields that you want to block from
1062 * getting copied
1063 *
1064 *
1065 * @return (reference ) the newly created copy of the object
1066 * @access public
1067 */
1068 static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1069 $object = new $daoName( );
1070 if (!$newData) {
1071 $object->id = $criteria['id'];
1072 }
1073 else {
1074 foreach ($criteria as $key => $value) {
1075 $object->$key = $value;
1076 }
1077 }
1078
1079 $object->find();
1080 while ($object->fetch()) {
1081
1082 // all the objects except with $blockCopyOfDependencies set
1083 // be copied - addresses #CRM-1962
1084
1085 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1086 break;
1087 }
1088
1089 $newObject = new $daoName( );
1090
1091 $fields = &$object->fields();
1092 if (!is_array($fieldsFix)) {
1093 $fieldsToPrefix = array();
1094 $fieldsToSuffix = array();
1095 $fieldsToReplace = array();
1096 }
1097 if (CRM_Utils_Array::value('prefix', $fieldsFix)) {
1098 $fieldsToPrefix = $fieldsFix['prefix'];
1099 }
1100 if (CRM_Utils_Array::value('suffix', $fieldsFix)) {
1101 $fieldsToSuffix = $fieldsFix['suffix'];
1102 }
1103 if (CRM_Utils_Array::value('replace', $fieldsFix)) {
1104 $fieldsToReplace = $fieldsFix['replace'];
1105 }
1106
1107 foreach ($fields as $name => $value) {
1108 if ($name == 'id' || $value['name'] == 'id') {
1109 // copy everything but the id!
1110 continue;
1111 }
1112
1113 $dbName = $value['name'];
1114 $newObject->$dbName = $object->$dbName;
1115 if (isset($fieldsToPrefix[$dbName])) {
1116 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1117 }
1118 if (isset($fieldsToSuffix[$dbName])) {
1119 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1120 }
1121 if (isset($fieldsToReplace[$dbName])) {
1122 $newObject->$dbName = $fieldsToReplace[$dbName];
1123 }
1124
1125 if (substr($name, -5) == '_date' ||
1126 substr($name, -10) == '_date_time'
1127 ) {
1128 $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName);
1129 }
1130
1131 if ($newData) {
1132 foreach ($newData as $k => $v) {
1133 $newObject->$k = $v;
1134 }
1135 }
1136 }
1137 $newObject->save();
1138 }
1139 return $newObject;
1140 }
1141
1142 /**
1143 * Given the component id, compute the contact id
1144 * since its used for things like send email
1145 */
1146 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1147 $contactIDs = array();
1148
1149 if (empty($componentIDs)) {
1150 return $contactIDs;
1151 }
1152
1153 $IDs = implode(',', $componentIDs);
1154 $query = "
1155 SELECT contact_id
1156 FROM $tableName
1157 WHERE id IN ( $IDs )
1158 ";
1159
1160 $dao = CRM_Core_DAO::executeQuery($query);
1161 while ($dao->fetch()) {
1162 $contactIDs[] = $dao->contact_id;
1163 }
1164 return $contactIDs;
1165 }
1166
1167 /**
1168 * Takes a bunch of params that are needed to match certain criteria and
1169 * retrieves the relevant objects. Typically the valid params are only
1170 * contact_id. We'll tweak this function to be more full featured over a period
1171 * of time. This is the inverse function of create. It also stores all the retrieved
1172 * values in the default array
1173 *
1174 * @param string $daoName name of the dao object
1175 * @param array $params (reference ) an assoc array of name/value pairs
1176 * @param array $defaults (reference ) an assoc array to hold the flattened values
1177 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1178 *
1179 * @return object an object of type referenced by daoName
1180 * @access public
1181 * @static
1182 */
1183 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1184 require_once (str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php");
1185 $object = new $daoName( );
1186 $object->$fieldIdName = $fieldId;
1187
1188 // return only specific fields if returnproperties are sent
1189 if (!empty($returnProperities)) {
1190 $object->selectAdd();
1191 $object->selectAdd('id');
1192 $object->selectAdd(implode(',', $returnProperities));
1193 }
1194
1195 $object->find();
1196 while ($object->fetch()) {
1197 $defaults = array();
1198 self::storeValues($object, $defaults);
1199 $details[$object->id] = $defaults;
1200 }
1201
1202 return $details;
1203 }
1204
1205 static function dropAllTables() {
1206
1207 // first drop all the custom tables we've created
1208 CRM_Core_BAO_CustomGroup::dropAllTables();
1209
1210 // drop all multilingual views
1211 CRM_Core_I18n_Schema::dropAllViews();
1212
1213 CRM_Utils_File::sourceSQLFile(CIVICRM_DSN,
1214 dirname(__FILE__) . DIRECTORY_SEPARATOR .
1215 '..' . DIRECTORY_SEPARATOR .
1216 '..' . DIRECTORY_SEPARATOR .
1217 'sql' . DIRECTORY_SEPARATOR .
1218 'civicrm_drop.mysql'
1219 );
1220 }
1221
1222 static function escapeString($string) {
1223 static $_dao = NULL;
1224
1225 if (!$_dao) {
1226 $_dao = new CRM_Core_DAO();
1227 }
1228
1229 return $_dao->escape($string);
1230 }
1231
1232 /**
1233 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1234 *
1235 * @param $strings array
1236 * @param $default string the value to use if $strings has no elements
1237 * @return string eg "abc","def","ghi"
1238 */
1239 static function escapeStrings($strings, $default = NULL) {
1240 static $_dao = NULL;
1241 if (!$_dao) {
1242 $_dao = new CRM_Core_DAO();
1243 }
1244
1245 if (empty($strings)) {
1246 return $default;
1247 }
1248
1249 $escapes = array_map(array($_dao, 'escape'), $strings);
1250 return '"' . implode('","', $escapes) . '"';
1251 }
1252
1253 static function escapeWildCardString($string) {
1254 // CRM-9155
1255 // ensure we escape the single characters % and _ which are mysql wild
1256 // card characters and could come in via sortByCharacter
1257 // note that mysql does not escape these characters
1258 if ($string && in_array($string,
1259 array('%', '_', '%%', '_%')
1260 )) {
1261 return '\\' . $string;
1262 }
1263
1264 return self::escapeString($string);
1265 }
1266
1267 //Creates a test object, including any required objects it needs via recursion
1268 //createOnly: only create in database, do not store or return the objects (useful for perf testing)
1269 //ONLY USE FOR TESTING
1270 static function createTestObject(
1271 $daoName,
1272 $params = array(),
1273 $numObjects = 1,
1274 $createOnly = FALSE
1275 ) {
1276 static $counter = 0;
1277 CRM_Core_DAO::$_testEntitiesToSkip = array(
1278 'CRM_Core_DAO_Worldregion',
1279 'CRM_Core_DAO_StateProvince',
1280 'CRM_Core_DAO_Country',
1281 'CRM_Core_DAO_Domain',
1282 );
1283
1284 require_once (str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php");
1285
1286 for ($i = 0; $i < $numObjects; ++$i) {
1287
1288 ++$counter;
1289 $object = new $daoName ( );
1290
1291 $fields = &$object->fields();
1292 foreach ($fields as $name => $value) {
1293 $dbName = $value['name'];
1294 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1295 //coming up with a rule to set this is too complex let's not set it
1296 continue;
1297 }
1298 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1299 $required = CRM_Utils_Array::value('required', $value);
1300 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1301 $object->$dbName = $params[$dbName];
1302 }
1303
1304 elseif ($dbName != 'id') {
1305 if ($FKClassName != NULL) {
1306 //skip the FK if it is not required
1307 // if it's contact id we should create even if not required
1308 // we'll have a go @ fetching first though
1309 if (!$required && $dbName != 'contact_id') {
1310 $fkDAO = new $FKClassName;
1311 if($fkDAO->find(TRUE)){
1312 $object->$dbName = $fkDAO->id;
1313 }
1314 unset($fkDAO);
1315 continue;
1316 }
1317 if(in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)){
1318 $depObject = new $FKClassName();
1319 $depObject->find(TRUE);
1320 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1321 // FIXME: the fields() metadata is not specific enough
1322 $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1323 }else{
1324 //if it is required we need to generate the dependency object first
1325 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
1326 }
1327 $object->$dbName = $depObject->id;
1328 unset($depObject);
1329
1330 continue;
1331 }
1332 $constant = CRM_Utils_Array::value('pseudoconstant', $value);
1333 if (!empty($constant)) {
1334 $constantValues = CRM_Utils_PseudoConstant::getConstant($constant['name']);
1335 if (!empty($constantValues)) {
1336 $constantOptions = array_keys($constantValues);
1337 $object->$dbName = $constantOptions[0];
1338 }
1339 continue;
1340 }
1341 $enum = CRM_Utils_Array::value('enumValues', $value);
1342 if (!empty($enum)) {
1343 $options = explode(',', $enum);
1344 $object->$dbName = $options[0];
1345 continue;
1346 }
1347 switch ($value['type']) {
1348 case CRM_Utils_Type::T_INT:
1349 case CRM_Utils_Type::T_FLOAT:
1350 case CRM_Utils_Type::T_MONEY:
1351 $object->$dbName = $counter;
1352 break;
1353
1354 case CRM_Utils_Type::T_BOOL:
1355 case CRM_Utils_Type::T_BOOLEAN:
1356 if (isset($value['default'])) {
1357 $object->$dbName = $value['default'];
1358 }
1359 elseif ($value['name'] == 'is_deleted' || $value['name'] == 'is_test') {
1360 $object->$dbName = 0;
1361 }
1362 else {
1363 $object->$dbName = 1;
1364 }
1365 break;
1366
1367 case CRM_Utils_Type::T_DATE:
1368 case CRM_Utils_Type::T_TIMESTAMP:
1369 $object->$dbName = '19700101';
1370 break;
1371
1372 case CRM_Utils_Type::T_TIME:
1373 CRM_Core_Error::fatal('T_TIME shouldnt be used.');
1374 //$object->$dbName='000000';
1375 //break;
1376 case CRM_Utils_Type::T_CCNUM:
1377 $object->$dbName = '4111 1111 1111 1111';
1378 break;
1379
1380 case CRM_Utils_Type::T_URL:
1381 $object->$dbName = 'http://www.civicrm.org';
1382 break;
1383
1384 case CRM_Utils_Type::T_STRING:
1385 case CRM_Utils_Type::T_BLOB:
1386 case CRM_Utils_Type::T_MEDIUMBLOB:
1387 case CRM_Utils_Type::T_TEXT:
1388 case CRM_Utils_Type::T_LONGTEXT:
1389 case CRM_Utils_Type::T_EMAIL:
1390 default:
1391 if (isset($value['enumValues'])) {
1392 if (isset($value['default'])) {
1393 $object->$dbName = $value['default'];
1394 }
1395 else {
1396 if (is_array($value['enumValues'])) {
1397 $object->$dbName = $value['enumValues'][0];
1398 }
1399 else {
1400 $defaultValues = explode(',', $value['enumValues']);
1401 $object->$dbName = $defaultValues[0];
1402 }
1403 }
1404 }
1405 else {
1406 $object->$dbName = $dbName . '_' . $counter;
1407 $maxlength = CRM_Utils_Array::value('maxlength', $value);
1408 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1409 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1410 }
1411 }
1412 }
1413 }
1414 }
1415 $object->save();
1416
1417 if (!$createOnly) {
1418
1419 $objects[$i] = $object;
1420
1421 }
1422 else unset($object);
1423 }
1424
1425 if ($createOnly) {
1426
1427 return;
1428
1429 }
1430 elseif ($numObjects == 1) { return $objects[0];}
1431 else return $objects;
1432 }
1433
1434 //deletes the this object plus any dependent objects that are associated with it
1435 //ONLY USE FOR TESTING
1436
1437 static function deleteTestObjects($daoName, $params = array(
1438 )) {
1439
1440 $object = new $daoName ( );
1441 $object->id = CRM_Utils_Array::value('id', $params);
1442
1443 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1444 if ($object->find(TRUE)) {
1445
1446 $fields = &$object->fields();
1447 foreach ($fields as $name => $value) {
1448
1449 $dbName = $value['name'];
1450
1451 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1452 $required = CRM_Utils_Array::value('required', $value);
1453 if ($FKClassName != NULL
1454 && $object->$dbName
1455 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
1456 && ($required || $dbName == 'contact_id')) {
1457 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1458 }
1459 }
1460 }
1461
1462 $object->delete();
1463
1464 foreach ($deletions as $deletion) {
1465 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
1466 }
1467 }
1468
1469 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1470 $tableName = $prefix . "_temp";
1471
1472 if ($addRandomString) {
1473 if ($string) {
1474 $tableName .= "_" . $string;
1475 }
1476 else {
1477 $tableName .= "_" . md5(uniqid('', TRUE));
1478 }
1479 }
1480 return $tableName;
1481 }
1482
1483 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1484 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1485 // and logging
1486 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1487 CRM_Core_Error::ignoreException();
1488 $dao = new CRM_Core_DAO();
1489 if ($view) {
1490 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1491 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1492 CRM_Core_Error::setCallback();
1493 return FALSE;
1494 }
1495 }
1496
1497 if ($trigger) {
1498 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1499 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
1500 CRM_Core_Error::setCallback();
1501 if ($view) {
1502 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1503 }
1504 return FALSE;
1505 }
1506
1507 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1508 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1509 CRM_Core_Error::setCallback();
1510 if ($view) {
1511 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1512 }
1513 return FALSE;
1514 }
1515 }
1516
1517 if ($view) {
1518 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1519 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1520 CRM_Core_Error::setCallback();
1521 return FALSE;
1522 }
1523 }
1524 CRM_Core_Error::setCallback();
1525
1526 return TRUE;
1527 }
1528
1529 static function debugPrint($message = NULL, $printDAO = TRUE) {
1530 CRM_Utils_System::xMemory("{$message}: ");
1531
1532 if ($printDAO) {
1533 global $_DB_DATAOBJECT;
1534 $q = array();
1535 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1536 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1537 }
1538 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
1539 }
1540 }
1541
1542 /**
1543 * Build a list of triggers via hook and add them to (err, reconcile them
1544 * with) the database.
1545 *
1546 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1547 * @see CRM-9716
1548 */
1549 static function triggerRebuild($tableName = NULL) {
1550 $info = array();
1551
1552 $logging = new CRM_Logging_Schema;
1553 $logging->triggerInfo($info, $tableName);
1554
1555 CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
1556 CRM_Contact_BAO_Contact::triggerInfo($info, $tableName);
1557
1558 CRM_Utils_Hook::triggerInfo($info, $tableName);
1559
1560 // drop all existing triggers on all tables
1561 $logging->dropTriggers($tableName);
1562
1563 // now create the set of new triggers
1564 self::createTriggers($info);
1565 }
1566
1567 /**
1568 * Wrapper function to drop triggers
1569 *
1570 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1571 */
1572 static function dropTriggers($tableName = NULL) {
1573 $info = array();
1574
1575 $logging = new CRM_Logging_Schema;
1576 $logging->triggerInfo($info, $tableName);
1577
1578 // drop all existing triggers on all tables
1579 $logging->dropTriggers($tableName);
1580 }
1581
1582 /**
1583 * @param $info array per hook_civicrm_triggerInfo
1584 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1585 */
1586 static function createTriggers(&$info, $onlyTableName = NULL) {
1587 // Validate info array, should probably raise errors?
1588 if (is_array($info) == FALSE) {
1589 return;
1590 }
1591
1592 $triggers = array();
1593
1594 // now enumerate the tables and the events and collect the same set in a different format
1595 foreach ($info as $value) {
1596
1597 // clean the incoming data, skip malformed entries
1598 // TODO: malformed entries should raise errors or get logged.
1599 if (isset($value['table']) == FALSE ||
1600 isset($value['event']) == FALSE ||
1601 isset($value['when']) == FALSE ||
1602 isset($value['sql']) == FALSE
1603 ) {
1604 continue;
1605 }
1606
1607 if (is_string($value['table']) == TRUE) {
1608 $tables = array($value['table']);
1609 }
1610 else {
1611 $tables = $value['table'];
1612 }
1613
1614 if (is_string($value['event']) == TRUE) {
1615 $events = array(strtolower($value['event']));
1616 }
1617 else {
1618 $events = array_map('strtolower', $value['event']);
1619 }
1620
1621 $whenName = strtolower($value['when']);
1622
1623 foreach ($tables as $tableName) {
1624 if (!isset($triggers[$tableName])) {
1625 $triggers[$tableName] = array();
1626 }
1627
1628 foreach ($events as $eventName) {
1629 $template_params = array('{tableName}', '{eventName}');
1630 $template_values = array($tableName, $eventName);
1631
1632 $sql = str_replace($template_params,
1633 $template_values,
1634 $value['sql']
1635 );
1636 $variables = str_replace($template_params,
1637 $template_values,
1638 CRM_Utils_Array::value('variables', $value)
1639 );
1640
1641 if (!isset($triggers[$tableName][$eventName])) {
1642 $triggers[$tableName][$eventName] = array();
1643 }
1644
1645 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1646 // We're leaving out cursors, conditions, and handlers for now
1647 // they are kind of dangerous in this context anyway
1648 // better off putting them in stored procedures
1649 $triggers[$tableName][$eventName][$whenName] = array(
1650 'variables' => array(),
1651 'sql' => array(),
1652 );
1653 }
1654
1655 if ($variables) {
1656 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1657 }
1658
1659 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1660 }
1661 }
1662 }
1663
1664 // now spit out the sql
1665 foreach ($triggers as $tableName => $tables) {
1666 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1667 continue;
1668 }
1669 foreach ($tables as $eventName => $events) {
1670 foreach ($events as $whenName => $parts) {
1671 $varString = implode("\n", $parts['variables']);
1672 $sqlString = implode("\n", $parts['sql']);
1673 $triggerName = "{$tableName}_{$whenName}_{$eventName}";
1674 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1675
1676 CRM_Core_DAO::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1677 CRM_Core_DAO::executeQuery(
1678 $triggerSQL,
1679 array(),
1680 TRUE,
1681 NULL,
1682 FALSE,
1683 FALSE
1684 );
1685 }
1686 }
1687 }
1688 }
1689
1690 /**
1691 * Check the tables sent in, to see if there are any tables where there is a value for
1692 * a column
1693 *
1694 * This is typically used when we want to delete a row, but want to avoid the FK errors
1695 * that it might cause due to this being a required FK
1696 *
1697 * @param array an array of values (tableName, columnName)
1698 * @param array the parameter array with the value and type
1699 * @param array (reference) the tables which had an entry for this value
1700 *
1701 * @return boolean true if no value exists in all the tables
1702 * @static
1703 */
1704 public static function doesValueExistInTable(&$tables, $params, &$errors) {
1705 $errors = array();
1706 foreach ($tables as $table) {
1707 $sql = "SELECT count(*) FROM {$table['table']} WHERE {$table['column']} = %1";
1708 $count = self::singleValueQuery($sql, $params);
1709 if ($count > 0) {
1710 $errors[$table['table']] = $count;
1711 }
1712 }
1713
1714 return (empty($errors)) ? FALSE : TRUE;
1715 }
1716
1717 /**
1718 * Lookup the value of a MySQL global configuration variable.
1719 *
1720 * @param string $name e.g. "thread_stack"
1721 * @param mixed $default
1722 * @return mixed
1723 */
1724 public static function getGlobalSetting($name, $default = NULL) {
1725 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1726 // that has been reported to fail under MySQL 5.0 for OS X
1727 $escapedName = self::escapeString($name);
1728 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1729 if ($dao->fetch()) {
1730 return $dao->Value;
1731 }
1732 else {
1733 return $default;
1734 }
1735 }
1736 }
1737