3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
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. |
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. |
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 +--------------------------------------------------------------------+
29 * Our base DAO class. All DAO classes should inherit from this class.
32 * @copyright CiviCRM LLC (c) 2004-2013
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
40 require_once 'CRM/Core/I18n.php';
41 class CRM_Core_DAO
extends DB_DataObject
{
44 * a null object so we can pass it as reference if / when needed
46 static $_nullObject = NULL;
47 static $_nullArray = array();
49 static $_dbColumnValueCache = NULL;
50 CONST NOT_NULL
= 1, IS_NULL
= 2,
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;
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
63 static $_testEntitiesToSkip = array();
65 * the factory class for this application
68 static $_factory = NULL;
76 function __construct() {
78 $this->__table
= $this->getTableName();
82 * empty definition for virtual function
84 static function getTableName() {
89 * initialize the DAO object
91 * @param string $dsn the database connection string
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
);
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
116 foreach (array_keys($this->table()) as $field) {
117 unset($this->$field);
121 * reset the various DB_DAO structures manually
123 $this->_query
= array();
129 static function getLocaleTableName($tableName) {
132 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
133 if (in_array($tableName, $tables)) {
134 return $tableName . $dbLocale;
141 * Execute a query by the current DAO, localizing it along the way (if needed).
143 * @param string $query the SQL query for execution
144 * @param bool $i18nRewrite whether to rewrite the query
146 * @return object the current DAO object after the query execution
148 function query($query, $i18nRewrite = TRUE) {
149 // rewrite queries that should use $dbLocale-based views for multi-language installs
151 if ($i18nRewrite and $dbLocale) {
152 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
155 return parent
::query($query);
159 * Static function to set the factory instance for this class.
161 * @param object $factory the factory application object
167 static function setFactory(&$factory) {
168 self
::$_factory = &$factory;
172 * Factory method to instantiate a new object from a table name.
177 function factory($table = '') {
178 if (!isset(self
::$_factory)) {
179 return parent
::factory($table);
182 return self
::$_factory->create($table);
186 * Initialization for all DAO objects. Since we access DB_DO programatically
187 * we need to set the links manually.
192 function initialize() {
193 $links = $this->links();
200 if (!isset($GLOBALS['_DB_DATAOBJECT']['LINKS'][$this->_database
])) {
201 $GLOBALS['_DB_DATAOBJECT']['LINKS'][$this->_database
] = array();
204 if (!array_key_exists($this->__table
, $GLOBALS['_DB_DATAOBJECT']['LINKS'][$this->_database
])) {
205 $GLOBALS['_DB_DATAOBJECT']['LINKS'][$this->_database
][$this->__table
] = $links;
210 * Defines the default key as 'id'.
225 * Tells DB_DataObject which keys use autoincrement.
226 * 'id' is autoincrementing by default.
232 function sequenceKey() {
233 static $sequenceKeys;
234 if (!isset($sequenceKeys)) {
235 $sequenceKeys = array('id', TRUE);
237 return $sequenceKeys;
241 * returns list of FK relationships
252 * returns all the column names of this table
258 static function &fields() {
264 $fields = &$this->fields();
268 foreach ($fields as $name => $value) {
269 $table[$value['name']] = $value['type'];
270 if (CRM_Utils_Array
::value('required', $value)) {
271 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
283 if (!empty($this->id
)) {
291 CRM_Utils_Hook
::postSave($this);
296 function log($created = FALSE) {
299 if (!$this->getLog()) {
304 $session = CRM_Core_Session
::singleton();
305 $cid = $session->get('userID');
308 // return is we dont have handle to FK
313 $dao = new CRM_Core_DAO_Log();
314 $dao->entity_table
= $this->getTableName();
315 $dao->entity_id
= $this->id
;
316 $dao->modified_id
= $cid;
317 $dao->modified_date
= date("YmdHis");
322 * Given an associative array of name/value pairs, extract all the values
323 * that belong to this object and initialize the object with said values
325 * @param array $params (reference ) associative array of name/value pairs
327 * @return boolean did we copy all null values into the object
330 function copyValues(&$params) {
331 $fields = &$this->fields();
333 foreach ($fields as $name => $value) {
334 $dbName = $value['name'];
335 if (array_key_exists($dbName, $params)) {
336 $pValue = $params[$dbName];
339 elseif (array_key_exists($name, $params)) {
340 $pValue = $params[$name];
347 // if there is no value then make the variable NULL
349 if ($pValue === '') {
350 $this->$dbName = 'null';
353 $this->$dbName = $pValue;
362 * Store all the values from this object in an associative array
363 * this is a destructive store, calling function is responsible
364 * for keeping sanity of id's.
366 * @param object $object the object that we are extracting data from
367 * @param array $values (reference ) associative array of name/value pairs
373 static function storeValues(&$object, &$values) {
374 $fields = &$object->fields();
375 foreach ($fields as $name => $value) {
376 $dbName = $value['name'];
377 if (isset($object->$dbName) && $object->$dbName !== 'null') {
378 $values[$dbName] = $object->$dbName;
379 if ($name != $dbName) {
380 $values[$name] = $object->$dbName;
387 * create an attribute for this specific field. We only do this for strings and text
389 * @param array $field the field under task
391 * @return array|null the attributes for the object
395 static function makeAttribute($field) {
397 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
398 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
399 $size = CRM_Utils_Array
::value('size', $field);
400 if ($maxLength ||
$size) {
401 $attributes = array();
403 $attributes['maxlength'] = $maxLength;
406 $attributes['size'] = $size;
411 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
412 $rows = CRM_Utils_Array
::value('rows', $field);
416 $cols = CRM_Utils_Array
::value('cols', $field);
421 $attributes = array();
422 $attributes['rows'] = $rows;
423 $attributes['cols'] = $cols;
426 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_INT || CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_FLOAT || CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_MONEY
) {
427 $attributes['size'] = 6;
428 $attributes['maxlength'] = 14;
436 * Get the size and maxLength attributes for this text field
437 * (or for all text fields) in the DAO object.
439 * @param string $class name of DAO class
440 * @param string $fieldName field that i'm interested in or null if
441 * you want the attributes for all DAO text fields
443 * @return array assoc array of name => attribute pairs
447 static function getAttribute($class, $fieldName = NULL) {
448 $object = new $class( );
449 $fields = &$object->fields();
450 if ($fieldName != NULL) {
451 $field = CRM_Utils_Array
::value($fieldName, $fields);
452 return self
::makeAttribute($field);
455 $attributes = array();
456 foreach ($fields as $name => $field) {
457 $attribute = self
::makeAttribute($field);
459 $attributes[$name] = $attribute;
463 if (!empty($attributes)) {
470 static function transaction($type) {
471 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
475 * Check if there is a record with the same name in the db
477 * @param string $value the value of the field we are checking
478 * @param string $daoName the dao object name
479 * @param string $daoID the id of the object being updated. u can change your name
480 * as long as there is no conflict
481 * @param string $fieldName the name of the field in the DAO
483 * @return boolean true if object exists
487 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
488 $object = new $daoName( );
489 $object->$fieldName = $value;
491 $config = CRM_Core_Config
::singleton();
493 if ($object->find(TRUE)) {
494 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
502 * Check if there is a given column in a specific table
504 * @param string $tableName
505 * @param string $columnName
506 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
508 * @return boolean true if exists, else false
511 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
517 $params = array(1 => array($columnName, 'String'));
518 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
519 $result = $dao->fetch() ?
TRUE : FALSE;
525 * Returns the storage engine used by given table-name(optional).
526 * Otherwise scans all the tables and return an array of all the
527 * distinct storage engines being used.
529 * @param string $tableName
534 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
536 $query = "SHOW TABLE STATUS LIKE %1";
540 if (isset($tableName)) {
541 $params = array(1 => array($tableName, 'String'));
544 $params = array(1 => array('civicrm_%', 'String'));
547 $dao = CRM_Core_DAO
::executeQuery($query, $params);
550 while ($dao->fetch()) {
551 if (isset($values[$dao->$fieldName]) ||
552 // ignore import and other temp tables
553 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
554 strpos($dao->Name
, '_temp') !== FALSE
558 $values[$dao->$fieldName] = 1;
560 if ($maxTablesToCheck &&
561 $count >= $maxTablesToCheck
570 static function isDBMyISAM($maxTablesToCheck = 10) {
571 // show error if any of the tables, use 'MyISAM' storage engine.
572 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
573 if (array_key_exists('MyISAM', $engines)) {
580 * Checks if a constraint exists for a specified table.
582 * @param string $tableName
583 * @param string $constraint
585 * @return boolean true if constraint exists, false otherwise
588 static function checkConstraintExists($tableName, $constraint) {
589 static $show = array();
591 if (!array_key_exists($tableName, $show)) {
592 $query = "SHOW CREATE TABLE $tableName";
593 $dao = CRM_Core_DAO
::executeQuery($query);
595 if (!$dao->fetch()) {
596 CRM_Core_Error
::fatal();
600 $show[$tableName] = $dao->Create_Table
;
603 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
607 * Checks if CONSTRAINT keyword exists for a specified table.
609 * @param string $tableName
611 * @return boolean true if CONSTRAINT keyword exists, false otherwise
613 function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
615 foreach($tables as $tableName){
616 if (!array_key_exists($tableName, $show)) {
617 $query = "SHOW CREATE TABLE $tableName";
618 $dao = CRM_Core_DAO
::executeQuery($query);
620 if (!$dao->fetch()) {
621 CRM_Core_Error
::fatal();
625 $show[$tableName] = $dao->Create_Table
;
628 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
640 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
641 * for a specified column of a table.
643 * @param string $tableName
644 * @param string $columnName
646 * @return boolean true if in format, false otherwise
649 static function checkFKConstraintInFormat($tableName, $columnName) {
650 static $show = array();
652 if (!array_key_exists($tableName, $show)) {
653 $query = "SHOW CREATE TABLE $tableName";
654 $dao = CRM_Core_DAO
::executeQuery($query);
656 if (!$dao->fetch()) {
657 CRM_Core_Error
::fatal();
661 $show[$tableName] = $dao->Create_Table
;
663 $constraint = "`FK_{$tableName}_{$columnName}`";
664 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
665 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
669 * Check whether a specific column in a specific table has always the same value
671 * @param string $tableName
672 * @param string $columnName
673 * @param string $columnValue
675 * @return boolean true if the value is always $columnValue, false otherwise
678 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
679 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
680 $dao = CRM_Core_DAO
::executeQuery($query);
681 $result = $dao->fetch() ?
FALSE : TRUE;
687 * Check whether a specific column in a specific table is always NULL
689 * @param string $tableName
690 * @param string $columnName
692 * @return boolean true if if the value is always NULL, false otherwise
695 static function checkFieldIsAlwaysNull($tableName, $columnName) {
696 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
697 $dao = CRM_Core_DAO
::executeQuery($query);
698 $result = $dao->fetch() ?
FALSE : TRUE;
704 * Check if there is a given table in the database
706 * @param string $tableName
708 * @return boolean true if exists, else false
711 static function checkTableExists($tableName) {
716 $params = array(1 => array($tableName, 'String'));
718 $dao = CRM_Core_DAO
::executeQuery($query, $params);
719 $result = $dao->fetch() ?
TRUE : FALSE;
724 function checkVersion($version) {
729 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
730 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
734 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
736 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
737 * @param int $searchValue Value of the column you want to search by
738 * @param string $returnColumn Name of the column you want to GET the value of
739 * @param string $searchColumn Name of the column you want to search by
740 * @param boolean $force Skip use of the cache
742 * @return string|null Value of $returnColumn in the retrieved record
746 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
748 empty($searchValue) ||
749 trim(strtolower($searchValue)) == 'null'
751 // adding this year since developers forget to check for an id
752 // or for the 'null' (which is a bad DAO kludge)
753 // and hence we get the first value in the db
754 CRM_Core_Error
::fatal();
757 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
758 if (self
::$_dbColumnValueCache === NULL) {
759 self
::$_dbColumnValueCache = array();
762 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
763 $object = new $daoName( );
764 $object->$searchColumn = $searchValue;
765 $object->selectAdd();
766 $object->selectAdd($returnColumn);
769 if ($object->find(TRUE)) {
770 $result = $object->$returnColumn;
774 self
::$_dbColumnValueCache[$cacheKey] = $result;
776 return self
::$_dbColumnValueCache[$cacheKey];
780 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
782 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
783 * @param int $searchValue Value of the column you want to search by
784 * @param string $setColumn Name of the column you want to SET the value of
785 * @param string $setValue SET the setColumn to this value
786 * @param string $searchColumn Name of the column you want to search by
788 * @return boolean true if we found and updated the object, else false
792 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
793 $object = new $daoName( );
794 $object->selectAdd();
795 $object->selectAdd("$searchColumn, $setColumn");
796 $object->$searchColumn = $searchValue;
798 if ($object->find(TRUE)) {
799 $object->$setColumn = $setValue;
800 if ($object->save()) {
811 * @param array|object $sort either array or CRM_Utils_Sort
812 * @param string $default - default sort value
814 * @return string - sortString
818 static function getSortString($sort, $default = NULL) {
819 // check if sort is of type CRM_Utils_Sort
820 if (is_a($sort, 'CRM_Utils_Sort')) {
821 return $sort->orderBy();
824 // is it an array specified as $field => $sortDirection ?
826 foreach ($sort as $k => $v) {
827 $sortString .= "$k $v,";
829 return rtrim($sortString, ',');
835 * Takes a bunch of params that are needed to match certain criteria and
836 * retrieves the relevant objects. Typically the valid params are only
837 * contact_id. We'll tweak this function to be more full featured over a period
838 * of time. This is the inverse function of create. It also stores all the retrieved
839 * values in the default array
841 * @param string $daoName name of the dao object
842 * @param array $params (reference ) an assoc array of name/value pairs
843 * @param array $defaults (reference ) an assoc array to hold the flattened values
844 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
846 * @return object an object of type referenced by daoName
850 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
851 $object = new $daoName( );
852 $object->copyValues($params);
854 // return only specific fields if returnproperties are sent
855 if (!empty($returnProperities)) {
856 $object->selectAdd();
857 $object->selectAdd(implode(',', $returnProperities));
860 if ($object->find(TRUE)) {
861 self
::storeValues($object, $defaults);
868 * Delete the object records that are associated with this contact
870 * @param string $daoName name of the dao object
871 * @param int $contactId id of the contact to delete
877 static function deleteEntityContact($daoName, $contactId) {
878 $object = new $daoName( );
880 $object->entity_table
= 'civicrm_contact';
881 $object->entity_id
= $contactId;
888 * @param string $query query to be executed
890 * @return Object CRM_Core_DAO object that holds the results of the query
894 static function &executeQuery(
901 $trapException = FALSE
903 $queryStr = self
::composeQuery($query, $params, $abort);
904 //CRM_Core_Error::debug( 'q', $queryStr );
907 $dao = new CRM_Core_DAO();
910 $dao = new $daoName( );
913 if ($trapException) {
914 CRM_Core_Error
::ignoreException();
917 $result = $dao->query($queryStr, $i18nRewrite);
919 if ($trapException) {
920 CRM_Core_Error
::setCallback();
923 if (is_a($result, 'DB_Error')) {
928 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
930 // we typically do this for insert/update/delete stataments OR if explicitly asked to
938 * execute a query and get the single result
940 * @param string $query query to be executed
942 * @return string the result of the query
946 static function &singleValueQuery($query,
951 $queryStr = self
::composeQuery($query, $params, $abort);
956 $_dao = new CRM_Core_DAO();
959 $_dao->query($queryStr, $i18nRewrite);
961 $result = $_dao->getDatabaseResult();
964 $row = $result->fetchRow();
973 static function composeQuery($query, &$params, $abort = TRUE) {
975 foreach ($params as $key => $item) {
976 if (is_numeric($key)) {
977 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
978 $item[0] = self
::escapeString($item[0]);
979 if ($item[1] == 'String' ||
980 $item[1] == 'Memo' ||
983 if (isset($item[2]) &&
986 $item[0] = "'%{$item[0]}%'";
989 $item[0] = "'{$item[0]}'";
993 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
994 strlen($item[0]) == 0
999 $tr['%' . $key] = $item[0];
1002 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1008 foreach($tr as $key => $value) {
1009 $key = preg_quote($key);
1010 $value = preg_quote($value);
1011 $query = preg_replace("/$key\b/", $value, $query);
1016 static function freeResult($ids = NULL) {
1017 global $_DB_DATAOBJECT;
1021 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1022 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1024 CRM_Core_Error::debug( 'k', $q );
1029 if (!$_DB_DATAOBJECT ||
1030 !isset($_DB_DATAOBJECT['RESULTS'])
1034 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1037 foreach ($ids as $id) {
1038 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1039 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1040 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1042 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1045 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1046 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1052 * This function is to make a shallow copy of an object
1053 * and all the fields in the object
1055 * @param string $daoName name of the dao
1056 * @param array $criteria array of all the fields & values
1057 * on which basis to copy
1058 * @param array $newData array of all the fields & values
1059 * to be copied besides the other fields
1060 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1061 * @param string $blockCopyOfDependencies fields that you want to block from
1065 * @return (reference ) the newly created copy of the object
1068 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1069 $object = new $daoName( );
1071 $object->id
= $criteria['id'];
1074 foreach ($criteria as $key => $value) {
1075 $object->$key = $value;
1080 while ($object->fetch()) {
1082 // all the objects except with $blockCopyOfDependencies set
1083 // be copied - addresses #CRM-1962
1085 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1089 $newObject = new $daoName( );
1091 $fields = &$object->fields();
1092 if (!is_array($fieldsFix)) {
1093 $fieldsToPrefix = array();
1094 $fieldsToSuffix = array();
1095 $fieldsToReplace = array();
1097 if (CRM_Utils_Array
::value('prefix', $fieldsFix)) {
1098 $fieldsToPrefix = $fieldsFix['prefix'];
1100 if (CRM_Utils_Array
::value('suffix', $fieldsFix)) {
1101 $fieldsToSuffix = $fieldsFix['suffix'];
1103 if (CRM_Utils_Array
::value('replace', $fieldsFix)) {
1104 $fieldsToReplace = $fieldsFix['replace'];
1107 foreach ($fields as $name => $value) {
1108 if ($name == 'id' ||
$value['name'] == 'id') {
1109 // copy everything but the id!
1113 $dbName = $value['name'];
1114 $newObject->$dbName = $object->$dbName;
1115 if (isset($fieldsToPrefix[$dbName])) {
1116 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1118 if (isset($fieldsToSuffix[$dbName])) {
1119 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1121 if (isset($fieldsToReplace[$dbName])) {
1122 $newObject->$dbName = $fieldsToReplace[$dbName];
1125 if (substr($name, -5) == '_date' ||
1126 substr($name, -10) == '_date_time'
1128 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1132 foreach ($newData as $k => $v) {
1133 $newObject->$k = $v;
1143 * Given the component id, compute the contact id
1144 * since its used for things like send email
1146 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1147 $contactIDs = array();
1149 if (empty($componentIDs)) {
1153 $IDs = implode(',', $componentIDs);
1157 WHERE id IN ( $IDs )
1160 $dao = CRM_Core_DAO
::executeQuery($query);
1161 while ($dao->fetch()) {
1162 $contactIDs[] = $dao->contact_id
;
1168 * Takes a bunch of params that are needed to match certain criteria and
1169 * retrieves the relevant objects. Typically the valid params are only
1170 * contact_id. We'll tweak this function to be more full featured over a period
1171 * of time. This is the inverse function of create. It also stores all the retrieved
1172 * values in the default array
1174 * @param string $daoName name of the dao object
1175 * @param array $params (reference ) an assoc array of name/value pairs
1176 * @param array $defaults (reference ) an assoc array to hold the flattened values
1177 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1179 * @return object an object of type referenced by daoName
1183 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1184 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1185 $object = new $daoName( );
1186 $object->$fieldIdName = $fieldId;
1188 // return only specific fields if returnproperties are sent
1189 if (!empty($returnProperities)) {
1190 $object->selectAdd();
1191 $object->selectAdd('id');
1192 $object->selectAdd(implode(',', $returnProperities));
1196 while ($object->fetch()) {
1197 $defaults = array();
1198 self
::storeValues($object, $defaults);
1199 $details[$object->id
] = $defaults;
1205 static function dropAllTables() {
1207 // first drop all the custom tables we've created
1208 CRM_Core_BAO_CustomGroup
::dropAllTables();
1210 // drop all multilingual views
1211 CRM_Core_I18n_Schema
::dropAllViews();
1213 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1214 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1215 '..' . DIRECTORY_SEPARATOR
.
1216 '..' . DIRECTORY_SEPARATOR
.
1217 'sql' . DIRECTORY_SEPARATOR
.
1218 'civicrm_drop.mysql'
1222 static function escapeString($string) {
1223 static $_dao = NULL;
1226 $_dao = new CRM_Core_DAO();
1229 return $_dao->escape($string);
1233 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1235 * @param $strings array
1236 * @param $default string the value to use if $strings has no elements
1237 * @return string eg "abc","def","ghi"
1239 static function escapeStrings($strings, $default = NULL) {
1240 static $_dao = NULL;
1242 $_dao = new CRM_Core_DAO();
1245 if (empty($strings)) {
1249 $escapes = array_map(array($_dao, 'escape'), $strings);
1250 return '"' . implode('","', $escapes) . '"';
1253 static function escapeWildCardString($string) {
1255 // ensure we escape the single characters % and _ which are mysql wild
1256 // card characters and could come in via sortByCharacter
1257 // note that mysql does not escape these characters
1258 if ($string && in_array($string,
1259 array('%', '_', '%%', '_%')
1261 return '\\' . $string;
1264 return self
::escapeString($string);
1267 //Creates a test object, including any required objects it needs via recursion
1268 //createOnly: only create in database, do not store or return the objects (useful for perf testing)
1269 //ONLY USE FOR TESTING
1270 static function createTestObject(
1276 static $counter = 0;
1277 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1278 'CRM_Core_DAO_Worldregion',
1279 'CRM_Core_DAO_StateProvince',
1280 'CRM_Core_DAO_Country',
1281 'CRM_Core_DAO_Domain',
1284 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1286 for ($i = 0; $i < $numObjects; ++
$i) {
1289 $object = new $daoName ( );
1291 $fields = &$object->fields();
1292 foreach ($fields as $name => $value) {
1293 $dbName = $value['name'];
1294 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1295 //coming up with a rule to set this is too complex let's not set it
1298 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1299 $required = CRM_Utils_Array
::value('required', $value);
1300 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1301 $object->$dbName = $params[$dbName];
1304 elseif ($dbName != 'id') {
1305 if ($FKClassName != NULL) {
1306 //skip the FK if it is not required
1307 // if it's contact id we should create even if not required
1308 // we'll have a go @ fetching first though
1309 if (!$required && $dbName != 'contact_id') {
1310 $fkDAO = new $FKClassName;
1311 if($fkDAO->find(TRUE)){
1312 $object->$dbName = $fkDAO->id
;
1317 if(in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)){
1318 $depObject = new $FKClassName();
1319 $depObject->find(TRUE);
1320 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1321 // FIXME: the fields() metadata is not specific enough
1322 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1324 //if it is required we need to generate the dependency object first
1325 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
1327 $object->$dbName = $depObject->id
;
1332 $constant = CRM_Utils_Array
::value('pseudoconstant', $value);
1333 if (!empty($constant)) {
1334 $constantValues = CRM_Utils_PseudoConstant
::getConstant($constant['name']);
1335 if (!empty($constantValues)) {
1336 $constantOptions = array_keys($constantValues);
1337 $object->$dbName = $constantOptions[0];
1341 $enum = CRM_Utils_Array
::value('enumValues', $value);
1342 if (!empty($enum)) {
1343 $options = explode(',', $enum);
1344 $object->$dbName = $options[0];
1347 switch ($value['type']) {
1348 case CRM_Utils_Type
::T_INT
:
1349 case CRM_Utils_Type
::T_FLOAT
:
1350 case CRM_Utils_Type
::T_MONEY
:
1351 $object->$dbName = $counter;
1354 case CRM_Utils_Type
::T_BOOL
:
1355 case CRM_Utils_Type
::T_BOOLEAN
:
1356 if (isset($value['default'])) {
1357 $object->$dbName = $value['default'];
1359 elseif ($value['name'] == 'is_deleted' ||
$value['name'] == 'is_test') {
1360 $object->$dbName = 0;
1363 $object->$dbName = 1;
1367 case CRM_Utils_Type
::T_DATE
:
1368 case CRM_Utils_Type
::T_TIMESTAMP
:
1369 $object->$dbName = '19700101';
1372 case CRM_Utils_Type
::T_TIME
:
1373 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
1374 //$object->$dbName='000000';
1376 case CRM_Utils_Type
::T_CCNUM
:
1377 $object->$dbName = '4111 1111 1111 1111';
1380 case CRM_Utils_Type
::T_URL
:
1381 $object->$dbName = 'http://www.civicrm.org';
1384 case CRM_Utils_Type
::T_STRING
:
1385 case CRM_Utils_Type
::T_BLOB
:
1386 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1387 case CRM_Utils_Type
::T_TEXT
:
1388 case CRM_Utils_Type
::T_LONGTEXT
:
1389 case CRM_Utils_Type
::T_EMAIL
:
1391 if (isset($value['enumValues'])) {
1392 if (isset($value['default'])) {
1393 $object->$dbName = $value['default'];
1396 if (is_array($value['enumValues'])) {
1397 $object->$dbName = $value['enumValues'][0];
1400 $defaultValues = explode(',', $value['enumValues']);
1401 $object->$dbName = $defaultValues[0];
1406 $object->$dbName = $dbName . '_' . $counter;
1407 $maxlength = CRM_Utils_Array
::value('maxlength', $value);
1408 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1409 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1419 $objects[$i] = $object;
1422 else unset($object);
1430 elseif ($numObjects == 1) { return $objects[0];}
1431 else return $objects;
1434 //deletes the this object plus any dependent objects that are associated with it
1435 //ONLY USE FOR TESTING
1437 static function deleteTestObjects($daoName, $params = array(
1440 $object = new $daoName ( );
1441 $object->id
= CRM_Utils_Array
::value('id', $params);
1443 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1444 if ($object->find(TRUE)) {
1446 $fields = &$object->fields();
1447 foreach ($fields as $name => $value) {
1449 $dbName = $value['name'];
1451 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1452 $required = CRM_Utils_Array
::value('required', $value);
1453 if ($FKClassName != NULL
1455 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1456 && ($required ||
$dbName == 'contact_id')) {
1457 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1464 foreach ($deletions as $deletion) {
1465 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1469 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1470 $tableName = $prefix . "_temp";
1472 if ($addRandomString) {
1474 $tableName .= "_" . $string;
1477 $tableName .= "_" . md5(uniqid('', TRUE));
1483 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1484 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1486 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1487 CRM_Core_Error
::ignoreException();
1488 $dao = new CRM_Core_DAO();
1490 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1491 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1492 CRM_Core_Error
::setCallback();
1498 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1499 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1500 CRM_Core_Error
::setCallback();
1502 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1507 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1508 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1509 CRM_Core_Error
::setCallback();
1511 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1518 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1519 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1520 CRM_Core_Error
::setCallback();
1524 CRM_Core_Error
::setCallback();
1529 static function debugPrint($message = NULL, $printDAO = TRUE) {
1530 CRM_Utils_System
::xMemory("{$message}: ");
1533 global $_DB_DATAOBJECT;
1535 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1536 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1538 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1543 * Build a list of triggers via hook and add them to (err, reconcile them
1544 * with) the database.
1546 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1549 static function triggerRebuild($tableName = NULL) {
1552 $logging = new CRM_Logging_Schema
;
1553 $logging->triggerInfo($info, $tableName);
1555 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1556 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1558 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1560 // drop all existing triggers on all tables
1561 $logging->dropTriggers($tableName);
1563 // now create the set of new triggers
1564 self
::createTriggers($info);
1568 * Wrapper function to drop triggers
1570 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1572 static function dropTriggers($tableName = NULL) {
1575 $logging = new CRM_Logging_Schema
;
1576 $logging->triggerInfo($info, $tableName);
1578 // drop all existing triggers on all tables
1579 $logging->dropTriggers($tableName);
1583 * @param $info array per hook_civicrm_triggerInfo
1584 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1586 static function createTriggers(&$info, $onlyTableName = NULL) {
1587 // Validate info array, should probably raise errors?
1588 if (is_array($info) == FALSE) {
1592 $triggers = array();
1594 // now enumerate the tables and the events and collect the same set in a different format
1595 foreach ($info as $value) {
1597 // clean the incoming data, skip malformed entries
1598 // TODO: malformed entries should raise errors or get logged.
1599 if (isset($value['table']) == FALSE ||
1600 isset($value['event']) == FALSE ||
1601 isset($value['when']) == FALSE ||
1602 isset($value['sql']) == FALSE
1607 if (is_string($value['table']) == TRUE) {
1608 $tables = array($value['table']);
1611 $tables = $value['table'];
1614 if (is_string($value['event']) == TRUE) {
1615 $events = array(strtolower($value['event']));
1618 $events = array_map('strtolower', $value['event']);
1621 $whenName = strtolower($value['when']);
1623 foreach ($tables as $tableName) {
1624 if (!isset($triggers[$tableName])) {
1625 $triggers[$tableName] = array();
1628 foreach ($events as $eventName) {
1629 $template_params = array('{tableName}', '{eventName}');
1630 $template_values = array($tableName, $eventName);
1632 $sql = str_replace($template_params,
1636 $variables = str_replace($template_params,
1638 CRM_Utils_Array
::value('variables', $value)
1641 if (!isset($triggers[$tableName][$eventName])) {
1642 $triggers[$tableName][$eventName] = array();
1645 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1646 // We're leaving out cursors, conditions, and handlers for now
1647 // they are kind of dangerous in this context anyway
1648 // better off putting them in stored procedures
1649 $triggers[$tableName][$eventName][$whenName] = array(
1650 'variables' => array(),
1656 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1659 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1664 // now spit out the sql
1665 foreach ($triggers as $tableName => $tables) {
1666 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1669 foreach ($tables as $eventName => $events) {
1670 foreach ($events as $whenName => $parts) {
1671 $varString = implode("\n", $parts['variables']);
1672 $sqlString = implode("\n", $parts['sql']);
1673 $triggerName = "{$tableName}_{$whenName}_{$eventName}";
1674 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1676 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1677 CRM_Core_DAO
::executeQuery(
1691 * Check the tables sent in, to see if there are any tables where there is a value for
1694 * This is typically used when we want to delete a row, but want to avoid the FK errors
1695 * that it might cause due to this being a required FK
1697 * @param array an array of values (tableName, columnName)
1698 * @param array the parameter array with the value and type
1699 * @param array (reference) the tables which had an entry for this value
1701 * @return boolean true if no value exists in all the tables
1704 public static function doesValueExistInTable(&$tables, $params, &$errors) {
1706 foreach ($tables as $table) {
1707 $sql = "SELECT count(*) FROM {$table['table']} WHERE {$table['column']} = %1";
1708 $count = self
::singleValueQuery($sql, $params);
1710 $errors[$table['table']] = $count;
1714 return (empty($errors)) ?
FALSE : TRUE;
1718 * Lookup the value of a MySQL global configuration variable.
1720 * @param string $name e.g. "thread_stack"
1721 * @param mixed $default
1724 public static function getGlobalSetting($name, $default = NULL) {
1725 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1726 // that has been reported to fail under MySQL 5.0 for OS X
1727 $escapedName = self
::escapeString($name);
1728 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1729 if ($dao->fetch()) {