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() {
197 * Defines the default key as 'id'.
212 * Tells DB_DataObject which keys use autoincrement.
213 * 'id' is autoincrementing by default.
219 function sequenceKey() {
220 static $sequenceKeys;
221 if (!isset($sequenceKeys)) {
222 $sequenceKeys = array('id', TRUE);
224 return $sequenceKeys;
228 * returns list of FK relationships
233 * @return array of CRM_Core_EntityReference
235 static function getReferenceColumns() {
240 * returns all the column names of this table
246 static function &fields() {
252 $fields = &$this->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
;
268 if (!empty($this->id
)) {
276 CRM_Utils_Hook
::postSave($this);
281 function log($created = FALSE) {
284 if (!$this->getLog()) {
289 $session = CRM_Core_Session
::singleton();
290 $cid = $session->get('userID');
293 // return is we dont have handle to FK
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");
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
310 * @param array $params (reference ) associative array of name/value pairs
312 * @return boolean did we copy all null values into the object
315 function copyValues(&$params) {
316 $fields = &$this->fields();
318 foreach ($fields as $name => $value) {
319 $dbName = $value['name'];
320 if (array_key_exists($dbName, $params)) {
321 $pValue = $params[$dbName];
324 elseif (array_key_exists($name, $params)) {
325 $pValue = $params[$name];
332 // if there is no value then make the variable NULL
334 if ($pValue === '') {
335 $this->$dbName = 'null';
338 $this->$dbName = $pValue;
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.
351 * @param object $object the object that we are extracting data from
352 * @param array $values (reference ) associative array of name/value pairs
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;
372 * create an attribute for this specific field. We only do this for strings and text
374 * @param array $field the field under task
376 * @return array|null the attributes for the object
380 static function makeAttribute($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();
388 $attributes['maxlength'] = $maxLength;
391 $attributes['size'] = $size;
396 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
397 $rows = CRM_Utils_Array
::value('rows', $field);
401 $cols = CRM_Utils_Array
::value('cols', $field);
406 $attributes = array();
407 $attributes['rows'] = $rows;
408 $attributes['cols'] = $cols;
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;
421 * Get the size and maxLength attributes for this text field
422 * (or for all text fields) in the DAO object.
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
428 * @return array assoc array of name => attribute pairs
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);
440 $attributes = array();
441 foreach ($fields as $name => $field) {
442 $attribute = self
::makeAttribute($field);
444 $attributes[$name] = $attribute;
448 if (!empty($attributes)) {
455 static function transaction($type) {
456 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
460 * Check if there is a record with the same name in the db
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
468 * @return boolean true if object exists
472 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
473 $object = new $daoName( );
474 $object->$fieldName = $value;
476 $config = CRM_Core_Config
::singleton();
478 if ($object->find(TRUE)) {
479 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
487 * Check if there is a given column in a specific table
489 * @param string $tableName
490 * @param string $columnName
491 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
493 * @return boolean true if exists, else false
496 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
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;
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.
514 * @param string $tableName
519 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
521 $query = "SHOW TABLE STATUS LIKE %1";
525 if (isset($tableName)) {
526 $params = array(1 => array($tableName, 'String'));
529 $params = array(1 => array('civicrm_%', 'String'));
532 $dao = CRM_Core_DAO
::executeQuery($query, $params);
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
543 $values[$dao->$fieldName] = 1;
545 if ($maxTablesToCheck &&
546 $count >= $maxTablesToCheck
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)) {
565 * Checks if a constraint exists for a specified table.
567 * @param string $tableName
568 * @param string $constraint
570 * @return boolean true if constraint exists, false otherwise
573 static function checkConstraintExists($tableName, $constraint) {
574 static $show = array();
576 if (!array_key_exists($tableName, $show)) {
577 $query = "SHOW CREATE TABLE $tableName";
578 $dao = CRM_Core_DAO
::executeQuery($query);
580 if (!$dao->fetch()) {
581 CRM_Core_Error
::fatal();
585 $show[$tableName] = $dao->Create_Table
;
588 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
592 * Checks if CONSTRAINT keyword exists for a specified table.
594 * @param string $tableName
596 * @return boolean true if CONSTRAINT keyword exists, false otherwise
598 function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
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);
605 if (!$dao->fetch()) {
606 CRM_Core_Error
::fatal();
610 $show[$tableName] = $dao->Create_Table
;
613 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
625 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
626 * for a specified column of a table.
628 * @param string $tableName
629 * @param string $columnName
631 * @return boolean true if in format, false otherwise
634 static function checkFKConstraintInFormat($tableName, $columnName) {
635 static $show = array();
637 if (!array_key_exists($tableName, $show)) {
638 $query = "SHOW CREATE TABLE $tableName";
639 $dao = CRM_Core_DAO
::executeQuery($query);
641 if (!$dao->fetch()) {
642 CRM_Core_Error
::fatal();
646 $show[$tableName] = $dao->Create_Table
;
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;
654 * Check whether a specific column in a specific table has always the same value
656 * @param string $tableName
657 * @param string $columnName
658 * @param string $columnValue
660 * @return boolean true if the value is always $columnValue, false otherwise
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;
672 * Check whether a specific column in a specific table is always NULL
674 * @param string $tableName
675 * @param string $columnName
677 * @return boolean true if if the value is always NULL, false otherwise
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;
689 * Check if there is a given table in the database
691 * @param string $tableName
693 * @return boolean true if exists, else false
696 static function checkTableExists($tableName) {
701 $params = array(1 => array($tableName, 'String'));
703 $dao = CRM_Core_DAO
::executeQuery($query, $params);
704 $result = $dao->fetch() ?
TRUE : FALSE;
709 function checkVersion($version) {
714 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
715 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
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
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
727 * @return string|null Value of $returnColumn in the retrieved record
731 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
733 empty($searchValue) ||
734 trim(strtolower($searchValue)) == 'null'
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();
742 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
743 if (self
::$_dbColumnValueCache === NULL) {
744 self
::$_dbColumnValueCache = array();
747 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
748 $object = new $daoName( );
749 $object->$searchColumn = $searchValue;
750 $object->selectAdd();
751 $object->selectAdd($returnColumn);
754 if ($object->find(TRUE)) {
755 $result = $object->$returnColumn;
759 self
::$_dbColumnValueCache[$cacheKey] = $result;
761 return self
::$_dbColumnValueCache[$cacheKey];
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
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
773 * @return boolean true if we found and updated the object, else false
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;
783 if ($object->find(TRUE)) {
784 $object->$setColumn = $setValue;
785 if ($object->save()) {
796 * @param array|object $sort either array or CRM_Utils_Sort
797 * @param string $default - default sort value
799 * @return string - sortString
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();
809 // is it an array specified as $field => $sortDirection ?
811 foreach ($sort as $k => $v) {
812 $sortString .= "$k $v,";
814 return rtrim($sortString, ',');
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
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')
831 * @return object an object of type referenced by daoName
835 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
836 $object = new $daoName( );
837 $object->copyValues($params);
839 // return only specific fields if returnproperties are sent
840 if (!empty($returnProperities)) {
841 $object->selectAdd();
842 $object->selectAdd(implode(',', $returnProperities));
845 if ($object->find(TRUE)) {
846 self
::storeValues($object, $defaults);
853 * Delete the object records that are associated with this contact
855 * @param string $daoName name of the dao object
856 * @param int $contactId id of the contact to delete
862 static function deleteEntityContact($daoName, $contactId) {
863 $object = new $daoName( );
865 $object->entity_table
= 'civicrm_contact';
866 $object->entity_id
= $contactId;
873 * @param string $query query to be executed
875 * @return Object CRM_Core_DAO object that holds the results of the query
879 static function &executeQuery(
886 $trapException = FALSE
888 $queryStr = self
::composeQuery($query, $params, $abort);
889 //CRM_Core_Error::debug( 'q', $queryStr );
892 $dao = new CRM_Core_DAO();
895 $dao = new $daoName( );
898 if ($trapException) {
899 CRM_Core_Error
::ignoreException();
902 $result = $dao->query($queryStr, $i18nRewrite);
904 if ($trapException) {
905 CRM_Core_Error
::setCallback();
908 if (is_a($result, 'DB_Error')) {
913 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
915 // we typically do this for insert/update/delete stataments OR if explicitly asked to
923 * execute a query and get the single result
925 * @param string $query query to be executed
927 * @return string the result of the query
931 static function &singleValueQuery($query,
936 $queryStr = self
::composeQuery($query, $params, $abort);
941 $_dao = new CRM_Core_DAO();
944 $_dao->query($queryStr, $i18nRewrite);
946 $result = $_dao->getDatabaseResult();
949 $row = $result->fetchRow();
958 static function composeQuery($query, &$params, $abort = TRUE) {
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' ||
968 if (isset($item[2]) &&
971 $item[0] = "'%{$item[0]}%'";
974 $item[0] = "'{$item[0]}'";
978 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
979 strlen($item[0]) == 0
984 $tr['%' . $key] = $item[0];
987 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
993 foreach($tr as $key => $value) {
994 $key = preg_quote($key);
995 $query = preg_replace("/$key\b/", $value, $query);
1000 static function freeResult($ids = NULL) {
1001 global $_DB_DATAOBJECT;
1005 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1006 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1008 CRM_Core_Error::debug( 'k', $q );
1013 if (!$_DB_DATAOBJECT ||
1014 !isset($_DB_DATAOBJECT['RESULTS'])
1018 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
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
);
1026 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1029 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1030 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1036 * This function is to make a shallow copy of an object
1037 * and all the fields in the object
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
1049 * @return (reference ) the newly created copy of the object
1052 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1053 $object = new $daoName( );
1055 $object->id
= $criteria['id'];
1058 foreach ($criteria as $key => $value) {
1059 $object->$key = $value;
1064 while ($object->fetch()) {
1066 // all the objects except with $blockCopyOfDependencies set
1067 // be copied - addresses #CRM-1962
1069 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1073 $newObject = new $daoName( );
1075 $fields = &$object->fields();
1076 if (!is_array($fieldsFix)) {
1077 $fieldsToPrefix = array();
1078 $fieldsToSuffix = array();
1079 $fieldsToReplace = array();
1081 if (CRM_Utils_Array
::value('prefix', $fieldsFix)) {
1082 $fieldsToPrefix = $fieldsFix['prefix'];
1084 if (CRM_Utils_Array
::value('suffix', $fieldsFix)) {
1085 $fieldsToSuffix = $fieldsFix['suffix'];
1087 if (CRM_Utils_Array
::value('replace', $fieldsFix)) {
1088 $fieldsToReplace = $fieldsFix['replace'];
1091 foreach ($fields as $name => $value) {
1092 if ($name == 'id' ||
$value['name'] == 'id') {
1093 // copy everything but the id!
1097 $dbName = $value['name'];
1098 $newObject->$dbName = $object->$dbName;
1099 if (isset($fieldsToPrefix[$dbName])) {
1100 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1102 if (isset($fieldsToSuffix[$dbName])) {
1103 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1105 if (isset($fieldsToReplace[$dbName])) {
1106 $newObject->$dbName = $fieldsToReplace[$dbName];
1109 if (substr($name, -5) == '_date' ||
1110 substr($name, -10) == '_date_time'
1112 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1116 foreach ($newData as $k => $v) {
1117 $newObject->$k = $v;
1127 * Given the component id, compute the contact id
1128 * since its used for things like send email
1130 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1131 $contactIDs = array();
1133 if (empty($componentIDs)) {
1137 $IDs = implode(',', $componentIDs);
1141 WHERE id IN ( $IDs )
1144 $dao = CRM_Core_DAO
::executeQuery($query);
1145 while ($dao->fetch()) {
1146 $contactIDs[] = $dao->contact_id
;
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
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')
1163 * @return object an object of type referenced by daoName
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;
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));
1180 while ($object->fetch()) {
1181 $defaults = array();
1182 self
::storeValues($object, $defaults);
1183 $details[$object->id
] = $defaults;
1189 static function dropAllTables() {
1191 // first drop all the custom tables we've created
1192 CRM_Core_BAO_CustomGroup
::dropAllTables();
1194 // drop all multilingual views
1195 CRM_Core_I18n_Schema
::dropAllViews();
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'
1206 static function escapeString($string) {
1207 static $_dao = NULL;
1210 $_dao = new CRM_Core_DAO();
1213 return $_dao->escape($string);
1217 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1219 * @param $strings array
1220 * @param $default string the value to use if $strings has no elements
1221 * @return string eg "abc","def","ghi"
1223 static function escapeStrings($strings, $default = NULL) {
1224 static $_dao = NULL;
1226 $_dao = new CRM_Core_DAO();
1229 if (empty($strings)) {
1233 $escapes = array_map(array($_dao, 'escape'), $strings);
1234 return '"' . implode('","', $escapes) . '"';
1237 static function escapeWildCardString($string) {
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('%', '_', '%%', '_%')
1245 return '\\' . $string;
1248 return self
::escapeString($string);
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(
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',
1268 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1270 for ($i = 0; $i < $numObjects; ++
$i) {
1273 $object = new $daoName ( );
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
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];
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
;
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'));
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));
1311 $object->$dbName = $depObject->id
;
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];
1325 $enum = CRM_Utils_Array
::value('enumValues', $value);
1326 if (!empty($enum)) {
1327 $options = explode(',', $enum);
1328 $object->$dbName = $options[0];
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;
1338 case CRM_Utils_Type
::T_BOOL
:
1339 case CRM_Utils_Type
::T_BOOLEAN
:
1340 if (isset($value['default'])) {
1341 $object->$dbName = $value['default'];
1343 elseif ($value['name'] == 'is_deleted' ||
$value['name'] == 'is_test') {
1344 $object->$dbName = 0;
1347 $object->$dbName = 1;
1351 case CRM_Utils_Type
::T_DATE
:
1352 case CRM_Utils_Type
::T_TIMESTAMP
:
1353 $object->$dbName = '19700101';
1356 case CRM_Utils_Type
::T_TIME
:
1357 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
1358 //$object->$dbName='000000';
1360 case CRM_Utils_Type
::T_CCNUM
:
1361 $object->$dbName = '4111 1111 1111 1111';
1364 case CRM_Utils_Type
::T_URL
:
1365 $object->$dbName = 'http://www.civicrm.org';
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
:
1375 if (isset($value['enumValues'])) {
1376 if (isset($value['default'])) {
1377 $object->$dbName = $value['default'];
1380 if (is_array($value['enumValues'])) {
1381 $object->$dbName = $value['enumValues'][0];
1384 $defaultValues = explode(',', $value['enumValues']);
1385 $object->$dbName = $defaultValues[0];
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']);
1403 $objects[$i] = $object;
1406 else unset($object);
1414 elseif ($numObjects == 1) { return $objects[0];}
1415 else return $objects;
1418 //deletes the this object plus any dependent objects that are associated with it
1419 //ONLY USE FOR TESTING
1421 static function deleteTestObjects($daoName, $params = array(
1424 $object = new $daoName ( );
1425 $object->id
= CRM_Utils_Array
::value('id', $params);
1427 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1428 if ($object->find(TRUE)) {
1430 $fields = &$object->fields();
1431 foreach ($fields as $name => $value) {
1433 $dbName = $value['name'];
1435 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1436 $required = CRM_Utils_Array
::value('required', $value);
1437 if ($FKClassName != NULL
1439 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1440 && ($required ||
$dbName == 'contact_id')) {
1441 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1448 foreach ($deletions as $deletion) {
1449 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1453 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1454 $tableName = $prefix . "_temp";
1456 if ($addRandomString) {
1458 $tableName .= "_" . $string;
1461 $tableName .= "_" . md5(uniqid('', TRUE));
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
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();
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();
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();
1486 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1491 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1492 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1493 CRM_Core_Error
::setCallback();
1495 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1502 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1503 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1504 CRM_Core_Error
::setCallback();
1508 CRM_Core_Error
::setCallback();
1513 static function debugPrint($message = NULL, $printDAO = TRUE) {
1514 CRM_Utils_System
::xMemory("{$message}: ");
1517 global $_DB_DATAOBJECT;
1519 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1520 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1522 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1527 * Build a list of triggers via hook and add them to (err, reconcile them
1528 * with) the database.
1530 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1533 static function triggerRebuild($tableName = NULL) {
1536 $logging = new CRM_Logging_Schema
;
1537 $logging->triggerInfo($info, $tableName);
1539 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1540 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1542 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1544 // drop all existing triggers on all tables
1545 $logging->dropTriggers($tableName);
1547 // now create the set of new triggers
1548 self
::createTriggers($info);
1552 * Wrapper function to drop triggers
1554 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1556 static function dropTriggers($tableName = NULL) {
1559 $logging = new CRM_Logging_Schema
;
1560 $logging->triggerInfo($info, $tableName);
1562 // drop all existing triggers on all tables
1563 $logging->dropTriggers($tableName);
1567 * @param $info array per hook_civicrm_triggerInfo
1568 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1570 static function createTriggers(&$info, $onlyTableName = NULL) {
1571 // Validate info array, should probably raise errors?
1572 if (is_array($info) == FALSE) {
1576 $triggers = array();
1578 // now enumerate the tables and the events and collect the same set in a different format
1579 foreach ($info as $value) {
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
1591 if (is_string($value['table']) == TRUE) {
1592 $tables = array($value['table']);
1595 $tables = $value['table'];
1598 if (is_string($value['event']) == TRUE) {
1599 $events = array(strtolower($value['event']));
1602 $events = array_map('strtolower', $value['event']);
1605 $whenName = strtolower($value['when']);
1607 foreach ($tables as $tableName) {
1608 if (!isset($triggers[$tableName])) {
1609 $triggers[$tableName] = array();
1612 foreach ($events as $eventName) {
1613 $template_params = array('{tableName}', '{eventName}');
1614 $template_values = array($tableName, $eventName);
1616 $sql = str_replace($template_params,
1620 $variables = str_replace($template_params,
1622 CRM_Utils_Array
::value('variables', $value)
1625 if (!isset($triggers[$tableName][$eventName])) {
1626 $triggers[$tableName][$eventName] = array();
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(),
1640 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1643 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1648 // now spit out the sql
1649 foreach ($triggers as $tableName => $tables) {
1650 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
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";
1660 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1661 CRM_Core_DAO
::executeQuery(
1675 * Find all records which refer to this entity.
1677 * @return array of objects referencing this
1679 function findReferences() {
1680 $links = self
::getReferencesToTable(static::getTableName());
1682 $occurrences = array();
1683 foreach ($links as $refSpec) {
1684 $refColumn = $refSpec->getReferenceKey();
1685 $targetColumn = $refSpec->getTargetKey();
1686 $params = array(1 => array($this->$targetColumn, 'String'));
1689 FROM {$refSpec->getReferenceTable()}
1690 WHERE {$refColumn} = %1
1692 if ($refSpec->isGeneric()) {
1693 $params[2] = array(static::getTableName(), 'String');
1695 AND {$refSpec->getTypeColumn()} = %2
1698 $daoName = CRM_Core_DAO_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;
1707 return $occurrences;
1711 * List all tables which have hard foreign keys to this table.
1713 * For now, this returns a description of every entity_id/entity_table
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.
1719 * @param string $tableName table referred to
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.
1724 static function getReferencesToTable($tableName) {
1725 $refsFound = array();
1726 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
1727 $links = $daoClassName::getReferenceColumns();
1728 $daoTableName = $daoClassName::getTableName();
1730 foreach ($links as $refSpec) {
1731 if ($refSpec->getTargetTable() === $tableName
1732 or $refSpec->isGeneric()
1734 $refsFound[] = $refSpec;
1742 * Lookup the value of a MySQL global configuration variable.
1744 * @param string $name e.g. "thread_stack"
1745 * @param mixed $default
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()) {