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