3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Our base DAO class. All DAO classes should inherit from this class.
32 * @copyright CiviCRM LLC (c) 2004-2017
35 if (!defined('DB_DSN_MODE')) {
36 define('DB_DSN_MODE', 'auto');
39 require_once 'PEAR.php';
40 require_once 'DB/DataObject.php';
42 require_once 'CRM/Core/I18n.php';
47 class CRM_Core_DAO
extends DB_DataObject
{
53 static $_nullObject = NULL;
58 static $_nullArray = array();
60 static $_dbColumnValueCache = NULL;
61 const NOT_NULL
= 1, IS_NULL
= 2,
63 VALUE_SEPARATOR
= "\ 1",
64 BULK_INSERT_COUNT
= 200,
65 BULK_INSERT_HIGH_COUNT
= 200,
66 QUERY_FORMAT_WILDCARD
= 1,
67 QUERY_FORMAT_NO_QUOTES
= 2;
70 * Define entities that shouldn't be created or deleted when creating/ deleting
71 * test objects - this prevents world regions, countries etc from being added / deleted
74 static $_testEntitiesToSkip = array();
76 * The factory class for this application.
79 static $_factory = NULL;
81 static $_checkedSqlFunctionsExist = FALSE;
84 * https://issues.civicrm.org/jira/browse/CRM-17748
85 * internal variable for DAO to hold per-query settings
87 protected $_options = array();
92 * @return \CRM_Core_DAO
94 public function __construct() {
96 $this->__table
= $this->getTableName();
100 * Empty definition for virtual function.
102 public static function getTableName() {
107 * Initialize the DAO object.
110 * The database connection string.
112 public static function init($dsn) {
113 Civi
::$statics[__CLASS__
]['init'] = 1;
114 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
115 $options['database'] = $dsn;
116 if (defined('CIVICRM_DAO_DEBUG')) {
117 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
119 $factory = new CRM_Contact_DAO_Factory();
120 CRM_Core_DAO
::setFactory($factory);
121 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
122 CRM_Core_DAO
::executeQuery('SET SESSION sql_mode = STRICT_TRANS_TABLES');
124 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
125 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request
::id(), 'String')));
131 public static function getConnection() {
132 global $_DB_DATAOBJECT;
133 $dao = new CRM_Core_DAO();
134 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
138 * @param string $fieldName
140 * @param array $params
142 protected function assignTestFK($fieldName, $fieldDef, $params) {
143 $required = CRM_Utils_Array
::value('required', $fieldDef);
144 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
145 $dbName = $fieldDef['name'];
146 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
148 // skip the FK if it is not required
149 // if it's contact id we should create even if not required
150 // we'll have a go @ fetching first though
151 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
152 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
155 if (!$required && $dbName != 'contact_id') {
156 $fkDAO = new $FKClassName();
157 if ($fkDAO->find(TRUE)) {
158 $this->$dbName = $fkDAO->id
;
163 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
164 $depObject = new $FKClassName();
165 $depObject->find(TRUE);
166 $this->$dbName = $depObject->id
;
169 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
170 // FIXME: the fields() metadata is not specific enough
171 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
172 $this->$dbName = $depObject->id
;
176 //if it is required we need to generate the dependency object first
177 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
178 $this->$dbName = $depObject->id
;
184 * Generate and assign an arbitrary value to a field of a test object.
186 * @param string $fieldName
187 * @param array $fieldDef
188 * @param int $counter
189 * The globally-unique ID of the test object.
191 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
192 $dbName = $fieldDef['name'];
193 $daoName = get_class($this);
196 if (!$handled && $dbName == 'contact_sub_type') {
197 //coming up with a rule to set this is too complex let's not set it
201 // Pick an option value if needed
202 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
203 $options = $daoName::buildOptions($dbName, 'create');
205 $this->$dbName = key($options);
211 switch ($fieldDef['type']) {
212 case CRM_Utils_Type
::T_INT
:
213 case CRM_Utils_Type
::T_FLOAT
:
214 case CRM_Utils_Type
::T_MONEY
:
215 if (isset($fieldDef['precision'])) {
216 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
217 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
220 $this->$dbName = $counter;
224 case CRM_Utils_Type
::T_BOOLEAN
:
225 if (isset($fieldDef['default'])) {
226 $this->$dbName = $fieldDef['default'];
228 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
236 case CRM_Utils_Type
::T_DATE
:
237 case CRM_Utils_Type
::T_TIMESTAMP
:
238 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
239 $this->$dbName = '19700101';
240 if ($dbName == 'end_date') {
241 // put this in the future
242 $this->$dbName = '20200101';
246 case CRM_Utils_Type
::T_TIME
:
247 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
248 //$object->$dbName='000000';
250 case CRM_Utils_Type
::T_CCNUM
:
251 $this->$dbName = '4111 1111 1111 1111';
254 case CRM_Utils_Type
::T_URL
:
255 $this->$dbName = 'http://www.civicrm.org';
258 case CRM_Utils_Type
::T_STRING
:
259 case CRM_Utils_Type
::T_BLOB
:
260 case CRM_Utils_Type
::T_MEDIUMBLOB
:
261 case CRM_Utils_Type
::T_TEXT
:
262 case CRM_Utils_Type
::T_LONGTEXT
:
263 case CRM_Utils_Type
::T_EMAIL
:
265 // WAS: if (isset($value['enumValues'])) {
266 // TODO: see if this works with all pseudoconstants
267 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
268 if (isset($fieldDef['default'])) {
269 $this->$dbName = $fieldDef['default'];
272 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
273 if (is_array($options)) {
274 $this->$dbName = $options[0];
277 $defaultValues = explode(',', $options);
278 $this->$dbName = $defaultValues[0];
283 $this->$dbName = $dbName . '_' . $counter;
284 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
285 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
286 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
294 * Reset the DAO object.
296 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
298 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
300 public function reset() {
302 foreach (array_keys($this->table()) as $field) {
303 unset($this->$field);
307 * reset the various DB_DAO structures manually
309 $this->_query
= array();
316 * @param string $tableName
320 public static function getLocaleTableName($tableName) {
323 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
324 if (in_array($tableName, $tables)) {
325 return $tableName . $dbLocale;
332 * Execute a query by the current DAO, localizing it along the way (if needed).
334 * @param string $query
335 * The SQL query for execution.
336 * @param bool $i18nRewrite
337 * Whether to rewrite the query.
340 * the current DAO object after the query execution
342 public function query($query, $i18nRewrite = TRUE) {
343 // rewrite queries that should use $dbLocale-based views for multi-language installs
344 global $dbLocale, $_DB_DATAOBJECT;
346 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
347 $orig_options = $conn->options
;
348 $this->_setDBOptions($this->_options
);
350 if ($i18nRewrite and $dbLocale) {
351 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
354 $ret = parent
::query($query);
356 $this->_setDBOptions($orig_options);
361 * Static function to set the factory instance for this class.
363 * @param object $factory
364 * The factory application object.
366 public static function setFactory(&$factory) {
367 self
::$_factory = &$factory;
371 * Factory method to instantiate a new object from a table name.
373 * @param string $table
375 public function factory($table = '') {
376 if (!isset(self
::$_factory)) {
377 return parent
::factory($table);
380 return self
::$_factory->create($table);
384 * Initialization for all DAO objects. Since we access DB_DO programatically
385 * we need to set the links manually.
387 public function initialize() {
389 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
390 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
391 // This occurs very early in bootstrap - error handlers may not be wired up.
392 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
393 CRM_Utils_System
::civiExit();
398 * Defines the default key as 'id'.
403 public function keys() {
412 * Tells DB_DataObject which keys use autoincrement.
413 * 'id' is autoincrementing by default.
418 public function sequenceKey() {
419 static $sequenceKeys;
420 if (!isset($sequenceKeys)) {
421 $sequenceKeys = array('id', TRUE);
423 return $sequenceKeys;
427 * Returns list of FK relationships.
431 * Array of CRM_Core_Reference_Interface
433 public static function getReferenceColumns() {
438 * Returns all the column names of this table.
443 public static function &fields() {
449 * Get/set an associative array of table columns
454 public function table() {
455 $fields = &$this->fields();
459 foreach ($fields as $name => $value) {
460 $table[$value['name']] = $value['type'];
461 if (!empty($value['required'])) {
462 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
475 * @return CRM_Core_DAO
477 public function save($hook = TRUE) {
478 if (!empty($this->id
)) {
482 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
483 \Civi
::service('dispatcher')->dispatch("civi.dao.postUpdate", $event);
490 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
491 \Civi
::service('dispatcher')->dispatch("civi.dao.postInsert", $event);
497 CRM_Utils_Hook
::postSave($this);
504 * Deletes items from table which match current objects variables.
506 * Returns the true on success
510 * Designed to be extended
512 * $object = new mytable();
514 * echo $object->delete(); // builds a conditon
516 * $object = new mytable();
517 * $object->whereAdd('age > 12');
519 * $object->orderBy('age DESC');
520 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
522 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
523 * we will build the condition only using the whereAdd's. Default is to
524 * build the condition only using the object parameters.
526 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
528 public function delete($useWhere = FALSE) {
529 $result = parent
::delete($useWhere);
531 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
532 \Civi
::service('dispatcher')->dispatch("civi.dao.postDelete", $event);
539 * @param bool $created
541 public function log($created = FALSE) {
544 if (!$this->getLog()) {
549 $session = CRM_Core_Session
::singleton();
550 $cid = $session->get('userID');
553 // return is we dont have handle to FK
558 $dao = new CRM_Core_DAO_Log();
559 $dao->entity_table
= $this->getTableName();
560 $dao->entity_id
= $this->id
;
561 $dao->modified_id
= $cid;
562 $dao->modified_date
= date("YmdHis");
567 * Given an associative array of name/value pairs, extract all the values
568 * that belong to this object and initialize the object with said values
570 * @param array $params
571 * (reference ) associative array of name/value pairs.
574 * Did we copy all null values into the object
576 public function copyValues(&$params) {
577 $fields = &$this->fields();
579 foreach ($fields as $name => $value) {
580 $dbName = $value['name'];
581 if (array_key_exists($dbName, $params)) {
582 $pValue = $params[$dbName];
585 elseif (array_key_exists($name, $params)) {
586 $pValue = $params[$name];
593 // if there is no value then make the variable NULL
595 if ($pValue === '') {
596 $this->$dbName = 'null';
599 $this->$dbName = $pValue;
608 * Store all the values from this object in an associative array
609 * this is a destructive store, calling function is responsible
610 * for keeping sanity of id's.
612 * @param object $object
613 * The object that we are extracting data from.
614 * @param array $values
615 * (reference ) associative array of name/value pairs.
617 public static function storeValues(&$object, &$values) {
618 $fields = &$object->fields();
619 foreach ($fields as $name => $value) {
620 $dbName = $value['name'];
621 if (isset($object->$dbName) && $object->$dbName !== 'null') {
622 $values[$dbName] = $object->$dbName;
623 if ($name != $dbName) {
624 $values[$name] = $object->$dbName;
631 * Create an attribute for this specific field. We only do this for strings and text
633 * @param array $field
634 * The field under task.
637 * the attributes for the object
639 public static function makeAttribute($field) {
641 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
642 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
643 $size = CRM_Utils_Array
::value('size', $field);
644 if ($maxLength ||
$size) {
645 $attributes = array();
647 $attributes['maxlength'] = $maxLength;
650 $attributes['size'] = $size;
655 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
656 $rows = CRM_Utils_Array
::value('rows', $field);
660 $cols = CRM_Utils_Array
::value('cols', $field);
665 $attributes = array();
666 $attributes['rows'] = $rows;
667 $attributes['cols'] = $cols;
670 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
) {
671 $attributes['size'] = 6;
672 $attributes['maxlength'] = 14;
680 * Get the size and maxLength attributes for this text field.
681 * (or for all text fields) in the DAO object.
683 * @param string $class
685 * @param string $fieldName
686 * Field that i'm interested in or null if.
687 * you want the attributes for all DAO text fields
690 * assoc array of name => attribute pairs
692 public static function getAttribute($class, $fieldName = NULL) {
693 $object = new $class();
694 $fields = &$object->fields();
695 if ($fieldName != NULL) {
696 $field = CRM_Utils_Array
::value($fieldName, $fields);
697 return self
::makeAttribute($field);
700 $attributes = array();
701 foreach ($fields as $name => $field) {
702 $attribute = self
::makeAttribute($field);
704 $attributes[$name] = $attribute;
708 if (!empty($attributes)) {
720 public static function transaction($type) {
721 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
725 * Check if there is a record with the same name in the db.
727 * @param string $value
728 * The value of the field we are checking.
729 * @param string $daoName
730 * The dao object name.
731 * @param string $daoID
732 * The id of the object being updated. u can change your name.
733 * as long as there is no conflict
734 * @param string $fieldName
735 * The name of the field in the DAO.
737 * @param string $domainID
738 * The id of the domain. Object exists only for the given domain.
741 * true if object exists
743 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name', $domainID = NULL) {
744 $object = new $daoName();
745 $object->$fieldName = $value;
747 $object->domain_id
= $domainID;
750 if ($object->find(TRUE)) {
751 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
759 * Check if there is a given column in a specific table.
761 * @param string $tableName
762 * @param string $columnName
763 * @param bool $i18nRewrite
764 * Whether to rewrite the query on multilingual setups.
767 * true if exists, else false
769 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
775 $params = array(1 => array($columnName, 'String'));
776 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
777 $result = $dao->fetch() ?
TRUE : FALSE;
783 * Scans all the tables using a slow query and table name.
787 public static function getTableNames() {
788 $dao = CRM_Core_DAO
::executeQuery(
790 FROM information_schema.TABLES
791 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
792 AND TABLE_NAME LIKE 'civicrm_%'
793 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
794 AND TABLE_NAME NOT LIKE '%_temp%'
797 while ($dao->fetch()) {
798 $values[] = $dao->TABLE_NAME
;
805 * @param int $maxTablesToCheck
809 public static function isDBMyISAM($maxTablesToCheck = 10) {
810 return CRM_Core_DAO
::singleValueQuery(
812 FROM information_schema.TABLES
813 WHERE ENGINE = 'MyISAM'
814 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
815 AND TABLE_NAME LIKE 'civicrm_%'
816 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
817 AND TABLE_NAME NOT LIKE '%_temp%'
822 * Get the name of the CiviCRM database.
826 public static function getDatabaseName() {
827 $daoObj = new CRM_Core_DAO();
828 return $daoObj->database();
832 * Checks if a constraint exists for a specified table.
834 * @param string $tableName
835 * @param string $constraint
838 * true if constraint exists, false otherwise
840 public static function checkConstraintExists($tableName, $constraint) {
841 static $show = array();
843 if (!array_key_exists($tableName, $show)) {
844 $query = "SHOW CREATE TABLE $tableName";
845 $dao = CRM_Core_DAO
::executeQuery($query);
847 if (!$dao->fetch()) {
848 CRM_Core_Error
::fatal();
852 $show[$tableName] = $dao->Create_Table
;
855 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
859 * Checks if CONSTRAINT keyword exists for a specified table.
861 * @param array $tables
866 * true if CONSTRAINT keyword exists, false otherwise
868 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
870 foreach ($tables as $tableName) {
871 if (!array_key_exists($tableName, $show)) {
872 $query = "SHOW CREATE TABLE $tableName";
873 $dao = CRM_Core_DAO
::executeQuery($query);
875 if (!$dao->fetch()) {
876 CRM_Core_Error
::fatal();
880 $show[$tableName] = $dao->Create_Table
;
883 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
884 if ($result == TRUE) {
895 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
896 * for a specified column of a table.
898 * @param string $tableName
899 * @param string $columnName
902 * true if in format, false otherwise
904 public static function checkFKConstraintInFormat($tableName, $columnName) {
905 static $show = array();
907 if (!array_key_exists($tableName, $show)) {
908 $query = "SHOW CREATE TABLE $tableName";
909 $dao = CRM_Core_DAO
::executeQuery($query);
911 if (!$dao->fetch()) {
912 CRM_Core_Error
::fatal();
916 $show[$tableName] = $dao->Create_Table
;
918 $constraint = "`FK_{$tableName}_{$columnName}`";
919 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
920 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
924 * Check whether a specific column in a specific table has always the same value.
926 * @param string $tableName
927 * @param string $columnName
928 * @param string $columnValue
931 * true if the value is always $columnValue, false otherwise
933 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
934 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
935 $dao = CRM_Core_DAO
::executeQuery($query);
936 $result = $dao->fetch() ?
FALSE : TRUE;
942 * Check whether a specific column in a specific table is always NULL.
944 * @param string $tableName
945 * @param string $columnName
948 * true if if the value is always NULL, false otherwise
950 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
951 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
952 $dao = CRM_Core_DAO
::executeQuery($query);
953 $result = $dao->fetch() ?
FALSE : TRUE;
959 * Check if there is a given table in the database.
961 * @param string $tableName
964 * true if exists, else false
966 public static function checkTableExists($tableName) {
971 $params = array(1 => array($tableName, 'String'));
973 $dao = CRM_Core_DAO
::executeQuery($query, $params);
974 $result = $dao->fetch() ?
TRUE : FALSE;
984 public function checkVersion($version) {
989 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
990 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
994 * Find a DAO object for the given ID and return it.
997 * Id of the DAO object being searched for.
1000 * Object of the type of the class that called this function.
1002 public static function findById($id) {
1003 $object = new static();
1005 if (!$object->find(TRUE)) {
1006 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1012 * Returns all results as array-encoded records.
1016 public function fetchAll() {
1018 while ($this->fetch()) {
1019 $result[] = $this->toArray();
1025 * Get all the result records as mapping between columns.
1027 * @param string $keyColumn
1029 * @param string $valueColumn
1032 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1034 public function fetchMap($keyColumn, $valueColumn) {
1036 while ($this->fetch()) {
1037 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1043 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1045 * @param string $daoName
1046 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1047 * @param int $searchValue
1048 * Value of the column you want to search by.
1049 * @param string $returnColumn
1050 * Name of the column you want to GET the value of.
1051 * @param string $searchColumn
1052 * Name of the column you want to search by.
1053 * @param bool $force
1054 * Skip use of the cache.
1056 * @return string|null
1057 * Value of $returnColumn in the retrieved record
1059 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1061 empty($searchValue) ||
1062 trim(strtolower($searchValue)) == 'null'
1064 // adding this year since developers forget to check for an id
1065 // or for the 'null' (which is a bad DAO kludge)
1066 // and hence we get the first value in the db
1067 CRM_Core_Error
::fatal();
1070 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1071 if (self
::$_dbColumnValueCache === NULL) {
1072 self
::$_dbColumnValueCache = array();
1075 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1076 $object = new $daoName();
1077 $object->$searchColumn = $searchValue;
1078 $object->selectAdd();
1079 $object->selectAdd($returnColumn);
1082 if ($object->find(TRUE)) {
1083 $result = $object->$returnColumn;
1087 self
::$_dbColumnValueCache[$cacheKey] = $result;
1089 return self
::$_dbColumnValueCache[$cacheKey];
1093 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1095 * @param string $daoName
1096 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1097 * @param int $searchValue
1098 * Value of the column you want to search by.
1099 * @param string $setColumn
1100 * Name of the column you want to SET the value of.
1101 * @param string $setValue
1102 * SET the setColumn to this value.
1103 * @param string $searchColumn
1104 * Name of the column you want to search by.
1107 * true if we found and updated the object, else false
1109 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1110 $object = new $daoName();
1111 $object->selectAdd();
1112 $object->selectAdd("$searchColumn, $setColumn");
1113 $object->$searchColumn = $searchValue;
1115 if ($object->find(TRUE)) {
1116 $object->$setColumn = $setValue;
1117 if ($object->save()) {
1128 * @param array|object $sort either array or CRM_Utils_Sort
1129 * @param string $default
1130 * Default sort value.
1135 public static function getSortString($sort, $default = NULL) {
1136 // check if sort is of type CRM_Utils_Sort
1137 if (is_a($sort, 'CRM_Utils_Sort')) {
1138 return $sort->orderBy();
1141 // is it an array specified as $field => $sortDirection ?
1143 foreach ($sort as $k => $v) {
1144 $sortString .= "$k $v,";
1146 return rtrim($sortString, ',');
1152 * Fetch object based on array of properties.
1154 * @param string $daoName
1155 * Name of the dao object.
1156 * @param array $params
1157 * (reference ) an assoc array of name/value pairs.
1158 * @param array $defaults
1159 * (reference ) an assoc array to hold the flattened values.
1160 * @param array $returnProperities
1161 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1164 * an object of type referenced by daoName
1166 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1167 $object = new $daoName();
1168 $object->copyValues($params);
1170 // return only specific fields if returnproperties are sent
1171 if (!empty($returnProperities)) {
1172 $object->selectAdd();
1173 $object->selectAdd(implode(',', $returnProperities));
1176 if ($object->find(TRUE)) {
1177 self
::storeValues($object, $defaults);
1184 * Delete the object records that are associated with this contact.
1186 * @param string $daoName
1187 * Name of the dao object.
1188 * @param int $contactId
1189 * Id of the contact to delete.
1191 public static function deleteEntityContact($daoName, $contactId) {
1192 $object = new $daoName();
1194 $object->entity_table
= 'civicrm_contact';
1195 $object->entity_id
= $contactId;
1200 * Execute an unbuffered query.
1202 * This is a wrapper around new functionality exposed with CRM-17748.
1204 * @param string $query query to be executed
1206 * @param array $params
1207 * @param bool $abort
1208 * @param null $daoName
1209 * @param bool $freeDAO
1210 * @param bool $i18nRewrite
1211 * @param bool $trapException
1213 * @return CRM_Core_DAO
1214 * Object that points to an unbuffered result set
1216 static public function executeUnbufferedQuery(
1222 $i18nRewrite = TRUE,
1223 $trapException = FALSE
1225 $queryStr = self
::composeQuery($query, $params, $abort);
1226 //CRM_Core_Error::debug( 'q', $queryStr );
1228 $dao = new CRM_Core_DAO();
1231 $dao = new $daoName();
1234 if ($trapException) {
1235 CRM_Core_Error
::ignoreException();
1238 // set the DAO object to use an unbuffered query
1239 $dao->setOptions(array('result_buffering' => 0));
1241 $result = $dao->query($queryStr, $i18nRewrite);
1243 if ($trapException) {
1244 CRM_Core_Error
::setCallback();
1247 if (is_a($result, 'DB_Error')) {
1251 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1255 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1257 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1267 * @param string $query
1268 * Query to be executed.
1270 * @param array $params
1271 * @param bool $abort
1272 * @param null $daoName
1273 * @param bool $freeDAO
1274 * @param bool $i18nRewrite
1275 * @param bool $trapException
1277 * @return CRM_Core_DAO|object
1278 * object that holds the results of the query
1279 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1280 * out all the properties that are not part of the DAO
1282 public static function &executeQuery(
1288 $i18nRewrite = TRUE,
1289 $trapException = FALSE
1291 $queryStr = self
::composeQuery($query, $params, $abort);
1294 $dao = new CRM_Core_DAO();
1297 $dao = new $daoName();
1300 if ($trapException) {
1301 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1304 $result = $dao->query($queryStr, $i18nRewrite);
1306 if (is_a($result, 'DB_Error')) {
1311 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1313 // we typically do this for insert/update/delete statements OR if explicitly asked to
1321 * Execute a query and get the single result.
1323 * @param string $query
1324 * Query to be executed.
1325 * @param array $params
1326 * @param bool $abort
1327 * @param bool $i18nRewrite
1328 * @return string|null
1329 * the result of the query if any
1332 public static function &singleValueQuery(
1338 $queryStr = self
::composeQuery($query, $params, $abort);
1340 static $_dao = NULL;
1343 $_dao = new CRM_Core_DAO();
1346 $_dao->query($queryStr, $i18nRewrite);
1348 $result = $_dao->getDatabaseResult();
1351 $row = $result->fetchRow();
1361 * Compose the query by merging the parameters into it.
1363 * @param string $query
1364 * @param array $params
1365 * @param bool $abort
1370 public static function composeQuery($query, $params, $abort = TRUE) {
1372 foreach ($params as $key => $item) {
1373 if (is_numeric($key)) {
1374 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1375 $item[0] = self
::escapeString($item[0]);
1376 if ($item[1] == 'String' ||
1377 $item[1] == 'Memo' ||
1380 // Support class constants stipulating wildcard characters and/or
1381 // non-quoting of strings. Also support legacy code which may be
1382 // passing in TRUE or 1 for $item[2], which used to indicate the
1383 // use of wildcard characters.
1384 if (!empty($item[2])) {
1385 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1386 $item[0] = "'%{$item[0]}%'";
1388 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1389 $item[0] = "'{$item[0]}'";
1393 $item[0] = "'{$item[0]}'";
1397 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1398 strlen($item[0]) == 0
1403 $tr['%' . $key] = $item[0];
1406 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1411 return strtr($query, $tr);
1417 public static function freeResult($ids = NULL) {
1418 global $_DB_DATAOBJECT;
1421 if (!$_DB_DATAOBJECT ||
1422 !isset($_DB_DATAOBJECT['RESULTS'])
1426 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1429 foreach ($ids as $id) {
1430 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1431 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1432 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1435 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1436 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1442 * make a shallow copy of an object.
1443 * and all the fields in the object
1445 * @param string $daoName
1447 * @param array $criteria
1448 * Array of all the fields & values.
1449 * on which basis to copy
1450 * @param array $newData
1451 * Array of all the fields & values.
1452 * to be copied besides the other fields
1453 * @param string $fieldsFix
1454 * Array of fields that you want to prefix/suffix/replace.
1455 * @param string $blockCopyOfDependencies
1456 * Fields that you want to block from.
1460 * @return CRM_Core_DAO
1461 * the newly created copy of the object
1463 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1464 $object = new $daoName();
1466 $object->id
= $criteria['id'];
1469 foreach ($criteria as $key => $value) {
1470 $object->$key = $value;
1475 while ($object->fetch()) {
1477 // all the objects except with $blockCopyOfDependencies set
1478 // be copied - addresses #CRM-1962
1480 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1484 $newObject = new $daoName();
1486 $fields = &$object->fields();
1487 if (!is_array($fieldsFix)) {
1488 $fieldsToPrefix = array();
1489 $fieldsToSuffix = array();
1490 $fieldsToReplace = array();
1492 if (!empty($fieldsFix['prefix'])) {
1493 $fieldsToPrefix = $fieldsFix['prefix'];
1495 if (!empty($fieldsFix['suffix'])) {
1496 $fieldsToSuffix = $fieldsFix['suffix'];
1498 if (!empty($fieldsFix['replace'])) {
1499 $fieldsToReplace = $fieldsFix['replace'];
1502 foreach ($fields as $name => $value) {
1503 if ($name == 'id' ||
$value['name'] == 'id') {
1504 // copy everything but the id!
1508 $dbName = $value['name'];
1509 $type = CRM_Utils_Type
::typeToString($value['type']);
1510 $newObject->$dbName = $object->$dbName;
1511 if (isset($fieldsToPrefix[$dbName])) {
1512 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1514 if (isset($fieldsToSuffix[$dbName])) {
1515 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1517 if (isset($fieldsToReplace[$dbName])) {
1518 $newObject->$dbName = $fieldsToReplace[$dbName];
1521 if ($type == 'Timestamp' ||
$type == 'Date') {
1522 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1526 foreach ($newData as $k => $v) {
1527 $newObject->$k = $v;
1537 * Cascade update through related entities.
1539 * @param string $daoName
1542 * @param array $newData
1544 * @return CRM_Core_DAO|null
1546 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1547 $object = new $daoName();
1548 $object->id
= $fromId;
1550 if ($object->find(TRUE)) {
1551 $newObject = new $daoName();
1552 $newObject->id
= $toId;
1554 if ($newObject->find(TRUE)) {
1555 $fields = &$object->fields();
1556 foreach ($fields as $name => $value) {
1557 if ($name == 'id' ||
$value['name'] == 'id') {
1558 // copy everything but the id!
1562 $colName = $value['name'];
1563 $newObject->$colName = $object->$colName;
1565 if (substr($name, -5) == '_date' ||
1566 substr($name, -10) == '_date_time'
1568 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1571 foreach ($newData as $k => $v) {
1572 $newObject->$k = $v;
1582 * Given the component id, compute the contact id
1583 * since its used for things like send email
1585 * @param $componentIDs
1586 * @param string $tableName
1590 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1591 $contactIDs = array();
1593 if (empty($componentIDs)) {
1597 $IDs = implode(',', $componentIDs);
1601 WHERE id IN ( $IDs )
1604 $dao = CRM_Core_DAO
::executeQuery($query);
1605 while ($dao->fetch()) {
1606 $contactIDs[] = $dao->contact_id
;
1612 * Fetch object based on array of properties.
1614 * @param string $daoName
1615 * Name of the dao object.
1616 * @param string $fieldIdName
1617 * @param int $fieldId
1619 * @param array $returnProperities
1620 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1623 * an object of type referenced by daoName
1625 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1626 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1627 $object = new $daoName();
1628 $object->$fieldIdName = $fieldId;
1630 // return only specific fields if returnproperties are sent
1631 if (!empty($returnProperities)) {
1632 $object->selectAdd();
1633 $object->selectAdd('id');
1634 $object->selectAdd(implode(',', $returnProperities));
1638 while ($object->fetch()) {
1639 $defaults = array();
1640 self
::storeValues($object, $defaults);
1641 $details[$object->id
] = $defaults;
1647 public static function dropAllTables() {
1649 // first drop all the custom tables we've created
1650 CRM_Core_BAO_CustomGroup
::dropAllTables();
1652 // drop all multilingual views
1653 CRM_Core_I18n_Schema
::dropAllViews();
1655 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1656 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1657 '..' . DIRECTORY_SEPARATOR
.
1658 '..' . DIRECTORY_SEPARATOR
.
1659 'sql' . DIRECTORY_SEPARATOR
.
1660 'civicrm_drop.mysql'
1669 public static function escapeString($string) {
1670 static $_dao = NULL;
1672 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1673 // has been installed), then we fallback DB-less str_replace escaping, as
1674 // we can't use mysqli_real_escape_string, as there is no DB connection.
1675 // Note: In typical usage, escapeString() will only check one conditional
1676 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1677 if (!defined('CIVICRM_DSN')) {
1678 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1679 // list of characters mysqli_real_escape_string escapes.
1680 $search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
1681 $replace = array("\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z");
1682 return str_replace($search, $replace, $string);
1684 $_dao = new CRM_Core_DAO();
1686 return $_dao->escape($string);
1690 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1692 * @param array $strings
1693 * @param string $default
1694 * the value to use if $strings has no elements.
1696 * eg "abc","def","ghi"
1698 public static function escapeStrings($strings, $default = NULL) {
1699 static $_dao = NULL;
1701 $_dao = new CRM_Core_DAO();
1704 if (empty($strings)) {
1708 $escapes = array_map(array($_dao, 'escape'), $strings);
1709 return '"' . implode('","', $escapes) . '"';
1717 public static function escapeWildCardString($string) {
1719 // ensure we escape the single characters % and _ which are mysql wild
1720 // card characters and could come in via sortByCharacter
1721 // note that mysql does not escape these characters
1722 if ($string && in_array($string,
1723 array('%', '_', '%%', '_%')
1726 return '\\' . $string;
1729 return self
::escapeString($string);
1733 * Creates a test object, including any required objects it needs via recursion
1734 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1735 * ONLY USE FOR TESTING
1737 * @param string $daoName
1738 * @param array $params
1739 * @param int $numObjects
1740 * @param bool $createOnly
1742 * @return object|array|NULL
1743 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1745 public static function createTestObject(
1751 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1752 // so we re-set here in case
1753 $config = CRM_Core_Config
::singleton();
1754 $config->backtrace
= TRUE;
1756 static $counter = 0;
1757 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1758 'CRM_Core_DAO_Worldregion',
1759 'CRM_Core_DAO_StateProvince',
1760 'CRM_Core_DAO_Country',
1761 'CRM_Core_DAO_Domain',
1762 'CRM_Financial_DAO_FinancialType',
1763 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1766 // Prefer to instantiate BAO's instead of DAO's (when possible)
1767 // so that assignTestValue()/assignTestFK() can be overloaded.
1768 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1769 if (class_exists($baoName)) {
1770 $daoName = $baoName;
1773 for ($i = 0; $i < $numObjects; ++
$i) {
1776 /** @var CRM_Core_DAO $object */
1777 $object = new $daoName();
1779 $fields = &$object->fields();
1780 foreach ($fields as $fieldName => $fieldDef) {
1781 $dbName = $fieldDef['name'];
1782 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1783 $required = CRM_Utils_Array
::value('required', $fieldDef);
1785 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1786 $object->$dbName = $params[$dbName];
1789 elseif ($dbName != 'id') {
1790 if ($FKClassName != NULL) {
1791 $object->assignTestFK($fieldName, $fieldDef, $params);
1795 $object->assignTestValue($fieldName, $fieldDef, $counter);
1803 $objects[$i] = $object;
1813 elseif ($numObjects == 1) {
1822 * Deletes the this object plus any dependent objects that are associated with it.
1823 * ONLY USE FOR TESTING
1825 * @param string $daoName
1826 * @param array $params
1828 public static function deleteTestObjects($daoName, $params = array()) {
1829 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1830 // so we re-set here in case
1831 $config = CRM_Core_Config
::singleton();
1832 $config->backtrace
= TRUE;
1834 $object = new $daoName();
1835 $object->id
= CRM_Utils_Array
::value('id', $params);
1837 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1838 if ($object->find(TRUE)) {
1840 $fields = &$object->fields();
1841 foreach ($fields as $name => $value) {
1843 $dbName = $value['name'];
1845 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1846 $required = CRM_Utils_Array
::value('required', $value);
1847 if ($FKClassName != NULL
1849 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1850 && ($required ||
$dbName == 'contact_id')
1851 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1852 // to make this test process pass - line below makes pass for now
1853 && $dbName != 'member_of_contact_id'
1855 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1862 foreach ($deletions as $deletion) {
1863 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1868 * Set defaults when creating new entity.
1869 * (don't call this set defaults as already in use with different signature in some places)
1871 * @param array $params
1874 public static function setCreateDefaults(&$params, $defaults) {
1875 if (!empty($params['id'])) {
1878 foreach ($defaults as $key => $value) {
1879 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1880 $params[$key] = $value;
1886 * @param string $prefix
1887 * @param bool $addRandomString
1888 * @param null $string
1892 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1893 $tableName = $prefix . "_temp";
1895 if ($addRandomString) {
1897 $tableName .= "_" . $string;
1900 $tableName .= "_" . md5(uniqid('', TRUE));
1908 * @param bool $trigger
1912 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1913 if (\Civi
::settings()->get('logging_no_trigger_permission')) {
1916 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1918 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1919 CRM_Core_TemporaryErrorScope
::ignoreException();
1920 $dao = new CRM_Core_DAO();
1922 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1923 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1929 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1930 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1932 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1937 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1938 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1940 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1947 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1948 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1957 * @param null $message
1958 * @param bool $printDAO
1960 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1961 CRM_Utils_System
::xMemory("{$message}: ");
1964 global $_DB_DATAOBJECT;
1966 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1967 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1969 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1974 * Build a list of triggers via hook and add them to (err, reconcile them
1975 * with) the database.
1977 * @param string $tableName
1978 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1979 * @param bool $force
1984 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1985 Civi
::service('sql_triggers')->rebuild($tableName, $force);
1989 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1990 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1991 * TODO: Alternative solutions might be
1992 * * Stop using functions and find another way to strip numeric characters from phones
1993 * * Give better error messages (currently a missing fn fatals with "unknown error")
1995 public static function checkSqlFunctionsExist() {
1996 if (!self
::$_checkedSqlFunctionsExist) {
1997 self
::$_checkedSqlFunctionsExist = TRUE;
1998 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1999 if (!$dao->fetch()) {
2000 self
::triggerRebuild();
2006 * Wrapper function to drop triggers.
2008 * @param string $tableName
2009 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2012 public static function dropTriggers($tableName = NULL) {
2013 Civi
::service('sql_triggers')->dropTriggers($tableName);
2017 * @param array $info
2018 * per hook_civicrm_triggerInfo.
2019 * @param string $onlyTableName
2020 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2023 public static function createTriggers(&$info, $onlyTableName = NULL) {
2024 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2028 * Given a list of fields, create a list of references.
2030 * @param string $className
2031 * BAO/DAO class name.
2032 * @return array<CRM_Core_Reference_Interface>
2034 public static function createReferenceColumns($className) {
2036 $fields = $className::fields();
2037 foreach ($fields as $field) {
2038 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2039 $result[] = new CRM_Core_Reference_OptionValue(
2040 $className::getTableName(),
2042 'civicrm_option_value',
2043 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2044 $field['pseudoconstant']['optionGroupName']
2052 * Find all records which refer to this entity.
2055 * Array of objects referencing this
2057 public function findReferences() {
2058 $links = self
::getReferencesToTable(static::getTableName());
2060 $occurrences = array();
2061 foreach ($links as $refSpec) {
2062 /** @var $refSpec CRM_Core_Reference_Interface */
2063 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2064 $result = $refSpec->findReferences($this);
2066 while ($result->fetch()) {
2067 $obj = new $daoName();
2068 $obj->id
= $result->id
;
2069 $occurrences[] = $obj;
2074 return $occurrences;
2079 * each item has keys:
2083 * - table: string|null SQL table name
2084 * - key: string|null SQL column name
2086 public function getReferenceCounts() {
2087 $links = self
::getReferencesToTable(static::getTableName());
2090 foreach ($links as $refSpec) {
2091 /** @var $refSpec CRM_Core_Reference_Interface */
2092 $count = $refSpec->getReferenceCount($this);
2093 if ($count['count'] != 0) {
2098 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2099 /** @var $component CRM_Core_Component_Info */
2100 $counts = array_merge($counts, $component->getReferenceCounts($this));
2102 CRM_Utils_Hook
::referenceCounts($this, $counts);
2108 * List all tables which have hard foreign keys to this table.
2110 * For now, this returns a description of every entity_id/entity_table
2112 * TODO: filter dynamic entity references on the $tableName, based on
2113 * schema metadata in dynamicForeignKey which enumerates a restricted
2114 * set of possible entity_table's.
2116 * @param string $tableName
2117 * Table referred to.
2120 * structure of table and column, listing every table with a
2121 * foreign key reference to $tableName, and the column where the key appears.
2123 public static function getReferencesToTable($tableName) {
2124 $refsFound = array();
2125 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2126 $links = $daoClassName::getReferenceColumns();
2127 $daoTableName = $daoClassName::getTableName();
2129 foreach ($links as $refSpec) {
2130 /** @var $refSpec CRM_Core_Reference_Interface */
2131 if ($refSpec->matchesTargetTable($tableName)) {
2132 $refsFound[] = $refSpec;
2140 * Lookup the value of a MySQL global configuration variable.
2142 * @param string $name
2143 * E.g. "thread_stack".
2144 * @param mixed $default
2147 public static function getGlobalSetting($name, $default = NULL) {
2148 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2149 // that has been reported to fail under MySQL 5.0 for OS X
2150 $escapedName = self
::escapeString($name);
2151 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2152 if ($dao->fetch()) {
2162 * Update the fields array to also hold keys for pseudoconstant fields that relate to contained fields.
2164 * This is relevant where we want to offer both the ID field and the label field
2165 * as an option, e.g. search builder.
2167 * It is currently limited for optionGroupName for purposes keeping the scope of the
2168 * change small, but is appropriate for other sorts of pseudoconstants.
2170 * @param array $fields
2172 protected static function appendPseudoConstantsToFields(&$fields) {
2173 foreach ($fields as $field) {
2174 if (!empty($field['pseudoconstant']) && !empty($field['pseudoconstant']['optionGroupName'])) {
2175 $fields[$field['pseudoconstant']['optionGroupName']] = array(
2176 'title' => CRM_Core_BAO_OptionGroup
::getTitleByName($field['pseudoconstant']['optionGroupName']),
2177 'name' => $field['pseudoconstant']['optionGroupName'],
2178 'data_type' => CRM_Utils_Type
::T_STRING
,
2185 * Get options for the called BAO object's field.
2187 * This function can be overridden by each BAO to add more logic related to context.
2188 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2190 * @param string $fieldName
2191 * @param string $context
2192 * @see CRM_Core_DAO::buildOptionsContext
2193 * @param array $props
2194 * whatever is known about this bao object.
2196 * @return array|bool
2198 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2199 // If a given bao does not override this function
2200 $baoName = get_called_class();
2201 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2205 * Populate option labels for this object's fields.
2207 * @throws exception if called directly on the base class
2209 public function getOptionLabels() {
2210 $fields = $this->fields();
2211 if ($fields === NULL) {
2212 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2214 foreach ($fields as $field) {
2215 $name = CRM_Utils_Array
::value('name', $field);
2216 if ($name && isset($this->$name)) {
2217 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2218 if ($label !== FALSE) {
2219 // Append 'label' onto the field name
2220 $labelName = $name . '_label';
2221 $this->$labelName = $label;
2228 * Provides documentation and validation for the buildOptions $context param
2230 * @param string $context
2235 public static function buildOptionsContext($context = NULL) {
2237 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2238 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2239 'search' => "search: searchable options are returned; labels are translated.",
2240 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2241 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2242 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2244 // Validation: enforce uniformity of this param
2245 if ($context !== NULL && !isset($contexts[$context])) {
2246 throw new Exception("'$context' is not a valid context for buildOptions.");
2252 * @param string $fieldName
2253 * @return bool|array
2255 public function getFieldSpec($fieldName) {
2256 $fields = $this->fields();
2257 $fieldKeys = $this->fieldKeys();
2259 // Support "unique names" as well as sql names
2260 $fieldKey = $fieldName;
2261 if (empty($fields[$fieldKey])) {
2262 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2264 // If neither worked then this field doesn't exist. Return false.
2265 if (empty($fields[$fieldKey])) {
2268 return $fields[$fieldKey];
2272 * Get SQL where clause for SQL filter syntax input parameters.
2274 * SQL version of api function to assign filters to the DAO based on the syntax
2275 * $field => array('IN' => array(4,6,9))
2277 * $field => array('LIKE' => array('%me%))
2280 * @param string $fieldName
2282 * @param array $filter
2283 * filter to be applied indexed by operator.
2284 * @param string $type
2285 * type of field (not actually used - nor in api @todo ).
2286 * @param string $alias
2287 * alternative field name ('as') @todo- not actually used.
2288 * @param bool $returnSanitisedArray
2289 * Return a sanitised array instead of a clause.
2290 * this is primarily so we can add filters @ the api level to the Query object based fields
2294 * @return NULL|string|array
2295 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2296 * depending on whether it is supported as yet
2298 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2299 foreach ($filter as $operator => $criteria) {
2300 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2301 switch ($operator) {
2305 if (!$returnSanitisedArray) {
2306 return (sprintf('%s %s', $fieldName, $operator));
2309 return (sprintf('%s %s ', $fieldName, $operator));
2313 // ternary operators
2316 if (empty($criteria[0]) ||
empty($criteria[1])) {
2317 throw new Exception("invalid criteria for $operator");
2319 if (!$returnSanitisedArray) {
2320 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2323 return NULL; // not yet implemented (tests required to implement)
2330 if (empty($criteria)) {
2331 throw new Exception("invalid criteria for $operator");
2333 $escapedCriteria = array_map(array(
2337 if (!$returnSanitisedArray) {
2338 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2340 return $escapedCriteria;
2345 if (!$returnSanitisedArray) {
2346 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2349 return NULL; // not yet implemented (tests required to implement)
2357 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2358 * support for other syntaxes is discussed in ticket but being put off for now
2361 public static function acceptedSQLOperators() {
2382 * SQL has a limit of 64 characters on various names:
2383 * table name, trigger name, column name ...
2385 * For custom groups and fields we generated names from user entered input
2386 * which can be longer than this length, this function helps with creating
2387 * strings that meet various criteria.
2389 * @param string $string
2390 * The string to be shortened.
2391 * @param int $length
2392 * The max length of the string.
2394 * @param bool $makeRandom
2398 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2399 // early return for strings that meet the requirements
2400 if (strlen($string) <= $length) {
2404 // easy return for calls that dont need a randomized uniq string
2406 return substr($string, 0, $length);
2409 // the string is longer than the length and we need a uniq string
2410 // for the same tablename we need the same uniq string every time
2411 // hence we use md5 on the string, which is not random
2412 // we'll append 8 characters to the end of the tableName
2413 $md5string = substr(md5($string), 0, 8);
2414 return substr($string, 0, $length - 8) . "_{$md5string}";
2418 * https://issues.civicrm.org/jira/browse/CRM-17748
2419 * Sets the internal options to be used on a query
2421 * @param array $options
2424 public function setOptions($options) {
2425 if (is_array($options)) {
2426 $this->_options
= $options;
2431 * https://issues.civicrm.org/jira/browse/CRM-17748
2432 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2434 * @param array $options
2437 protected function _setDBOptions($options) {
2438 global $_DB_DATAOBJECT;
2440 if (is_array($options) && count($options)) {
2441 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2442 foreach ($options as $option_name => $option_value) {
2443 $conn->setOption($option_name, $option_value);
2450 * @param array $params
2452 public function setApiFilter(&$params) {
2456 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2458 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2461 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2465 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2469 public function addSelectWhereClause() {
2471 $fields = $this->fields();
2472 foreach ($fields as $fieldName => $field) {
2473 // Clause for contact-related entities like Email, Relationship, etc.
2474 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2475 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2477 // Clause for an entity_table/entity_id combo
2478 if ($fieldName == 'entity_id' && isset($fields['entity_table'])) {
2479 $relatedClauses = array();
2480 $relatedEntities = $this->buildOptions('entity_table', 'get');
2481 foreach ((array) $relatedEntities as $table => $ent) {
2483 $ent = CRM_Core_DAO_AllCoreTables
::getBriefName(CRM_Core_DAO_AllCoreTables
::getClassForTable($table));
2484 $subquery = CRM_Utils_SQL
::mergeSubquery($ent);
2486 $relatedClauses[] = "(entity_table = '$table' AND entity_id " . implode(' AND entity_id ', $subquery) . ")";
2489 $relatedClauses[] = "(entity_table = '$table')";
2493 if ($relatedClauses) {
2494 $clauses['id'] = 'IN (SELECT id FROM `' . $this->tableName() . '` WHERE (' . implode(') OR (', $relatedClauses) . '))';
2498 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2503 * This returns the final permissioned query string for this entity
2505 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2507 * @param string $tableAlias
2510 public static function getSelectWhereClause($tableAlias = NULL) {
2511 $bao = new static();
2512 if ($tableAlias === NULL) {
2513 $tableAlias = $bao->tableName();
2516 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2517 $clauses[$field] = NULL;
2519 $clauses[$field] = "`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals);
2526 * ensure database name is 'safe', i.e. only contains word characters (includes underscores)
2527 * and dashes, and contains at least one [a-z] case insenstive.
2533 public static function requireSafeDBName($database) {
2536 "/^[\w\-]*[a-z]+[\w\-]*$/i",
2540 if (empty($matches)) {