3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
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-2017
35 if (!defined('DB_DSN_MODE')) {
36 define('DB_DSN_MODE', 'auto');
39 require_once 'PEAR.php';
40 require_once 'DB/DataObject.php';
42 require_once 'CRM/Core/I18n.php';
47 class CRM_Core_DAO
extends DB_DataObject
{
53 static $_nullObject = NULL;
58 static $_nullArray = array();
60 static $_dbColumnValueCache = NULL;
61 const NOT_NULL
= 1, IS_NULL
= 2,
63 VALUE_SEPARATOR
= "\ 1",
64 BULK_INSERT_COUNT
= 200,
65 BULK_INSERT_HIGH_COUNT
= 200,
66 QUERY_FORMAT_WILDCARD
= 1,
67 QUERY_FORMAT_NO_QUOTES
= 2,
70 * Serialized string separated by and bookended with VALUE_SEPARATOR
72 SERIALIZE_SEPARATOR_BOOKEND
= 1,
74 * @deprecated format separated by VALUE_SEPARATOR
76 SERIALIZE_SEPARATOR_TRIMMED
= 2,
78 * Recommended serialization format
82 * @deprecated format using php serialize()
87 * Define entities that shouldn't be created or deleted when creating/ deleting
88 * test objects - this prevents world regions, countries etc from being added / deleted
91 static $_testEntitiesToSkip = array();
93 * The factory class for this application.
96 static $_factory = NULL;
98 static $_checkedSqlFunctionsExist = FALSE;
101 * https://issues.civicrm.org/jira/browse/CRM-17748
102 * internal variable for DAO to hold per-query settings
104 protected $_options = array();
109 * @return \CRM_Core_DAO
111 public function __construct() {
113 $this->__table
= $this->getTableName();
117 * Empty definition for virtual function.
119 public static function getTableName() {
124 * Initialize the DAO object.
127 * The database connection string.
129 public static function init($dsn) {
130 Civi
::$statics[__CLASS__
]['init'] = 1;
131 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
132 $options['database'] = $dsn;
133 if (defined('CIVICRM_DAO_DEBUG')) {
134 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
136 $factory = new CRM_Contact_DAO_Factory();
137 CRM_Core_DAO
::setFactory($factory);
138 $currentModes = CRM_Utils_SQL
::getSqlModes();
139 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
140 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
141 $currentModes[] = 'ONLY_FULL_GROUP_BY';
143 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
144 $currentModes = array_merge(array('STRICT_TRANS_TABLES'), $currentModes);
146 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", array(1 => array(implode(',', $currentModes), 'String')));
148 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
149 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request
::id(), 'String')));
155 public static function getConnection() {
156 global $_DB_DATAOBJECT;
157 $dao = new CRM_Core_DAO();
158 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
162 * @param string $fieldName
164 * @param array $params
166 protected function assignTestFK($fieldName, $fieldDef, $params) {
167 $required = CRM_Utils_Array
::value('required', $fieldDef);
168 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
169 $dbName = $fieldDef['name'];
170 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
172 // skip the FK if it is not required
173 // if it's contact id we should create even if not required
174 // we'll have a go @ fetching first though
175 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
176 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
179 if (!$required && $dbName != 'contact_id') {
180 $fkDAO = new $FKClassName();
181 if ($fkDAO->find(TRUE)) {
182 $this->$dbName = $fkDAO->id
;
187 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
188 $depObject = new $FKClassName();
189 $depObject->find(TRUE);
190 $this->$dbName = $depObject->id
;
193 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
194 // FIXME: the fields() metadata is not specific enough
195 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
196 $this->$dbName = $depObject->id
;
200 //if it is required we need to generate the dependency object first
201 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
202 $this->$dbName = $depObject->id
;
208 * Generate and assign an arbitrary value to a field of a test object.
210 * @param string $fieldName
211 * @param array $fieldDef
212 * @param int $counter
213 * The globally-unique ID of the test object.
215 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
216 $dbName = $fieldDef['name'];
217 $daoName = get_class($this);
220 if (!$handled && $dbName == 'contact_sub_type') {
221 //coming up with a rule to set this is too complex let's not set it
225 // Pick an option value if needed
226 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
227 $options = $daoName::buildOptions($dbName, 'create');
229 $this->$dbName = key($options);
235 switch ($fieldDef['type']) {
236 case CRM_Utils_Type
::T_INT
:
237 case CRM_Utils_Type
::T_FLOAT
:
238 case CRM_Utils_Type
::T_MONEY
:
239 if (isset($fieldDef['precision'])) {
240 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
241 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
244 $this->$dbName = $counter;
248 case CRM_Utils_Type
::T_BOOLEAN
:
249 if (isset($fieldDef['default'])) {
250 $this->$dbName = $fieldDef['default'];
252 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
260 case CRM_Utils_Type
::T_DATE
:
261 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
262 $this->$dbName = '19700101';
263 if ($dbName == 'end_date') {
264 // put this in the future
265 $this->$dbName = '20200101';
269 case CRM_Utils_Type
::T_TIMESTAMP
:
270 $this->$dbName = '19700201000000';
273 case CRM_Utils_Type
::T_TIME
:
274 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
275 //$object->$dbName='000000';
277 case CRM_Utils_Type
::T_CCNUM
:
278 $this->$dbName = '4111 1111 1111 1111';
281 case CRM_Utils_Type
::T_URL
:
282 $this->$dbName = 'http://www.civicrm.org';
285 case CRM_Utils_Type
::T_STRING
:
286 case CRM_Utils_Type
::T_BLOB
:
287 case CRM_Utils_Type
::T_MEDIUMBLOB
:
288 case CRM_Utils_Type
::T_TEXT
:
289 case CRM_Utils_Type
::T_LONGTEXT
:
290 case CRM_Utils_Type
::T_EMAIL
:
292 // WAS: if (isset($value['enumValues'])) {
293 // TODO: see if this works with all pseudoconstants
294 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
295 if (isset($fieldDef['default'])) {
296 $this->$dbName = $fieldDef['default'];
299 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
300 if (is_array($options)) {
301 $this->$dbName = $options[0];
304 $defaultValues = explode(',', $options);
305 $this->$dbName = $defaultValues[0];
310 $this->$dbName = $dbName . '_' . $counter;
311 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
312 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
313 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
321 * Reset the DAO object.
323 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
325 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
327 public function reset() {
329 foreach (array_keys($this->table()) as $field) {
330 unset($this->$field);
334 * reset the various DB_DAO structures manually
336 $this->_query
= array();
343 * @param string $tableName
347 public static function getLocaleTableName($tableName) {
350 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
351 if (in_array($tableName, $tables)) {
352 return $tableName . $dbLocale;
359 * Execute a query by the current DAO, localizing it along the way (if needed).
361 * @param string $query
362 * The SQL query for execution.
363 * @param bool $i18nRewrite
364 * Whether to rewrite the query.
367 * the current DAO object after the query execution
369 public function query($query, $i18nRewrite = TRUE) {
370 // rewrite queries that should use $dbLocale-based views for multi-language installs
371 global $dbLocale, $_DB_DATAOBJECT;
373 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
374 // Will force connection to be populated per CRM-20541.
378 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
379 $orig_options = $conn->options
;
380 $this->_setDBOptions($this->_options
);
382 if ($i18nRewrite and $dbLocale) {
383 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
386 $ret = parent
::query($query);
388 $this->_setDBOptions($orig_options);
393 * Static function to set the factory instance for this class.
395 * @param object $factory
396 * The factory application object.
398 public static function setFactory(&$factory) {
399 self
::$_factory = &$factory;
403 * Factory method to instantiate a new object from a table name.
405 * @param string $table
407 public function factory($table = '') {
408 if (!isset(self
::$_factory)) {
409 return parent
::factory($table);
412 return self
::$_factory->create($table);
416 * Initialization for all DAO objects. Since we access DB_DO programatically
417 * we need to set the links manually.
419 public function initialize() {
421 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
422 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
423 // This occurs very early in bootstrap - error handlers may not be wired up.
424 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
425 CRM_Utils_System
::civiExit();
430 * Defines the default key as 'id'.
435 public function keys() {
444 * Tells DB_DataObject which keys use autoincrement.
445 * 'id' is autoincrementing by default.
450 public function sequenceKey() {
451 static $sequenceKeys;
452 if (!isset($sequenceKeys)) {
453 $sequenceKeys = array('id', TRUE);
455 return $sequenceKeys;
459 * Returns list of FK relationships.
463 * Array of CRM_Core_Reference_Interface
465 public static function getReferenceColumns() {
470 * Returns all the column names of this table.
475 public static function &fields() {
481 * Get/set an associative array of table columns
486 public function table() {
487 $fields = &$this->fields();
491 foreach ($fields as $name => $value) {
492 $table[$value['name']] = $value['type'];
493 if (!empty($value['required'])) {
494 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
507 * @return CRM_Core_DAO
509 public function save($hook = TRUE) {
510 if (!empty($this->id
)) {
514 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
515 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
522 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
523 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
529 CRM_Utils_Hook
::postSave($this);
536 * Deletes items from table which match current objects variables.
538 * Returns the true on success
542 * Designed to be extended
544 * $object = new mytable();
546 * echo $object->delete(); // builds a conditon
548 * $object = new mytable();
549 * $object->whereAdd('age > 12');
551 * $object->orderBy('age DESC');
552 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
554 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
555 * we will build the condition only using the whereAdd's. Default is to
556 * build the condition only using the object parameters.
558 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
560 public function delete($useWhere = FALSE) {
561 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
562 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
564 $result = parent
::delete($useWhere);
566 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
567 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
574 * @param bool $created
576 public function log($created = FALSE) {
579 if (!$this->getLog()) {
584 $session = CRM_Core_Session
::singleton();
585 $cid = $session->get('userID');
588 // return is we dont have handle to FK
593 $dao = new CRM_Core_DAO_Log();
594 $dao->entity_table
= $this->getTableName();
595 $dao->entity_id
= $this->id
;
596 $dao->modified_id
= $cid;
597 $dao->modified_date
= date("YmdHis");
602 * Given an associative array of name/value pairs, extract all the values
603 * that belong to this object and initialize the object with said values
605 * @param array $params
606 * (reference ) associative array of name/value pairs.
609 * Did we copy all null values into the object
611 public function copyValues(&$params) {
612 $fields = &$this->fields();
614 foreach ($fields as $name => $value) {
615 $dbName = $value['name'];
616 if (array_key_exists($dbName, $params)) {
617 $pValue = $params[$dbName];
620 elseif (array_key_exists($name, $params)) {
621 $pValue = $params[$name];
628 // if there is no value then make the variable NULL
630 if ($pValue === '') {
631 $this->$dbName = 'null';
634 $this->$dbName = $pValue;
643 * Store all the values from this object in an associative array
644 * this is a destructive store, calling function is responsible
645 * for keeping sanity of id's.
647 * @param object $object
648 * The object that we are extracting data from.
649 * @param array $values
650 * (reference ) associative array of name/value pairs.
652 public static function storeValues(&$object, &$values) {
653 $fields = &$object->fields();
654 foreach ($fields as $name => $value) {
655 $dbName = $value['name'];
656 if (isset($object->$dbName) && $object->$dbName !== 'null') {
657 $values[$dbName] = $object->$dbName;
658 if ($name != $dbName) {
659 $values[$name] = $object->$dbName;
666 * Create an attribute for this specific field. We only do this for strings and text
668 * @param array $field
669 * The field under task.
672 * the attributes for the object
674 public static function makeAttribute($field) {
676 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
677 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
678 $size = CRM_Utils_Array
::value('size', $field);
679 if ($maxLength ||
$size) {
680 $attributes = array();
682 $attributes['maxlength'] = $maxLength;
685 $attributes['size'] = $size;
690 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
691 $rows = CRM_Utils_Array
::value('rows', $field);
695 $cols = CRM_Utils_Array
::value('cols', $field);
700 $attributes = array();
701 $attributes['rows'] = $rows;
702 $attributes['cols'] = $cols;
705 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
) {
706 $attributes['size'] = 6;
707 $attributes['maxlength'] = 14;
715 * Get the size and maxLength attributes for this text field.
716 * (or for all text fields) in the DAO object.
718 * @param string $class
720 * @param string $fieldName
721 * Field that i'm interested in or null if.
722 * you want the attributes for all DAO text fields
725 * assoc array of name => attribute pairs
727 public static function getAttribute($class, $fieldName = NULL) {
728 $object = new $class();
729 $fields = &$object->fields();
730 if ($fieldName != NULL) {
731 $field = CRM_Utils_Array
::value($fieldName, $fields);
732 return self
::makeAttribute($field);
735 $attributes = array();
736 foreach ($fields as $name => $field) {
737 $attribute = self
::makeAttribute($field);
739 $attributes[$name] = $attribute;
743 if (!empty($attributes)) {
755 public static function transaction($type) {
756 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
760 * Check if there is a record with the same name in the db.
762 * @param string $value
763 * The value of the field we are checking.
764 * @param string $daoName
765 * The dao object name.
766 * @param string $daoID
767 * The id of the object being updated. u can change your name.
768 * as long as there is no conflict
769 * @param string $fieldName
770 * The name of the field in the DAO.
772 * @param string $domainID
773 * The id of the domain. Object exists only for the given domain.
776 * true if object exists
778 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
779 $object = new $daoName();
780 $object->$fieldName = $value;
782 $object->domain_id
= $domainID;
785 if ($object->find(TRUE)) {
786 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
794 * Check if there is a given column in a specific table.
796 * @param string $tableName
797 * @param string $columnName
798 * @param bool $i18nRewrite
799 * Whether to rewrite the query on multilingual setups.
802 * true if exists, else false
804 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
810 $params = array(1 => array($columnName, 'String'));
811 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
812 $result = $dao->fetch() ?
TRUE : FALSE;
818 * Scans all the tables using a slow query and table name.
822 public static function getTableNames() {
823 $dao = CRM_Core_DAO
::executeQuery(
825 FROM information_schema.TABLES
826 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
827 AND TABLE_NAME LIKE 'civicrm_%'
828 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
829 AND TABLE_NAME NOT LIKE '%_temp%'
832 while ($dao->fetch()) {
833 $values[] = $dao->TABLE_NAME
;
840 * @param int $maxTablesToCheck
844 public static function isDBMyISAM($maxTablesToCheck = 10) {
845 return CRM_Core_DAO
::singleValueQuery(
847 FROM information_schema.TABLES
848 WHERE ENGINE = 'MyISAM'
849 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
850 AND TABLE_NAME LIKE 'civicrm_%'
851 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
852 AND TABLE_NAME NOT LIKE '%_temp%'
857 * Get the name of the CiviCRM database.
861 public static function getDatabaseName() {
862 $daoObj = new CRM_Core_DAO();
863 return $daoObj->database();
867 * Checks if a constraint exists for a specified table.
869 * @param string $tableName
870 * @param string $constraint
873 * true if constraint exists, false otherwise
875 public static function checkConstraintExists($tableName, $constraint) {
876 static $show = array();
878 if (!array_key_exists($tableName, $show)) {
879 $query = "SHOW CREATE TABLE $tableName";
880 $dao = CRM_Core_DAO
::executeQuery($query);
882 if (!$dao->fetch()) {
883 CRM_Core_Error
::fatal();
887 $show[$tableName] = $dao->Create_Table
;
890 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
894 * Checks if CONSTRAINT keyword exists for a specified table.
896 * @param array $tables
901 * true if CONSTRAINT keyword exists, false otherwise
903 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
905 foreach ($tables as $tableName) {
906 if (!array_key_exists($tableName, $show)) {
907 $query = "SHOW CREATE TABLE $tableName";
908 $dao = CRM_Core_DAO
::executeQuery($query);
910 if (!$dao->fetch()) {
911 CRM_Core_Error
::fatal();
915 $show[$tableName] = $dao->Create_Table
;
918 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
919 if ($result == TRUE) {
930 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
931 * for a specified column of a table.
933 * @param string $tableName
934 * @param string $columnName
937 * true if in format, false otherwise
939 public static function checkFKConstraintInFormat($tableName, $columnName) {
940 static $show = array();
942 if (!array_key_exists($tableName, $show)) {
943 $query = "SHOW CREATE TABLE $tableName";
944 $dao = CRM_Core_DAO
::executeQuery($query);
946 if (!$dao->fetch()) {
947 CRM_Core_Error
::fatal();
951 $show[$tableName] = $dao->Create_Table
;
953 $constraint = "`FK_{$tableName}_{$columnName}`";
954 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
955 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
959 * Check whether a specific column in a specific table has always the same value.
961 * @param string $tableName
962 * @param string $columnName
963 * @param string $columnValue
966 * true if the value is always $columnValue, false otherwise
968 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
969 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
970 $dao = CRM_Core_DAO
::executeQuery($query);
971 $result = $dao->fetch() ?
FALSE : TRUE;
977 * Check whether a specific column in a specific table is always NULL.
979 * @param string $tableName
980 * @param string $columnName
983 * true if if the value is always NULL, false otherwise
985 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
986 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
987 $dao = CRM_Core_DAO
::executeQuery($query);
988 $result = $dao->fetch() ?
FALSE : TRUE;
994 * Check if there is a given table in the database.
996 * @param string $tableName
999 * true if exists, else false
1001 public static function checkTableExists($tableName) {
1006 $params = array(1 => array($tableName, 'String'));
1008 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1009 $result = $dao->fetch() ?
TRUE : FALSE;
1019 public function checkVersion($version) {
1024 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1025 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1029 * Find a DAO object for the given ID and return it.
1032 * Id of the DAO object being searched for.
1035 * Object of the type of the class that called this function.
1037 public static function findById($id) {
1038 $object = new static();
1040 if (!$object->find(TRUE)) {
1041 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1047 * Returns all results as array-encoded records.
1051 public function fetchAll() {
1053 while ($this->fetch()) {
1054 $result[] = $this->toArray();
1060 * Returns a singular value.
1062 * @return mixed|NULL
1064 public function fetchValue() {
1065 $result = $this->getDatabaseResult();
1066 $row = $result->fetchRow();
1076 * Get all the result records as mapping between columns.
1078 * @param string $keyColumn
1080 * @param string $valueColumn
1083 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1085 public function fetchMap($keyColumn, $valueColumn) {
1087 while ($this->fetch()) {
1088 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1094 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1096 * @param string $daoName
1097 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1098 * @param int $searchValue
1099 * Value of the column you want to search by.
1100 * @param string $returnColumn
1101 * Name of the column you want to GET the value of.
1102 * @param string $searchColumn
1103 * Name of the column you want to search by.
1104 * @param bool $force
1105 * Skip use of the cache.
1107 * @return string|null
1108 * Value of $returnColumn in the retrieved record
1110 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1112 empty($searchValue) ||
1113 trim(strtolower($searchValue)) == 'null'
1115 // adding this here since developers forget to check for an id
1116 // or for the 'null' (which is a bad DAO kludge)
1117 // and hence we get the first value in the db
1118 CRM_Core_Error
::fatal();
1121 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1122 if (self
::$_dbColumnValueCache === NULL) {
1123 self
::$_dbColumnValueCache = array();
1126 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1127 $object = new $daoName();
1128 $object->$searchColumn = $searchValue;
1129 $object->selectAdd();
1130 $object->selectAdd($returnColumn);
1133 if ($object->find(TRUE)) {
1134 $result = $object->$returnColumn;
1138 self
::$_dbColumnValueCache[$cacheKey] = $result;
1140 return self
::$_dbColumnValueCache[$cacheKey];
1144 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1146 * @param string $daoName
1147 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1148 * @param int $searchValue
1149 * Value of the column you want to search by.
1150 * @param string $setColumn
1151 * Name of the column you want to SET the value of.
1152 * @param string $setValue
1153 * SET the setColumn to this value.
1154 * @param string $searchColumn
1155 * Name of the column you want to search by.
1158 * true if we found and updated the object, else false
1160 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1161 $object = new $daoName();
1162 $object->selectAdd();
1163 $object->selectAdd("$searchColumn, $setColumn");
1164 $object->$searchColumn = $searchValue;
1166 if ($object->find(TRUE)) {
1167 $object->$setColumn = $setValue;
1168 if ($object->save()) {
1179 * @param array|object $sort either array or CRM_Utils_Sort
1180 * @param string $default
1181 * Default sort value.
1186 public static function getSortString($sort, $default = NULL) {
1187 // check if sort is of type CRM_Utils_Sort
1188 if (is_a($sort, 'CRM_Utils_Sort')) {
1189 return $sort->orderBy();
1192 // is it an array specified as $field => $sortDirection ?
1194 foreach ($sort as $k => $v) {
1195 $sortString .= "$k $v,";
1197 return rtrim($sortString, ',');
1203 * Fetch object based on array of properties.
1205 * @param string $daoName
1206 * Name of the dao object.
1207 * @param array $params
1208 * (reference ) an assoc array of name/value pairs.
1209 * @param array $defaults
1210 * (reference ) an assoc array to hold the flattened values.
1211 * @param array $returnProperities
1212 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1215 * an object of type referenced by daoName
1217 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1218 $object = new $daoName();
1219 $object->copyValues($params);
1221 // return only specific fields if returnproperties are sent
1222 if (!empty($returnProperities)) {
1223 $object->selectAdd();
1224 $object->selectAdd(implode(',', $returnProperities));
1227 if ($object->find(TRUE)) {
1228 self
::storeValues($object, $defaults);
1235 * Delete the object records that are associated with this contact.
1237 * @param string $daoName
1238 * Name of the dao object.
1239 * @param int $contactId
1240 * Id of the contact to delete.
1242 public static function deleteEntityContact($daoName, $contactId) {
1243 $object = new $daoName();
1245 $object->entity_table
= 'civicrm_contact';
1246 $object->entity_id
= $contactId;
1251 * Execute an unbuffered query.
1253 * This is a wrapper around new functionality exposed with CRM-17748.
1255 * @param string $query query to be executed
1257 * @param array $params
1258 * @param bool $abort
1259 * @param null $daoName
1260 * @param bool $freeDAO
1261 * @param bool $i18nRewrite
1262 * @param bool $trapException
1264 * @return CRM_Core_DAO
1265 * Object that points to an unbuffered result set
1267 static public function executeUnbufferedQuery(
1273 $i18nRewrite = TRUE,
1274 $trapException = FALSE
1277 return self
::executeQuery(
1285 array('result_buffering' => 0)
1292 * @param string $query
1293 * Query to be executed.
1295 * @param array $params
1296 * @param bool $abort
1297 * @param null $daoName
1298 * @param bool $freeDAO
1299 * @param bool $i18nRewrite
1300 * @param bool $trapException
1301 * @param array $options
1303 * @return CRM_Core_DAO|object
1304 * object that holds the results of the query
1305 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1306 * out all the properties that are not part of the DAO
1308 public static function &executeQuery(
1314 $i18nRewrite = TRUE,
1315 $trapException = FALSE,
1318 $queryStr = self
::composeQuery($query, $params, $abort);
1321 $dao = new CRM_Core_DAO();
1324 $dao = new $daoName();
1327 if ($trapException) {
1328 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1331 if ($dao->isValidOption($options)) {
1332 $dao->setOptions($options);
1335 $result = $dao->query($queryStr, $i18nRewrite);
1337 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1338 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1342 if (is_a($result, 'DB_Error')) {
1347 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1349 // we typically do this for insert/update/delete statements OR if explicitly asked to
1357 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1359 * @param array $options
1362 * Provided options are valid
1364 public function isValidOption($options) {
1366 $validOptions = array(
1373 if (empty($options)) {
1377 foreach (array_keys($options) as $option) {
1378 if (!in_array($option, $validOptions)) {
1388 * Execute a query and get the single result.
1390 * @param string $query
1391 * Query to be executed.
1392 * @param array $params
1393 * @param bool $abort
1394 * @param bool $i18nRewrite
1395 * @return string|null
1396 * the result of the query if any
1399 public static function &singleValueQuery(
1405 $queryStr = self
::composeQuery($query, $params, $abort);
1407 static $_dao = NULL;
1410 $_dao = new CRM_Core_DAO();
1413 $_dao->query($queryStr, $i18nRewrite);
1415 $result = $_dao->getDatabaseResult();
1418 $row = $result->fetchRow();
1428 * Compose the query by merging the parameters into it.
1430 * @param string $query
1431 * @param array $params
1432 * @param bool $abort
1437 public static function composeQuery($query, $params, $abort = TRUE) {
1439 foreach ($params as $key => $item) {
1440 if (is_numeric($key)) {
1441 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1442 $item[0] = self
::escapeString($item[0]);
1443 if ($item[1] == 'String' ||
1444 $item[1] == 'Memo' ||
1447 // Support class constants stipulating wildcard characters and/or
1448 // non-quoting of strings. Also support legacy code which may be
1449 // passing in TRUE or 1 for $item[2], which used to indicate the
1450 // use of wildcard characters.
1451 if (!empty($item[2])) {
1452 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1453 $item[0] = "'%{$item[0]}%'";
1455 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1456 $item[0] = "'{$item[0]}'";
1460 $item[0] = "'{$item[0]}'";
1464 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1465 strlen($item[0]) == 0
1470 $tr['%' . $key] = $item[0];
1473 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1478 return strtr($query, $tr);
1484 public static function freeResult($ids = NULL) {
1485 global $_DB_DATAOBJECT;
1488 if (!$_DB_DATAOBJECT ||
1489 !isset($_DB_DATAOBJECT['RESULTS'])
1493 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1496 foreach ($ids as $id) {
1497 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1498 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1499 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1502 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1503 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1509 * make a shallow copy of an object.
1510 * and all the fields in the object
1512 * @param string $daoName
1514 * @param array $criteria
1515 * Array of all the fields & values.
1516 * on which basis to copy
1517 * @param array $newData
1518 * Array of all the fields & values.
1519 * to be copied besides the other fields
1520 * @param string $fieldsFix
1521 * Array of fields that you want to prefix/suffix/replace.
1522 * @param string $blockCopyOfDependencies
1523 * Fields that you want to block from.
1527 * @return CRM_Core_DAO
1528 * the newly created copy of the object
1530 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1531 $object = new $daoName();
1533 $object->id
= $criteria['id'];
1536 foreach ($criteria as $key => $value) {
1537 $object->$key = $value;
1542 while ($object->fetch()) {
1544 // all the objects except with $blockCopyOfDependencies set
1545 // be copied - addresses #CRM-1962
1547 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1551 $newObject = new $daoName();
1553 $fields = &$object->fields();
1554 if (!is_array($fieldsFix)) {
1555 $fieldsToPrefix = array();
1556 $fieldsToSuffix = array();
1557 $fieldsToReplace = array();
1559 if (!empty($fieldsFix['prefix'])) {
1560 $fieldsToPrefix = $fieldsFix['prefix'];
1562 if (!empty($fieldsFix['suffix'])) {
1563 $fieldsToSuffix = $fieldsFix['suffix'];
1565 if (!empty($fieldsFix['replace'])) {
1566 $fieldsToReplace = $fieldsFix['replace'];
1569 foreach ($fields as $name => $value) {
1570 if ($name == 'id' ||
$value['name'] == 'id') {
1571 // copy everything but the id!
1575 $dbName = $value['name'];
1576 $type = CRM_Utils_Type
::typeToString($value['type']);
1577 $newObject->$dbName = $object->$dbName;
1578 if (isset($fieldsToPrefix[$dbName])) {
1579 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1581 if (isset($fieldsToSuffix[$dbName])) {
1582 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1584 if (isset($fieldsToReplace[$dbName])) {
1585 $newObject->$dbName = $fieldsToReplace[$dbName];
1588 if ($type == 'Timestamp' ||
$type == 'Date') {
1589 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1593 foreach ($newData as $k => $v) {
1594 $newObject->$k = $v;
1604 * Cascade update through related entities.
1606 * @param string $daoName
1609 * @param array $newData
1611 * @return CRM_Core_DAO|null
1613 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1614 $object = new $daoName();
1615 $object->id
= $fromId;
1617 if ($object->find(TRUE)) {
1618 $newObject = new $daoName();
1619 $newObject->id
= $toId;
1621 if ($newObject->find(TRUE)) {
1622 $fields = &$object->fields();
1623 foreach ($fields as $name => $value) {
1624 if ($name == 'id' ||
$value['name'] == 'id') {
1625 // copy everything but the id!
1629 $colName = $value['name'];
1630 $newObject->$colName = $object->$colName;
1632 if (substr($name, -5) == '_date' ||
1633 substr($name, -10) == '_date_time'
1635 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1638 foreach ($newData as $k => $v) {
1639 $newObject->$k = $v;
1649 * Given the component id, compute the contact id
1650 * since its used for things like send email
1652 * @param $componentIDs
1653 * @param string $tableName
1657 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1658 $contactIDs = array();
1660 if (empty($componentIDs)) {
1664 $IDs = implode(',', $componentIDs);
1668 WHERE id IN ( $IDs )
1671 $dao = CRM_Core_DAO
::executeQuery($query);
1672 while ($dao->fetch()) {
1673 $contactIDs[] = $dao->contact_id
;
1679 * Fetch object based on array of properties.
1681 * @param string $daoName
1682 * Name of the dao object.
1683 * @param string $fieldIdName
1684 * @param int $fieldId
1686 * @param array $returnProperities
1687 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1690 * an object of type referenced by daoName
1692 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1693 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1694 $object = new $daoName();
1695 $object->$fieldIdName = $fieldId;
1697 // return only specific fields if returnproperties are sent
1698 if (!empty($returnProperities)) {
1699 $object->selectAdd();
1700 $object->selectAdd('id');
1701 $object->selectAdd(implode(',', $returnProperities));
1705 while ($object->fetch()) {
1706 $defaults = array();
1707 self
::storeValues($object, $defaults);
1708 $details[$object->id
] = $defaults;
1714 public static function dropAllTables() {
1716 // first drop all the custom tables we've created
1717 CRM_Core_BAO_CustomGroup
::dropAllTables();
1719 // drop all multilingual views
1720 CRM_Core_I18n_Schema
::dropAllViews();
1722 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1723 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1724 '..' . DIRECTORY_SEPARATOR
.
1725 '..' . DIRECTORY_SEPARATOR
.
1726 'sql' . DIRECTORY_SEPARATOR
.
1727 'civicrm_drop.mysql'
1736 public static function escapeString($string) {
1737 static $_dao = NULL;
1739 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1740 // has been installed), then we fallback DB-less str_replace escaping, as
1741 // we can't use mysqli_real_escape_string, as there is no DB connection.
1742 // Note: In typical usage, escapeString() will only check one conditional
1743 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1744 if (!defined('CIVICRM_DSN')) {
1745 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1746 // list of characters mysqli_real_escape_string escapes.
1747 $search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
1748 $replace = array("\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z");
1749 return str_replace($search, $replace, $string);
1751 $_dao = new CRM_Core_DAO();
1753 return $_dao->escape($string);
1757 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1759 * @param array $strings
1760 * @param string $default
1761 * the value to use if $strings has no elements.
1763 * eg "abc","def","ghi"
1765 public static function escapeStrings($strings, $default = NULL) {
1766 static $_dao = NULL;
1768 $_dao = new CRM_Core_DAO();
1771 if (empty($strings)) {
1775 $escapes = array_map(array($_dao, 'escape'), $strings);
1776 return '"' . implode('","', $escapes) . '"';
1784 public static function escapeWildCardString($string) {
1786 // ensure we escape the single characters % and _ which are mysql wild
1787 // card characters and could come in via sortByCharacter
1788 // note that mysql does not escape these characters
1789 if ($string && in_array($string,
1790 array('%', '_', '%%', '_%')
1793 return '\\' . $string;
1796 return self
::escapeString($string);
1800 * Creates a test object, including any required objects it needs via recursion
1801 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1802 * ONLY USE FOR TESTING
1804 * @param string $daoName
1805 * @param array $params
1806 * @param int $numObjects
1807 * @param bool $createOnly
1809 * @return object|array|NULL
1810 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1812 public static function createTestObject(
1818 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1819 // so we re-set here in case
1820 $config = CRM_Core_Config
::singleton();
1821 $config->backtrace
= TRUE;
1823 static $counter = 0;
1824 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1825 'CRM_Core_DAO_Worldregion',
1826 'CRM_Core_DAO_StateProvince',
1827 'CRM_Core_DAO_Country',
1828 'CRM_Core_DAO_Domain',
1829 'CRM_Financial_DAO_FinancialType',
1830 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1833 // Prefer to instantiate BAO's instead of DAO's (when possible)
1834 // so that assignTestValue()/assignTestFK() can be overloaded.
1835 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1836 if (class_exists($baoName)) {
1837 $daoName = $baoName;
1840 for ($i = 0; $i < $numObjects; ++
$i) {
1843 /** @var CRM_Core_DAO $object */
1844 $object = new $daoName();
1846 $fields = &$object->fields();
1847 foreach ($fields as $fieldName => $fieldDef) {
1848 $dbName = $fieldDef['name'];
1849 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1850 $required = CRM_Utils_Array
::value('required', $fieldDef);
1852 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1853 $object->$dbName = $params[$dbName];
1856 elseif ($dbName != 'id') {
1857 if ($FKClassName != NULL) {
1858 $object->assignTestFK($fieldName, $fieldDef, $params);
1862 $object->assignTestValue($fieldName, $fieldDef, $counter);
1870 $objects[$i] = $object;
1880 elseif ($numObjects == 1) {
1889 * Deletes the this object plus any dependent objects that are associated with it.
1890 * ONLY USE FOR TESTING
1892 * @param string $daoName
1893 * @param array $params
1895 public static function deleteTestObjects($daoName, $params = array()) {
1896 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1897 // so we re-set here in case
1898 $config = CRM_Core_Config
::singleton();
1899 $config->backtrace
= TRUE;
1901 $object = new $daoName();
1902 $object->id
= CRM_Utils_Array
::value('id', $params);
1904 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1905 if ($object->find(TRUE)) {
1907 $fields = &$object->fields();
1908 foreach ($fields as $name => $value) {
1910 $dbName = $value['name'];
1912 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1913 $required = CRM_Utils_Array
::value('required', $value);
1914 if ($FKClassName != NULL
1916 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1917 && ($required ||
$dbName == 'contact_id')
1918 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1919 // to make this test process pass - line below makes pass for now
1920 && $dbName != 'member_of_contact_id'
1922 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1929 foreach ($deletions as $deletion) {
1930 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1935 * Set defaults when creating new entity.
1936 * (don't call this set defaults as already in use with different signature in some places)
1938 * @param array $params
1941 public static function setCreateDefaults(&$params, $defaults) {
1942 if (!empty($params['id'])) {
1945 foreach ($defaults as $key => $value) {
1946 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1947 $params[$key] = $value;
1953 * @param string $prefix
1954 * @param bool $addRandomString
1955 * @param null $string
1959 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1960 $tableName = $prefix . "_temp";
1962 if ($addRandomString) {
1964 $tableName .= "_" . $string;
1967 $tableName .= "_" . md5(uniqid('', TRUE));
1975 * @param bool $trigger
1979 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1980 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
1983 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1985 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1986 CRM_Core_TemporaryErrorScope
::ignoreException();
1987 $dao = new CRM_Core_DAO();
1989 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1990 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1996 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1997 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1999 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2004 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2005 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2007 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2014 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2015 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2024 * @param null $message
2025 * @param bool $printDAO
2027 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2028 CRM_Utils_System
::xMemory("{$message}: ");
2031 global $_DB_DATAOBJECT;
2033 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2034 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2036 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2041 * Build a list of triggers via hook and add them to (err, reconcile them
2042 * with) the database.
2044 * @param string $tableName
2045 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2046 * @param bool $force
2051 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2052 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2056 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2057 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2058 * TODO: Alternative solutions might be
2059 * * Stop using functions and find another way to strip numeric characters from phones
2060 * * Give better error messages (currently a missing fn fatals with "unknown error")
2062 public static function checkSqlFunctionsExist() {
2063 if (!self
::$_checkedSqlFunctionsExist) {
2064 self
::$_checkedSqlFunctionsExist = TRUE;
2065 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2066 if (!$dao->fetch()) {
2067 self
::triggerRebuild();
2073 * Wrapper function to drop triggers.
2075 * @param string $tableName
2076 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2079 public static function dropTriggers($tableName = NULL) {
2080 Civi
::service('sql_triggers')->dropTriggers($tableName);
2084 * @param array $info
2085 * per hook_civicrm_triggerInfo.
2086 * @param string $onlyTableName
2087 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2090 public static function createTriggers(&$info, $onlyTableName = NULL) {
2091 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2095 * Given a list of fields, create a list of references.
2097 * @param string $className
2098 * BAO/DAO class name.
2099 * @return array<CRM_Core_Reference_Interface>
2101 public static function createReferenceColumns($className) {
2103 $fields = $className::fields();
2104 foreach ($fields as $field) {
2105 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2106 $result[] = new CRM_Core_Reference_OptionValue(
2107 $className::getTableName(),
2109 'civicrm_option_value',
2110 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2111 $field['pseudoconstant']['optionGroupName']
2119 * Find all records which refer to this entity.
2122 * Array of objects referencing this
2124 public function findReferences() {
2125 $links = self
::getReferencesToTable(static::getTableName());
2127 $occurrences = array();
2128 foreach ($links as $refSpec) {
2129 /** @var $refSpec CRM_Core_Reference_Interface */
2130 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2131 $result = $refSpec->findReferences($this);
2133 while ($result->fetch()) {
2134 $obj = new $daoName();
2135 $obj->id
= $result->id
;
2136 $occurrences[] = $obj;
2141 return $occurrences;
2146 * each item has keys:
2150 * - table: string|null SQL table name
2151 * - key: string|null SQL column name
2153 public function getReferenceCounts() {
2154 $links = self
::getReferencesToTable(static::getTableName());
2157 foreach ($links as $refSpec) {
2158 /** @var $refSpec CRM_Core_Reference_Interface */
2159 $count = $refSpec->getReferenceCount($this);
2160 if ($count['count'] != 0) {
2165 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2166 /** @var $component CRM_Core_Component_Info */
2167 $counts = array_merge($counts, $component->getReferenceCounts($this));
2169 CRM_Utils_Hook
::referenceCounts($this, $counts);
2175 * List all tables which have hard foreign keys to this table.
2177 * For now, this returns a description of every entity_id/entity_table
2179 * TODO: filter dynamic entity references on the $tableName, based on
2180 * schema metadata in dynamicForeignKey which enumerates a restricted
2181 * set of possible entity_table's.
2183 * @param string $tableName
2184 * Table referred to.
2187 * structure of table and column, listing every table with a
2188 * foreign key reference to $tableName, and the column where the key appears.
2190 public static function getReferencesToTable($tableName) {
2191 $refsFound = array();
2192 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2193 $links = $daoClassName::getReferenceColumns();
2194 $daoTableName = $daoClassName::getTableName();
2196 foreach ($links as $refSpec) {
2197 /** @var $refSpec CRM_Core_Reference_Interface */
2198 if ($refSpec->matchesTargetTable($tableName)) {
2199 $refsFound[] = $refSpec;
2207 * Lookup the value of a MySQL global configuration variable.
2209 * @param string $name
2210 * E.g. "thread_stack".
2211 * @param mixed $default
2214 public static function getGlobalSetting($name, $default = NULL) {
2215 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2216 // that has been reported to fail under MySQL 5.0 for OS X
2217 $escapedName = self
::escapeString($name);
2218 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2219 if ($dao->fetch()) {
2229 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2231 * This is relevant where we want to offer both the ID field and the label field
2232 * as an option, e.g. search builder.
2234 * It is currently limited for optionGroupName for purposes keeping the scope of the
2235 * change small, but is appropriate for other sorts of pseudoconstants.
2237 * @param array $fields
2239 protected static function appendPseudoConstantsToFields(&$fields) {
2240 foreach ($fields as $field) {
2241 if (!empty($field['pseudoconstant']) && !empty($field['pseudoconstant']['optionGroupName'])) {
2242 $fields[$field['pseudoconstant']['optionGroupName']] = array(
2243 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($field['pseudoconstant']['optionGroupName']),
2244 'name' => $field['pseudoconstant']['optionGroupName'],
2245 'data_type' => CRM_Utils_Type
::T_STRING
,
2252 * Get options for the called BAO object's field.
2254 * This function can be overridden by each BAO to add more logic related to context.
2255 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2257 * @param string $fieldName
2258 * @param string $context
2259 * @see CRM_Core_DAO::buildOptionsContext
2260 * @param array $props
2261 * whatever is known about this bao object.
2263 * @return array|bool
2265 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2266 // If a given bao does not override this function
2267 $baoName = get_called_class();
2268 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2272 * Populate option labels for this object's fields.
2274 * @throws exception if called directly on the base class
2276 public function getOptionLabels() {
2277 $fields = $this->fields();
2278 if ($fields === NULL) {
2279 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2281 foreach ($fields as $field) {
2282 $name = CRM_Utils_Array
::value('name', $field);
2283 if ($name && isset($this->$name)) {
2284 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2285 if ($label !== FALSE) {
2286 // Append 'label' onto the field name
2287 $labelName = $name . '_label';
2288 $this->$labelName = $label;
2295 * Provides documentation and validation for the buildOptions $context param
2297 * @param string $context
2302 public static function buildOptionsContext($context = NULL) {
2304 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2305 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2306 'search' => "search: searchable options are returned; labels are translated.",
2307 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2308 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2309 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2311 // Validation: enforce uniformity of this param
2312 if ($context !== NULL && !isset($contexts[$context])) {
2313 throw new Exception("'$context' is not a valid context for buildOptions.");
2319 * @param string $fieldName
2320 * @return bool|array
2322 public function getFieldSpec($fieldName) {
2323 $fields = $this->fields();
2324 $fieldKeys = $this->fieldKeys();
2326 // Support "unique names" as well as sql names
2327 $fieldKey = $fieldName;
2328 if (empty($fields[$fieldKey])) {
2329 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2331 // If neither worked then this field doesn't exist. Return false.
2332 if (empty($fields[$fieldKey])) {
2335 return $fields[$fieldKey];
2339 * Get SQL where clause for SQL filter syntax input parameters.
2341 * SQL version of api function to assign filters to the DAO based on the syntax
2342 * $field => array('IN' => array(4,6,9))
2344 * $field => array('LIKE' => array('%me%))
2347 * @param string $fieldName
2349 * @param array $filter
2350 * filter to be applied indexed by operator.
2351 * @param string $type
2352 * type of field (not actually used - nor in api @todo ).
2353 * @param string $alias
2354 * alternative field name ('as') @todo- not actually used.
2355 * @param bool $returnSanitisedArray
2356 * Return a sanitised array instead of a clause.
2357 * this is primarily so we can add filters @ the api level to the Query object based fields
2361 * @return NULL|string|array
2362 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2363 * depending on whether it is supported as yet
2365 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2366 foreach ($filter as $operator => $criteria) {
2367 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2368 switch ($operator) {
2372 if (!$returnSanitisedArray) {
2373 return (sprintf('%s %s', $fieldName, $operator));
2376 return (sprintf('%s %s ', $fieldName, $operator));
2380 // ternary operators
2383 if (empty($criteria[0]) ||
empty($criteria[1])) {
2384 throw new Exception("invalid criteria for $operator");
2386 if (!$returnSanitisedArray) {
2387 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2390 return NULL; // not yet implemented (tests required to implement)
2397 if (empty($criteria)) {
2398 throw new Exception("invalid criteria for $operator");
2400 $escapedCriteria = array_map(array(
2404 if (!$returnSanitisedArray) {
2405 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2407 return $escapedCriteria;
2412 if (!$returnSanitisedArray) {
2413 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2416 return NULL; // not yet implemented (tests required to implement)
2424 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2425 * support for other syntaxes is discussed in ticket but being put off for now
2428 public static function acceptedSQLOperators() {
2449 * SQL has a limit of 64 characters on various names:
2450 * table name, trigger name, column name ...
2452 * For custom groups and fields we generated names from user entered input
2453 * which can be longer than this length, this function helps with creating
2454 * strings that meet various criteria.
2456 * @param string $string
2457 * The string to be shortened.
2458 * @param int $length
2459 * The max length of the string.
2461 * @param bool $makeRandom
2465 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2466 // early return for strings that meet the requirements
2467 if (strlen($string) <= $length) {
2471 // easy return for calls that dont need a randomized uniq string
2473 return substr($string, 0, $length);
2476 // the string is longer than the length and we need a uniq string
2477 // for the same tablename we need the same uniq string every time
2478 // hence we use md5 on the string, which is not random
2479 // we'll append 8 characters to the end of the tableName
2480 $md5string = substr(md5($string), 0, 8);
2481 return substr($string, 0, $length - 8) . "_{$md5string}";
2485 * https://issues.civicrm.org/jira/browse/CRM-17748
2486 * Sets the internal options to be used on a query
2488 * @param array $options
2491 public function setOptions($options) {
2492 if (is_array($options)) {
2493 $this->_options
= $options;
2498 * https://issues.civicrm.org/jira/browse/CRM-17748
2499 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2501 * @param array $options
2504 protected function _setDBOptions($options) {
2505 global $_DB_DATAOBJECT;
2507 if (is_array($options) && count($options)) {
2508 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2509 foreach ($options as $option_name => $option_value) {
2510 $conn->setOption($option_name, $option_value);
2517 * @param array $params
2519 public function setApiFilter(&$params) {
2523 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2525 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2528 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2532 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2536 public function addSelectWhereClause() {
2538 $fields = $this->fields();
2539 foreach ($fields as $fieldName => $field) {
2540 // Clause for contact-related entities like Email, Relationship, etc.
2541 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2542 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2544 // Clause for an entity_table/entity_id combo
2545 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2546 $relatedClauses = array();
2547 $relatedEntities = $this->buildOptions('entity_table', 'get');
2548 foreach ((array) $relatedEntities as $table => $ent) {
2550 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2551 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2553 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2556 $relatedClauses[] = "(entity_table = '$table')";
2560 if ($relatedClauses) {
2561 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2565 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2570 * This returns the final permissioned query string for this entity
2572 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2574 * @param string $tableAlias
2577 public static function getSelectWhereClause($tableAlias = NULL) {
2578 $bao = new static();
2579 if ($tableAlias === NULL) {
2580 $tableAlias = $bao->tableName();
2583 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2584 $clauses[$field] = NULL;
2586 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2593 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2594 * and dashes, and contains at least one [a-z] case insenstive.
2600 public static function requireSafeDBName($database) {
2603 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2607 if (empty($matches)) {
2614 * Transform an array to a serialized string for database storage.
2616 * @param array|NULL $value
2617 * @param $serializationType
2618 * @return string|NULL
2620 public static function serializeField($value, $serializationType) {
2621 if ($value === NULL) {
2624 switch ($serializationType) {
2625 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2626 return $value === array() ?
'' : CRM_Utils_Array
::implodePadded($value);
2628 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2629 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2631 case self
::SERIALIZE_JSON
:
2632 return is_array($value) ?
json_encode($value) : $value;
2634 case self
::SERIALIZE_PHP
:
2635 return is_array($value) ?
serialize($value) : $value;
2640 * Transform a serialized string from the database into an array.
2642 * @param string|null $value
2643 * @param $serializationType
2644 * @return array|null
2646 public static function unSerializeField($value, $serializationType) {
2647 if ($value === NULL) {
2650 if ($value === '') {
2653 switch ($serializationType) {
2654 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2655 return (array) CRM_Utils_Array
::explodePadded($value);
2657 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2658 return explode(self
::VALUE_SEPARATOR
, trim($value));
2660 case self
::SERIALIZE_JSON
:
2661 return strlen($value) ?
json_decode($value, TRUE) : array();
2663 case self
::SERIALIZE_PHP
:
2664 return strlen($value) ?
unserialize($value) : array();