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