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 // No ts() since this is a sysadmin-y string not seen by general users.
762 Civi
::log()->warning('A string for field {dbName} has been truncated. The original string was {value}.', ['dbName' => $dbName, 'value' => $value]);
763 // The string is too long - what to do what to do? Well losing data is generally bad so let's truncate
764 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
766 $this->$dbName = $value;
775 * Store all the values from this object in an associative array
776 * this is a destructive store, calling function is responsible
777 * for keeping sanity of id's.
779 * @param object $object
780 * The object that we are extracting data from.
781 * @param array $values
782 * (reference ) associative array of name/value pairs.
784 public static function storeValues(&$object, &$values) {
785 $fields = $object->fields();
786 foreach ($fields as $name => $value) {
787 $dbName = $value['name'];
788 if (isset($object->$dbName) && $object->$dbName !== 'null') {
789 $values[$dbName] = $object->$dbName;
790 if ($name != $dbName) {
791 $values[$name] = $object->$dbName;
798 * Create an attribute for this specific field. We only do this for strings and text
800 * @param array $field
801 * The field under task.
804 * the attributes for the object
806 public static function makeAttribute($field) {
808 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
809 $maxLength = $field['maxlength'] ??
NULL;
810 $size = $field['size'] ??
NULL;
811 if ($maxLength ||
$size) {
814 $attributes['maxlength'] = $maxLength;
817 $attributes['size'] = $size;
822 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
823 $rows = $field['rows'] ??
NULL;
827 $cols = $field['cols'] ??
NULL;
833 $attributes['rows'] = $rows;
834 $attributes['cols'] = $cols;
837 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
) {
838 $attributes['size'] = 6;
839 $attributes['maxlength'] = 14;
847 * Get the size and maxLength attributes for this text field.
848 * (or for all text fields) in the DAO object.
850 * @param string $class
852 * @param string $fieldName
853 * Field that i'm interested in or null if.
854 * you want the attributes for all DAO text fields
857 * assoc array of name => attribute pairs
859 public static function getAttribute($class, $fieldName = NULL) {
860 $object = new $class();
861 $fields = $object->fields();
862 if ($fieldName != NULL) {
863 $field = $fields[$fieldName] ??
NULL;
864 return self
::makeAttribute($field);
868 foreach ($fields as $name => $field) {
869 $attribute = self
::makeAttribute($field);
871 $attributes[$name] = $attribute;
875 if (!empty($attributes)) {
883 * Create or update a record from supplied params.
885 * If 'id' is supplied, an existing record will be updated
886 * Otherwise a new record will be created.
888 * @param array $record
889 * @return CRM_Core_DAO
890 * @throws CRM_Core_Exception
892 public static function writeRecord(array $record) {
893 $hook = empty($record['id']) ?
'create' : 'edit';
894 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
895 if ($className === 'CRM_Core_DAO') {
896 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
898 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
900 \CRM_Utils_Hook
::pre($hook, $entityName, $record['id'] ??
NULL, $record);
901 $instance = new $className();
902 $instance->copyValues($record);
904 \CRM_Utils_Hook
::post($hook, $entityName, $instance->id
, $instance);
910 * Delete a record from supplied params.
912 * @param array $record
914 * @return CRM_Core_DAO
915 * @throws CRM_Core_Exception
917 public static function deleteRecord(array $record) {
918 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
919 if ($className === 'CRM_Core_DAO') {
920 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
922 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
923 if (empty($record['id'])) {
924 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
927 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
928 $instance = new $className();
929 $instance->id
= $record['id'];
930 if (!$instance->delete()) {
931 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
933 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
939 * Check if there is a record with the same name in the db.
941 * @param string $value
942 * The value of the field we are checking.
943 * @param string $daoName
944 * The dao object name.
945 * @param string $daoID
946 * The id of the object being updated. u can change your name.
947 * as long as there is no conflict
948 * @param string $fieldName
949 * The name of the field in the DAO.
951 * @param string $domainID
952 * The id of the domain. Object exists only for the given domain.
955 * true if object exists
957 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
958 $object = new $daoName();
959 $object->$fieldName = $value;
961 $object->domain_id
= $domainID;
964 if ($object->find(TRUE)) {
965 return $daoID && $object->id
== $daoID;
973 * Check if there is a given column in a specific table.
976 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
978 * @param string $tableName
979 * @param string $columnName
980 * @param bool $i18nRewrite
981 * Whether to rewrite the query on multilingual setups.
984 * true if exists, else false
986 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
987 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
988 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
992 * Scans all the tables using a slow query and table name.
996 public static function getTableNames() {
997 $dao = CRM_Core_DAO
::executeQuery(
999 FROM information_schema.TABLES
1000 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1001 AND TABLE_NAME LIKE 'civicrm_%'
1002 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1003 AND TABLE_NAME NOT LIKE '%_temp%'
1006 while ($dao->fetch()) {
1007 $values[] = $dao->TABLE_NAME
;
1013 * @param int $maxTablesToCheck
1017 public static function isDBMyISAM($maxTablesToCheck = 10) {
1018 return CRM_Core_DAO
::singleValueQuery(
1020 FROM information_schema.TABLES
1021 WHERE ENGINE = 'MyISAM'
1022 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1023 AND TABLE_NAME LIKE 'civicrm_%'
1024 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1025 AND TABLE_NAME NOT LIKE '%_temp%'
1026 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1031 * Get the name of the CiviCRM database.
1035 public static function getDatabaseName() {
1036 $daoObj = new CRM_Core_DAO();
1037 return $daoObj->database();
1041 * Checks if a constraint exists for a specified table.
1043 * @param string $tableName
1044 * @param string $constraint
1047 * true if constraint exists, false otherwise
1049 * @throws \CRM_Core_Exception
1051 public static function checkConstraintExists($tableName, $constraint) {
1054 if (!array_key_exists($tableName, $show)) {
1055 $query = "SHOW CREATE TABLE $tableName";
1056 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1058 if (!$dao->fetch()) {
1059 throw new CRM_Core_Exception('query failed');
1062 $show[$tableName] = $dao->Create_Table
;
1065 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1069 * Checks if CONSTRAINT keyword exists for a specified table.
1071 * @param array $tables
1073 * @throws CRM_Core_Exception
1076 * true if CONSTRAINT keyword exists, false otherwise
1078 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1080 foreach ($tables as $tableName) {
1081 if (!array_key_exists($tableName, $show)) {
1082 $query = "SHOW CREATE TABLE $tableName";
1083 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1085 if (!$dao->fetch()) {
1086 throw new CRM_Core_Exception('Show create table failed.');
1089 $show[$tableName] = $dao->Create_Table
;
1092 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1093 if ($result == TRUE) {
1104 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1105 * for a specified column of a table.
1107 * @param string $tableName
1108 * @param string $columnName
1111 * true if in format, false otherwise
1113 * @throws \CRM_Core_Exception
1115 public static function checkFKConstraintInFormat($tableName, $columnName) {
1118 if (!array_key_exists($tableName, $show)) {
1119 $query = "SHOW CREATE TABLE $tableName";
1120 $dao = CRM_Core_DAO
::executeQuery($query);
1122 if (!$dao->fetch()) {
1123 throw new CRM_Core_Exception('query failed');
1126 $show[$tableName] = $dao->Create_Table
;
1128 $constraint = "`FK_{$tableName}_{$columnName}`";
1129 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1130 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1134 * Check whether a specific column in a specific table has always the same value.
1136 * @param string $tableName
1137 * @param string $columnName
1138 * @param string $columnValue
1141 * true if the value is always $columnValue, false otherwise
1143 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1144 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1145 $dao = CRM_Core_DAO
::executeQuery($query);
1146 $result = $dao->fetch() ?
FALSE : TRUE;
1151 * Check whether a specific column in a specific table is always NULL.
1153 * @param string $tableName
1154 * @param string $columnName
1157 * true if if the value is always NULL, false otherwise
1159 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1160 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1161 $dao = CRM_Core_DAO
::executeQuery($query);
1162 $result = $dao->fetch() ?
FALSE : TRUE;
1167 * Checks if this DAO's table ought to exist.
1169 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1172 * @throws CRM_Core_Exception
1174 public static function tableHasBeenAdded() {
1175 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1178 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1179 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1180 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1184 * Check if there is a given table in the database.
1186 * @param string $tableName
1189 * true if exists, else false
1191 public static function checkTableExists($tableName) {
1196 $params = [1 => [$tableName, 'String']];
1198 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1199 return (bool) $dao->fetch();
1203 * Check if a given table has data.
1205 * @param string $tableName
1207 * TRUE if $tableName has at least one record.
1209 public static function checkTableHasData($tableName) {
1210 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1219 public function checkVersion($version) {
1220 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1221 $dbVersion = CRM_Core_BAO_Domain
::version();
1222 return trim($version) == trim($dbVersion);
1226 * Find a DAO object for the given ID and return it.
1229 * Id of the DAO object being searched for.
1231 * @return CRM_Core_DAO
1232 * Object of the type of the class that called this function.
1236 public static function findById($id) {
1237 $object = new static();
1239 if (!$object->find(TRUE)) {
1240 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1246 * Returns all results as array-encoded records.
1250 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1252 while ($this->fetch()) {
1253 $result[] = $this->toArray();
1259 * Return the results as PHP generator.
1261 * @param string $type
1262 * Whether the generator yields 'dao' objects or 'array's.
1264 public function fetchGenerator($type = 'dao') {
1265 while ($this->fetch()) {
1272 yield
$this->toArray();
1276 throw new \
RuntimeException("Invalid record type ($type)");
1282 * Returns a singular value.
1284 * @return mixed|NULL
1286 public function fetchValue() {
1287 $result = $this->getDatabaseResult();
1288 $row = $result->fetchRow();
1298 * Get all the result records as mapping between columns.
1300 * @param string $keyColumn
1302 * @param string $valueColumn
1305 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1307 public function fetchMap($keyColumn, $valueColumn) {
1309 while ($this->fetch()) {
1310 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1316 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1318 * @param string $daoName
1319 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1320 * @param int $searchValue
1321 * Value of the column you want to search by.
1322 * @param string $returnColumn
1323 * Name of the column you want to GET the value of.
1324 * @param string $searchColumn
1325 * Name of the column you want to search by.
1326 * @param bool $force
1327 * Skip use of the cache.
1329 * @return string|int|null
1330 * Value of $returnColumn in the retrieved record
1332 * @throws \CRM_Core_Exception
1334 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1336 empty($searchValue) ||
1337 trim(strtolower($searchValue)) == 'null'
1339 // adding this here since developers forget to check for an id
1340 // or for the 'null' (which is a bad DAO kludge)
1341 // and hence we get the first value in the db
1342 throw new CRM_Core_Exception('getFieldValue failed');
1345 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1347 while (strpos($daoName, '_BAO_') !== FALSE) {
1348 $daoName = get_parent_class($daoName);
1352 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1353 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1355 $object = new $daoName();
1356 $object->$searchColumn = $searchValue;
1357 $object->selectAdd();
1358 $object->selectAdd($returnColumn);
1361 if ($object->find(TRUE)) {
1362 $result = $object->$returnColumn;
1365 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1367 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1371 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1373 * @param string $daoName
1374 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1375 * @param int $searchValue
1376 * Value of the column you want to search by.
1377 * @param string $setColumn
1378 * Name of the column you want to SET the value of.
1379 * @param string $setValue
1380 * SET the setColumn to this value.
1381 * @param string $searchColumn
1382 * Name of the column you want to search by.
1385 * true if we found and updated the object, else false
1387 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1388 $object = new $daoName();
1389 $object->selectAdd();
1390 $object->selectAdd("$searchColumn, $setColumn");
1391 $object->$searchColumn = $searchValue;
1393 if ($object->find(TRUE)) {
1394 $object->$setColumn = $setValue;
1395 if ($object->save()) {
1406 * @param array|object $sort either array or CRM_Utils_Sort
1407 * @param string $default
1408 * Default sort value.
1412 public static function getSortString($sort, $default = NULL) {
1413 // check if sort is of type CRM_Utils_Sort
1414 if (is_a($sort, 'CRM_Utils_Sort')) {
1415 return $sort->orderBy();
1420 // is it an array specified as $field => $sortDirection ?
1422 foreach ($sort as $k => $v) {
1423 $sortString .= "$k $v,";
1425 return rtrim($sortString, ',');
1431 * Fetch object based on array of properties.
1433 * @param string $daoName
1434 * Name of the dao object.
1435 * @param array $params
1436 * (reference ) an assoc array of name/value pairs.
1437 * @param array $defaults
1438 * (reference ) an assoc array to hold the flattened values.
1439 * @param array $returnProperities
1440 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1443 * an object of type referenced by daoName
1445 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1446 $object = new $daoName();
1447 $object->copyValues($params);
1449 // return only specific fields if returnproperties are sent
1450 if (!empty($returnProperities)) {
1451 $object->selectAdd();
1452 $object->selectAdd(implode(',', $returnProperities));
1455 if ($object->find(TRUE)) {
1456 self
::storeValues($object, $defaults);
1463 * Delete the object records that are associated with this contact.
1465 * @param string $daoName
1466 * Name of the dao object.
1467 * @param int $contactId
1468 * Id of the contact to delete.
1470 public static function deleteEntityContact($daoName, $contactId) {
1471 $object = new $daoName();
1473 $object->entity_table
= 'civicrm_contact';
1474 $object->entity_id
= $contactId;
1479 * Execute an unbuffered query.
1481 * This is a wrapper around new functionality exposed with CRM-17748.
1483 * @param string $query query to be executed
1485 * @param array $params
1486 * @param bool $abort
1487 * @param null $daoName
1488 * @param bool $freeDAO
1489 * @param bool $i18nRewrite
1490 * @param bool $trapException
1492 * @return CRM_Core_DAO
1493 * Object that points to an unbuffered result set
1495 public static function executeUnbufferedQuery(
1501 $i18nRewrite = TRUE,
1502 $trapException = FALSE
1505 return self
::executeQuery(
1513 ['result_buffering' => 0]
1520 * @param string $query
1521 * Query to be executed.
1523 * @param array $params
1524 * @param bool $abort
1525 * @param null $daoName
1526 * @param bool $freeDAO
1527 * @param bool $i18nRewrite
1528 * @param bool $trapException
1529 * @param array $options
1531 * @return CRM_Core_DAO|object
1532 * object that holds the results of the query
1533 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1534 * out all the properties that are not part of the DAO
1536 public static function &executeQuery(
1542 $i18nRewrite = TRUE,
1543 $trapException = FALSE,
1546 $queryStr = self
::composeQuery($query, $params, $abort);
1549 $dao = new CRM_Core_DAO();
1552 $dao = new $daoName();
1555 if ($trapException) {
1556 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1557 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1560 if ($dao->isValidOption($options)) {
1561 $dao->setOptions($options);
1564 $result = $dao->query($queryStr, $i18nRewrite);
1566 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1567 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1571 if (is_a($result, 'DB_Error')) {
1572 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1580 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1582 * @param array $options
1585 * Provided options are valid
1587 public function isValidOption($options) {
1596 if (empty($options)) {
1600 foreach (array_keys($options) as $option) {
1601 if (!in_array($option, $validOptions)) {
1611 * Execute a query and get the single result.
1613 * @param string $query
1614 * Query to be executed.
1615 * @param array $params
1616 * @param bool $abort
1617 * @param bool $i18nRewrite
1618 * @return string|null
1619 * the result of the query if any
1622 public static function &singleValueQuery(
1628 $queryStr = self
::composeQuery($query, $params, $abort);
1630 static $_dao = NULL;
1633 $_dao = new CRM_Core_DAO();
1636 $_dao->query($queryStr, $i18nRewrite);
1638 $result = $_dao->getDatabaseResult();
1641 $row = $result->fetchRow();
1651 * Compose the query by merging the parameters into it.
1653 * @param string $query
1654 * @param array $params
1655 * @param bool $abort
1658 * @throws CRM_Core_Exception
1660 public static function composeQuery($query, $params = [], $abort = TRUE) {
1662 foreach ($params as $key => $item) {
1663 if (is_numeric($key)) {
1664 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1665 $item[0] = self
::escapeString($item[0]);
1666 if ($item[1] == 'String' ||
1667 $item[1] == 'Memo' ||
1670 // Support class constants stipulating wildcard characters and/or
1671 // non-quoting of strings. Also support legacy code which may be
1672 // passing in TRUE or 1 for $item[2], which used to indicate the
1673 // use of wildcard characters.
1674 if (!empty($item[2])) {
1675 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1676 $item[0] = "'%{$item[0]}%'";
1678 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1679 $item[0] = "'{$item[0]}'";
1683 $item[0] = "'{$item[0]}'";
1687 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1688 strlen($item[0]) == 0
1693 $tr['%' . $key] = $item[0];
1696 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1701 return strtr($query, $tr);
1707 public static function freeResult($ids = NULL) {
1708 global $_DB_DATAOBJECT;
1711 if (!$_DB_DATAOBJECT ||
1712 !isset($_DB_DATAOBJECT['RESULTS'])
1716 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1719 foreach ($ids as $id) {
1720 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1721 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1722 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1725 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1726 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1732 * Make a shallow copy of an object and all the fields in the object.
1734 * @param string $daoName
1736 * @param array $criteria
1737 * Array of all the fields & values.
1738 * on which basis to copy
1739 * @param array $newData
1740 * Array of all the fields & values.
1741 * to be copied besides the other fields
1742 * @param string $fieldsFix
1743 * Array of fields that you want to prefix/suffix/replace.
1744 * @param string $blockCopyOfDependencies
1745 * Fields that you want to block from.
1747 * @param bool $blockCopyofCustomValues
1748 * Case when you don't want to copy the custom values set in a
1749 * template as it will override/ignore the submitted custom values
1751 * @return CRM_Core_DAO|bool
1752 * the newly created copy of the object. False if none created.
1754 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1755 $object = new $daoName();
1758 $object->id
= $criteria['id'];
1761 foreach ($criteria as $key => $value) {
1762 $object->$key = $value;
1767 while ($object->fetch()) {
1769 // all the objects except with $blockCopyOfDependencies set
1770 // be copied - addresses #CRM-1962
1772 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1776 $newObject = new $daoName();
1778 $fields = $object->fields();
1779 if (!is_array($fieldsFix)) {
1780 $fieldsToPrefix = [];
1781 $fieldsToSuffix = [];
1782 $fieldsToReplace = [];
1784 if (!empty($fieldsFix['prefix'])) {
1785 $fieldsToPrefix = $fieldsFix['prefix'];
1787 if (!empty($fieldsFix['suffix'])) {
1788 $fieldsToSuffix = $fieldsFix['suffix'];
1790 if (!empty($fieldsFix['replace'])) {
1791 $fieldsToReplace = $fieldsFix['replace'];
1794 foreach ($fields as $name => $value) {
1795 if ($name == 'id' ||
$value['name'] == 'id') {
1796 // copy everything but the id!
1800 $dbName = $value['name'];
1801 $type = CRM_Utils_Type
::typeToString($value['type']);
1802 $newObject->$dbName = $object->$dbName;
1803 if (isset($fieldsToPrefix[$dbName])) {
1804 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1806 if (isset($fieldsToSuffix[$dbName])) {
1807 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1809 if (isset($fieldsToReplace[$dbName])) {
1810 $newObject->$dbName = $fieldsToReplace[$dbName];
1813 if ($type == 'Timestamp' ||
$type == 'Date') {
1814 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1818 $newObject->copyValues($newData);
1822 if (!$blockCopyofCustomValues) {
1823 $newObject->copyCustomFields($object->id
, $newObject->id
);
1825 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1832 * Method that copies custom fields values from an old entity to a new one.
1834 * Fixes bug CRM-19302,
1835 * where if a custom field of File type was present, left both events using the same file,
1836 * breaking download URL's for the old event.
1838 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1839 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1841 * @param int $entityID
1842 * @param int $newEntityID
1844 public function copyCustomFields($entityID, $newEntityID) {
1845 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1846 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1847 // Obtain custom values for old event
1848 $customParams = $htmlType = [];
1849 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1851 // If custom values present, we copy them
1852 if (!empty($customValues)) {
1853 // Get Field ID's and identify File type attributes, to handle file copying.
1854 $fieldIds = implode(', ', array_keys($customValues));
1855 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1856 $result = CRM_Core_DAO
::executeQuery($sql);
1858 // Build array of File type fields
1859 while ($result->fetch()) {
1860 $htmlType[] = $result->id
;
1863 // Build params array of custom values
1864 foreach ($customValues as $field => $value) {
1865 if ($value !== NULL) {
1866 // Handle File type attributes
1867 if (in_array($field, $htmlType)) {
1868 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1869 $customParams["custom_{$field}_-1"] = [
1870 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1871 'type' => $fileValues[1],
1874 // Handle other types
1876 $customParams["custom_{$field}_-1"] = $value;
1881 // Save Custom Fields for new Event
1882 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1885 // copy activity attachments ( if any )
1886 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1890 * Cascade update through related entities.
1892 * @param string $daoName
1895 * @param array $newData
1897 * @return CRM_Core_DAO|null
1899 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1900 $object = new $daoName();
1901 $object->id
= $fromId;
1903 if ($object->find(TRUE)) {
1904 $newObject = new $daoName();
1905 $newObject->id
= $toId;
1907 if ($newObject->find(TRUE)) {
1908 $fields = $object->fields();
1909 foreach ($fields as $name => $value) {
1910 if ($name == 'id' ||
$value['name'] == 'id') {
1911 // copy everything but the id!
1915 $colName = $value['name'];
1916 $newObject->$colName = $object->$colName;
1918 if (substr($name, -5) == '_date' ||
1919 substr($name, -10) == '_date_time'
1921 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1924 foreach ($newData as $k => $v) {
1925 $newObject->$k = $v;
1935 * Given the component id, compute the contact id
1936 * since its used for things like send email
1938 * @param $componentIDs
1939 * @param string $tableName
1940 * @param string $idField
1944 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1947 if (empty($componentIDs)) {
1951 $IDs = implode(',', $componentIDs);
1955 WHERE $idField IN ( $IDs )
1958 $dao = CRM_Core_DAO
::executeQuery($query);
1959 while ($dao->fetch()) {
1960 $contactIDs[] = $dao->contact_id
;
1966 * Fetch object based on array of properties.
1968 * @param string $daoName
1969 * Name of the dao object.
1970 * @param string $fieldIdName
1971 * @param int $fieldId
1973 * @param array $returnProperities
1974 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1977 * an object of type referenced by daoName
1979 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1980 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1981 $object = new $daoName();
1982 $object->$fieldIdName = $fieldId;
1984 // return only specific fields if returnproperties are sent
1985 if (!empty($returnProperities)) {
1986 $object->selectAdd();
1987 $object->selectAdd('id');
1988 $object->selectAdd(implode(',', $returnProperities));
1992 while ($object->fetch()) {
1994 self
::storeValues($object, $defaults);
1995 $details[$object->id
] = $defaults;
2002 * Drop all CiviCRM tables.
2004 * @throws \CRM_Core_Exception
2006 public static function dropAllTables() {
2008 // first drop all the custom tables we've created
2009 CRM_Core_BAO_CustomGroup
::dropAllTables();
2011 // drop all multilingual views
2012 CRM_Core_I18n_Schema
::dropAllViews();
2014 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2015 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2016 '..' . DIRECTORY_SEPARATOR
.
2017 '..' . DIRECTORY_SEPARATOR
.
2018 'sql' . DIRECTORY_SEPARATOR
.
2019 'civicrm_drop.mysql'
2028 public static function escapeString($string) {
2029 static $_dao = NULL;
2031 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2032 // has been installed), then we fallback DB-less str_replace escaping, as
2033 // we can't use mysqli_real_escape_string, as there is no DB connection.
2034 // Note: In typical usage, escapeString() will only check one conditional
2035 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2036 if (!defined('CIVICRM_DSN')) {
2037 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2038 // list of characters mysqli_real_escape_string escapes.
2039 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2040 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2041 return str_replace($search, $replace, $string);
2043 $_dao = new CRM_Core_DAO();
2045 return $_dao->escape($string);
2049 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2051 * @param array $strings
2052 * @param string $default
2053 * the value to use if $strings has no elements.
2055 * eg "abc","def","ghi"
2057 public static function escapeStrings($strings, $default = NULL) {
2058 static $_dao = NULL;
2060 $_dao = new CRM_Core_DAO();
2063 if (empty($strings)) {
2067 $escapes = array_map([$_dao, 'escape'], $strings);
2068 return '"' . implode('","', $escapes) . '"';
2076 public static function escapeWildCardString($string) {
2078 // ensure we escape the single characters % and _ which are mysql wild
2079 // card characters and could come in via sortByCharacter
2080 // note that mysql does not escape these characters
2081 if ($string && in_array($string,
2082 ['%', '_', '%%', '_%']
2085 return '\\' . $string;
2088 return self
::escapeString($string);
2092 * Creates a test object, including any required objects it needs via recursion
2093 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2094 * ONLY USE FOR TESTING
2096 * @param string $daoName
2097 * @param array $params
2098 * @param int $numObjects
2099 * @param bool $createOnly
2101 * @return object|array|NULL
2102 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2104 public static function createTestObject(
2110 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2111 // so we re-set here in case
2112 $config = CRM_Core_Config
::singleton();
2113 $config->backtrace
= TRUE;
2115 static $counter = 0;
2116 CRM_Core_DAO
::$_testEntitiesToSkip = [
2117 'CRM_Core_DAO_Worldregion',
2118 'CRM_Core_DAO_StateProvince',
2119 'CRM_Core_DAO_Country',
2120 'CRM_Core_DAO_Domain',
2121 'CRM_Financial_DAO_FinancialType',
2122 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2125 // Prefer to instantiate BAO's instead of DAO's (when possible)
2126 // so that assignTestValue()/assignTestFK() can be overloaded.
2127 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2128 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2129 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2130 // @todo create a new class called what the BAO SHOULD be
2131 // that extends BAO-crazy-name.... migrate.
2132 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2134 if (class_exists($baoName)) {
2135 $daoName = $baoName;
2138 for ($i = 0; $i < $numObjects; ++
$i) {
2141 /** @var CRM_Core_DAO $object */
2142 $object = new $daoName();
2144 $fields = $object->fields();
2145 foreach ($fields as $fieldName => $fieldDef) {
2146 $dbName = $fieldDef['name'];
2147 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2149 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2150 $object->$dbName = $params[$dbName];
2153 elseif ($dbName != 'id') {
2154 if ($FKClassName != NULL) {
2155 $object->assignTestFK($fieldName, $fieldDef, $params);
2159 $object->assignTestValue($fieldName, $fieldDef, $counter);
2167 $objects[$i] = $object;
2177 elseif ($numObjects == 1) {
2186 * Deletes the this object plus any dependent objects that are associated with it.
2187 * ONLY USE FOR TESTING
2189 * @param string $daoName
2190 * @param array $params
2192 public static function deleteTestObjects($daoName, $params = []) {
2193 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2194 // so we re-set here in case
2195 $config = CRM_Core_Config
::singleton();
2196 $config->backtrace
= TRUE;
2198 $object = new $daoName();
2199 $object->id
= $params['id'] ??
NULL;
2201 // array(array(0 => $daoName, 1 => $daoParams))
2203 if ($object->find(TRUE)) {
2205 $fields = $object->fields();
2206 foreach ($fields as $name => $value) {
2208 $dbName = $value['name'];
2210 $FKClassName = $value['FKClassName'] ??
NULL;
2211 $required = $value['required'] ??
NULL;
2212 if ($FKClassName != NULL
2214 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2215 && ($required ||
$dbName == 'contact_id')
2216 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2217 // to make this test process pass - line below makes pass for now
2218 && $dbName != 'member_of_contact_id'
2221 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2228 foreach ($deletions as $deletion) {
2229 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2234 * Set defaults when creating new entity.
2235 * (don't call this set defaults as already in use with different signature in some places)
2237 * @param array $params
2240 public static function setCreateDefaults(&$params, $defaults) {
2241 if (!empty($params['id'])) {
2244 foreach ($defaults as $key => $value) {
2245 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2246 $params[$key] = $value;
2252 * @param string $prefix
2253 * @param bool $addRandomString
2254 * @param null $string
2258 * @see CRM_Utils_SQL_TempTable
2260 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2261 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2262 $tableName = $prefix . "_temp";
2264 if ($addRandomString) {
2266 $tableName .= "_" . $string;
2269 $tableName .= "_" . md5(uniqid('', TRUE));
2277 * @param bool $trigger
2281 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2282 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2285 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2287 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2288 CRM_Core_TemporaryErrorScope
::ignoreException();
2289 $dao = new CRM_Core_DAO();
2291 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2292 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2298 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2299 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2301 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2306 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2307 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2309 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2316 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2317 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2326 * @param null $message
2327 * @param bool $printDAO
2329 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2330 CRM_Utils_System
::xMemory("{$message}: ");
2333 global $_DB_DATAOBJECT;
2335 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2336 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2338 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2343 * Build a list of triggers via hook and add them to (err, reconcile them
2344 * with) the database.
2346 * @param string $tableName
2347 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2348 * @param bool $force
2353 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2354 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2358 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2359 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2360 * TODO: Alternative solutions might be
2361 * * Stop using functions and find another way to strip numeric characters from phones
2362 * * Give better error messages (currently a missing fn fatals with "unknown error")
2364 public static function checkSqlFunctionsExist() {
2365 if (!self
::$_checkedSqlFunctionsExist) {
2366 self
::$_checkedSqlFunctionsExist = TRUE;
2367 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2368 if (!$dao->fetch()) {
2369 self
::triggerRebuild();
2375 * Wrapper function to drop triggers.
2377 * @param string $tableName
2378 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2381 public static function dropTriggers($tableName = NULL) {
2382 Civi
::service('sql_triggers')->dropTriggers($tableName);
2386 * @param array $info
2387 * per hook_civicrm_triggerInfo.
2388 * @param string $onlyTableName
2389 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2392 public static function createTriggers(&$info, $onlyTableName = NULL) {
2393 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2397 * Given a list of fields, create a list of references.
2399 * @param string $className
2400 * BAO/DAO class name.
2401 * @return array<CRM_Core_Reference_Interface>
2403 public static function createReferenceColumns($className) {
2405 $fields = $className::fields();
2406 foreach ($fields as $field) {
2407 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2408 $result[] = new CRM_Core_Reference_OptionValue(
2409 $className::getTableName(),
2411 'civicrm_option_value',
2412 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2413 $field['pseudoconstant']['optionGroupName']
2421 * Find all records which refer to this entity.
2424 * Array of objects referencing this
2426 public function findReferences() {
2427 $links = self
::getReferencesToTable(static::getTableName());
2430 foreach ($links as $refSpec) {
2431 /** @var $refSpec CRM_Core_Reference_Interface */
2432 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2433 $result = $refSpec->findReferences($this);
2435 while ($result->fetch()) {
2436 $obj = new $daoName();
2437 $obj->id
= $result->id
;
2438 $occurrences[] = $obj;
2443 return $occurrences;
2448 * each item has keys:
2452 * - table: string|null SQL table name
2453 * - key: string|null SQL column name
2455 public function getReferenceCounts() {
2456 $links = self
::getReferencesToTable(static::getTableName());
2459 foreach ($links as $refSpec) {
2460 /** @var $refSpec CRM_Core_Reference_Interface */
2461 $count = $refSpec->getReferenceCount($this);
2462 if ($count['count'] != 0) {
2467 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2468 /** @var $component CRM_Core_Component_Info */
2469 $counts = array_merge($counts, $component->getReferenceCounts($this));
2471 CRM_Utils_Hook
::referenceCounts($this, $counts);
2477 * List all tables which have hard foreign keys to this table.
2479 * For now, this returns a description of every entity_id/entity_table
2481 * TODO: filter dynamic entity references on the $tableName, based on
2482 * schema metadata in dynamicForeignKey which enumerates a restricted
2483 * set of possible entity_table's.
2485 * @param string $tableName
2486 * Table referred to.
2489 * structure of table and column, listing every table with a
2490 * foreign key reference to $tableName, and the column where the key appears.
2492 public static function getReferencesToTable($tableName) {
2494 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2495 $links = $daoClassName::getReferenceColumns();
2497 foreach ($links as $refSpec) {
2498 /** @var $refSpec CRM_Core_Reference_Interface */
2499 if ($refSpec->matchesTargetTable($tableName)) {
2500 $refsFound[] = $refSpec;
2508 * Get all references to contact table.
2510 * This includes core tables, custom group tables, tables added by the merge
2511 * hook and the entity_tag table.
2513 * Refer to CRM-17454 for information on the danger of querying the information
2514 * schema to derive this.
2516 * @throws \CiviCRM_API3_Exception
2518 public static function getReferencesToContactTable() {
2519 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2520 return \Civi
::$statics[__CLASS__
]['contact_references'];
2522 $contactReferences = [];
2523 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2524 foreach ($coreReferences as $coreReference) {
2525 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2526 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2529 self
::appendCustomTablesExtendingContacts($contactReferences);
2530 self
::appendCustomContactReferenceFields($contactReferences);
2531 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2532 return \Civi
::$statics[__CLASS__
]['contact_references'];
2536 * Get all dynamic references to the given table.
2538 * @param string $tableName
2542 public static function getDynamicReferencesToTable($tableName) {
2543 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2544 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2545 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2546 foreach ($coreReferences as $coreReference) {
2547 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2548 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2552 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2556 * Add custom tables that extend contacts to the list of contact references.
2558 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2559 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2560 * - the down side is it is not cached.
2562 * Further changes should be include tests in the CRM_Core_MergerTest class
2563 * to ensure that disabled, subtype, multiple etc groups are still captured.
2565 * @param array $cidRefs
2567 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2568 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2569 $customValueTables->find();
2570 while ($customValueTables->fetch()) {
2571 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2576 * Add custom ContactReference fields to the list of contact references
2578 * This includes active and inactive fields/groups
2580 * @param array $cidRefs
2582 * @throws \CiviCRM_API3_Exception
2584 public static function appendCustomContactReferenceFields(&$cidRefs) {
2585 $fields = civicrm_api3('CustomField', 'get', [
2586 'return' => ['column_name', 'custom_group_id.table_name'],
2587 'data_type' => 'ContactReference',
2588 'options' => ['limit' => 0],
2590 foreach ($fields as $field) {
2591 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2596 * Lookup the value of a MySQL global configuration variable.
2598 * @param string $name
2599 * E.g. "thread_stack".
2600 * @param mixed $default
2603 public static function getGlobalSetting($name, $default = NULL) {
2604 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2605 // that has been reported to fail under MySQL 5.0 for OS X
2606 $escapedName = self
::escapeString($name);
2607 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2608 if ($dao->fetch()) {
2617 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2619 * This is relevant where we want to offer both the ID field and the label field
2620 * as an option, e.g. search builder.
2622 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2623 * change small, but is appropriate for other sorts of pseudoconstants.
2625 * @param array $fields
2627 public static function appendPseudoConstantsToFields(&$fields) {
2628 foreach ($fields as $fieldUniqueName => $field) {
2629 if (!empty($field['pseudoconstant'])) {
2630 $pseudoConstant = $field['pseudoconstant'];
2631 if (!empty($pseudoConstant['optionGroupName'])) {
2632 $fields[$pseudoConstant['optionGroupName']] = [
2633 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2634 'name' => $pseudoConstant['optionGroupName'],
2635 'data_type' => CRM_Utils_Type
::T_STRING
,
2636 'is_pseudofield_for' => $fieldUniqueName,
2639 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2641 !empty($field['FKClassName'])
2642 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2643 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2645 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2646 // This if is just an extra caution when adding change.
2647 if (!isset($fields[$pseudoFieldName])) {
2648 $daoName = $field['FKClassName'];
2649 $fkFields = $daoName::fields();
2650 foreach ($fkFields as $fkField) {
2651 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2652 $fields[$pseudoFieldName] = [
2653 'name' => $pseudoFieldName,
2654 'is_pseudofield_for' => $field['name'],
2655 'title' => $fkField['title'],
2656 'data_type' => $fkField['type'],
2657 'where' => $field['where'],
2668 * Get options for the called BAO object's field.
2670 * This function can be overridden by each BAO to add more logic related to context.
2671 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2673 * @param string $fieldName
2674 * @param string $context
2675 * @see CRM_Core_DAO::buildOptionsContext
2676 * @param array $props
2677 * Raw field values; whatever is known about this bao object.
2679 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2681 * @return array|bool
2683 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2684 // If a given bao does not override this function
2685 $baoName = get_called_class();
2686 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2690 * Populate option labels for this object's fields.
2692 * @throws exception if called directly on the base class
2694 public function getOptionLabels() {
2695 $fields = $this->fields();
2696 if ($fields === NULL) {
2697 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2699 foreach ($fields as $field) {
2700 $name = $field['name'] ??
NULL;
2701 if ($name && isset($this->$name)) {
2702 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2703 if ($label !== FALSE) {
2704 // Append 'label' onto the field name
2705 $labelName = $name . '_label';
2706 $this->$labelName = $label;
2713 * Provides documentation and validation for the buildOptions $context param
2715 * @param string $context
2717 * @throws CRM_Core_Exception
2720 public static function buildOptionsContext($context = NULL) {
2722 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2723 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2724 'search' => "search: searchable options are returned; labels are translated.",
2725 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2726 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2727 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2729 // Validation: enforce uniformity of this param
2730 if ($context !== NULL && !isset($contexts[$context])) {
2731 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2737 * @param string $fieldName
2738 * @return bool|array
2740 public function getFieldSpec($fieldName) {
2741 $fields = $this->fields();
2743 // Support "unique names" as well as sql names
2744 $fieldKey = $fieldName;
2745 if (empty($fields[$fieldKey])) {
2746 $fieldKeys = $this->fieldKeys();
2747 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2749 // If neither worked then this field doesn't exist. Return false.
2750 if (empty($fields[$fieldKey])) {
2753 return $fields[$fieldKey];
2757 * Get SQL where clause for SQL filter syntax input parameters.
2759 * SQL version of api function to assign filters to the DAO based on the syntax
2760 * $field => array('IN' => array(4,6,9))
2762 * $field => array('LIKE' => array('%me%))
2765 * @param string $fieldName
2767 * @param array $filter
2768 * filter to be applied indexed by operator.
2769 * @param string $type
2770 * type of field (not actually used - nor in api @todo ).
2771 * @param string $alias
2772 * alternative field name ('as') @todo- not actually used.
2773 * @param bool $returnSanitisedArray
2774 * Return a sanitised array instead of a clause.
2775 * this is primarily so we can add filters @ the api level to the Query object based fields
2779 * @return NULL|string|array
2780 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2781 * depending on whether it is supported as yet
2783 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2784 foreach ($filter as $operator => $criteria) {
2785 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2786 switch ($operator) {
2790 if (!$returnSanitisedArray) {
2791 return (sprintf('%s %s', $fieldName, $operator));
2794 return (sprintf('%s %s ', $fieldName, $operator));
2798 // ternary operators
2801 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2802 throw new Exception("invalid criteria for $operator");
2804 if (!$returnSanitisedArray) {
2805 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2808 // not yet implemented (tests required to implement)
2816 if (empty($criteria)) {
2817 throw new Exception("invalid criteria for $operator");
2819 $escapedCriteria = array_map([
2823 if (!$returnSanitisedArray) {
2824 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2826 return $escapedCriteria;
2831 if (!$returnSanitisedArray) {
2832 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2835 // not yet implemented (tests required to implement)
2844 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2845 * support for other syntaxes is discussed in ticket but being put off for now
2848 public static function acceptedSQLOperators() {
2869 * SQL has a limit of 64 characters on various names:
2870 * table name, trigger name, column name ...
2872 * For custom groups and fields we generated names from user entered input
2873 * which can be longer than this length, this function helps with creating
2874 * strings that meet various criteria.
2876 * @param string $string
2877 * The string to be shortened.
2878 * @param int $length
2879 * The max length of the string.
2881 * @param bool $makeRandom
2885 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2886 // early return for strings that meet the requirements
2887 if (strlen($string) <= $length) {
2891 // easy return for calls that dont need a randomized uniq string
2893 return substr($string, 0, $length);
2896 // the string is longer than the length and we need a uniq string
2897 // for the same tablename we need the same uniq string every time
2898 // hence we use md5 on the string, which is not random
2899 // we'll append 8 characters to the end of the tableName
2900 $md5string = substr(md5($string), 0, 8);
2901 return substr($string, 0, $length - 8) . "_{$md5string}";
2905 * https://issues.civicrm.org/jira/browse/CRM-17748
2906 * Sets the internal options to be used on a query
2908 * @param array $options
2911 public function setOptions($options) {
2912 if (is_array($options)) {
2913 $this->_options
= $options;
2918 * https://issues.civicrm.org/jira/browse/CRM-17748
2919 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2921 * @param array $options
2924 protected function _setDBOptions($options) {
2925 global $_DB_DATAOBJECT;
2927 if (is_array($options) && count($options)) {
2928 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2929 foreach ($options as $option_name => $option_value) {
2930 $conn->setOption($option_name, $option_value);
2937 * @param array $params
2939 public function setApiFilter(&$params) {
2943 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2945 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2948 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2952 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2956 public function addSelectWhereClause() {
2958 $fields = $this->fields();
2959 foreach ($fields as $fieldName => $field) {
2960 // Clause for contact-related entities like Email, Relationship, etc.
2961 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2962 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2964 // Clause for an entity_table/entity_id combo
2965 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2966 $relatedClauses = [];
2967 $relatedEntities = $this->buildOptions('entity_table', 'get');
2968 foreach ((array) $relatedEntities as $table => $ent) {
2970 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2971 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2973 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2976 $relatedClauses[] = "(entity_table = '$table')";
2980 if ($relatedClauses) {
2981 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2985 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2990 * This returns the final permissioned query string for this entity
2992 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2994 * @param string $tableAlias
2997 public static function getSelectWhereClause($tableAlias = NULL) {
2998 $bao = new static();
2999 if ($tableAlias === NULL) {
3000 $tableAlias = $bao->tableName();
3003 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
3004 $clauses[$field] = NULL;
3006 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
3013 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3014 * and dashes, and contains at least one [a-z] case insenstive.
3020 public static function requireSafeDBName($database) {
3023 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3027 if (empty($matches)) {
3034 * Transform an array to a serialized string for database storage.
3036 * @param array|null $value
3037 * @param int $serializationType
3038 * @return string|null
3040 * @throws \Exception
3042 public static function serializeField($value, $serializationType) {
3043 if ($value === NULL) {
3046 switch ($serializationType) {
3047 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3048 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3050 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3051 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3053 case self
::SERIALIZE_JSON
:
3054 return is_array($value) ?
json_encode($value) : $value;
3056 case self
::SERIALIZE_PHP
:
3057 return is_array($value) ?
serialize($value) : $value;
3059 case self
::SERIALIZE_COMMA
:
3060 return is_array($value) ?
implode(',', $value) : $value;
3063 throw new Exception('Unknown serialization method for field.');
3068 * Transform a serialized string from the database into an array.
3070 * @param string|null $value
3071 * @param $serializationType
3073 * @return array|null
3074 * @throws CRM_Core_Exception
3076 public static function unSerializeField($value, $serializationType) {
3077 if ($value === NULL) {
3080 if ($value === '') {
3083 switch ($serializationType) {
3084 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3085 return (array) CRM_Utils_Array
::explodePadded($value);
3087 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3088 return explode(self
::VALUE_SEPARATOR
, trim($value));
3090 case self
::SERIALIZE_JSON
:
3091 return strlen($value) ?
json_decode($value, TRUE) : [];
3093 case self
::SERIALIZE_PHP
:
3094 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3096 case self
::SERIALIZE_COMMA
:
3097 return explode(',', trim(str_replace(', ', '', $value)));
3100 throw new CRM_Core_Exception('Unknown serialization method for field.');
3107 public static function getEntityRefFilters() {
3112 * Get exportable fields with pseudoconstants rendered as an extra field.
3114 * @param string $baoClass
3118 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3119 if (method_exists($baoClass, 'exportableFields')) {
3120 $fields = $baoClass::exportableFields();
3123 $fields = $baoClass::export();
3125 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3130 * Remove item from static cache during update/delete operations
3132 private function clearDbColumnValueCache() {
3133 $daoName = get_class($this);
3134 while (strpos($daoName, '_BAO_') !== FALSE) {
3135 $daoName = get_parent_class($daoName);
3137 if (isset($this->id
)) {
3138 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3140 if (isset($this->name
)) {
3141 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);
3146 * Return a mapping from field-name to the corresponding key (as used in fields()).
3149 * Array(string $name => string $uniqueName).
3151 public static function fieldKeys() {
3152 return array_flip(CRM_Utils_Array
::collect('name', static::fields()));
3156 * Returns system paths related to this entity (as defined in the xml schema)
3160 public static function getEntityPaths() {
3161 return static::$_paths ??
[];