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.
127 public static function getEntityTitle() {
128 $className = static::class;
129 Civi
::log()->warning("$className needs to be regenerated. Missing getEntityTitle method.", ['civi.tag' => 'deprecated']);
130 return CRM_Core_DAO_AllCoreTables
::getBriefName($className);
133 public function __clone() {
134 if (!empty($this->_DB_resultid
)) {
135 $this->resultCopies++
;
142 public function __destruct() {
143 if ($this->resultCopies
=== 0) {
146 $this->resultCopies
--;
150 * Returns the name of this table
154 public static function getTableName() {
155 return self
::getLocaleTableName(static::$_tableName ??
NULL);
159 * Returns if this table needs to be logged
163 public function getLog() {
164 return static::$_log ??
FALSE;
168 * Initialize the DAO object.
171 * The database connection string.
173 public static function init($dsn) {
174 Civi
::$statics[__CLASS__
]['init'] = 1;
175 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
176 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsn);
177 $options['database'] = $dsn;
178 $options['quote_identifiers'] = TRUE;
179 if (CRM_Utils_SQL
::isSSLDSN($dsn)) {
180 // There are two different options arrays.
181 $other_options = &PEAR
::getStaticProperty('DB', 'options');
182 $other_options['ssl'] = TRUE;
184 if (defined('CIVICRM_DAO_DEBUG')) {
185 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
187 $factory = new CRM_Contact_DAO_Factory();
188 CRM_Core_DAO
::setFactory($factory);
189 $currentModes = CRM_Utils_SQL
::getSqlModes();
190 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
191 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
192 $currentModes[] = 'ONLY_FULL_GROUP_BY';
194 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
195 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
197 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
199 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
200 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
206 public static function getConnection() {
207 global $_DB_DATAOBJECT;
208 $dao = new CRM_Core_DAO();
209 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
213 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
215 public static function disableFullGroupByMode() {
216 $currentModes = CRM_Utils_SQL
::getSqlModes();
217 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
218 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
219 unset($currentModes[$key]);
220 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
225 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
227 public static function reenableFullGroupByMode() {
228 $currentModes = CRM_Utils_SQL
::getSqlModes();
229 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
230 $currentModes[] = 'ONLY_FULL_GROUP_BY';
231 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
236 * @param string $fieldName
238 * @param array $params
240 protected function assignTestFK($fieldName, $fieldDef, $params) {
241 $required = $fieldDef['required'] ??
NULL;
242 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
243 $dbName = $fieldDef['name'];
244 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
246 // skip the FK if it is not required
247 // if it's contact id we should create even if not required
248 // we'll have a go @ fetching first though
249 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
250 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
253 if (!$required && $dbName != 'contact_id') {
254 $fkDAO = new $FKClassName();
255 if ($fkDAO->find(TRUE)) {
256 $this->$dbName = $fkDAO->id
;
260 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
261 $depObject = new $FKClassName();
262 $depObject->find(TRUE);
263 $this->$dbName = $depObject->id
;
265 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
266 // FIXME: the fields() metadata is not specific enough
267 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
268 $this->$dbName = $depObject->id
;
271 //if it is required we need to generate the dependency object first
272 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
273 $this->$dbName = $depObject->id
;
278 * Generate and assign an arbitrary value to a field of a test object.
280 * @param string $fieldName
281 * @param array $fieldDef
282 * @param int $counter
283 * The globally-unique ID of the test object.
285 * @throws \CRM_Core_Exception
287 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
288 $dbName = $fieldDef['name'];
289 $daoName = get_class($this);
292 if (!$handled && $dbName == 'contact_sub_type') {
293 //coming up with a rule to set this is too complex let's not set it
297 // Pick an option value if needed
298 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
299 $options = $daoName::buildOptions($dbName, 'create');
301 $this->$dbName = key($options);
307 switch ($fieldDef['type']) {
308 case CRM_Utils_Type
::T_INT
:
309 case CRM_Utils_Type
::T_FLOAT
:
310 case CRM_Utils_Type
::T_MONEY
:
311 if (isset($fieldDef['precision'])) {
312 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
313 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
316 $this->$dbName = $counter;
320 case CRM_Utils_Type
::T_BOOLEAN
:
321 if (isset($fieldDef['default'])) {
322 $this->$dbName = $fieldDef['default'];
324 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
332 case CRM_Utils_Type
::T_DATE
:
333 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
334 $this->$dbName = '19700101';
335 if ($dbName == 'end_date') {
336 // put this in the future
337 $this->$dbName = '20200101';
341 case CRM_Utils_Type
::T_TIMESTAMP
:
342 $this->$dbName = '19700201000000';
345 case CRM_Utils_Type
::T_TIME
:
346 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
348 case CRM_Utils_Type
::T_CCNUM
:
349 $this->$dbName = '4111 1111 1111 1111';
352 case CRM_Utils_Type
::T_URL
:
353 $this->$dbName = 'http://www.civicrm.org';
356 case CRM_Utils_Type
::T_STRING
:
357 case CRM_Utils_Type
::T_BLOB
:
358 case CRM_Utils_Type
::T_MEDIUMBLOB
:
359 case CRM_Utils_Type
::T_TEXT
:
360 case CRM_Utils_Type
::T_LONGTEXT
:
361 case CRM_Utils_Type
::T_EMAIL
:
363 // WAS: if (isset($value['enumValues'])) {
364 // TODO: see if this works with all pseudoconstants
365 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
366 if (isset($fieldDef['default'])) {
367 $this->$dbName = $fieldDef['default'];
370 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
371 if (is_array($options)) {
372 $this->$dbName = $options[0];
375 $defaultValues = explode(',', $options);
376 $this->$dbName = $defaultValues[0];
381 $this->$dbName = $dbName . '_' . $counter;
382 $maxlength = $fieldDef['maxlength'] ??
NULL;
383 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
384 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
392 * Reset the DAO object.
394 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
396 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
398 public function reset() {
400 foreach (array_keys($this->table()) as $field) {
401 unset($this->$field);
405 * reset the various DB_DAO structures manually
414 * @param string $tableName
418 public static function getLocaleTableName($tableName) {
421 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
422 if (in_array($tableName, $tables)) {
423 return $tableName . $dbLocale;
430 * Execute a query by the current DAO, localizing it along the way (if needed).
432 * @param string $query
433 * The SQL query for execution.
434 * @param bool $i18nRewrite
435 * Whether to rewrite the query.
438 * the current DAO object after the query execution
440 public function query($query, $i18nRewrite = TRUE) {
441 // rewrite queries that should use $dbLocale-based views for multi-language installs
442 global $dbLocale, $_DB_DATAOBJECT;
444 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
445 // Will force connection to be populated per CRM-20541.
449 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
450 $orig_options = $conn->options
;
451 $this->_setDBOptions($this->_options
);
453 if ($i18nRewrite and $dbLocale) {
454 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
457 $ret = parent
::query($query);
459 $this->_setDBOptions($orig_options);
464 * Static function to set the factory instance for this class.
466 * @param object $factory
467 * The factory application object.
469 public static function setFactory(&$factory) {
470 self
::$_factory = &$factory;
474 * Factory method to instantiate a new object from a table name.
476 * @param string $table
477 * @return \DataObject|\PEAR_Error
479 public function factory($table = '') {
480 if (!isset(self
::$_factory)) {
481 return parent
::factory($table);
484 return self
::$_factory->create($table);
488 * Initialization for all DAO objects. Since we access DB_DO programatically
489 * we need to set the links manually.
491 public function initialize() {
493 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
494 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
495 // This occurs very early in bootstrap - error handlers may not be wired up.
496 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
497 CRM_Utils_System
::civiExit();
502 * Defines the default key as 'id'.
506 public function keys() {
515 * Tells DB_DataObject which keys use autoincrement.
516 * 'id' is autoincrementing by default.
521 public function sequenceKey() {
522 static $sequenceKeys;
523 if (!isset($sequenceKeys)) {
524 $sequenceKeys = ['id', TRUE];
526 return $sequenceKeys;
530 * Returns list of FK relationships.
534 * Array of CRM_Core_Reference_Interface
536 public static function getReferenceColumns() {
541 * Returns all the column names of this table.
546 public static function &fields() {
552 * Returns all usable fields, indexed by name.
554 * This function differs from fields() in that it indexes by name rather than unique_name.
556 * It excludes fields not added yet by pending upgrades.
557 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
559 * @param bool $checkPermissions
560 * Filter by field permissions.
563 public static function getSupportedFields($checkPermissions = FALSE) {
564 $fields = array_column((array) static::fields(), NULL, 'name');
566 // Exclude fields yet not added by pending upgrades
567 $dbVer = \CRM_Core_BAO_Domain
::version();
568 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
569 if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
570 $fields = array_filter($fields, function($field) use ($dbVer) {
571 $add = $field['add'] ??
'1.0.0';
572 if (substr_count($add, '.') < 2) {
575 return version_compare($dbVer, $add, '>=');
579 // Exclude fields the user does not have permission for
580 if ($checkPermissions) {
581 $fields = array_filter($fields, function($field) {
582 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
590 * Get/set an associative array of table columns
595 public function table() {
596 $fields = $this->fields();
600 foreach ($fields as $name => $value) {
601 $table[$value['name']] = $value['type'];
602 if (!empty($value['required'])) {
603 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
616 * @return CRM_Core_DAO
618 public function save($hook = TRUE) {
619 if (!empty($this->id
)) {
621 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
622 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
625 $result = $this->update();
628 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
629 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
631 $this->clearDbColumnValueCache();
635 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
636 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
639 $result = $this->insert();
642 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
643 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
649 CRM_Utils_Hook
::postSave($this);
656 * Deletes items from table which match current objects variables.
658 * Returns the true on success
662 * Designed to be extended
664 * $object = new mytable();
666 * echo $object->delete(); // builds a conditon
668 * $object = new mytable();
669 * $object->whereAdd('age > 12');
671 * $object->orderBy('age DESC');
672 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
674 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
675 * we will build the condition only using the whereAdd's. Default is to
676 * build the condition only using the object parameters.
678 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
680 public function delete($useWhere = FALSE) {
681 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
682 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
684 $result = parent
::delete($useWhere);
686 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
687 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
690 $this->clearDbColumnValueCache();
696 * @param bool $created
698 public function log($created = FALSE) {
701 if (!$this->getLog()) {
706 $session = CRM_Core_Session
::singleton();
707 $cid = $session->get('userID');
710 // return is we dont have handle to FK
715 $dao = new CRM_Core_DAO_Log();
716 $dao->entity_table
= $this->getTableName();
717 $dao->entity_id
= $this->id
;
718 $dao->modified_id
= $cid;
719 $dao->modified_date
= date("YmdHis");
724 * Given an associative array of name/value pairs, extract all the values
725 * that belong to this object and initialize the object with said values
727 * @param array $params
728 * Array of name/value pairs to save.
731 * Did we copy all null values into the object
733 public function copyValues($params) {
735 foreach ($this->fields() as $uniqueName => $field) {
736 $dbName = $field['name'];
737 if (array_key_exists($dbName, $params)) {
738 $value = $params[$dbName];
741 elseif (array_key_exists($uniqueName, $params)) {
742 $value = $params[$uniqueName];
749 // if there is no value then make the variable NULL
752 $this->$dbName = 'null';
754 elseif (is_array($value) && !empty($field['serialize'])) {
755 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
759 $maxLength = $field['maxlength'] ??
NULL;
760 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
761 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($value, 'String')]));
762 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
763 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
765 $this->$dbName = $value;
774 * Store all the values from this object in an associative array
775 * this is a destructive store, calling function is responsible
776 * for keeping sanity of id's.
778 * @param object $object
779 * The object that we are extracting data from.
780 * @param array $values
781 * (reference ) associative array of name/value pairs.
783 public static function storeValues(&$object, &$values) {
784 $fields = $object->fields();
785 foreach ($fields as $name => $value) {
786 $dbName = $value['name'];
787 if (isset($object->$dbName) && $object->$dbName !== 'null') {
788 $values[$dbName] = $object->$dbName;
789 if ($name != $dbName) {
790 $values[$name] = $object->$dbName;
797 * Create an attribute for this specific field. We only do this for strings and text
799 * @param array $field
800 * The field under task.
803 * the attributes for the object
805 public static function makeAttribute($field) {
807 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
808 $maxLength = $field['maxlength'] ??
NULL;
809 $size = $field['size'] ??
NULL;
810 if ($maxLength ||
$size) {
813 $attributes['maxlength'] = $maxLength;
816 $attributes['size'] = $size;
821 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
822 $rows = $field['rows'] ??
NULL;
826 $cols = $field['cols'] ??
NULL;
832 $attributes['rows'] = $rows;
833 $attributes['cols'] = $cols;
836 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
) {
837 $attributes['size'] = 6;
838 $attributes['maxlength'] = 14;
846 * Get the size and maxLength attributes for this text field.
847 * (or for all text fields) in the DAO object.
849 * @param string $class
851 * @param string $fieldName
852 * Field that i'm interested in or null if.
853 * you want the attributes for all DAO text fields
856 * assoc array of name => attribute pairs
858 public static function getAttribute($class, $fieldName = NULL) {
859 $object = new $class();
860 $fields = $object->fields();
861 if ($fieldName != NULL) {
862 $field = $fields[$fieldName] ??
NULL;
863 return self
::makeAttribute($field);
867 foreach ($fields as $name => $field) {
868 $attribute = self
::makeAttribute($field);
870 $attributes[$name] = $attribute;
874 if (!empty($attributes)) {
882 * Create or update a record from supplied params.
884 * If 'id' is supplied, an existing record will be updated
885 * Otherwise a new record will be created.
887 * @param array $record
888 * @return CRM_Core_DAO
889 * @throws CRM_Core_Exception
891 public static function writeRecord(array $record) {
892 $hook = empty($record['id']) ?
'create' : 'edit';
893 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
894 if ($className === 'CRM_Core_DAO') {
895 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
897 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
899 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
900 $instance = new $className();
901 $instance->copyValues($record);
903 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
909 * Delete a record from supplied params.
911 * @param array $record
913 * @return CRM_Core_DAO
914 * @throws CRM_Core_Exception
916 public static function deleteRecord(array $record) {
917 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
918 if ($className === 'CRM_Core_DAO') {
919 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
921 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
922 if (empty($record['id'])) {
923 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
926 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
927 $instance = new $className();
928 $instance->id
= $record['id'];
929 if (!$instance->delete()) {
930 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
932 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
938 * Check if there is a record with the same name in the db.
940 * @param string $value
941 * The value of the field we are checking.
942 * @param string $daoName
943 * The dao object name.
944 * @param string $daoID
945 * The id of the object being updated. u can change your name.
946 * as long as there is no conflict
947 * @param string $fieldName
948 * The name of the field in the DAO.
950 * @param string $domainID
951 * The id of the domain. Object exists only for the given domain.
954 * true if object exists
956 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
957 $object = new $daoName();
958 $object->$fieldName = $value;
960 $object->domain_id
= $domainID;
963 if ($object->find(TRUE)) {
964 return $daoID && $object->id
== $daoID;
972 * Check if there is a given column in a specific table.
975 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
977 * @param string $tableName
978 * @param string $columnName
979 * @param bool $i18nRewrite
980 * Whether to rewrite the query on multilingual setups.
983 * true if exists, else false
985 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
986 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
987 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
991 * Scans all the tables using a slow query and table name.
995 public static function getTableNames() {
996 $dao = CRM_Core_DAO
::executeQuery(
998 FROM information_schema.TABLES
999 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1000 AND TABLE_NAME LIKE 'civicrm_%'
1001 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1002 AND TABLE_NAME NOT LIKE '%_temp%'
1005 while ($dao->fetch()) {
1006 $values[] = $dao->TABLE_NAME
;
1012 * @param int $maxTablesToCheck
1016 public static function isDBMyISAM($maxTablesToCheck = 10) {
1017 return CRM_Core_DAO
::singleValueQuery(
1019 FROM information_schema.TABLES
1020 WHERE ENGINE = 'MyISAM'
1021 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1022 AND TABLE_NAME LIKE 'civicrm_%'
1023 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1024 AND TABLE_NAME NOT LIKE '%_temp%'
1025 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1030 * Get the name of the CiviCRM database.
1034 public static function getDatabaseName() {
1035 $daoObj = new CRM_Core_DAO();
1036 return $daoObj->database();
1040 * Checks if a constraint exists for a specified table.
1042 * @param string $tableName
1043 * @param string $constraint
1046 * true if constraint exists, false otherwise
1048 * @throws \CRM_Core_Exception
1050 public static function checkConstraintExists($tableName, $constraint) {
1053 if (!array_key_exists($tableName, $show)) {
1054 $query = "SHOW CREATE TABLE $tableName";
1055 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1057 if (!$dao->fetch()) {
1058 throw new CRM_Core_Exception('query failed');
1061 $show[$tableName] = $dao->Create_Table
;
1064 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1068 * Checks if CONSTRAINT keyword exists for a specified table.
1070 * @param array $tables
1072 * @throws CRM_Core_Exception
1075 * true if CONSTRAINT keyword exists, false otherwise
1077 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1079 foreach ($tables as $tableName) {
1080 if (!array_key_exists($tableName, $show)) {
1081 $query = "SHOW CREATE TABLE $tableName";
1082 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1084 if (!$dao->fetch()) {
1085 throw new CRM_Core_Exception('Show create table failed.');
1088 $show[$tableName] = $dao->Create_Table
;
1091 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1092 if ($result == TRUE) {
1103 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1104 * for a specified column of a table.
1106 * @param string $tableName
1107 * @param string $columnName
1110 * true if in format, false otherwise
1112 * @throws \CRM_Core_Exception
1114 public static function checkFKConstraintInFormat($tableName, $columnName) {
1117 if (!array_key_exists($tableName, $show)) {
1118 $query = "SHOW CREATE TABLE $tableName";
1119 $dao = CRM_Core_DAO
::executeQuery($query);
1121 if (!$dao->fetch()) {
1122 throw new CRM_Core_Exception('query failed');
1125 $show[$tableName] = $dao->Create_Table
;
1127 $constraint = "`FK_{$tableName}_{$columnName}`";
1128 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1129 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1133 * Check whether a specific column in a specific table has always the same value.
1135 * @param string $tableName
1136 * @param string $columnName
1137 * @param string $columnValue
1140 * true if the value is always $columnValue, false otherwise
1142 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1143 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1144 $dao = CRM_Core_DAO
::executeQuery($query);
1145 $result = $dao->fetch() ?
FALSE : TRUE;
1150 * Check whether a specific column in a specific table is always NULL.
1152 * @param string $tableName
1153 * @param string $columnName
1156 * true if if the value is always NULL, false otherwise
1158 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1159 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1160 $dao = CRM_Core_DAO
::executeQuery($query);
1161 $result = $dao->fetch() ?
FALSE : TRUE;
1166 * Checks if this DAO's table ought to exist.
1168 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1171 * @throws CRM_Core_Exception
1173 public static function tableHasBeenAdded() {
1174 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1177 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1178 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1179 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1183 * Check if there is a given table in the database.
1185 * @param string $tableName
1188 * true if exists, else false
1190 public static function checkTableExists($tableName) {
1195 $params = [1 => [$tableName, 'String']];
1197 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1198 return (bool) $dao->fetch();
1202 * Check if a given table has data.
1204 * @param string $tableName
1206 * TRUE if $tableName has at least one record.
1208 public static function checkTableHasData($tableName) {
1209 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1218 public function checkVersion($version) {
1219 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1220 $dbVersion = CRM_Core_BAO_Domain
::version();
1221 return trim($version) == trim($dbVersion);
1225 * Find a DAO object for the given ID and return it.
1228 * Id of the DAO object being searched for.
1230 * @return CRM_Core_DAO
1231 * Object of the type of the class that called this function.
1235 public static function findById($id) {
1236 $object = new static();
1238 if (!$object->find(TRUE)) {
1239 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1245 * Returns all results as array-encoded records.
1249 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1251 while ($this->fetch()) {
1252 $result[] = $this->toArray();
1258 * Return the results as PHP generator.
1260 * @param string $type
1261 * Whether the generator yields 'dao' objects or 'array's.
1263 public function fetchGenerator($type = 'dao') {
1264 while ($this->fetch()) {
1271 yield
$this->toArray();
1275 throw new \
RuntimeException("Invalid record type ($type)");
1281 * Returns a singular value.
1283 * @return mixed|NULL
1285 public function fetchValue() {
1286 $result = $this->getDatabaseResult();
1287 $row = $result->fetchRow();
1297 * Get all the result records as mapping between columns.
1299 * @param string $keyColumn
1301 * @param string $valueColumn
1304 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1306 public function fetchMap($keyColumn, $valueColumn) {
1308 while ($this->fetch()) {
1309 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1315 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1317 * @param string $daoName
1318 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1319 * @param int $searchValue
1320 * Value of the column you want to search by.
1321 * @param string $returnColumn
1322 * Name of the column you want to GET the value of.
1323 * @param string $searchColumn
1324 * Name of the column you want to search by.
1325 * @param bool $force
1326 * Skip use of the cache.
1328 * @return string|int|null
1329 * Value of $returnColumn in the retrieved record
1331 * @throws \CRM_Core_Exception
1333 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1335 empty($searchValue) ||
1336 trim(strtolower($searchValue)) == 'null'
1338 // adding this here since developers forget to check for an id
1339 // or for the 'null' (which is a bad DAO kludge)
1340 // and hence we get the first value in the db
1341 throw new CRM_Core_Exception('getFieldValue failed');
1344 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1346 while (strpos($daoName, '_BAO_') !== FALSE) {
1347 $daoName = get_parent_class($daoName);
1351 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1352 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1354 $object = new $daoName();
1355 $object->$searchColumn = $searchValue;
1356 $object->selectAdd();
1357 $object->selectAdd($returnColumn);
1360 if ($object->find(TRUE)) {
1361 $result = $object->$returnColumn;
1364 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1366 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1370 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1372 * @param string $daoName
1373 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1374 * @param int $searchValue
1375 * Value of the column you want to search by.
1376 * @param string $setColumn
1377 * Name of the column you want to SET the value of.
1378 * @param string $setValue
1379 * SET the setColumn to this value.
1380 * @param string $searchColumn
1381 * Name of the column you want to search by.
1384 * true if we found and updated the object, else false
1386 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1387 $object = new $daoName();
1388 $object->selectAdd();
1389 $object->selectAdd("$searchColumn, $setColumn");
1390 $object->$searchColumn = $searchValue;
1392 if ($object->find(TRUE)) {
1393 $object->$setColumn = $setValue;
1394 if ($object->save()) {
1405 * @param array|object $sort either array or CRM_Utils_Sort
1406 * @param string $default
1407 * Default sort value.
1411 public static function getSortString($sort, $default = NULL) {
1412 // check if sort is of type CRM_Utils_Sort
1413 if (is_a($sort, 'CRM_Utils_Sort')) {
1414 return $sort->orderBy();
1419 // is it an array specified as $field => $sortDirection ?
1421 foreach ($sort as $k => $v) {
1422 $sortString .= "$k $v,";
1424 return rtrim($sortString, ',');
1430 * Fetch object based on array of properties.
1432 * @param string $daoName
1433 * Name of the dao object.
1434 * @param array $params
1435 * (reference ) an assoc array of name/value pairs.
1436 * @param array $defaults
1437 * (reference ) an assoc array to hold the flattened values.
1438 * @param array $returnProperities
1439 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1442 * an object of type referenced by daoName
1444 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1445 $object = new $daoName();
1446 $object->copyValues($params);
1448 // return only specific fields if returnproperties are sent
1449 if (!empty($returnProperities)) {
1450 $object->selectAdd();
1451 $object->selectAdd(implode(',', $returnProperities));
1454 if ($object->find(TRUE)) {
1455 self
::storeValues($object, $defaults);
1462 * Delete the object records that are associated with this contact.
1464 * @param string $daoName
1465 * Name of the dao object.
1466 * @param int $contactId
1467 * Id of the contact to delete.
1469 public static function deleteEntityContact($daoName, $contactId) {
1470 $object = new $daoName();
1472 $object->entity_table
= 'civicrm_contact';
1473 $object->entity_id
= $contactId;
1478 * Execute an unbuffered query.
1480 * This is a wrapper around new functionality exposed with CRM-17748.
1482 * @param string $query query to be executed
1484 * @param array $params
1485 * @param bool $abort
1486 * @param null $daoName
1487 * @param bool $freeDAO
1488 * @param bool $i18nRewrite
1489 * @param bool $trapException
1491 * @return CRM_Core_DAO
1492 * Object that points to an unbuffered result set
1494 public static function executeUnbufferedQuery(
1500 $i18nRewrite = TRUE,
1501 $trapException = FALSE
1504 return self
::executeQuery(
1512 ['result_buffering' => 0]
1519 * @param string $query
1520 * Query to be executed.
1522 * @param array $params
1523 * @param bool $abort
1524 * @param null $daoName
1525 * @param bool $freeDAO
1526 * @param bool $i18nRewrite
1527 * @param bool $trapException
1528 * @param array $options
1530 * @return CRM_Core_DAO|object
1531 * object that holds the results of the query
1532 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1533 * out all the properties that are not part of the DAO
1535 public static function &executeQuery(
1541 $i18nRewrite = TRUE,
1542 $trapException = FALSE,
1545 $queryStr = self
::composeQuery($query, $params, $abort);
1548 $dao = new CRM_Core_DAO();
1551 $dao = new $daoName();
1554 if ($trapException) {
1555 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1556 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1559 if ($dao->isValidOption($options)) {
1560 $dao->setOptions($options);
1563 $result = $dao->query($queryStr, $i18nRewrite);
1565 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1566 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1570 if (is_a($result, 'DB_Error')) {
1571 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1579 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1581 * @param array $options
1584 * Provided options are valid
1586 public function isValidOption($options) {
1595 if (empty($options)) {
1599 foreach (array_keys($options) as $option) {
1600 if (!in_array($option, $validOptions)) {
1610 * Execute a query and get the single result.
1612 * @param string $query
1613 * Query to be executed.
1614 * @param array $params
1615 * @param bool $abort
1616 * @param bool $i18nRewrite
1617 * @return string|null
1618 * the result of the query if any
1621 public static function &singleValueQuery(
1627 $queryStr = self
::composeQuery($query, $params, $abort);
1629 static $_dao = NULL;
1632 $_dao = new CRM_Core_DAO();
1635 $_dao->query($queryStr, $i18nRewrite);
1637 $result = $_dao->getDatabaseResult();
1640 $row = $result->fetchRow();
1650 * Compose the query by merging the parameters into it.
1652 * @param string $query
1653 * @param array $params
1654 * @param bool $abort
1657 * @throws CRM_Core_Exception
1659 public static function composeQuery($query, $params = [], $abort = TRUE) {
1661 foreach ($params as $key => $item) {
1662 if (is_numeric($key)) {
1663 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1664 $item[0] = self
::escapeString($item[0]);
1665 if ($item[1] == 'String' ||
1666 $item[1] == 'Memo' ||
1669 // Support class constants stipulating wildcard characters and/or
1670 // non-quoting of strings. Also support legacy code which may be
1671 // passing in TRUE or 1 for $item[2], which used to indicate the
1672 // use of wildcard characters.
1673 if (!empty($item[2])) {
1674 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1675 $item[0] = "'%{$item[0]}%'";
1677 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1678 $item[0] = "'{$item[0]}'";
1682 $item[0] = "'{$item[0]}'";
1686 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1687 strlen($item[0]) == 0
1692 $tr['%' . $key] = $item[0];
1695 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1700 return strtr($query, $tr);
1706 public static function freeResult($ids = NULL) {
1707 global $_DB_DATAOBJECT;
1710 if (!$_DB_DATAOBJECT ||
1711 !isset($_DB_DATAOBJECT['RESULTS'])
1715 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1718 foreach ($ids as $id) {
1719 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1720 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1721 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1724 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1725 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1731 * Make a shallow copy of an object and all the fields in the object.
1733 * @param string $daoName
1735 * @param array $criteria
1736 * Array of all the fields & values.
1737 * on which basis to copy
1738 * @param array $newData
1739 * Array of all the fields & values.
1740 * to be copied besides the other fields
1741 * @param string $fieldsFix
1742 * Array of fields that you want to prefix/suffix/replace.
1743 * @param string $blockCopyOfDependencies
1744 * Fields that you want to block from.
1746 * @param bool $blockCopyofCustomValues
1747 * Case when you don't want to copy the custom values set in a
1748 * template as it will override/ignore the submitted custom values
1750 * @return CRM_Core_DAO|bool
1751 * the newly created copy of the object. False if none created.
1753 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1754 $object = new $daoName();
1757 $object->id
= $criteria['id'];
1760 foreach ($criteria as $key => $value) {
1761 $object->$key = $value;
1766 while ($object->fetch()) {
1768 // all the objects except with $blockCopyOfDependencies set
1769 // be copied - addresses #CRM-1962
1771 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1775 $newObject = new $daoName();
1777 $fields = $object->fields();
1778 if (!is_array($fieldsFix)) {
1779 $fieldsToPrefix = [];
1780 $fieldsToSuffix = [];
1781 $fieldsToReplace = [];
1783 if (!empty($fieldsFix['prefix'])) {
1784 $fieldsToPrefix = $fieldsFix['prefix'];
1786 if (!empty($fieldsFix['suffix'])) {
1787 $fieldsToSuffix = $fieldsFix['suffix'];
1789 if (!empty($fieldsFix['replace'])) {
1790 $fieldsToReplace = $fieldsFix['replace'];
1793 foreach ($fields as $name => $value) {
1794 if ($name == 'id' ||
$value['name'] == 'id') {
1795 // copy everything but the id!
1799 $dbName = $value['name'];
1800 $type = CRM_Utils_Type
::typeToString($value['type']);
1801 $newObject->$dbName = $object->$dbName;
1802 if (isset($fieldsToPrefix[$dbName])) {
1803 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1805 if (isset($fieldsToSuffix[$dbName])) {
1806 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1808 if (isset($fieldsToReplace[$dbName])) {
1809 $newObject->$dbName = $fieldsToReplace[$dbName];
1812 if ($type == 'Timestamp' ||
$type == 'Date') {
1813 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1817 $newObject->copyValues($newData);
1821 if (!$blockCopyofCustomValues) {
1822 $newObject->copyCustomFields($object->id
, $newObject->id
);
1824 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1831 * Method that copies custom fields values from an old entity to a new one.
1833 * Fixes bug CRM-19302,
1834 * where if a custom field of File type was present, left both events using the same file,
1835 * breaking download URL's for the old event.
1837 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1838 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1840 * @param int $entityID
1841 * @param int $newEntityID
1843 public function copyCustomFields($entityID, $newEntityID) {
1844 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1845 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1846 // Obtain custom values for old event
1847 $customParams = $htmlType = [];
1848 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1850 // If custom values present, we copy them
1851 if (!empty($customValues)) {
1852 // Get Field ID's and identify File type attributes, to handle file copying.
1853 $fieldIds = implode(', ', array_keys($customValues));
1854 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1855 $result = CRM_Core_DAO
::executeQuery($sql);
1857 // Build array of File type fields
1858 while ($result->fetch()) {
1859 $htmlType[] = $result->id
;
1862 // Build params array of custom values
1863 foreach ($customValues as $field => $value) {
1864 if ($value !== NULL) {
1865 // Handle File type attributes
1866 if (in_array($field, $htmlType)) {
1867 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1868 $customParams["custom_{$field}_-1"] = [
1869 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1870 'type' => $fileValues[1],
1873 // Handle other types
1875 $customParams["custom_{$field}_-1"] = $value;
1880 // Save Custom Fields for new Event
1881 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1884 // copy activity attachments ( if any )
1885 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1889 * Cascade update through related entities.
1891 * @param string $daoName
1894 * @param array $newData
1896 * @return CRM_Core_DAO|null
1898 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1899 $object = new $daoName();
1900 $object->id
= $fromId;
1902 if ($object->find(TRUE)) {
1903 $newObject = new $daoName();
1904 $newObject->id
= $toId;
1906 if ($newObject->find(TRUE)) {
1907 $fields = $object->fields();
1908 foreach ($fields as $name => $value) {
1909 if ($name == 'id' ||
$value['name'] == 'id') {
1910 // copy everything but the id!
1914 $colName = $value['name'];
1915 $newObject->$colName = $object->$colName;
1917 if (substr($name, -5) == '_date' ||
1918 substr($name, -10) == '_date_time'
1920 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1923 foreach ($newData as $k => $v) {
1924 $newObject->$k = $v;
1934 * Given the component id, compute the contact id
1935 * since its used for things like send email
1937 * @param $componentIDs
1938 * @param string $tableName
1939 * @param string $idField
1943 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1946 if (empty($componentIDs)) {
1950 $IDs = implode(',', $componentIDs);
1954 WHERE $idField IN ( $IDs )
1957 $dao = CRM_Core_DAO
::executeQuery($query);
1958 while ($dao->fetch()) {
1959 $contactIDs[] = $dao->contact_id
;
1965 * Fetch object based on array of properties.
1967 * @param string $daoName
1968 * Name of the dao object.
1969 * @param string $fieldIdName
1970 * @param int $fieldId
1972 * @param array $returnProperities
1973 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1976 * an object of type referenced by daoName
1978 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1979 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1980 $object = new $daoName();
1981 $object->$fieldIdName = $fieldId;
1983 // return only specific fields if returnproperties are sent
1984 if (!empty($returnProperities)) {
1985 $object->selectAdd();
1986 $object->selectAdd('id');
1987 $object->selectAdd(implode(',', $returnProperities));
1991 while ($object->fetch()) {
1993 self
::storeValues($object, $defaults);
1994 $details[$object->id
] = $defaults;
2001 * Drop all CiviCRM tables.
2003 * @throws \CRM_Core_Exception
2005 public static function dropAllTables() {
2007 // first drop all the custom tables we've created
2008 CRM_Core_BAO_CustomGroup
::dropAllTables();
2010 // drop all multilingual views
2011 CRM_Core_I18n_Schema
::dropAllViews();
2013 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2014 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2015 '..' . DIRECTORY_SEPARATOR
.
2016 '..' . DIRECTORY_SEPARATOR
.
2017 'sql' . DIRECTORY_SEPARATOR
.
2018 'civicrm_drop.mysql'
2027 public static function escapeString($string) {
2028 static $_dao = NULL;
2030 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2031 // has been installed), then we fallback DB-less str_replace escaping, as
2032 // we can't use mysqli_real_escape_string, as there is no DB connection.
2033 // Note: In typical usage, escapeString() will only check one conditional
2034 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2035 if (!defined('CIVICRM_DSN')) {
2036 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2037 // list of characters mysqli_real_escape_string escapes.
2038 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2039 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2040 return str_replace($search, $replace, $string);
2042 $_dao = new CRM_Core_DAO();
2044 return $_dao->escape($string);
2048 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2050 * @param array $strings
2051 * @param string $default
2052 * the value to use if $strings has no elements.
2054 * eg "abc","def","ghi"
2056 public static function escapeStrings($strings, $default = NULL) {
2057 static $_dao = NULL;
2059 $_dao = new CRM_Core_DAO();
2062 if (empty($strings)) {
2066 $escapes = array_map([$_dao, 'escape'], $strings);
2067 return '"' . implode('","', $escapes) . '"';
2075 public static function escapeWildCardString($string) {
2077 // ensure we escape the single characters % and _ which are mysql wild
2078 // card characters and could come in via sortByCharacter
2079 // note that mysql does not escape these characters
2080 if ($string && in_array($string,
2081 ['%', '_', '%%', '_%']
2084 return '\\' . $string;
2087 return self
::escapeString($string);
2091 * Creates a test object, including any required objects it needs via recursion
2092 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2093 * ONLY USE FOR TESTING
2095 * @param string $daoName
2096 * @param array $params
2097 * @param int $numObjects
2098 * @param bool $createOnly
2100 * @return object|array|NULL
2101 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2103 public static function createTestObject(
2109 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2110 // so we re-set here in case
2111 $config = CRM_Core_Config
::singleton();
2112 $config->backtrace
= TRUE;
2114 static $counter = 0;
2115 CRM_Core_DAO
::$_testEntitiesToSkip = [
2116 'CRM_Core_DAO_Worldregion',
2117 'CRM_Core_DAO_StateProvince',
2118 'CRM_Core_DAO_Country',
2119 'CRM_Core_DAO_Domain',
2120 'CRM_Financial_DAO_FinancialType',
2121 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2124 // Prefer to instantiate BAO's instead of DAO's (when possible)
2125 // so that assignTestValue()/assignTestFK() can be overloaded.
2126 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2127 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2128 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2129 // @todo create a new class called what the BAO SHOULD be
2130 // that extends BAO-crazy-name.... migrate.
2131 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2133 if (class_exists($baoName)) {
2134 $daoName = $baoName;
2137 for ($i = 0; $i < $numObjects; ++
$i) {
2140 /** @var CRM_Core_DAO $object */
2141 $object = new $daoName();
2143 $fields = $object->fields();
2144 foreach ($fields as $fieldName => $fieldDef) {
2145 $dbName = $fieldDef['name'];
2146 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2148 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2149 $object->$dbName = $params[$dbName];
2152 elseif ($dbName != 'id') {
2153 if ($FKClassName != NULL) {
2154 $object->assignTestFK($fieldName, $fieldDef, $params);
2158 $object->assignTestValue($fieldName, $fieldDef, $counter);
2166 $objects[$i] = $object;
2176 elseif ($numObjects == 1) {
2185 * Deletes the this object plus any dependent objects that are associated with it.
2186 * ONLY USE FOR TESTING
2188 * @param string $daoName
2189 * @param array $params
2191 public static function deleteTestObjects($daoName, $params = []) {
2192 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2193 // so we re-set here in case
2194 $config = CRM_Core_Config
::singleton();
2195 $config->backtrace
= TRUE;
2197 $object = new $daoName();
2198 $object->id
= $params['id'] ??
NULL;
2200 // array(array(0 => $daoName, 1 => $daoParams))
2202 if ($object->find(TRUE)) {
2204 $fields = $object->fields();
2205 foreach ($fields as $name => $value) {
2207 $dbName = $value['name'];
2209 $FKClassName = $value['FKClassName'] ??
NULL;
2210 $required = $value['required'] ??
NULL;
2211 if ($FKClassName != NULL
2213 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2214 && ($required ||
$dbName == 'contact_id')
2215 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2216 // to make this test process pass - line below makes pass for now
2217 && $dbName != 'member_of_contact_id'
2220 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2227 foreach ($deletions as $deletion) {
2228 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2233 * Set defaults when creating new entity.
2234 * (don't call this set defaults as already in use with different signature in some places)
2236 * @param array $params
2239 public static function setCreateDefaults(&$params, $defaults) {
2240 if (!empty($params['id'])) {
2243 foreach ($defaults as $key => $value) {
2244 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2245 $params[$key] = $value;
2251 * @param string $prefix
2252 * @param bool $addRandomString
2253 * @param null $string
2257 * @see CRM_Utils_SQL_TempTable
2259 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2260 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2261 $tableName = $prefix . "_temp";
2263 if ($addRandomString) {
2265 $tableName .= "_" . $string;
2268 $tableName .= "_" . md5(uniqid('', TRUE));
2276 * @param bool $trigger
2280 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2281 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2284 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2286 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2287 CRM_Core_TemporaryErrorScope
::ignoreException();
2288 $dao = new CRM_Core_DAO();
2290 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2291 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2297 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2298 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2300 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2305 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2306 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2308 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2315 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2316 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2325 * @param null $message
2326 * @param bool $printDAO
2328 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2329 CRM_Utils_System
::xMemory("{$message}: ");
2332 global $_DB_DATAOBJECT;
2334 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2335 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2337 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2342 * Build a list of triggers via hook and add them to (err, reconcile them
2343 * with) the database.
2345 * @param string $tableName
2346 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2347 * @param bool $force
2352 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2353 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2357 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2358 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2359 * TODO: Alternative solutions might be
2360 * * Stop using functions and find another way to strip numeric characters from phones
2361 * * Give better error messages (currently a missing fn fatals with "unknown error")
2363 public static function checkSqlFunctionsExist() {
2364 if (!self
::$_checkedSqlFunctionsExist) {
2365 self
::$_checkedSqlFunctionsExist = TRUE;
2366 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2367 if (!$dao->fetch()) {
2368 self
::triggerRebuild();
2374 * Wrapper function to drop triggers.
2376 * @param string $tableName
2377 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2380 public static function dropTriggers($tableName = NULL) {
2381 Civi
::service('sql_triggers')->dropTriggers($tableName);
2385 * @param array $info
2386 * per hook_civicrm_triggerInfo.
2387 * @param string $onlyTableName
2388 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2391 public static function createTriggers(&$info, $onlyTableName = NULL) {
2392 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2396 * Given a list of fields, create a list of references.
2398 * @param string $className
2399 * BAO/DAO class name.
2400 * @return array<CRM_Core_Reference_Interface>
2402 public static function createReferenceColumns($className) {
2404 $fields = $className::fields();
2405 foreach ($fields as $field) {
2406 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2407 $result[] = new CRM_Core_Reference_OptionValue(
2408 $className::getTableName(),
2410 'civicrm_option_value',
2411 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2412 $field['pseudoconstant']['optionGroupName']
2420 * Find all records which refer to this entity.
2423 * Array of objects referencing this
2425 public function findReferences() {
2426 $links = self
::getReferencesToTable(static::getTableName());
2429 foreach ($links as $refSpec) {
2430 /** @var $refSpec CRM_Core_Reference_Interface */
2431 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2432 $result = $refSpec->findReferences($this);
2434 while ($result->fetch()) {
2435 $obj = new $daoName();
2436 $obj->id
= $result->id
;
2437 $occurrences[] = $obj;
2442 return $occurrences;
2447 * each item has keys:
2451 * - table: string|null SQL table name
2452 * - key: string|null SQL column name
2454 public function getReferenceCounts() {
2455 $links = self
::getReferencesToTable(static::getTableName());
2458 foreach ($links as $refSpec) {
2459 /** @var $refSpec CRM_Core_Reference_Interface */
2460 $count = $refSpec->getReferenceCount($this);
2461 if ($count['count'] != 0) {
2466 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2467 /** @var $component CRM_Core_Component_Info */
2468 $counts = array_merge($counts, $component->getReferenceCounts($this));
2470 CRM_Utils_Hook
::referenceCounts($this, $counts);
2476 * List all tables which have hard foreign keys to this table.
2478 * For now, this returns a description of every entity_id/entity_table
2480 * TODO: filter dynamic entity references on the $tableName, based on
2481 * schema metadata in dynamicForeignKey which enumerates a restricted
2482 * set of possible entity_table's.
2484 * @param string $tableName
2485 * Table referred to.
2488 * structure of table and column, listing every table with a
2489 * foreign key reference to $tableName, and the column where the key appears.
2491 public static function getReferencesToTable($tableName) {
2493 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2494 $links = $daoClassName::getReferenceColumns();
2496 foreach ($links as $refSpec) {
2497 /** @var $refSpec CRM_Core_Reference_Interface */
2498 if ($refSpec->matchesTargetTable($tableName)) {
2499 $refsFound[] = $refSpec;
2507 * Get all references to contact table.
2509 * This includes core tables, custom group tables, tables added by the merge
2510 * hook and the entity_tag table.
2512 * Refer to CRM-17454 for information on the danger of querying the information
2513 * schema to derive this.
2515 * @throws \CiviCRM_API3_Exception
2517 public static function getReferencesToContactTable() {
2518 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2519 return \Civi
::$statics[__CLASS__
]['contact_references'];
2521 $contactReferences = [];
2522 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2523 foreach ($coreReferences as $coreReference) {
2524 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2525 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2528 self
::appendCustomTablesExtendingContacts($contactReferences);
2529 self
::appendCustomContactReferenceFields($contactReferences);
2530 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2531 return \Civi
::$statics[__CLASS__
]['contact_references'];
2535 * Get all dynamic references to the given table.
2537 * @param string $tableName
2541 public static function getDynamicReferencesToTable($tableName) {
2542 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2543 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2544 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2545 foreach ($coreReferences as $coreReference) {
2546 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2547 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2551 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2555 * Add custom tables that extend contacts to the list of contact references.
2557 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2558 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2559 * - the down side is it is not cached.
2561 * Further changes should be include tests in the CRM_Core_MergerTest class
2562 * to ensure that disabled, subtype, multiple etc groups are still captured.
2564 * @param array $cidRefs
2566 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2567 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2568 $customValueTables->find();
2569 while ($customValueTables->fetch()) {
2570 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2575 * Add custom ContactReference fields to the list of contact references
2577 * This includes active and inactive fields/groups
2579 * @param array $cidRefs
2581 * @throws \CiviCRM_API3_Exception
2583 public static function appendCustomContactReferenceFields(&$cidRefs) {
2584 $fields = civicrm_api3('CustomField', 'get', [
2585 'return' => ['column_name', 'custom_group_id.table_name'],
2586 'data_type' => 'ContactReference',
2587 'options' => ['limit' => 0],
2589 foreach ($fields as $field) {
2590 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2595 * Lookup the value of a MySQL global configuration variable.
2597 * @param string $name
2598 * E.g. "thread_stack".
2599 * @param mixed $default
2602 public static function getGlobalSetting($name, $default = NULL) {
2603 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2604 // that has been reported to fail under MySQL 5.0 for OS X
2605 $escapedName = self
::escapeString($name);
2606 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2607 if ($dao->fetch()) {
2616 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2618 * This is relevant where we want to offer both the ID field and the label field
2619 * as an option, e.g. search builder.
2621 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2622 * change small, but is appropriate for other sorts of pseudoconstants.
2624 * @param array $fields
2626 public static function appendPseudoConstantsToFields(&$fields) {
2627 foreach ($fields as $fieldUniqueName => $field) {
2628 if (!empty($field['pseudoconstant'])) {
2629 $pseudoConstant = $field['pseudoconstant'];
2630 if (!empty($pseudoConstant['optionGroupName'])) {
2631 $fields[$pseudoConstant['optionGroupName']] = [
2632 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2633 'name' => $pseudoConstant['optionGroupName'],
2634 'data_type' => CRM_Utils_Type
::T_STRING
,
2635 'is_pseudofield_for' => $fieldUniqueName,
2638 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2640 !empty($field['FKClassName'])
2641 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2642 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2644 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2645 // This if is just an extra caution when adding change.
2646 if (!isset($fields[$pseudoFieldName])) {
2647 $daoName = $field['FKClassName'];
2648 $fkFields = $daoName::fields();
2649 foreach ($fkFields as $fkField) {
2650 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2651 $fields[$pseudoFieldName] = [
2652 'name' => $pseudoFieldName,
2653 'is_pseudofield_for' => $field['name'],
2654 'title' => $fkField['title'],
2655 'data_type' => $fkField['type'],
2656 'where' => $field['where'],
2667 * Get options for the called BAO object's field.
2669 * This function can be overridden by each BAO to add more logic related to context.
2670 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2672 * @param string $fieldName
2673 * @param string $context
2674 * @see CRM_Core_DAO::buildOptionsContext
2675 * @param array $props
2676 * Raw field values; whatever is known about this bao object.
2678 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2680 * @return array|bool
2682 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2683 // If a given bao does not override this function
2684 $baoName = get_called_class();
2685 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2689 * Populate option labels for this object's fields.
2691 * @throws exception if called directly on the base class
2693 public function getOptionLabels() {
2694 $fields = $this->fields();
2695 if ($fields === NULL) {
2696 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2698 foreach ($fields as $field) {
2699 $name = $field['name'] ??
NULL;
2700 if ($name && isset($this->$name)) {
2701 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2702 if ($label !== FALSE) {
2703 // Append 'label' onto the field name
2704 $labelName = $name . '_label';
2705 $this->$labelName = $label;
2712 * Provides documentation and validation for the buildOptions $context param
2714 * @param string $context
2716 * @throws CRM_Core_Exception
2719 public static function buildOptionsContext($context = NULL) {
2721 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2722 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2723 'search' => "search: searchable options are returned; labels are translated.",
2724 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2725 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2726 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2728 // Validation: enforce uniformity of this param
2729 if ($context !== NULL && !isset($contexts[$context])) {
2730 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2736 * @param string $fieldName
2737 * @return bool|array
2739 public function getFieldSpec($fieldName) {
2740 $fields = $this->fields();
2742 // Support "unique names" as well as sql names
2743 $fieldKey = $fieldName;
2744 if (empty($fields[$fieldKey])) {
2745 $fieldKeys = $this->fieldKeys();
2746 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2748 // If neither worked then this field doesn't exist. Return false.
2749 if (empty($fields[$fieldKey])) {
2752 return $fields[$fieldKey];
2756 * Get SQL where clause for SQL filter syntax input parameters.
2758 * SQL version of api function to assign filters to the DAO based on the syntax
2759 * $field => array('IN' => array(4,6,9))
2761 * $field => array('LIKE' => array('%me%))
2764 * @param string $fieldName
2766 * @param array $filter
2767 * filter to be applied indexed by operator.
2768 * @param string $type
2769 * type of field (not actually used - nor in api @todo ).
2770 * @param string $alias
2771 * alternative field name ('as') @todo- not actually used.
2772 * @param bool $returnSanitisedArray
2773 * Return a sanitised array instead of a clause.
2774 * this is primarily so we can add filters @ the api level to the Query object based fields
2778 * @return NULL|string|array
2779 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2780 * depending on whether it is supported as yet
2782 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2783 foreach ($filter as $operator => $criteria) {
2784 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2785 switch ($operator) {
2789 if (!$returnSanitisedArray) {
2790 return (sprintf('%s %s', $fieldName, $operator));
2793 return (sprintf('%s %s ', $fieldName, $operator));
2797 // ternary operators
2800 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2801 throw new Exception("invalid criteria for $operator");
2803 if (!$returnSanitisedArray) {
2804 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2807 // not yet implemented (tests required to implement)
2815 if (empty($criteria)) {
2816 throw new Exception("invalid criteria for $operator");
2818 $escapedCriteria = array_map([
2822 if (!$returnSanitisedArray) {
2823 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2825 return $escapedCriteria;
2830 if (!$returnSanitisedArray) {
2831 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2834 // not yet implemented (tests required to implement)
2843 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2844 * support for other syntaxes is discussed in ticket but being put off for now
2847 public static function acceptedSQLOperators() {
2868 * SQL has a limit of 64 characters on various names:
2869 * table name, trigger name, column name ...
2871 * For custom groups and fields we generated names from user entered input
2872 * which can be longer than this length, this function helps with creating
2873 * strings that meet various criteria.
2875 * @param string $string
2876 * The string to be shortened.
2877 * @param int $length
2878 * The max length of the string.
2880 * @param bool $makeRandom
2884 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2885 // early return for strings that meet the requirements
2886 if (strlen($string) <= $length) {
2890 // easy return for calls that dont need a randomized uniq string
2892 return substr($string, 0, $length);
2895 // the string is longer than the length and we need a uniq string
2896 // for the same tablename we need the same uniq string every time
2897 // hence we use md5 on the string, which is not random
2898 // we'll append 8 characters to the end of the tableName
2899 $md5string = substr(md5($string), 0, 8);
2900 return substr($string, 0, $length - 8) . "_{$md5string}";
2904 * https://issues.civicrm.org/jira/browse/CRM-17748
2905 * Sets the internal options to be used on a query
2907 * @param array $options
2910 public function setOptions($options) {
2911 if (is_array($options)) {
2912 $this->_options
= $options;
2917 * https://issues.civicrm.org/jira/browse/CRM-17748
2918 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2920 * @param array $options
2923 protected function _setDBOptions($options) {
2924 global $_DB_DATAOBJECT;
2926 if (is_array($options) && count($options)) {
2927 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2928 foreach ($options as $option_name => $option_value) {
2929 $conn->setOption($option_name, $option_value);
2936 * @param array $params
2938 public function setApiFilter(&$params) {
2942 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2944 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2947 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2951 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2955 public function addSelectWhereClause() {
2957 $fields = $this->fields();
2958 foreach ($fields as $fieldName => $field) {
2959 // Clause for contact-related entities like Email, Relationship, etc.
2960 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2961 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2963 // Clause for an entity_table/entity_id combo
2964 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2965 $relatedClauses = [];
2966 $relatedEntities = $this->buildOptions('entity_table', 'get');
2967 foreach ((array) $relatedEntities as $table => $ent) {
2969 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2970 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2972 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2975 $relatedClauses[] = "(entity_table = '$table')";
2979 if ($relatedClauses) {
2980 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2984 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2989 * This returns the final permissioned query string for this entity
2991 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2993 * @param string $tableAlias
2996 public static function getSelectWhereClause($tableAlias = NULL) {
2997 $bao = new static();
2998 if ($tableAlias === NULL) {
2999 $tableAlias = $bao->tableName();
3002 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
3003 $clauses[$field] = NULL;
3005 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
3012 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3013 * and dashes, and contains at least one [a-z] case insenstive.
3019 public static function requireSafeDBName($database) {
3022 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3026 if (empty($matches)) {
3033 * Transform an array to a serialized string for database storage.
3035 * @param array|null $value
3036 * @param int $serializationType
3037 * @return string|null
3039 * @throws \Exception
3041 public static function serializeField($value, $serializationType) {
3042 if ($value === NULL) {
3045 switch ($serializationType) {
3046 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3047 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3049 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3050 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3052 case self
::SERIALIZE_JSON
:
3053 return is_array($value) ?
json_encode($value) : $value;
3055 case self
::SERIALIZE_PHP
:
3056 return is_array($value) ?
serialize($value) : $value;
3058 case self
::SERIALIZE_COMMA
:
3059 return is_array($value) ?
implode(',', $value) : $value;
3062 throw new Exception('Unknown serialization method for field.');
3067 * Transform a serialized string from the database into an array.
3069 * @param string|null $value
3070 * @param $serializationType
3072 * @return array|null
3073 * @throws CRM_Core_Exception
3075 public static function unSerializeField($value, $serializationType) {
3076 if ($value === NULL) {
3079 if ($value === '') {
3082 switch ($serializationType) {
3083 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3084 return (array) CRM_Utils_Array
::explodePadded($value);
3086 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3087 return explode(self
::VALUE_SEPARATOR
, trim($value));
3089 case self
::SERIALIZE_JSON
:
3090 return strlen($value) ?
json_decode($value, TRUE) : [];
3092 case self
::SERIALIZE_PHP
:
3093 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3095 case self
::SERIALIZE_COMMA
:
3096 return explode(',', trim(str_replace(', ', '', $value)));
3099 throw new CRM_Core_Exception('Unknown serialization method for field.');
3106 public static function getEntityRefFilters() {
3111 * Get exportable fields with pseudoconstants rendered as an extra field.
3113 * @param string $baoClass
3117 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3118 if (method_exists($baoClass, 'exportableFields')) {
3119 $fields = $baoClass::exportableFields();
3122 $fields = $baoClass::export();
3124 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3129 * Remove item from static cache during update/delete operations
3131 private function clearDbColumnValueCache() {
3132 $daoName = get_class($this);
3133 while (strpos($daoName, '_BAO_') !== FALSE) {
3134 $daoName = get_parent_class($daoName);
3136 if (isset($this->id
)) {
3137 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3139 if (isset($this->name
)) {
3140 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);
3145 * Return a mapping from field-name to the corresponding key (as used in fields()).
3148 * Array(string $name => string $uniqueName).
3150 public static function fieldKeys() {
3151 return array_flip(CRM_Utils_Array
::collect('name', static::fields()));