3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
13 * Base Database Access Object class.
15 * All DAO classes should inherit from this class.
18 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 if (!defined('DB_DSN_MODE')) {
22 define('DB_DSN_MODE', 'auto');
25 require_once 'PEAR.php';
26 require_once 'DB/DataObject.php';
28 require_once 'CRM/Core/I18n.php';
33 class CRM_Core_DAO
extends DB_DataObject
{
36 * How many times has this instance been cloned.
40 protected $resultCopies = 0;
46 public static $_nullObject = NULL;
51 public static $_nullArray = [];
53 public static $_dbColumnValueCache = NULL;
54 const NOT_NULL
= 1, IS_NULL
= 2,
56 VALUE_SEPARATOR
= "\ 1",
57 BULK_INSERT_COUNT
= 200,
58 BULK_INSERT_HIGH_COUNT
= 200,
59 QUERY_FORMAT_WILDCARD
= 1,
60 QUERY_FORMAT_NO_QUOTES
= 2,
63 * Serialized string separated by and bookended with VALUE_SEPARATOR
65 SERIALIZE_SEPARATOR_BOOKEND
= 1,
67 * @deprecated format separated by VALUE_SEPARATOR
69 SERIALIZE_SEPARATOR_TRIMMED
= 2,
71 * Recommended serialization format
75 * @deprecated format using php serialize()
79 * Comma separated string, no quotes, no spaces
84 * Define entities that shouldn't be created or deleted when creating/ deleting
85 * test objects - this prevents world regions, countries etc from being added / deleted
88 public static $_testEntitiesToSkip = [];
90 * The factory class for this application.
93 public static $_factory = NULL;
95 public static $_checkedSqlFunctionsExist = FALSE;
98 * https://issues.civicrm.org/jira/browse/CRM-17748
99 * internal variable for DAO to hold per-query settings
102 protected $_options = [];
107 * @return \CRM_Core_DAO
109 public function __construct() {
111 $this->__table
= $this->getTableName();
114 public function __clone() {
115 if (!empty($this->_DB_resultid
)) {
116 $this->resultCopies++
;
123 public function __destruct() {
124 if ($this->resultCopies
=== 0) {
127 $this->resultCopies
--;
131 * Empty definition for virtual function.
133 public static function getTableName() {
138 * Initialize the DAO object.
141 * The database connection string.
143 public static function init($dsn) {
144 Civi
::$statics[__CLASS__
]['init'] = 1;
145 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
146 $options['database'] = $dsn;
147 $options['quote_identifiers'] = TRUE;
148 if (defined('CIVICRM_DAO_DEBUG')) {
149 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
151 $factory = new CRM_Contact_DAO_Factory();
152 CRM_Core_DAO
::setFactory($factory);
153 $currentModes = CRM_Utils_SQL
::getSqlModes();
154 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
155 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
156 $currentModes[] = 'ONLY_FULL_GROUP_BY';
158 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
159 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
161 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
163 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
164 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
170 public static function getConnection() {
171 global $_DB_DATAOBJECT;
172 $dao = new CRM_Core_DAO();
173 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
177 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
179 public static function disableFullGroupByMode() {
180 $currentModes = CRM_Utils_SQL
::getSqlModes();
181 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
182 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
183 unset($currentModes[$key]);
184 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
189 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
191 public static function reenableFullGroupByMode() {
192 $currentModes = CRM_Utils_SQL
::getSqlModes();
193 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
194 $currentModes[] = 'ONLY_FULL_GROUP_BY';
195 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
200 * @param string $fieldName
202 * @param array $params
204 protected function assignTestFK($fieldName, $fieldDef, $params) {
205 $required = CRM_Utils_Array
::value('required', $fieldDef);
206 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
207 $dbName = $fieldDef['name'];
208 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
210 // skip the FK if it is not required
211 // if it's contact id we should create even if not required
212 // we'll have a go @ fetching first though
213 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
214 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
217 if (!$required && $dbName != 'contact_id') {
218 $fkDAO = new $FKClassName();
219 if ($fkDAO->find(TRUE)) {
220 $this->$dbName = $fkDAO->id
;
224 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
225 $depObject = new $FKClassName();
226 $depObject->find(TRUE);
227 $this->$dbName = $depObject->id
;
229 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
230 // FIXME: the fields() metadata is not specific enough
231 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
232 $this->$dbName = $depObject->id
;
235 //if it is required we need to generate the dependency object first
236 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
237 $this->$dbName = $depObject->id
;
242 * Generate and assign an arbitrary value to a field of a test object.
244 * @param string $fieldName
245 * @param array $fieldDef
246 * @param int $counter
247 * The globally-unique ID of the test object.
249 * @throws \CRM_Core_Exception
251 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
252 $dbName = $fieldDef['name'];
253 $daoName = get_class($this);
256 if (!$handled && $dbName == 'contact_sub_type') {
257 //coming up with a rule to set this is too complex let's not set it
261 // Pick an option value if needed
262 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
263 $options = $daoName::buildOptions($dbName, 'create');
265 $this->$dbName = key($options);
271 switch ($fieldDef['type']) {
272 case CRM_Utils_Type
::T_INT
:
273 case CRM_Utils_Type
::T_FLOAT
:
274 case CRM_Utils_Type
::T_MONEY
:
275 if (isset($fieldDef['precision'])) {
276 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
277 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
280 $this->$dbName = $counter;
284 case CRM_Utils_Type
::T_BOOLEAN
:
285 if (isset($fieldDef['default'])) {
286 $this->$dbName = $fieldDef['default'];
288 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
296 case CRM_Utils_Type
::T_DATE
:
297 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
298 $this->$dbName = '19700101';
299 if ($dbName == 'end_date') {
300 // put this in the future
301 $this->$dbName = '20200101';
305 case CRM_Utils_Type
::T_TIMESTAMP
:
306 $this->$dbName = '19700201000000';
309 case CRM_Utils_Type
::T_TIME
:
310 throw new CRM_Core_Exception('T_TIME shouldn\'t be used.');
312 case CRM_Utils_Type
::T_CCNUM
:
313 $this->$dbName = '4111 1111 1111 1111';
316 case CRM_Utils_Type
::T_URL
:
317 $this->$dbName = 'http://www.civicrm.org';
320 case CRM_Utils_Type
::T_STRING
:
321 case CRM_Utils_Type
::T_BLOB
:
322 case CRM_Utils_Type
::T_MEDIUMBLOB
:
323 case CRM_Utils_Type
::T_TEXT
:
324 case CRM_Utils_Type
::T_LONGTEXT
:
325 case CRM_Utils_Type
::T_EMAIL
:
327 // WAS: if (isset($value['enumValues'])) {
328 // TODO: see if this works with all pseudoconstants
329 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
330 if (isset($fieldDef['default'])) {
331 $this->$dbName = $fieldDef['default'];
334 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
335 if (is_array($options)) {
336 $this->$dbName = $options[0];
339 $defaultValues = explode(',', $options);
340 $this->$dbName = $defaultValues[0];
345 $this->$dbName = $dbName . '_' . $counter;
346 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
347 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
348 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
356 * Reset the DAO object.
358 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
360 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
362 public function reset() {
364 foreach (array_keys($this->table()) as $field) {
365 unset($this->$field);
369 * reset the various DB_DAO structures manually
378 * @param string $tableName
382 public static function getLocaleTableName($tableName) {
385 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
386 if (in_array($tableName, $tables)) {
387 return $tableName . $dbLocale;
394 * Execute a query by the current DAO, localizing it along the way (if needed).
396 * @param string $query
397 * The SQL query for execution.
398 * @param bool $i18nRewrite
399 * Whether to rewrite the query.
402 * the current DAO object after the query execution
404 public function query($query, $i18nRewrite = TRUE) {
405 // rewrite queries that should use $dbLocale-based views for multi-language installs
406 global $dbLocale, $_DB_DATAOBJECT;
408 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
409 // Will force connection to be populated per CRM-20541.
413 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
414 $orig_options = $conn->options
;
415 $this->_setDBOptions($this->_options
);
417 if ($i18nRewrite and $dbLocale) {
418 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
421 $ret = parent
::query($query);
423 $this->_setDBOptions($orig_options);
428 * Static function to set the factory instance for this class.
430 * @param object $factory
431 * The factory application object.
433 public static function setFactory(&$factory) {
434 self
::$_factory = &$factory;
438 * Factory method to instantiate a new object from a table name.
440 * @param string $table
441 * @return \DataObject|\PEAR_Error
443 public function factory($table = '') {
444 if (!isset(self
::$_factory)) {
445 return parent
::factory($table);
448 return self
::$_factory->create($table);
452 * Initialization for all DAO objects. Since we access DB_DO programatically
453 * we need to set the links manually.
455 public function initialize() {
457 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
458 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
459 // This occurs very early in bootstrap - error handlers may not be wired up.
460 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
461 CRM_Utils_System
::civiExit();
466 * Defines the default key as 'id'.
470 public function keys() {
479 * Tells DB_DataObject which keys use autoincrement.
480 * 'id' is autoincrementing by default.
485 public function sequenceKey() {
486 static $sequenceKeys;
487 if (!isset($sequenceKeys)) {
488 $sequenceKeys = ['id', TRUE];
490 return $sequenceKeys;
494 * Returns list of FK relationships.
498 * Array of CRM_Core_Reference_Interface
500 public static function getReferenceColumns() {
505 * Returns all the column names of this table.
510 public static function &fields() {
516 * Get/set an associative array of table columns
521 public function table() {
522 $fields = $this->fields();
526 foreach ($fields as $name => $value) {
527 $table[$value['name']] = $value['type'];
528 if (!empty($value['required'])) {
529 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
542 * @return CRM_Core_DAO
544 public function save($hook = TRUE) {
545 if (!empty($this->id
)) {
549 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
550 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
552 $this->clearDbColumnValueCache();
558 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
559 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
565 CRM_Utils_Hook
::postSave($this);
572 * Deletes items from table which match current objects variables.
574 * Returns the true on success
578 * Designed to be extended
580 * $object = new mytable();
582 * echo $object->delete(); // builds a conditon
584 * $object = new mytable();
585 * $object->whereAdd('age > 12');
587 * $object->orderBy('age DESC');
588 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
590 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
591 * we will build the condition only using the whereAdd's. Default is to
592 * build the condition only using the object parameters.
594 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
596 public function delete($useWhere = FALSE) {
597 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
598 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
600 $result = parent
::delete($useWhere);
602 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
603 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
606 $this->clearDbColumnValueCache();
612 * @param bool $created
614 public function log($created = FALSE) {
617 if (!$this->getLog()) {
622 $session = CRM_Core_Session
::singleton();
623 $cid = $session->get('userID');
626 // return is we dont have handle to FK
631 $dao = new CRM_Core_DAO_Log();
632 $dao->entity_table
= $this->getTableName();
633 $dao->entity_id
= $this->id
;
634 $dao->modified_id
= $cid;
635 $dao->modified_date
= date("YmdHis");
640 * Given an associative array of name/value pairs, extract all the values
641 * that belong to this object and initialize the object with said values
643 * @param array $params
644 * (reference ) associative array of name/value pairs.
645 * @param bool $serializeArrays
646 * Should arrays that are passed in be serialised according to the metadata.
647 * Eventually this should be always true / gone, but in the interests of caution
648 * it is being grandfathered in. In general an array is not valid on the DAO
649 * but there may be instances where this function is called & then some handling
650 * takes place on the would-be array.
653 * Did we copy all null values into the object
655 public function copyValues(&$params, $serializeArrays = FALSE) {
656 $fields = $this->fields();
658 foreach ($fields as $name => $value) {
659 $dbName = $value['name'];
660 if (array_key_exists($dbName, $params)) {
661 $pValue = $params[$dbName];
664 elseif (array_key_exists($name, $params)) {
665 $pValue = $params[$name];
672 // if there is no value then make the variable NULL
674 if ($pValue === '') {
675 $this->$dbName = 'null';
677 elseif ($serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
678 $this->$dbName = CRM_Core_DAO
::serializeField($pValue, $value['serialize']);
682 if (!$serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
683 Civi
::log()->warning(ts('use copyParams to serialize arrays (' . __CLASS__
. '.' . $name . ')'), ['civi.tag' => 'deprecated']);
685 $maxLength = CRM_Utils_Array
::value('maxlength', $value);
686 if (!is_array($pValue) && $maxLength && mb_strlen($pValue) > $maxLength
687 && empty($value['pseudoconstant'])
689 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($pValue, 'String')]));
690 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
691 $pValue = CRM_Utils_String
::ellipsify($pValue, $maxLength);
693 $this->$dbName = $pValue;
702 * Store all the values from this object in an associative array
703 * this is a destructive store, calling function is responsible
704 * for keeping sanity of id's.
706 * @param object $object
707 * The object that we are extracting data from.
708 * @param array $values
709 * (reference ) associative array of name/value pairs.
711 public static function storeValues(&$object, &$values) {
712 $fields = $object->fields();
713 foreach ($fields as $name => $value) {
714 $dbName = $value['name'];
715 if (isset($object->$dbName) && $object->$dbName !== 'null') {
716 $values[$dbName] = $object->$dbName;
717 if ($name != $dbName) {
718 $values[$name] = $object->$dbName;
725 * Create an attribute for this specific field. We only do this for strings and text
727 * @param array $field
728 * The field under task.
731 * the attributes for the object
733 public static function makeAttribute($field) {
735 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
736 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
737 $size = CRM_Utils_Array
::value('size', $field);
738 if ($maxLength ||
$size) {
741 $attributes['maxlength'] = $maxLength;
744 $attributes['size'] = $size;
749 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
750 $rows = CRM_Utils_Array
::value('rows', $field);
754 $cols = CRM_Utils_Array
::value('cols', $field);
760 $attributes['rows'] = $rows;
761 $attributes['cols'] = $cols;
764 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
) {
765 $attributes['size'] = 6;
766 $attributes['maxlength'] = 14;
774 * Get the size and maxLength attributes for this text field.
775 * (or for all text fields) in the DAO object.
777 * @param string $class
779 * @param string $fieldName
780 * Field that i'm interested in or null if.
781 * you want the attributes for all DAO text fields
784 * assoc array of name => attribute pairs
786 public static function getAttribute($class, $fieldName = NULL) {
787 $object = new $class();
788 $fields = $object->fields();
789 if ($fieldName != NULL) {
790 $field = CRM_Utils_Array
::value($fieldName, $fields);
791 return self
::makeAttribute($field);
795 foreach ($fields as $name => $field) {
796 $attribute = self
::makeAttribute($field);
798 $attributes[$name] = $attribute;
802 if (!empty($attributes)) {
810 * Check if there is a record with the same name in the db.
812 * @param string $value
813 * The value of the field we are checking.
814 * @param string $daoName
815 * The dao object name.
816 * @param string $daoID
817 * The id of the object being updated. u can change your name.
818 * as long as there is no conflict
819 * @param string $fieldName
820 * The name of the field in the DAO.
822 * @param string $domainID
823 * The id of the domain. Object exists only for the given domain.
826 * true if object exists
828 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
829 $object = new $daoName();
830 $object->$fieldName = $value;
832 $object->domain_id
= $domainID;
835 if ($object->find(TRUE)) {
836 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
844 * Check if there is a given column in a specific table.
847 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
849 * @param string $tableName
850 * @param string $columnName
851 * @param bool $i18nRewrite
852 * Whether to rewrite the query on multilingual setups.
855 * true if exists, else false
857 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
858 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
862 * Scans all the tables using a slow query and table name.
866 public static function getTableNames() {
867 $dao = CRM_Core_DAO
::executeQuery(
869 FROM information_schema.TABLES
870 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
871 AND TABLE_NAME LIKE 'civicrm_%'
872 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
873 AND TABLE_NAME NOT LIKE '%_temp%'
876 while ($dao->fetch()) {
877 $values[] = $dao->TABLE_NAME
;
883 * @param int $maxTablesToCheck
887 public static function isDBMyISAM($maxTablesToCheck = 10) {
888 return CRM_Core_DAO
::singleValueQuery(
890 FROM information_schema.TABLES
891 WHERE ENGINE = 'MyISAM'
892 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
893 AND TABLE_NAME LIKE 'civicrm_%'
894 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
895 AND TABLE_NAME NOT LIKE '%_temp%'
896 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
901 * Get the name of the CiviCRM database.
905 public static function getDatabaseName() {
906 $daoObj = new CRM_Core_DAO();
907 return $daoObj->database();
911 * Checks if a constraint exists for a specified table.
913 * @param string $tableName
914 * @param string $constraint
917 * true if constraint exists, false otherwise
919 * @throws \CRM_Core_Exception
921 public static function checkConstraintExists($tableName, $constraint) {
924 if (!array_key_exists($tableName, $show)) {
925 $query = "SHOW CREATE TABLE $tableName";
926 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
928 if (!$dao->fetch()) {
929 throw new CRM_Core_Exception('query failed');
932 $show[$tableName] = $dao->Create_Table
;
935 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
939 * Checks if CONSTRAINT keyword exists for a specified table.
941 * @param array $tables
943 * @throws CRM_Core_Exception
946 * true if CONSTRAINT keyword exists, false otherwise
948 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
950 foreach ($tables as $tableName) {
951 if (!array_key_exists($tableName, $show)) {
952 $query = "SHOW CREATE TABLE $tableName";
953 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
955 if (!$dao->fetch()) {
956 throw new CRM_Core_Exception('Show create table failed.');
959 $show[$tableName] = $dao->Create_Table
;
962 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
963 if ($result == TRUE) {
974 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
975 * for a specified column of a table.
977 * @param string $tableName
978 * @param string $columnName
981 * true if in format, false otherwise
983 * @throws \CRM_Core_Exception
985 public static function checkFKConstraintInFormat($tableName, $columnName) {
988 if (!array_key_exists($tableName, $show)) {
989 $query = "SHOW CREATE TABLE $tableName";
990 $dao = CRM_Core_DAO
::executeQuery($query);
992 if (!$dao->fetch()) {
993 throw new CRM_Core_Exception('query failed');
996 $show[$tableName] = $dao->Create_Table
;
998 $constraint = "`FK_{$tableName}_{$columnName}`";
999 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
1000 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
1004 * Check whether a specific column in a specific table has always the same value.
1006 * @param string $tableName
1007 * @param string $columnName
1008 * @param string $columnValue
1011 * true if the value is always $columnValue, false otherwise
1013 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1014 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1015 $dao = CRM_Core_DAO
::executeQuery($query);
1016 $result = $dao->fetch() ?
FALSE : TRUE;
1021 * Check whether a specific column in a specific table is always NULL.
1023 * @param string $tableName
1024 * @param string $columnName
1027 * true if if the value is always NULL, false otherwise
1029 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1030 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1031 $dao = CRM_Core_DAO
::executeQuery($query);
1032 $result = $dao->fetch() ?
FALSE : TRUE;
1037 * Check if there is a given table in the database.
1039 * @param string $tableName
1042 * true if exists, else false
1044 public static function checkTableExists($tableName) {
1049 $params = [1 => [$tableName, 'String']];
1051 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1052 $result = $dao->fetch() ?
TRUE : FALSE;
1057 * Check if a given table has data.
1059 * @param string $tableName
1061 * TRUE if $tableName has at least one record.
1063 public static function checkTableHasData($tableName) {
1064 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1073 public function checkVersion($version) {
1078 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1079 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1083 * Find a DAO object for the given ID and return it.
1086 * Id of the DAO object being searched for.
1088 * @return CRM_Core_DAO
1089 * Object of the type of the class that called this function.
1093 public static function findById($id) {
1094 $object = new static();
1096 if (!$object->find(TRUE)) {
1097 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1103 * Returns all results as array-encoded records.
1107 public function fetchAll($k = FALSE, $v = FALSE, $method = FALSE) {
1109 while ($this->fetch()) {
1110 $result[] = $this->toArray();
1116 * Return the results as PHP generator.
1118 * @param string $type
1119 * Whether the generator yields 'dao' objects or 'array's.
1121 public function fetchGenerator($type = 'dao') {
1122 while ($this->fetch()) {
1129 yield
$this->toArray();
1133 throw new \
RuntimeException("Invalid record type ($type)");
1139 * Returns a singular value.
1141 * @return mixed|NULL
1143 public function fetchValue() {
1144 $result = $this->getDatabaseResult();
1145 $row = $result->fetchRow();
1155 * Get all the result records as mapping between columns.
1157 * @param string $keyColumn
1159 * @param string $valueColumn
1162 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1164 public function fetchMap($keyColumn, $valueColumn) {
1166 while ($this->fetch()) {
1167 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1173 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1175 * @param string $daoName
1176 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1177 * @param int $searchValue
1178 * Value of the column you want to search by.
1179 * @param string $returnColumn
1180 * Name of the column you want to GET the value of.
1181 * @param string $searchColumn
1182 * Name of the column you want to search by.
1183 * @param bool $force
1184 * Skip use of the cache.
1186 * @return string|null
1187 * Value of $returnColumn in the retrieved record
1189 * @throws \CRM_Core_Exception
1191 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1193 empty($searchValue) ||
1194 trim(strtolower($searchValue)) == 'null'
1196 // adding this here since developers forget to check for an id
1197 // or for the 'null' (which is a bad DAO kludge)
1198 // and hence we get the first value in the db
1199 throw new CRM_Core_Exception('getFieldValue failed');
1202 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1204 while (strpos($daoName, '_BAO_') !== FALSE) {
1205 $daoName = get_parent_class($daoName);
1209 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1210 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1212 $object = new $daoName();
1213 $object->$searchColumn = $searchValue;
1214 $object->selectAdd();
1215 $object->selectAdd($returnColumn);
1218 if ($object->find(TRUE)) {
1219 $result = $object->$returnColumn;
1222 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1224 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1228 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1230 * @param string $daoName
1231 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1232 * @param int $searchValue
1233 * Value of the column you want to search by.
1234 * @param string $setColumn
1235 * Name of the column you want to SET the value of.
1236 * @param string $setValue
1237 * SET the setColumn to this value.
1238 * @param string $searchColumn
1239 * Name of the column you want to search by.
1242 * true if we found and updated the object, else false
1244 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1245 $object = new $daoName();
1246 $object->selectAdd();
1247 $object->selectAdd("$searchColumn, $setColumn");
1248 $object->$searchColumn = $searchValue;
1250 if ($object->find(TRUE)) {
1251 $object->$setColumn = $setValue;
1252 if ($object->save()) {
1263 * @param array|object $sort either array or CRM_Utils_Sort
1264 * @param string $default
1265 * Default sort value.
1269 public static function getSortString($sort, $default = NULL) {
1270 // check if sort is of type CRM_Utils_Sort
1271 if (is_a($sort, 'CRM_Utils_Sort')) {
1272 return $sort->orderBy();
1277 // is it an array specified as $field => $sortDirection ?
1279 foreach ($sort as $k => $v) {
1280 $sortString .= "$k $v,";
1282 return rtrim($sortString, ',');
1288 * Fetch object based on array of properties.
1290 * @param string $daoName
1291 * Name of the dao object.
1292 * @param array $params
1293 * (reference ) an assoc array of name/value pairs.
1294 * @param array $defaults
1295 * (reference ) an assoc array to hold the flattened values.
1296 * @param array $returnProperities
1297 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1300 * an object of type referenced by daoName
1302 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1303 $object = new $daoName();
1304 $object->copyValues($params);
1306 // return only specific fields if returnproperties are sent
1307 if (!empty($returnProperities)) {
1308 $object->selectAdd();
1309 $object->selectAdd(implode(',', $returnProperities));
1312 if ($object->find(TRUE)) {
1313 self
::storeValues($object, $defaults);
1320 * Delete the object records that are associated with this contact.
1322 * @param string $daoName
1323 * Name of the dao object.
1324 * @param int $contactId
1325 * Id of the contact to delete.
1327 public static function deleteEntityContact($daoName, $contactId) {
1328 $object = new $daoName();
1330 $object->entity_table
= 'civicrm_contact';
1331 $object->entity_id
= $contactId;
1336 * Execute an unbuffered query.
1338 * This is a wrapper around new functionality exposed with CRM-17748.
1340 * @param string $query query to be executed
1342 * @param array $params
1343 * @param bool $abort
1344 * @param null $daoName
1345 * @param bool $freeDAO
1346 * @param bool $i18nRewrite
1347 * @param bool $trapException
1349 * @return CRM_Core_DAO
1350 * Object that points to an unbuffered result set
1352 public static function executeUnbufferedQuery(
1358 $i18nRewrite = TRUE,
1359 $trapException = FALSE
1362 return self
::executeQuery(
1370 ['result_buffering' => 0]
1377 * @param string $query
1378 * Query to be executed.
1380 * @param array $params
1381 * @param bool $abort
1382 * @param null $daoName
1383 * @param bool $freeDAO
1384 * @param bool $i18nRewrite
1385 * @param bool $trapException
1386 * @param array $options
1388 * @return CRM_Core_DAO|object
1389 * object that holds the results of the query
1390 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1391 * out all the properties that are not part of the DAO
1393 public static function &executeQuery(
1399 $i18nRewrite = TRUE,
1400 $trapException = FALSE,
1403 $queryStr = self
::composeQuery($query, $params, $abort);
1406 $dao = new CRM_Core_DAO();
1409 $dao = new $daoName();
1412 if ($trapException) {
1413 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1416 if ($dao->isValidOption($options)) {
1417 $dao->setOptions($options);
1420 $result = $dao->query($queryStr, $i18nRewrite);
1422 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1423 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1427 if (is_a($result, 'DB_Error')) {
1432 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1434 // we typically do this for insert/update/delete statements OR if explicitly asked to
1441 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1443 * @param array $options
1446 * Provided options are valid
1448 public function isValidOption($options) {
1457 if (empty($options)) {
1461 foreach (array_keys($options) as $option) {
1462 if (!in_array($option, $validOptions)) {
1472 * Execute a query and get the single result.
1474 * @param string $query
1475 * Query to be executed.
1476 * @param array $params
1477 * @param bool $abort
1478 * @param bool $i18nRewrite
1479 * @return string|null
1480 * the result of the query if any
1483 public static function &singleValueQuery(
1489 $queryStr = self
::composeQuery($query, $params, $abort);
1491 static $_dao = NULL;
1494 $_dao = new CRM_Core_DAO();
1497 $_dao->query($queryStr, $i18nRewrite);
1499 $result = $_dao->getDatabaseResult();
1502 $row = $result->fetchRow();
1512 * Compose the query by merging the parameters into it.
1514 * @param string $query
1515 * @param array $params
1516 * @param bool $abort
1519 * @throws CRM_Core_Exception
1521 public static function composeQuery($query, $params = [], $abort = TRUE) {
1523 foreach ($params as $key => $item) {
1524 if (is_numeric($key)) {
1525 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1526 $item[0] = self
::escapeString($item[0]);
1527 if ($item[1] == 'String' ||
1528 $item[1] == 'Memo' ||
1531 // Support class constants stipulating wildcard characters and/or
1532 // non-quoting of strings. Also support legacy code which may be
1533 // passing in TRUE or 1 for $item[2], which used to indicate the
1534 // use of wildcard characters.
1535 if (!empty($item[2])) {
1536 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1537 $item[0] = "'%{$item[0]}%'";
1539 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1540 $item[0] = "'{$item[0]}'";
1544 $item[0] = "'{$item[0]}'";
1548 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1549 strlen($item[0]) == 0
1554 $tr['%' . $key] = $item[0];
1557 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1562 return strtr($query, $tr);
1568 public static function freeResult($ids = NULL) {
1569 global $_DB_DATAOBJECT;
1572 if (!$_DB_DATAOBJECT ||
1573 !isset($_DB_DATAOBJECT['RESULTS'])
1577 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1580 foreach ($ids as $id) {
1581 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1582 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1583 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1586 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1587 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1593 * Make a shallow copy of an object and all the fields in the object.
1595 * @param string $daoName
1597 * @param array $criteria
1598 * Array of all the fields & values.
1599 * on which basis to copy
1600 * @param array $newData
1601 * Array of all the fields & values.
1602 * to be copied besides the other fields
1603 * @param string $fieldsFix
1604 * Array of fields that you want to prefix/suffix/replace.
1605 * @param string $blockCopyOfDependencies
1606 * Fields that you want to block from.
1608 * @param bool $blockCopyofCustomValues
1609 * Case when you don't want to copy the custom values set in a
1610 * template as it will override/ignore the submitted custom values
1612 * @return CRM_Core_DAO|bool
1613 * the newly created copy of the object. False if none created.
1615 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1616 $object = new $daoName();
1619 $object->id
= $criteria['id'];
1622 foreach ($criteria as $key => $value) {
1623 $object->$key = $value;
1628 while ($object->fetch()) {
1630 // all the objects except with $blockCopyOfDependencies set
1631 // be copied - addresses #CRM-1962
1633 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1637 $newObject = new $daoName();
1639 $fields = $object->fields();
1640 if (!is_array($fieldsFix)) {
1641 $fieldsToPrefix = [];
1642 $fieldsToSuffix = [];
1643 $fieldsToReplace = [];
1645 if (!empty($fieldsFix['prefix'])) {
1646 $fieldsToPrefix = $fieldsFix['prefix'];
1648 if (!empty($fieldsFix['suffix'])) {
1649 $fieldsToSuffix = $fieldsFix['suffix'];
1651 if (!empty($fieldsFix['replace'])) {
1652 $fieldsToReplace = $fieldsFix['replace'];
1655 foreach ($fields as $name => $value) {
1656 if ($name == 'id' ||
$value['name'] == 'id') {
1657 // copy everything but the id!
1661 $dbName = $value['name'];
1662 $type = CRM_Utils_Type
::typeToString($value['type']);
1663 $newObject->$dbName = $object->$dbName;
1664 if (isset($fieldsToPrefix[$dbName])) {
1665 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1667 if (isset($fieldsToSuffix[$dbName])) {
1668 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1670 if (isset($fieldsToReplace[$dbName])) {
1671 $newObject->$dbName = $fieldsToReplace[$dbName];
1674 if ($type == 'Timestamp' ||
$type == 'Date') {
1675 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1679 $newObject->copyValues($newData);
1683 if (!$blockCopyofCustomValues) {
1684 $newObject->copyCustomFields($object->id
, $newObject->id
);
1686 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $daoName)), $newObject->id
, $newObject);
1693 * Method that copies custom fields values from an old entity to a new one.
1695 * Fixes bug CRM-19302,
1696 * where if a custom field of File type was present, left both events using the same file,
1697 * breaking download URL's for the old event.
1699 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1700 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1702 * @param int $entityID
1703 * @param int $newEntityID
1705 public function copyCustomFields($entityID, $newEntityID) {
1706 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1707 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1708 // Obtain custom values for old event
1709 $customParams = $htmlType = [];
1710 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1712 // If custom values present, we copy them
1713 if (!empty($customValues)) {
1714 // Get Field ID's and identify File type attributes, to handle file copying.
1715 $fieldIds = implode(', ', array_keys($customValues));
1716 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1717 $result = CRM_Core_DAO
::executeQuery($sql);
1719 // Build array of File type fields
1720 while ($result->fetch()) {
1721 $htmlType[] = $result->id
;
1724 // Build params array of custom values
1725 foreach ($customValues as $field => $value) {
1726 if ($value !== NULL) {
1727 // Handle File type attributes
1728 if (in_array($field, $htmlType)) {
1729 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1730 $customParams["custom_{$field}_-1"] = [
1731 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1732 'type' => $fileValues[1],
1735 // Handle other types
1737 $customParams["custom_{$field}_-1"] = $value;
1742 // Save Custom Fields for new Event
1743 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1746 // copy activity attachments ( if any )
1747 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1751 * Cascade update through related entities.
1753 * @param string $daoName
1756 * @param array $newData
1758 * @return CRM_Core_DAO|null
1760 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1761 $object = new $daoName();
1762 $object->id
= $fromId;
1764 if ($object->find(TRUE)) {
1765 $newObject = new $daoName();
1766 $newObject->id
= $toId;
1768 if ($newObject->find(TRUE)) {
1769 $fields = $object->fields();
1770 foreach ($fields as $name => $value) {
1771 if ($name == 'id' ||
$value['name'] == 'id') {
1772 // copy everything but the id!
1776 $colName = $value['name'];
1777 $newObject->$colName = $object->$colName;
1779 if (substr($name, -5) == '_date' ||
1780 substr($name, -10) == '_date_time'
1782 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1785 foreach ($newData as $k => $v) {
1786 $newObject->$k = $v;
1796 * Given the component id, compute the contact id
1797 * since its used for things like send email
1799 * @param $componentIDs
1800 * @param string $tableName
1801 * @param string $idField
1805 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1808 if (empty($componentIDs)) {
1812 $IDs = implode(',', $componentIDs);
1816 WHERE $idField IN ( $IDs )
1819 $dao = CRM_Core_DAO
::executeQuery($query);
1820 while ($dao->fetch()) {
1821 $contactIDs[] = $dao->contact_id
;
1827 * Fetch object based on array of properties.
1829 * @param string $daoName
1830 * Name of the dao object.
1831 * @param string $fieldIdName
1832 * @param int $fieldId
1834 * @param array $returnProperities
1835 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1838 * an object of type referenced by daoName
1840 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1841 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1842 $object = new $daoName();
1843 $object->$fieldIdName = $fieldId;
1845 // return only specific fields if returnproperties are sent
1846 if (!empty($returnProperities)) {
1847 $object->selectAdd();
1848 $object->selectAdd('id');
1849 $object->selectAdd(implode(',', $returnProperities));
1853 while ($object->fetch()) {
1855 self
::storeValues($object, $defaults);
1856 $details[$object->id
] = $defaults;
1863 * Drop all CiviCRM tables.
1865 * @throws \CRM_Core_Exception
1867 public static function dropAllTables() {
1869 // first drop all the custom tables we've created
1870 CRM_Core_BAO_CustomGroup
::dropAllTables();
1872 // drop all multilingual views
1873 CRM_Core_I18n_Schema
::dropAllViews();
1875 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1876 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1877 '..' . DIRECTORY_SEPARATOR
.
1878 '..' . DIRECTORY_SEPARATOR
.
1879 'sql' . DIRECTORY_SEPARATOR
.
1880 'civicrm_drop.mysql'
1889 public static function escapeString($string) {
1890 static $_dao = NULL;
1892 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1893 // has been installed), then we fallback DB-less str_replace escaping, as
1894 // we can't use mysqli_real_escape_string, as there is no DB connection.
1895 // Note: In typical usage, escapeString() will only check one conditional
1896 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1897 if (!defined('CIVICRM_DSN')) {
1898 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1899 // list of characters mysqli_real_escape_string escapes.
1900 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
1901 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
1902 return str_replace($search, $replace, $string);
1904 $_dao = new CRM_Core_DAO();
1906 return $_dao->escape($string);
1910 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1912 * @param array $strings
1913 * @param string $default
1914 * the value to use if $strings has no elements.
1916 * eg "abc","def","ghi"
1918 public static function escapeStrings($strings, $default = NULL) {
1919 static $_dao = NULL;
1921 $_dao = new CRM_Core_DAO();
1924 if (empty($strings)) {
1928 $escapes = array_map([$_dao, 'escape'], $strings);
1929 return '"' . implode('","', $escapes) . '"';
1937 public static function escapeWildCardString($string) {
1939 // ensure we escape the single characters % and _ which are mysql wild
1940 // card characters and could come in via sortByCharacter
1941 // note that mysql does not escape these characters
1942 if ($string && in_array($string,
1943 ['%', '_', '%%', '_%']
1946 return '\\' . $string;
1949 return self
::escapeString($string);
1953 * Creates a test object, including any required objects it needs via recursion
1954 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1955 * ONLY USE FOR TESTING
1957 * @param string $daoName
1958 * @param array $params
1959 * @param int $numObjects
1960 * @param bool $createOnly
1962 * @return object|array|NULL
1963 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1965 public static function createTestObject(
1971 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1972 // so we re-set here in case
1973 $config = CRM_Core_Config
::singleton();
1974 $config->backtrace
= TRUE;
1976 static $counter = 0;
1977 CRM_Core_DAO
::$_testEntitiesToSkip = [
1978 'CRM_Core_DAO_Worldregion',
1979 'CRM_Core_DAO_StateProvince',
1980 'CRM_Core_DAO_Country',
1981 'CRM_Core_DAO_Domain',
1982 'CRM_Financial_DAO_FinancialType',
1983 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1986 // Prefer to instantiate BAO's instead of DAO's (when possible)
1987 // so that assignTestValue()/assignTestFK() can be overloaded.
1988 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1989 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
1990 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
1991 // @todo create a new class called what the BAO SHOULD be
1992 // that extends BAO-crazy-name.... migrate.
1993 $baoName = 'CRM_Core_BAO_FinancialTrxn';
1995 if (class_exists($baoName)) {
1996 $daoName = $baoName;
1999 for ($i = 0; $i < $numObjects; ++
$i) {
2002 /** @var CRM_Core_DAO $object */
2003 $object = new $daoName();
2005 $fields = $object->fields();
2006 foreach ($fields as $fieldName => $fieldDef) {
2007 $dbName = $fieldDef['name'];
2008 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
2009 $required = CRM_Utils_Array
::value('required', $fieldDef);
2011 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
2012 $object->$dbName = $params[$dbName];
2015 elseif ($dbName != 'id') {
2016 if ($FKClassName != NULL) {
2017 $object->assignTestFK($fieldName, $fieldDef, $params);
2021 $object->assignTestValue($fieldName, $fieldDef, $counter);
2029 $objects[$i] = $object;
2039 elseif ($numObjects == 1) {
2048 * Deletes the this object plus any dependent objects that are associated with it.
2049 * ONLY USE FOR TESTING
2051 * @param string $daoName
2052 * @param array $params
2054 public static function deleteTestObjects($daoName, $params = []) {
2055 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2056 // so we re-set here in case
2057 $config = CRM_Core_Config
::singleton();
2058 $config->backtrace
= TRUE;
2060 $object = new $daoName();
2061 $object->id
= CRM_Utils_Array
::value('id', $params);
2063 // array(array(0 => $daoName, 1 => $daoParams))
2065 if ($object->find(TRUE)) {
2067 $fields = $object->fields();
2068 foreach ($fields as $name => $value) {
2070 $dbName = $value['name'];
2072 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
2073 $required = CRM_Utils_Array
::value('required', $value);
2074 if ($FKClassName != NULL
2076 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2077 && ($required ||
$dbName == 'contact_id')
2078 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2079 // to make this test process pass - line below makes pass for now
2080 && $dbName != 'member_of_contact_id'
2083 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2090 foreach ($deletions as $deletion) {
2091 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2096 * Set defaults when creating new entity.
2097 * (don't call this set defaults as already in use with different signature in some places)
2099 * @param array $params
2102 public static function setCreateDefaults(&$params, $defaults) {
2103 if (!empty($params['id'])) {
2106 foreach ($defaults as $key => $value) {
2107 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2108 $params[$key] = $value;
2114 * @param string $prefix
2115 * @param bool $addRandomString
2116 * @param null $string
2120 * @see CRM_Utils_SQL_TempTable
2122 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2123 CRM_Core_Error
::deprecatedFunctionWarning('Use CRM_Utils_SQL_TempTable interface to create temporary tables');
2124 $tableName = $prefix . "_temp";
2126 if ($addRandomString) {
2128 $tableName .= "_" . $string;
2131 $tableName .= "_" . md5(uniqid('', TRUE));
2139 * @param bool $trigger
2143 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2144 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2147 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2149 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2150 CRM_Core_TemporaryErrorScope
::ignoreException();
2151 $dao = new CRM_Core_DAO();
2153 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2154 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2160 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2161 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2163 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2168 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2169 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2171 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2178 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2179 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2188 * @param null $message
2189 * @param bool $printDAO
2191 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2192 CRM_Utils_System
::xMemory("{$message}: ");
2195 global $_DB_DATAOBJECT;
2197 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2198 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2200 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2205 * Build a list of triggers via hook and add them to (err, reconcile them
2206 * with) the database.
2208 * @param string $tableName
2209 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2210 * @param bool $force
2215 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2216 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2220 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2221 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2222 * TODO: Alternative solutions might be
2223 * * Stop using functions and find another way to strip numeric characters from phones
2224 * * Give better error messages (currently a missing fn fatals with "unknown error")
2226 public static function checkSqlFunctionsExist() {
2227 if (!self
::$_checkedSqlFunctionsExist) {
2228 self
::$_checkedSqlFunctionsExist = TRUE;
2229 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2230 if (!$dao->fetch()) {
2231 self
::triggerRebuild();
2237 * Wrapper function to drop triggers.
2239 * @param string $tableName
2240 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2243 public static function dropTriggers($tableName = NULL) {
2244 Civi
::service('sql_triggers')->dropTriggers($tableName);
2248 * @param array $info
2249 * per hook_civicrm_triggerInfo.
2250 * @param string $onlyTableName
2251 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2254 public static function createTriggers(&$info, $onlyTableName = NULL) {
2255 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2259 * Given a list of fields, create a list of references.
2261 * @param string $className
2262 * BAO/DAO class name.
2263 * @return array<CRM_Core_Reference_Interface>
2265 public static function createReferenceColumns($className) {
2267 $fields = $className::fields();
2268 foreach ($fields as $field) {
2269 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2270 $result[] = new CRM_Core_Reference_OptionValue(
2271 $className::getTableName(),
2273 'civicrm_option_value',
2274 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2275 $field['pseudoconstant']['optionGroupName']
2283 * Find all records which refer to this entity.
2286 * Array of objects referencing this
2288 public function findReferences() {
2289 $links = self
::getReferencesToTable(static::getTableName());
2292 foreach ($links as $refSpec) {
2293 /** @var $refSpec CRM_Core_Reference_Interface */
2294 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2295 $result = $refSpec->findReferences($this);
2297 while ($result->fetch()) {
2298 $obj = new $daoName();
2299 $obj->id
= $result->id
;
2300 $occurrences[] = $obj;
2305 return $occurrences;
2310 * each item has keys:
2314 * - table: string|null SQL table name
2315 * - key: string|null SQL column name
2317 public function getReferenceCounts() {
2318 $links = self
::getReferencesToTable(static::getTableName());
2321 foreach ($links as $refSpec) {
2322 /** @var $refSpec CRM_Core_Reference_Interface */
2323 $count = $refSpec->getReferenceCount($this);
2324 if ($count['count'] != 0) {
2329 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2330 /** @var $component CRM_Core_Component_Info */
2331 $counts = array_merge($counts, $component->getReferenceCounts($this));
2333 CRM_Utils_Hook
::referenceCounts($this, $counts);
2339 * List all tables which have hard foreign keys to this table.
2341 * For now, this returns a description of every entity_id/entity_table
2343 * TODO: filter dynamic entity references on the $tableName, based on
2344 * schema metadata in dynamicForeignKey which enumerates a restricted
2345 * set of possible entity_table's.
2347 * @param string $tableName
2348 * Table referred to.
2351 * structure of table and column, listing every table with a
2352 * foreign key reference to $tableName, and the column where the key appears.
2354 public static function getReferencesToTable($tableName) {
2356 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2357 $links = $daoClassName::getReferenceColumns();
2358 $daoTableName = $daoClassName::getTableName();
2360 foreach ($links as $refSpec) {
2361 /** @var $refSpec CRM_Core_Reference_Interface */
2362 if ($refSpec->matchesTargetTable($tableName)) {
2363 $refsFound[] = $refSpec;
2371 * Get all references to contact table.
2373 * This includes core tables, custom group tables, tables added by the merge
2374 * hook and the entity_tag table.
2376 * Refer to CRM-17454 for information on the danger of querying the information
2377 * schema to derive this.
2379 public static function getReferencesToContactTable() {
2380 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2381 return \Civi
::$statics[__CLASS__
]['contact_references'];
2383 $contactReferences = [];
2384 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2385 foreach ($coreReferences as $coreReference) {
2386 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2387 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2390 self
::appendCustomTablesExtendingContacts($contactReferences);
2391 self
::appendCustomContactReferenceFields($contactReferences);
2393 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
2394 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
2395 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2396 return \Civi
::$statics[__CLASS__
]['contact_references'];
2400 * Add custom tables that extend contacts to the list of contact references.
2402 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2403 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2404 * - the down side is it is not cached.
2406 * Further changes should be include tests in the CRM_Core_MergerTest class
2407 * to ensure that disabled, subtype, multiple etc groups are still captured.
2409 * @param array $cidRefs
2411 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2412 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2413 $customValueTables->find();
2414 while ($customValueTables->fetch()) {
2415 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2420 * Add custom ContactReference fields to the list of contact references
2422 * This includes active and inactive fields/groups
2424 * @param array $cidRefs
2426 * @throws \CiviCRM_API3_Exception
2428 public static function appendCustomContactReferenceFields(&$cidRefs) {
2429 $fields = civicrm_api3('CustomField', 'get', [
2430 'return' => ['column_name', 'custom_group_id.table_name'],
2431 'data_type' => 'ContactReference',
2433 foreach ($fields as $field) {
2434 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2439 * Lookup the value of a MySQL global configuration variable.
2441 * @param string $name
2442 * E.g. "thread_stack".
2443 * @param mixed $default
2446 public static function getGlobalSetting($name, $default = NULL) {
2447 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2448 // that has been reported to fail under MySQL 5.0 for OS X
2449 $escapedName = self
::escapeString($name);
2450 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2451 if ($dao->fetch()) {
2460 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2462 * This is relevant where we want to offer both the ID field and the label field
2463 * as an option, e.g. search builder.
2465 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2466 * change small, but is appropriate for other sorts of pseudoconstants.
2468 * @param array $fields
2470 public static function appendPseudoConstantsToFields(&$fields) {
2471 foreach ($fields as $fieldUniqueName => $field) {
2472 if (!empty($field['pseudoconstant'])) {
2473 $pseudoConstant = $field['pseudoconstant'];
2474 if (!empty($pseudoConstant['optionGroupName'])) {
2475 $fields[$pseudoConstant['optionGroupName']] = [
2476 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2477 'name' => $pseudoConstant['optionGroupName'],
2478 'data_type' => CRM_Utils_Type
::T_STRING
,
2479 'is_pseudofield_for' => $fieldUniqueName,
2482 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2484 !empty($field['FKClassName'])
2485 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2486 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2488 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2489 // This if is just an extra caution when adding change.
2490 if (!isset($fields[$pseudoFieldName])) {
2491 $daoName = $field['FKClassName'];
2492 $fkFields = $daoName::fields();
2493 foreach ($fkFields as $fkField) {
2494 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2495 $fields[$pseudoFieldName] = [
2496 'name' => $pseudoFieldName,
2497 'is_pseudofield_for' => $field['name'],
2498 'title' => $fkField['title'],
2499 'data_type' => $fkField['type'],
2500 'where' => $field['where'],
2511 * Get options for the called BAO object's field.
2513 * This function can be overridden by each BAO to add more logic related to context.
2514 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2516 * @param string $fieldName
2517 * @param string $context
2518 * @see CRM_Core_DAO::buildOptionsContext
2519 * @param array $props
2520 * whatever is known about this bao object.
2522 * @return array|bool
2524 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2525 // If a given bao does not override this function
2526 $baoName = get_called_class();
2527 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2531 * Populate option labels for this object's fields.
2533 * @throws exception if called directly on the base class
2535 public function getOptionLabels() {
2536 $fields = $this->fields();
2537 if ($fields === NULL) {
2538 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2540 foreach ($fields as $field) {
2541 $name = CRM_Utils_Array
::value('name', $field);
2542 if ($name && isset($this->$name)) {
2543 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2544 if ($label !== FALSE) {
2545 // Append 'label' onto the field name
2546 $labelName = $name . '_label';
2547 $this->$labelName = $label;
2554 * Provides documentation and validation for the buildOptions $context param
2556 * @param string $context
2561 public static function buildOptionsContext($context = NULL) {
2563 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2564 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2565 'search' => "search: searchable options are returned; labels are translated.",
2566 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2567 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2568 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2570 // Validation: enforce uniformity of this param
2571 if ($context !== NULL && !isset($contexts[$context])) {
2572 throw new Exception("'$context' is not a valid context for buildOptions.");
2578 * @param string $fieldName
2579 * @return bool|array
2581 public function getFieldSpec($fieldName) {
2582 $fields = $this->fields();
2583 $fieldKeys = $this->fieldKeys();
2585 // Support "unique names" as well as sql names
2586 $fieldKey = $fieldName;
2587 if (empty($fields[$fieldKey])) {
2588 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2590 // If neither worked then this field doesn't exist. Return false.
2591 if (empty($fields[$fieldKey])) {
2594 return $fields[$fieldKey];
2598 * Get SQL where clause for SQL filter syntax input parameters.
2600 * SQL version of api function to assign filters to the DAO based on the syntax
2601 * $field => array('IN' => array(4,6,9))
2603 * $field => array('LIKE' => array('%me%))
2606 * @param string $fieldName
2608 * @param array $filter
2609 * filter to be applied indexed by operator.
2610 * @param string $type
2611 * type of field (not actually used - nor in api @todo ).
2612 * @param string $alias
2613 * alternative field name ('as') @todo- not actually used.
2614 * @param bool $returnSanitisedArray
2615 * Return a sanitised array instead of a clause.
2616 * this is primarily so we can add filters @ the api level to the Query object based fields
2620 * @return NULL|string|array
2621 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2622 * depending on whether it is supported as yet
2624 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2625 foreach ($filter as $operator => $criteria) {
2626 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2627 switch ($operator) {
2631 if (!$returnSanitisedArray) {
2632 return (sprintf('%s %s', $fieldName, $operator));
2635 return (sprintf('%s %s ', $fieldName, $operator));
2639 // ternary operators
2642 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2643 throw new Exception("invalid criteria for $operator");
2645 if (!$returnSanitisedArray) {
2646 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2649 // not yet implemented (tests required to implement)
2657 if (empty($criteria)) {
2658 throw new Exception("invalid criteria for $operator");
2660 $escapedCriteria = array_map([
2664 if (!$returnSanitisedArray) {
2665 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2667 return $escapedCriteria;
2672 if (!$returnSanitisedArray) {
2673 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2676 // not yet implemented (tests required to implement)
2685 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2686 * support for other syntaxes is discussed in ticket but being put off for now
2689 public static function acceptedSQLOperators() {
2710 * SQL has a limit of 64 characters on various names:
2711 * table name, trigger name, column name ...
2713 * For custom groups and fields we generated names from user entered input
2714 * which can be longer than this length, this function helps with creating
2715 * strings that meet various criteria.
2717 * @param string $string
2718 * The string to be shortened.
2719 * @param int $length
2720 * The max length of the string.
2722 * @param bool $makeRandom
2726 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2727 // early return for strings that meet the requirements
2728 if (strlen($string) <= $length) {
2732 // easy return for calls that dont need a randomized uniq string
2734 return substr($string, 0, $length);
2737 // the string is longer than the length and we need a uniq string
2738 // for the same tablename we need the same uniq string every time
2739 // hence we use md5 on the string, which is not random
2740 // we'll append 8 characters to the end of the tableName
2741 $md5string = substr(md5($string), 0, 8);
2742 return substr($string, 0, $length - 8) . "_{$md5string}";
2746 * https://issues.civicrm.org/jira/browse/CRM-17748
2747 * Sets the internal options to be used on a query
2749 * @param array $options
2752 public function setOptions($options) {
2753 if (is_array($options)) {
2754 $this->_options
= $options;
2759 * https://issues.civicrm.org/jira/browse/CRM-17748
2760 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2762 * @param array $options
2765 protected function _setDBOptions($options) {
2766 global $_DB_DATAOBJECT;
2768 if (is_array($options) && count($options)) {
2769 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2770 foreach ($options as $option_name => $option_value) {
2771 $conn->setOption($option_name, $option_value);
2778 * @param array $params
2780 public function setApiFilter(&$params) {
2784 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2786 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2789 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2793 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2797 public function addSelectWhereClause() {
2799 $fields = $this->fields();
2800 foreach ($fields as $fieldName => $field) {
2801 // Clause for contact-related entities like Email, Relationship, etc.
2802 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2803 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2805 // Clause for an entity_table/entity_id combo
2806 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2807 $relatedClauses = [];
2808 $relatedEntities = $this->buildOptions('entity_table', 'get');
2809 foreach ((array) $relatedEntities as $table => $ent) {
2811 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2812 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2814 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2817 $relatedClauses[] = "(entity_table = '$table')";
2821 if ($relatedClauses) {
2822 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2826 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2831 * This returns the final permissioned query string for this entity
2833 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2835 * @param string $tableAlias
2838 public static function getSelectWhereClause($tableAlias = NULL) {
2839 $bao = new static();
2840 if ($tableAlias === NULL) {
2841 $tableAlias = $bao->tableName();
2844 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2845 $clauses[$field] = NULL;
2847 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2854 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2855 * and dashes, and contains at least one [a-z] case insenstive.
2861 public static function requireSafeDBName($database) {
2864 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2868 if (empty($matches)) {
2875 * Transform an array to a serialized string for database storage.
2877 * @param array|null $value
2878 * @param int $serializationType
2879 * @return string|null
2881 * @throws \Exception
2883 public static function serializeField($value, $serializationType) {
2884 if ($value === NULL) {
2887 switch ($serializationType) {
2888 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2889 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
2891 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2892 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2894 case self
::SERIALIZE_JSON
:
2895 return is_array($value) ?
json_encode($value) : $value;
2897 case self
::SERIALIZE_PHP
:
2898 return is_array($value) ?
serialize($value) : $value;
2900 case self
::SERIALIZE_COMMA
:
2901 return is_array($value) ?
implode(',', $value) : $value;
2904 throw new Exception('Unknown serialization method for field.');
2909 * Transform a serialized string from the database into an array.
2911 * @param string|null $value
2912 * @param $serializationType
2914 * @return array|null
2915 * @throws CRM_Core_Exception
2917 public static function unSerializeField($value, $serializationType) {
2918 if ($value === NULL) {
2921 if ($value === '') {
2924 switch ($serializationType) {
2925 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2926 return (array) CRM_Utils_Array
::explodePadded($value);
2928 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2929 return explode(self
::VALUE_SEPARATOR
, trim($value));
2931 case self
::SERIALIZE_JSON
:
2932 return strlen($value) ?
json_decode($value, TRUE) : [];
2934 case self
::SERIALIZE_PHP
:
2935 return strlen($value) ? CRM_Utils_String
::unserialize($value) : [];
2937 case self
::SERIALIZE_COMMA
:
2938 return explode(',', trim(str_replace(', ', '', $value)));
2941 throw new CRM_Core_Exception('Unknown serialization method for field.');
2948 public static function getEntityRefFilters() {
2953 * Get exportable fields with pseudoconstants rendered as an extra field.
2955 * @param string $baoClass
2959 public static function getExportableFieldsWithPseudoConstants($baoClass) {
2960 if (method_exists($baoClass, 'exportableFields')) {
2961 $fields = $baoClass::exportableFields();
2964 $fields = $baoClass::export();
2966 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
2971 * Remove item from static cache during update/delete operations
2973 private function clearDbColumnValueCache() {
2974 $daoName = get_class($this);
2975 while (strpos($daoName, '_BAO_') !== FALSE) {
2976 $daoName = get_parent_class($daoName);
2978 if (isset($this->id
)) {
2979 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
2981 if (isset($this->name
)) {
2982 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);