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 * Primary key field(s).
40 public static $_primaryKey = ['id'];
43 * How many times has this instance been cloned.
47 protected $resultCopies = 0;
53 public static $_nullObject = NULL;
56 * Icon associated with this entity.
60 public static $_icon = NULL;
63 * Field to show when displaying a record.
67 public static $_labelField = NULL;
73 public static $_nullArray = [];
75 public static $_dbColumnValueCache = NULL;
76 const NOT_NULL
= 1, IS_NULL
= 2,
78 VALUE_SEPARATOR
= "\ 1",
79 BULK_INSERT_COUNT
= 200,
80 BULK_INSERT_HIGH_COUNT
= 200,
81 QUERY_FORMAT_WILDCARD
= 1,
82 QUERY_FORMAT_NO_QUOTES
= 2,
85 * Serialized string separated by and bookended with VALUE_SEPARATOR
87 SERIALIZE_SEPARATOR_BOOKEND
= 1,
89 * @deprecated format separated by VALUE_SEPARATOR
91 SERIALIZE_SEPARATOR_TRIMMED
= 2,
93 * Recommended serialization format
97 * @deprecated format using php serialize()
101 * Comma separated string, no quotes, no spaces
106 * Define entities that shouldn't be created or deleted when creating/ deleting
107 * test objects - this prevents world regions, countries etc from being added / deleted
110 public static $_testEntitiesToSkip = [];
112 * The factory class for this application.
115 public static $_factory = NULL;
118 * https://issues.civicrm.org/jira/browse/CRM-17748
119 * internal variable for DAO to hold per-query settings
122 protected $_options = [];
129 public function __construct() {
131 $this->__table
= $this->getTableName();
135 * Returns localized title of this entity.
139 public static function getEntityTitle() {
140 $className = static::class;
141 CRM_Core_Error
::deprecatedWarning("$className needs to be regenerated. Missing getEntityTitle method.");
142 return CRM_Core_DAO_AllCoreTables
::getBriefName($className);
146 * Returns user-friendly description of this entity.
148 * @return string|null
150 public static function getEntityDescription() {
154 public function __clone() {
155 if (!empty($this->_DB_resultid
)) {
156 $this->resultCopies++
;
163 public function __destruct() {
164 if ($this->resultCopies
=== 0) {
167 $this->resultCopies
--;
171 * Returns the name of this table
175 public static function getTableName() {
176 return self
::getLocaleTableName(static::$_tableName ??
NULL);
180 * Returns if this table needs to be logged
184 public function getLog() {
185 return static::$_log ??
FALSE;
189 * Initialize the DAO object.
192 * The database connection string.
194 public static function init($dsn) {
195 Civi
::$statics[__CLASS__
]['init'] = 1;
196 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
197 $dsn = CRM_Utils_SQL
::autoSwitchDSN($dsn);
198 $options['database'] = $dsn;
199 $options['quote_identifiers'] = TRUE;
200 if (CRM_Utils_SQL
::isSSLDSN($dsn)) {
201 // There are two different options arrays.
202 $other_options = &PEAR
::getStaticProperty('DB', 'options');
203 $other_options['ssl'] = TRUE;
205 if (defined('CIVICRM_DAO_DEBUG')) {
206 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
208 $factory = new CRM_Contact_DAO_Factory();
209 CRM_Core_DAO
::setFactory($factory);
210 CRM_Core_DAO
::executeQuery('SET NAMES utf8mb4');
211 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
217 public static function getConnection() {
218 global $_DB_DATAOBJECT;
219 $dao = new CRM_Core_DAO();
220 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
224 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
226 public static function disableFullGroupByMode() {
227 $currentModes = CRM_Utils_SQL
::getSqlModes();
228 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
229 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
230 unset($currentModes[$key]);
231 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
236 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
238 public static function reenableFullGroupByMode() {
239 $currentModes = CRM_Utils_SQL
::getSqlModes();
240 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
241 $currentModes[] = 'ONLY_FULL_GROUP_BY';
242 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
247 * @param string $fieldName
249 * @param array $params
251 protected function assignTestFK($fieldName, $fieldDef, $params) {
252 $required = $fieldDef['required'] ??
NULL;
253 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
254 $dbName = $fieldDef['name'];
255 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
257 // skip the FK if it is not required
258 // if it's contact id we should create even if not required
259 // we'll have a go @ fetching first though
260 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
261 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
264 if (!$required && $dbName != 'contact_id') {
265 $fkDAO = new $FKClassName();
266 if ($fkDAO->find(TRUE)) {
267 $this->$dbName = $fkDAO->id
;
271 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
272 $depObject = new $FKClassName();
273 $depObject->find(TRUE);
274 $this->$dbName = $depObject->id
;
276 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
277 // FIXME: the fields() metadata is not specific enough
278 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
279 $this->$dbName = $depObject->id
;
282 //if it is required we need to generate the dependency object first
283 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
284 $this->$dbName = $depObject->id
;
289 * Generate and assign an arbitrary value to a field of a test object.
291 * @param string $fieldName
292 * @param array $fieldDef
293 * @param int $counter
294 * The globally-unique ID of the test object.
296 * @throws \CRM_Core_Exception
298 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
299 $dbName = $fieldDef['name'];
300 $daoName = get_class($this);
303 if (in_array($dbName, ['contact_sub_type', 'email_greeting_id', 'postal_greeting_id', 'addressee_id'], TRUE)) {
304 //coming up with a rule to set these is too complex - skip
308 // Pick an option value if needed
309 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
310 $options = $daoName::buildOptions($dbName, 'create');
312 $this->$dbName = key($options);
318 switch ($fieldDef['type']) {
319 case CRM_Utils_Type
::T_INT
:
320 case CRM_Utils_Type
::T_FLOAT
:
321 case CRM_Utils_Type
::T_MONEY
:
322 if (isset($fieldDef['precision'])) {
323 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
324 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
327 $this->$dbName = $counter;
331 case CRM_Utils_Type
::T_BOOLEAN
:
332 if (isset($fieldDef['default'])) {
333 $this->$dbName = $fieldDef['default'];
335 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
343 case CRM_Utils_Type
::T_DATE
:
344 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
345 $this->$dbName = '19700101';
346 if ($dbName == 'end_date') {
347 // put this in the future
348 $this->$dbName = '20200101';
352 case CRM_Utils_Type
::T_TIMESTAMP
:
353 $this->$dbName = '19700201000000';
356 case CRM_Utils_Type
::T_TIME
:
357 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
359 case CRM_Utils_Type
::T_CCNUM
:
360 $this->$dbName = '4111 1111 1111 1111';
363 case CRM_Utils_Type
::T_URL
:
364 $this->$dbName = 'http://www.civicrm.org';
367 case CRM_Utils_Type
::T_STRING
:
368 case CRM_Utils_Type
::T_BLOB
:
369 case CRM_Utils_Type
::T_MEDIUMBLOB
:
370 case CRM_Utils_Type
::T_TEXT
:
371 case CRM_Utils_Type
::T_LONGTEXT
:
372 case CRM_Utils_Type
::T_EMAIL
:
374 // WAS: if (isset($value['enumValues'])) {
375 // TODO: see if this works with all pseudoconstants
376 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
377 if (isset($fieldDef['default'])) {
378 $this->$dbName = $fieldDef['default'];
381 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
382 if (is_array($options)) {
383 $this->$dbName = $options[0];
386 $defaultValues = explode(',', $options);
387 $this->$dbName = $defaultValues[0];
392 $this->$dbName = $dbName . '_' . $counter;
393 $maxlength = $fieldDef['maxlength'] ??
NULL;
394 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
395 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
403 * Reset the DAO object.
405 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
407 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
409 public function reset() {
411 foreach (array_keys($this->table()) as $field) {
412 unset($this->$field);
416 * reset the various DB_DAO structures manually
425 * @param string $tableName
429 public static function getLocaleTableName($tableName) {
432 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
433 if (in_array($tableName, $tables)) {
434 return $tableName . $dbLocale;
441 * Execute a query by the current DAO, localizing it along the way (if needed).
443 * @param string $query
444 * The SQL query for execution.
445 * @param bool $i18nRewrite
446 * Whether to rewrite the query.
449 * the current DAO object after the query execution
451 public function query($query, $i18nRewrite = TRUE) {
452 // rewrite queries that should use $dbLocale-based views for multi-language installs
453 global $dbLocale, $_DB_DATAOBJECT;
455 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
456 // Will force connection to be populated per CRM-20541.
460 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
461 $orig_options = $conn->options
;
462 $this->_setDBOptions($this->_options
);
464 if ($i18nRewrite and $dbLocale) {
465 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
468 $ret = parent
::query($query);
470 $this->_setDBOptions($orig_options);
475 * Static function to set the factory instance for this class.
477 * @param object $factory
478 * The factory application object.
480 public static function setFactory(&$factory) {
481 self
::$_factory = &$factory;
485 * Factory method to instantiate a new object from a table name.
487 * @param string $table
488 * @return \DataObject|\PEAR_Error
490 public function factory($table = '') {
491 if (!isset(self
::$_factory)) {
492 return parent
::factory($table);
495 return self
::$_factory->create($table);
499 * Initialization for all DAO objects. Since we access DB_DO programatically
500 * we need to set the links manually.
502 public function initialize() {
504 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
505 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
506 // This occurs very early in bootstrap - error handlers may not be wired up.
507 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
508 CRM_Utils_System
::civiExit();
513 * Defines the default key as 'id'.
517 public function keys() {
526 * Tells DB_DataObject which keys use autoincrement.
527 * 'id' is autoincrementing by default.
532 public function sequenceKey() {
533 static $sequenceKeys;
534 if (!isset($sequenceKeys)) {
535 $sequenceKeys = ['id', TRUE];
537 return $sequenceKeys;
541 * Returns list of FK relationships.
543 * @return CRM_Core_Reference_Basic[]
545 public static function getReferenceColumns() {
546 if (!isset(Civi
::$statics[static::class]['links'])) {
547 Civi
::$statics[static::class]['links'] = static::createReferenceColumns(static::class);
548 CRM_Core_DAO_AllCoreTables
::invoke(static::class, 'links_callback', Civi
::$statics[static::class]['links']);
550 return Civi
::$statics[static::class]['links'];
554 * Returns all the column names of this table.
559 public static function &fields() {
565 * Returns all usable fields, indexed by name.
567 * This function differs from fields() in that it indexes by name rather than unique_name.
569 * It excludes fields not added yet by pending upgrades.
570 * This avoids problems with trying to SELECT a field that exists in code but has not yet been added to the db.
572 * @param bool $checkPermissions
573 * Filter by field permissions.
576 public static function getSupportedFields($checkPermissions = FALSE) {
577 $fields = array_column((array) static::fields(), NULL, 'name');
579 // Exclude fields yet not added by pending upgrades
580 $dbVer = \CRM_Core_BAO_Domain
::version();
581 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
582 if ($fields && $daoExt === 'civicrm' && version_compare($dbVer, \CRM_Utils_System
::version()) < 0) {
583 $fields = array_filter($fields, function($field) use ($dbVer) {
584 $add = $field['add'] ??
'1.0.0';
585 if (substr_count($add, '.') < 2) {
588 return version_compare($dbVer, $add, '>=');
592 // Exclude fields the user does not have permission for
593 if ($checkPermissions) {
594 $fields = array_filter($fields, function($field) {
595 return empty($field['permission']) || CRM_Core_Permission
::check($field['permission']);
603 * Get/set an associative array of table columns
608 public function table() {
609 $fields = $this->fields();
613 foreach ($fields as $name => $value) {
614 $table[$value['name']] = $value['type'];
615 if (!empty($value['required'])) {
616 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
629 * @return CRM_Core_DAO
631 public function save($hook = TRUE) {
633 if (!empty($this->id
)) {
635 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
636 $preEvent->eventID
= $eventID;
637 \Civi
::dispatcher()->dispatch("civi.dao.preUpdate", $preEvent);
640 $result = $this->update();
643 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
644 $event->eventID
= $eventID;
645 \Civi
::dispatcher()->dispatch("civi.dao.postUpdate", $event);
647 $this->clearDbColumnValueCache();
651 $preEvent = new \Civi\Core\DAO\Event\
PreUpdate($this);
652 $preEvent->eventID
= $eventID;
653 \Civi
::dispatcher()->dispatch("civi.dao.preInsert", $preEvent);
656 $result = $this->insert();
659 $event = new \Civi\Core\DAO\Event\
PostUpdate($this, $result);
660 $event->eventID
= $eventID;
661 \Civi
::dispatcher()->dispatch("civi.dao.postInsert", $event);
667 CRM_Utils_Hook
::postSave($this);
674 * Deletes items from table which match current objects variables.
676 * Returns the true on success
680 * Designed to be extended
682 * $object = new mytable();
684 * echo $object->delete(); // builds a conditon
686 * $object = new mytable();
687 * $object->whereAdd('age > 12');
689 * $object->orderBy('age DESC');
690 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
692 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
693 * we will build the condition only using the whereAdd's. Default is to
694 * build the condition only using the object parameters.
697 * Int (No. of rows affected) on success, false on failure, 0 on no data affected
699 public function delete($useWhere = FALSE) {
700 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
701 \Civi
::dispatcher()->dispatch("civi.dao.preDelete", $preEvent);
703 $result = parent
::delete($useWhere);
705 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
706 \Civi
::dispatcher()->dispatch("civi.dao.postDelete", $event);
709 $this->clearDbColumnValueCache();
715 * @param bool $created
717 public function log($created = FALSE) {
720 if (!$this->getLog()) {
725 $session = CRM_Core_Session
::singleton();
726 $cid = $session->get('userID');
729 // return is we dont have handle to FK
734 $dao = new CRM_Core_DAO_Log();
735 $dao->entity_table
= $this->getTableName();
736 $dao->entity_id
= $this->id
;
737 $dao->modified_id
= $cid;
738 $dao->modified_date
= date("YmdHis");
743 * Given an associative array of name/value pairs, extract all the values
744 * that belong to this object and initialize the object with said values
746 * @param array $params
747 * Array of name/value pairs to save.
750 * Did we copy all null values into the object
752 public function copyValues($params) {
754 foreach ($this->fields() as $uniqueName => $field) {
755 $dbName = $field['name'];
756 if (array_key_exists($dbName, $params)) {
757 $value = $params[$dbName];
760 elseif (array_key_exists($uniqueName, $params)) {
761 $value = $params[$uniqueName];
768 // if there is no value then make the variable NULL
771 $this->$dbName = 'null';
773 elseif (is_array($value) && !empty($field['serialize'])) {
774 $this->$dbName = CRM_Core_DAO
::serializeField($value, $field['serialize']);
778 $maxLength = $field['maxlength'] ??
NULL;
779 if (!is_array($value) && $maxLength && mb_strlen($value) > $maxLength && empty($field['pseudoconstant'])) {
780 // No ts() since this is a sysadmin-y string not seen by general users.
781 Civi
::log()->warning('A string for field {dbName} has been truncated. The original string was {value}.', ['dbName' => $dbName, 'value' => $value]);
782 // The string is too long - what to do what to do? Well losing data is generally bad so let's truncate
783 $value = CRM_Utils_String
::ellipsify($value, $maxLength);
785 $this->$dbName = $value;
794 * Store all the values from this object in an associative array
795 * this is a destructive store, calling function is responsible
796 * for keeping sanity of id's.
798 * @param object $object
799 * The object that we are extracting data from.
800 * @param array $values
801 * (reference ) associative array of name/value pairs.
803 public static function storeValues(&$object, &$values) {
804 $fields = $object->fields();
805 foreach ($fields as $name => $value) {
806 $dbName = $value['name'];
807 if (isset($object->$dbName) && $object->$dbName !== 'null') {
808 $values[$dbName] = $object->$dbName;
809 if ($name != $dbName) {
810 $values[$name] = $object->$dbName;
817 * Create an attribute for this specific field. We only do this for strings and text
819 * @param array $field
820 * The field under task.
823 * the attributes for the object
825 public static function makeAttribute($field) {
827 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
828 $maxLength = $field['maxlength'] ??
NULL;
829 $size = $field['size'] ??
NULL;
830 if ($maxLength ||
$size) {
833 $attributes['maxlength'] = $maxLength;
836 $attributes['size'] = $size;
841 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
842 $rows = $field['rows'] ??
NULL;
846 $cols = $field['cols'] ??
NULL;
852 $attributes['rows'] = $rows;
853 $attributes['cols'] = $cols;
856 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
) {
857 $attributes['size'] = 6;
858 $attributes['maxlength'] = 14;
866 * Get the size and maxLength attributes for this text field.
867 * (or for all text fields) in the DAO object.
869 * @param string $class
871 * @param string $fieldName
872 * Field that i'm interested in or null if.
873 * you want the attributes for all DAO text fields
876 * assoc array of name => attribute pairs
878 public static function getAttribute($class, $fieldName = NULL) {
879 $object = new $class();
880 $fields = $object->fields();
881 if ($fieldName != NULL) {
882 $field = $fields[$fieldName] ??
NULL;
883 return self
::makeAttribute($field);
887 foreach ($fields as $name => $field) {
888 $attribute = self
::makeAttribute($field);
890 $attributes[$name] = $attribute;
894 if (!empty($attributes)) {
902 * Create or update a record from supplied params.
904 * If 'id' is supplied, an existing record will be updated
905 * Otherwise a new record will be created.
907 * @param array $record
910 * @throws \CRM_Core_Exception
912 public static function writeRecord(array $record): CRM_Core_DAO
{
913 $op = empty($record['id']) ?
'create' : 'edit';
914 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
915 if ($className === 'CRM_Core_DAO') {
916 throw new CRM_Core_Exception('Function writeRecord must be called on a subclass of CRM_Core_DAO');
918 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
920 \CRM_Utils_Hook
::pre($op, $entityName, $record['id'] ??
NULL, $record);
921 $instance = new $className();
922 // Ensure fields exist before attempting to write to them
923 $values = array_intersect_key($record, self
::getSupportedFields());
924 $instance->copyValues($values);
927 if (!empty($record['custom']) && is_array($record['custom'])) {
928 CRM_Core_BAO_CustomValueTable
::store($record['custom'], static::$_tableName, $instance->id
, $op);
931 \CRM_Utils_Hook
::post($op, $entityName, $instance->id
, $instance);
937 * Bulk save multiple records
939 * @param array[] $records
941 * @throws CRM_Core_Exception
943 public static function writeRecords(array $records): array {
945 foreach ($records as $record) {
946 $results[] = static::writeRecord($record);
952 * Delete a record from supplied params.
954 * @param array $record
957 * @throws CRM_Core_Exception
959 public static function deleteRecord(array $record) {
960 $className = CRM_Core_DAO_AllCoreTables
::getCanonicalClassName(static::class);
961 if ($className === 'CRM_Core_DAO') {
962 throw new CRM_Core_Exception('Function deleteRecord must be called on a subclass of CRM_Core_DAO');
964 $entityName = CRM_Core_DAO_AllCoreTables
::getBriefName($className);
965 if (empty($record['id'])) {
966 throw new CRM_Core_Exception("Cannot delete {$entityName} with no id.");
968 CRM_Utils_Type
::validate($record['id'], 'Positive');
970 CRM_Utils_Hook
::pre('delete', $entityName, $record['id'], $record);
971 $instance = new $className();
972 $instance->id
= $record['id'];
973 // Load complete object for the sake of hook_civicrm_post, below
974 $instance->find(TRUE);
975 if (!$instance ||
!$instance->delete()) {
976 throw new CRM_Core_Exception("Could not delete {$entityName} id {$record['id']}");
978 // For other operations this hook is passed an incomplete object and hook listeners can load if needed.
979 // But that's not possible with delete because it's gone from the database by the time this hook is called.
980 // So in this case the object has been pre-loaded so hook listeners have access to the complete record.
981 CRM_Utils_Hook
::post('delete', $entityName, $record['id'], $instance);
987 * Bulk delete multiple records.
989 * @param array[] $records
991 * @throws CRM_Core_Exception
993 public static function deleteRecords(array $records) {
995 foreach ($records as $record) {
996 $results[] = static::deleteRecord($record);
1002 * Check if there is a record with the same name in the db.
1004 * @param string $value
1005 * The value of the field we are checking.
1006 * @param string $daoName
1007 * The dao object name.
1008 * @param string $daoID
1009 * The id of the object being updated. u can change your name.
1010 * as long as there is no conflict
1011 * @param string $fieldName
1012 * The name of the field in the DAO.
1014 * @param string $domainID
1015 * The id of the domain. Object exists only for the given domain.
1018 * true if object exists
1020 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
1021 $object = new $daoName();
1022 $object->$fieldName = $value;
1024 $object->domain_id
= $domainID;
1027 if ($object->find(TRUE)) {
1028 return $daoID && $object->id
== $daoID;
1036 * Check if there is a given column in a specific table.
1039 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
1041 * @param string $tableName
1042 * @param string $columnName
1043 * @param bool $i18nRewrite
1044 * Whether to rewrite the query on multilingual setups.
1047 * true if exists, else false
1049 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
1050 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_SchemaHandler::checkIfFieldExists');
1051 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
1055 * Scans all the tables using a slow query and table name.
1059 public static function getTableNames() {
1060 $dao = CRM_Core_DAO
::executeQuery(
1062 FROM information_schema.TABLES
1063 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1064 AND TABLE_NAME LIKE 'civicrm_%'
1065 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1066 AND TABLE_NAME NOT LIKE '%_temp%'
1069 while ($dao->fetch()) {
1070 $values[] = $dao->TABLE_NAME
;
1076 * @param int $maxTablesToCheck
1080 public static function isDBMyISAM($maxTablesToCheck = 10) {
1081 return CRM_Core_DAO
::singleValueQuery(
1083 FROM information_schema.TABLES
1084 WHERE ENGINE = 'MyISAM'
1085 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
1086 AND TABLE_NAME LIKE 'civicrm_%'
1087 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
1088 AND TABLE_NAME NOT LIKE '%_temp%'
1089 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
1094 * Get the name of the CiviCRM database.
1098 public static function getDatabaseName() {
1099 $daoObj = new CRM_Core_DAO();
1100 return $daoObj->database();
1104 * Checks if a constraint exists for a specified table.
1106 * @param string $tableName
1107 * @param string $constraint
1110 * true if constraint exists, false otherwise
1112 * @throws \CRM_Core_Exception
1114 public static function checkConstraintExists($tableName, $constraint) {
1117 if (!array_key_exists($tableName, $show)) {
1118 $query = "SHOW CREATE TABLE $tableName";
1119 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1121 if (!$dao->fetch()) {
1122 throw new CRM_Core_Exception('query failed');
1125 $show[$tableName] = $dao->Create_Table
;
1128 return (bool) preg_match("/\b$constraint\b/i", $show[$tableName]);
1132 * Checks if CONSTRAINT keyword exists for a specified table.
1134 * @param array $tables
1136 * @throws CRM_Core_Exception
1139 * true if CONSTRAINT keyword exists, false otherwise
1141 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
1143 foreach ($tables as $tableName) {
1144 if (!array_key_exists($tableName, $show)) {
1145 $query = "SHOW CREATE TABLE $tableName";
1146 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
1148 if (!$dao->fetch()) {
1149 throw new CRM_Core_Exception('Show create table failed.');
1152 $show[$tableName] = $dao->Create_Table
;
1155 $result = (bool) preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]);
1156 if ($result == TRUE) {
1167 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
1168 * for a specified column of a table.
1170 * @param string $tableName
1171 * @param string $columnName
1174 * true if in format, false otherwise
1176 * @throws \CRM_Core_Exception
1178 public static function checkFKConstraintInFormat($tableName, $columnName) {
1181 if (!array_key_exists($tableName, $show)) {
1182 $query = "SHOW CREATE TABLE $tableName";
1183 $dao = CRM_Core_DAO
::executeQuery($query);
1185 if (!$dao->fetch()) {
1186 throw new CRM_Core_Exception('query failed');
1189 $show[$tableName] = $dao->Create_Table
;
1191 $constraint = "`FK_{$tableName}_{$columnName}`";
1192 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1193 return (bool) preg_match(sprintf($pattern, $constraint), $show[$tableName]);
1197 * Check whether a specific column in a specific table has always the same value.
1199 * @param string $tableName
1200 * @param string $columnName
1201 * @param string $columnValue
1204 * true if the value is always $columnValue, false otherwise
1206 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1207 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1208 $dao = CRM_Core_DAO
::executeQuery($query);
1209 $result = $dao->fetch() ?
FALSE : TRUE;
1214 * Check whether a specific column in a specific table is always NULL.
1216 * @param string $tableName
1217 * @param string $columnName
1220 * true if if the value is always NULL, false otherwise
1222 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1223 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1224 $dao = CRM_Core_DAO
::executeQuery($query);
1225 $result = $dao->fetch() ?
FALSE : TRUE;
1230 * Checks if this DAO's table ought to exist.
1232 * If there are pending DB updates, this function compares the CiviCRM version of the table to the current schema version.
1235 * @throws CRM_Core_Exception
1237 public static function tableHasBeenAdded() {
1238 if (CRM_Utils_System
::version() === CRM_Core_BAO_Domain
::version()) {
1241 $daoExt = defined(static::class . '::EXT') ?
constant(static::class . '::EXT') : NULL;
1242 $daoVersion = defined(static::class . '::TABLE_ADDED') ?
constant(static::class . '::TABLE_ADDED') : '1.0';
1243 return !($daoExt === 'civicrm' && version_compare(CRM_Core_BAO_Domain
::version(), $daoVersion, '<'));
1247 * Check if there is a given table in the database.
1249 * @param string $tableName
1252 * true if exists, else false
1254 public static function checkTableExists($tableName) {
1259 $params = [1 => [$tableName, 'String']];
1261 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1262 return (bool) $dao->fetch();
1266 * Check if a given table has data.
1268 * @param string $tableName
1270 * TRUE if $tableName has at least one record.
1272 public static function checkTableHasData($tableName) {
1273 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1282 public function checkVersion($version) {
1283 CRM_Core_Error
::deprecatedFunctionWarning('CRM_Core_BAO_Domain::version');
1284 $dbVersion = CRM_Core_BAO_Domain
::version();
1285 return trim($version) == trim($dbVersion);
1289 * Find a DAO object for the given ID and return it.
1292 * Id of the DAO object being searched for.
1294 * @return CRM_Core_DAO
1295 * Object of the type of the class that called this function.
1299 public static function findById($id) {
1300 $object = new static();
1302 if (!$object->find(TRUE)) {
1303 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1309 * Returns all results as array-encoded records.
1313 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1315 while ($this->fetch()) {
1316 $result[] = $this->toArray();
1322 * Return the results as PHP generator.
1324 * @param string $type
1325 * Whether the generator yields 'dao' objects or 'array's.
1327 public function fetchGenerator($type = 'dao') {
1328 while ($this->fetch()) {
1335 yield
$this->toArray();
1339 throw new \
RuntimeException("Invalid record type ($type)");
1345 * Returns a singular value.
1347 * @return mixed|NULL
1349 public function fetchValue() {
1350 $result = $this->getDatabaseResult();
1351 $row = $result->fetchRow();
1361 * Get all the result records as mapping between columns.
1363 * @param string $keyColumn
1365 * @param string $valueColumn
1368 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1370 public function fetchMap($keyColumn, $valueColumn) {
1372 while ($this->fetch()) {
1373 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1379 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1381 * @param string $daoName
1382 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1383 * @param int $searchValue
1384 * Value of the column you want to search by.
1385 * @param string $returnColumn
1386 * Name of the column you want to GET the value of.
1387 * @param string $searchColumn
1388 * Name of the column you want to search by.
1389 * @param bool $force
1390 * Skip use of the cache.
1392 * @return string|int|null
1393 * Value of $returnColumn in the retrieved record
1395 * @throws \CRM_Core_Exception
1397 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1399 empty($searchValue) ||
1400 trim(strtolower($searchValue)) == 'null'
1402 // adding this here since developers forget to check for an id
1403 // or for the 'null' (which is a bad DAO kludge)
1404 // and hence we get the first value in the db
1405 throw new CRM_Core_Exception('getFieldValue failed');
1408 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1410 while (strpos($daoName, '_BAO_') !== FALSE) {
1411 $daoName = get_parent_class($daoName);
1415 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1416 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1418 $object = new $daoName();
1419 $object->$searchColumn = $searchValue;
1420 $object->selectAdd();
1421 $object->selectAdd($returnColumn);
1424 if ($object->find(TRUE)) {
1425 $result = $object->$returnColumn;
1428 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1430 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1434 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1436 * @param string $daoName
1437 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1438 * @param int $searchValue
1439 * Value of the column you want to search by.
1440 * @param string $setColumn
1441 * Name of the column you want to SET the value of.
1442 * @param string $setValue
1443 * SET the setColumn to this value.
1444 * @param string $searchColumn
1445 * Name of the column you want to search by.
1448 * true if we found and updated the object, else false
1450 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1451 $object = new $daoName();
1452 $object->selectAdd();
1453 $object->selectAdd("$searchColumn, $setColumn");
1454 $object->$searchColumn = $searchValue;
1456 if ($object->find(TRUE)) {
1457 $object->$setColumn = $setValue;
1458 if ($object->save()) {
1469 * @param array|object $sort either array or CRM_Utils_Sort
1470 * @param string $default
1471 * Default sort value.
1475 public static function getSortString($sort, $default = NULL) {
1476 // check if sort is of type CRM_Utils_Sort
1477 if (is_a($sort, 'CRM_Utils_Sort')) {
1478 return $sort->orderBy();
1483 // is it an array specified as $field => $sortDirection ?
1485 foreach ($sort as $k => $v) {
1486 $sortString .= "$k $v,";
1488 return rtrim($sortString, ',');
1494 * Fetch object based on array of properties.
1496 * @param string $daoName
1497 * Name of the dao object.
1498 * @param array $params
1499 * (reference ) an assoc array of name/value pairs.
1500 * @param array $defaults
1501 * (reference ) an assoc array to hold the flattened values.
1502 * @param array $returnProperities
1503 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1506 * an object of type referenced by daoName
1508 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1509 $object = new $daoName();
1510 $object->copyValues($params);
1512 // return only specific fields if returnproperties are sent
1513 if (!empty($returnProperities)) {
1514 $object->selectAdd();
1515 $object->selectAdd(implode(',', $returnProperities));
1518 if ($object->find(TRUE)) {
1519 self
::storeValues($object, $defaults);
1526 * Delete the object records that are associated with this contact.
1528 * @param string $daoName
1529 * Name of the dao object.
1530 * @param int $contactId
1531 * Id of the contact to delete.
1533 public static function deleteEntityContact($daoName, $contactId) {
1534 $object = new $daoName();
1536 $object->entity_table
= 'civicrm_contact';
1537 $object->entity_id
= $contactId;
1542 * Execute an unbuffered query.
1544 * This is a wrapper around new functionality exposed with CRM-17748.
1546 * @param string $query query to be executed
1548 * @param array $params
1549 * @param bool $abort
1550 * @param null $daoName
1551 * @param bool $freeDAO
1552 * @param bool $i18nRewrite
1553 * @param bool $trapException
1555 * @return CRM_Core_DAO
1556 * Object that points to an unbuffered result set
1558 public static function executeUnbufferedQuery(
1564 $i18nRewrite = TRUE,
1565 $trapException = FALSE
1568 return self
::executeQuery(
1576 ['result_buffering' => 0]
1583 * @param string $query
1584 * Query to be executed.
1586 * @param array $params
1587 * @param bool $abort
1588 * @param null $daoName
1589 * @param bool $freeDAO
1590 * @param bool $i18nRewrite
1591 * @param bool $trapException
1592 * @param array $options
1594 * @return CRM_Core_DAO|object
1595 * object that holds the results of the query
1596 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1597 * out all the properties that are not part of the DAO
1599 public static function &executeQuery(
1605 $i18nRewrite = TRUE,
1606 $trapException = FALSE,
1609 $queryStr = self
::composeQuery($query, $params, $abort);
1612 $dao = new CRM_Core_DAO();
1615 $dao = new $daoName();
1618 if ($trapException) {
1619 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1620 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1623 if ($dao->isValidOption($options)) {
1624 $dao->setOptions($options);
1627 $result = $dao->query($queryStr, $i18nRewrite);
1629 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1630 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1634 if (is_a($result, 'DB_Error')) {
1635 CRM_Core_Error
::deprecatedFunctionWarning('calling functions should handle exceptions');
1643 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1645 * @param array $options
1648 * Provided options are valid
1650 public function isValidOption($options) {
1659 if (empty($options)) {
1663 foreach (array_keys($options) as $option) {
1664 if (!in_array($option, $validOptions)) {
1674 * Execute a query and get the single result.
1676 * @param string $query
1677 * Query to be executed.
1678 * @param array $params
1679 * @param bool $abort
1680 * @param bool $i18nRewrite
1681 * @return string|null
1682 * the result of the query if any
1685 public static function &singleValueQuery(
1691 $queryStr = self
::composeQuery($query, $params, $abort);
1693 static $_dao = NULL;
1696 $_dao = new CRM_Core_DAO();
1699 $_dao->query($queryStr, $i18nRewrite);
1701 $result = $_dao->getDatabaseResult();
1704 $row = $result->fetchRow();
1714 * Compose the query by merging the parameters into it.
1716 * @param string $query
1717 * @param array $params
1718 * @param bool $abort
1721 * @throws CRM_Core_Exception
1723 public static function composeQuery($query, $params = [], $abort = TRUE) {
1725 foreach ($params as $key => $item) {
1726 if (is_numeric($key)) {
1727 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1728 $item[0] = self
::escapeString($item[0]);
1729 if ($item[1] == 'String' ||
1730 $item[1] == 'Memo' ||
1733 // Support class constants stipulating wildcard characters and/or
1734 // non-quoting of strings. Also support legacy code which may be
1735 // passing in TRUE or 1 for $item[2], which used to indicate the
1736 // use of wildcard characters.
1737 if (!empty($item[2])) {
1738 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1739 $item[0] = "'%{$item[0]}%'";
1741 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1742 $item[0] = "'{$item[0]}'";
1746 $item[0] = "'{$item[0]}'";
1750 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1751 strlen($item[0]) == 0
1756 $tr['%' . $key] = $item[0];
1759 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1764 return strtr($query, $tr);
1770 public static function freeResult($ids = NULL) {
1771 global $_DB_DATAOBJECT;
1774 if (!$_DB_DATAOBJECT ||
1775 !isset($_DB_DATAOBJECT['RESULTS'])
1779 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1782 foreach ($ids as $id) {
1783 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1784 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1785 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1788 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1789 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1795 * Make a shallow copy of an object and all the fields in the object.
1797 * @param string $daoName
1799 * @param array $criteria
1800 * Array of all the fields & values.
1801 * on which basis to copy
1802 * @param array $newData
1803 * Array of all the fields & values.
1804 * to be copied besides the other fields
1805 * @param string $fieldsFix
1806 * Array of fields that you want to prefix/suffix/replace.
1807 * @param string $blockCopyOfDependencies
1808 * Fields that you want to block from.
1810 * @param bool $blockCopyofCustomValues
1811 * Case when you don't want to copy the custom values set in a
1812 * template as it will override/ignore the submitted custom values
1814 * @return CRM_Core_DAO|bool
1815 * the newly created copy of the object. False if none created.
1817 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1818 $object = new $daoName();
1821 $object->id
= $criteria['id'];
1824 foreach ($criteria as $key => $value) {
1825 $object->$key = $value;
1830 while ($object->fetch()) {
1832 // all the objects except with $blockCopyOfDependencies set
1833 // be copied - addresses #CRM-1962
1835 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1839 $newObject = new $daoName();
1841 $fields = $object->fields();
1842 $fieldsToPrefix = [];
1843 $fieldsToSuffix = [];
1844 $fieldsToReplace = [];
1845 if (!empty($fieldsFix['prefix'])) {
1846 $fieldsToPrefix = $fieldsFix['prefix'];
1848 if (!empty($fieldsFix['suffix'])) {
1849 $fieldsToSuffix = $fieldsFix['suffix'];
1851 if (!empty($fieldsFix['replace'])) {
1852 $fieldsToReplace = $fieldsFix['replace'];
1855 $localizableFields = FALSE;
1856 foreach ($fields as $name => $value) {
1857 if ($name == 'id' ||
$value['name'] == 'id') {
1858 // copy everything but the id!
1862 $dbName = $value['name'];
1863 $type = CRM_Utils_Type
::typeToString($value['type']);
1864 $newObject->$dbName = $object->$dbName;
1865 if (isset($fieldsToPrefix[$dbName])) {
1866 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1868 if (isset($fieldsToSuffix[$dbName])) {
1869 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1871 if (isset($fieldsToReplace[$dbName])) {
1872 $newObject->$dbName = $fieldsToReplace[$dbName];
1875 if ($type == 'Timestamp' ||
$type == 'Date') {
1876 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1879 if (!empty($value['localizable'])) {
1880 $localizableFields = TRUE;
1884 $newObject->copyValues($newData);
1889 // ensure we copy all localized fields as well
1890 if (CRM_Core_I18n
::isMultilingual() && $localizableFields) {
1892 $locales = CRM_Core_I18n
::getMultilingual();
1893 $curLocale = CRM_Core_I18n
::getLocale();
1894 // loop on other locales
1895 foreach ($locales as $locale) {
1896 if ($locale != $curLocale) {
1897 // setLocale doesn't seems to be reliable to set dbLocale and we only need to change the db locale
1898 $dbLocale = '_' . $locale;
1899 $newObject->copyLocalizable($object->id
, $newObject->id
, $fieldsToPrefix, $fieldsToSuffix, $fieldsToReplace);
1902 // restore dbLocale to starting value
1903 $dbLocale = '_' . $curLocale;
1906 if (!$blockCopyofCustomValues) {
1907 $newObject->copyCustomFields($object->id
, $newObject->id
);
1909 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName($daoName), $newObject->id
, $newObject);
1916 * Method that copies localizable fields from an old entity to a new one.
1918 * Fixes bug dev/core#2479,
1919 * where non current locale fields are copied from current locale losing translation when copying
1921 * @param int $entityID
1922 * @param int $newEntityID
1923 * @param array $fieldsToPrefix
1924 * @param array $fieldsToSuffix
1925 * @param array $fieldsToReplace
1927 protected function copyLocalizable($entityID, $newEntityID, $fieldsToPrefix, $fieldsToSuffix, $fieldsToReplace) {
1928 $entity = get_class($this);
1929 $object = new $entity();
1930 $object->id
= $entityID;
1933 $newObject = new $entity();
1934 $newObject->id
= $newEntityID;
1938 if ($object->fetch() && $newObject->fetch()) {
1940 $fields = $object->fields();
1941 foreach ($fields as $name => $value) {
1943 if ($name == 'id' ||
$value['name'] == 'id') {
1944 // copy everything but the id!
1948 // only copy localizable fields
1949 if (!$value['localizable']) {
1953 $dbName = $value['name'];
1954 $type = CRM_Utils_Type
::typeToString($value['type']);
1955 $newObject->$dbName = $object->$dbName;
1956 if (isset($fieldsToPrefix[$dbName])) {
1957 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1959 if (isset($fieldsToSuffix[$dbName])) {
1960 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1962 if (isset($fieldsToReplace[$dbName])) {
1963 $newObject->$dbName = $fieldsToReplace[$dbName];
1966 if ($type == 'Timestamp' ||
$type == 'Date') {
1967 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1977 * Method that copies custom fields values from an old entity to a new one.
1979 * Fixes bug CRM-19302,
1980 * where if a custom field of File type was present, left both events using the same file,
1981 * breaking download URL's for the old event.
1983 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1984 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1986 * @param int $entityID
1987 * @param int $newEntityID
1988 * @param string $parentOperation
1990 public function copyCustomFields($entityID, $newEntityID, $parentOperation = NULL) {
1991 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1992 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1993 // Obtain custom values for the old entity.
1994 $customParams = $htmlType = [];
1995 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1997 // If custom values present, we copy them
1998 if (!empty($customValues)) {
1999 // Get Field ID's and identify File type attributes, to handle file copying.
2000 $fieldIds = implode(', ', array_keys($customValues));
2001 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
2002 $result = CRM_Core_DAO
::executeQuery($sql);
2004 // Build array of File type fields
2005 while ($result->fetch()) {
2006 $htmlType[] = $result->id
;
2009 // Build params array of custom values
2010 foreach ($customValues as $field => $value) {
2011 if ($value !== NULL) {
2012 // Handle File type attributes
2013 if (in_array($field, $htmlType)) {
2014 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
2015 $customParams["custom_{$field}_-1"] = [
2016 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
2017 'type' => $fileValues[1],
2020 // Handle other types
2022 $customParams["custom_{$field}_-1"] = $value;
2027 // Save Custom Fields for new Entity.
2028 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity, $parentOperation ??
'create');
2031 // copy activity attachments ( if any )
2032 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
2036 * Cascade update through related entities.
2038 * @param string $daoName
2041 * @param array $newData
2043 * @return CRM_Core_DAO|null
2045 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
2046 $object = new $daoName();
2047 $object->id
= $fromId;
2049 if ($object->find(TRUE)) {
2050 $newObject = new $daoName();
2051 $newObject->id
= $toId;
2053 if ($newObject->find(TRUE)) {
2054 $fields = $object->fields();
2055 foreach ($fields as $name => $value) {
2056 if ($name == 'id' ||
$value['name'] == 'id') {
2057 // copy everything but the id!
2061 $colName = $value['name'];
2062 $newObject->$colName = $object->$colName;
2064 if (substr($name, -5) == '_date' ||
2065 substr($name, -10) == '_date_time'
2067 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
2070 foreach ($newData as $k => $v) {
2071 $newObject->$k = $v;
2081 * Given the component id, compute the contact id
2082 * since its used for things like send email
2084 * @param $componentIDs
2085 * @param string $tableName
2086 * @param string $idField
2090 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
2093 if (empty($componentIDs)) {
2097 $IDs = implode(',', $componentIDs);
2101 WHERE $idField IN ( $IDs )
2104 $dao = CRM_Core_DAO
::executeQuery($query);
2105 while ($dao->fetch()) {
2106 $contactIDs[] = $dao->contact_id
;
2112 * Fetch object based on array of properties.
2114 * @param string $daoName
2115 * Name of the dao object.
2116 * @param string $fieldIdName
2117 * @param int $fieldId
2119 * @param array $returnProperities
2120 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
2123 * an object of type referenced by daoName
2125 public static function commonRetrieveAll($daoName, $fieldIdName, $fieldId, &$details, $returnProperities = NULL) {
2126 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
2127 $object = new $daoName();
2128 $object->$fieldIdName = $fieldId;
2130 // return only specific fields if returnproperties are sent
2131 if (!empty($returnProperities)) {
2132 $object->selectAdd();
2133 $object->selectAdd('id');
2134 $object->selectAdd(implode(',', $returnProperities));
2138 while ($object->fetch()) {
2140 self
::storeValues($object, $defaults);
2141 $details[$object->id
] = $defaults;
2148 * Drop all CiviCRM tables.
2150 * @throws \CRM_Core_Exception
2152 public static function dropAllTables() {
2154 // first drop all the custom tables we've created
2155 CRM_Core_BAO_CustomGroup
::dropAllTables();
2157 // drop all multilingual views
2158 CRM_Core_I18n_Schema
::dropAllViews();
2160 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
2161 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
2162 '..' . DIRECTORY_SEPARATOR
.
2163 '..' . DIRECTORY_SEPARATOR
.
2164 'sql' . DIRECTORY_SEPARATOR
.
2165 'civicrm_drop.mysql'
2174 public static function escapeString($string) {
2175 static $_dao = NULL;
2177 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
2178 // has been installed), then we fallback DB-less str_replace escaping, as
2179 // we can't use mysqli_real_escape_string, as there is no DB connection.
2180 // Note: In typical usage, escapeString() will only check one conditional
2181 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
2182 if (!defined('CIVICRM_DSN')) {
2183 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
2184 // list of characters mysqli_real_escape_string escapes.
2185 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
2186 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
2187 return str_replace($search, $replace, $string);
2189 $_dao = new CRM_Core_DAO();
2191 return $_dao->escape($string);
2195 * Escape a list of strings for use with "WHERE X IN (...)" queries.
2197 * @param array $strings
2198 * @param string $default
2199 * the value to use if $strings has no elements.
2201 * eg "abc","def","ghi"
2203 public static function escapeStrings($strings, $default = NULL) {
2204 static $_dao = NULL;
2206 $_dao = new CRM_Core_DAO();
2209 if (empty($strings)) {
2213 $escapes = array_map([$_dao, 'escape'], $strings);
2214 return '"' . implode('","', $escapes) . '"';
2222 public static function escapeWildCardString($string) {
2224 // ensure we escape the single characters % and _ which are mysql wild
2225 // card characters and could come in via sortByCharacter
2226 // note that mysql does not escape these characters
2227 if ($string && in_array($string,
2228 ['%', '_', '%%', '_%']
2231 return '\\' . $string;
2234 return self
::escapeString($string);
2238 * Creates a test object, including any required objects it needs via recursion
2239 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
2240 * ONLY USE FOR TESTING
2242 * @param string $daoName
2243 * @param array $params
2244 * @param int $numObjects
2245 * @param bool $createOnly
2247 * @return object|array|NULL
2248 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
2250 public static function createTestObject(
2256 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2257 // so we re-set here in case
2258 $config = CRM_Core_Config
::singleton();
2259 $config->backtrace
= TRUE;
2261 static $counter = 0;
2262 CRM_Core_DAO
::$_testEntitiesToSkip = [
2263 'CRM_Core_DAO_Worldregion',
2264 'CRM_Core_DAO_StateProvince',
2265 'CRM_Core_DAO_Country',
2266 'CRM_Core_DAO_Domain',
2267 'CRM_Financial_DAO_FinancialType',
2268 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
2271 // Prefer to instantiate BAO's instead of DAO's (when possible)
2272 // so that assignTestValue()/assignTestFK() can be overloaded.
2273 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
2274 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
2275 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
2276 // @todo create a new class called what the BAO SHOULD be
2277 // that extends BAO-crazy-name.... migrate.
2278 $baoName = 'CRM_Core_BAO_FinancialTrxn';
2280 if (class_exists($baoName)) {
2281 $daoName = $baoName;
2284 for ($i = 0; $i < $numObjects; ++
$i) {
2287 /** @var CRM_Core_DAO $object */
2288 $object = new $daoName();
2290 $fields = $object->fields();
2291 foreach ($fields as $fieldName => $fieldDef) {
2292 $dbName = $fieldDef['name'];
2293 $FKClassName = $fieldDef['FKClassName'] ??
NULL;
2295 if (isset($params[$dbName]) && !is_array($params[$dbName])) {
2296 $object->$dbName = $params[$dbName];
2299 elseif ($dbName != 'id') {
2300 if ($FKClassName != NULL) {
2301 $object->assignTestFK($fieldName, $fieldDef, $params);
2305 $object->assignTestValue($fieldName, $fieldDef, $counter);
2313 $objects[$i] = $object;
2323 elseif ($numObjects == 1) {
2332 * Deletes the this object plus any dependent objects that are associated with it.
2333 * ONLY USE FOR TESTING
2335 * @param string $daoName
2336 * @param array $params
2338 public static function deleteTestObjects($daoName, $params = []) {
2339 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2340 // so we re-set here in case
2341 $config = CRM_Core_Config
::singleton();
2342 $config->backtrace
= TRUE;
2344 $object = new $daoName();
2345 $object->id
= $params['id'] ??
NULL;
2347 // array(array(0 => $daoName, 1 => $daoParams))
2349 if ($object->find(TRUE)) {
2351 $fields = $object->fields();
2352 foreach ($fields as $name => $value) {
2354 $dbName = $value['name'];
2356 $FKClassName = $value['FKClassName'] ??
NULL;
2357 $required = $value['required'] ??
NULL;
2358 if ($FKClassName != NULL
2360 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2361 && ($required ||
$dbName == 'contact_id')
2362 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2363 // to make this test process pass - line below makes pass for now
2364 && $dbName != 'member_of_contact_id'
2367 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2374 foreach ($deletions as $deletion) {
2375 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2380 * Set defaults when creating new entity.
2381 * (don't call this set defaults as already in use with different signature in some places)
2383 * @param array $params
2386 public static function setCreateDefaults(&$params, $defaults) {
2387 if (!empty($params['id'])) {
2390 foreach ($defaults as $key => $value) {
2391 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2392 $params[$key] = $value;
2398 * @param string $prefix
2399 * @param bool $addRandomString
2400 * @param null $string
2404 * @see CRM_Utils_SQL_TempTable
2406 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2407 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2408 $tableName = $prefix . "_temp";
2410 if ($addRandomString) {
2412 $tableName .= "_" . $string;
2415 $tableName .= "_" . md5(uniqid('', TRUE));
2423 * @param bool $trigger
2427 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2428 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2431 // test for create view and trigger permissions and if allowed, add the option to go multilingual and logging
2432 $dao = new CRM_Core_DAO();
2435 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2436 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2440 $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2441 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2444 catch (Exception
$e) {
2452 * @param null $message
2453 * @param bool $printDAO
2455 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2456 CRM_Utils_System
::xMemory("{$message}: ");
2459 global $_DB_DATAOBJECT;
2461 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2462 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2464 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2469 * Build a list of triggers via hook and add them to (err, reconcile them
2470 * with) the database.
2472 * @param string $tableName
2473 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2474 * @param bool $force
2479 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2480 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2484 * Wrapper function to drop triggers.
2486 * @param string $tableName
2487 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2490 public static function dropTriggers($tableName = NULL) {
2491 Civi
::service('sql_triggers')->dropTriggers($tableName);
2495 * @param array $info
2496 * per hook_civicrm_triggerInfo.
2497 * @param string $onlyTableName
2498 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2501 public static function createTriggers(&$info, $onlyTableName = NULL) {
2502 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2506 * Given a list of fields, create a list of references.
2508 * @param string $className
2509 * BAO/DAO class name.
2510 * @return array<CRM_Core_Reference_Interface>
2512 public static function createReferenceColumns($className) {
2514 $fields = $className::fields();
2515 foreach ($fields as $field) {
2516 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2517 $result[] = new CRM_Core_Reference_OptionValue(
2518 $className::getTableName(),
2520 'civicrm_option_value',
2521 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2522 $field['pseudoconstant']['optionGroupName']
2530 * Find all records which refer to this entity.
2532 * @return CRM_Core_DAO[]
2534 public function findReferences() {
2535 $links = self
::getReferencesToTable(static::getTableName());
2538 foreach ($links as $refSpec) {
2539 /** @var $refSpec CRM_Core_Reference_Interface */
2540 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2541 $result = $refSpec->findReferences($this);
2543 while ($result->fetch()) {
2544 $obj = new $daoName();
2545 $obj->id
= $result->id
;
2546 $occurrences[] = $obj;
2551 return $occurrences;
2555 * @return array{name: string, type: string, count: int, table: string|null, key: string|null}[]
2556 * each item has keys:
2560 * - table: string|null SQL table name
2561 * - key: string|null SQL column name
2563 public function getReferenceCounts() {
2564 $links = self
::getReferencesToTable(static::getTableName());
2567 foreach ($links as $refSpec) {
2568 /** @var $refSpec CRM_Core_Reference_Interface */
2569 $count = $refSpec->getReferenceCount($this);
2570 if (!empty($count['count'])) {
2575 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2576 /** @var $component CRM_Core_Component_Info */
2577 $counts = array_merge($counts, $component->getReferenceCounts($this));
2579 CRM_Utils_Hook
::referenceCounts($this, $counts);
2585 * List all tables which have hard foreign keys to this table.
2587 * For now, this returns a description of every entity_id/entity_table
2589 * TODO: filter dynamic entity references on the $tableName, based on
2590 * schema metadata in dynamicForeignKey which enumerates a restricted
2591 * set of possible entity_table's.
2593 * @param string $tableName
2594 * Table referred to.
2596 * @return CRM_Core_Reference_Interface[]
2597 * structure of table and column, listing every table with a
2598 * foreign key reference to $tableName, and the column where the key appears.
2600 public static function getReferencesToTable($tableName) {
2602 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2603 $links = $daoClassName::getReferenceColumns();
2605 foreach ($links as $refSpec) {
2606 /** @var $refSpec CRM_Core_Reference_Interface */
2607 if ($refSpec->matchesTargetTable($tableName)) {
2608 $refsFound[] = $refSpec;
2616 * Get all references to contact table.
2618 * This includes core tables, custom group tables, tables added by the merge
2619 * hook and the entity_tag table.
2621 * Refer to CRM-17454 for information on the danger of querying the information
2622 * schema to derive this.
2624 * @throws \CiviCRM_API3_Exception
2626 public static function getReferencesToContactTable() {
2627 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2628 return \Civi
::$statics[__CLASS__
]['contact_references'];
2630 $contactReferences = [];
2631 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2632 foreach ($coreReferences as $coreReference) {
2634 // Exclude option values
2635 !is_a($coreReference, 'CRM_Core_Reference_Dynamic') &&
2636 // Exclude references to other columns
2637 $coreReference->getTargetKey() === 'id'
2639 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2642 self
::appendCustomTablesExtendingContacts($contactReferences);
2643 self
::appendCustomContactReferenceFields($contactReferences);
2644 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2645 return \Civi
::$statics[__CLASS__
]['contact_references'];
2649 * Get all dynamic references to the given table.
2651 * @param string $tableName
2655 public static function getDynamicReferencesToTable($tableName) {
2656 if (!isset(\Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName])) {
2657 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName] = [];
2658 $coreReferences = CRM_Core_DAO
::getReferencesToTable($tableName);
2659 foreach ($coreReferences as $coreReference) {
2660 if ($coreReference instanceof \CRM_Core_Reference_Dynamic
) {
2661 \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName][$coreReference->getReferenceTable()][] = [$coreReference->getReferenceKey(), $coreReference->getTypeColumn()];
2665 return \Civi
::$statics[__CLASS__
]['contact_references_dynamic'][$tableName];
2669 * Add custom tables that extend contacts to the list of contact references.
2671 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2672 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2673 * - the down side is it is not cached.
2675 * Further changes should be include tests in the CRM_Core_MergerTest class
2676 * to ensure that disabled, subtype, multiple etc groups are still captured.
2678 * @param array $cidRefs
2680 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2681 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2682 $customValueTables->find();
2683 while ($customValueTables->fetch()) {
2684 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2689 * Add custom ContactReference fields to the list of contact references
2691 * This includes active and inactive fields/groups
2693 * @param array $cidRefs
2695 * @throws \CiviCRM_API3_Exception
2697 public static function appendCustomContactReferenceFields(&$cidRefs) {
2698 $fields = civicrm_api3('CustomField', 'get', [
2699 'return' => ['column_name', 'custom_group_id.table_name'],
2700 'data_type' => 'ContactReference',
2701 'options' => ['limit' => 0],
2703 foreach ($fields as $field) {
2704 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2709 * Lookup the value of a MySQL global configuration variable.
2711 * @param string $name
2712 * E.g. "thread_stack".
2713 * @param mixed $default
2716 public static function getGlobalSetting($name, $default = NULL) {
2717 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2718 // that has been reported to fail under MySQL 5.0 for OS X
2719 $escapedName = self
::escapeString($name);
2720 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2721 if ($dao->fetch()) {
2730 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2732 * This is relevant where we want to offer both the ID field and the label field
2733 * as an option, e.g. search builder.
2735 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2736 * change small, but is appropriate for other sorts of pseudoconstants.
2738 * @param array $fields
2740 public static function appendPseudoConstantsToFields(&$fields) {
2741 foreach ($fields as $fieldUniqueName => $field) {
2742 if (!empty($field['pseudoconstant'])) {
2743 $pseudoConstant = $field['pseudoconstant'];
2744 if (!empty($pseudoConstant['optionGroupName'])) {
2745 $fields[$pseudoConstant['optionGroupName']] = [
2746 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2747 'name' => $pseudoConstant['optionGroupName'],
2748 'data_type' => CRM_Utils_Type
::T_STRING
,
2749 'is_pseudofield_for' => $fieldUniqueName,
2752 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2754 !empty($field['FKClassName'])
2755 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2756 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2758 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2759 // This if is just an extra caution when adding change.
2760 if (!isset($fields[$pseudoFieldName])) {
2761 $daoName = $field['FKClassName'];
2762 $fkFields = $daoName::fields();
2763 foreach ($fkFields as $fkField) {
2764 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2765 $fields[$pseudoFieldName] = [
2766 'name' => $pseudoFieldName,
2767 'is_pseudofield_for' => $field['name'],
2768 'title' => $fkField['title'],
2769 'data_type' => $fkField['type'],
2770 'where' => $field['where'],
2781 * Get options for the called BAO object's field.
2783 * This function can be overridden by each BAO to add more logic related to context.
2784 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2786 * @param string $fieldName
2787 * @param string $context
2788 * @see CRM_Core_DAO::buildOptionsContext
2789 * @param array $props
2790 * Raw field values; whatever is known about this bao object.
2792 * Note: $props can contain unsanitized input and should not be passed directly to CRM_Core_PseudoConstant::get
2794 * @return array|bool
2796 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2797 // If a given bao does not override this function
2798 $baoName = get_called_class();
2799 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, [], $context);
2803 * Populate option labels for this object's fields.
2805 * @throws exception if called directly on the base class
2807 public function getOptionLabels() {
2808 $fields = $this->fields();
2809 if ($fields === NULL) {
2810 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2812 foreach ($fields as $field) {
2813 $name = $field['name'] ??
NULL;
2814 if ($name && isset($this->$name)) {
2815 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2816 if ($label !== FALSE) {
2817 // Append 'label' onto the field name
2818 $labelName = $name . '_label';
2819 $this->$labelName = $label;
2826 * Provides documentation and validation for the buildOptions $context param
2828 * @param string $context
2830 * @throws CRM_Core_Exception
2833 public static function buildOptionsContext($context = NULL) {
2835 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2836 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2837 'search' => "search: searchable options are returned; labels are translated.",
2838 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2839 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2840 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2842 // Validation: enforce uniformity of this param
2843 if ($context !== NULL && !isset($contexts[$context])) {
2844 throw new CRM_Core_Exception("'$context' is not a valid context for buildOptions.");
2850 * @param string $fieldName
2851 * @return bool|array
2853 public function getFieldSpec($fieldName) {
2854 $fields = $this->fields();
2856 // Support "unique names" as well as sql names
2857 $fieldKey = $fieldName;
2858 if (empty($fields[$fieldKey])) {
2859 $fieldKeys = $this->fieldKeys();
2860 $fieldKey = $fieldKeys[$fieldName] ??
NULL;
2862 // If neither worked then this field doesn't exist. Return false.
2863 if (empty($fields[$fieldKey])) {
2866 return $fields[$fieldKey];
2870 * Get SQL where clause for SQL filter syntax input parameters.
2872 * SQL version of api function to assign filters to the DAO based on the syntax
2873 * $field => array('IN' => array(4,6,9))
2875 * $field => array('LIKE' => array('%me%))
2878 * @param string $fieldName
2880 * @param array $filter
2881 * filter to be applied indexed by operator.
2882 * @param string $type
2883 * type of field (not actually used - nor in api @todo ).
2884 * @param string $alias
2885 * alternative field name ('as') @todo- not actually used.
2886 * @param bool $returnSanitisedArray
2887 * Return a sanitised array instead of a clause.
2888 * this is primarily so we can add filters @ the api level to the Query object based fields
2892 * @return NULL|string|array
2893 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2894 * depending on whether it is supported as yet
2896 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2897 foreach ($filter as $operator => $criteria) {
2898 $emojiFilter = CRM_Utils_SQL
::handleEmojiInQuery($criteria);
2899 if ($emojiFilter === '0 = 1') {
2900 return $emojiFilter;
2903 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2904 switch ($operator) {
2908 if (!$returnSanitisedArray) {
2909 return (sprintf('%s %s', $fieldName, $operator));
2912 return (sprintf('%s %s ', $fieldName, $operator));
2916 // ternary operators
2919 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2920 throw new Exception("invalid criteria for $operator");
2922 if (!$returnSanitisedArray) {
2923 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2926 // not yet implemented (tests required to implement)
2934 if (empty($criteria)) {
2935 throw new Exception("invalid criteria for $operator");
2937 $escapedCriteria = array_map([
2941 if (!$returnSanitisedArray) {
2942 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2944 return $escapedCriteria;
2949 if (!$returnSanitisedArray) {
2950 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2953 // not yet implemented (tests required to implement)
2962 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2963 * support for other syntaxes is discussed in ticket but being put off for now
2966 public static function acceptedSQLOperators() {
2987 * SQL has a limit of 64 characters on various names:
2988 * table name, trigger name, column name ...
2990 * For custom groups and fields we generated names from user entered input
2991 * which can be longer than this length, this function helps with creating
2992 * strings that meet various criteria.
2994 * @param string $string
2995 * The string to be shortened.
2996 * @param int $length
2997 * The max length of the string.
2999 * @param bool $makeRandom
3003 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
3004 // early return for strings that meet the requirements
3005 if (strlen($string) <= $length) {
3009 // easy return for calls that dont need a randomized uniq string
3011 return substr($string, 0, $length);
3014 // the string is longer than the length and we need a uniq string
3015 // for the same tablename we need the same uniq string every time
3016 // hence we use md5 on the string, which is not random
3017 // we'll append 8 characters to the end of the tableName
3018 $md5string = substr(md5($string), 0, 8);
3019 return substr($string, 0, $length - 8) . "_{$md5string}";
3023 * https://issues.civicrm.org/jira/browse/CRM-17748
3024 * Sets the internal options to be used on a query
3026 * @param array $options
3029 public function setOptions($options) {
3030 if (is_array($options)) {
3031 $this->_options
= $options;
3036 * https://issues.civicrm.org/jira/browse/CRM-17748
3037 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
3039 * @param array $options
3042 protected function _setDBOptions($options) {
3043 global $_DB_DATAOBJECT;
3045 if (is_array($options) && count($options)) {
3046 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
3047 foreach ($options as $option_name => $option_value) {
3048 $conn->setOption($option_name, $option_value);
3055 * @param array $params
3057 public function setApiFilter(&$params) {
3061 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
3063 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
3066 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
3070 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
3074 public function addSelectWhereClause() {
3076 $fields = $this->fields();
3077 foreach ($fields as $fieldName => $field) {
3078 // Clause for contact-related entities like Email, Relationship, etc.
3079 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
3080 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
3082 // Clause for an entity_table/entity_id combo
3083 if ($fieldName === 'entity_id' && isset($fields['entity_table'])) {
3084 $relatedClauses = [];
3085 $relatedEntities = $this->buildOptions('entity_table', 'get');
3086 foreach ((array) $relatedEntities as $table => $ent) {
3088 $ent = CRM_Core_DAO_AllCoreTables
::getEntityNameForTable($table);
3089 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
3091 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
3094 $relatedClauses[] = "(entity_table = '$table')";
3098 if ($relatedClauses) {
3099 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
3103 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
3108 * This returns the final permissioned query string for this entity
3110 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
3112 * @param string $tableAlias
3115 public static function getSelectWhereClause($tableAlias = NULL) {
3116 $bao = new static();
3117 if ($tableAlias === NULL) {
3118 $tableAlias = $bao->tableName();
3121 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
3122 $clauses[$field] = NULL;
3124 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
3131 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
3132 * and dashes, and contains at least one [a-z] case insensitive.
3138 public static function requireSafeDBName($database) {
3141 "/^[\w\-]*[a-z]+[\w\-]*$/i",
3145 if (empty($matches)) {
3152 * Transform an array to a serialized string for database storage.
3154 * @param array|null $value
3155 * @param int $serializationType
3156 * @return string|null
3158 * @throws \Exception
3160 public static function serializeField($value, $serializationType) {
3161 if ($value === NULL) {
3164 switch ($serializationType) {
3165 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3166 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
3168 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3169 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
3171 case self
::SERIALIZE_JSON
:
3172 return is_array($value) ?
json_encode($value) : $value;
3174 case self
::SERIALIZE_PHP
:
3175 return is_array($value) ?
serialize($value) : $value;
3177 case self
::SERIALIZE_COMMA
:
3178 return is_array($value) ?
implode(',', $value) : $value;
3181 throw new Exception('Unknown serialization method for field.');
3186 * Transform a serialized string from the database into an array.
3188 * @param string|null $value
3189 * @param $serializationType
3191 * @return array|null
3192 * @throws CRM_Core_Exception
3194 public static function unSerializeField($value, $serializationType) {
3195 if ($value === NULL) {
3198 if ($value === '') {
3201 switch ($serializationType) {
3202 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
3203 return (array) CRM_Utils_Array
::explodePadded($value);
3205 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
3206 return explode(self
::VALUE_SEPARATOR
, trim($value));
3208 case self
::SERIALIZE_JSON
:
3209 return strlen($value) ?
json_decode($value, TRUE) : [];
3211 case self
::SERIALIZE_PHP
:
3212 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
3214 case self
::SERIALIZE_COMMA
:
3215 return explode(',', trim(str_replace(', ', '', $value)));
3218 throw new CRM_Core_Exception('Unknown serialization method for field.');
3225 public static function getEntityRefFilters() {
3230 * Get exportable fields with pseudoconstants rendered as an extra field.
3232 * @param string $baoClass
3236 public static function getExportableFieldsWithPseudoConstants($baoClass) {
3237 if (method_exists($baoClass, 'exportableFields')) {
3238 $fields = $baoClass::exportableFields();
3241 $fields = $baoClass::export();
3243 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
3248 * Remove item from static cache during update/delete operations
3250 private function clearDbColumnValueCache() {
3251 $daoName = get_class($this);
3252 while (strpos($daoName, '_BAO_') !== FALSE) {
3253 $daoName = get_parent_class($daoName);
3255 if (isset($this->id
)) {
3256 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
3258 if (isset($this->name
)) {
3259 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);
3264 * Return a mapping from field-name to the corresponding key (as used in fields()).
3267 * Array(string $name => string $uniqueName).
3269 public static function fieldKeys() {
3270 return array_flip(CRM_Utils_Array
::collect('name', static::fields()));
3274 * Returns system paths related to this entity (as defined in the xml schema)
3278 public static function getEntityPaths() {
3279 return static::$_paths ??
[];