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;
49 * Icon associated with this entity.
53 public static $_icon = NULL;
59 public static $_nullArray = [];
61 public static $_dbColumnValueCache = NULL;
62 const NOT_NULL
= 1, IS_NULL
= 2,
64 VALUE_SEPARATOR
= "\ 1",
65 BULK_INSERT_COUNT
= 200,
66 BULK_INSERT_HIGH_COUNT
= 200,
67 QUERY_FORMAT_WILDCARD
= 1,
68 QUERY_FORMAT_NO_QUOTES
= 2,
71 * Serialized string separated by and bookended with VALUE_SEPARATOR
73 SERIALIZE_SEPARATOR_BOOKEND
= 1,
75 * @deprecated format separated by VALUE_SEPARATOR
77 SERIALIZE_SEPARATOR_TRIMMED
= 2,
79 * Recommended serialization format
83 * @deprecated format using php serialize()
87 * Comma separated string, no quotes, no spaces
92 * Define entities that shouldn't be created or deleted when creating/ deleting
93 * test objects - this prevents world regions, countries etc from being added / deleted
96 public static $_testEntitiesToSkip = [];
98 * The factory class for this application.
101 public static $_factory = NULL;
103 public static $_checkedSqlFunctionsExist = FALSE;
106 * https://issues.civicrm.org/jira/browse/CRM-17748
107 * internal variable for DAO to hold per-query settings
110 protected $_options = [];
115 * @return \CRM_Core_DAO
117 public function __construct() {
119 $this->__table
= $this->getTableName();
123 * Returns localized title of this entity.
126 public static function getEntityTitle() {
127 $className = static::class;
128 Civi
::log()->warning("$className needs to be regeneraged. Missing getEntityTitle method.", ['civi.tag' => 'deprecated']);
129 return CRM_Core_DAO_AllCoreTables
::getBriefName($className);
132 public function __clone() {
133 if (!empty($this->_DB_resultid
)) {
134 $this->resultCopies++
;
141 public function __destruct() {
142 if ($this->resultCopies
=== 0) {
145 $this->resultCopies
--;
149 * Empty definition for virtual function.
151 public static function getTableName() {
156 * Initialize the DAO object.
159 * The database connection string.
161 public static function init($dsn) {
162 Civi
::$statics[__CLASS__
]['init'] = 1;
163 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
164 $options['database'] = $dsn;
165 $options['quote_identifiers'] = TRUE;
166 if (self
::isSSLDSN($dsn)) {
167 // There are two different options arrays.
168 $other_options = &PEAR
::getStaticProperty('DB', 'options');
169 $other_options['ssl'] = TRUE;
171 if (defined('CIVICRM_DAO_DEBUG')) {
172 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
174 $factory = new CRM_Contact_DAO_Factory();
175 CRM_Core_DAO
::setFactory($factory);
176 $currentModes = CRM_Utils_SQL
::getSqlModes();
177 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
178 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
179 $currentModes[] = 'ONLY_FULL_GROUP_BY';
181 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
182 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
184 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
186 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
187 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
193 public static function getConnection() {
194 global $_DB_DATAOBJECT;
195 $dao = new CRM_Core_DAO();
196 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
200 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
202 public static function disableFullGroupByMode() {
203 $currentModes = CRM_Utils_SQL
::getSqlModes();
204 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
205 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
206 unset($currentModes[$key]);
207 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
212 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
214 public static function reenableFullGroupByMode() {
215 $currentModes = CRM_Utils_SQL
::getSqlModes();
216 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
217 $currentModes[] = 'ONLY_FULL_GROUP_BY';
218 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
223 * @param string $fieldName
225 * @param array $params
227 protected function assignTestFK($fieldName, $fieldDef, $params) {
228 $required = $fieldDef['required'] ??
NULL;
229 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
230 $dbName = $fieldDef['name'];
231 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
233 // skip the FK if it is not required
234 // if it's contact id we should create even if not required
235 // we'll have a go @ fetching first though
236 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
237 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
240 if (!$required && $dbName != 'contact_id') {
241 $fkDAO = new $FKClassName();
242 if ($fkDAO->find(TRUE)) {
243 $this->$dbName = $fkDAO->id
;
247 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
248 $depObject = new $FKClassName();
249 $depObject->find(TRUE);
250 $this->$dbName = $depObject->id
;
252 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
253 // FIXME: the fields() metadata is not specific enough
254 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
255 $this->$dbName = $depObject->id
;
258 //if it is required we need to generate the dependency object first
259 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
260 $this->$dbName = $depObject->id
;
265 * Generate and assign an arbitrary value to a field of a test object.
267 * @param string $fieldName
268 * @param array $fieldDef
269 * @param int $counter
270 * The globally-unique ID of the test object.
272 * @throws \CRM_Core_Exception
274 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
275 $dbName = $fieldDef['name'];
276 $daoName = get_class($this);
279 if (!$handled && $dbName == 'contact_sub_type') {
280 //coming up with a rule to set this is too complex let's not set it
284 // Pick an option value if needed
285 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
286 $options = $daoName::buildOptions($dbName, 'create');
288 $this->$dbName = key($options);
294 switch ($fieldDef['type']) {
295 case CRM_Utils_Type
::T_INT
:
296 case CRM_Utils_Type
::T_FLOAT
:
297 case CRM_Utils_Type
::T_MONEY
:
298 if (isset($fieldDef['precision'])) {
299 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
300 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
303 $this->$dbName = $counter;
307 case CRM_Utils_Type
::T_BOOLEAN
:
308 if (isset($fieldDef['default'])) {
309 $this->$dbName = $fieldDef['default'];
311 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
319 case CRM_Utils_Type
::T_DATE
:
320 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
321 $this->$dbName = '19700101';
322 if ($dbName == 'end_date') {
323 // put this in the future
324 $this->$dbName = '20200101';
328 case CRM_Utils_Type
::T_TIMESTAMP
:
329 $this->$dbName = '19700201000000';
332 case CRM_Utils_Type
::T_TIME
:
333 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
335 case CRM_Utils_Type
::T_CCNUM
:
336 $this->$dbName = '4111 1111 1111 1111';
339 case CRM_Utils_Type
::T_URL
:
340 $this->$dbName = 'http://www.civicrm.org';
343 case CRM_Utils_Type
::T_STRING
:
344 case CRM_Utils_Type
::T_BLOB
:
345 case CRM_Utils_Type
::T_MEDIUMBLOB
:
346 case CRM_Utils_Type
::T_TEXT
:
347 case CRM_Utils_Type
::T_LONGTEXT
:
348 case CRM_Utils_Type
::T_EMAIL
:
350 // WAS: if (isset($value['enumValues'])) {
351 // TODO: see if this works with all pseudoconstants
352 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
353 if (isset($fieldDef['default'])) {
354 $this->$dbName = $fieldDef['default'];
357 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
358 if (is_array($options)) {
359 $this->$dbName = $options[0];
362 $defaultValues = explode(',', $options);
363 $this->$dbName = $defaultValues[0];
368 $this->$dbName = $dbName . '_' . $counter;
369 $maxlength = $fieldDef['maxlength'] ??
NULL;
370 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
371 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
379 * Reset the DAO object.
381 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
383 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
385 public function reset() {
387 foreach (array_keys($this->table()) as $field) {
388 unset($this->$field);
392 * reset the various DB_DAO structures manually
401 * @param string $tableName
405 public static function getLocaleTableName($tableName) {
408 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
409 if (in_array($tableName, $tables)) {
410 return $tableName . $dbLocale;
417 * Execute a query by the current DAO, localizing it along the way (if needed).
419 * @param string $query
420 * The SQL query for execution.
421 * @param bool $i18nRewrite
422 * Whether to rewrite the query.
425 * the current DAO object after the query execution
427 public function query($query, $i18nRewrite = TRUE) {
428 // rewrite queries that should use $dbLocale-based views for multi-language installs
429 global $dbLocale, $_DB_DATAOBJECT;
431 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
432 // Will force connection to be populated per CRM-20541.
436 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
437 $orig_options = $conn->options
;
438 $this->_setDBOptions($this->_options
);
440 if ($i18nRewrite and $dbLocale) {
441 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
444 $ret = parent
::query($query);
446 $this->_setDBOptions($orig_options);
451 * Static function to set the factory instance for this class.
453 * @param object $factory
454 * The factory application object.
456 public static function setFactory(&$factory) {
457 self
::$_factory = &$factory;
461 * Factory method to instantiate a new object from a table name.
463 * @param string $table
464 * @return \DataObject|\PEAR_Error
466 public function factory($table = '') {
467 if (!isset(self
::$_factory)) {
468 return parent
::factory($table);
471 return self
::$_factory->create($table);
475 * Initialization for all DAO objects. Since we access DB_DO programatically
476 * we need to set the links manually.
478 public function initialize() {
480 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
481 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
482 // This occurs very early in bootstrap - error handlers may not be wired up.
483 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
484 CRM_Utils_System
::civiExit();
489 * Defines the default key as 'id'.
493 public function keys() {
502 * Tells DB_DataObject which keys use autoincrement.
503 * 'id' is autoincrementing by default.
508 public function sequenceKey() {
509 static $sequenceKeys;
510 if (!isset($sequenceKeys)) {
511 $sequenceKeys = ['id', TRUE];
513 return $sequenceKeys;
517 * Returns list of FK relationships.
521 * Array of CRM_Core_Reference_Interface
523 public static function getReferenceColumns() {
528 * Returns all the column names of this table.
533 public static function &fields() {
539 * Returns all usable fields, indexed by name.
541 * This function differs from fields() in that it indexes by name rather than unique_name.
543 * It excludes fields not added yet by pending upgrades.
544 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
546 * @param bool $checkPermissions
547 * Filter by field permissions.
550 public static function getSupportedFields($checkPermissions = FALSE) {
551 $fields = array_column((array) static::fields(), NULL, 'name');
553 // Exclude fields yet not added by pending upgrades
554 $dbVer = \CRM_Core_BAO_Domain
::version();
555 if ($fields && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
556 $fields = array_filter($fields, function($field) use ($dbVer) {
557 $add = $field['add'] ??
'1.0.0';
558 if (substr_count($add, '.') < 2) {
561 return version_compare($dbVer, $add, '>=');
565 // Exclude fields the user does not have permission for
566 if ($checkPermissions) {
567 $fields = array_filter($fields, function($field) {
568 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
576 * Get/set an associative array of table columns
581 public function table() {
582 $fields = $this->fields();
586 foreach ($fields as $name => $value) {
587 $table[$value['name']] = $value['type'];
588 if (!empty($value['required'])) {
589 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
602 * @return CRM_Core_DAO
604 public function save($hook = TRUE) {
605 if (!empty($this->id
)) {
607 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
608 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
611 $result = $this->update();
614 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
615 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
617 $this->clearDbColumnValueCache();
621 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
622 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
625 $result = $this->insert();
628 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
629 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
635 CRM_Utils_Hook
::postSave($this);
642 * Deletes items from table which match current objects variables.
644 * Returns the true on success
648 * Designed to be extended
650 * $object = new mytable();
652 * echo $object->delete(); // builds a conditon
654 * $object = new mytable();
655 * $object->whereAdd('age > 12');
657 * $object->orderBy('age DESC');
658 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
660 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
661 * we will build the condition only using the whereAdd's. Default is to
662 * build the condition only using the object parameters.
664 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
666 public function delete($useWhere = FALSE) {
667 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
668 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
670 $result = parent
::delete($useWhere);
672 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
673 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
676 $this->clearDbColumnValueCache();
682 * @param bool $created
684 public function log($created = FALSE) {
687 if (!$this->getLog()) {
692 $session = CRM_Core_Session
::singleton();
693 $cid = $session->get('userID');
696 // return is we dont have handle to FK
701 $dao = new CRM_Core_DAO_Log();
702 $dao->entity_table
= $this->getTableName();
703 $dao->entity_id
= $this->id
;
704 $dao->modified_id
= $cid;
705 $dao->modified_date
= date("YmdHis");
710 * Given an associative array of name/value pairs, extract all the values
711 * that belong to this object and initialize the object with said values
713 * @param array $params
714 * Array of name/value pairs to save.
717 * Did we copy all null values into the object
719 public function copyValues($params) {
721 foreach ($this->fields() as $uniqueName => $field) {
722 $dbName = $field['name'];
723 if (array_key_exists($dbName, $params)) {
724 $value = $params[$dbName];
727 elseif (array_key_exists($uniqueName, $params)) {
728 $value = $params[$uniqueName];
735 // if there is no value then make the variable NULL
738 $this->$dbName = 'null';
740 elseif (is_array($value) && !empty($field['serialize'])) {
741 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
745 $maxLength = $field['maxlength'] ??
NULL;
746 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
747 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($value, 'String')]));
748 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
749 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
751 $this->$dbName = $value;
760 * Store all the values from this object in an associative array
761 * this is a destructive store, calling function is responsible
762 * for keeping sanity of id's.
764 * @param object $object
765 * The object that we are extracting data from.
766 * @param array $values
767 * (reference ) associative array of name/value pairs.
769 public static function storeValues(&$object, &$values) {
770 $fields = $object->fields();
771 foreach ($fields as $name => $value) {
772 $dbName = $value['name'];
773 if (isset($object->$dbName) && $object->$dbName !== 'null') {
774 $values[$dbName] = $object->$dbName;
775 if ($name != $dbName) {
776 $values[$name] = $object->$dbName;
783 * Create an attribute for this specific field. We only do this for strings and text
785 * @param array $field
786 * The field under task.
789 * the attributes for the object
791 public static function makeAttribute($field) {
793 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
794 $maxLength = $field['maxlength'] ??
NULL;
795 $size = $field['size'] ??
NULL;
796 if ($maxLength ||
$size) {
799 $attributes['maxlength'] = $maxLength;
802 $attributes['size'] = $size;
807 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
808 $rows = $field['rows'] ??
NULL;
812 $cols = $field['cols'] ??
NULL;
818 $attributes['rows'] = $rows;
819 $attributes['cols'] = $cols;
822 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
) {
823 $attributes['size'] = 6;
824 $attributes['maxlength'] = 14;
832 * Get the size and maxLength attributes for this text field.
833 * (or for all text fields) in the DAO object.
835 * @param string $class
837 * @param string $fieldName
838 * Field that i'm interested in or null if.
839 * you want the attributes for all DAO text fields
842 * assoc array of name => attribute pairs
844 public static function getAttribute($class, $fieldName = NULL) {
845 $object = new $class();
846 $fields = $object->fields();
847 if ($fieldName != NULL) {
848 $field = $fields[$fieldName] ??
NULL;
849 return self
::makeAttribute($field);
853 foreach ($fields as $name => $field) {
854 $attribute = self
::makeAttribute($field);
856 $attributes[$name] = $attribute;
860 if (!empty($attributes)) {
868 * Create or update a record from supplied params.
870 * If 'id' is supplied, an existing record will be updated
871 * Otherwise a new record will be created.
873 * @param array $record
874 * @return CRM_Core_DAO
875 * @throws CRM_Core_Exception
877 public static function writeRecord(array $record) {
878 $hook = empty($record['id']) ?
'create' : 'edit';
879 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
880 if ($className === 'CRM_Core_DAO') {
881 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
883 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
885 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
886 $instance = new $className();
887 $instance->copyValues($record);
889 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
895 * Delete a record from supplied params.
897 * @param array $record
899 * @return CRM_Core_DAO
900 * @throws CRM_Core_Exception
902 public static function deleteRecord(array $record) {
903 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
904 if ($className === 'CRM_Core_DAO') {
905 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
907 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
908 if (empty($record['id'])) {
909 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
912 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
913 $instance = new $className();
914 $instance->id
= $record['id'];
915 if (!$instance->delete()) {
916 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
918 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
924 * Check if there is a record with the same name in the db.
926 * @param string $value
927 * The value of the field we are checking.
928 * @param string $daoName
929 * The dao object name.
930 * @param string $daoID
931 * The id of the object being updated. u can change your name.
932 * as long as there is no conflict
933 * @param string $fieldName
934 * The name of the field in the DAO.
936 * @param string $domainID
937 * The id of the domain. Object exists only for the given domain.
940 * true if object exists
942 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
943 $object = new $daoName();
944 $object->$fieldName = $value;
946 $object->domain_id
= $domainID;
949 if ($object->find(TRUE)) {
950 return $daoID && $object->id
== $daoID;
958 * Check if there is a given column in a specific table.
961 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
963 * @param string $tableName
964 * @param string $columnName
965 * @param bool $i18nRewrite
966 * Whether to rewrite the query on multilingual setups.
969 * true if exists, else false
971 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
972 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
973 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
977 * Scans all the tables using a slow query and table name.
981 public static function getTableNames() {
982 $dao = CRM_Core_DAO
::executeQuery(
984 FROM information_schema.TABLES
985 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
986 AND TABLE_NAME LIKE 'civicrm_%'
987 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
988 AND TABLE_NAME NOT LIKE '%_temp%'
991 while ($dao->fetch()) {
992 $values[] = $dao->TABLE_NAME
;
998 * @param int $maxTablesToCheck
1002 public static function isDBMyISAM($maxTablesToCheck = 10) {
1003 return CRM_Core_DAO
::singleValueQuery(
1005 FROM information_schema.TABLES
1006 WHERE ENGINE = 'MyISAM'
1007 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1008 AND TABLE_NAME LIKE 'civicrm_%'
1009 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1010 AND TABLE_NAME NOT LIKE '%_temp%'
1011 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1016 * Get the name of the CiviCRM database.
1020 public static function getDatabaseName() {
1021 $daoObj = new CRM_Core_DAO();
1022 return $daoObj->database();
1026 * Checks if a constraint exists for a specified table.
1028 * @param string $tableName
1029 * @param string $constraint
1032 * true if constraint exists, false otherwise
1034 * @throws \CRM_Core_Exception
1036 public static function checkConstraintExists($tableName, $constraint) {
1039 if (!array_key_exists($tableName, $show)) {
1040 $query = "SHOW CREATE TABLE $tableName";
1041 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1043 if (!$dao->fetch()) {
1044 throw new CRM_Core_Exception('query failed');
1047 $show[$tableName] = $dao->Create_Table
;
1050 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1054 * Checks if CONSTRAINT keyword exists for a specified table.
1056 * @param array $tables
1058 * @throws CRM_Core_Exception
1061 * true if CONSTRAINT keyword exists, false otherwise
1063 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1065 foreach ($tables as $tableName) {
1066 if (!array_key_exists($tableName, $show)) {
1067 $query = "SHOW CREATE TABLE $tableName";
1068 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1070 if (!$dao->fetch()) {
1071 throw new CRM_Core_Exception('Show create table failed.');
1074 $show[$tableName] = $dao->Create_Table
;
1077 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1078 if ($result == TRUE) {
1089 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1090 * for a specified column of a table.
1092 * @param string $tableName
1093 * @param string $columnName
1096 * true if in format, false otherwise
1098 * @throws \CRM_Core_Exception
1100 public static function checkFKConstraintInFormat($tableName, $columnName) {
1103 if (!array_key_exists($tableName, $show)) {
1104 $query = "SHOW CREATE TABLE $tableName";
1105 $dao = CRM_Core_DAO
::executeQuery($query);
1107 if (!$dao->fetch()) {
1108 throw new CRM_Core_Exception('query failed');
1111 $show[$tableName] = $dao->Create_Table
;
1113 $constraint = "`FK_{$tableName}_{$columnName}`";
1114 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1115 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1119 * Check whether a specific column in a specific table has always the same value.
1121 * @param string $tableName
1122 * @param string $columnName
1123 * @param string $columnValue
1126 * true if the value is always $columnValue, false otherwise
1128 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1129 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1130 $dao = CRM_Core_DAO
::executeQuery($query);
1131 $result = $dao->fetch() ?
FALSE : TRUE;
1136 * Check whether a specific column in a specific table is always NULL.
1138 * @param string $tableName
1139 * @param string $columnName
1142 * true if if the value is always NULL, false otherwise
1144 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1145 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1146 $dao = CRM_Core_DAO
::executeQuery($query);
1147 $result = $dao->fetch() ?
FALSE : TRUE;
1152 * Check if there is a given table in the database.
1154 * @param string $tableName
1157 * true if exists, else false
1159 public static function checkTableExists($tableName) {
1164 $params = [1 => [$tableName, 'String']];
1166 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1167 return (bool) $dao->fetch();
1171 * Check if a given table has data.
1173 * @param string $tableName
1175 * TRUE if $tableName has at least one record.
1177 public static function checkTableHasData($tableName) {
1178 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1187 public function checkVersion($version) {
1192 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1193 return trim($version) == trim($dbVersion);
1197 * Find a DAO object for the given ID and return it.
1200 * Id of the DAO object being searched for.
1202 * @return CRM_Core_DAO
1203 * Object of the type of the class that called this function.
1207 public static function findById($id) {
1208 $object = new static();
1210 if (!$object->find(TRUE)) {
1211 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1217 * Returns all results as array-encoded records.
1221 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1223 while ($this->fetch()) {
1224 $result[] = $this->toArray();
1230 * Return the results as PHP generator.
1232 * @param string $type
1233 * Whether the generator yields 'dao' objects or 'array's.
1235 public function fetchGenerator($type = 'dao') {
1236 while ($this->fetch()) {
1243 yield
$this->toArray();
1247 throw new \
RuntimeException("Invalid record type ($type)");
1253 * Returns a singular value.
1255 * @return mixed|NULL
1257 public function fetchValue() {
1258 $result = $this->getDatabaseResult();
1259 $row = $result->fetchRow();
1269 * Get all the result records as mapping between columns.
1271 * @param string $keyColumn
1273 * @param string $valueColumn
1276 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1278 public function fetchMap($keyColumn, $valueColumn) {
1280 while ($this->fetch()) {
1281 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1287 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1289 * @param string $daoName
1290 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1291 * @param int $searchValue
1292 * Value of the column you want to search by.
1293 * @param string $returnColumn
1294 * Name of the column you want to GET the value of.
1295 * @param string $searchColumn
1296 * Name of the column you want to search by.
1297 * @param bool $force
1298 * Skip use of the cache.
1300 * @return string|int|null
1301 * Value of $returnColumn in the retrieved record
1303 * @throws \CRM_Core_Exception
1305 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1307 empty($searchValue) ||
1308 trim(strtolower($searchValue)) == 'null'
1310 // adding this here since developers forget to check for an id
1311 // or for the 'null' (which is a bad DAO kludge)
1312 // and hence we get the first value in the db
1313 throw new CRM_Core_Exception('getFieldValue failed');
1316 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1318 while (strpos($daoName, '_BAO_') !== FALSE) {
1319 $daoName = get_parent_class($daoName);
1323 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1324 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1326 $object = new $daoName();
1327 $object->$searchColumn = $searchValue;
1328 $object->selectAdd();
1329 $object->selectAdd($returnColumn);
1332 if ($object->find(TRUE)) {
1333 $result = $object->$returnColumn;
1336 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1338 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1342 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1344 * @param string $daoName
1345 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1346 * @param int $searchValue
1347 * Value of the column you want to search by.
1348 * @param string $setColumn
1349 * Name of the column you want to SET the value of.
1350 * @param string $setValue
1351 * SET the setColumn to this value.
1352 * @param string $searchColumn
1353 * Name of the column you want to search by.
1356 * true if we found and updated the object, else false
1358 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1359 $object = new $daoName();
1360 $object->selectAdd();
1361 $object->selectAdd("$searchColumn, $setColumn");
1362 $object->$searchColumn = $searchValue;
1364 if ($object->find(TRUE)) {
1365 $object->$setColumn = $setValue;
1366 if ($object->save()) {
1377 * @param array|object $sort either array or CRM_Utils_Sort
1378 * @param string $default
1379 * Default sort value.
1383 public static function getSortString($sort, $default = NULL) {
1384 // check if sort is of type CRM_Utils_Sort
1385 if (is_a($sort, 'CRM_Utils_Sort')) {
1386 return $sort->orderBy();
1391 // is it an array specified as $field => $sortDirection ?
1393 foreach ($sort as $k => $v) {
1394 $sortString .= "$k $v,";
1396 return rtrim($sortString, ',');
1402 * Fetch object based on array of properties.
1404 * @param string $daoName
1405 * Name of the dao object.
1406 * @param array $params
1407 * (reference ) an assoc array of name/value pairs.
1408 * @param array $defaults
1409 * (reference ) an assoc array to hold the flattened values.
1410 * @param array $returnProperities
1411 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1414 * an object of type referenced by daoName
1416 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1417 $object = new $daoName();
1418 $object->copyValues($params);
1420 // return only specific fields if returnproperties are sent
1421 if (!empty($returnProperities)) {
1422 $object->selectAdd();
1423 $object->selectAdd(implode(',', $returnProperities));
1426 if ($object->find(TRUE)) {
1427 self
::storeValues($object, $defaults);
1434 * Delete the object records that are associated with this contact.
1436 * @param string $daoName
1437 * Name of the dao object.
1438 * @param int $contactId
1439 * Id of the contact to delete.
1441 public static function deleteEntityContact($daoName, $contactId) {
1442 $object = new $daoName();
1444 $object->entity_table
= 'civicrm_contact';
1445 $object->entity_id
= $contactId;
1450 * Execute an unbuffered query.
1452 * This is a wrapper around new functionality exposed with CRM-17748.
1454 * @param string $query query to be executed
1456 * @param array $params
1457 * @param bool $abort
1458 * @param null $daoName
1459 * @param bool $freeDAO
1460 * @param bool $i18nRewrite
1461 * @param bool $trapException
1463 * @return CRM_Core_DAO
1464 * Object that points to an unbuffered result set
1466 public static function executeUnbufferedQuery(
1472 $i18nRewrite = TRUE,
1473 $trapException = FALSE
1476 return self
::executeQuery(
1484 ['result_buffering' => 0]
1491 * @param string $query
1492 * Query to be executed.
1494 * @param array $params
1495 * @param bool $abort
1496 * @param null $daoName
1497 * @param bool $freeDAO
1498 * @param bool $i18nRewrite
1499 * @param bool $trapException
1500 * @param array $options
1502 * @return CRM_Core_DAO|object
1503 * object that holds the results of the query
1504 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1505 * out all the properties that are not part of the DAO
1507 public static function &executeQuery(
1513 $i18nRewrite = TRUE,
1514 $trapException = FALSE,
1517 $queryStr = self
::composeQuery($query, $params, $abort);
1520 $dao = new CRM_Core_DAO();
1523 $dao = new $daoName();
1526 if ($trapException) {
1527 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1530 if ($dao->isValidOption($options)) {
1531 $dao->setOptions($options);
1534 $result = $dao->query($queryStr, $i18nRewrite);
1536 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1537 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1541 if (is_a($result, 'DB_Error')) {
1549 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1551 * @param array $options
1554 * Provided options are valid
1556 public function isValidOption($options) {
1565 if (empty($options)) {
1569 foreach (array_keys($options) as $option) {
1570 if (!in_array($option, $validOptions)) {
1580 * Execute a query and get the single result.
1582 * @param string $query
1583 * Query to be executed.
1584 * @param array $params
1585 * @param bool $abort
1586 * @param bool $i18nRewrite
1587 * @return string|null
1588 * the result of the query if any
1591 public static function &singleValueQuery(
1597 $queryStr = self
::composeQuery($query, $params, $abort);
1599 static $_dao = NULL;
1602 $_dao = new CRM_Core_DAO();
1605 $_dao->query($queryStr, $i18nRewrite);
1607 $result = $_dao->getDatabaseResult();
1610 $row = $result->fetchRow();
1620 * Compose the query by merging the parameters into it.
1622 * @param string $query
1623 * @param array $params
1624 * @param bool $abort
1627 * @throws CRM_Core_Exception
1629 public static function composeQuery($query, $params = [], $abort = TRUE) {
1631 foreach ($params as $key => $item) {
1632 if (is_numeric($key)) {
1633 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1634 $item[0] = self
::escapeString($item[0]);
1635 if ($item[1] == 'String' ||
1636 $item[1] == 'Memo' ||
1639 // Support class constants stipulating wildcard characters and/or
1640 // non-quoting of strings. Also support legacy code which may be
1641 // passing in TRUE or 1 for $item[2], which used to indicate the
1642 // use of wildcard characters.
1643 if (!empty($item[2])) {
1644 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1645 $item[0] = "'%{$item[0]}%'";
1647 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1648 $item[0] = "'{$item[0]}'";
1652 $item[0] = "'{$item[0]}'";
1656 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1657 strlen($item[0]) == 0
1662 $tr['%' . $key] = $item[0];
1665 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1670 return strtr($query, $tr);
1676 public static function freeResult($ids = NULL) {
1677 global $_DB_DATAOBJECT;
1680 if (!$_DB_DATAOBJECT ||
1681 !isset($_DB_DATAOBJECT['RESULTS'])
1685 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1688 foreach ($ids as $id) {
1689 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1690 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1691 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1694 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1695 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1701 * Make a shallow copy of an object and all the fields in the object.
1703 * @param string $daoName
1705 * @param array $criteria
1706 * Array of all the fields & values.
1707 * on which basis to copy
1708 * @param array $newData
1709 * Array of all the fields & values.
1710 * to be copied besides the other fields
1711 * @param string $fieldsFix
1712 * Array of fields that you want to prefix/suffix/replace.
1713 * @param string $blockCopyOfDependencies
1714 * Fields that you want to block from.
1716 * @param bool $blockCopyofCustomValues
1717 * Case when you don't want to copy the custom values set in a
1718 * template as it will override/ignore the submitted custom values
1720 * @return CRM_Core_DAO|bool
1721 * the newly created copy of the object. False if none created.
1723 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1724 $object = new $daoName();
1727 $object->id
= $criteria['id'];
1730 foreach ($criteria as $key => $value) {
1731 $object->$key = $value;
1736 while ($object->fetch()) {
1738 // all the objects except with $blockCopyOfDependencies set
1739 // be copied - addresses #CRM-1962
1741 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1745 $newObject = new $daoName();
1747 $fields = $object->fields();
1748 if (!is_array($fieldsFix)) {
1749 $fieldsToPrefix = [];
1750 $fieldsToSuffix = [];
1751 $fieldsToReplace = [];
1753 if (!empty($fieldsFix['prefix'])) {
1754 $fieldsToPrefix = $fieldsFix['prefix'];
1756 if (!empty($fieldsFix['suffix'])) {
1757 $fieldsToSuffix = $fieldsFix['suffix'];
1759 if (!empty($fieldsFix['replace'])) {
1760 $fieldsToReplace = $fieldsFix['replace'];
1763 foreach ($fields as $name => $value) {
1764 if ($name == 'id' ||
$value['name'] == 'id') {
1765 // copy everything but the id!
1769 $dbName = $value['name'];
1770 $type = CRM_Utils_Type
::typeToString($value['type']);
1771 $newObject->$dbName = $object->$dbName;
1772 if (isset($fieldsToPrefix[$dbName])) {
1773 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1775 if (isset($fieldsToSuffix[$dbName])) {
1776 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1778 if (isset($fieldsToReplace[$dbName])) {
1779 $newObject->$dbName = $fieldsToReplace[$dbName];
1782 if ($type == 'Timestamp' ||
$type == 'Date') {
1783 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1787 $newObject->copyValues($newData);
1791 if (!$blockCopyofCustomValues) {
1792 $newObject->copyCustomFields($object->id
, $newObject->id
);
1794 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1801 * Method that copies custom fields values from an old entity to a new one.
1803 * Fixes bug CRM-19302,
1804 * where if a custom field of File type was present, left both events using the same file,
1805 * breaking download URL's for the old event.
1807 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1808 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1810 * @param int $entityID
1811 * @param int $newEntityID
1813 public function copyCustomFields($entityID, $newEntityID) {
1814 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1815 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1816 // Obtain custom values for old event
1817 $customParams = $htmlType = [];
1818 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1820 // If custom values present, we copy them
1821 if (!empty($customValues)) {
1822 // Get Field ID's and identify File type attributes, to handle file copying.
1823 $fieldIds = implode(', ', array_keys($customValues));
1824 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1825 $result = CRM_Core_DAO
::executeQuery($sql);
1827 // Build array of File type fields
1828 while ($result->fetch()) {
1829 $htmlType[] = $result->id
;
1832 // Build params array of custom values
1833 foreach ($customValues as $field => $value) {
1834 if ($value !== NULL) {
1835 // Handle File type attributes
1836 if (in_array($field, $htmlType)) {
1837 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1838 $customParams["custom_{$field}_-1"] = [
1839 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1840 'type' => $fileValues[1],
1843 // Handle other types
1845 $customParams["custom_{$field}_-1"] = $value;
1850 // Save Custom Fields for new Event
1851 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1854 // copy activity attachments ( if any )
1855 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1859 * Cascade update through related entities.
1861 * @param string $daoName
1864 * @param array $newData
1866 * @return CRM_Core_DAO|null
1868 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1869 $object = new $daoName();
1870 $object->id
= $fromId;
1872 if ($object->find(TRUE)) {
1873 $newObject = new $daoName();
1874 $newObject->id
= $toId;
1876 if ($newObject->find(TRUE)) {
1877 $fields = $object->fields();
1878 foreach ($fields as $name => $value) {
1879 if ($name == 'id' ||
$value['name'] == 'id') {
1880 // copy everything but the id!
1884 $colName = $value['name'];
1885 $newObject->$colName = $object->$colName;
1887 if (substr($name, -5) == '_date' ||
1888 substr($name, -10) == '_date_time'
1890 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1893 foreach ($newData as $k => $v) {
1894 $newObject->$k = $v;
1904 * Given the component id, compute the contact id
1905 * since its used for things like send email
1907 * @param $componentIDs
1908 * @param string $tableName
1909 * @param string $idField
1913 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1916 if (empty($componentIDs)) {
1920 $IDs = implode(',', $componentIDs);
1924 WHERE $idField IN ( $IDs )
1927 $dao = CRM_Core_DAO
::executeQuery($query);
1928 while ($dao->fetch()) {
1929 $contactIDs[] = $dao->contact_id
;
1935 * Fetch object based on array of properties.
1937 * @param string $daoName
1938 * Name of the dao object.
1939 * @param string $fieldIdName
1940 * @param int $fieldId
1942 * @param array $returnProperities
1943 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1946 * an object of type referenced by daoName
1948 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1949 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1950 $object = new $daoName();
1951 $object->$fieldIdName = $fieldId;
1953 // return only specific fields if returnproperties are sent
1954 if (!empty($returnProperities)) {
1955 $object->selectAdd();
1956 $object->selectAdd('id');
1957 $object->selectAdd(implode(',', $returnProperities));
1961 while ($object->fetch()) {
1963 self
::storeValues($object, $defaults);
1964 $details[$object->id
] = $defaults;
1971 * Drop all CiviCRM tables.
1973 * @throws \CRM_Core_Exception
1975 public static function dropAllTables() {
1977 // first drop all the custom tables we've created
1978 CRM_Core_BAO_CustomGroup
::dropAllTables();
1980 // drop all multilingual views
1981 CRM_Core_I18n_Schema
::dropAllViews();
1983 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1984 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1985 '..' . DIRECTORY_SEPARATOR
.
1986 '..' . DIRECTORY_SEPARATOR
.
1987 'sql' . DIRECTORY_SEPARATOR
.
1988 'civicrm_drop.mysql'
1997 public static function escapeString($string) {
1998 static $_dao = NULL;
2000 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2001 // has been installed), then we fallback DB-less str_replace escaping, as
2002 // we can't use mysqli_real_escape_string, as there is no DB connection.
2003 // Note: In typical usage, escapeString() will only check one conditional
2004 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2005 if (!defined('CIVICRM_DSN')) {
2006 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2007 // list of characters mysqli_real_escape_string escapes.
2008 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2009 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2010 return str_replace($search, $replace, $string);
2012 $_dao = new CRM_Core_DAO();
2014 return $_dao->escape($string);
2018 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2020 * @param array $strings
2021 * @param string $default
2022 * the value to use if $strings has no elements.
2024 * eg "abc","def","ghi"
2026 public static function escapeStrings($strings, $default = NULL) {
2027 static $_dao = NULL;
2029 $_dao = new CRM_Core_DAO();
2032 if (empty($strings)) {
2036 $escapes = array_map([$_dao, 'escape'], $strings);
2037 return '"' . implode('","', $escapes) . '"';
2045 public static function escapeWildCardString($string) {
2047 // ensure we escape the single characters % and _ which are mysql wild
2048 // card characters and could come in via sortByCharacter
2049 // note that mysql does not escape these characters
2050 if ($string && in_array($string,
2051 ['%', '_', '%%', '_%']
2054 return '\\' . $string;
2057 return self
::escapeString($string);
2061 * Creates a test object, including any required objects it needs via recursion
2062 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2063 * ONLY USE FOR TESTING
2065 * @param string $daoName
2066 * @param array $params
2067 * @param int $numObjects
2068 * @param bool $createOnly
2070 * @return object|array|NULL
2071 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2073 public static function createTestObject(
2079 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2080 // so we re-set here in case
2081 $config = CRM_Core_Config
::singleton();
2082 $config->backtrace
= TRUE;
2084 static $counter = 0;
2085 CRM_Core_DAO
::$_testEntitiesToSkip = [
2086 'CRM_Core_DAO_Worldregion',
2087 'CRM_Core_DAO_StateProvince',
2088 'CRM_Core_DAO_Country',
2089 'CRM_Core_DAO_Domain',
2090 'CRM_Financial_DAO_FinancialType',
2091 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2094 // Prefer to instantiate BAO's instead of DAO's (when possible)
2095 // so that assignTestValue()/assignTestFK() can be overloaded.
2096 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2097 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2098 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2099 // @todo create a new class called what the BAO SHOULD be
2100 // that extends BAO-crazy-name.... migrate.
2101 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2103 if (class_exists($baoName)) {
2104 $daoName = $baoName;
2107 for ($i = 0; $i < $numObjects; ++
$i) {
2110 /** @var CRM_Core_DAO $object */
2111 $object = new $daoName();
2113 $fields = $object->fields();
2114 foreach ($fields as $fieldName => $fieldDef) {
2115 $dbName = $fieldDef['name'];
2116 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2118 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2119 $object->$dbName = $params[$dbName];
2122 elseif ($dbName != 'id') {
2123 if ($FKClassName != NULL) {
2124 $object->assignTestFK($fieldName, $fieldDef, $params);
2128 $object->assignTestValue($fieldName, $fieldDef, $counter);
2136 $objects[$i] = $object;
2146 elseif ($numObjects == 1) {
2155 * Deletes the this object plus any dependent objects that are associated with it.
2156 * ONLY USE FOR TESTING
2158 * @param string $daoName
2159 * @param array $params
2161 public static function deleteTestObjects($daoName, $params = []) {
2162 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2163 // so we re-set here in case
2164 $config = CRM_Core_Config
::singleton();
2165 $config->backtrace
= TRUE;
2167 $object = new $daoName();
2168 $object->id
= $params['id'] ??
NULL;
2170 // array(array(0 => $daoName, 1 => $daoParams))
2172 if ($object->find(TRUE)) {
2174 $fields = $object->fields();
2175 foreach ($fields as $name => $value) {
2177 $dbName = $value['name'];
2179 $FKClassName = $value['FKClassName'] ??
NULL;
2180 $required = $value['required'] ??
NULL;
2181 if ($FKClassName != NULL
2183 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2184 && ($required ||
$dbName == 'contact_id')
2185 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2186 // to make this test process pass - line below makes pass for now
2187 && $dbName != 'member_of_contact_id'
2190 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2197 foreach ($deletions as $deletion) {
2198 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2203 * Set defaults when creating new entity.
2204 * (don't call this set defaults as already in use with different signature in some places)
2206 * @param array $params
2209 public static function setCreateDefaults(&$params, $defaults) {
2210 if (!empty($params['id'])) {
2213 foreach ($defaults as $key => $value) {
2214 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2215 $params[$key] = $value;
2221 * @param string $prefix
2222 * @param bool $addRandomString
2223 * @param null $string
2227 * @see CRM_Utils_SQL_TempTable
2229 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2230 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2231 $tableName = $prefix . "_temp";
2233 if ($addRandomString) {
2235 $tableName .= "_" . $string;
2238 $tableName .= "_" . md5(uniqid('', TRUE));
2246 * @param bool $trigger
2250 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2251 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2254 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2256 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2257 CRM_Core_TemporaryErrorScope
::ignoreException();
2258 $dao = new CRM_Core_DAO();
2260 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2261 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2267 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2268 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2270 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2275 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2276 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2278 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2285 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2286 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2295 * @param null $message
2296 * @param bool $printDAO
2298 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2299 CRM_Utils_System
::xMemory("{$message}: ");
2302 global $_DB_DATAOBJECT;
2304 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2305 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2307 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2312 * Build a list of triggers via hook and add them to (err, reconcile them
2313 * with) the database.
2315 * @param string $tableName
2316 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2317 * @param bool $force
2322 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2323 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2327 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2328 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2329 * TODO: Alternative solutions might be
2330 * * Stop using functions and find another way to strip numeric characters from phones
2331 * * Give better error messages (currently a missing fn fatals with "unknown error")
2333 public static function checkSqlFunctionsExist() {
2334 if (!self
::$_checkedSqlFunctionsExist) {
2335 self
::$_checkedSqlFunctionsExist = TRUE;
2336 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2337 if (!$dao->fetch()) {
2338 self
::triggerRebuild();
2344 * Wrapper function to drop triggers.
2346 * @param string $tableName
2347 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2350 public static function dropTriggers($tableName = NULL) {
2351 Civi
::service('sql_triggers')->dropTriggers($tableName);
2355 * @param array $info
2356 * per hook_civicrm_triggerInfo.
2357 * @param string $onlyTableName
2358 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2361 public static function createTriggers(&$info, $onlyTableName = NULL) {
2362 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2366 * Given a list of fields, create a list of references.
2368 * @param string $className
2369 * BAO/DAO class name.
2370 * @return array<CRM_Core_Reference_Interface>
2372 public static function createReferenceColumns($className) {
2374 $fields = $className::fields();
2375 foreach ($fields as $field) {
2376 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2377 $result[] = new CRM_Core_Reference_OptionValue(
2378 $className::getTableName(),
2380 'civicrm_option_value',
2381 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2382 $field['pseudoconstant']['optionGroupName']
2390 * Find all records which refer to this entity.
2393 * Array of objects referencing this
2395 public function findReferences() {
2396 $links = self
::getReferencesToTable(static::getTableName());
2399 foreach ($links as $refSpec) {
2400 /** @var $refSpec CRM_Core_Reference_Interface */
2401 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2402 $result = $refSpec->findReferences($this);
2404 while ($result->fetch()) {
2405 $obj = new $daoName();
2406 $obj->id
= $result->id
;
2407 $occurrences[] = $obj;
2412 return $occurrences;
2417 * each item has keys:
2421 * - table: string|null SQL table name
2422 * - key: string|null SQL column name
2424 public function getReferenceCounts() {
2425 $links = self
::getReferencesToTable(static::getTableName());
2428 foreach ($links as $refSpec) {
2429 /** @var $refSpec CRM_Core_Reference_Interface */
2430 $count = $refSpec->getReferenceCount($this);
2431 if ($count['count'] != 0) {
2436 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2437 /** @var $component CRM_Core_Component_Info */
2438 $counts = array_merge($counts, $component->getReferenceCounts($this));
2440 CRM_Utils_Hook
::referenceCounts($this, $counts);
2446 * List all tables which have hard foreign keys to this table.
2448 * For now, this returns a description of every entity_id/entity_table
2450 * TODO: filter dynamic entity references on the $tableName, based on
2451 * schema metadata in dynamicForeignKey which enumerates a restricted
2452 * set of possible entity_table's.
2454 * @param string $tableName
2455 * Table referred to.
2458 * structure of table and column, listing every table with a
2459 * foreign key reference to $tableName, and the column where the key appears.
2461 public static function getReferencesToTable($tableName) {
2463 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2464 $links = $daoClassName::getReferenceColumns();
2466 foreach ($links as $refSpec) {
2467 /** @var $refSpec CRM_Core_Reference_Interface */
2468 if ($refSpec->matchesTargetTable($tableName)) {
2469 $refsFound[] = $refSpec;
2477 * Get all references to contact table.
2479 * This includes core tables, custom group tables, tables added by the merge
2480 * hook and the entity_tag table.
2482 * Refer to CRM-17454 for information on the danger of querying the information
2483 * schema to derive this.
2485 * @throws \CiviCRM_API3_Exception
2487 public static function getReferencesToContactTable() {
2488 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2489 return \Civi
::$statics[__CLASS__
]['contact_references'];
2491 $contactReferences = [];
2492 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2493 foreach ($coreReferences as $coreReference) {
2494 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2495 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2498 self
::appendCustomTablesExtendingContacts($contactReferences);
2499 self
::appendCustomContactReferenceFields($contactReferences);
2500 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2501 return \Civi
::$statics[__CLASS__
]['contact_references'];
2505 * Get all dynamic references to the given table.
2507 * @param string $tableName
2511 public static function getDynamicReferencesToTable($tableName) {
2512 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2513 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2514 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2515 foreach ($coreReferences as $coreReference) {
2516 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2517 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2521 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2525 * Add custom tables that extend contacts to the list of contact references.
2527 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2528 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2529 * - the down side is it is not cached.
2531 * Further changes should be include tests in the CRM_Core_MergerTest class
2532 * to ensure that disabled, subtype, multiple etc groups are still captured.
2534 * @param array $cidRefs
2536 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2537 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2538 $customValueTables->find();
2539 while ($customValueTables->fetch()) {
2540 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2545 * Add custom ContactReference fields to the list of contact references
2547 * This includes active and inactive fields/groups
2549 * @param array $cidRefs
2551 * @throws \CiviCRM_API3_Exception
2553 public static function appendCustomContactReferenceFields(&$cidRefs) {
2554 $fields = civicrm_api3('CustomField', 'get', [
2555 'return' => ['column_name', 'custom_group_id.table_name'],
2556 'data_type' => 'ContactReference',
2557 'options' => ['limit' => 0],
2559 foreach ($fields as $field) {
2560 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2565 * Lookup the value of a MySQL global configuration variable.
2567 * @param string $name
2568 * E.g. "thread_stack".
2569 * @param mixed $default
2572 public static function getGlobalSetting($name, $default = NULL) {
2573 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2574 // that has been reported to fail under MySQL 5.0 for OS X
2575 $escapedName = self
::escapeString($name);
2576 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2577 if ($dao->fetch()) {
2586 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2588 * This is relevant where we want to offer both the ID field and the label field
2589 * as an option, e.g. search builder.
2591 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2592 * change small, but is appropriate for other sorts of pseudoconstants.
2594 * @param array $fields
2596 public static function appendPseudoConstantsToFields(&$fields) {
2597 foreach ($fields as $fieldUniqueName => $field) {
2598 if (!empty($field['pseudoconstant'])) {
2599 $pseudoConstant = $field['pseudoconstant'];
2600 if (!empty($pseudoConstant['optionGroupName'])) {
2601 $fields[$pseudoConstant['optionGroupName']] = [
2602 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2603 'name' => $pseudoConstant['optionGroupName'],
2604 'data_type' => CRM_Utils_Type
::T_STRING
,
2605 'is_pseudofield_for' => $fieldUniqueName,
2608 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2610 !empty($field['FKClassName'])
2611 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2612 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2614 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2615 // This if is just an extra caution when adding change.
2616 if (!isset($fields[$pseudoFieldName])) {
2617 $daoName = $field['FKClassName'];
2618 $fkFields = $daoName::fields();
2619 foreach ($fkFields as $fkField) {
2620 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2621 $fields[$pseudoFieldName] = [
2622 'name' => $pseudoFieldName,
2623 'is_pseudofield_for' => $field['name'],
2624 'title' => $fkField['title'],
2625 'data_type' => $fkField['type'],
2626 'where' => $field['where'],
2637 * Get options for the called BAO object's field.
2639 * This function can be overridden by each BAO to add more logic related to context.
2640 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2642 * @param string $fieldName
2643 * @param string $context
2644 * @see CRM_Core_DAO::buildOptionsContext
2645 * @param array $props
2646 * Raw field values; whatever is known about this bao object.
2648 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2650 * @return array|bool
2652 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2653 // If a given bao does not override this function
2654 $baoName = get_called_class();
2655 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2659 * Populate option labels for this object's fields.
2661 * @throws exception if called directly on the base class
2663 public function getOptionLabels() {
2664 $fields = $this->fields();
2665 if ($fields === NULL) {
2666 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2668 foreach ($fields as $field) {
2669 $name = $field['name'] ??
NULL;
2670 if ($name && isset($this->$name)) {
2671 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2672 if ($label !== FALSE) {
2673 // Append 'label' onto the field name
2674 $labelName = $name . '_label';
2675 $this->$labelName = $label;
2682 * Provides documentation and validation for the buildOptions $context param
2684 * @param string $context
2686 * @throws CRM_Core_Exception
2689 public static function buildOptionsContext($context = NULL) {
2691 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2692 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2693 'search' => "search: searchable options are returned; labels are translated.",
2694 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2695 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2696 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2698 // Validation: enforce uniformity of this param
2699 if ($context !== NULL && !isset($contexts[$context])) {
2700 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2706 * @param string $fieldName
2707 * @return bool|array
2709 public function getFieldSpec($fieldName) {
2710 $fields = $this->fields();
2711 $fieldKeys = $this->fieldKeys();
2713 // Support "unique names" as well as sql names
2714 $fieldKey = $fieldName;
2715 if (empty($fields[$fieldKey])) {
2716 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2718 // If neither worked then this field doesn't exist. Return false.
2719 if (empty($fields[$fieldKey])) {
2722 return $fields[$fieldKey];
2726 * Get SQL where clause for SQL filter syntax input parameters.
2728 * SQL version of api function to assign filters to the DAO based on the syntax
2729 * $field => array('IN' => array(4,6,9))
2731 * $field => array('LIKE' => array('%me%))
2734 * @param string $fieldName
2736 * @param array $filter
2737 * filter to be applied indexed by operator.
2738 * @param string $type
2739 * type of field (not actually used - nor in api @todo ).
2740 * @param string $alias
2741 * alternative field name ('as') @todo- not actually used.
2742 * @param bool $returnSanitisedArray
2743 * Return a sanitised array instead of a clause.
2744 * this is primarily so we can add filters @ the api level to the Query object based fields
2748 * @return NULL|string|array
2749 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2750 * depending on whether it is supported as yet
2752 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2753 foreach ($filter as $operator => $criteria) {
2754 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2755 switch ($operator) {
2759 if (!$returnSanitisedArray) {
2760 return (sprintf('%s %s', $fieldName, $operator));
2763 return (sprintf('%s %s ', $fieldName, $operator));
2767 // ternary operators
2770 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2771 throw new Exception("invalid criteria for $operator");
2773 if (!$returnSanitisedArray) {
2774 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2777 // not yet implemented (tests required to implement)
2785 if (empty($criteria)) {
2786 throw new Exception("invalid criteria for $operator");
2788 $escapedCriteria = array_map([
2792 if (!$returnSanitisedArray) {
2793 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2795 return $escapedCriteria;
2800 if (!$returnSanitisedArray) {
2801 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2804 // not yet implemented (tests required to implement)
2813 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2814 * support for other syntaxes is discussed in ticket but being put off for now
2817 public static function acceptedSQLOperators() {
2838 * SQL has a limit of 64 characters on various names:
2839 * table name, trigger name, column name ...
2841 * For custom groups and fields we generated names from user entered input
2842 * which can be longer than this length, this function helps with creating
2843 * strings that meet various criteria.
2845 * @param string $string
2846 * The string to be shortened.
2847 * @param int $length
2848 * The max length of the string.
2850 * @param bool $makeRandom
2854 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2855 // early return for strings that meet the requirements
2856 if (strlen($string) <= $length) {
2860 // easy return for calls that dont need a randomized uniq string
2862 return substr($string, 0, $length);
2865 // the string is longer than the length and we need a uniq string
2866 // for the same tablename we need the same uniq string every time
2867 // hence we use md5 on the string, which is not random
2868 // we'll append 8 characters to the end of the tableName
2869 $md5string = substr(md5($string), 0, 8);
2870 return substr($string, 0, $length - 8) . "_{$md5string}";
2874 * https://issues.civicrm.org/jira/browse/CRM-17748
2875 * Sets the internal options to be used on a query
2877 * @param array $options
2880 public function setOptions($options) {
2881 if (is_array($options)) {
2882 $this->_options
= $options;
2887 * https://issues.civicrm.org/jira/browse/CRM-17748
2888 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2890 * @param array $options
2893 protected function _setDBOptions($options) {
2894 global $_DB_DATAOBJECT;
2896 if (is_array($options) && count($options)) {
2897 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2898 foreach ($options as $option_name => $option_value) {
2899 $conn->setOption($option_name, $option_value);
2906 * @param array $params
2908 public function setApiFilter(&$params) {
2912 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2914 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2917 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2921 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2925 public function addSelectWhereClause() {
2927 $fields = $this->fields();
2928 foreach ($fields as $fieldName => $field) {
2929 // Clause for contact-related entities like Email, Relationship, etc.
2930 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2931 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2933 // Clause for an entity_table/entity_id combo
2934 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2935 $relatedClauses = [];
2936 $relatedEntities = $this->buildOptions('entity_table', 'get');
2937 foreach ((array) $relatedEntities as $table => $ent) {
2939 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2940 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2942 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2945 $relatedClauses[] = "(entity_table = '$table')";
2949 if ($relatedClauses) {
2950 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2954 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2959 * This returns the final permissioned query string for this entity
2961 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2963 * @param string $tableAlias
2966 public static function getSelectWhereClause($tableAlias = NULL) {
2967 $bao = new static();
2968 if ($tableAlias === NULL) {
2969 $tableAlias = $bao->tableName();
2972 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2973 $clauses[$field] = NULL;
2975 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2982 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2983 * and dashes, and contains at least one [a-z] case insenstive.
2989 public static function requireSafeDBName($database) {
2992 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2996 if (empty($matches)) {
3003 * Transform an array to a serialized string for database storage.
3005 * @param array|null $value
3006 * @param int $serializationType
3007 * @return string|null
3009 * @throws \Exception
3011 public static function serializeField($value, $serializationType) {
3012 if ($value === NULL) {
3015 switch ($serializationType) {
3016 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3017 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3019 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3020 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3022 case self
::SERIALIZE_JSON
:
3023 return is_array($value) ?
json_encode($value) : $value;
3025 case self
::SERIALIZE_PHP
:
3026 return is_array($value) ?
serialize($value) : $value;
3028 case self
::SERIALIZE_COMMA
:
3029 return is_array($value) ?
implode(',', $value) : $value;
3032 throw new Exception('Unknown serialization method for field.');
3037 * Transform a serialized string from the database into an array.
3039 * @param string|null $value
3040 * @param $serializationType
3042 * @return array|null
3043 * @throws CRM_Core_Exception
3045 public static function unSerializeField($value, $serializationType) {
3046 if ($value === NULL) {
3049 if ($value === '') {
3052 switch ($serializationType) {
3053 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3054 return (array) CRM_Utils_Array
::explodePadded($value);
3056 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3057 return explode(self
::VALUE_SEPARATOR
, trim($value));
3059 case self
::SERIALIZE_JSON
:
3060 return strlen($value) ?
json_decode($value, TRUE) : [];
3062 case self
::SERIALIZE_PHP
:
3063 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3065 case self
::SERIALIZE_COMMA
:
3066 return explode(',', trim(str_replace(', ', '', $value)));
3069 throw new CRM_Core_Exception('Unknown serialization method for field.');
3076 public static function getEntityRefFilters() {
3081 * Get exportable fields with pseudoconstants rendered as an extra field.
3083 * @param string $baoClass
3087 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3088 if (method_exists($baoClass, 'exportableFields')) {
3089 $fields = $baoClass::exportableFields();
3092 $fields = $baoClass::export();
3094 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3099 * Remove item from static cache during update/delete operations
3101 private function clearDbColumnValueCache() {
3102 $daoName = get_class($this);
3103 while (strpos($daoName, '_BAO_') !== FALSE) {
3104 $daoName = get_parent_class($daoName);
3106 if (isset($this->id
)) {
3107 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3109 if (isset($this->name
)) {
3110 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);
3115 * Does the DSN indicate the connection should use ssl.
3117 * @param string $dsn
3121 public static function isSSLDSN(string $dsn):bool {
3122 // Note that ssl= below is not an official PEAR::DB option. It doesn't know
3123 // what to do with it. We made it up because it's not required
3124 // to have client-side certificates to use ssl, so here you can specify
3125 // you want that by putting ssl=1 in the DSN string.
3127 // Cast to bool in case of error which we interpret as no ssl.
3128 return (bool) preg_match('/[\?&](key|cert|ca|capath|cipher|ssl)=/', $dsn);