Merge pull request #992 from deepak-srivastava/hr
[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
887a4028
A
58 BULK_MAIL_INSERT_COUNT = 10,
59 QUERY_FORMAT_WILDCARD = 1,
60 QUERY_FORMAT_NO_QUOTES = 2;
61
6a488035
TO
62 /*
63 * Define entities that shouldn't be created or deleted when creating/ deleting
64 * test objects - this prevents world regions, countries etc from being added / deleted
65 */
66 static $_testEntitiesToSkip = array();
67 /**
68 * the factory class for this application
69 * @var object
70 */
71 static $_factory = NULL;
72
73 /**
74 * Class constructor
75 *
76 * @return object
77 * @access public
78 */
79 function __construct() {
80 $this->initialize();
81 $this->__table = $this->getTableName();
82 }
83
84 /**
85 * empty definition for virtual function
86 */
87 static function getTableName() {
88 return NULL;
89 }
90
91 /**
92 * initialize the DAO object
93 *
94 * @param string $dsn the database connection string
95 *
96 * @return void
97 * @access private
98 * @static
99 */
100 static function init($dsn) {
101 $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
102 $options['database'] = $dsn;
103 if (defined('CIVICRM_DAO_DEBUG')) {
104 self::DebugLevel(CIVICRM_DAO_DEBUG);
105 }
106 }
107
108 /**
109 * reset the DAO object. DAO is kinda crappy in that there is an unwritten
110 * rule of one query per DAO. We attempt to get around this crappy restricrion
111 * by resetting some of DAO's internal fields. Use this with caution
112 *
113 * @return void
114 * @access public
115 *
116 */
117 function reset() {
118
119 foreach (array_keys($this->table()) as $field) {
120 unset($this->$field);
121 }
122
123 /**
124 * reset the various DB_DAO structures manually
125 */
126 $this->_query = array();
127 $this->whereAdd();
128 $this->selectAdd();
129 $this->joinAdd();
130 }
131
132 static function getLocaleTableName($tableName) {
133 global $dbLocale;
134 if ($dbLocale) {
135 $tables = CRM_Core_I18n_Schema::schemaStructureTables();
136 if (in_array($tableName, $tables)) {
137 return $tableName . $dbLocale;
138 }
139 }
140 return $tableName;
141 }
142
143 /**
144 * Execute a query by the current DAO, localizing it along the way (if needed).
145 *
146 * @param string $query the SQL query for execution
147 * @param bool $i18nRewrite whether to rewrite the query
148 *
149 * @return object the current DAO object after the query execution
150 */
151 function query($query, $i18nRewrite = TRUE) {
152 // rewrite queries that should use $dbLocale-based views for multi-language installs
153 global $dbLocale;
154 if ($i18nRewrite and $dbLocale) {
155 $query = CRM_Core_I18n_Schema::rewriteQuery($query);
156 }
157
158 return parent::query($query);
159 }
160
161 /**
162 * Static function to set the factory instance for this class.
163 *
164 * @param object $factory the factory application object
165 *
166 * @return void
167 * @access public
168 * @static
169 */
170 static function setFactory(&$factory) {
171 self::$_factory = &$factory;
172 }
173
174 /**
175 * Factory method to instantiate a new object from a table name.
176 *
177 * @return void
178 * @access public
179 */
180 function factory($table = '') {
181 if (!isset(self::$_factory)) {
182 return parent::factory($table);
183 }
184
185 return self::$_factory->create($table);
186 }
187
188 /**
189 * Initialization for all DAO objects. Since we access DB_DO programatically
190 * we need to set the links manually.
191 *
192 * @return void
193 * @access protected
194 */
195 function initialize() {
6a488035 196 $this->_connect();
6a488035
TO
197 }
198
199 /**
200 * Defines the default key as 'id'.
201 *
202 * @access protected
203 *
204 * @return array
205 */
206 function keys() {
207 static $keys;
208 if (!isset($keys)) {
209 $keys = array('id');
210 }
211 return $keys;
212 }
213
214 /**
215 * Tells DB_DataObject which keys use autoincrement.
216 * 'id' is autoincrementing by default.
217 *
218 * @access protected
219 *
220 * @return array
221 */
222 function sequenceKey() {
223 static $sequenceKeys;
224 if (!isset($sequenceKeys)) {
225 $sequenceKeys = array('id', TRUE);
226 }
227 return $sequenceKeys;
228 }
229
230 /**
231 * returns list of FK relationships
232 *
71e5aa5c 233 * @static
6a488035
TO
234 * @access public
235 *
71e5aa5c 236 * @return array of CRM_Core_EntityReference
6a488035 237 */
71e5aa5c
ARW
238 static function getReferenceColumns() {
239 return array();
6a488035
TO
240 }
241
242 /**
243 * returns all the column names of this table
244 *
245 * @access public
246 *
247 * @return array
248 */
249 static function &fields() {
250 $result = NULL;
251 return $result;
252 }
253
254 function table() {
255 $fields = &$this->fields();
256
257 $table = array();
258 if ($fields) {
259 foreach ($fields as $name => $value) {
260 $table[$value['name']] = $value['type'];
261 if (CRM_Utils_Array::value('required', $value)) {
262 $table[$value['name']] += self::DB_DAO_NOTNULL;
263 }
264 }
265 }
266
6a488035
TO
267 return $table;
268 }
269
270 function save() {
271 if (!empty($this->id)) {
272 $this->update();
273 }
274 else {
275 $this->insert();
276 }
277 $this->free();
278
279 CRM_Utils_Hook::postSave($this);
280
281 return $this;
282 }
283
284 function log($created = FALSE) {
285 static $cid = NULL;
286
287 if (!$this->getLog()) {
288 return;
289 }
290
291 if (!$cid) {
292 $session = CRM_Core_Session::singleton();
293 $cid = $session->get('userID');
294 }
295
296 // return is we dont have handle to FK
297 if (!$cid) {
298 return;
299 }
300
301 $dao = new CRM_Core_DAO_Log();
302 $dao->entity_table = $this->getTableName();
303 $dao->entity_id = $this->id;
304 $dao->modified_id = $cid;
305 $dao->modified_date = date("YmdHis");
306 $dao->insert();
307 }
308
309 /**
310 * Given an associative array of name/value pairs, extract all the values
311 * that belong to this object and initialize the object with said values
312 *
313 * @param array $params (reference ) associative array of name/value pairs
314 *
315 * @return boolean did we copy all null values into the object
316 * @access public
317 */
318 function copyValues(&$params) {
319 $fields = &$this->fields();
320 $allNull = TRUE;
321 foreach ($fields as $name => $value) {
322 $dbName = $value['name'];
323 if (array_key_exists($dbName, $params)) {
324 $pValue = $params[$dbName];
325 $exists = TRUE;
326 }
327 elseif (array_key_exists($name, $params)) {
328 $pValue = $params[$name];
329 $exists = TRUE;
330 }
331 else {
332 $exists = FALSE;
333 }
334
335 // if there is no value then make the variable NULL
336 if ($exists) {
337 if ($pValue === '') {
338 $this->$dbName = 'null';
339 }
340 else {
341 $this->$dbName = $pValue;
342 $allNull = FALSE;
343 }
344 }
345 }
346 return $allNull;
347 }
348
349 /**
350 * Store all the values from this object in an associative array
351 * this is a destructive store, calling function is responsible
352 * for keeping sanity of id's.
353 *
354 * @param object $object the object that we are extracting data from
355 * @param array $values (reference ) associative array of name/value pairs
356 *
357 * @return void
358 * @access public
359 * @static
360 */
361 static function storeValues(&$object, &$values) {
362 $fields = &$object->fields();
363 foreach ($fields as $name => $value) {
364 $dbName = $value['name'];
365 if (isset($object->$dbName) && $object->$dbName !== 'null') {
366 $values[$dbName] = $object->$dbName;
367 if ($name != $dbName) {
368 $values[$name] = $object->$dbName;
369 }
370 }
371 }
372 }
373
374 /**
375 * create an attribute for this specific field. We only do this for strings and text
376 *
377 * @param array $field the field under task
378 *
379 * @return array|null the attributes for the object
380 * @access public
381 * @static
382 */
383 static function makeAttribute($field) {
384 if ($field) {
385 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
386 $maxLength = CRM_Utils_Array::value('maxlength', $field);
387 $size = CRM_Utils_Array::value('size', $field);
388 if ($maxLength || $size) {
389 $attributes = array();
390 if ($maxLength) {
391 $attributes['maxlength'] = $maxLength;
392 }
393 if ($size) {
394 $attributes['size'] = $size;
395 }
396 return $attributes;
397 }
398 }
399 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) {
400 $rows = CRM_Utils_Array::value('rows', $field);
401 if (!isset($rows)) {
402 $rows = 2;
403 }
404 $cols = CRM_Utils_Array::value('cols', $field);
405 if (!isset($cols)) {
406 $cols = 80;
407 }
408
409 $attributes = array();
410 $attributes['rows'] = $rows;
411 $attributes['cols'] = $cols;
412 return $attributes;
413 }
414 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) {
415 $attributes['size'] = 6;
416 $attributes['maxlength'] = 14;
417 return $attributes;
418 }
419 }
420 return NULL;
421 }
422
423 /**
424 * Get the size and maxLength attributes for this text field
425 * (or for all text fields) in the DAO object.
426 *
427 * @param string $class name of DAO class
428 * @param string $fieldName field that i'm interested in or null if
429 * you want the attributes for all DAO text fields
430 *
431 * @return array assoc array of name => attribute pairs
432 * @access public
433 * @static
434 */
435 static function getAttribute($class, $fieldName = NULL) {
436 $object = new $class( );
437 $fields = &$object->fields();
438 if ($fieldName != NULL) {
439 $field = CRM_Utils_Array::value($fieldName, $fields);
440 return self::makeAttribute($field);
441 }
442 else {
443 $attributes = array();
444 foreach ($fields as $name => $field) {
445 $attribute = self::makeAttribute($field);
446 if ($attribute) {
447 $attributes[$name] = $attribute;
448 }
449 }
450
451 if (!empty($attributes)) {
452 return $attributes;
453 }
454 }
455 return NULL;
456 }
457
458 static function transaction($type) {
459 CRM_Core_Error::fatal('This function is obsolete, please use CRM_Core_Transaction');
460 }
461
462 /**
463 * Check if there is a record with the same name in the db
464 *
465 * @param string $value the value of the field we are checking
466 * @param string $daoName the dao object name
467 * @param string $daoID the id of the object being updated. u can change your name
468 * as long as there is no conflict
469 * @param string $fieldName the name of the field in the DAO
470 *
471 * @return boolean true if object exists
472 * @access public
473 * @static
474 */
475 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
476 $object = new $daoName( );
477 $object->$fieldName = $value;
478
479 $config = CRM_Core_Config::singleton();
480
481 if ($object->find(TRUE)) {
482 return ($daoID && $object->id == $daoID) ? TRUE : FALSE;
483 }
484 else {
485 return TRUE;
486 }
487 }
488
489 /**
490 * Check if there is a given column in a specific table
491 *
492 * @param string $tableName
493 * @param string $columnName
494 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
495 *
496 * @return boolean true if exists, else false
497 * @static
498 */
499 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
500 $query = "
501SHOW COLUMNS
502FROM $tableName
503LIKE %1
504";
505 $params = array(1 => array($columnName, 'String'));
506 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
507 $result = $dao->fetch() ? TRUE : FALSE;
508 $dao->free();
509 return $result;
510 }
511
512 /**
513 * Returns the storage engine used by given table-name(optional).
514 * Otherwise scans all the tables and return an array of all the
515 * distinct storage engines being used.
516 *
517 * @param string $tableName
518 *
519 * @return array
520 * @static
521 */
522 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
523 $values = array();
524 $query = "SHOW TABLE STATUS LIKE %1";
525
526 $params = array();
527
528 if (isset($tableName)) {
529 $params = array(1 => array($tableName, 'String'));
530 }
531 else {
532 $params = array(1 => array('civicrm_%', 'String'));
533 }
534
535 $dao = CRM_Core_DAO::executeQuery($query, $params);
536
537 $count = 0;
538 while ($dao->fetch()) {
539 if (isset($values[$dao->$fieldName]) ||
540 // ignore import and other temp tables
541 strpos($dao->Name, 'civicrm_import_job_') !== FALSE ||
542 strpos($dao->Name, '_temp') !== FALSE
543 ) {
544 continue;
545 }
546 $values[$dao->$fieldName] = 1;
547 $count++;
548 if ($maxTablesToCheck &&
549 $count >= $maxTablesToCheck
550 ) {
551 break;
552 }
553 }
554 $dao->free();
555 return $values;
556 }
557
558 static function isDBMyISAM($maxTablesToCheck = 10) {
559 // show error if any of the tables, use 'MyISAM' storage engine.
560 $engines = self::getStorageValues(NULL, $maxTablesToCheck);
561 if (array_key_exists('MyISAM', $engines)) {
562 return TRUE;
563 }
564 return FALSE;
565 }
566
567 /**
568 * Checks if a constraint exists for a specified table.
569 *
570 * @param string $tableName
571 * @param string $constraint
572 *
573 * @return boolean true if constraint exists, false otherwise
574 * @static
575 */
576 static function checkConstraintExists($tableName, $constraint) {
577 static $show = array();
578
579 if (!array_key_exists($tableName, $show)) {
580 $query = "SHOW CREATE TABLE $tableName";
581 $dao = CRM_Core_DAO::executeQuery($query);
582
583 if (!$dao->fetch()) {
584 CRM_Core_Error::fatal();
585 }
586
587 $dao->free();
588 $show[$tableName] = $dao->Create_Table;
589 }
590
591 return preg_match("/\b$constraint\b/i", $show[$tableName]) ? TRUE : FALSE;
592 }
593
594 /**
595 * Checks if CONSTRAINT keyword exists for a specified table.
596 *
597 * @param string $tableName
598 *
599 * @return boolean true if CONSTRAINT keyword exists, false otherwise
600 */
601 function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
602 $show = array();
603 foreach($tables as $tableName){
604 if (!array_key_exists($tableName, $show)) {
605 $query = "SHOW CREATE TABLE $tableName";
606 $dao = CRM_Core_DAO::executeQuery($query);
607
608 if (!$dao->fetch()) {
609 CRM_Core_Error::fatal();
610 }
611
612 $dao->free();
613 $show[$tableName] = $dao->Create_Table;
614 }
615
616 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ? TRUE : FALSE;
617 if($result == TRUE){
618 continue;
619 }
620 else{
621 return FALSE;
622 }
623 }
624 return TRUE;
625 }
626
627 /**
628 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
629 * for a specified column of a table.
630 *
631 * @param string $tableName
632 * @param string $columnName
633 *
634 * @return boolean true if in format, false otherwise
635 * @static
636 */
637 static function checkFKConstraintInFormat($tableName, $columnName) {
638 static $show = array();
639
640 if (!array_key_exists($tableName, $show)) {
641 $query = "SHOW CREATE TABLE $tableName";
642 $dao = CRM_Core_DAO::executeQuery($query);
643
644 if (!$dao->fetch()) {
645 CRM_Core_Error::fatal();
646 }
647
648 $dao->free();
649 $show[$tableName] = $dao->Create_Table;
650 }
651 $constraint = "`FK_{$tableName}_{$columnName}`";
652 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
653 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ? TRUE : FALSE;
654 }
655
656 /**
657 * Check whether a specific column in a specific table has always the same value
658 *
659 * @param string $tableName
660 * @param string $columnName
661 * @param string $columnValue
662 *
663 * @return boolean true if the value is always $columnValue, false otherwise
664 * @static
665 */
666 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
667 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
668 $dao = CRM_Core_DAO::executeQuery($query);
669 $result = $dao->fetch() ? FALSE : TRUE;
670 $dao->free();
671 return $result;
672 }
673
674 /**
675 * Check whether a specific column in a specific table is always NULL
676 *
677 * @param string $tableName
678 * @param string $columnName
679 *
680 * @return boolean true if if the value is always NULL, false otherwise
681 * @static
682 */
683 static function checkFieldIsAlwaysNull($tableName, $columnName) {
684 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
685 $dao = CRM_Core_DAO::executeQuery($query);
686 $result = $dao->fetch() ? FALSE : TRUE;
687 $dao->free();
688 return $result;
689 }
690
691 /**
692 * Check if there is a given table in the database
693 *
694 * @param string $tableName
695 *
696 * @return boolean true if exists, else false
697 * @static
698 */
699 static function checkTableExists($tableName) {
700 $query = "
701SHOW TABLES
702LIKE %1
703";
704 $params = array(1 => array($tableName, 'String'));
705
706 $dao = CRM_Core_DAO::executeQuery($query, $params);
707 $result = $dao->fetch() ? TRUE : FALSE;
708 $dao->free();
709 return $result;
710 }
711
712 function checkVersion($version) {
713 $query = "
714SELECT version
715FROM civicrm_domain
716";
717 $dbVersion = CRM_Core_DAO::singleValueQuery($query);
718 return trim($version) == trim($dbVersion) ? TRUE : FALSE;
719 }
720
721 /**
722 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
723 *
724 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
725 * @param int $searchValue Value of the column you want to search by
726 * @param string $returnColumn Name of the column you want to GET the value of
727 * @param string $searchColumn Name of the column you want to search by
728 * @param boolean $force Skip use of the cache
729 *
730 * @return string|null Value of $returnColumn in the retrieved record
731 * @static
732 * @access public
733 */
032c9d10 734 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
6a488035
TO
735 if (
736 empty($searchValue) ||
737 trim(strtolower($searchValue)) == 'null'
738 ) {
739 // adding this year since developers forget to check for an id
740 // or for the 'null' (which is a bad DAO kludge)
741 // and hence we get the first value in the db
742 CRM_Core_Error::fatal();
743 }
744
745 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
746 if (self::$_dbColumnValueCache === NULL) {
747 self::$_dbColumnValueCache = array();
748 }
749
750 if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
751 $object = new $daoName( );
752 $object->$searchColumn = $searchValue;
753 $object->selectAdd();
754 $object->selectAdd($returnColumn);
755
756 $result = NULL;
757 if ($object->find(TRUE)) {
758 $result = $object->$returnColumn;
759 }
760 $object->free();
761
762 self::$_dbColumnValueCache[$cacheKey] = $result;
763 }
764 return self::$_dbColumnValueCache[$cacheKey];
765 }
766
767 /**
768 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
769 *
770 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
771 * @param int $searchValue Value of the column you want to search by
772 * @param string $setColumn Name of the column you want to SET the value of
773 * @param string $setValue SET the setColumn to this value
774 * @param string $searchColumn Name of the column you want to search by
775 *
776 * @return boolean true if we found and updated the object, else false
777 * @static
778 * @access public
779 */
780 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
781 $object = new $daoName( );
782 $object->selectAdd();
783 $object->selectAdd("$searchColumn, $setColumn");
784 $object->$searchColumn = $searchValue;
785 $result = FALSE;
786 if ($object->find(TRUE)) {
787 $object->$setColumn = $setValue;
788 if ($object->save()) {
789 $result = TRUE;
790 }
791 }
792 $object->free();
793 return $result;
794 }
795
796 /**
797 * Get sort string
798 *
799 * @param array|object $sort either array or CRM_Utils_Sort
800 * @param string $default - default sort value
801 *
802 * @return string - sortString
803 * @access public
804 * @static
805 */
806 static function getSortString($sort, $default = NULL) {
807 // check if sort is of type CRM_Utils_Sort
808 if (is_a($sort, 'CRM_Utils_Sort')) {
809 return $sort->orderBy();
810 }
811
812 // is it an array specified as $field => $sortDirection ?
813 if ($sort) {
814 foreach ($sort as $k => $v) {
815 $sortString .= "$k $v,";
816 }
817 return rtrim($sortString, ',');
818 }
819 return $default;
820 }
821
822 /**
823 * Takes a bunch of params that are needed to match certain criteria and
824 * retrieves the relevant objects. Typically the valid params are only
825 * contact_id. We'll tweak this function to be more full featured over a period
826 * of time. This is the inverse function of create. It also stores all the retrieved
827 * values in the default array
828 *
829 * @param string $daoName name of the dao object
830 * @param array $params (reference ) an assoc array of name/value pairs
831 * @param array $defaults (reference ) an assoc array to hold the flattened values
832 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
833 *
834 * @return object an object of type referenced by daoName
835 * @access public
836 * @static
837 */
838 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
839 $object = new $daoName( );
840 $object->copyValues($params);
841
842 // return only specific fields if returnproperties are sent
843 if (!empty($returnProperities)) {
844 $object->selectAdd();
845 $object->selectAdd(implode(',', $returnProperities));
846 }
847
848 if ($object->find(TRUE)) {
849 self::storeValues($object, $defaults);
850 return $object;
851 }
852 return NULL;
853 }
854
855 /**
856 * Delete the object records that are associated with this contact
857 *
858 * @param string $daoName name of the dao object
859 * @param int $contactId id of the contact to delete
860 *
861 * @return void
862 * @access public
863 * @static
864 */
865 static function deleteEntityContact($daoName, $contactId) {
866 $object = new $daoName( );
867
868 $object->entity_table = 'civicrm_contact';
869 $object->entity_id = $contactId;
870 $object->delete();
871 }
872
873 /**
874 * execute a query
875 *
876 * @param string $query query to be executed
877 *
878 * @return Object CRM_Core_DAO object that holds the results of the query
879 * @static
880 * @access public
881 */
882 static function &executeQuery(
883 $query,
884 $params = array(),
885 $abort = TRUE,
886 $daoName = NULL,
887 $freeDAO = FALSE,
888 $i18nRewrite = TRUE,
889 $trapException = FALSE
890 ) {
891 $queryStr = self::composeQuery($query, $params, $abort);
892 //CRM_Core_Error::debug( 'q', $queryStr );
893
894 if (!$daoName) {
895 $dao = new CRM_Core_DAO();
896 }
897 else {
898 $dao = new $daoName( );
899 }
900
901 if ($trapException) {
902 CRM_Core_Error::ignoreException();
903 }
904
905 $result = $dao->query($queryStr, $i18nRewrite);
906
907 if ($trapException) {
908 CRM_Core_Error::setCallback();
909 }
910
911 if (is_a($result, 'DB_Error')) {
912 return $result;
913 }
914
915 if ($freeDAO ||
916 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
917 ) {
918 // we typically do this for insert/update/delete stataments OR if explicitly asked to
919 // free the dao
920 $dao->free();
921 }
922 return $dao;
923 }
924
925 /**
926 * execute a query and get the single result
927 *
928 * @param string $query query to be executed
929 *
930 * @return string the result of the query
931 * @static
932 * @access public
933 */
934 static function &singleValueQuery($query,
935 $params = array(),
936 $abort = TRUE,
937 $i18nRewrite = TRUE
938 ) {
939 $queryStr = self::composeQuery($query, $params, $abort);
940
941 static $_dao = NULL;
942
943 if (!$_dao) {
944 $_dao = new CRM_Core_DAO();
945 }
946
947 $_dao->query($queryStr, $i18nRewrite);
948
949 $result = $_dao->getDatabaseResult();
950 $ret = NULL;
951 if ($result) {
952 $row = $result->fetchRow();
953 if ($row) {
954 $ret = $row[0];
955 }
956 }
957 $_dao->free();
958 return $ret;
959 }
960
961 static function composeQuery($query, &$params, $abort = TRUE) {
962 $tr = array();
963 foreach ($params as $key => $item) {
964 if (is_numeric($key)) {
965 if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) {
966 $item[0] = self::escapeString($item[0]);
967 if ($item[1] == 'String' ||
968 $item[1] == 'Memo' ||
969 $item[1] == 'Link'
970 ) {
887a4028
A
971 // Support class constants stipulating wildcard characters and/or
972 // non-quoting of strings. Also support legacy code which may be
973 // passing in TRUE or 1 for $item[2], which used to indicate the
974 // use of wildcard characters.
975 if (!empty($item[2])) {
976 if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) {
977 $item[0] = "'%{$item[0]}%'";
978 }
979 elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) {
980 $item[0] = "'{$item[0]}'";
981 }
6a488035
TO
982 }
983 else {
984 $item[0] = "'{$item[0]}'";
985 }
986 }
987
988 if (($item[1] == 'Date' || $item[1] == 'Timestamp') &&
989 strlen($item[0]) == 0
990 ) {
991 $item[0] = 'null';
992 }
993
994 $tr['%' . $key] = $item[0];
995 }
996 elseif ($abort) {
997 CRM_Core_Error::fatal("{$item[0]} is not of type {$item[1]}");
998 }
999 }
1000 }
1001
1002 // CRM-11582
1003 foreach($tr as $key => $value) {
1004 $key = preg_quote($key);
1005 $query = preg_replace("/$key\b/", $value, $query);
1006 }
1007 return $query;
1008 }
1009
1010 static function freeResult($ids = NULL) {
1011 global $_DB_DATAOBJECT;
1012
1013 /***
1014 $q = array( );
1015 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1016 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1017 }
1018 CRM_Core_Error::debug( 'k', $q );
1019 return;
1020 ***/
1021
1022 if (!$ids) {
1023 if (!$_DB_DATAOBJECT ||
1024 !isset($_DB_DATAOBJECT['RESULTS'])
1025 ) {
1026 return;
1027 }
1028 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1029 }
1030
1031 foreach ($ids as $id) {
1032 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1033 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result)) {
1034 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result);
1035 }
1036 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1037 }
1038
1039 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1040 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1041 }
1042 }
1043 }
1044
1045 /**
1046 * This function is to make a shallow copy of an object
1047 * and all the fields in the object
1048 *
1049 * @param string $daoName name of the dao
1050 * @param array $criteria array of all the fields & values
1051 * on which basis to copy
1052 * @param array $newData array of all the fields & values
1053 * to be copied besides the other fields
1054 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1055 * @param string $blockCopyOfDependencies fields that you want to block from
1056 * getting copied
1057 *
1058 *
1059 * @return (reference ) the newly created copy of the object
1060 * @access public
1061 */
1062 static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1063 $object = new $daoName( );
1064 if (!$newData) {
1065 $object->id = $criteria['id'];
1066 }
1067 else {
1068 foreach ($criteria as $key => $value) {
1069 $object->$key = $value;
1070 }
1071 }
1072
1073 $object->find();
1074 while ($object->fetch()) {
1075
1076 // all the objects except with $blockCopyOfDependencies set
1077 // be copied - addresses #CRM-1962
1078
1079 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1080 break;
1081 }
1082
1083 $newObject = new $daoName( );
1084
1085 $fields = &$object->fields();
1086 if (!is_array($fieldsFix)) {
1087 $fieldsToPrefix = array();
1088 $fieldsToSuffix = array();
1089 $fieldsToReplace = array();
1090 }
1091 if (CRM_Utils_Array::value('prefix', $fieldsFix)) {
1092 $fieldsToPrefix = $fieldsFix['prefix'];
1093 }
1094 if (CRM_Utils_Array::value('suffix', $fieldsFix)) {
1095 $fieldsToSuffix = $fieldsFix['suffix'];
1096 }
1097 if (CRM_Utils_Array::value('replace', $fieldsFix)) {
1098 $fieldsToReplace = $fieldsFix['replace'];
1099 }
1100
1101 foreach ($fields as $name => $value) {
1102 if ($name == 'id' || $value['name'] == 'id') {
1103 // copy everything but the id!
1104 continue;
1105 }
1106
1107 $dbName = $value['name'];
1108 $newObject->$dbName = $object->$dbName;
1109 if (isset($fieldsToPrefix[$dbName])) {
1110 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1111 }
1112 if (isset($fieldsToSuffix[$dbName])) {
1113 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1114 }
1115 if (isset($fieldsToReplace[$dbName])) {
1116 $newObject->$dbName = $fieldsToReplace[$dbName];
1117 }
1118
1119 if (substr($name, -5) == '_date' ||
1120 substr($name, -10) == '_date_time'
1121 ) {
1122 $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName);
1123 }
1124
1125 if ($newData) {
1126 foreach ($newData as $k => $v) {
1127 $newObject->$k = $v;
1128 }
1129 }
1130 }
1131 $newObject->save();
1132 }
1133 return $newObject;
1134 }
1135
1136 /**
1137 * Given the component id, compute the contact id
1138 * since its used for things like send email
1139 */
a5611c8e 1140 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
6a488035
TO
1141 $contactIDs = array();
1142
1143 if (empty($componentIDs)) {
1144 return $contactIDs;
1145 }
1146
1147 $IDs = implode(',', $componentIDs);
1148 $query = "
1149SELECT contact_id
1150 FROM $tableName
1151 WHERE id IN ( $IDs )
1152";
1153
1154 $dao = CRM_Core_DAO::executeQuery($query);
1155 while ($dao->fetch()) {
1156 $contactIDs[] = $dao->contact_id;
1157 }
1158 return $contactIDs;
1159 }
1160
1161 /**
1162 * Takes a bunch of params that are needed to match certain criteria and
1163 * retrieves the relevant objects. Typically the valid params are only
1164 * contact_id. We'll tweak this function to be more full featured over a period
1165 * of time. This is the inverse function of create. It also stores all the retrieved
1166 * values in the default array
1167 *
1168 * @param string $daoName name of the dao object
1169 * @param array $params (reference ) an assoc array of name/value pairs
1170 * @param array $defaults (reference ) an assoc array to hold the flattened values
1171 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1172 *
1173 * @return object an object of type referenced by daoName
1174 * @access public
1175 * @static
1176 */
1177 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1178 require_once (str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php");
1179 $object = new $daoName( );
1180 $object->$fieldIdName = $fieldId;
1181
1182 // return only specific fields if returnproperties are sent
1183 if (!empty($returnProperities)) {
1184 $object->selectAdd();
1185 $object->selectAdd('id');
1186 $object->selectAdd(implode(',', $returnProperities));
1187 }
1188
1189 $object->find();
1190 while ($object->fetch()) {
1191 $defaults = array();
1192 self::storeValues($object, $defaults);
1193 $details[$object->id] = $defaults;
1194 }
1195
1196 return $details;
1197 }
1198
1199 static function dropAllTables() {
1200
1201 // first drop all the custom tables we've created
1202 CRM_Core_BAO_CustomGroup::dropAllTables();
1203
1204 // drop all multilingual views
1205 CRM_Core_I18n_Schema::dropAllViews();
1206
1207 CRM_Utils_File::sourceSQLFile(CIVICRM_DSN,
1208 dirname(__FILE__) . DIRECTORY_SEPARATOR .
1209 '..' . DIRECTORY_SEPARATOR .
1210 '..' . DIRECTORY_SEPARATOR .
1211 'sql' . DIRECTORY_SEPARATOR .
1212 'civicrm_drop.mysql'
1213 );
1214 }
1215
1216 static function escapeString($string) {
1217 static $_dao = NULL;
1218
1219 if (!$_dao) {
1220 $_dao = new CRM_Core_DAO();
1221 }
1222
1223 return $_dao->escape($string);
1224 }
1225
1226 /**
1227 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1228 *
1229 * @param $strings array
1230 * @param $default string the value to use if $strings has no elements
1231 * @return string eg "abc","def","ghi"
1232 */
1233 static function escapeStrings($strings, $default = NULL) {
1234 static $_dao = NULL;
1235 if (!$_dao) {
1236 $_dao = new CRM_Core_DAO();
1237 }
1238
1239 if (empty($strings)) {
1240 return $default;
1241 }
1242
1243 $escapes = array_map(array($_dao, 'escape'), $strings);
1244 return '"' . implode('","', $escapes) . '"';
1245 }
1246
1247 static function escapeWildCardString($string) {
1248 // CRM-9155
1249 // ensure we escape the single characters % and _ which are mysql wild
1250 // card characters and could come in via sortByCharacter
1251 // note that mysql does not escape these characters
1252 if ($string && in_array($string,
1253 array('%', '_', '%%', '_%')
1254 )) {
1255 return '\\' . $string;
1256 }
1257
1258 return self::escapeString($string);
1259 }
1260
1261 //Creates a test object, including any required objects it needs via recursion
1262 //createOnly: only create in database, do not store or return the objects (useful for perf testing)
1263 //ONLY USE FOR TESTING
1264 static function createTestObject(
1265 $daoName,
1266 $params = array(),
1267 $numObjects = 1,
1268 $createOnly = FALSE
1269 ) {
1270 static $counter = 0;
1271 CRM_Core_DAO::$_testEntitiesToSkip = array(
1272 'CRM_Core_DAO_Worldregion',
1273 'CRM_Core_DAO_StateProvince',
1274 'CRM_Core_DAO_Country',
1275 'CRM_Core_DAO_Domain',
1276 );
1277
6a488035
TO
1278 for ($i = 0; $i < $numObjects; ++$i) {
1279
1280 ++$counter;
ab9aa379 1281 $object = new $daoName();
6a488035
TO
1282
1283 $fields = &$object->fields();
1284 foreach ($fields as $name => $value) {
1285 $dbName = $value['name'];
1286 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1287 //coming up with a rule to set this is too complex let's not set it
1288 continue;
1289 }
1290 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1291 $required = CRM_Utils_Array::value('required', $value);
1292 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1293 $object->$dbName = $params[$dbName];
1294 }
1295
1296 elseif ($dbName != 'id') {
1297 if ($FKClassName != NULL) {
1298 //skip the FK if it is not required
1299 // if it's contact id we should create even if not required
1300 // we'll have a go @ fetching first though
1301 if (!$required && $dbName != 'contact_id') {
1302 $fkDAO = new $FKClassName;
1303 if($fkDAO->find(TRUE)){
1304 $object->$dbName = $fkDAO->id;
1305 }
1306 unset($fkDAO);
1307 continue;
1308 }
1309 if(in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)){
1310 $depObject = new $FKClassName();
032c9d10 1311 $depObject->find(TRUE);
6a488035
TO
1312 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1313 // FIXME: the fields() metadata is not specific enough
1314 $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1315 }else{
1316 //if it is required we need to generate the dependency object first
1317 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
1318 }
1319 $object->$dbName = $depObject->id;
1320 unset($depObject);
1321
1322 continue;
1323 }
ab9aa379
CW
1324 // Pick an option value if needed
1325 $options = $daoName::buildOptions($dbName);
1326 if ($options) {
1327 $object->$dbName = key($options);
6a488035
TO
1328 continue;
1329 }
ab9aa379 1330
6a488035
TO
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 /**
71e5aa5c
ARW
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
1688SELECT id
1689FROM {$refSpec->getReferenceTable()}
1690WHERE {$refColumn} = %1
1691EOS;
1692 if ($refSpec->isGeneric()) {
1693 $params[2] = array(static::getTableName(), 'String');
1694 $sql .= <<<EOS
1695 AND {$refSpec->getTypeColumn()} = %2
1696EOS;
1697 }
31bed28c 1698 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
71e5aa5c
ARW
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.
6a488035 1712 *
71e5aa5c
ARW
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.
6a488035 1718 *
71e5aa5c 1719 * @param string $tableName table referred to
6a488035 1720 *
71e5aa5c
ARW
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.
6a488035 1723 */
71e5aa5c
ARW
1724 static function getReferencesToTable($tableName) {
1725 $refsFound = array();
31bed28c 1726 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
71e5aa5c
ARW
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 }
6a488035
TO
1736 }
1737 }
71e5aa5c 1738 return $refsFound;
6a488035 1739 }
032c9d10
TO
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;
ab00f69d
DL
1755 }
1756 else {
032c9d10
TO
1757 return $default;
1758 }
1759 }
dc86f881
CW
1760
1761 /**
1762 * Get options for the called BAO object's field.
1763 * This function can be overridden by each BAO to add more logic related to context.
2158332a 1764 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
dc86f881
CW
1765 *
1766 * @param String $fieldName
1767 * @param String $context: e.g. "search" "edit" "create" "view"
1768 * @param Array $props: whatever is known about this bao object
1769 */
1770 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2158332a 1771 // If a given bao does not override this function
dc86f881
CW
1772 $baoName = get_called_class();
1773 return CRM_Core_PseudoConstant::get($baoName, $fieldName);
1774 }
6a488035
TO
1775}
1776