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 if (defined('CIVICRM_DAO_DEBUG')) {
148 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
150 $factory = new CRM_Contact_DAO_Factory();
151 CRM_Core_DAO
::setFactory($factory);
152 $currentModes = CRM_Utils_SQL
::getSqlModes();
153 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
154 if (CRM_Utils_SQL
::supportsFullGroupBy() && !in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
155 $currentModes[] = 'ONLY_FULL_GROUP_BY';
157 if (!in_array('STRICT_TRANS_TABLES', $currentModes)) {
158 $currentModes = array_merge(['STRICT_TRANS_TABLES'], $currentModes);
160 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
162 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
163 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', [1 => [CRM_Utils_Request
::id(), 'String']]);
169 public static function getConnection() {
170 global $_DB_DATAOBJECT;
171 $dao = new CRM_Core_DAO();
172 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
176 * Disables usage of the ONLY_FULL_GROUP_BY Mode if necessary
178 public static function disableFullGroupByMode() {
179 $currentModes = CRM_Utils_SQL
::getSqlModes();
180 if (in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
181 $key = array_search('ONLY_FULL_GROUP_BY', $currentModes);
182 unset($currentModes[$key]);
183 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
188 * Re-enables ONLY_FULL_GROUP_BY sql_mode as necessary..
190 public static function reenableFullGroupByMode() {
191 $currentModes = CRM_Utils_SQL
::getSqlModes();
192 if (!in_array('ONLY_FULL_GROUP_BY', $currentModes) && CRM_Utils_SQL
::isGroupByModeInDefault()) {
193 $currentModes[] = 'ONLY_FULL_GROUP_BY';
194 CRM_Core_DAO
::executeQuery("SET SESSION sql_mode = %1", [1 => [implode(',', $currentModes), 'String']]);
199 * @param string $fieldName
201 * @param array $params
203 protected function assignTestFK($fieldName, $fieldDef, $params) {
204 $required = CRM_Utils_Array
::value('required', $fieldDef);
205 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
206 $dbName = $fieldDef['name'];
207 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
209 // skip the FK if it is not required
210 // if it's contact id we should create even if not required
211 // we'll have a go @ fetching first though
212 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
213 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
216 if (!$required && $dbName != 'contact_id') {
217 $fkDAO = new $FKClassName();
218 if ($fkDAO->find(TRUE)) {
219 $this->$dbName = $fkDAO->id
;
223 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
224 $depObject = new $FKClassName();
225 $depObject->find(TRUE);
226 $this->$dbName = $depObject->id
;
228 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
229 // FIXME: the fields() metadata is not specific enough
230 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, ['contact_type' => 'Organization']);
231 $this->$dbName = $depObject->id
;
234 //if it is required we need to generate the dependency object first
235 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
236 $this->$dbName = $depObject->id
;
241 * Generate and assign an arbitrary value to a field of a test object.
243 * @param string $fieldName
244 * @param array $fieldDef
245 * @param int $counter
246 * The globally-unique ID of the test object.
248 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
249 $dbName = $fieldDef['name'];
250 $daoName = get_class($this);
253 if (!$handled && $dbName == 'contact_sub_type') {
254 //coming up with a rule to set this is too complex let's not set it
258 // Pick an option value if needed
259 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
260 $options = $daoName::buildOptions($dbName, 'create');
262 $this->$dbName = key($options);
268 switch ($fieldDef['type']) {
269 case CRM_Utils_Type
::T_INT
:
270 case CRM_Utils_Type
::T_FLOAT
:
271 case CRM_Utils_Type
::T_MONEY
:
272 if (isset($fieldDef['precision'])) {
273 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
274 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
277 $this->$dbName = $counter;
281 case CRM_Utils_Type
::T_BOOLEAN
:
282 if (isset($fieldDef['default'])) {
283 $this->$dbName = $fieldDef['default'];
285 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
293 case CRM_Utils_Type
::T_DATE
:
294 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
295 $this->$dbName = '19700101';
296 if ($dbName == 'end_date') {
297 // put this in the future
298 $this->$dbName = '20200101';
302 case CRM_Utils_Type
::T_TIMESTAMP
:
303 $this->$dbName = '19700201000000';
306 case CRM_Utils_Type
::T_TIME
:
307 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
308 //$object->$dbName='000000';
310 case CRM_Utils_Type
::T_CCNUM
:
311 $this->$dbName = '4111 1111 1111 1111';
314 case CRM_Utils_Type
::T_URL
:
315 $this->$dbName = 'http://www.civicrm.org';
318 case CRM_Utils_Type
::T_STRING
:
319 case CRM_Utils_Type
::T_BLOB
:
320 case CRM_Utils_Type
::T_MEDIUMBLOB
:
321 case CRM_Utils_Type
::T_TEXT
:
322 case CRM_Utils_Type
::T_LONGTEXT
:
323 case CRM_Utils_Type
::T_EMAIL
:
325 // WAS: if (isset($value['enumValues'])) {
326 // TODO: see if this works with all pseudoconstants
327 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
328 if (isset($fieldDef['default'])) {
329 $this->$dbName = $fieldDef['default'];
332 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
333 if (is_array($options)) {
334 $this->$dbName = $options[0];
337 $defaultValues = explode(',', $options);
338 $this->$dbName = $defaultValues[0];
343 $this->$dbName = $dbName . '_' . $counter;
344 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
345 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
346 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
354 * Reset the DAO object.
356 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
358 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
360 public function reset() {
362 foreach (array_keys($this->table()) as $field) {
363 unset($this->$field);
367 * reset the various DB_DAO structures manually
376 * @param string $tableName
380 public static function getLocaleTableName($tableName) {
383 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
384 if (in_array($tableName, $tables)) {
385 return $tableName . $dbLocale;
392 * Execute a query by the current DAO, localizing it along the way (if needed).
394 * @param string $query
395 * The SQL query for execution.
396 * @param bool $i18nRewrite
397 * Whether to rewrite the query.
400 * the current DAO object after the query execution
402 public function query($query, $i18nRewrite = TRUE) {
403 // rewrite queries that should use $dbLocale-based views for multi-language installs
404 global $dbLocale, $_DB_DATAOBJECT;
406 if (empty($_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
])) {
407 // Will force connection to be populated per CRM-20541.
411 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
412 $orig_options = $conn->options
;
413 $this->_setDBOptions($this->_options
);
415 if ($i18nRewrite and $dbLocale) {
416 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
419 $ret = parent
::query($query);
421 $this->_setDBOptions($orig_options);
426 * Static function to set the factory instance for this class.
428 * @param object $factory
429 * The factory application object.
431 public static function setFactory(&$factory) {
432 self
::$_factory = &$factory;
436 * Factory method to instantiate a new object from a table name.
438 * @param string $table
439 * @return \DataObject|\PEAR_Error
441 public function factory($table = '') {
442 if (!isset(self
::$_factory)) {
443 return parent
::factory($table);
446 return self
::$_factory->create($table);
450 * Initialization for all DAO objects. Since we access DB_DO programatically
451 * we need to set the links manually.
453 public function initialize() {
455 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
456 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
457 // This occurs very early in bootstrap - error handlers may not be wired up.
458 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
459 CRM_Utils_System
::civiExit();
464 * Defines the default key as 'id'.
468 public function keys() {
477 * Tells DB_DataObject which keys use autoincrement.
478 * 'id' is autoincrementing by default.
483 public function sequenceKey() {
484 static $sequenceKeys;
485 if (!isset($sequenceKeys)) {
486 $sequenceKeys = ['id', TRUE];
488 return $sequenceKeys;
492 * Returns list of FK relationships.
496 * Array of CRM_Core_Reference_Interface
498 public static function getReferenceColumns() {
503 * Returns all the column names of this table.
508 public static function &fields() {
514 * Get/set an associative array of table columns
519 public function table() {
520 $fields = $this->fields();
524 foreach ($fields as $name => $value) {
525 $table[$value['name']] = $value['type'];
526 if (!empty($value['required'])) {
527 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
540 * @return CRM_Core_DAO
542 public function save($hook = TRUE) {
543 if (!empty($this->id
)) {
547 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
548 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
550 $this->clearDbColumnValueCache();
556 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
557 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
563 CRM_Utils_Hook
::postSave($this);
570 * Deletes items from table which match current objects variables.
572 * Returns the true on success
576 * Designed to be extended
578 * $object = new mytable();
580 * echo $object->delete(); // builds a conditon
582 * $object = new mytable();
583 * $object->whereAdd('age > 12');
585 * $object->orderBy('age DESC');
586 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
588 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
589 * we will build the condition only using the whereAdd's. Default is to
590 * build the condition only using the object parameters.
592 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
594 public function delete($useWhere = FALSE) {
595 $preEvent = new \Civi\Core\DAO\Event\
PreDelete($this);
596 \Civi
::service('dispatcher')->dispatch("civi.dao.preDelete", $preEvent);
598 $result = parent
::delete($useWhere);
600 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
601 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
604 $this->clearDbColumnValueCache();
610 * @param bool $created
612 public function log($created = FALSE) {
615 if (!$this->getLog()) {
620 $session = CRM_Core_Session
::singleton();
621 $cid = $session->get('userID');
624 // return is we dont have handle to FK
629 $dao = new CRM_Core_DAO_Log();
630 $dao->entity_table
= $this->getTableName();
631 $dao->entity_id
= $this->id
;
632 $dao->modified_id
= $cid;
633 $dao->modified_date
= date("YmdHis");
638 * Given an associative array of name/value pairs, extract all the values
639 * that belong to this object and initialize the object with said values
641 * @param array $params
642 * (reference ) associative array of name/value pairs.
643 * @param bool $serializeArrays
644 * Should arrays that are passed in be serialised according to the metadata.
645 * Eventually this should be always true / gone, but in the interests of caution
646 * it is being grandfathered in. In general an array is not valid on the DAO
647 * but there may be instances where this function is called & then some handling
648 * takes place on the would-be array.
651 * Did we copy all null values into the object
653 public function copyValues(&$params, $serializeArrays = FALSE) {
654 $fields = $this->fields();
656 foreach ($fields as $name => $value) {
657 $dbName = $value['name'];
658 if (array_key_exists($dbName, $params)) {
659 $pValue = $params[$dbName];
662 elseif (array_key_exists($name, $params)) {
663 $pValue = $params[$name];
670 // if there is no value then make the variable NULL
672 if ($pValue === '') {
673 $this->$dbName = 'null';
675 elseif ($serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
676 $this->$dbName = CRM_Core_DAO
::serializeField($pValue, $value['serialize']);
680 if (!$serializeArrays && is_array($pValue) && !empty($value['serialize'])) {
681 Civi
::log()->warning(ts('use copyParams to serialize arrays (' . __CLASS__
. '.' . $name . ')'), ['civi.tag' => 'deprecated']);
683 $maxLength = CRM_Utils_Array
::value('maxlength', $value);
684 if (!is_array($pValue) && $maxLength && mb_strlen($pValue) > $maxLength
685 && empty($value['pseudoconstant'])
687 Civi
::log()->warning(ts('A string for field $dbName has been truncated. The original string was %1', [CRM_Utils_Type
::escape($pValue, 'String')]));
688 // The string is too long - what to do what to do? Well losing data is generally bad so lets' truncate
689 $pValue = CRM_Utils_String
::ellipsify($pValue, $maxLength);
691 $this->$dbName = $pValue;
700 * Store all the values from this object in an associative array
701 * this is a destructive store, calling function is responsible
702 * for keeping sanity of id's.
704 * @param object $object
705 * The object that we are extracting data from.
706 * @param array $values
707 * (reference ) associative array of name/value pairs.
709 public static function storeValues(&$object, &$values) {
710 $fields = $object->fields();
711 foreach ($fields as $name => $value) {
712 $dbName = $value['name'];
713 if (isset($object->$dbName) && $object->$dbName !== 'null') {
714 $values[$dbName] = $object->$dbName;
715 if ($name != $dbName) {
716 $values[$name] = $object->$dbName;
723 * Create an attribute for this specific field. We only do this for strings and text
725 * @param array $field
726 * The field under task.
729 * the attributes for the object
731 public static function makeAttribute($field) {
733 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
734 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
735 $size = CRM_Utils_Array
::value('size', $field);
736 if ($maxLength ||
$size) {
739 $attributes['maxlength'] = $maxLength;
742 $attributes['size'] = $size;
747 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
748 $rows = CRM_Utils_Array
::value('rows', $field);
752 $cols = CRM_Utils_Array
::value('cols', $field);
758 $attributes['rows'] = $rows;
759 $attributes['cols'] = $cols;
762 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
) {
763 $attributes['size'] = 6;
764 $attributes['maxlength'] = 14;
772 * Get the size and maxLength attributes for this text field.
773 * (or for all text fields) in the DAO object.
775 * @param string $class
777 * @param string $fieldName
778 * Field that i'm interested in or null if.
779 * you want the attributes for all DAO text fields
782 * assoc array of name => attribute pairs
784 public static function getAttribute($class, $fieldName = NULL) {
785 $object = new $class();
786 $fields = $object->fields();
787 if ($fieldName != NULL) {
788 $field = CRM_Utils_Array
::value($fieldName, $fields);
789 return self
::makeAttribute($field);
793 foreach ($fields as $name => $field) {
794 $attribute = self
::makeAttribute($field);
796 $attributes[$name] = $attribute;
800 if (!empty($attributes)) {
808 * Check if there is a record with the same name in the db.
810 * @param string $value
811 * The value of the field we are checking.
812 * @param string $daoName
813 * The dao object name.
814 * @param string $daoID
815 * The id of the object being updated. u can change your name.
816 * as long as there is no conflict
817 * @param string $fieldName
818 * The name of the field in the DAO.
820 * @param string $domainID
821 * The id of the domain. Object exists only for the given domain.
824 * true if object exists
826 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
827 $object = new $daoName();
828 $object->$fieldName = $value;
830 $object->domain_id
= $domainID;
833 if ($object->find(TRUE)) {
834 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
842 * Check if there is a given column in a specific table.
845 * @see CRM_Core_BAO_SchemaHandler::checkIfFieldExists
847 * @param string $tableName
848 * @param string $columnName
849 * @param bool $i18nRewrite
850 * Whether to rewrite the query on multilingual setups.
853 * true if exists, else false
855 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
856 return CRM_Core_BAO_SchemaHandler
::checkIfFieldExists($tableName, $columnName, $i18nRewrite);
860 * Scans all the tables using a slow query and table name.
864 public static function getTableNames() {
865 $dao = CRM_Core_DAO
::executeQuery(
867 FROM information_schema.TABLES
868 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
869 AND TABLE_NAME LIKE 'civicrm_%'
870 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
871 AND TABLE_NAME NOT LIKE '%_temp%'
874 while ($dao->fetch()) {
875 $values[] = $dao->TABLE_NAME
;
881 * @param int $maxTablesToCheck
885 public static function isDBMyISAM($maxTablesToCheck = 10) {
886 return CRM_Core_DAO
::singleValueQuery(
888 FROM information_schema.TABLES
889 WHERE ENGINE = 'MyISAM'
890 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
891 AND TABLE_NAME LIKE 'civicrm_%'
892 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
893 AND TABLE_NAME NOT LIKE '%_temp%'
894 AND TABLE_NAME NOT LIKE 'civicrm_tmp_%'
899 * Get the name of the CiviCRM database.
903 public static function getDatabaseName() {
904 $daoObj = new CRM_Core_DAO();
905 return $daoObj->database();
909 * Checks if a constraint exists for a specified table.
911 * @param string $tableName
912 * @param string $constraint
915 * true if constraint exists, false otherwise
917 public static function checkConstraintExists($tableName, $constraint) {
920 if (!array_key_exists($tableName, $show)) {
921 $query = "SHOW CREATE TABLE $tableName";
922 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
924 if (!$dao->fetch()) {
925 CRM_Core_Error
::fatal();
928 $show[$tableName] = $dao->Create_Table
;
931 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
935 * Checks if CONSTRAINT keyword exists for a specified table.
937 * @param array $tables
942 * true if CONSTRAINT keyword exists, false otherwise
944 public static function schemaRequiresRebuilding($tables = ["civicrm_contact"]) {
946 foreach ($tables as $tableName) {
947 if (!array_key_exists($tableName, $show)) {
948 $query = "SHOW CREATE TABLE $tableName";
949 $dao = CRM_Core_DAO
::executeQuery($query, [], TRUE, NULL, FALSE, FALSE);
951 if (!$dao->fetch()) {
952 CRM_Core_Error
::fatal();
955 $show[$tableName] = $dao->Create_Table
;
958 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
959 if ($result == TRUE) {
970 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
971 * for a specified column of a table.
973 * @param string $tableName
974 * @param string $columnName
977 * true if in format, false otherwise
979 public static function checkFKConstraintInFormat($tableName, $columnName) {
982 if (!array_key_exists($tableName, $show)) {
983 $query = "SHOW CREATE TABLE $tableName";
984 $dao = CRM_Core_DAO
::executeQuery($query);
986 if (!$dao->fetch()) {
987 CRM_Core_Error
::fatal();
990 $show[$tableName] = $dao->Create_Table
;
992 $constraint = "`FK_{$tableName}_{$columnName}`";
993 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
994 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
998 * Check whether a specific column in a specific table has always the same value.
1000 * @param string $tableName
1001 * @param string $columnName
1002 * @param string $columnValue
1005 * true if the value is always $columnValue, false otherwise
1007 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
1008 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
1009 $dao = CRM_Core_DAO
::executeQuery($query);
1010 $result = $dao->fetch() ?
FALSE : TRUE;
1015 * Check whether a specific column in a specific table is always NULL.
1017 * @param string $tableName
1018 * @param string $columnName
1021 * true if if the value is always NULL, false otherwise
1023 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
1024 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
1025 $dao = CRM_Core_DAO
::executeQuery($query);
1026 $result = $dao->fetch() ?
FALSE : TRUE;
1031 * Check if there is a given table in the database.
1033 * @param string $tableName
1036 * true if exists, else false
1038 public static function checkTableExists($tableName) {
1043 $params = [1 => [$tableName, 'String']];
1045 $dao = CRM_Core_DAO
::executeQuery($query, $params);
1046 $result = $dao->fetch() ?
TRUE : FALSE;
1051 * Check if a given table has data.
1053 * @param string $tableName
1055 * TRUE if $tableName has at least one record.
1057 public static function checkTableHasData($tableName) {
1058 $c = CRM_Core_DAO
::singleValueQuery(sprintf('SELECT count(*) c FROM `%s`', $tableName));
1067 public function checkVersion($version) {
1072 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
1073 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
1077 * Find a DAO object for the given ID and return it.
1080 * Id of the DAO object being searched for.
1082 * @return CRM_Core_DAO
1083 * Object of the type of the class that called this function.
1087 public static function findById($id) {
1088 $object = new static();
1090 if (!$object->find(TRUE)) {
1091 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1097 * Returns all results as array-encoded records.
1101 public function fetchAll() {
1103 while ($this->fetch()) {
1104 $result[] = $this->toArray();
1110 * Return the results as PHP generator.
1112 * @param string $type
1113 * Whether the generator yields 'dao' objects or 'array's.
1115 public function fetchGenerator($type = 'dao') {
1116 while ($this->fetch()) {
1123 yield
$this->toArray();
1127 throw new \
RuntimeException("Invalid record type ($type)");
1133 * Returns a singular value.
1135 * @return mixed|NULL
1137 public function fetchValue() {
1138 $result = $this->getDatabaseResult();
1139 $row = $result->fetchRow();
1149 * Get all the result records as mapping between columns.
1151 * @param string $keyColumn
1153 * @param string $valueColumn
1156 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1158 public function fetchMap($keyColumn, $valueColumn) {
1160 while ($this->fetch()) {
1161 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1167 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1169 * @param string $daoName
1170 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1171 * @param int $searchValue
1172 * Value of the column you want to search by.
1173 * @param string $returnColumn
1174 * Name of the column you want to GET the value of.
1175 * @param string $searchColumn
1176 * Name of the column you want to search by.
1177 * @param bool $force
1178 * Skip use of the cache.
1180 * @return string|null
1181 * Value of $returnColumn in the retrieved record
1183 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1185 empty($searchValue) ||
1186 trim(strtolower($searchValue)) == 'null'
1188 // adding this here since developers forget to check for an id
1189 // or for the 'null' (which is a bad DAO kludge)
1190 // and hence we get the first value in the db
1191 CRM_Core_Error
::fatal();
1194 self
::$_dbColumnValueCache = self
::$_dbColumnValueCache ??
[];
1196 while (strpos($daoName, '_BAO_') !== FALSE) {
1197 $daoName = get_parent_class($daoName);
1201 empty(self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue]) ||
1202 !array_key_exists($returnColumn, self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue])
1204 $object = new $daoName();
1205 $object->$searchColumn = $searchValue;
1206 $object->selectAdd();
1207 $object->selectAdd($returnColumn);
1210 if ($object->find(TRUE)) {
1211 $result = $object->$returnColumn;
1214 self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn] = $result;
1216 return self
::$_dbColumnValueCache[$daoName][$searchColumn][$searchValue][$returnColumn];
1220 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1222 * @param string $daoName
1223 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1224 * @param int $searchValue
1225 * Value of the column you want to search by.
1226 * @param string $setColumn
1227 * Name of the column you want to SET the value of.
1228 * @param string $setValue
1229 * SET the setColumn to this value.
1230 * @param string $searchColumn
1231 * Name of the column you want to search by.
1234 * true if we found and updated the object, else false
1236 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1237 $object = new $daoName();
1238 $object->selectAdd();
1239 $object->selectAdd("$searchColumn, $setColumn");
1240 $object->$searchColumn = $searchValue;
1242 if ($object->find(TRUE)) {
1243 $object->$setColumn = $setValue;
1244 if ($object->save()) {
1255 * @param array|object $sort either array or CRM_Utils_Sort
1256 * @param string $default
1257 * Default sort value.
1261 public static function getSortString($sort, $default = NULL) {
1262 // check if sort is of type CRM_Utils_Sort
1263 if (is_a($sort, 'CRM_Utils_Sort')) {
1264 return $sort->orderBy();
1269 // is it an array specified as $field => $sortDirection ?
1271 foreach ($sort as $k => $v) {
1272 $sortString .= "$k $v,";
1274 return rtrim($sortString, ',');
1280 * Fetch object based on array of properties.
1282 * @param string $daoName
1283 * Name of the dao object.
1284 * @param array $params
1285 * (reference ) an assoc array of name/value pairs.
1286 * @param array $defaults
1287 * (reference ) an assoc array to hold the flattened values.
1288 * @param array $returnProperities
1289 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1292 * an object of type referenced by daoName
1294 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1295 $object = new $daoName();
1296 $object->copyValues($params);
1298 // return only specific fields if returnproperties are sent
1299 if (!empty($returnProperities)) {
1300 $object->selectAdd();
1301 $object->selectAdd(implode(',', $returnProperities));
1304 if ($object->find(TRUE)) {
1305 self
::storeValues($object, $defaults);
1312 * Delete the object records that are associated with this contact.
1314 * @param string $daoName
1315 * Name of the dao object.
1316 * @param int $contactId
1317 * Id of the contact to delete.
1319 public static function deleteEntityContact($daoName, $contactId) {
1320 $object = new $daoName();
1322 $object->entity_table
= 'civicrm_contact';
1323 $object->entity_id
= $contactId;
1328 * Execute an unbuffered query.
1330 * This is a wrapper around new functionality exposed with CRM-17748.
1332 * @param string $query query to be executed
1334 * @param array $params
1335 * @param bool $abort
1336 * @param null $daoName
1337 * @param bool $freeDAO
1338 * @param bool $i18nRewrite
1339 * @param bool $trapException
1341 * @return CRM_Core_DAO
1342 * Object that points to an unbuffered result set
1344 public static function executeUnbufferedQuery(
1350 $i18nRewrite = TRUE,
1351 $trapException = FALSE
1354 return self
::executeQuery(
1362 ['result_buffering' => 0]
1369 * @param string $query
1370 * Query to be executed.
1372 * @param array $params
1373 * @param bool $abort
1374 * @param null $daoName
1375 * @param bool $freeDAO
1376 * @param bool $i18nRewrite
1377 * @param bool $trapException
1378 * @param array $options
1380 * @return CRM_Core_DAO|object
1381 * object that holds the results of the query
1382 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1383 * out all the properties that are not part of the DAO
1385 public static function &executeQuery(
1391 $i18nRewrite = TRUE,
1392 $trapException = FALSE,
1395 $queryStr = self
::composeQuery($query, $params, $abort);
1398 $dao = new CRM_Core_DAO();
1401 $dao = new $daoName();
1404 if ($trapException) {
1405 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1408 if ($dao->isValidOption($options)) {
1409 $dao->setOptions($options);
1412 $result = $dao->query($queryStr, $i18nRewrite);
1414 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1415 if (CRM_Utils_Array
::value('result_buffering', $options) === 0) {
1419 if (is_a($result, 'DB_Error')) {
1424 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1426 // we typically do this for insert/update/delete statements OR if explicitly asked to
1433 * Wrapper to validate internal DAO options before passing to DB_mysql/DB_Common level
1435 * @param array $options
1438 * Provided options are valid
1440 public function isValidOption($options) {
1449 if (empty($options)) {
1453 foreach (array_keys($options) as $option) {
1454 if (!in_array($option, $validOptions)) {
1464 * Execute a query and get the single result.
1466 * @param string $query
1467 * Query to be executed.
1468 * @param array $params
1469 * @param bool $abort
1470 * @param bool $i18nRewrite
1471 * @return string|null
1472 * the result of the query if any
1475 public static function &singleValueQuery(
1481 $queryStr = self
::composeQuery($query, $params, $abort);
1483 static $_dao = NULL;
1486 $_dao = new CRM_Core_DAO();
1489 $_dao->query($queryStr, $i18nRewrite);
1491 $result = $_dao->getDatabaseResult();
1494 $row = $result->fetchRow();
1504 * Compose the query by merging the parameters into it.
1506 * @param string $query
1507 * @param array $params
1508 * @param bool $abort
1511 * @throws CRM_Core_Exception
1513 public static function composeQuery($query, $params = [], $abort = TRUE) {
1515 foreach ($params as $key => $item) {
1516 if (is_numeric($key)) {
1517 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1518 $item[0] = self
::escapeString($item[0]);
1519 if ($item[1] == 'String' ||
1520 $item[1] == 'Memo' ||
1523 // Support class constants stipulating wildcard characters and/or
1524 // non-quoting of strings. Also support legacy code which may be
1525 // passing in TRUE or 1 for $item[2], which used to indicate the
1526 // use of wildcard characters.
1527 if (!empty($item[2])) {
1528 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1529 $item[0] = "'%{$item[0]}%'";
1531 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1532 $item[0] = "'{$item[0]}'";
1536 $item[0] = "'{$item[0]}'";
1540 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1541 strlen($item[0]) == 0
1546 $tr['%' . $key] = $item[0];
1549 throw new CRM_Core_Exception("{$item[0]} is not of type {$item[1]}");
1554 return strtr($query, $tr);
1560 public static function freeResult($ids = NULL) {
1561 global $_DB_DATAOBJECT;
1564 if (!$_DB_DATAOBJECT ||
1565 !isset($_DB_DATAOBJECT['RESULTS'])
1569 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1572 foreach ($ids as $id) {
1573 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1574 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1575 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1578 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1579 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1585 * Make a shallow copy of an object and all the fields in the object.
1587 * @param string $daoName
1589 * @param array $criteria
1590 * Array of all the fields & values.
1591 * on which basis to copy
1592 * @param array $newData
1593 * Array of all the fields & values.
1594 * to be copied besides the other fields
1595 * @param string $fieldsFix
1596 * Array of fields that you want to prefix/suffix/replace.
1597 * @param string $blockCopyOfDependencies
1598 * Fields that you want to block from.
1600 * @param bool $blockCopyofCustomValues
1601 * Case when you don't want to copy the custom values set in a
1602 * template as it will override/ignore the submitted custom values
1604 * @return CRM_Core_DAO|bool
1605 * the newly created copy of the object. False if none created.
1607 public static function copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL, $blockCopyofCustomValues = FALSE) {
1608 $object = new $daoName();
1611 $object->id
= $criteria['id'];
1614 foreach ($criteria as $key => $value) {
1615 $object->$key = $value;
1620 while ($object->fetch()) {
1622 // all the objects except with $blockCopyOfDependencies set
1623 // be copied - addresses #CRM-1962
1625 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1629 $newObject = new $daoName();
1631 $fields = $object->fields();
1632 if (!is_array($fieldsFix)) {
1633 $fieldsToPrefix = [];
1634 $fieldsToSuffix = [];
1635 $fieldsToReplace = [];
1637 if (!empty($fieldsFix['prefix'])) {
1638 $fieldsToPrefix = $fieldsFix['prefix'];
1640 if (!empty($fieldsFix['suffix'])) {
1641 $fieldsToSuffix = $fieldsFix['suffix'];
1643 if (!empty($fieldsFix['replace'])) {
1644 $fieldsToReplace = $fieldsFix['replace'];
1647 foreach ($fields as $name => $value) {
1648 if ($name == 'id' ||
$value['name'] == 'id') {
1649 // copy everything but the id!
1653 $dbName = $value['name'];
1654 $type = CRM_Utils_Type
::typeToString($value['type']);
1655 $newObject->$dbName = $object->$dbName;
1656 if (isset($fieldsToPrefix[$dbName])) {
1657 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1659 if (isset($fieldsToSuffix[$dbName])) {
1660 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1662 if (isset($fieldsToReplace[$dbName])) {
1663 $newObject->$dbName = $fieldsToReplace[$dbName];
1666 if ($type == 'Timestamp' ||
$type == 'Date') {
1667 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1671 $newObject->copyValues($newData);
1675 if (!$blockCopyofCustomValues) {
1676 $newObject->copyCustomFields($object->id
, $newObject->id
);
1678 CRM_Utils_Hook
::post('create', CRM_Core_DAO_AllCoreTables
::getBriefName(str_replace('_BAO_', '_DAO_', $daoName)), $newObject->id
, $newObject);
1685 * Method that copies custom fields values from an old entity to a new one.
1687 * Fixes bug CRM-19302,
1688 * where if a custom field of File type was present, left both events using the same file,
1689 * breaking download URL's for the old event.
1691 * @todo the goal here is to clean this up so that it works for any entity. Copy Generic already DOES some custom field stuff
1692 * but it seems to be bypassed & perhaps less good than this (or this just duplicates it...)
1694 * @param int $entityID
1695 * @param int $newEntityID
1697 public function copyCustomFields($entityID, $newEntityID) {
1698 $entity = CRM_Core_DAO_AllCoreTables
::getBriefName(get_class($this));
1699 $tableName = CRM_Core_DAO_AllCoreTables
::getTableForClass(get_class($this));
1700 // Obtain custom values for old event
1701 $customParams = $htmlType = [];
1702 $customValues = CRM_Core_BAO_CustomValueTable
::getEntityValues($entityID, $entity);
1704 // If custom values present, we copy them
1705 if (!empty($customValues)) {
1706 // Get Field ID's and identify File type attributes, to handle file copying.
1707 $fieldIds = implode(', ', array_keys($customValues));
1708 $sql = "SELECT id FROM civicrm_custom_field WHERE html_type = 'File' AND id IN ( {$fieldIds} )";
1709 $result = CRM_Core_DAO
::executeQuery($sql);
1711 // Build array of File type fields
1712 while ($result->fetch()) {
1713 $htmlType[] = $result->id
;
1716 // Build params array of custom values
1717 foreach ($customValues as $field => $value) {
1718 if ($value !== NULL) {
1719 // Handle File type attributes
1720 if (in_array($field, $htmlType)) {
1721 $fileValues = CRM_Core_BAO_File
::path($value, $entityID);
1722 $customParams["custom_{$field}_-1"] = [
1723 'name' => CRM_Utils_File
::duplicate($fileValues[0]),
1724 'type' => $fileValues[1],
1727 // Handle other types
1729 $customParams["custom_{$field}_-1"] = $value;
1734 // Save Custom Fields for new Event
1735 CRM_Core_BAO_CustomValueTable
::postProcess($customParams, $tableName, $newEntityID, $entity);
1738 // copy activity attachments ( if any )
1739 CRM_Core_BAO_File
::copyEntityFile($tableName, $entityID, $tableName, $newEntityID);
1743 * Cascade update through related entities.
1745 * @param string $daoName
1748 * @param array $newData
1750 * @return CRM_Core_DAO|null
1752 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = []) {
1753 $object = new $daoName();
1754 $object->id
= $fromId;
1756 if ($object->find(TRUE)) {
1757 $newObject = new $daoName();
1758 $newObject->id
= $toId;
1760 if ($newObject->find(TRUE)) {
1761 $fields = $object->fields();
1762 foreach ($fields as $name => $value) {
1763 if ($name == 'id' ||
$value['name'] == 'id') {
1764 // copy everything but the id!
1768 $colName = $value['name'];
1769 $newObject->$colName = $object->$colName;
1771 if (substr($name, -5) == '_date' ||
1772 substr($name, -10) == '_date_time'
1774 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1777 foreach ($newData as $k => $v) {
1778 $newObject->$k = $v;
1788 * Given the component id, compute the contact id
1789 * since its used for things like send email
1791 * @param $componentIDs
1792 * @param string $tableName
1793 * @param string $idField
1797 public static function getContactIDsFromComponent($componentIDs, $tableName, $idField = 'id') {
1800 if (empty($componentIDs)) {
1804 $IDs = implode(',', $componentIDs);
1808 WHERE $idField IN ( $IDs )
1811 $dao = CRM_Core_DAO
::executeQuery($query);
1812 while ($dao->fetch()) {
1813 $contactIDs[] = $dao->contact_id
;
1819 * Fetch object based on array of properties.
1821 * @param string $daoName
1822 * Name of the dao object.
1823 * @param string $fieldIdName
1824 * @param int $fieldId
1826 * @param array $returnProperities
1827 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1830 * an object of type referenced by daoName
1832 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1833 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1834 $object = new $daoName();
1835 $object->$fieldIdName = $fieldId;
1837 // return only specific fields if returnproperties are sent
1838 if (!empty($returnProperities)) {
1839 $object->selectAdd();
1840 $object->selectAdd('id');
1841 $object->selectAdd(implode(',', $returnProperities));
1845 while ($object->fetch()) {
1847 self
::storeValues($object, $defaults);
1848 $details[$object->id
] = $defaults;
1855 * Drop all CiviCRM tables.
1857 * @throws \CRM_Core_Exception
1859 public static function dropAllTables() {
1861 // first drop all the custom tables we've created
1862 CRM_Core_BAO_CustomGroup
::dropAllTables();
1864 // drop all multilingual views
1865 CRM_Core_I18n_Schema
::dropAllViews();
1867 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1868 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1869 '..' . DIRECTORY_SEPARATOR
.
1870 '..' . DIRECTORY_SEPARATOR
.
1871 'sql' . DIRECTORY_SEPARATOR
.
1872 'civicrm_drop.mysql'
1881 public static function escapeString($string) {
1882 static $_dao = NULL;
1884 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1885 // has been installed), then we fallback DB-less str_replace escaping, as
1886 // we can't use mysqli_real_escape_string, as there is no DB connection.
1887 // Note: In typical usage, escapeString() will only check one conditional
1888 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1889 if (!defined('CIVICRM_DSN')) {
1890 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1891 // list of characters mysqli_real_escape_string escapes.
1892 $search = ["\\", "\x00", "\n", "\r", "'", '"', "\x1a"];
1893 $replace = ["\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z"];
1894 return str_replace($search, $replace, $string);
1896 $_dao = new CRM_Core_DAO();
1898 return $_dao->escape($string);
1902 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1904 * @param array $strings
1905 * @param string $default
1906 * the value to use if $strings has no elements.
1908 * eg "abc","def","ghi"
1910 public static function escapeStrings($strings, $default = NULL) {
1911 static $_dao = NULL;
1913 $_dao = new CRM_Core_DAO();
1916 if (empty($strings)) {
1920 $escapes = array_map([$_dao, 'escape'], $strings);
1921 return '"' . implode('","', $escapes) . '"';
1929 public static function escapeWildCardString($string) {
1931 // ensure we escape the single characters % and _ which are mysql wild
1932 // card characters and could come in via sortByCharacter
1933 // note that mysql does not escape these characters
1934 if ($string && in_array($string,
1935 ['%', '_', '%%', '_%']
1938 return '\\' . $string;
1941 return self
::escapeString($string);
1945 * Creates a test object, including any required objects it needs via recursion
1946 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1947 * ONLY USE FOR TESTING
1949 * @param string $daoName
1950 * @param array $params
1951 * @param int $numObjects
1952 * @param bool $createOnly
1954 * @return object|array|NULL
1955 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1957 public static function createTestObject(
1963 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1964 // so we re-set here in case
1965 $config = CRM_Core_Config
::singleton();
1966 $config->backtrace
= TRUE;
1968 static $counter = 0;
1969 CRM_Core_DAO
::$_testEntitiesToSkip = [
1970 'CRM_Core_DAO_Worldregion',
1971 'CRM_Core_DAO_StateProvince',
1972 'CRM_Core_DAO_Country',
1973 'CRM_Core_DAO_Domain',
1974 'CRM_Financial_DAO_FinancialType',
1975 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1978 // Prefer to instantiate BAO's instead of DAO's (when possible)
1979 // so that assignTestValue()/assignTestFK() can be overloaded.
1980 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1981 if ($baoName === 'CRM_Financial_BAO_FinancialTrxn') {
1982 // OMG OMG OMG this is so incredibly bad. The BAO is insanely named.
1983 // @todo create a new class called what the BAO SHOULD be
1984 // that extends BAO-crazy-name.... migrate.
1985 $baoName = 'CRM_Core_BAO_FinancialTrxn';
1987 if (class_exists($baoName)) {
1988 $daoName = $baoName;
1991 for ($i = 0; $i < $numObjects; ++
$i) {
1994 /** @var CRM_Core_DAO $object */
1995 $object = new $daoName();
1997 $fields = $object->fields();
1998 foreach ($fields as $fieldName => $fieldDef) {
1999 $dbName = $fieldDef['name'];
2000 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
2001 $required = CRM_Utils_Array
::value('required', $fieldDef);
2003 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
2004 $object->$dbName = $params[$dbName];
2007 elseif ($dbName != 'id') {
2008 if ($FKClassName != NULL) {
2009 $object->assignTestFK($fieldName, $fieldDef, $params);
2013 $object->assignTestValue($fieldName, $fieldDef, $counter);
2021 $objects[$i] = $object;
2031 elseif ($numObjects == 1) {
2040 * Deletes the this object plus any dependent objects that are associated with it.
2041 * ONLY USE FOR TESTING
2043 * @param string $daoName
2044 * @param array $params
2046 public static function deleteTestObjects($daoName, $params = []) {
2047 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
2048 // so we re-set here in case
2049 $config = CRM_Core_Config
::singleton();
2050 $config->backtrace
= TRUE;
2052 $object = new $daoName();
2053 $object->id
= CRM_Utils_Array
::value('id', $params);
2055 // array(array(0 => $daoName, 1 => $daoParams))
2057 if ($object->find(TRUE)) {
2059 $fields = $object->fields();
2060 foreach ($fields as $name => $value) {
2062 $dbName = $value['name'];
2064 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
2065 $required = CRM_Utils_Array
::value('required', $value);
2066 if ($FKClassName != NULL
2068 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
2069 && ($required ||
$dbName == 'contact_id')
2070 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
2071 // to make this test process pass - line below makes pass for now
2072 && $dbName != 'member_of_contact_id'
2075 $deletions[] = [$FKClassName, ['id' => $object->$dbName]];
2082 foreach ($deletions as $deletion) {
2083 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
2088 * Set defaults when creating new entity.
2089 * (don't call this set defaults as already in use with different signature in some places)
2091 * @param array $params
2094 public static function setCreateDefaults(&$params, $defaults) {
2095 if (!empty($params['id'])) {
2098 foreach ($defaults as $key => $value) {
2099 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
2100 $params[$key] = $value;
2106 * @param string $prefix
2107 * @param bool $addRandomString
2108 * @param null $string
2112 * @see CRM_Utils_SQL_TempTable
2114 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
2115 $tableName = $prefix . "_temp";
2117 if ($addRandomString) {
2119 $tableName .= "_" . $string;
2122 $tableName .= "_" . md5(uniqid('', TRUE));
2130 * @param bool $trigger
2134 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
2135 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
2138 // test for create view and trigger permissions and if allowed, add the option to go multilingual
2140 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
2141 CRM_Core_TemporaryErrorScope
::ignoreException();
2142 $dao = new CRM_Core_DAO();
2144 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
2145 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2151 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
2152 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
2154 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2159 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
2160 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2162 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2169 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
2170 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
2179 * @param null $message
2180 * @param bool $printDAO
2182 public static function debugPrint($message = NULL, $printDAO = TRUE) {
2183 CRM_Utils_System
::xMemory("{$message}: ");
2186 global $_DB_DATAOBJECT;
2188 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
2189 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
2191 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
2196 * Build a list of triggers via hook and add them to (err, reconcile them
2197 * with) the database.
2199 * @param string $tableName
2200 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2201 * @param bool $force
2206 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
2207 Civi
::service('sql_triggers')->rebuild($tableName, $force);
2211 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
2212 * @see http://issues.civicrm.org/jira/browse/CRM-13822
2213 * TODO: Alternative solutions might be
2214 * * Stop using functions and find another way to strip numeric characters from phones
2215 * * Give better error messages (currently a missing fn fatals with "unknown error")
2217 public static function checkSqlFunctionsExist() {
2218 if (!self
::$_checkedSqlFunctionsExist) {
2219 self
::$_checkedSqlFunctionsExist = TRUE;
2220 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
2221 if (!$dao->fetch()) {
2222 self
::triggerRebuild();
2228 * Wrapper function to drop triggers.
2230 * @param string $tableName
2231 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2234 public static function dropTriggers($tableName = NULL) {
2235 Civi
::service('sql_triggers')->dropTriggers($tableName);
2239 * @param array $info
2240 * per hook_civicrm_triggerInfo.
2241 * @param string $onlyTableName
2242 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2245 public static function createTriggers(&$info, $onlyTableName = NULL) {
2246 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2250 * Given a list of fields, create a list of references.
2252 * @param string $className
2253 * BAO/DAO class name.
2254 * @return array<CRM_Core_Reference_Interface>
2256 public static function createReferenceColumns($className) {
2258 $fields = $className::fields();
2259 foreach ($fields as $field) {
2260 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2261 $result[] = new CRM_Core_Reference_OptionValue(
2262 $className::getTableName(),
2264 'civicrm_option_value',
2265 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2266 $field['pseudoconstant']['optionGroupName']
2274 * Find all records which refer to this entity.
2277 * Array of objects referencing this
2279 public function findReferences() {
2280 $links = self
::getReferencesToTable(static::getTableName());
2283 foreach ($links as $refSpec) {
2284 /** @var $refSpec CRM_Core_Reference_Interface */
2285 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2286 $result = $refSpec->findReferences($this);
2288 while ($result->fetch()) {
2289 $obj = new $daoName();
2290 $obj->id
= $result->id
;
2291 $occurrences[] = $obj;
2296 return $occurrences;
2301 * each item has keys:
2305 * - table: string|null SQL table name
2306 * - key: string|null SQL column name
2308 public function getReferenceCounts() {
2309 $links = self
::getReferencesToTable(static::getTableName());
2312 foreach ($links as $refSpec) {
2313 /** @var $refSpec CRM_Core_Reference_Interface */
2314 $count = $refSpec->getReferenceCount($this);
2315 if ($count['count'] != 0) {
2320 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2321 /** @var $component CRM_Core_Component_Info */
2322 $counts = array_merge($counts, $component->getReferenceCounts($this));
2324 CRM_Utils_Hook
::referenceCounts($this, $counts);
2330 * List all tables which have hard foreign keys to this table.
2332 * For now, this returns a description of every entity_id/entity_table
2334 * TODO: filter dynamic entity references on the $tableName, based on
2335 * schema metadata in dynamicForeignKey which enumerates a restricted
2336 * set of possible entity_table's.
2338 * @param string $tableName
2339 * Table referred to.
2342 * structure of table and column, listing every table with a
2343 * foreign key reference to $tableName, and the column where the key appears.
2345 public static function getReferencesToTable($tableName) {
2347 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2348 $links = $daoClassName::getReferenceColumns();
2349 $daoTableName = $daoClassName::getTableName();
2351 foreach ($links as $refSpec) {
2352 /** @var $refSpec CRM_Core_Reference_Interface */
2353 if ($refSpec->matchesTargetTable($tableName)) {
2354 $refsFound[] = $refSpec;
2362 * Get all references to contact table.
2364 * This includes core tables, custom group tables, tables added by the merge
2365 * hook and the entity_tag table.
2367 * Refer to CRM-17454 for information on the danger of querying the information
2368 * schema to derive this.
2370 public static function getReferencesToContactTable() {
2371 if (isset(\Civi
::$statics[__CLASS__
]) && isset(\Civi
::$statics[__CLASS__
]['contact_references'])) {
2372 return \Civi
::$statics[__CLASS__
]['contact_references'];
2374 $contactReferences = [];
2375 $coreReferences = CRM_Core_DAO
::getReferencesToTable('civicrm_contact');
2376 foreach ($coreReferences as $coreReference) {
2377 if (!is_a($coreReference, 'CRM_Core_Reference_Dynamic')) {
2378 $contactReferences[$coreReference->getReferenceTable()][] = $coreReference->getReferenceKey();
2381 self
::appendCustomTablesExtendingContacts($contactReferences);
2382 self
::appendCustomContactReferenceFields($contactReferences);
2384 // FixME for time being adding below line statically as no Foreign key constraint defined for table 'civicrm_entity_tag'
2385 $contactReferences['civicrm_entity_tag'][] = 'entity_id';
2386 \Civi
::$statics[__CLASS__
]['contact_references'] = $contactReferences;
2387 return \Civi
::$statics[__CLASS__
]['contact_references'];
2391 * Add custom tables that extend contacts to the list of contact references.
2393 * CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity seems like a safe-ish
2394 * function to be sure all are retrieved & we don't miss subtypes or inactive or multiples
2395 * - the down side is it is not cached.
2397 * Further changes should be include tests in the CRM_Core_MergerTest class
2398 * to ensure that disabled, subtype, multiple etc groups are still captured.
2400 * @param array $cidRefs
2402 public static function appendCustomTablesExtendingContacts(&$cidRefs) {
2403 $customValueTables = CRM_Core_BAO_CustomGroup
::getAllCustomGroupsByBaseEntity('Contact');
2404 $customValueTables->find();
2405 while ($customValueTables->fetch()) {
2406 $cidRefs[$customValueTables->table_name
][] = 'entity_id';
2411 * Add custom ContactReference fields to the list of contact references
2413 * This includes active and inactive fields/groups
2415 * @param array $cidRefs
2417 * @throws \CiviCRM_API3_Exception
2419 public static function appendCustomContactReferenceFields(&$cidRefs) {
2420 $fields = civicrm_api3('CustomField', 'get', [
2421 'return' => ['column_name', 'custom_group_id.table_name'],
2422 'data_type' => 'ContactReference',
2424 foreach ($fields as $field) {
2425 $cidRefs[$field['custom_group_id.table_name']][] = $field['column_name'];
2430 * Lookup the value of a MySQL global configuration variable.
2432 * @param string $name
2433 * E.g. "thread_stack".
2434 * @param mixed $default
2437 public static function getGlobalSetting($name, $default = NULL) {
2438 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2439 // that has been reported to fail under MySQL 5.0 for OS X
2440 $escapedName = self
::escapeString($name);
2441 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2442 if ($dao->fetch()) {
2451 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2453 * This is relevant where we want to offer both the ID field and the label field
2454 * as an option, e.g. search builder.
2456 * It is currently limited for optionGroupName & id+ name+ FK combos for purposes keeping the scope of the
2457 * change small, but is appropriate for other sorts of pseudoconstants.
2459 * @param array $fields
2461 public static function appendPseudoConstantsToFields(&$fields) {
2462 foreach ($fields as $field) {
2463 if (!empty($field['pseudoconstant'])) {
2464 $pseudoConstant = $field['pseudoconstant'];
2465 if (!empty($pseudoConstant['optionGroupName'])) {
2466 $fields[$pseudoConstant['optionGroupName']] = [
2467 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($pseudoConstant['optionGroupName']),
2468 'name' => $pseudoConstant['optionGroupName'],
2469 'data_type' => CRM_Utils_Type
::T_STRING
,
2470 'is_pseudofield_for' => $field['name'],
2473 // We restrict to id + name + FK as we are extending this a bit, but cautiously.
2475 !empty($field['FKClassName'])
2476 && CRM_Utils_Array
::value('keyColumn', $pseudoConstant) === 'id'
2477 && CRM_Utils_Array
::value('labelColumn', $pseudoConstant) === 'name'
2479 $pseudoFieldName = str_replace('_' . $pseudoConstant['keyColumn'], '', $field['name']);
2480 // This if is just an extra caution when adding change.
2481 if (!isset($fields[$pseudoFieldName])) {
2482 $daoName = $field['FKClassName'];
2483 $fkFields = $daoName::fields();
2484 foreach ($fkFields as $fkField) {
2485 if ($fkField['name'] === $pseudoConstant['labelColumn']) {
2486 $fields[$pseudoFieldName] = [
2487 'name' => $pseudoFieldName,
2488 'is_pseudofield_for' => $field['name'],
2489 'title' => $fkField['title'],
2490 'data_type' => $fkField['type'],
2491 'where' => $field['where'],
2502 * Get options for the called BAO object's field.
2504 * This function can be overridden by each BAO to add more logic related to context.
2505 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2507 * @param string $fieldName
2508 * @param string $context
2509 * @see CRM_Core_DAO::buildOptionsContext
2510 * @param array $props
2511 * whatever is known about this bao object.
2513 * @return array|bool
2515 public static function buildOptions($fieldName, $context = NULL, $props = []) {
2516 // If a given bao does not override this function
2517 $baoName = get_called_class();
2518 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, $props, $context);
2522 * Populate option labels for this object's fields.
2524 * @throws exception if called directly on the base class
2526 public function getOptionLabels() {
2527 $fields = $this->fields();
2528 if ($fields === NULL) {
2529 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2531 foreach ($fields as $field) {
2532 $name = CRM_Utils_Array
::value('name', $field);
2533 if ($name && isset($this->$name)) {
2534 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2535 if ($label !== FALSE) {
2536 // Append 'label' onto the field name
2537 $labelName = $name . '_label';
2538 $this->$labelName = $label;
2545 * Provides documentation and validation for the buildOptions $context param
2547 * @param string $context
2552 public static function buildOptionsContext($context = NULL) {
2554 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2555 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2556 'search' => "search: searchable options are returned; labels are translated.",
2557 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2558 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2559 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2561 // Validation: enforce uniformity of this param
2562 if ($context !== NULL && !isset($contexts[$context])) {
2563 throw new Exception("'$context' is not a valid context for buildOptions.");
2569 * @param string $fieldName
2570 * @return bool|array
2572 public function getFieldSpec($fieldName) {
2573 $fields = $this->fields();
2574 $fieldKeys = $this->fieldKeys();
2576 // Support "unique names" as well as sql names
2577 $fieldKey = $fieldName;
2578 if (empty($fields[$fieldKey])) {
2579 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2581 // If neither worked then this field doesn't exist. Return false.
2582 if (empty($fields[$fieldKey])) {
2585 return $fields[$fieldKey];
2589 * Get SQL where clause for SQL filter syntax input parameters.
2591 * SQL version of api function to assign filters to the DAO based on the syntax
2592 * $field => array('IN' => array(4,6,9))
2594 * $field => array('LIKE' => array('%me%))
2597 * @param string $fieldName
2599 * @param array $filter
2600 * filter to be applied indexed by operator.
2601 * @param string $type
2602 * type of field (not actually used - nor in api @todo ).
2603 * @param string $alias
2604 * alternative field name ('as') @todo- not actually used.
2605 * @param bool $returnSanitisedArray
2606 * Return a sanitised array instead of a clause.
2607 * this is primarily so we can add filters @ the api level to the Query object based fields
2611 * @return NULL|string|array
2612 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2613 * depending on whether it is supported as yet
2615 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2616 foreach ($filter as $operator => $criteria) {
2617 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2618 switch ($operator) {
2622 if (!$returnSanitisedArray) {
2623 return (sprintf('%s %s', $fieldName, $operator));
2626 return (sprintf('%s %s ', $fieldName, $operator));
2630 // ternary operators
2633 if ((empty($criteria[0]) && !in_array($criteria[0], ['0', 0]))||
(empty($criteria[1]) && !in_array($criteria[1], ['0', 0]))) {
2634 throw new Exception("invalid criteria for $operator");
2636 if (!$returnSanitisedArray) {
2637 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2640 // not yet implemented (tests required to implement)
2648 if (empty($criteria)) {
2649 throw new Exception("invalid criteria for $operator");
2651 $escapedCriteria = array_map([
2655 if (!$returnSanitisedArray) {
2656 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2658 return $escapedCriteria;
2663 if (!$returnSanitisedArray) {
2664 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2667 // not yet implemented (tests required to implement)
2676 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2677 * support for other syntaxes is discussed in ticket but being put off for now
2680 public static function acceptedSQLOperators() {
2701 * SQL has a limit of 64 characters on various names:
2702 * table name, trigger name, column name ...
2704 * For custom groups and fields we generated names from user entered input
2705 * which can be longer than this length, this function helps with creating
2706 * strings that meet various criteria.
2708 * @param string $string
2709 * The string to be shortened.
2710 * @param int $length
2711 * The max length of the string.
2713 * @param bool $makeRandom
2717 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2718 // early return for strings that meet the requirements
2719 if (strlen($string) <= $length) {
2723 // easy return for calls that dont need a randomized uniq string
2725 return substr($string, 0, $length);
2728 // the string is longer than the length and we need a uniq string
2729 // for the same tablename we need the same uniq string every time
2730 // hence we use md5 on the string, which is not random
2731 // we'll append 8 characters to the end of the tableName
2732 $md5string = substr(md5($string), 0, 8);
2733 return substr($string, 0, $length - 8) . "_{$md5string}";
2737 * https://issues.civicrm.org/jira/browse/CRM-17748
2738 * Sets the internal options to be used on a query
2740 * @param array $options
2743 public function setOptions($options) {
2744 if (is_array($options)) {
2745 $this->_options
= $options;
2750 * https://issues.civicrm.org/jira/browse/CRM-17748
2751 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2753 * @param array $options
2756 protected function _setDBOptions($options) {
2757 global $_DB_DATAOBJECT;
2759 if (is_array($options) && count($options)) {
2760 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2761 foreach ($options as $option_name => $option_value) {
2762 $conn->setOption($option_name, $option_value);
2769 * @param array $params
2771 public function setApiFilter(&$params) {
2775 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2777 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2780 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2784 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2788 public function addSelectWhereClause() {
2790 $fields = $this->fields();
2791 foreach ($fields as $fieldName => $field) {
2792 // Clause for contact-related entities like Email, Relationship, etc.
2793 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2794 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2796 // Clause for an entity_table/entity_id combo
2797 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2798 $relatedClauses = [];
2799 $relatedEntities = $this->buildOptions('entity_table', 'get');
2800 foreach ((array) $relatedEntities as $table => $ent) {
2802 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2803 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2805 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2808 $relatedClauses[] = "(entity_table = '$table')";
2812 if ($relatedClauses) {
2813 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2817 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2822 * This returns the final permissioned query string for this entity
2824 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2826 * @param string $tableAlias
2829 public static function getSelectWhereClause($tableAlias = NULL) {
2830 $bao = new static();
2831 if ($tableAlias === NULL) {
2832 $tableAlias = $bao->tableName();
2835 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2836 $clauses[$field] = NULL;
2838 $clauses[$field] = "(`$tableAlias`.`$field` IS NULL OR (`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals) . '))';
2845 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2846 * and dashes, and contains at least one [a-z] case insenstive.
2852 public static function requireSafeDBName($database) {
2855 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2859 if (empty($matches)) {
2866 * Transform an array to a serialized string for database storage.
2868 * @param array|null $value
2869 * @param int $serializationType
2870 * @return string|null
2872 * @throws \Exception
2874 public static function serializeField($value, $serializationType) {
2875 if ($value === NULL) {
2878 switch ($serializationType) {
2879 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2880 return $value === [] ?
'' : CRM_Utils_Array
::implodePadded($value);
2882 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2883 return is_array($value) ?
implode(self
::VALUE_SEPARATOR
, $value) : $value;
2885 case self
::SERIALIZE_JSON
:
2886 return is_array($value) ?
json_encode($value) : $value;
2888 case self
::SERIALIZE_PHP
:
2889 return is_array($value) ?
serialize($value) : $value;
2891 case self
::SERIALIZE_COMMA
:
2892 return is_array($value) ?
implode(',', $value) : $value;
2895 throw new Exception('Unknown serialization method for field.');
2900 * Transform a serialized string from the database into an array.
2902 * @param string|null $value
2903 * @param $serializationType
2905 * @return array|null
2906 * @throws CRM_Core_Exception
2908 public static function unSerializeField($value, $serializationType) {
2909 if ($value === NULL) {
2912 if ($value === '') {
2915 switch ($serializationType) {
2916 case self
::SERIALIZE_SEPARATOR_BOOKEND
:
2917 return (array) CRM_Utils_Array
::explodePadded($value);
2919 case self
::SERIALIZE_SEPARATOR_TRIMMED
:
2920 return explode(self
::VALUE_SEPARATOR
, trim($value));
2922 case self
::SERIALIZE_JSON
:
2923 return strlen($value) ?
json_decode($value, TRUE) : [];
2925 case self
::SERIALIZE_PHP
:
2926 return strlen($value) ?
unserialize($value, ['allowed_classes' => FALSE]) : [];
2928 case self
::SERIALIZE_COMMA
:
2929 return explode(',', trim(str_replace(', ', '', $value)));
2932 throw new CRM_Core_Exception('Unknown serialization method for field.');
2939 public static function getEntityRefFilters() {
2944 * Get exportable fields with pseudoconstants rendered as an extra field.
2946 * @param string $baoClass
2950 public static function getExportableFieldsWithPseudoConstants($baoClass) {
2951 if (method_exists($baoClass, 'exportableFields')) {
2952 $fields = $baoClass::exportableFields();
2955 $fields = $baoClass::export();
2957 CRM_Core_DAO
::appendPseudoConstantsToFields($fields);
2962 * Remove item from static cache during update/delete operations
2964 private function clearDbColumnValueCache() {
2965 $daoName = get_class($this);
2966 while (strpos($daoName, '_BAO_') !== FALSE) {
2967 $daoName = get_parent_class($daoName);
2969 if (isset($this->id
)) {
2970 unset(self
::$_dbColumnValueCache[$daoName]['id'][$this->id
]);
2972 if (isset($this->name
)) {
2973 unset(self
::$_dbColumnValueCache[$daoName]['name'][$this->name
]);