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 * Define entities that shouldn't be created or deleted when creating/ deleting
71 * test objects - this prevents world regions, countries etc from being added / deleted
74 static $_testEntitiesToSkip = array();
76 * The factory class for this application.
79 static $_factory = NULL;
81 static $_checkedSqlFunctionsExist = FALSE;
84 * https://issues.civicrm.org/jira/browse/CRM-17748
85 * internal variable for DAO to hold per-query settings
87 protected $_options = array();
92 * @return \CRM_Core_DAO
94 public function __construct() {
96 $this->__table
= $this->getTableName();
100 * Empty definition for virtual function.
102 public static function getTableName() {
107 * Initialize the DAO object.
110 * The database connection string.
112 public static function init($dsn) {
113 Civi
::$statics[__CLASS__
]['init'] = 1;
114 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
115 $options['database'] = $dsn;
116 if (defined('CIVICRM_DAO_DEBUG')) {
117 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
119 $factory = new CRM_Contact_DAO_Factory();
120 CRM_Core_DAO
::setFactory($factory);
121 $currentModes = CRM_Utils_SQL
::getSqlModes();
122 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
123 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
124 $currentModes[] = 'ONLY_FULL_GROUP_BY';
126 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
127 $currentModes = array_merge(array('STRICT_TRANS_TABLES'), $currentModes);
129 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", array(1 => array(implode(',', $currentModes), 'String')));
131 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
132 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request
::id(), 'String')));
138 public static function getConnection() {
139 global $_DB_DATAOBJECT;
140 $dao = new CRM_Core_DAO();
141 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
145 * @param string $fieldName
147 * @param array $params
149 protected function assignTestFK($fieldName, $fieldDef, $params) {
150 $required = CRM_Utils_Array
::value('required', $fieldDef);
151 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
152 $dbName = $fieldDef['name'];
153 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
155 // skip the FK if it is not required
156 // if it's contact id we should create even if not required
157 // we'll have a go @ fetching first though
158 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
159 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
162 if (!$required && $dbName != 'contact_id') {
163 $fkDAO = new $FKClassName();
164 if ($fkDAO->find(TRUE)) {
165 $this->$dbName = $fkDAO->id
;
170 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
171 $depObject = new $FKClassName();
172 $depObject->find(TRUE);
173 $this->$dbName = $depObject->id
;
176 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
177 // FIXME: the fields() metadata is not specific enough
178 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
179 $this->$dbName = $depObject->id
;
183 //if it is required we need to generate the dependency object first
184 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
185 $this->$dbName = $depObject->id
;
191 * Generate and assign an arbitrary value to a field of a test object.
193 * @param string $fieldName
194 * @param array $fieldDef
195 * @param int $counter
196 * The globally-unique ID of the test object.
198 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
199 $dbName = $fieldDef['name'];
200 $daoName = get_class($this);
203 if (!$handled && $dbName == 'contact_sub_type') {
204 //coming up with a rule to set this is too complex let's not set it
208 // Pick an option value if needed
209 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
210 $options = $daoName::buildOptions($dbName, 'create');
212 $this->$dbName = key($options);
218 switch ($fieldDef['type']) {
219 case CRM_Utils_Type
::T_INT
:
220 case CRM_Utils_Type
::T_FLOAT
:
221 case CRM_Utils_Type
::T_MONEY
:
222 if (isset($fieldDef['precision'])) {
223 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
224 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
227 $this->$dbName = $counter;
231 case CRM_Utils_Type
::T_BOOLEAN
:
232 if (isset($fieldDef['default'])) {
233 $this->$dbName = $fieldDef['default'];
235 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
243 case CRM_Utils_Type
::T_DATE
:
244 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
245 $this->$dbName = '19700101';
246 if ($dbName == 'end_date') {
247 // put this in the future
248 $this->$dbName = '20200101';
252 case CRM_Utils_Type
::T_TIMESTAMP
:
253 $this->$dbName = '19700201000000';
256 case CRM_Utils_Type
::T_TIME
:
257 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
258 //$object->$dbName='000000';
260 case CRM_Utils_Type
::T_CCNUM
:
261 $this->$dbName = '4111 1111 1111 1111';
264 case CRM_Utils_Type
::T_URL
:
265 $this->$dbName = 'http://www.civicrm.org';
268 case CRM_Utils_Type
::T_STRING
:
269 case CRM_Utils_Type
::T_BLOB
:
270 case CRM_Utils_Type
::T_MEDIUMBLOB
:
271 case CRM_Utils_Type
::T_TEXT
:
272 case CRM_Utils_Type
::T_LONGTEXT
:
273 case CRM_Utils_Type
::T_EMAIL
:
275 // WAS: if (isset($value['enumValues'])) {
276 // TODO: see if this works with all pseudoconstants
277 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
278 if (isset($fieldDef['default'])) {
279 $this->$dbName = $fieldDef['default'];
282 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
283 if (is_array($options)) {
284 $this->$dbName = $options[0];
287 $defaultValues = explode(',', $options);
288 $this->$dbName = $defaultValues[0];
293 $this->$dbName = $dbName . '_' . $counter;
294 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
295 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
296 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
304 * Reset the DAO object.
306 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
308 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
310 public function reset() {
312 foreach (array_keys($this->table()) as $field) {
313 unset($this->$field);
317 * reset the various DB_DAO structures manually
319 $this->_query
= array();
326 * @param string $tableName
330 public static function getLocaleTableName($tableName) {
333 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
334 if (in_array($tableName, $tables)) {
335 return $tableName . $dbLocale;
342 * Execute a query by the current DAO, localizing it along the way (if needed).
344 * @param string $query
345 * The SQL query for execution.
346 * @param bool $i18nRewrite
347 * Whether to rewrite the query.
350 * the current DAO object after the query execution
352 public function query($query, $i18nRewrite = TRUE) {
353 // rewrite queries that should use $dbLocale-based views for multi-language installs
354 global $dbLocale, $_DB_DATAOBJECT;
356 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
357 // Will force connection to be populated per CRM-20541.
361 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
362 $orig_options = $conn->options
;
363 $this->_setDBOptions($this->_options
);
365 if ($i18nRewrite and $dbLocale) {
366 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
369 $ret = parent
::query($query);
371 $this->_setDBOptions($orig_options);
376 * Static function to set the factory instance for this class.
378 * @param object $factory
379 * The factory application object.
381 public static function setFactory(&$factory) {
382 self
::$_factory = &$factory;
386 * Factory method to instantiate a new object from a table name.
388 * @param string $table
390 public function factory($table = '') {
391 if (!isset(self
::$_factory)) {
392 return parent
::factory($table);
395 return self
::$_factory->create($table);
399 * Initialization for all DAO objects. Since we access DB_DO programatically
400 * we need to set the links manually.
402 public function initialize() {
404 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
405 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
406 // This occurs very early in bootstrap - error handlers may not be wired up.
407 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
408 CRM_Utils_System
::civiExit();
413 * Defines the default key as 'id'.
418 public function keys() {
427 * Tells DB_DataObject which keys use autoincrement.
428 * 'id' is autoincrementing by default.
433 public function sequenceKey() {
434 static $sequenceKeys;
435 if (!isset($sequenceKeys)) {
436 $sequenceKeys = array('id', TRUE);
438 return $sequenceKeys;
442 * Returns list of FK relationships.
446 * Array of CRM_Core_Reference_Interface
448 public static function getReferenceColumns() {
453 * Returns all the column names of this table.
458 public static function &fields() {
464 * Get/set an associative array of table columns
469 public function table() {
470 $fields = &$this->fields();
474 foreach ($fields as $name => $value) {
475 $table[$value['name']] = $value['type'];
476 if (!empty($value['required'])) {
477 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
490 * @return CRM_Core_DAO
492 public function save($hook = TRUE) {
493 if (!empty($this->id
)) {
497 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
498 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
505 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
506 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
512 CRM_Utils_Hook
::postSave($this);
519 * Deletes items from table which match current objects variables.
521 * Returns the true on success
525 * Designed to be extended
527 * $object = new mytable();
529 * echo $object->delete(); // builds a conditon
531 * $object = new mytable();
532 * $object->whereAdd('age > 12');
534 * $object->orderBy('age DESC');
535 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
537 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
538 * we will build the condition only using the whereAdd's. Default is to
539 * build the condition only using the object parameters.
541 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
543 public function delete($useWhere = FALSE) {
544 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
545 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
547 $result = parent
::delete($useWhere);
549 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
550 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
557 * @param bool $created
559 public function log($created = FALSE) {
562 if (!$this->getLog()) {
567 $session = CRM_Core_Session
::singleton();
568 $cid = $session->get('userID');
571 // return is we dont have handle to FK
576 $dao = new CRM_Core_DAO_Log();
577 $dao->entity_table
= $this->getTableName();
578 $dao->entity_id
= $this->id
;
579 $dao->modified_id
= $cid;
580 $dao->modified_date
= date("YmdHis");
585 * Given an associative array of name/value pairs, extract all the values
586 * that belong to this object and initialize the object with said values
588 * @param array $params
589 * (reference ) associative array of name/value pairs.
592 * Did we copy all null values into the object
594 public function copyValues(&$params) {
595 $fields = &$this->fields();
597 foreach ($fields as $name => $value) {
598 $dbName = $value['name'];
599 if (array_key_exists($dbName, $params)) {
600 $pValue = $params[$dbName];
603 elseif (array_key_exists($name, $params)) {
604 $pValue = $params[$name];
611 // if there is no value then make the variable NULL
613 if ($pValue === '') {
614 $this->$dbName = 'null';
617 $this->$dbName = $pValue;
626 * Store all the values from this object in an associative array
627 * this is a destructive store, calling function is responsible
628 * for keeping sanity of id's.
630 * @param object $object
631 * The object that we are extracting data from.
632 * @param array $values
633 * (reference ) associative array of name/value pairs.
635 public static function storeValues(&$object, &$values) {
636 $fields = &$object->fields();
637 foreach ($fields as $name => $value) {
638 $dbName = $value['name'];
639 if (isset($object->$dbName) && $object->$dbName !== 'null') {
640 $values[$dbName] = $object->$dbName;
641 if ($name != $dbName) {
642 $values[$name] = $object->$dbName;
649 * Create an attribute for this specific field. We only do this for strings and text
651 * @param array $field
652 * The field under task.
655 * the attributes for the object
657 public static function makeAttribute($field) {
659 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
660 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
661 $size = CRM_Utils_Array
::value('size', $field);
662 if ($maxLength ||
$size) {
663 $attributes = array();
665 $attributes['maxlength'] = $maxLength;
668 $attributes['size'] = $size;
673 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
674 $rows = CRM_Utils_Array
::value('rows', $field);
678 $cols = CRM_Utils_Array
::value('cols', $field);
683 $attributes = array();
684 $attributes['rows'] = $rows;
685 $attributes['cols'] = $cols;
688 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
) {
689 $attributes['size'] = 6;
690 $attributes['maxlength'] = 14;
698 * Get the size and maxLength attributes for this text field.
699 * (or for all text fields) in the DAO object.
701 * @param string $class
703 * @param string $fieldName
704 * Field that i'm interested in or null if.
705 * you want the attributes for all DAO text fields
708 * assoc array of name => attribute pairs
710 public static function getAttribute($class, $fieldName = NULL) {
711 $object = new $class();
712 $fields = &$object->fields();
713 if ($fieldName != NULL) {
714 $field = CRM_Utils_Array
::value($fieldName, $fields);
715 return self
::makeAttribute($field);
718 $attributes = array();
719 foreach ($fields as $name => $field) {
720 $attribute = self
::makeAttribute($field);
722 $attributes[$name] = $attribute;
726 if (!empty($attributes)) {
738 public static function transaction($type) {
739 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
743 * Check if there is a record with the same name in the db.
745 * @param string $value
746 * The value of the field we are checking.
747 * @param string $daoName
748 * The dao object name.
749 * @param string $daoID
750 * The id of the object being updated. u can change your name.
751 * as long as there is no conflict
752 * @param string $fieldName
753 * The name of the field in the DAO.
755 * @param string $domainID
756 * The id of the domain. Object exists only for the given domain.
759 * true if object exists
761 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
762 $object = new $daoName();
763 $object->$fieldName = $value;
765 $object->domain_id
= $domainID;
768 if ($object->find(TRUE)) {
769 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
777 * Check if there is a given column in a specific table.
779 * @param string $tableName
780 * @param string $columnName
781 * @param bool $i18nRewrite
782 * Whether to rewrite the query on multilingual setups.
785 * true if exists, else false
787 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
793 $params = array(1 => array($columnName, 'String'));
794 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
795 $result = $dao->fetch() ?
TRUE : FALSE;
801 * Scans all the tables using a slow query and table name.
805 public static function getTableNames() {
806 $dao = CRM_Core_DAO
::executeQuery(
808 FROM information_schema.TABLES
809 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
810 AND TABLE_NAME LIKE 'civicrm_%'
811 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
812 AND TABLE_NAME NOT LIKE '%_temp%'
815 while ($dao->fetch()) {
816 $values[] = $dao->TABLE_NAME
;
823 * @param int $maxTablesToCheck
827 public static function isDBMyISAM($maxTablesToCheck = 10) {
828 return CRM_Core_DAO
::singleValueQuery(
830 FROM information_schema.TABLES
831 WHERE ENGINE = 'MyISAM'
832 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
833 AND TABLE_NAME LIKE 'civicrm_%'
834 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
835 AND TABLE_NAME NOT LIKE '%_temp%'
840 * Get the name of the CiviCRM database.
844 public static function getDatabaseName() {
845 $daoObj = new CRM_Core_DAO();
846 return $daoObj->database();
850 * Checks if a constraint exists for a specified table.
852 * @param string $tableName
853 * @param string $constraint
856 * true if constraint exists, false otherwise
858 public static function checkConstraintExists($tableName, $constraint) {
859 static $show = array();
861 if (!array_key_exists($tableName, $show)) {
862 $query = "SHOW CREATE TABLE $tableName";
863 $dao = CRM_Core_DAO
::executeQuery($query);
865 if (!$dao->fetch()) {
866 CRM_Core_Error
::fatal();
870 $show[$tableName] = $dao->Create_Table
;
873 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
877 * Checks if CONSTRAINT keyword exists for a specified table.
879 * @param array $tables
884 * true if CONSTRAINT keyword exists, false otherwise
886 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
888 foreach ($tables as $tableName) {
889 if (!array_key_exists($tableName, $show)) {
890 $query = "SHOW CREATE TABLE $tableName";
891 $dao = CRM_Core_DAO
::executeQuery($query);
893 if (!$dao->fetch()) {
894 CRM_Core_Error
::fatal();
898 $show[$tableName] = $dao->Create_Table
;
901 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
902 if ($result == TRUE) {
913 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
914 * for a specified column of a table.
916 * @param string $tableName
917 * @param string $columnName
920 * true if in format, false otherwise
922 public static function checkFKConstraintInFormat($tableName, $columnName) {
923 static $show = array();
925 if (!array_key_exists($tableName, $show)) {
926 $query = "SHOW CREATE TABLE $tableName";
927 $dao = CRM_Core_DAO
::executeQuery($query);
929 if (!$dao->fetch()) {
930 CRM_Core_Error
::fatal();
934 $show[$tableName] = $dao->Create_Table
;
936 $constraint = "`FK_{$tableName}_{$columnName}`";
937 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
938 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
942 * Check whether a specific column in a specific table has always the same value.
944 * @param string $tableName
945 * @param string $columnName
946 * @param string $columnValue
949 * true if the value is always $columnValue, false otherwise
951 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
952 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
953 $dao = CRM_Core_DAO
::executeQuery($query);
954 $result = $dao->fetch() ?
FALSE : TRUE;
960 * Check whether a specific column in a specific table is always NULL.
962 * @param string $tableName
963 * @param string $columnName
966 * true if if the value is always NULL, false otherwise
968 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
969 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
970 $dao = CRM_Core_DAO
::executeQuery($query);
971 $result = $dao->fetch() ?
FALSE : TRUE;
977 * Check if there is a given table in the database.
979 * @param string $tableName
982 * true if exists, else false
984 public static function checkTableExists($tableName) {
989 $params = array(1 => array($tableName, 'String'));
991 $dao = CRM_Core_DAO
::executeQuery($query, $params);
992 $result = $dao->fetch() ?
TRUE : FALSE;
1002 public function checkVersion($version) {
1007 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1008 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1012 * Find a DAO object for the given ID and return it.
1015 * Id of the DAO object being searched for.
1018 * Object of the type of the class that called this function.
1020 public static function findById($id) {
1021 $object = new static();
1023 if (!$object->find(TRUE)) {
1024 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1030 * Returns all results as array-encoded records.
1034 public function fetchAll() {
1036 while ($this->fetch()) {
1037 $result[] = $this->toArray();
1043 * Returns a singular value.
1045 * @return mixed|NULL
1047 public function fetchValue() {
1048 $result = $this->getDatabaseResult();
1049 $row = $result->fetchRow();
1059 * Get all the result records as mapping between columns.
1061 * @param string $keyColumn
1063 * @param string $valueColumn
1066 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1068 public function fetchMap($keyColumn, $valueColumn) {
1070 while ($this->fetch()) {
1071 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1077 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1079 * @param string $daoName
1080 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1081 * @param int $searchValue
1082 * Value of the column you want to search by.
1083 * @param string $returnColumn
1084 * Name of the column you want to GET the value of.
1085 * @param string $searchColumn
1086 * Name of the column you want to search by.
1087 * @param bool $force
1088 * Skip use of the cache.
1090 * @return string|null
1091 * Value of $returnColumn in the retrieved record
1093 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1095 empty($searchValue) ||
1096 trim(strtolower($searchValue)) == 'null'
1098 // adding this here since developers forget to check for an id
1099 // or for the 'null' (which is a bad DAO kludge)
1100 // and hence we get the first value in the db
1101 CRM_Core_Error
::fatal();
1104 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1105 if (self
::$_dbColumnValueCache === NULL) {
1106 self
::$_dbColumnValueCache = array();
1109 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1110 $object = new $daoName();
1111 $object->$searchColumn = $searchValue;
1112 $object->selectAdd();
1113 $object->selectAdd($returnColumn);
1116 if ($object->find(TRUE)) {
1117 $result = $object->$returnColumn;
1121 self
::$_dbColumnValueCache[$cacheKey] = $result;
1123 return self
::$_dbColumnValueCache[$cacheKey];
1127 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1129 * @param string $daoName
1130 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1131 * @param int $searchValue
1132 * Value of the column you want to search by.
1133 * @param string $setColumn
1134 * Name of the column you want to SET the value of.
1135 * @param string $setValue
1136 * SET the setColumn to this value.
1137 * @param string $searchColumn
1138 * Name of the column you want to search by.
1141 * true if we found and updated the object, else false
1143 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1144 $object = new $daoName();
1145 $object->selectAdd();
1146 $object->selectAdd("$searchColumn, $setColumn");
1147 $object->$searchColumn = $searchValue;
1149 if ($object->find(TRUE)) {
1150 $object->$setColumn = $setValue;
1151 if ($object->save()) {
1162 * @param array|object $sort either array or CRM_Utils_Sort
1163 * @param string $default
1164 * Default sort value.
1169 public static function getSortString($sort, $default = NULL) {
1170 // check if sort is of type CRM_Utils_Sort
1171 if (is_a($sort, 'CRM_Utils_Sort')) {
1172 return $sort->orderBy();
1175 // is it an array specified as $field => $sortDirection ?
1177 foreach ($sort as $k => $v) {
1178 $sortString .= "$k $v,";
1180 return rtrim($sortString, ',');
1186 * Fetch object based on array of properties.
1188 * @param string $daoName
1189 * Name of the dao object.
1190 * @param array $params
1191 * (reference ) an assoc array of name/value pairs.
1192 * @param array $defaults
1193 * (reference ) an assoc array to hold the flattened values.
1194 * @param array $returnProperities
1195 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1198 * an object of type referenced by daoName
1200 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1201 $object = new $daoName();
1202 $object->copyValues($params);
1204 // return only specific fields if returnproperties are sent
1205 if (!empty($returnProperities)) {
1206 $object->selectAdd();
1207 $object->selectAdd(implode(',', $returnProperities));
1210 if ($object->find(TRUE)) {
1211 self
::storeValues($object, $defaults);
1218 * Delete the object records that are associated with this contact.
1220 * @param string $daoName
1221 * Name of the dao object.
1222 * @param int $contactId
1223 * Id of the contact to delete.
1225 public static function deleteEntityContact($daoName, $contactId) {
1226 $object = new $daoName();
1228 $object->entity_table
= 'civicrm_contact';
1229 $object->entity_id
= $contactId;
1234 * Execute an unbuffered query.
1236 * This is a wrapper around new functionality exposed with CRM-17748.
1238 * @param string $query query to be executed
1240 * @param array $params
1241 * @param bool $abort
1242 * @param null $daoName
1243 * @param bool $freeDAO
1244 * @param bool $i18nRewrite
1245 * @param bool $trapException
1247 * @return CRM_Core_DAO
1248 * Object that points to an unbuffered result set
1250 static public function executeUnbufferedQuery(
1256 $i18nRewrite = TRUE,
1257 $trapException = FALSE
1260 return self
::executeQuery(
1268 array('result_buffering' => 0)
1275 * @param string $query
1276 * Query to be executed.
1278 * @param array $params
1279 * @param bool $abort
1280 * @param null $daoName
1281 * @param bool $freeDAO
1282 * @param bool $i18nRewrite
1283 * @param bool $trapException
1284 * @param array $options
1286 * @return CRM_Core_DAO|object
1287 * object that holds the results of the query
1288 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1289 * out all the properties that are not part of the DAO
1291 public static function &executeQuery(
1297 $i18nRewrite = TRUE,
1298 $trapException = FALSE,
1301 $queryStr = self
::composeQuery($query, $params, $abort);
1304 $dao = new CRM_Core_DAO();
1307 $dao = new $daoName();
1310 if ($trapException) {
1311 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1314 if ($dao->isValidOption($options)) {
1315 $dao->setOptions($options);
1318 $result = $dao->query($queryStr, $i18nRewrite);
1320 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1321 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1325 if (is_a($result, 'DB_Error')) {
1330 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1332 // we typically do this for insert/update/delete statements OR if explicitly asked to
1340 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1342 * @param array $options
1345 * Provided options are valid
1347 public function isValidOption($options) {
1349 $validOptions = array(
1356 if (empty($options)) {
1360 foreach (array_keys($options) as $option) {
1361 if (!in_array($option, $validOptions)) {
1371 * Execute a query and get the single result.
1373 * @param string $query
1374 * Query to be executed.
1375 * @param array $params
1376 * @param bool $abort
1377 * @param bool $i18nRewrite
1378 * @return string|null
1379 * the result of the query if any
1382 public static function &singleValueQuery(
1388 $queryStr = self
::composeQuery($query, $params, $abort);
1390 static $_dao = NULL;
1393 $_dao = new CRM_Core_DAO();
1396 $_dao->query($queryStr, $i18nRewrite);
1398 $result = $_dao->getDatabaseResult();
1401 $row = $result->fetchRow();
1411 * Compose the query by merging the parameters into it.
1413 * @param string $query
1414 * @param array $params
1415 * @param bool $abort
1420 public static function composeQuery($query, $params, $abort = TRUE) {
1422 foreach ($params as $key => $item) {
1423 if (is_numeric($key)) {
1424 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1425 $item[0] = self
::escapeString($item[0]);
1426 if ($item[1] == 'String' ||
1427 $item[1] == 'Memo' ||
1430 // Support class constants stipulating wildcard characters and/or
1431 // non-quoting of strings. Also support legacy code which may be
1432 // passing in TRUE or 1 for $item[2], which used to indicate the
1433 // use of wildcard characters.
1434 if (!empty($item[2])) {
1435 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1436 $item[0] = "'%{$item[0]}%'";
1438 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1439 $item[0] = "'{$item[0]}'";
1443 $item[0] = "'{$item[0]}'";
1447 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1448 strlen($item[0]) == 0
1453 $tr['%' . $key] = $item[0];
1456 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1461 return strtr($query, $tr);
1467 public static function freeResult($ids = NULL) {
1468 global $_DB_DATAOBJECT;
1471 if (!$_DB_DATAOBJECT ||
1472 !isset($_DB_DATAOBJECT['RESULTS'])
1476 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1479 foreach ($ids as $id) {
1480 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1481 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1482 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1485 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1486 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1492 * make a shallow copy of an object.
1493 * and all the fields in the object
1495 * @param string $daoName
1497 * @param array $criteria
1498 * Array of all the fields & values.
1499 * on which basis to copy
1500 * @param array $newData
1501 * Array of all the fields & values.
1502 * to be copied besides the other fields
1503 * @param string $fieldsFix
1504 * Array of fields that you want to prefix/suffix/replace.
1505 * @param string $blockCopyOfDependencies
1506 * Fields that you want to block from.
1510 * @return CRM_Core_DAO
1511 * the newly created copy of the object
1513 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1514 $object = new $daoName();
1516 $object->id
= $criteria['id'];
1519 foreach ($criteria as $key => $value) {
1520 $object->$key = $value;
1525 while ($object->fetch()) {
1527 // all the objects except with $blockCopyOfDependencies set
1528 // be copied - addresses #CRM-1962
1530 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1534 $newObject = new $daoName();
1536 $fields = &$object->fields();
1537 if (!is_array($fieldsFix)) {
1538 $fieldsToPrefix = array();
1539 $fieldsToSuffix = array();
1540 $fieldsToReplace = array();
1542 if (!empty($fieldsFix['prefix'])) {
1543 $fieldsToPrefix = $fieldsFix['prefix'];
1545 if (!empty($fieldsFix['suffix'])) {
1546 $fieldsToSuffix = $fieldsFix['suffix'];
1548 if (!empty($fieldsFix['replace'])) {
1549 $fieldsToReplace = $fieldsFix['replace'];
1552 foreach ($fields as $name => $value) {
1553 if ($name == 'id' ||
$value['name'] == 'id') {
1554 // copy everything but the id!
1558 $dbName = $value['name'];
1559 $type = CRM_Utils_Type
::typeToString($value['type']);
1560 $newObject->$dbName = $object->$dbName;
1561 if (isset($fieldsToPrefix[$dbName])) {
1562 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1564 if (isset($fieldsToSuffix[$dbName])) {
1565 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1567 if (isset($fieldsToReplace[$dbName])) {
1568 $newObject->$dbName = $fieldsToReplace[$dbName];
1571 if ($type == 'Timestamp' ||
$type == 'Date') {
1572 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1576 foreach ($newData as $k => $v) {
1577 $newObject->$k = $v;
1587 * Cascade update through related entities.
1589 * @param string $daoName
1592 * @param array $newData
1594 * @return CRM_Core_DAO|null
1596 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1597 $object = new $daoName();
1598 $object->id
= $fromId;
1600 if ($object->find(TRUE)) {
1601 $newObject = new $daoName();
1602 $newObject->id
= $toId;
1604 if ($newObject->find(TRUE)) {
1605 $fields = &$object->fields();
1606 foreach ($fields as $name => $value) {
1607 if ($name == 'id' ||
$value['name'] == 'id') {
1608 // copy everything but the id!
1612 $colName = $value['name'];
1613 $newObject->$colName = $object->$colName;
1615 if (substr($name, -5) == '_date' ||
1616 substr($name, -10) == '_date_time'
1618 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1621 foreach ($newData as $k => $v) {
1622 $newObject->$k = $v;
1632 * Given the component id, compute the contact id
1633 * since its used for things like send email
1635 * @param $componentIDs
1636 * @param string $tableName
1640 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1641 $contactIDs = array();
1643 if (empty($componentIDs)) {
1647 $IDs = implode(',', $componentIDs);
1651 WHERE id IN ( $IDs )
1654 $dao = CRM_Core_DAO
::executeQuery($query);
1655 while ($dao->fetch()) {
1656 $contactIDs[] = $dao->contact_id
;
1662 * Fetch object based on array of properties.
1664 * @param string $daoName
1665 * Name of the dao object.
1666 * @param string $fieldIdName
1667 * @param int $fieldId
1669 * @param array $returnProperities
1670 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1673 * an object of type referenced by daoName
1675 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1676 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1677 $object = new $daoName();
1678 $object->$fieldIdName = $fieldId;
1680 // return only specific fields if returnproperties are sent
1681 if (!empty($returnProperities)) {
1682 $object->selectAdd();
1683 $object->selectAdd('id');
1684 $object->selectAdd(implode(',', $returnProperities));
1688 while ($object->fetch()) {
1689 $defaults = array();
1690 self
::storeValues($object, $defaults);
1691 $details[$object->id
] = $defaults;
1697 public static function dropAllTables() {
1699 // first drop all the custom tables we've created
1700 CRM_Core_BAO_CustomGroup
::dropAllTables();
1702 // drop all multilingual views
1703 CRM_Core_I18n_Schema
::dropAllViews();
1705 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1706 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1707 '..' . DIRECTORY_SEPARATOR
.
1708 '..' . DIRECTORY_SEPARATOR
.
1709 'sql' . DIRECTORY_SEPARATOR
.
1710 'civicrm_drop.mysql'
1719 public static function escapeString($string) {
1720 static $_dao = NULL;
1722 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1723 // has been installed), then we fallback DB-less str_replace escaping, as
1724 // we can't use mysqli_real_escape_string, as there is no DB connection.
1725 // Note: In typical usage, escapeString() will only check one conditional
1726 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1727 if (!defined('CIVICRM_DSN')) {
1728 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1729 // list of characters mysqli_real_escape_string escapes.
1730 $search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
1731 $replace = array("\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z");
1732 return str_replace($search, $replace, $string);
1734 $_dao = new CRM_Core_DAO();
1736 return $_dao->escape($string);
1740 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1742 * @param array $strings
1743 * @param string $default
1744 * the value to use if $strings has no elements.
1746 * eg "abc","def","ghi"
1748 public static function escapeStrings($strings, $default = NULL) {
1749 static $_dao = NULL;
1751 $_dao = new CRM_Core_DAO();
1754 if (empty($strings)) {
1758 $escapes = array_map(array($_dao, 'escape'), $strings);
1759 return '"' . implode('","', $escapes) . '"';
1767 public static function escapeWildCardString($string) {
1769 // ensure we escape the single characters % and _ which are mysql wild
1770 // card characters and could come in via sortByCharacter
1771 // note that mysql does not escape these characters
1772 if ($string && in_array($string,
1773 array('%', '_', '%%', '_%')
1776 return '\\' . $string;
1779 return self
::escapeString($string);
1783 * Creates a test object, including any required objects it needs via recursion
1784 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1785 * ONLY USE FOR TESTING
1787 * @param string $daoName
1788 * @param array $params
1789 * @param int $numObjects
1790 * @param bool $createOnly
1792 * @return object|array|NULL
1793 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1795 public static function createTestObject(
1801 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1802 // so we re-set here in case
1803 $config = CRM_Core_Config
::singleton();
1804 $config->backtrace
= TRUE;
1806 static $counter = 0;
1807 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1808 'CRM_Core_DAO_Worldregion',
1809 'CRM_Core_DAO_StateProvince',
1810 'CRM_Core_DAO_Country',
1811 'CRM_Core_DAO_Domain',
1812 'CRM_Financial_DAO_FinancialType',
1813 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1816 // Prefer to instantiate BAO's instead of DAO's (when possible)
1817 // so that assignTestValue()/assignTestFK() can be overloaded.
1818 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1819 if (class_exists($baoName)) {
1820 $daoName = $baoName;
1823 for ($i = 0; $i < $numObjects; ++
$i) {
1826 /** @var CRM_Core_DAO $object */
1827 $object = new $daoName();
1829 $fields = &$object->fields();
1830 foreach ($fields as $fieldName => $fieldDef) {
1831 $dbName = $fieldDef['name'];
1832 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1833 $required = CRM_Utils_Array
::value('required', $fieldDef);
1835 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1836 $object->$dbName = $params[$dbName];
1839 elseif ($dbName != 'id') {
1840 if ($FKClassName != NULL) {
1841 $object->assignTestFK($fieldName, $fieldDef, $params);
1845 $object->assignTestValue($fieldName, $fieldDef, $counter);
1853 $objects[$i] = $object;
1863 elseif ($numObjects == 1) {
1872 * Deletes the this object plus any dependent objects that are associated with it.
1873 * ONLY USE FOR TESTING
1875 * @param string $daoName
1876 * @param array $params
1878 public static function deleteTestObjects($daoName, $params = array()) {
1879 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1880 // so we re-set here in case
1881 $config = CRM_Core_Config
::singleton();
1882 $config->backtrace
= TRUE;
1884 $object = new $daoName();
1885 $object->id
= CRM_Utils_Array
::value('id', $params);
1887 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1888 if ($object->find(TRUE)) {
1890 $fields = &$object->fields();
1891 foreach ($fields as $name => $value) {
1893 $dbName = $value['name'];
1895 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1896 $required = CRM_Utils_Array
::value('required', $value);
1897 if ($FKClassName != NULL
1899 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1900 && ($required ||
$dbName == 'contact_id')
1901 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1902 // to make this test process pass - line below makes pass for now
1903 && $dbName != 'member_of_contact_id'
1905 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1912 foreach ($deletions as $deletion) {
1913 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1918 * Set defaults when creating new entity.
1919 * (don't call this set defaults as already in use with different signature in some places)
1921 * @param array $params
1924 public static function setCreateDefaults(&$params, $defaults) {
1925 if (!empty($params['id'])) {
1928 foreach ($defaults as $key => $value) {
1929 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1930 $params[$key] = $value;
1936 * @param string $prefix
1937 * @param bool $addRandomString
1938 * @param null $string
1942 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1943 $tableName = $prefix . "_temp";
1945 if ($addRandomString) {
1947 $tableName .= "_" . $string;
1950 $tableName .= "_" . md5(uniqid('', TRUE));
1958 * @param bool $trigger
1962 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1963 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
1966 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1968 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1969 CRM_Core_TemporaryErrorScope
::ignoreException();
1970 $dao = new CRM_Core_DAO();
1972 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1973 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1979 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1980 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1982 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1987 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1988 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1990 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1997 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1998 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2007 * @param null $message
2008 * @param bool $printDAO
2010 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2011 CRM_Utils_System
::xMemory("{$message}: ");
2014 global $_DB_DATAOBJECT;
2016 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2017 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2019 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2024 * Build a list of triggers via hook and add them to (err, reconcile them
2025 * with) the database.
2027 * @param string $tableName
2028 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2029 * @param bool $force
2034 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2035 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2039 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2040 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2041 * TODO: Alternative solutions might be
2042 * * Stop using functions and find another way to strip numeric characters from phones
2043 * * Give better error messages (currently a missing fn fatals with "unknown error")
2045 public static function checkSqlFunctionsExist() {
2046 if (!self
::$_checkedSqlFunctionsExist) {
2047 self
::$_checkedSqlFunctionsExist = TRUE;
2048 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2049 if (!$dao->fetch()) {
2050 self
::triggerRebuild();
2056 * Wrapper function to drop triggers.
2058 * @param string $tableName
2059 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2062 public static function dropTriggers($tableName = NULL) {
2063 Civi
::service('sql_triggers')->dropTriggers($tableName);
2067 * @param array $info
2068 * per hook_civicrm_triggerInfo.
2069 * @param string $onlyTableName
2070 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2073 public static function createTriggers(&$info, $onlyTableName = NULL) {
2074 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2078 * Given a list of fields, create a list of references.
2080 * @param string $className
2081 * BAO/DAO class name.
2082 * @return array<CRM_Core_Reference_Interface>
2084 public static function createReferenceColumns($className) {
2086 $fields = $className::fields();
2087 foreach ($fields as $field) {
2088 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2089 $result[] = new CRM_Core_Reference_OptionValue(
2090 $className::getTableName(),
2092 'civicrm_option_value',
2093 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2094 $field['pseudoconstant']['optionGroupName']
2102 * Find all records which refer to this entity.
2105 * Array of objects referencing this
2107 public function findReferences() {
2108 $links = self
::getReferencesToTable(static::getTableName());
2110 $occurrences = array();
2111 foreach ($links as $refSpec) {
2112 /** @var $refSpec CRM_Core_Reference_Interface */
2113 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2114 $result = $refSpec->findReferences($this);
2116 while ($result->fetch()) {
2117 $obj = new $daoName();
2118 $obj->id
= $result->id
;
2119 $occurrences[] = $obj;
2124 return $occurrences;
2129 * each item has keys:
2133 * - table: string|null SQL table name
2134 * - key: string|null SQL column name
2136 public function getReferenceCounts() {
2137 $links = self
::getReferencesToTable(static::getTableName());
2140 foreach ($links as $refSpec) {
2141 /** @var $refSpec CRM_Core_Reference_Interface */
2142 $count = $refSpec->getReferenceCount($this);
2143 if ($count['count'] != 0) {
2148 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2149 /** @var $component CRM_Core_Component_Info */
2150 $counts = array_merge($counts, $component->getReferenceCounts($this));
2152 CRM_Utils_Hook
::referenceCounts($this, $counts);
2158 * List all tables which have hard foreign keys to this table.
2160 * For now, this returns a description of every entity_id/entity_table
2162 * TODO: filter dynamic entity references on the $tableName, based on
2163 * schema metadata in dynamicForeignKey which enumerates a restricted
2164 * set of possible entity_table's.
2166 * @param string $tableName
2167 * Table referred to.
2170 * structure of table and column, listing every table with a
2171 * foreign key reference to $tableName, and the column where the key appears.
2173 public static function getReferencesToTable($tableName) {
2174 $refsFound = array();
2175 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2176 $links = $daoClassName::getReferenceColumns();
2177 $daoTableName = $daoClassName::getTableName();
2179 foreach ($links as $refSpec) {
2180 /** @var $refSpec CRM_Core_Reference_Interface */
2181 if ($refSpec->matchesTargetTable($tableName)) {
2182 $refsFound[] = $refSpec;
2190 * Lookup the value of a MySQL global configuration variable.
2192 * @param string $name
2193 * E.g. "thread_stack".
2194 * @param mixed $default
2197 public static function getGlobalSetting($name, $default = NULL) {
2198 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2199 // that has been reported to fail under MySQL 5.0 for OS X
2200 $escapedName = self
::escapeString($name);
2201 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2202 if ($dao->fetch()) {
2212 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2214 * This is relevant where we want to offer both the ID field and the label field
2215 * as an option, e.g. search builder.
2217 * It is currently limited for optionGroupName for purposes keeping the scope of the
2218 * change small, but is appropriate for other sorts of pseudoconstants.
2220 * @param array $fields
2222 protected static function appendPseudoConstantsToFields(&$fields) {
2223 foreach ($fields as $field) {
2224 if (!empty($field['pseudoconstant']) && !empty($field['pseudoconstant']['optionGroupName'])) {
2225 $fields[$field['pseudoconstant']['optionGroupName']] = array(
2226 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($field['pseudoconstant']['optionGroupName']),
2227 'name' => $field['pseudoconstant']['optionGroupName'],
2228 'data_type' => CRM_Utils_Type
::T_STRING
,
2235 * Get options for the called BAO object's field.
2237 * This function can be overridden by each BAO to add more logic related to context.
2238 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2240 * @param string $fieldName
2241 * @param string $context
2242 * @see CRM_Core_DAO::buildOptionsContext
2243 * @param array $props
2244 * whatever is known about this bao object.
2246 * @return array|bool
2248 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2249 // If a given bao does not override this function
2250 $baoName = get_called_class();
2251 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2255 * Populate option labels for this object's fields.
2257 * @throws exception if called directly on the base class
2259 public function getOptionLabels() {
2260 $fields = $this->fields();
2261 if ($fields === NULL) {
2262 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2264 foreach ($fields as $field) {
2265 $name = CRM_Utils_Array
::value('name', $field);
2266 if ($name && isset($this->$name)) {
2267 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2268 if ($label !== FALSE) {
2269 // Append 'label' onto the field name
2270 $labelName = $name . '_label';
2271 $this->$labelName = $label;
2278 * Provides documentation and validation for the buildOptions $context param
2280 * @param string $context
2285 public static function buildOptionsContext($context = NULL) {
2287 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2288 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2289 'search' => "search: searchable options are returned; labels are translated.",
2290 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2291 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2292 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2294 // Validation: enforce uniformity of this param
2295 if ($context !== NULL && !isset($contexts[$context])) {
2296 throw new Exception("'$context' is not a valid context for buildOptions.");
2302 * @param string $fieldName
2303 * @return bool|array
2305 public function getFieldSpec($fieldName) {
2306 $fields = $this->fields();
2307 $fieldKeys = $this->fieldKeys();
2309 // Support "unique names" as well as sql names
2310 $fieldKey = $fieldName;
2311 if (empty($fields[$fieldKey])) {
2312 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2314 // If neither worked then this field doesn't exist. Return false.
2315 if (empty($fields[$fieldKey])) {
2318 return $fields[$fieldKey];
2322 * Get SQL where clause for SQL filter syntax input parameters.
2324 * SQL version of api function to assign filters to the DAO based on the syntax
2325 * $field => array('IN' => array(4,6,9))
2327 * $field => array('LIKE' => array('%me%))
2330 * @param string $fieldName
2332 * @param array $filter
2333 * filter to be applied indexed by operator.
2334 * @param string $type
2335 * type of field (not actually used - nor in api @todo ).
2336 * @param string $alias
2337 * alternative field name ('as') @todo- not actually used.
2338 * @param bool $returnSanitisedArray
2339 * Return a sanitised array instead of a clause.
2340 * this is primarily so we can add filters @ the api level to the Query object based fields
2344 * @return NULL|string|array
2345 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2346 * depending on whether it is supported as yet
2348 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2349 foreach ($filter as $operator => $criteria) {
2350 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2351 switch ($operator) {
2355 if (!$returnSanitisedArray) {
2356 return (sprintf('%s %s', $fieldName, $operator));
2359 return (sprintf('%s %s ', $fieldName, $operator));
2363 // ternary operators
2366 if (empty($criteria[0]) ||
empty($criteria[1])) {
2367 throw new Exception("invalid criteria for $operator");
2369 if (!$returnSanitisedArray) {
2370 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2373 return NULL; // not yet implemented (tests required to implement)
2380 if (empty($criteria)) {
2381 throw new Exception("invalid criteria for $operator");
2383 $escapedCriteria = array_map(array(
2387 if (!$returnSanitisedArray) {
2388 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2390 return $escapedCriteria;
2395 if (!$returnSanitisedArray) {
2396 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2399 return NULL; // not yet implemented (tests required to implement)
2407 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2408 * support for other syntaxes is discussed in ticket but being put off for now
2411 public static function acceptedSQLOperators() {
2432 * SQL has a limit of 64 characters on various names:
2433 * table name, trigger name, column name ...
2435 * For custom groups and fields we generated names from user entered input
2436 * which can be longer than this length, this function helps with creating
2437 * strings that meet various criteria.
2439 * @param string $string
2440 * The string to be shortened.
2441 * @param int $length
2442 * The max length of the string.
2444 * @param bool $makeRandom
2448 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2449 // early return for strings that meet the requirements
2450 if (strlen($string) <= $length) {
2454 // easy return for calls that dont need a randomized uniq string
2456 return substr($string, 0, $length);
2459 // the string is longer than the length and we need a uniq string
2460 // for the same tablename we need the same uniq string every time
2461 // hence we use md5 on the string, which is not random
2462 // we'll append 8 characters to the end of the tableName
2463 $md5string = substr(md5($string), 0, 8);
2464 return substr($string, 0, $length - 8) . "_{$md5string}";
2468 * https://issues.civicrm.org/jira/browse/CRM-17748
2469 * Sets the internal options to be used on a query
2471 * @param array $options
2474 public function setOptions($options) {
2475 if (is_array($options)) {
2476 $this->_options
= $options;
2481 * https://issues.civicrm.org/jira/browse/CRM-17748
2482 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2484 * @param array $options
2487 protected function _setDBOptions($options) {
2488 global $_DB_DATAOBJECT;
2490 if (is_array($options) && count($options)) {
2491 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2492 foreach ($options as $option_name => $option_value) {
2493 $conn->setOption($option_name, $option_value);
2500 * @param array $params
2502 public function setApiFilter(&$params) {
2506 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2508 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2511 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2515 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2519 public function addSelectWhereClause() {
2521 $fields = $this->fields();
2522 foreach ($fields as $fieldName => $field) {
2523 // Clause for contact-related entities like Email, Relationship, etc.
2524 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2525 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2527 // Clause for an entity_table/entity_id combo
2528 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2529 $relatedClauses = array();
2530 $relatedEntities = $this->buildOptions('entity_table', 'get');
2531 foreach ((array) $relatedEntities as $table => $ent) {
2533 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2534 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2536 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2539 $relatedClauses[] = "(entity_table = '$table')";
2543 if ($relatedClauses) {
2544 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2548 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2553 * This returns the final permissioned query string for this entity
2555 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2557 * @param string $tableAlias
2560 public static function getSelectWhereClause($tableAlias = NULL) {
2561 $bao = new static();
2562 if ($tableAlias === NULL) {
2563 $tableAlias = $bao->tableName();
2566 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2567 $clauses[$field] = NULL;
2569 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2576 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2577 * and dashes, and contains at least one [a-z] case insenstive.
2583 public static function requireSafeDBName($database) {
2586 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2590 if (empty($matches)) {