3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2018 |
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 * Base Database Access Object class.
31 * All DAO classes should inherit from this class.
34 * @copyright CiviCRM LLC (c) 2004-2018
37 if (!defined('DB_DSN_MODE')) {
38 define('DB_DSN_MODE', 'auto');
41 require_once 'PEAR.php';
42 require_once 'DB/DataObject.php';
44 require_once 'CRM/Core/I18n.php';
49 class CRM_Core_DAO
extends DB_DataObject
{
55 static $_nullObject = NULL;
60 static $_nullArray = array();
62 static $_dbColumnValueCache = NULL;
63 const NOT_NULL
= 1, IS_NULL
= 2,
65 VALUE_SEPARATOR
= "\ 1",
66 BULK_INSERT_COUNT
= 200,
67 BULK_INSERT_HIGH_COUNT
= 200,
68 QUERY_FORMAT_WILDCARD
= 1,
69 QUERY_FORMAT_NO_QUOTES
= 2,
72 * Serialized string separated by and bookended with VALUE_SEPARATOR
74 SERIALIZE_SEPARATOR_BOOKEND
= 1,
76 * @deprecated format separated by VALUE_SEPARATOR
78 SERIALIZE_SEPARATOR_TRIMMED
= 2,
80 * Recommended serialization format
84 * @deprecated format using php serialize()
88 * Comma separated string, no quotes, no spaces
93 * Define entities that shouldn't be created or deleted when creating/ deleting
94 * test objects - this prevents world regions, countries etc from being added / deleted
97 static $_testEntitiesToSkip = array();
99 * The factory class for this application.
102 static $_factory = NULL;
104 static $_checkedSqlFunctionsExist = FALSE;
107 * https://issues.civicrm.org/jira/browse/CRM-17748
108 * internal variable for DAO to hold per-query settings
110 protected $_options = array();
115 * @return \CRM_Core_DAO
117 public function __construct() {
119 $this->__table
= $this->getTableName();
123 * Empty definition for virtual function.
125 public static function getTableName() {
130 * Initialize the DAO object.
133 * The database connection string.
135 public static function init($dsn) {
136 Civi
::$statics[__CLASS__
]['init'] = 1;
137 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
138 $options['database'] = $dsn;
139 if (defined('CIVICRM_DAO_DEBUG')) {
140 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
142 $factory = new CRM_Contact_DAO_Factory();
143 CRM_Core_DAO
::setFactory($factory);
144 $currentModes = CRM_Utils_SQL
::getSqlModes();
145 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
146 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
147 $currentModes[] = 'ONLY_FULL_GROUP_BY';
149 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
150 $currentModes = array_merge(array('STRICT_TRANS_TABLES'), $currentModes);
152 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", array(1 => array(implode(',', $currentModes), 'String')));
154 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
155 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request
::id(), 'String')));
161 public static function getConnection() {
162 global $_DB_DATAOBJECT;
163 $dao = new CRM_Core_DAO();
164 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
168 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
170 public static function disableFullGroupByMode() {
171 $currentModes = CRM_Utils_SQL
::getSqlModes();
172 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
173 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
174 unset($currentModes[$key]);
175 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", array(1 => array(implode(',', $currentModes), 'String')));
180 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
182 public static function reenableFullGroupByMode() {
183 $currentModes = CRM_Utils_SQL
::getSqlModes();
184 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
185 $currentModes[] = 'ONLY_FULL_GROUP_BY';
186 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", array(1 => array(implode(',', $currentModes), 'String')));
191 * @param string $fieldName
193 * @param array $params
195 protected function assignTestFK($fieldName, $fieldDef, $params) {
196 $required = CRM_Utils_Array
::value('required', $fieldDef);
197 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
198 $dbName = $fieldDef['name'];
199 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
201 // skip the FK if it is not required
202 // if it's contact id we should create even if not required
203 // we'll have a go @ fetching first though
204 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
205 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
208 if (!$required && $dbName != 'contact_id') {
209 $fkDAO = new $FKClassName();
210 if ($fkDAO->find(TRUE)) {
211 $this->$dbName = $fkDAO->id
;
216 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
217 $depObject = new $FKClassName();
218 $depObject->find(TRUE);
219 $this->$dbName = $depObject->id
;
222 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
223 // FIXME: the fields() metadata is not specific enough
224 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
225 $this->$dbName = $depObject->id
;
229 //if it is required we need to generate the dependency object first
230 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
231 $this->$dbName = $depObject->id
;
237 * Generate and assign an arbitrary value to a field of a test object.
239 * @param string $fieldName
240 * @param array $fieldDef
241 * @param int $counter
242 * The globally-unique ID of the test object.
244 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
245 $dbName = $fieldDef['name'];
246 $daoName = get_class($this);
249 if (!$handled && $dbName == 'contact_sub_type') {
250 //coming up with a rule to set this is too complex let's not set it
254 // Pick an option value if needed
255 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
256 $options = $daoName::buildOptions($dbName, 'create');
258 $this->$dbName = key($options);
264 switch ($fieldDef['type']) {
265 case CRM_Utils_Type
::T_INT
:
266 case CRM_Utils_Type
::T_FLOAT
:
267 case CRM_Utils_Type
::T_MONEY
:
268 if (isset($fieldDef['precision'])) {
269 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
270 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
273 $this->$dbName = $counter;
277 case CRM_Utils_Type
::T_BOOLEAN
:
278 if (isset($fieldDef['default'])) {
279 $this->$dbName = $fieldDef['default'];
281 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
289 case CRM_Utils_Type
::T_DATE
:
290 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
291 $this->$dbName = '19700101';
292 if ($dbName == 'end_date') {
293 // put this in the future
294 $this->$dbName = '20200101';
298 case CRM_Utils_Type
::T_TIMESTAMP
:
299 $this->$dbName = '19700201000000';
302 case CRM_Utils_Type
::T_TIME
:
303 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
304 //$object->$dbName='000000';
306 case CRM_Utils_Type
::T_CCNUM
:
307 $this->$dbName = '4111 1111 1111 1111';
310 case CRM_Utils_Type
::T_URL
:
311 $this->$dbName = 'http://www.civicrm.org';
314 case CRM_Utils_Type
::T_STRING
:
315 case CRM_Utils_Type
::T_BLOB
:
316 case CRM_Utils_Type
::T_MEDIUMBLOB
:
317 case CRM_Utils_Type
::T_TEXT
:
318 case CRM_Utils_Type
::T_LONGTEXT
:
319 case CRM_Utils_Type
::T_EMAIL
:
321 // WAS: if (isset($value['enumValues'])) {
322 // TODO: see if this works with all pseudoconstants
323 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
324 if (isset($fieldDef['default'])) {
325 $this->$dbName = $fieldDef['default'];
328 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
329 if (is_array($options)) {
330 $this->$dbName = $options[0];
333 $defaultValues = explode(',', $options);
334 $this->$dbName = $defaultValues[0];
339 $this->$dbName = $dbName . '_' . $counter;
340 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
341 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
342 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
350 * Reset the DAO object.
352 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
354 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
356 public function reset() {
358 foreach (array_keys($this->table()) as $field) {
359 unset($this->$field);
363 * reset the various DB_DAO structures manually
365 $this->_query
= array();
372 * @param string $tableName
376 public static function getLocaleTableName($tableName) {
379 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
380 if (in_array($tableName, $tables)) {
381 return $tableName . $dbLocale;
388 * Execute a query by the current DAO, localizing it along the way (if needed).
390 * @param string $query
391 * The SQL query for execution.
392 * @param bool $i18nRewrite
393 * Whether to rewrite the query.
396 * the current DAO object after the query execution
398 public function query($query, $i18nRewrite = TRUE) {
399 // rewrite queries that should use $dbLocale-based views for multi-language installs
400 global $dbLocale, $_DB_DATAOBJECT;
402 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
403 // Will force connection to be populated per CRM-20541.
407 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
408 $orig_options = $conn->options
;
409 $this->_setDBOptions($this->_options
);
411 if ($i18nRewrite and $dbLocale) {
412 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
415 $ret = parent
::query($query);
417 $this->_setDBOptions($orig_options);
422 * Static function to set the factory instance for this class.
424 * @param object $factory
425 * The factory application object.
427 public static function setFactory(&$factory) {
428 self
::$_factory = &$factory;
432 * Factory method to instantiate a new object from a table name.
434 * @param string $table
435 * @return \DataObject|\PEAR_Error
437 public function factory($table = '') {
438 if (!isset(self
::$_factory)) {
439 return parent
::factory($table);
442 return self
::$_factory->create($table);
446 * Initialization for all DAO objects. Since we access DB_DO programatically
447 * we need to set the links manually.
449 public function initialize() {
451 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
452 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
453 // This occurs very early in bootstrap - error handlers may not be wired up.
454 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
455 CRM_Utils_System
::civiExit();
460 * Defines the default key as 'id'.
464 public function keys() {
473 * Tells DB_DataObject which keys use autoincrement.
474 * 'id' is autoincrementing by default.
479 public function sequenceKey() {
480 static $sequenceKeys;
481 if (!isset($sequenceKeys)) {
482 $sequenceKeys = array('id', TRUE);
484 return $sequenceKeys;
488 * Returns list of FK relationships.
492 * Array of CRM_Core_Reference_Interface
494 public static function getReferenceColumns() {
499 * Returns all the column names of this table.
504 public static function &fields() {
510 * Get/set an associative array of table columns
515 public function table() {
516 $fields = $this->fields();
520 foreach ($fields as $name => $value) {
521 $table[$value['name']] = $value['type'];
522 if (!empty($value['required'])) {
523 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
536 * @return CRM_Core_DAO
538 public function save($hook = TRUE) {
539 if (!empty($this->id
)) {
543 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
544 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
551 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
552 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
558 CRM_Utils_Hook
::postSave($this);
565 * Deletes items from table which match current objects variables.
567 * Returns the true on success
571 * Designed to be extended
573 * $object = new mytable();
575 * echo $object->delete(); // builds a conditon
577 * $object = new mytable();
578 * $object->whereAdd('age > 12');
580 * $object->orderBy('age DESC');
581 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
583 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
584 * we will build the condition only using the whereAdd's. Default is to
585 * build the condition only using the object parameters.
587 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
589 public function delete($useWhere = FALSE) {
590 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
591 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
593 $result = parent
::delete($useWhere);
595 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
596 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
603 * @param bool $created
605 public function log($created = FALSE) {
608 if (!$this->getLog()) {
613 $session = CRM_Core_Session
::singleton();
614 $cid = $session->get('userID');
617 // return is we dont have handle to FK
622 $dao = new CRM_Core_DAO_Log();
623 $dao->entity_table
= $this->getTableName();
624 $dao->entity_id
= $this->id
;
625 $dao->modified_id
= $cid;
626 $dao->modified_date
= date("YmdHis");
631 * Given an associative array of name/value pairs, extract all the values
632 * that belong to this object and initialize the object with said values
634 * @param array $params
635 * (reference ) associative array of name/value pairs.
636 * @param bool $serializeArrays
637 * Should arrays that are passed in be serialised according to the metadata.
638 * Eventually this should be always true / gone, but in the interests of caution
639 * it is being grandfathered in. In general an array is not valid on the DAO
640 * but there may be instances where this function is called & then some handling
641 * takes place on the would-be array.
644 * Did we copy all null values into the object
646 public function copyValues(&$params, $serializeArrays = FALSE) {
647 $fields = $this->fields();
649 foreach ($fields as $name => $value) {
650 $dbName = $value['name'];
651 if (array_key_exists($dbName, $params)) {
652 $pValue = $params[$dbName];
655 elseif (array_key_exists($name, $params)) {
656 $pValue = $params[$name];
663 // if there is no value then make the variable NULL
665 if ($pValue === '') {
666 $this->$dbName = 'null';
668 elseif ($serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
669 $this->$dbName = CRM_Core_DAO
::serializeField($pValue, $value['serialize']);
673 if (!$serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
674 Civi
::log()->warning(ts('use copyParams to serialize arrays (' . __CLASS__
. '.' . $name . ')'), ['civi.tag' => 'deprecated']);
676 $this->$dbName = $pValue;
685 * Store all the values from this object in an associative array
686 * this is a destructive store, calling function is responsible
687 * for keeping sanity of id's.
689 * @param object $object
690 * The object that we are extracting data from.
691 * @param array $values
692 * (reference ) associative array of name/value pairs.
694 public static function storeValues(&$object, &$values) {
695 $fields = $object->fields();
696 foreach ($fields as $name => $value) {
697 $dbName = $value['name'];
698 if (isset($object->$dbName) && $object->$dbName !== 'null') {
699 $values[$dbName] = $object->$dbName;
700 if ($name != $dbName) {
701 $values[$name] = $object->$dbName;
708 * Create an attribute for this specific field. We only do this for strings and text
710 * @param array $field
711 * The field under task.
714 * the attributes for the object
716 public static function makeAttribute($field) {
718 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
719 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
720 $size = CRM_Utils_Array
::value('size', $field);
721 if ($maxLength ||
$size) {
722 $attributes = array();
724 $attributes['maxlength'] = $maxLength;
727 $attributes['size'] = $size;
732 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
733 $rows = CRM_Utils_Array
::value('rows', $field);
737 $cols = CRM_Utils_Array
::value('cols', $field);
742 $attributes = array();
743 $attributes['rows'] = $rows;
744 $attributes['cols'] = $cols;
747 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
) {
748 $attributes['size'] = 6;
749 $attributes['maxlength'] = 14;
757 * Get the size and maxLength attributes for this text field.
758 * (or for all text fields) in the DAO object.
760 * @param string $class
762 * @param string $fieldName
763 * Field that i'm interested in or null if.
764 * you want the attributes for all DAO text fields
767 * assoc array of name => attribute pairs
769 public static function getAttribute($class, $fieldName = NULL) {
770 $object = new $class();
771 $fields = $object->fields();
772 if ($fieldName != NULL) {
773 $field = CRM_Utils_Array
::value($fieldName, $fields);
774 return self
::makeAttribute($field);
777 $attributes = array();
778 foreach ($fields as $name => $field) {
779 $attribute = self
::makeAttribute($field);
781 $attributes[$name] = $attribute;
785 if (!empty($attributes)) {
793 * Check if there is a record with the same name in the db.
795 * @param string $value
796 * The value of the field we are checking.
797 * @param string $daoName
798 * The dao object name.
799 * @param string $daoID
800 * The id of the object being updated. u can change your name.
801 * as long as there is no conflict
802 * @param string $fieldName
803 * The name of the field in the DAO.
805 * @param string $domainID
806 * The id of the domain. Object exists only for the given domain.
809 * true if object exists
811 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
812 $object = new $daoName();
813 $object->$fieldName = $value;
815 $object->domain_id
= $domainID;
818 if ($object->find(TRUE)) {
819 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
827 * Check if there is a given column in a specific table.
829 * @param string $tableName
830 * @param string $columnName
831 * @param bool $i18nRewrite
832 * Whether to rewrite the query on multilingual setups.
835 * true if exists, else false
837 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
843 $params = array(1 => array($columnName, 'String'));
844 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
845 $result = $dao->fetch() ?
TRUE : FALSE;
851 * Scans all the tables using a slow query and table name.
855 public static function getTableNames() {
856 $dao = CRM_Core_DAO
::executeQuery(
858 FROM information_schema.TABLES
859 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
860 AND TABLE_NAME LIKE 'civicrm_%'
861 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
862 AND TABLE_NAME NOT LIKE '%_temp%'
865 while ($dao->fetch()) {
866 $values[] = $dao->TABLE_NAME
;
873 * @param int $maxTablesToCheck
877 public static function isDBMyISAM($maxTablesToCheck = 10) {
878 return CRM_Core_DAO
::singleValueQuery(
880 FROM information_schema.TABLES
881 WHERE ENGINE = 'MyISAM'
882 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
883 AND TABLE_NAME LIKE 'civicrm_%'
884 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
885 AND TABLE_NAME NOT LIKE '%_temp%'
890 * Get the name of the CiviCRM database.
894 public static function getDatabaseName() {
895 $daoObj = new CRM_Core_DAO();
896 return $daoObj->database();
900 * Checks if a constraint exists for a specified table.
902 * @param string $tableName
903 * @param string $constraint
906 * true if constraint exists, false otherwise
908 public static function checkConstraintExists($tableName, $constraint) {
909 static $show = array();
911 if (!array_key_exists($tableName, $show)) {
912 $query = "SHOW CREATE TABLE $tableName";
913 $dao = CRM_Core_DAO
::executeQuery($query);
915 if (!$dao->fetch()) {
916 CRM_Core_Error
::fatal();
920 $show[$tableName] = $dao->Create_Table
;
923 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
927 * Checks if CONSTRAINT keyword exists for a specified table.
929 * @param array $tables
934 * true if CONSTRAINT keyword exists, false otherwise
936 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
938 foreach ($tables as $tableName) {
939 if (!array_key_exists($tableName, $show)) {
940 $query = "SHOW CREATE TABLE $tableName";
941 $dao = CRM_Core_DAO
::executeQuery($query);
943 if (!$dao->fetch()) {
944 CRM_Core_Error
::fatal();
948 $show[$tableName] = $dao->Create_Table
;
951 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
952 if ($result == TRUE) {
963 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
964 * for a specified column of a table.
966 * @param string $tableName
967 * @param string $columnName
970 * true if in format, false otherwise
972 public static function checkFKConstraintInFormat($tableName, $columnName) {
973 static $show = array();
975 if (!array_key_exists($tableName, $show)) {
976 $query = "SHOW CREATE TABLE $tableName";
977 $dao = CRM_Core_DAO
::executeQuery($query);
979 if (!$dao->fetch()) {
980 CRM_Core_Error
::fatal();
984 $show[$tableName] = $dao->Create_Table
;
986 $constraint = "`FK_{$tableName}_{$columnName}`";
987 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
988 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
992 * Check whether a specific column in a specific table has always the same value.
994 * @param string $tableName
995 * @param string $columnName
996 * @param string $columnValue
999 * true if the value is always $columnValue, false otherwise
1001 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1002 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1003 $dao = CRM_Core_DAO
::executeQuery($query);
1004 $result = $dao->fetch() ?
FALSE : TRUE;
1010 * Check whether a specific column in a specific table is always NULL.
1012 * @param string $tableName
1013 * @param string $columnName
1016 * true if if the value is always NULL, false otherwise
1018 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1019 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1020 $dao = CRM_Core_DAO
::executeQuery($query);
1021 $result = $dao->fetch() ?
FALSE : TRUE;
1027 * Check if there is a given table in the database.
1029 * @param string $tableName
1032 * true if exists, else false
1034 public static function checkTableExists($tableName) {
1039 $params = array(1 => array($tableName, 'String'));
1041 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1042 $result = $dao->fetch() ?
TRUE : FALSE;
1052 public function checkVersion($version) {
1057 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1058 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1062 * Find a DAO object for the given ID and return it.
1065 * Id of the DAO object being searched for.
1067 * @return CRM_Core_DAO
1068 * Object of the type of the class that called this function.
1072 public static function findById($id) {
1073 $object = new static();
1075 if (!$object->find(TRUE)) {
1076 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1082 * Returns all results as array-encoded records.
1086 public function fetchAll() {
1088 while ($this->fetch()) {
1089 $result[] = $this->toArray();
1095 * Returns a singular value.
1097 * @return mixed|NULL
1099 public function fetchValue() {
1100 $result = $this->getDatabaseResult();
1101 $row = $result->fetchRow();
1111 * Get all the result records as mapping between columns.
1113 * @param string $keyColumn
1115 * @param string $valueColumn
1118 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1120 public function fetchMap($keyColumn, $valueColumn) {
1122 while ($this->fetch()) {
1123 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1129 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1131 * @param string $daoName
1132 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1133 * @param int $searchValue
1134 * Value of the column you want to search by.
1135 * @param string $returnColumn
1136 * Name of the column you want to GET the value of.
1137 * @param string $searchColumn
1138 * Name of the column you want to search by.
1139 * @param bool $force
1140 * Skip use of the cache.
1142 * @return string|null
1143 * Value of $returnColumn in the retrieved record
1145 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1147 empty($searchValue) ||
1148 trim(strtolower($searchValue)) == 'null'
1150 // adding this here since developers forget to check for an id
1151 // or for the 'null' (which is a bad DAO kludge)
1152 // and hence we get the first value in the db
1153 CRM_Core_Error
::fatal();
1156 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1157 if (self
::$_dbColumnValueCache === NULL) {
1158 self
::$_dbColumnValueCache = array();
1161 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1162 $object = new $daoName();
1163 $object->$searchColumn = $searchValue;
1164 $object->selectAdd();
1165 $object->selectAdd($returnColumn);
1168 if ($object->find(TRUE)) {
1169 $result = $object->$returnColumn;
1173 self
::$_dbColumnValueCache[$cacheKey] = $result;
1175 return self
::$_dbColumnValueCache[$cacheKey];
1179 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1181 * @param string $daoName
1182 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1183 * @param int $searchValue
1184 * Value of the column you want to search by.
1185 * @param string $setColumn
1186 * Name of the column you want to SET the value of.
1187 * @param string $setValue
1188 * SET the setColumn to this value.
1189 * @param string $searchColumn
1190 * Name of the column you want to search by.
1193 * true if we found and updated the object, else false
1195 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1196 $object = new $daoName();
1197 $object->selectAdd();
1198 $object->selectAdd("$searchColumn, $setColumn");
1199 $object->$searchColumn = $searchValue;
1201 if ($object->find(TRUE)) {
1202 $object->$setColumn = $setValue;
1203 if ($object->save()) {
1214 * @param array|object $sort either array or CRM_Utils_Sort
1215 * @param string $default
1216 * Default sort value.
1220 public static function getSortString($sort, $default = NULL) {
1221 // check if sort is of type CRM_Utils_Sort
1222 if (is_a($sort, 'CRM_Utils_Sort')) {
1223 return $sort->orderBy();
1228 // is it an array specified as $field => $sortDirection ?
1230 foreach ($sort as $k => $v) {
1231 $sortString .= "$k $v,";
1233 return rtrim($sortString, ',');
1239 * Fetch object based on array of properties.
1241 * @param string $daoName
1242 * Name of the dao object.
1243 * @param array $params
1244 * (reference ) an assoc array of name/value pairs.
1245 * @param array $defaults
1246 * (reference ) an assoc array to hold the flattened values.
1247 * @param array $returnProperities
1248 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1251 * an object of type referenced by daoName
1253 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1254 $object = new $daoName();
1255 $object->copyValues($params);
1257 // return only specific fields if returnproperties are sent
1258 if (!empty($returnProperities)) {
1259 $object->selectAdd();
1260 $object->selectAdd(implode(',', $returnProperities));
1263 if ($object->find(TRUE)) {
1264 self
::storeValues($object, $defaults);
1271 * Delete the object records that are associated with this contact.
1273 * @param string $daoName
1274 * Name of the dao object.
1275 * @param int $contactId
1276 * Id of the contact to delete.
1278 public static function deleteEntityContact($daoName, $contactId) {
1279 $object = new $daoName();
1281 $object->entity_table
= 'civicrm_contact';
1282 $object->entity_id
= $contactId;
1287 * Execute an unbuffered query.
1289 * This is a wrapper around new functionality exposed with CRM-17748.
1291 * @param string $query query to be executed
1293 * @param array $params
1294 * @param bool $abort
1295 * @param null $daoName
1296 * @param bool $freeDAO
1297 * @param bool $i18nRewrite
1298 * @param bool $trapException
1300 * @return CRM_Core_DAO
1301 * Object that points to an unbuffered result set
1303 static public function executeUnbufferedQuery(
1309 $i18nRewrite = TRUE,
1310 $trapException = FALSE
1313 return self
::executeQuery(
1321 array('result_buffering' => 0)
1328 * @param string $query
1329 * Query to be executed.
1331 * @param array $params
1332 * @param bool $abort
1333 * @param null $daoName
1334 * @param bool $freeDAO
1335 * @param bool $i18nRewrite
1336 * @param bool $trapException
1337 * @param array $options
1339 * @return CRM_Core_DAO|object
1340 * object that holds the results of the query
1341 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1342 * out all the properties that are not part of the DAO
1344 public static function &executeQuery(
1350 $i18nRewrite = TRUE,
1351 $trapException = FALSE,
1354 $queryStr = self
::composeQuery($query, $params, $abort);
1357 $dao = new CRM_Core_DAO();
1360 $dao = new $daoName();
1363 if ($trapException) {
1364 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1367 if ($dao->isValidOption($options)) {
1368 $dao->setOptions($options);
1371 $result = $dao->query($queryStr, $i18nRewrite);
1373 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1374 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1378 if (is_a($result, 'DB_Error')) {
1383 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1385 // we typically do this for insert/update/delete statements OR if explicitly asked to
1393 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1395 * @param array $options
1398 * Provided options are valid
1400 public function isValidOption($options) {
1402 $validOptions = array(
1409 if (empty($options)) {
1413 foreach (array_keys($options) as $option) {
1414 if (!in_array($option, $validOptions)) {
1424 * Execute a query and get the single result.
1426 * @param string $query
1427 * Query to be executed.
1428 * @param array $params
1429 * @param bool $abort
1430 * @param bool $i18nRewrite
1431 * @return string|null
1432 * the result of the query if any
1435 public static function &singleValueQuery(
1441 $queryStr = self
::composeQuery($query, $params, $abort);
1443 static $_dao = NULL;
1446 $_dao = new CRM_Core_DAO();
1449 $_dao->query($queryStr, $i18nRewrite);
1451 $result = $_dao->getDatabaseResult();
1454 $row = $result->fetchRow();
1464 * Compose the query by merging the parameters into it.
1466 * @param string $query
1467 * @param array $params
1468 * @param bool $abort
1473 public static function composeQuery($query, $params, $abort = TRUE) {
1475 foreach ($params as $key => $item) {
1476 if (is_numeric($key)) {
1477 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1478 $item[0] = self
::escapeString($item[0]);
1479 if ($item[1] == 'String' ||
1480 $item[1] == 'Memo' ||
1483 // Support class constants stipulating wildcard characters and/or
1484 // non-quoting of strings. Also support legacy code which may be
1485 // passing in TRUE or 1 for $item[2], which used to indicate the
1486 // use of wildcard characters.
1487 if (!empty($item[2])) {
1488 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1489 $item[0] = "'%{$item[0]}%'";
1491 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1492 $item[0] = "'{$item[0]}'";
1496 $item[0] = "'{$item[0]}'";
1500 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1501 strlen($item[0]) == 0
1506 $tr['%' . $key] = $item[0];
1509 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1514 return strtr($query, $tr);
1520 public static function freeResult($ids = NULL) {
1521 global $_DB_DATAOBJECT;
1524 if (!$_DB_DATAOBJECT ||
1525 !isset($_DB_DATAOBJECT['RESULTS'])
1529 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1532 foreach ($ids as $id) {
1533 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1534 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1535 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1538 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1539 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1545 * Make a shallow copy of an object and all the fields in the object.
1547 * @param string $daoName
1549 * @param array $criteria
1550 * Array of all the fields & values.
1551 * on which basis to copy
1552 * @param array $newData
1553 * Array of all the fields & values.
1554 * to be copied besides the other fields
1555 * @param string $fieldsFix
1556 * Array of fields that you want to prefix/suffix/replace.
1557 * @param string $blockCopyOfDependencies
1558 * Fields that you want to block from.
1561 * @return CRM_Core_DAO
1562 * the newly created copy of the object
1564 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1565 $object = new $daoName();
1567 $object->id
= $criteria['id'];
1570 foreach ($criteria as $key => $value) {
1571 $object->$key = $value;
1576 while ($object->fetch()) {
1578 // all the objects except with $blockCopyOfDependencies set
1579 // be copied - addresses #CRM-1962
1581 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1585 $newObject = new $daoName();
1587 $fields = $object->fields();
1588 if (!is_array($fieldsFix)) {
1589 $fieldsToPrefix = array();
1590 $fieldsToSuffix = array();
1591 $fieldsToReplace = array();
1593 if (!empty($fieldsFix['prefix'])) {
1594 $fieldsToPrefix = $fieldsFix['prefix'];
1596 if (!empty($fieldsFix['suffix'])) {
1597 $fieldsToSuffix = $fieldsFix['suffix'];
1599 if (!empty($fieldsFix['replace'])) {
1600 $fieldsToReplace = $fieldsFix['replace'];
1603 foreach ($fields as $name => $value) {
1604 if ($name == 'id' ||
$value['name'] == 'id') {
1605 // copy everything but the id!
1609 $dbName = $value['name'];
1610 $type = CRM_Utils_Type
::typeToString($value['type']);
1611 $newObject->$dbName = $object->$dbName;
1612 if (isset($fieldsToPrefix[$dbName])) {
1613 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1615 if (isset($fieldsToSuffix[$dbName])) {
1616 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1618 if (isset($fieldsToReplace[$dbName])) {
1619 $newObject->$dbName = $fieldsToReplace[$dbName];
1622 if ($type == 'Timestamp' ||
$type == 'Date') {
1623 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1627 foreach ($newData as $k => $v) {
1628 $newObject->$k = $v;
1638 * Cascade update through related entities.
1640 * @param string $daoName
1643 * @param array $newData
1645 * @return CRM_Core_DAO|null
1647 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1648 $object = new $daoName();
1649 $object->id
= $fromId;
1651 if ($object->find(TRUE)) {
1652 $newObject = new $daoName();
1653 $newObject->id
= $toId;
1655 if ($newObject->find(TRUE)) {
1656 $fields = $object->fields();
1657 foreach ($fields as $name => $value) {
1658 if ($name == 'id' ||
$value['name'] == 'id') {
1659 // copy everything but the id!
1663 $colName = $value['name'];
1664 $newObject->$colName = $object->$colName;
1666 if (substr($name, -5) == '_date' ||
1667 substr($name, -10) == '_date_time'
1669 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1672 foreach ($newData as $k => $v) {
1673 $newObject->$k = $v;
1683 * Given the component id, compute the contact id
1684 * since its used for things like send email
1686 * @param $componentIDs
1687 * @param string $tableName
1688 * @param string $idField
1692 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1693 $contactIDs = array();
1695 if (empty($componentIDs)) {
1699 $IDs = implode(',', $componentIDs);
1703 WHERE $idField IN ( $IDs )
1706 $dao = CRM_Core_DAO
::executeQuery($query);
1707 while ($dao->fetch()) {
1708 $contactIDs[] = $dao->contact_id
;
1714 * Fetch object based on array of properties.
1716 * @param string $daoName
1717 * Name of the dao object.
1718 * @param string $fieldIdName
1719 * @param int $fieldId
1721 * @param array $returnProperities
1722 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1725 * an object of type referenced by daoName
1727 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1728 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1729 $object = new $daoName();
1730 $object->$fieldIdName = $fieldId;
1732 // return only specific fields if returnproperties are sent
1733 if (!empty($returnProperities)) {
1734 $object->selectAdd();
1735 $object->selectAdd('id');
1736 $object->selectAdd(implode(',', $returnProperities));
1740 while ($object->fetch()) {
1741 $defaults = array();
1742 self
::storeValues($object, $defaults);
1743 $details[$object->id
] = $defaults;
1750 * Drop all CiviCRM tables.
1752 * @throws \CRM_Exception
1754 public static function dropAllTables() {
1756 // first drop all the custom tables we've created
1757 CRM_Core_BAO_CustomGroup
::dropAllTables();
1759 // drop all multilingual views
1760 CRM_Core_I18n_Schema
::dropAllViews();
1762 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1763 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1764 '..' . DIRECTORY_SEPARATOR
.
1765 '..' . DIRECTORY_SEPARATOR
.
1766 'sql' . DIRECTORY_SEPARATOR
.
1767 'civicrm_drop.mysql'
1776 public static function escapeString($string) {
1777 static $_dao = NULL;
1779 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1780 // has been installed), then we fallback DB-less str_replace escaping, as
1781 // we can't use mysqli_real_escape_string, as there is no DB connection.
1782 // Note: In typical usage, escapeString() will only check one conditional
1783 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1784 if (!defined('CIVICRM_DSN')) {
1785 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1786 // list of characters mysqli_real_escape_string escapes.
1787 $search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
1788 $replace = array("\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z");
1789 return str_replace($search, $replace, $string);
1791 $_dao = new CRM_Core_DAO();
1793 return $_dao->escape($string);
1797 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1799 * @param array $strings
1800 * @param string $default
1801 * the value to use if $strings has no elements.
1803 * eg "abc","def","ghi"
1805 public static function escapeStrings($strings, $default = NULL) {
1806 static $_dao = NULL;
1808 $_dao = new CRM_Core_DAO();
1811 if (empty($strings)) {
1815 $escapes = array_map(array($_dao, 'escape'), $strings);
1816 return '"' . implode('","', $escapes) . '"';
1824 public static function escapeWildCardString($string) {
1826 // ensure we escape the single characters % and _ which are mysql wild
1827 // card characters and could come in via sortByCharacter
1828 // note that mysql does not escape these characters
1829 if ($string && in_array($string,
1830 array('%', '_', '%%', '_%')
1833 return '\\' . $string;
1836 return self
::escapeString($string);
1840 * Creates a test object, including any required objects it needs via recursion
1841 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1842 * ONLY USE FOR TESTING
1844 * @param string $daoName
1845 * @param array $params
1846 * @param int $numObjects
1847 * @param bool $createOnly
1849 * @return object|array|NULL
1850 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1852 public static function createTestObject(
1858 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1859 // so we re-set here in case
1860 $config = CRM_Core_Config
::singleton();
1861 $config->backtrace
= TRUE;
1863 static $counter = 0;
1864 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1865 'CRM_Core_DAO_Worldregion',
1866 'CRM_Core_DAO_StateProvince',
1867 'CRM_Core_DAO_Country',
1868 'CRM_Core_DAO_Domain',
1869 'CRM_Financial_DAO_FinancialType',
1870 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1873 // Prefer to instantiate BAO's instead of DAO's (when possible)
1874 // so that assignTestValue()/assignTestFK() can be overloaded.
1875 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1876 if (class_exists($baoName)) {
1877 $daoName = $baoName;
1880 for ($i = 0; $i < $numObjects; ++
$i) {
1883 /** @var CRM_Core_DAO $object */
1884 $object = new $daoName();
1886 $fields = $object->fields();
1887 foreach ($fields as $fieldName => $fieldDef) {
1888 $dbName = $fieldDef['name'];
1889 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1890 $required = CRM_Utils_Array
::value('required', $fieldDef);
1892 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1893 $object->$dbName = $params[$dbName];
1896 elseif ($dbName != 'id') {
1897 if ($FKClassName != NULL) {
1898 $object->assignTestFK($fieldName, $fieldDef, $params);
1902 $object->assignTestValue($fieldName, $fieldDef, $counter);
1910 $objects[$i] = $object;
1920 elseif ($numObjects == 1) {
1929 * Deletes the this object plus any dependent objects that are associated with it.
1930 * ONLY USE FOR TESTING
1932 * @param string $daoName
1933 * @param array $params
1935 public static function deleteTestObjects($daoName, $params = array()) {
1936 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1937 // so we re-set here in case
1938 $config = CRM_Core_Config
::singleton();
1939 $config->backtrace
= TRUE;
1941 $object = new $daoName();
1942 $object->id
= CRM_Utils_Array
::value('id', $params);
1944 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1945 if ($object->find(TRUE)) {
1947 $fields = $object->fields();
1948 foreach ($fields as $name => $value) {
1950 $dbName = $value['name'];
1952 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1953 $required = CRM_Utils_Array
::value('required', $value);
1954 if ($FKClassName != NULL
1956 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1957 && ($required ||
$dbName == 'contact_id')
1958 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1959 // to make this test process pass - line below makes pass for now
1960 && $dbName != 'member_of_contact_id'
1962 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1969 foreach ($deletions as $deletion) {
1970 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1975 * Set defaults when creating new entity.
1976 * (don't call this set defaults as already in use with different signature in some places)
1978 * @param array $params
1981 public static function setCreateDefaults(&$params, $defaults) {
1982 if (!empty($params['id'])) {
1985 foreach ($defaults as $key => $value) {
1986 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1987 $params[$key] = $value;
1993 * @param string $prefix
1994 * @param bool $addRandomString
1995 * @param null $string
1999 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2000 $tableName = $prefix . "_temp";
2002 if ($addRandomString) {
2004 $tableName .= "_" . $string;
2007 $tableName .= "_" . md5(uniqid('', TRUE));
2015 * @param bool $trigger
2019 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2020 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2023 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2025 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2026 CRM_Core_TemporaryErrorScope
::ignoreException();
2027 $dao = new CRM_Core_DAO();
2029 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2030 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2036 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2037 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2039 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2044 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2045 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2047 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2054 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2055 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2064 * @param null $message
2065 * @param bool $printDAO
2067 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2068 CRM_Utils_System
::xMemory("{$message}: ");
2071 global $_DB_DATAOBJECT;
2073 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2074 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2076 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2081 * Build a list of triggers via hook and add them to (err, reconcile them
2082 * with) the database.
2084 * @param string $tableName
2085 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2086 * @param bool $force
2091 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2092 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2096 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2097 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2098 * TODO: Alternative solutions might be
2099 * * Stop using functions and find another way to strip numeric characters from phones
2100 * * Give better error messages (currently a missing fn fatals with "unknown error")
2102 public static function checkSqlFunctionsExist() {
2103 if (!self
::$_checkedSqlFunctionsExist) {
2104 self
::$_checkedSqlFunctionsExist = TRUE;
2105 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2106 if (!$dao->fetch()) {
2107 self
::triggerRebuild();
2113 * Wrapper function to drop triggers.
2115 * @param string $tableName
2116 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2119 public static function dropTriggers($tableName = NULL) {
2120 Civi
::service('sql_triggers')->dropTriggers($tableName);
2124 * @param array $info
2125 * per hook_civicrm_triggerInfo.
2126 * @param string $onlyTableName
2127 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2130 public static function createTriggers(&$info, $onlyTableName = NULL) {
2131 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2135 * Given a list of fields, create a list of references.
2137 * @param string $className
2138 * BAO/DAO class name.
2139 * @return array<CRM_Core_Reference_Interface>
2141 public static function createReferenceColumns($className) {
2143 $fields = $className::fields();
2144 foreach ($fields as $field) {
2145 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2146 $result[] = new CRM_Core_Reference_OptionValue(
2147 $className::getTableName(),
2149 'civicrm_option_value',
2150 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2151 $field['pseudoconstant']['optionGroupName']
2159 * Find all records which refer to this entity.
2162 * Array of objects referencing this
2164 public function findReferences() {
2165 $links = self
::getReferencesToTable(static::getTableName());
2167 $occurrences = array();
2168 foreach ($links as $refSpec) {
2169 /** @var $refSpec CRM_Core_Reference_Interface */
2170 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2171 $result = $refSpec->findReferences($this);
2173 while ($result->fetch()) {
2174 $obj = new $daoName();
2175 $obj->id
= $result->id
;
2176 $occurrences[] = $obj;
2181 return $occurrences;
2186 * each item has keys:
2190 * - table: string|null SQL table name
2191 * - key: string|null SQL column name
2193 public function getReferenceCounts() {
2194 $links = self
::getReferencesToTable(static::getTableName());
2197 foreach ($links as $refSpec) {
2198 /** @var $refSpec CRM_Core_Reference_Interface */
2199 $count = $refSpec->getReferenceCount($this);
2200 if ($count['count'] != 0) {
2205 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2206 /** @var $component CRM_Core_Component_Info */
2207 $counts = array_merge($counts, $component->getReferenceCounts($this));
2209 CRM_Utils_Hook
::referenceCounts($this, $counts);
2215 * List all tables which have hard foreign keys to this table.
2217 * For now, this returns a description of every entity_id/entity_table
2219 * TODO: filter dynamic entity references on the $tableName, based on
2220 * schema metadata in dynamicForeignKey which enumerates a restricted
2221 * set of possible entity_table's.
2223 * @param string $tableName
2224 * Table referred to.
2227 * structure of table and column, listing every table with a
2228 * foreign key reference to $tableName, and the column where the key appears.
2230 public static function getReferencesToTable($tableName) {
2231 $refsFound = array();
2232 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2233 $links = $daoClassName::getReferenceColumns();
2234 $daoTableName = $daoClassName::getTableName();
2236 foreach ($links as $refSpec) {
2237 /** @var $refSpec CRM_Core_Reference_Interface */
2238 if ($refSpec->matchesTargetTable($tableName)) {
2239 $refsFound[] = $refSpec;
2247 * Lookup the value of a MySQL global configuration variable.
2249 * @param string $name
2250 * E.g. "thread_stack".
2251 * @param mixed $default
2254 public static function getGlobalSetting($name, $default = NULL) {
2255 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2256 // that has been reported to fail under MySQL 5.0 for OS X
2257 $escapedName = self
::escapeString($name);
2258 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2259 if ($dao->fetch()) {
2269 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2271 * This is relevant where we want to offer both the ID field and the label field
2272 * as an option, e.g. search builder.
2274 * It is currently limited for optionGroupName for purposes keeping the scope of the
2275 * change small, but is appropriate for other sorts of pseudoconstants.
2277 * @param array $fields
2279 protected static function appendPseudoConstantsToFields(&$fields) {
2280 foreach ($fields as $field) {
2281 if (!empty($field['pseudoconstant']) && !empty($field['pseudoconstant']['optionGroupName'])) {
2282 $fields[$field['pseudoconstant']['optionGroupName']] = array(
2283 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($field['pseudoconstant']['optionGroupName']),
2284 'name' => $field['pseudoconstant']['optionGroupName'],
2285 'data_type' => CRM_Utils_Type
::T_STRING
,
2292 * Get options for the called BAO object's field.
2294 * This function can be overridden by each BAO to add more logic related to context.
2295 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2297 * @param string $fieldName
2298 * @param string $context
2299 * @see CRM_Core_DAO::buildOptionsContext
2300 * @param array $props
2301 * whatever is known about this bao object.
2303 * @return array|bool
2305 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2306 // If a given bao does not override this function
2307 $baoName = get_called_class();
2308 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2312 * Populate option labels for this object's fields.
2314 * @throws exception if called directly on the base class
2316 public function getOptionLabels() {
2317 $fields = $this->fields();
2318 if ($fields === NULL) {
2319 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2321 foreach ($fields as $field) {
2322 $name = CRM_Utils_Array
::value('name', $field);
2323 if ($name && isset($this->$name)) {
2324 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2325 if ($label !== FALSE) {
2326 // Append 'label' onto the field name
2327 $labelName = $name . '_label';
2328 $this->$labelName = $label;
2335 * Provides documentation and validation for the buildOptions $context param
2337 * @param string $context
2342 public static function buildOptionsContext($context = NULL) {
2344 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2345 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2346 'search' => "search: searchable options are returned; labels are translated.",
2347 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2348 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2349 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2351 // Validation: enforce uniformity of this param
2352 if ($context !== NULL && !isset($contexts[$context])) {
2353 throw new Exception("'$context' is not a valid context for buildOptions.");
2359 * @param string $fieldName
2360 * @return bool|array
2362 public function getFieldSpec($fieldName) {
2363 $fields = $this->fields();
2364 $fieldKeys = $this->fieldKeys();
2366 // Support "unique names" as well as sql names
2367 $fieldKey = $fieldName;
2368 if (empty($fields[$fieldKey])) {
2369 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2371 // If neither worked then this field doesn't exist. Return false.
2372 if (empty($fields[$fieldKey])) {
2375 return $fields[$fieldKey];
2379 * Get SQL where clause for SQL filter syntax input parameters.
2381 * SQL version of api function to assign filters to the DAO based on the syntax
2382 * $field => array('IN' => array(4,6,9))
2384 * $field => array('LIKE' => array('%me%))
2387 * @param string $fieldName
2389 * @param array $filter
2390 * filter to be applied indexed by operator.
2391 * @param string $type
2392 * type of field (not actually used - nor in api @todo ).
2393 * @param string $alias
2394 * alternative field name ('as') @todo- not actually used.
2395 * @param bool $returnSanitisedArray
2396 * Return a sanitised array instead of a clause.
2397 * this is primarily so we can add filters @ the api level to the Query object based fields
2401 * @return NULL|string|array
2402 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2403 * depending on whether it is supported as yet
2405 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2406 foreach ($filter as $operator => $criteria) {
2407 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2408 switch ($operator) {
2412 if (!$returnSanitisedArray) {
2413 return (sprintf('%s %s', $fieldName, $operator));
2416 return (sprintf('%s %s ', $fieldName, $operator));
2420 // ternary operators
2423 if (empty($criteria[0]) ||
empty($criteria[1])) {
2424 throw new Exception("invalid criteria for $operator");
2426 if (!$returnSanitisedArray) {
2427 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2430 return NULL; // not yet implemented (tests required to implement)
2437 if (empty($criteria)) {
2438 throw new Exception("invalid criteria for $operator");
2440 $escapedCriteria = array_map(array(
2444 if (!$returnSanitisedArray) {
2445 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2447 return $escapedCriteria;
2452 if (!$returnSanitisedArray) {
2453 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2456 return NULL; // not yet implemented (tests required to implement)
2464 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2465 * support for other syntaxes is discussed in ticket but being put off for now
2468 public static function acceptedSQLOperators() {
2489 * SQL has a limit of 64 characters on various names:
2490 * table name, trigger name, column name ...
2492 * For custom groups and fields we generated names from user entered input
2493 * which can be longer than this length, this function helps with creating
2494 * strings that meet various criteria.
2496 * @param string $string
2497 * The string to be shortened.
2498 * @param int $length
2499 * The max length of the string.
2501 * @param bool $makeRandom
2505 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2506 // early return for strings that meet the requirements
2507 if (strlen($string) <= $length) {
2511 // easy return for calls that dont need a randomized uniq string
2513 return substr($string, 0, $length);
2516 // the string is longer than the length and we need a uniq string
2517 // for the same tablename we need the same uniq string every time
2518 // hence we use md5 on the string, which is not random
2519 // we'll append 8 characters to the end of the tableName
2520 $md5string = substr(md5($string), 0, 8);
2521 return substr($string, 0, $length - 8) . "_{$md5string}";
2525 * https://issues.civicrm.org/jira/browse/CRM-17748
2526 * Sets the internal options to be used on a query
2528 * @param array $options
2531 public function setOptions($options) {
2532 if (is_array($options)) {
2533 $this->_options
= $options;
2538 * https://issues.civicrm.org/jira/browse/CRM-17748
2539 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2541 * @param array $options
2544 protected function _setDBOptions($options) {
2545 global $_DB_DATAOBJECT;
2547 if (is_array($options) && count($options)) {
2548 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2549 foreach ($options as $option_name => $option_value) {
2550 $conn->setOption($option_name, $option_value);
2557 * @param array $params
2559 public function setApiFilter(&$params) {
2563 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2565 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2568 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2572 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2576 public function addSelectWhereClause() {
2578 $fields = $this->fields();
2579 foreach ($fields as $fieldName => $field) {
2580 // Clause for contact-related entities like Email, Relationship, etc.
2581 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2582 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2584 // Clause for an entity_table/entity_id combo
2585 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2586 $relatedClauses = array();
2587 $relatedEntities = $this->buildOptions('entity_table', 'get');
2588 foreach ((array) $relatedEntities as $table => $ent) {
2590 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2591 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2593 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2596 $relatedClauses[] = "(entity_table = '$table')";
2600 if ($relatedClauses) {
2601 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2605 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2610 * This returns the final permissioned query string for this entity
2612 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2614 * @param string $tableAlias
2617 public static function getSelectWhereClause($tableAlias = NULL) {
2618 $bao = new static();
2619 if ($tableAlias === NULL) {
2620 $tableAlias = $bao->tableName();
2623 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2624 $clauses[$field] = NULL;
2626 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2633 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2634 * and dashes, and contains at least one [a-z] case insenstive.
2640 public static function requireSafeDBName($database) {
2643 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2647 if (empty($matches)) {
2654 * Transform an array to a serialized string for database storage.
2656 * @param array|NULL $value
2657 * @param $serializationType
2658 * @return string|NULL
2659 * @throws \Exception
2661 public static function serializeField($value, $serializationType) {
2662 if ($value === NULL) {
2665 switch ($serializationType) {
2666 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2667 return $value === array() ?
'' : CRM_Utils_Array
::implodePadded($value);
2669 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2670 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2672 case self
::SERIALIZE_JSON
:
2673 return is_array($value) ?
json_encode($value) : $value;
2675 case self
::SERIALIZE_PHP
:
2676 return is_array($value) ?
serialize($value) : $value;
2678 case self
::SERIALIZE_COMMA
:
2679 return is_array($value) ?
implode(',', $value) : $value;
2682 throw new Exception('Unknown serialization method for field.');
2687 * Transform a serialized string from the database into an array.
2689 * @param string|null $value
2690 * @param $serializationType
2691 * @return array|null
2692 * @throws \Exception
2694 public static function unSerializeField($value, $serializationType) {
2695 if ($value === NULL) {
2698 if ($value === '') {
2701 switch ($serializationType) {
2702 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2703 return (array) CRM_Utils_Array
::explodePadded($value);
2705 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2706 return explode(self
::VALUE_SEPARATOR
, trim($value));
2708 case self
::SERIALIZE_JSON
:
2709 return strlen($value) ?
json_decode($value, TRUE) : array();
2711 case self
::SERIALIZE_PHP
:
2712 return strlen($value) ?
unserialize($value) : array();
2714 case self
::SERIALIZE_COMMA
:
2715 return explode(',', trim(str_replace(', ', '', $value)));
2718 throw new Exception('Unknown serialization method for field.');