3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Base Database Access Object class.
15 * All DAO classes should inherit from this class.
18 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 if (!defined('DB_DSN_MODE')) {
22 define('DB_DSN_MODE', 'auto');
25 require_once 'PEAR.php';
26 require_once 'DB/DataObject.php';
28 require_once 'CRM/Core/I18n.php';
33 class CRM_Core_DAO
extends DB_DataObject
{
36 * How many times has this instance been cloned.
40 protected $resultCopies = 0;
46 public static $_nullObject = NULL;
51 public static $_nullArray = [];
53 public static $_dbColumnValueCache = NULL;
54 const NOT_NULL
= 1, IS_NULL
= 2,
56 VALUE_SEPARATOR
= "\ 1",
57 BULK_INSERT_COUNT
= 200,
58 BULK_INSERT_HIGH_COUNT
= 200,
59 QUERY_FORMAT_WILDCARD
= 1,
60 QUERY_FORMAT_NO_QUOTES
= 2,
63 * Serialized string separated by and bookended with VALUE_SEPARATOR
65 SERIALIZE_SEPARATOR_BOOKEND
= 1,
67 * @deprecated format separated by VALUE_SEPARATOR
69 SERIALIZE_SEPARATOR_TRIMMED
= 2,
71 * Recommended serialization format
75 * @deprecated format using php serialize()
79 * Comma separated string, no quotes, no spaces
84 * Define entities that shouldn't be created or deleted when creating/ deleting
85 * test objects - this prevents world regions, countries etc from being added / deleted
88 public static $_testEntitiesToSkip = [];
90 * The factory class for this application.
93 public static $_factory = NULL;
95 public static $_checkedSqlFunctionsExist = FALSE;
98 * https://issues.civicrm.org/jira/browse/CRM-17748
99 * internal variable for DAO to hold per-query settings
102 protected $_options = [];
107 * @return \CRM_Core_DAO
109 public function __construct() {
111 $this->__table
= $this->getTableName();
114 public function __clone() {
115 if (!empty($this->_DB_resultid
)) {
116 $this->resultCopies++
;
123 public function __destruct() {
124 if ($this->resultCopies
=== 0) {
127 $this->resultCopies
--;
131 * Empty definition for virtual function.
133 public static function getTableName() {
138 * Initialize the DAO object.
141 * The database connection string.
143 public static function init($dsn) {
144 Civi
::$statics[__CLASS__
]['init'] = 1;
145 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
146 $options['database'] = $dsn;
147 $options['quote_identifiers'] = TRUE;
148 if (defined('CIVICRM_DAO_DEBUG')) {
149 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
151 $factory = new CRM_Contact_DAO_Factory();
152 CRM_Core_DAO
::setFactory($factory);
153 $currentModes = CRM_Utils_SQL
::getSqlModes();
154 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
155 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
156 $currentModes[] = 'ONLY_FULL_GROUP_BY';
158 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
159 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
161 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
163 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
164 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
170 public static function getConnection() {
171 global $_DB_DATAOBJECT;
172 $dao = new CRM_Core_DAO();
173 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
177 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
179 public static function disableFullGroupByMode() {
180 $currentModes = CRM_Utils_SQL
::getSqlModes();
181 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
182 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
183 unset($currentModes[$key]);
184 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
189 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
191 public static function reenableFullGroupByMode() {
192 $currentModes = CRM_Utils_SQL
::getSqlModes();
193 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
194 $currentModes[] = 'ONLY_FULL_GROUP_BY';
195 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
200 * @param string $fieldName
202 * @param array $params
204 protected function assignTestFK($fieldName, $fieldDef, $params) {
205 $required = $fieldDef['required'] ??
NULL;
206 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
207 $dbName = $fieldDef['name'];
208 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
210 // skip the FK if it is not required
211 // if it's contact id we should create even if not required
212 // we'll have a go @ fetching first though
213 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
214 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
217 if (!$required && $dbName != 'contact_id') {
218 $fkDAO = new $FKClassName();
219 if ($fkDAO->find(TRUE)) {
220 $this->$dbName = $fkDAO->id
;
224 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
225 $depObject = new $FKClassName();
226 $depObject->find(TRUE);
227 $this->$dbName = $depObject->id
;
229 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
230 // FIXME: the fields() metadata is not specific enough
231 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
232 $this->$dbName = $depObject->id
;
235 //if it is required we need to generate the dependency object first
236 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
237 $this->$dbName = $depObject->id
;
242 * Generate and assign an arbitrary value to a field of a test object.
244 * @param string $fieldName
245 * @param array $fieldDef
246 * @param int $counter
247 * The globally-unique ID of the test object.
249 * @throws \CRM_Core_Exception
251 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
252 $dbName = $fieldDef['name'];
253 $daoName = get_class($this);
256 if (!$handled && $dbName == 'contact_sub_type') {
257 //coming up with a rule to set this is too complex let's not set it
261 // Pick an option value if needed
262 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
263 $options = $daoName::buildOptions($dbName, 'create');
265 $this->$dbName = key($options);
271 switch ($fieldDef['type']) {
272 case CRM_Utils_Type
::T_INT
:
273 case CRM_Utils_Type
::T_FLOAT
:
274 case CRM_Utils_Type
::T_MONEY
:
275 if (isset($fieldDef['precision'])) {
276 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
277 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
280 $this->$dbName = $counter;
284 case CRM_Utils_Type
::T_BOOLEAN
:
285 if (isset($fieldDef['default'])) {
286 $this->$dbName = $fieldDef['default'];
288 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
296 case CRM_Utils_Type
::T_DATE
:
297 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
298 $this->$dbName = '19700101';
299 if ($dbName == 'end_date') {
300 // put this in the future
301 $this->$dbName = '20200101';
305 case CRM_Utils_Type
::T_TIMESTAMP
:
306 $this->$dbName = '19700201000000';
309 case CRM_Utils_Type
::T_TIME
:
310 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
312 case CRM_Utils_Type
::T_CCNUM
:
313 $this->$dbName = '4111 1111 1111 1111';
316 case CRM_Utils_Type
::T_URL
:
317 $this->$dbName = 'http://www.civicrm.org';
320 case CRM_Utils_Type
::T_STRING
:
321 case CRM_Utils_Type
::T_BLOB
:
322 case CRM_Utils_Type
::T_MEDIUMBLOB
:
323 case CRM_Utils_Type
::T_TEXT
:
324 case CRM_Utils_Type
::T_LONGTEXT
:
325 case CRM_Utils_Type
::T_EMAIL
:
327 // WAS: if (isset($value['enumValues'])) {
328 // TODO: see if this works with all pseudoconstants
329 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
330 if (isset($fieldDef['default'])) {
331 $this->$dbName = $fieldDef['default'];
334 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
335 if (is_array($options)) {
336 $this->$dbName = $options[0];
339 $defaultValues = explode(',', $options);
340 $this->$dbName = $defaultValues[0];
345 $this->$dbName = $dbName . '_' . $counter;
346 $maxlength = $fieldDef['maxlength'] ??
NULL;
347 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
348 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
356 * Reset the DAO object.
358 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
360 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
362 public function reset() {
364 foreach (array_keys($this->table()) as $field) {
365 unset($this->$field);
369 * reset the various DB_DAO structures manually
378 * @param string $tableName
382 public static function getLocaleTableName($tableName) {
385 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
386 if (in_array($tableName, $tables)) {
387 return $tableName . $dbLocale;
394 * Execute a query by the current DAO, localizing it along the way (if needed).
396 * @param string $query
397 * The SQL query for execution.
398 * @param bool $i18nRewrite
399 * Whether to rewrite the query.
402 * the current DAO object after the query execution
404 public function query($query, $i18nRewrite = TRUE) {
405 // rewrite queries that should use $dbLocale-based views for multi-language installs
406 global $dbLocale, $_DB_DATAOBJECT;
408 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
409 // Will force connection to be populated per CRM-20541.
413 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
414 $orig_options = $conn->options
;
415 $this->_setDBOptions($this->_options
);
417 if ($i18nRewrite and $dbLocale) {
418 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
421 $ret = parent
::query($query);
423 $this->_setDBOptions($orig_options);
428 * Static function to set the factory instance for this class.
430 * @param object $factory
431 * The factory application object.
433 public static function setFactory(&$factory) {
434 self
::$_factory = &$factory;
438 * Factory method to instantiate a new object from a table name.
440 * @param string $table
441 * @return \DataObject|\PEAR_Error
443 public function factory($table = '') {
444 if (!isset(self
::$_factory)) {
445 return parent
::factory($table);
448 return self
::$_factory->create($table);
452 * Initialization for all DAO objects. Since we access DB_DO programatically
453 * we need to set the links manually.
455 public function initialize() {
457 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
458 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
459 // This occurs very early in bootstrap - error handlers may not be wired up.
460 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
461 CRM_Utils_System
::civiExit();
466 * Defines the default key as 'id'.
470 public function keys() {
479 * Tells DB_DataObject which keys use autoincrement.
480 * 'id' is autoincrementing by default.
485 public function sequenceKey() {
486 static $sequenceKeys;
487 if (!isset($sequenceKeys)) {
488 $sequenceKeys = ['id', TRUE];
490 return $sequenceKeys;
494 * Returns list of FK relationships.
498 * Array of CRM_Core_Reference_Interface
500 public static function getReferenceColumns() {
505 * Returns all the column names of this table.
510 public static function &fields() {
516 * Get/set an associative array of table columns
521 public function table() {
522 $fields = $this->fields();
526 foreach ($fields as $name => $value) {
527 $table[$value['name']] = $value['type'];
528 if (!empty($value['required'])) {
529 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
542 * @return CRM_Core_DAO
544 public function save($hook = TRUE) {
545 if (!empty($this->id
)) {
547 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
548 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
551 $result = $this->update();
554 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
555 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
557 $this->clearDbColumnValueCache();
561 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
562 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
565 $result = $this->insert();
568 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
569 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
575 CRM_Utils_Hook
::postSave($this);
582 * Deletes items from table which match current objects variables.
584 * Returns the true on success
588 * Designed to be extended
590 * $object = new mytable();
592 * echo $object->delete(); // builds a conditon
594 * $object = new mytable();
595 * $object->whereAdd('age > 12');
597 * $object->orderBy('age DESC');
598 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
600 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
601 * we will build the condition only using the whereAdd's. Default is to
602 * build the condition only using the object parameters.
604 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
606 public function delete($useWhere = FALSE) {
607 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
608 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
610 $result = parent
::delete($useWhere);
612 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
613 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
616 $this->clearDbColumnValueCache();
622 * @param bool $created
624 public function log($created = FALSE) {
627 if (!$this->getLog()) {
632 $session = CRM_Core_Session
::singleton();
633 $cid = $session->get('userID');
636 // return is we dont have handle to FK
641 $dao = new CRM_Core_DAO_Log();
642 $dao->entity_table
= $this->getTableName();
643 $dao->entity_id
= $this->id
;
644 $dao->modified_id
= $cid;
645 $dao->modified_date
= date("YmdHis");
650 * Given an associative array of name/value pairs, extract all the values
651 * that belong to this object and initialize the object with said values
653 * @param array $params
654 * Array of name/value pairs to save.
657 * Did we copy all null values into the object
659 public function copyValues($params) {
661 foreach ($this->fields() as $uniqueName => $field) {
662 $dbName = $field['name'];
663 if (array_key_exists($dbName, $params)) {
664 $value = $params[$dbName];
667 elseif (array_key_exists($uniqueName, $params)) {
668 $value = $params[$uniqueName];
675 // if there is no value then make the variable NULL
678 $this->$dbName = 'null';
680 elseif (is_array($value) && !empty($field['serialize'])) {
681 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
685 $maxLength = $field['maxlength'] ??
NULL;
686 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
687 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($value, 'String')]));
688 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
689 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
691 $this->$dbName = $value;
700 * Store all the values from this object in an associative array
701 * this is a destructive store, calling function is responsible
702 * for keeping sanity of id's.
704 * @param object $object
705 * The object that we are extracting data from.
706 * @param array $values
707 * (reference ) associative array of name/value pairs.
709 public static function storeValues(&$object, &$values) {
710 $fields = $object->fields();
711 foreach ($fields as $name => $value) {
712 $dbName = $value['name'];
713 if (isset($object->$dbName) && $object->$dbName !== 'null') {
714 $values[$dbName] = $object->$dbName;
715 if ($name != $dbName) {
716 $values[$name] = $object->$dbName;
723 * Create an attribute for this specific field. We only do this for strings and text
725 * @param array $field
726 * The field under task.
729 * the attributes for the object
731 public static function makeAttribute($field) {
733 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
734 $maxLength = $field['maxlength'] ??
NULL;
735 $size = $field['size'] ??
NULL;
736 if ($maxLength ||
$size) {
739 $attributes['maxlength'] = $maxLength;
742 $attributes['size'] = $size;
747 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
748 $rows = $field['rows'] ??
NULL;
752 $cols = $field['cols'] ??
NULL;
758 $attributes['rows'] = $rows;
759 $attributes['cols'] = $cols;
762 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
) {
763 $attributes['size'] = 6;
764 $attributes['maxlength'] = 14;
772 * Get the size and maxLength attributes for this text field.
773 * (or for all text fields) in the DAO object.
775 * @param string $class
777 * @param string $fieldName
778 * Field that i'm interested in or null if.
779 * you want the attributes for all DAO text fields
782 * assoc array of name => attribute pairs
784 public static function getAttribute($class, $fieldName = NULL) {
785 $object = new $class();
786 $fields = $object->fields();
787 if ($fieldName != NULL) {
788 $field = $fields[$fieldName] ??
NULL;
789 return self
::makeAttribute($field);
793 foreach ($fields as $name => $field) {
794 $attribute = self
::makeAttribute($field);
796 $attributes[$name] = $attribute;
800 if (!empty($attributes)) {
808 * Create or update a record from supplied params.
810 * If 'id' is supplied, an existing record will be updated
811 * Otherwise a new record will be created.
813 * @param array $record
814 * @return CRM_Core_DAO
815 * @throws CRM_Core_Exception
817 public static function writeRecord(array $record) {
818 $hook = empty($record['id']) ?
'create' : 'edit';
819 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
820 if ($className === 'CRM_Core_DAO') {
821 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
823 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
825 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
826 $instance = new $className();
827 $instance->copyValues($record);
829 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
835 * Delete a record from supplied params.
837 * @param array $record
839 * @return CRM_Core_DAO
840 * @throws CRM_Core_Exception
842 public static function deleteRecord(array $record) {
843 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
844 if ($className === 'CRM_Core_DAO') {
845 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
847 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
848 if (empty($record['id'])) {
849 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
852 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
853 $instance = new $className();
854 $instance->id
= $record['id'];
855 if (!$instance->delete()) {
856 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
858 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
864 * Check if there is a record with the same name in the db.
866 * @param string $value
867 * The value of the field we are checking.
868 * @param string $daoName
869 * The dao object name.
870 * @param string $daoID
871 * The id of the object being updated. u can change your name.
872 * as long as there is no conflict
873 * @param string $fieldName
874 * The name of the field in the DAO.
876 * @param string $domainID
877 * The id of the domain. Object exists only for the given domain.
880 * true if object exists
882 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
883 $object = new $daoName();
884 $object->$fieldName = $value;
886 $object->domain_id
= $domainID;
889 if ($object->find(TRUE)) {
890 return $daoID && $object->id
== $daoID;
898 * Check if there is a given column in a specific table.
901 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
903 * @param string $tableName
904 * @param string $columnName
905 * @param bool $i18nRewrite
906 * Whether to rewrite the query on multilingual setups.
909 * true if exists, else false
911 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
912 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
916 * Scans all the tables using a slow query and table name.
920 public static function getTableNames() {
921 $dao = CRM_Core_DAO
::executeQuery(
923 FROM information_schema.TABLES
924 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
925 AND TABLE_NAME LIKE 'civicrm_%'
926 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
927 AND TABLE_NAME NOT LIKE '%_temp%'
930 while ($dao->fetch()) {
931 $values[] = $dao->TABLE_NAME
;
937 * @param int $maxTablesToCheck
941 public static function isDBMyISAM($maxTablesToCheck = 10) {
942 return CRM_Core_DAO
::singleValueQuery(
944 FROM information_schema.TABLES
945 WHERE ENGINE = 'MyISAM'
946 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
947 AND TABLE_NAME LIKE 'civicrm_%'
948 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
949 AND TABLE_NAME NOT LIKE '%_temp%'
950 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
955 * Get the name of the CiviCRM database.
959 public static function getDatabaseName() {
960 $daoObj = new CRM_Core_DAO();
961 return $daoObj->database();
965 * Checks if a constraint exists for a specified table.
967 * @param string $tableName
968 * @param string $constraint
971 * true if constraint exists, false otherwise
973 * @throws \CRM_Core_Exception
975 public static function checkConstraintExists($tableName, $constraint) {
978 if (!array_key_exists($tableName, $show)) {
979 $query = "SHOW CREATE TABLE $tableName";
980 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
982 if (!$dao->fetch()) {
983 throw new CRM_Core_Exception('query failed');
986 $show[$tableName] = $dao->Create_Table
;
989 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
993 * Checks if CONSTRAINT keyword exists for a specified table.
995 * @param array $tables
997 * @throws CRM_Core_Exception
1000 * true if CONSTRAINT keyword exists, false otherwise
1002 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1004 foreach ($tables as $tableName) {
1005 if (!array_key_exists($tableName, $show)) {
1006 $query = "SHOW CREATE TABLE $tableName";
1007 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1009 if (!$dao->fetch()) {
1010 throw new CRM_Core_Exception('Show create table failed.');
1013 $show[$tableName] = $dao->Create_Table
;
1016 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1017 if ($result == TRUE) {
1028 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1029 * for a specified column of a table.
1031 * @param string $tableName
1032 * @param string $columnName
1035 * true if in format, false otherwise
1037 * @throws \CRM_Core_Exception
1039 public static function checkFKConstraintInFormat($tableName, $columnName) {
1042 if (!array_key_exists($tableName, $show)) {
1043 $query = "SHOW CREATE TABLE $tableName";
1044 $dao = CRM_Core_DAO
::executeQuery($query);
1046 if (!$dao->fetch()) {
1047 throw new CRM_Core_Exception('query failed');
1050 $show[$tableName] = $dao->Create_Table
;
1052 $constraint = "`FK_{$tableName}_{$columnName}`";
1053 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1054 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1058 * Check whether a specific column in a specific table has always the same value.
1060 * @param string $tableName
1061 * @param string $columnName
1062 * @param string $columnValue
1065 * true if the value is always $columnValue, false otherwise
1067 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1068 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1069 $dao = CRM_Core_DAO
::executeQuery($query);
1070 $result = $dao->fetch() ?
FALSE : TRUE;
1075 * Check whether a specific column in a specific table is always NULL.
1077 * @param string $tableName
1078 * @param string $columnName
1081 * true if if the value is always NULL, false otherwise
1083 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1084 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1085 $dao = CRM_Core_DAO
::executeQuery($query);
1086 $result = $dao->fetch() ?
FALSE : TRUE;
1091 * Check if there is a given table in the database.
1093 * @param string $tableName
1096 * true if exists, else false
1098 public static function checkTableExists($tableName) {
1103 $params = [1 => [$tableName, 'String']];
1105 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1106 return (bool) $dao->fetch();
1110 * Check if a given table has data.
1112 * @param string $tableName
1114 * TRUE if $tableName has at least one record.
1116 public static function checkTableHasData($tableName) {
1117 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1126 public function checkVersion($version) {
1131 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1132 return trim($version) == trim($dbVersion);
1136 * Find a DAO object for the given ID and return it.
1139 * Id of the DAO object being searched for.
1141 * @return CRM_Core_DAO
1142 * Object of the type of the class that called this function.
1146 public static function findById($id) {
1147 $object = new static();
1149 if (!$object->find(TRUE)) {
1150 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1156 * Returns all results as array-encoded records.
1160 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1162 while ($this->fetch()) {
1163 $result[] = $this->toArray();
1169 * Return the results as PHP generator.
1171 * @param string $type
1172 * Whether the generator yields 'dao' objects or 'array's.
1174 public function fetchGenerator($type = 'dao') {
1175 while ($this->fetch()) {
1182 yield
$this->toArray();
1186 throw new \
RuntimeException("Invalid record type ($type)");
1192 * Returns a singular value.
1194 * @return mixed|NULL
1196 public function fetchValue() {
1197 $result = $this->getDatabaseResult();
1198 $row = $result->fetchRow();
1208 * Get all the result records as mapping between columns.
1210 * @param string $keyColumn
1212 * @param string $valueColumn
1215 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1217 public function fetchMap($keyColumn, $valueColumn) {
1219 while ($this->fetch()) {
1220 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1226 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1228 * @param string $daoName
1229 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1230 * @param int $searchValue
1231 * Value of the column you want to search by.
1232 * @param string $returnColumn
1233 * Name of the column you want to GET the value of.
1234 * @param string $searchColumn
1235 * Name of the column you want to search by.
1236 * @param bool $force
1237 * Skip use of the cache.
1239 * @return string|int|null
1240 * Value of $returnColumn in the retrieved record
1242 * @throws \CRM_Core_Exception
1244 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1246 empty($searchValue) ||
1247 trim(strtolower($searchValue)) == 'null'
1249 // adding this here since developers forget to check for an id
1250 // or for the 'null' (which is a bad DAO kludge)
1251 // and hence we get the first value in the db
1252 throw new CRM_Core_Exception('getFieldValue failed');
1255 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1257 while (strpos($daoName, '_BAO_') !== FALSE) {
1258 $daoName = get_parent_class($daoName);
1262 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1263 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1265 $object = new $daoName();
1266 $object->$searchColumn = $searchValue;
1267 $object->selectAdd();
1268 $object->selectAdd($returnColumn);
1271 if ($object->find(TRUE)) {
1272 $result = $object->$returnColumn;
1275 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1277 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1281 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1283 * @param string $daoName
1284 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1285 * @param int $searchValue
1286 * Value of the column you want to search by.
1287 * @param string $setColumn
1288 * Name of the column you want to SET the value of.
1289 * @param string $setValue
1290 * SET the setColumn to this value.
1291 * @param string $searchColumn
1292 * Name of the column you want to search by.
1295 * true if we found and updated the object, else false
1297 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1298 $object = new $daoName();
1299 $object->selectAdd();
1300 $object->selectAdd("$searchColumn, $setColumn");
1301 $object->$searchColumn = $searchValue;
1303 if ($object->find(TRUE)) {
1304 $object->$setColumn = $setValue;
1305 if ($object->save()) {
1316 * @param array|object $sort either array or CRM_Utils_Sort
1317 * @param string $default
1318 * Default sort value.
1322 public static function getSortString($sort, $default = NULL) {
1323 // check if sort is of type CRM_Utils_Sort
1324 if (is_a($sort, 'CRM_Utils_Sort')) {
1325 return $sort->orderBy();
1330 // is it an array specified as $field => $sortDirection ?
1332 foreach ($sort as $k => $v) {
1333 $sortString .= "$k $v,";
1335 return rtrim($sortString, ',');
1341 * Fetch object based on array of properties.
1343 * @param string $daoName
1344 * Name of the dao object.
1345 * @param array $params
1346 * (reference ) an assoc array of name/value pairs.
1347 * @param array $defaults
1348 * (reference ) an assoc array to hold the flattened values.
1349 * @param array $returnProperities
1350 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1353 * an object of type referenced by daoName
1355 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1356 $object = new $daoName();
1357 $object->copyValues($params);
1359 // return only specific fields if returnproperties are sent
1360 if (!empty($returnProperities)) {
1361 $object->selectAdd();
1362 $object->selectAdd(implode(',', $returnProperities));
1365 if ($object->find(TRUE)) {
1366 self
::storeValues($object, $defaults);
1373 * Delete the object records that are associated with this contact.
1375 * @param string $daoName
1376 * Name of the dao object.
1377 * @param int $contactId
1378 * Id of the contact to delete.
1380 public static function deleteEntityContact($daoName, $contactId) {
1381 $object = new $daoName();
1383 $object->entity_table
= 'civicrm_contact';
1384 $object->entity_id
= $contactId;
1389 * Execute an unbuffered query.
1391 * This is a wrapper around new functionality exposed with CRM-17748.
1393 * @param string $query query to be executed
1395 * @param array $params
1396 * @param bool $abort
1397 * @param null $daoName
1398 * @param bool $freeDAO
1399 * @param bool $i18nRewrite
1400 * @param bool $trapException
1402 * @return CRM_Core_DAO
1403 * Object that points to an unbuffered result set
1405 public static function executeUnbufferedQuery(
1411 $i18nRewrite = TRUE,
1412 $trapException = FALSE
1415 return self
::executeQuery(
1423 ['result_buffering' => 0]
1430 * @param string $query
1431 * Query to be executed.
1433 * @param array $params
1434 * @param bool $abort
1435 * @param null $daoName
1436 * @param bool $freeDAO
1437 * @param bool $i18nRewrite
1438 * @param bool $trapException
1439 * @param array $options
1441 * @return CRM_Core_DAO|object
1442 * object that holds the results of the query
1443 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1444 * out all the properties that are not part of the DAO
1446 public static function &executeQuery(
1452 $i18nRewrite = TRUE,
1453 $trapException = FALSE,
1456 $queryStr = self
::composeQuery($query, $params, $abort);
1459 $dao = new CRM_Core_DAO();
1462 $dao = new $daoName();
1465 if ($trapException) {
1466 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1469 if ($dao->isValidOption($options)) {
1470 $dao->setOptions($options);
1473 $result = $dao->query($queryStr, $i18nRewrite);
1475 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1476 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1480 if (is_a($result, 'DB_Error')) {
1488 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1490 * @param array $options
1493 * Provided options are valid
1495 public function isValidOption($options) {
1504 if (empty($options)) {
1508 foreach (array_keys($options) as $option) {
1509 if (!in_array($option, $validOptions)) {
1519 * Execute a query and get the single result.
1521 * @param string $query
1522 * Query to be executed.
1523 * @param array $params
1524 * @param bool $abort
1525 * @param bool $i18nRewrite
1526 * @return string|null
1527 * the result of the query if any
1530 public static function &singleValueQuery(
1536 $queryStr = self
::composeQuery($query, $params, $abort);
1538 static $_dao = NULL;
1541 $_dao = new CRM_Core_DAO();
1544 $_dao->query($queryStr, $i18nRewrite);
1546 $result = $_dao->getDatabaseResult();
1549 $row = $result->fetchRow();
1559 * Compose the query by merging the parameters into it.
1561 * @param string $query
1562 * @param array $params
1563 * @param bool $abort
1566 * @throws CRM_Core_Exception
1568 public static function composeQuery($query, $params = [], $abort = TRUE) {
1570 foreach ($params as $key => $item) {
1571 if (is_numeric($key)) {
1572 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1573 $item[0] = self
::escapeString($item[0]);
1574 if ($item[1] == 'String' ||
1575 $item[1] == 'Memo' ||
1578 // Support class constants stipulating wildcard characters and/or
1579 // non-quoting of strings. Also support legacy code which may be
1580 // passing in TRUE or 1 for $item[2], which used to indicate the
1581 // use of wildcard characters.
1582 if (!empty($item[2])) {
1583 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1584 $item[0] = "'%{$item[0]}%'";
1586 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1587 $item[0] = "'{$item[0]}'";
1591 $item[0] = "'{$item[0]}'";
1595 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1596 strlen($item[0]) == 0
1601 $tr['%' . $key] = $item[0];
1604 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1609 return strtr($query, $tr);
1615 public static function freeResult($ids = NULL) {
1616 global $_DB_DATAOBJECT;
1619 if (!$_DB_DATAOBJECT ||
1620 !isset($_DB_DATAOBJECT['RESULTS'])
1624 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1627 foreach ($ids as $id) {
1628 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1629 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1630 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1633 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1634 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1640 * Make a shallow copy of an object and all the fields in the object.
1642 * @param string $daoName
1644 * @param array $criteria
1645 * Array of all the fields & values.
1646 * on which basis to copy
1647 * @param array $newData
1648 * Array of all the fields & values.
1649 * to be copied besides the other fields
1650 * @param string $fieldsFix
1651 * Array of fields that you want to prefix/suffix/replace.
1652 * @param string $blockCopyOfDependencies
1653 * Fields that you want to block from.
1655 * @param bool $blockCopyofCustomValues
1656 * Case when you don't want to copy the custom values set in a
1657 * template as it will override/ignore the submitted custom values
1659 * @return CRM_Core_DAO|bool
1660 * the newly created copy of the object. False if none created.
1662 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1663 $object = new $daoName();
1666 $object->id
= $criteria['id'];
1669 foreach ($criteria as $key => $value) {
1670 $object->$key = $value;
1675 while ($object->fetch()) {
1677 // all the objects except with $blockCopyOfDependencies set
1678 // be copied - addresses #CRM-1962
1680 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1684 $newObject = new $daoName();
1686 $fields = $object->fields();
1687 if (!is_array($fieldsFix)) {
1688 $fieldsToPrefix = [];
1689 $fieldsToSuffix = [];
1690 $fieldsToReplace = [];
1692 if (!empty($fieldsFix['prefix'])) {
1693 $fieldsToPrefix = $fieldsFix['prefix'];
1695 if (!empty($fieldsFix['suffix'])) {
1696 $fieldsToSuffix = $fieldsFix['suffix'];
1698 if (!empty($fieldsFix['replace'])) {
1699 $fieldsToReplace = $fieldsFix['replace'];
1702 foreach ($fields as $name => $value) {
1703 if ($name == 'id' ||
$value['name'] == 'id') {
1704 // copy everything but the id!
1708 $dbName = $value['name'];
1709 $type = CRM_Utils_Type
::typeToString($value['type']);
1710 $newObject->$dbName = $object->$dbName;
1711 if (isset($fieldsToPrefix[$dbName])) {
1712 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1714 if (isset($fieldsToSuffix[$dbName])) {
1715 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1717 if (isset($fieldsToReplace[$dbName])) {
1718 $newObject->$dbName = $fieldsToReplace[$dbName];
1721 if ($type == 'Timestamp' ||
$type == 'Date') {
1722 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1726 $newObject->copyValues($newData);
1730 if (!$blockCopyofCustomValues) {
1731 $newObject->copyCustomFields($object->id
, $newObject->id
);
1733 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1740 * Method that copies custom fields values from an old entity to a new one.
1742 * Fixes bug CRM-19302,
1743 * where if a custom field of File type was present, left both events using the same file,
1744 * breaking download URL's for the old event.
1746 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1747 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1749 * @param int $entityID
1750 * @param int $newEntityID
1752 public function copyCustomFields($entityID, $newEntityID) {
1753 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1754 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1755 // Obtain custom values for old event
1756 $customParams = $htmlType = [];
1757 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1759 // If custom values present, we copy them
1760 if (!empty($customValues)) {
1761 // Get Field ID's and identify File type attributes, to handle file copying.
1762 $fieldIds = implode(', ', array_keys($customValues));
1763 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1764 $result = CRM_Core_DAO
::executeQuery($sql);
1766 // Build array of File type fields
1767 while ($result->fetch()) {
1768 $htmlType[] = $result->id
;
1771 // Build params array of custom values
1772 foreach ($customValues as $field => $value) {
1773 if ($value !== NULL) {
1774 // Handle File type attributes
1775 if (in_array($field, $htmlType)) {
1776 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1777 $customParams["custom_{$field}_-1"] = [
1778 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1779 'type' => $fileValues[1],
1782 // Handle other types
1784 $customParams["custom_{$field}_-1"] = $value;
1789 // Save Custom Fields for new Event
1790 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1793 // copy activity attachments ( if any )
1794 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1798 * Cascade update through related entities.
1800 * @param string $daoName
1803 * @param array $newData
1805 * @return CRM_Core_DAO|null
1807 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1808 $object = new $daoName();
1809 $object->id
= $fromId;
1811 if ($object->find(TRUE)) {
1812 $newObject = new $daoName();
1813 $newObject->id
= $toId;
1815 if ($newObject->find(TRUE)) {
1816 $fields = $object->fields();
1817 foreach ($fields as $name => $value) {
1818 if ($name == 'id' ||
$value['name'] == 'id') {
1819 // copy everything but the id!
1823 $colName = $value['name'];
1824 $newObject->$colName = $object->$colName;
1826 if (substr($name, -5) == '_date' ||
1827 substr($name, -10) == '_date_time'
1829 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1832 foreach ($newData as $k => $v) {
1833 $newObject->$k = $v;
1843 * Given the component id, compute the contact id
1844 * since its used for things like send email
1846 * @param $componentIDs
1847 * @param string $tableName
1848 * @param string $idField
1852 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1855 if (empty($componentIDs)) {
1859 $IDs = implode(',', $componentIDs);
1863 WHERE $idField IN ( $IDs )
1866 $dao = CRM_Core_DAO
::executeQuery($query);
1867 while ($dao->fetch()) {
1868 $contactIDs[] = $dao->contact_id
;
1874 * Fetch object based on array of properties.
1876 * @param string $daoName
1877 * Name of the dao object.
1878 * @param string $fieldIdName
1879 * @param int $fieldId
1881 * @param array $returnProperities
1882 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1885 * an object of type referenced by daoName
1887 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1888 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1889 $object = new $daoName();
1890 $object->$fieldIdName = $fieldId;
1892 // return only specific fields if returnproperties are sent
1893 if (!empty($returnProperities)) {
1894 $object->selectAdd();
1895 $object->selectAdd('id');
1896 $object->selectAdd(implode(',', $returnProperities));
1900 while ($object->fetch()) {
1902 self
::storeValues($object, $defaults);
1903 $details[$object->id
] = $defaults;
1910 * Drop all CiviCRM tables.
1912 * @throws \CRM_Core_Exception
1914 public static function dropAllTables() {
1916 // first drop all the custom tables we've created
1917 CRM_Core_BAO_CustomGroup
::dropAllTables();
1919 // drop all multilingual views
1920 CRM_Core_I18n_Schema
::dropAllViews();
1922 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1923 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1924 '..' . DIRECTORY_SEPARATOR
.
1925 '..' . DIRECTORY_SEPARATOR
.
1926 'sql' . DIRECTORY_SEPARATOR
.
1927 'civicrm_drop.mysql'
1936 public static function escapeString($string) {
1937 static $_dao = NULL;
1939 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1940 // has been installed), then we fallback DB-less str_replace escaping, as
1941 // we can't use mysqli_real_escape_string, as there is no DB connection.
1942 // Note: In typical usage, escapeString() will only check one conditional
1943 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1944 if (!defined('CIVICRM_DSN')) {
1945 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1946 // list of characters mysqli_real_escape_string escapes.
1947 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
1948 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
1949 return str_replace($search, $replace, $string);
1951 $_dao = new CRM_Core_DAO();
1953 return $_dao->escape($string);
1957 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1959 * @param array $strings
1960 * @param string $default
1961 * the value to use if $strings has no elements.
1963 * eg "abc","def","ghi"
1965 public static function escapeStrings($strings, $default = NULL) {
1966 static $_dao = NULL;
1968 $_dao = new CRM_Core_DAO();
1971 if (empty($strings)) {
1975 $escapes = array_map([$_dao, 'escape'], $strings);
1976 return '"' . implode('","', $escapes) . '"';
1984 public static function escapeWildCardString($string) {
1986 // ensure we escape the single characters % and _ which are mysql wild
1987 // card characters and could come in via sortByCharacter
1988 // note that mysql does not escape these characters
1989 if ($string && in_array($string,
1990 ['%', '_', '%%', '_%']
1993 return '\\' . $string;
1996 return self
::escapeString($string);
2000 * Creates a test object, including any required objects it needs via recursion
2001 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2002 * ONLY USE FOR TESTING
2004 * @param string $daoName
2005 * @param array $params
2006 * @param int $numObjects
2007 * @param bool $createOnly
2009 * @return object|array|NULL
2010 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2012 public static function createTestObject(
2018 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2019 // so we re-set here in case
2020 $config = CRM_Core_Config
::singleton();
2021 $config->backtrace
= TRUE;
2023 static $counter = 0;
2024 CRM_Core_DAO
::$_testEntitiesToSkip = [
2025 'CRM_Core_DAO_Worldregion',
2026 'CRM_Core_DAO_StateProvince',
2027 'CRM_Core_DAO_Country',
2028 'CRM_Core_DAO_Domain',
2029 'CRM_Financial_DAO_FinancialType',
2030 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2033 // Prefer to instantiate BAO's instead of DAO's (when possible)
2034 // so that assignTestValue()/assignTestFK() can be overloaded.
2035 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2036 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2037 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2038 // @todo create a new class called what the BAO SHOULD be
2039 // that extends BAO-crazy-name.... migrate.
2040 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2042 if (class_exists($baoName)) {
2043 $daoName = $baoName;
2046 for ($i = 0; $i < $numObjects; ++
$i) {
2049 /** @var CRM_Core_DAO $object */
2050 $object = new $daoName();
2052 $fields = $object->fields();
2053 foreach ($fields as $fieldName => $fieldDef) {
2054 $dbName = $fieldDef['name'];
2055 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2057 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2058 $object->$dbName = $params[$dbName];
2061 elseif ($dbName != 'id') {
2062 if ($FKClassName != NULL) {
2063 $object->assignTestFK($fieldName, $fieldDef, $params);
2067 $object->assignTestValue($fieldName, $fieldDef, $counter);
2075 $objects[$i] = $object;
2085 elseif ($numObjects == 1) {
2094 * Deletes the this object plus any dependent objects that are associated with it.
2095 * ONLY USE FOR TESTING
2097 * @param string $daoName
2098 * @param array $params
2100 public static function deleteTestObjects($daoName, $params = []) {
2101 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2102 // so we re-set here in case
2103 $config = CRM_Core_Config
::singleton();
2104 $config->backtrace
= TRUE;
2106 $object = new $daoName();
2107 $object->id
= $params['id'] ??
NULL;
2109 // array(array(0 => $daoName, 1 => $daoParams))
2111 if ($object->find(TRUE)) {
2113 $fields = $object->fields();
2114 foreach ($fields as $name => $value) {
2116 $dbName = $value['name'];
2118 $FKClassName = $value['FKClassName'] ??
NULL;
2119 $required = $value['required'] ??
NULL;
2120 if ($FKClassName != NULL
2122 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2123 && ($required ||
$dbName == 'contact_id')
2124 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2125 // to make this test process pass - line below makes pass for now
2126 && $dbName != 'member_of_contact_id'
2129 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2136 foreach ($deletions as $deletion) {
2137 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2142 * Set defaults when creating new entity.
2143 * (don't call this set defaults as already in use with different signature in some places)
2145 * @param array $params
2148 public static function setCreateDefaults(&$params, $defaults) {
2149 if (!empty($params['id'])) {
2152 foreach ($defaults as $key => $value) {
2153 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2154 $params[$key] = $value;
2160 * @param string $prefix
2161 * @param bool $addRandomString
2162 * @param null $string
2166 * @see CRM_Utils_SQL_TempTable
2168 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2169 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2170 $tableName = $prefix . "_temp";
2172 if ($addRandomString) {
2174 $tableName .= "_" . $string;
2177 $tableName .= "_" . md5(uniqid('', TRUE));
2185 * @param bool $trigger
2189 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2190 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2193 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2195 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2196 CRM_Core_TemporaryErrorScope
::ignoreException();
2197 $dao = new CRM_Core_DAO();
2199 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2200 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2206 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2207 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2209 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2214 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2215 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2217 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2224 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2225 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2234 * @param null $message
2235 * @param bool $printDAO
2237 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2238 CRM_Utils_System
::xMemory("{$message}: ");
2241 global $_DB_DATAOBJECT;
2243 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2244 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2246 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2251 * Build a list of triggers via hook and add them to (err, reconcile them
2252 * with) the database.
2254 * @param string $tableName
2255 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2256 * @param bool $force
2261 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2262 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2266 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2267 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2268 * TODO: Alternative solutions might be
2269 * * Stop using functions and find another way to strip numeric characters from phones
2270 * * Give better error messages (currently a missing fn fatals with "unknown error")
2272 public static function checkSqlFunctionsExist() {
2273 if (!self
::$_checkedSqlFunctionsExist) {
2274 self
::$_checkedSqlFunctionsExist = TRUE;
2275 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2276 if (!$dao->fetch()) {
2277 self
::triggerRebuild();
2283 * Wrapper function to drop triggers.
2285 * @param string $tableName
2286 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2289 public static function dropTriggers($tableName = NULL) {
2290 Civi
::service('sql_triggers')->dropTriggers($tableName);
2294 * @param array $info
2295 * per hook_civicrm_triggerInfo.
2296 * @param string $onlyTableName
2297 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2300 public static function createTriggers(&$info, $onlyTableName = NULL) {
2301 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2305 * Given a list of fields, create a list of references.
2307 * @param string $className
2308 * BAO/DAO class name.
2309 * @return array<CRM_Core_Reference_Interface>
2311 public static function createReferenceColumns($className) {
2313 $fields = $className::fields();
2314 foreach ($fields as $field) {
2315 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2316 $result[] = new CRM_Core_Reference_OptionValue(
2317 $className::getTableName(),
2319 'civicrm_option_value',
2320 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2321 $field['pseudoconstant']['optionGroupName']
2329 * Find all records which refer to this entity.
2332 * Array of objects referencing this
2334 public function findReferences() {
2335 $links = self
::getReferencesToTable(static::getTableName());
2338 foreach ($links as $refSpec) {
2339 /** @var $refSpec CRM_Core_Reference_Interface */
2340 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2341 $result = $refSpec->findReferences($this);
2343 while ($result->fetch()) {
2344 $obj = new $daoName();
2345 $obj->id
= $result->id
;
2346 $occurrences[] = $obj;
2351 return $occurrences;
2356 * each item has keys:
2360 * - table: string|null SQL table name
2361 * - key: string|null SQL column name
2363 public function getReferenceCounts() {
2364 $links = self
::getReferencesToTable(static::getTableName());
2367 foreach ($links as $refSpec) {
2368 /** @var $refSpec CRM_Core_Reference_Interface */
2369 $count = $refSpec->getReferenceCount($this);
2370 if ($count['count'] != 0) {
2375 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2376 /** @var $component CRM_Core_Component_Info */
2377 $counts = array_merge($counts, $component->getReferenceCounts($this));
2379 CRM_Utils_Hook
::referenceCounts($this, $counts);
2385 * List all tables which have hard foreign keys to this table.
2387 * For now, this returns a description of every entity_id/entity_table
2389 * TODO: filter dynamic entity references on the $tableName, based on
2390 * schema metadata in dynamicForeignKey which enumerates a restricted
2391 * set of possible entity_table's.
2393 * @param string $tableName
2394 * Table referred to.
2397 * structure of table and column, listing every table with a
2398 * foreign key reference to $tableName, and the column where the key appears.
2400 public static function getReferencesToTable($tableName) {
2402 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2403 $links = $daoClassName::getReferenceColumns();
2405 foreach ($links as $refSpec) {
2406 /** @var $refSpec CRM_Core_Reference_Interface */
2407 if ($refSpec->matchesTargetTable($tableName)) {
2408 $refsFound[] = $refSpec;
2416 * Get all references to contact table.
2418 * This includes core tables, custom group tables, tables added by the merge
2419 * hook and the entity_tag table.
2421 * Refer to CRM-17454 for information on the danger of querying the information
2422 * schema to derive this.
2424 * @throws \CiviCRM_API3_Exception
2426 public static function getReferencesToContactTable() {
2427 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2428 return \Civi
::$statics[__CLASS__
]['contact_references'];
2430 $contactReferences = [];
2431 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2432 foreach ($coreReferences as $coreReference) {
2433 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2434 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2437 self
::appendCustomTablesExtendingContacts($contactReferences);
2438 self
::appendCustomContactReferenceFields($contactReferences);
2439 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2440 return \Civi
::$statics[__CLASS__
]['contact_references'];
2444 * Get all dynamic references to the given table.
2446 * @param string $tableName
2450 public static function getDynamicReferencesToTable($tableName) {
2451 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2452 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2453 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2454 foreach ($coreReferences as $coreReference) {
2455 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2456 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2460 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2464 * Add custom tables that extend contacts to the list of contact references.
2466 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2467 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2468 * - the down side is it is not cached.
2470 * Further changes should be include tests in the CRM_Core_MergerTest class
2471 * to ensure that disabled, subtype, multiple etc groups are still captured.
2473 * @param array $cidRefs
2475 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2476 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2477 $customValueTables->find();
2478 while ($customValueTables->fetch()) {
2479 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2484 * Add custom ContactReference fields to the list of contact references
2486 * This includes active and inactive fields/groups
2488 * @param array $cidRefs
2490 * @throws \CiviCRM_API3_Exception
2492 public static function appendCustomContactReferenceFields(&$cidRefs) {
2493 $fields = civicrm_api3('CustomField', 'get', [
2494 'return' => ['column_name', 'custom_group_id.table_name'],
2495 'data_type' => 'ContactReference',
2496 'options' => ['limit' => 0],
2498 foreach ($fields as $field) {
2499 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2504 * Lookup the value of a MySQL global configuration variable.
2506 * @param string $name
2507 * E.g. "thread_stack".
2508 * @param mixed $default
2511 public static function getGlobalSetting($name, $default = NULL) {
2512 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2513 // that has been reported to fail under MySQL 5.0 for OS X
2514 $escapedName = self
::escapeString($name);
2515 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2516 if ($dao->fetch()) {
2525 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2527 * This is relevant where we want to offer both the ID field and the label field
2528 * as an option, e.g. search builder.
2530 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2531 * change small, but is appropriate for other sorts of pseudoconstants.
2533 * @param array $fields
2535 public static function appendPseudoConstantsToFields(&$fields) {
2536 foreach ($fields as $fieldUniqueName => $field) {
2537 if (!empty($field['pseudoconstant'])) {
2538 $pseudoConstant = $field['pseudoconstant'];
2539 if (!empty($pseudoConstant['optionGroupName'])) {
2540 $fields[$pseudoConstant['optionGroupName']] = [
2541 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2542 'name' => $pseudoConstant['optionGroupName'],
2543 'data_type' => CRM_Utils_Type
::T_STRING
,
2544 'is_pseudofield_for' => $fieldUniqueName,
2547 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2549 !empty($field['FKClassName'])
2550 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2551 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2553 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2554 // This if is just an extra caution when adding change.
2555 if (!isset($fields[$pseudoFieldName])) {
2556 $daoName = $field['FKClassName'];
2557 $fkFields = $daoName::fields();
2558 foreach ($fkFields as $fkField) {
2559 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2560 $fields[$pseudoFieldName] = [
2561 'name' => $pseudoFieldName,
2562 'is_pseudofield_for' => $field['name'],
2563 'title' => $fkField['title'],
2564 'data_type' => $fkField['type'],
2565 'where' => $field['where'],
2576 * Get options for the called BAO object's field.
2578 * This function can be overridden by each BAO to add more logic related to context.
2579 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2581 * @param string $fieldName
2582 * @param string $context
2583 * @see CRM_Core_DAO::buildOptionsContext
2584 * @param array $props
2585 * Raw field values; whatever is known about this bao object.
2587 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2589 * @return array|bool
2591 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2592 // If a given bao does not override this function
2593 $baoName = get_called_class();
2594 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2598 * Populate option labels for this object's fields.
2600 * @throws exception if called directly on the base class
2602 public function getOptionLabels() {
2603 $fields = $this->fields();
2604 if ($fields === NULL) {
2605 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2607 foreach ($fields as $field) {
2608 $name = $field['name'] ??
NULL;
2609 if ($name && isset($this->$name)) {
2610 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2611 if ($label !== FALSE) {
2612 // Append 'label' onto the field name
2613 $labelName = $name . '_label';
2614 $this->$labelName = $label;
2621 * Provides documentation and validation for the buildOptions $context param
2623 * @param string $context
2628 public static function buildOptionsContext($context = NULL) {
2630 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2631 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2632 'search' => "search: searchable options are returned; labels are translated.",
2633 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2634 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2635 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2637 // Validation: enforce uniformity of this param
2638 if ($context !== NULL && !isset($contexts[$context])) {
2639 throw new Exception("'$context' is not a valid context for buildOptions.");
2645 * @param string $fieldName
2646 * @return bool|array
2648 public function getFieldSpec($fieldName) {
2649 $fields = $this->fields();
2650 $fieldKeys = $this->fieldKeys();
2652 // Support "unique names" as well as sql names
2653 $fieldKey = $fieldName;
2654 if (empty($fields[$fieldKey])) {
2655 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2657 // If neither worked then this field doesn't exist. Return false.
2658 if (empty($fields[$fieldKey])) {
2661 return $fields[$fieldKey];
2665 * Get SQL where clause for SQL filter syntax input parameters.
2667 * SQL version of api function to assign filters to the DAO based on the syntax
2668 * $field => array('IN' => array(4,6,9))
2670 * $field => array('LIKE' => array('%me%))
2673 * @param string $fieldName
2675 * @param array $filter
2676 * filter to be applied indexed by operator.
2677 * @param string $type
2678 * type of field (not actually used - nor in api @todo ).
2679 * @param string $alias
2680 * alternative field name ('as') @todo- not actually used.
2681 * @param bool $returnSanitisedArray
2682 * Return a sanitised array instead of a clause.
2683 * this is primarily so we can add filters @ the api level to the Query object based fields
2687 * @return NULL|string|array
2688 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2689 * depending on whether it is supported as yet
2691 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2692 foreach ($filter as $operator => $criteria) {
2693 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2694 switch ($operator) {
2698 if (!$returnSanitisedArray) {
2699 return (sprintf('%s %s', $fieldName, $operator));
2702 return (sprintf('%s %s ', $fieldName, $operator));
2706 // ternary operators
2709 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2710 throw new Exception("invalid criteria for $operator");
2712 if (!$returnSanitisedArray) {
2713 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2716 // not yet implemented (tests required to implement)
2724 if (empty($criteria)) {
2725 throw new Exception("invalid criteria for $operator");
2727 $escapedCriteria = array_map([
2731 if (!$returnSanitisedArray) {
2732 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2734 return $escapedCriteria;
2739 if (!$returnSanitisedArray) {
2740 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2743 // not yet implemented (tests required to implement)
2752 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2753 * support for other syntaxes is discussed in ticket but being put off for now
2756 public static function acceptedSQLOperators() {
2777 * SQL has a limit of 64 characters on various names:
2778 * table name, trigger name, column name ...
2780 * For custom groups and fields we generated names from user entered input
2781 * which can be longer than this length, this function helps with creating
2782 * strings that meet various criteria.
2784 * @param string $string
2785 * The string to be shortened.
2786 * @param int $length
2787 * The max length of the string.
2789 * @param bool $makeRandom
2793 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2794 // early return for strings that meet the requirements
2795 if (strlen($string) <= $length) {
2799 // easy return for calls that dont need a randomized uniq string
2801 return substr($string, 0, $length);
2804 // the string is longer than the length and we need a uniq string
2805 // for the same tablename we need the same uniq string every time
2806 // hence we use md5 on the string, which is not random
2807 // we'll append 8 characters to the end of the tableName
2808 $md5string = substr(md5($string), 0, 8);
2809 return substr($string, 0, $length - 8) . "_{$md5string}";
2813 * https://issues.civicrm.org/jira/browse/CRM-17748
2814 * Sets the internal options to be used on a query
2816 * @param array $options
2819 public function setOptions($options) {
2820 if (is_array($options)) {
2821 $this->_options
= $options;
2826 * https://issues.civicrm.org/jira/browse/CRM-17748
2827 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2829 * @param array $options
2832 protected function _setDBOptions($options) {
2833 global $_DB_DATAOBJECT;
2835 if (is_array($options) && count($options)) {
2836 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2837 foreach ($options as $option_name => $option_value) {
2838 $conn->setOption($option_name, $option_value);
2845 * @param array $params
2847 public function setApiFilter(&$params) {
2851 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2853 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2856 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2860 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2864 public function addSelectWhereClause() {
2866 $fields = $this->fields();
2867 foreach ($fields as $fieldName => $field) {
2868 // Clause for contact-related entities like Email, Relationship, etc.
2869 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2870 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2872 // Clause for an entity_table/entity_id combo
2873 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2874 $relatedClauses = [];
2875 $relatedEntities = $this->buildOptions('entity_table', 'get');
2876 foreach ((array) $relatedEntities as $table => $ent) {
2878 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2879 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2881 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2884 $relatedClauses[] = "(entity_table = '$table')";
2888 if ($relatedClauses) {
2889 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2893 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2898 * This returns the final permissioned query string for this entity
2900 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2902 * @param string $tableAlias
2905 public static function getSelectWhereClause($tableAlias = NULL) {
2906 $bao = new static();
2907 if ($tableAlias === NULL) {
2908 $tableAlias = $bao->tableName();
2911 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2912 $clauses[$field] = NULL;
2914 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2921 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2922 * and dashes, and contains at least one [a-z] case insenstive.
2928 public static function requireSafeDBName($database) {
2931 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2935 if (empty($matches)) {
2942 * Transform an array to a serialized string for database storage.
2944 * @param array|null $value
2945 * @param int $serializationType
2946 * @return string|null
2948 * @throws \Exception
2950 public static function serializeField($value, $serializationType) {
2951 if ($value === NULL) {
2954 switch ($serializationType) {
2955 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2956 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
2958 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2959 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2961 case self
::SERIALIZE_JSON
:
2962 return is_array($value) ?
json_encode($value) : $value;
2964 case self
::SERIALIZE_PHP
:
2965 return is_array($value) ?
serialize($value) : $value;
2967 case self
::SERIALIZE_COMMA
:
2968 return is_array($value) ?
implode(',', $value) : $value;
2971 throw new Exception('Unknown serialization method for field.');
2976 * Transform a serialized string from the database into an array.
2978 * @param string|null $value
2979 * @param $serializationType
2981 * @return array|null
2982 * @throws CRM_Core_Exception
2984 public static function unSerializeField($value, $serializationType) {
2985 if ($value === NULL) {
2988 if ($value === '') {
2991 switch ($serializationType) {
2992 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2993 return (array) CRM_Utils_Array
::explodePadded($value);
2995 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2996 return explode(self
::VALUE_SEPARATOR
, trim($value));
2998 case self
::SERIALIZE_JSON
:
2999 return strlen($value) ?
json_decode($value, TRUE) : [];
3001 case self
::SERIALIZE_PHP
:
3002 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3004 case self
::SERIALIZE_COMMA
:
3005 return explode(',', trim(str_replace(', ', '', $value)));
3008 throw new CRM_Core_Exception('Unknown serialization method for field.');
3015 public static function getEntityRefFilters() {
3020 * Get exportable fields with pseudoconstants rendered as an extra field.
3022 * @param string $baoClass
3026 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3027 if (method_exists($baoClass, 'exportableFields')) {
3028 $fields = $baoClass::exportableFields();
3031 $fields = $baoClass::export();
3033 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3038 * Remove item from static cache during update/delete operations
3040 private function clearDbColumnValueCache() {
3041 $daoName = get_class($this);
3042 while (strpos($daoName, '_BAO_') !== FALSE) {
3043 $daoName = get_parent_class($daoName);
3045 if (isset($this->id
)) {
3046 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3048 if (isset($this->name
)) {
3049 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);