3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
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
{
50 * A null object so we can pass it as reference if / when needed
52 static $_nullObject = NULL;
53 static $_nullArray = array();
55 static $_dbColumnValueCache = NULL;
56 const NOT_NULL
= 1, IS_NULL
= 2,
58 VALUE_SEPARATOR
= "\ 1",
59 BULK_INSERT_COUNT
= 200,
60 BULK_INSERT_HIGH_COUNT
= 200,
61 QUERY_FORMAT_WILDCARD
= 1,
62 QUERY_FORMAT_NO_QUOTES
= 2;
65 * Define entities that shouldn't be created or deleted when creating/ deleting
66 * test objects - this prevents world regions, countries etc from being added / deleted
69 static $_testEntitiesToSkip = array();
71 * The factory class for this application.
74 static $_factory = NULL;
76 static $_checkedSqlFunctionsExist = FALSE;
79 * https://issues.civicrm.org/jira/browse/CRM-17748
80 * internal variable for DAO to hold per-query settings
82 protected $_options = array();
87 * @return \CRM_Core_DAO
89 public function __construct() {
91 $this->__table
= $this->getTableName();
95 * Empty definition for virtual function.
97 public static function getTableName() {
102 * Initialize the DAO object.
105 * The database connection string.
107 public static function init($dsn) {
108 Civi
::$statics[__CLASS__
]['init'] = 1;
109 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
110 $options['database'] = $dsn;
111 if (defined('CIVICRM_DAO_DEBUG')) {
112 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
114 $factory = new CRM_Contact_DAO_Factory();
115 CRM_Core_DAO
::setFactory($factory);
116 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
117 CRM_Core_DAO
::executeQuery('SET SESSION sql_mode = STRICT_TRANS_TABLES');
119 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
120 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request
::id(), 'String')));
126 public static function getConnection() {
127 global $_DB_DATAOBJECT;
128 $dao = new CRM_Core_DAO();
129 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
133 * @param string $fieldName
135 * @param array $params
137 protected function assignTestFK($fieldName, $fieldDef, $params) {
138 $required = CRM_Utils_Array
::value('required', $fieldDef);
139 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
140 $dbName = $fieldDef['name'];
141 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
143 // skip the FK if it is not required
144 // if it's contact id we should create even if not required
145 // we'll have a go @ fetching first though
146 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
147 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
150 if (!$required && $dbName != 'contact_id') {
151 $fkDAO = new $FKClassName();
152 if ($fkDAO->find(TRUE)) {
153 $this->$dbName = $fkDAO->id
;
158 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
159 $depObject = new $FKClassName();
160 $depObject->find(TRUE);
161 $this->$dbName = $depObject->id
;
164 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
165 // FIXME: the fields() metadata is not specific enough
166 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
167 $this->$dbName = $depObject->id
;
171 //if it is required we need to generate the dependency object first
172 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
173 $this->$dbName = $depObject->id
;
179 * Generate and assign an arbitrary value to a field of a test object.
181 * @param string $fieldName
182 * @param array $fieldDef
183 * @param int $counter
184 * The globally-unique ID of the test object.
186 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
187 $dbName = $fieldDef['name'];
188 $daoName = get_class($this);
191 if (!$handled && $dbName == 'contact_sub_type') {
192 //coming up with a rule to set this is too complex let's not set it
196 // Pick an option value if needed
197 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
198 $options = $daoName::buildOptions($dbName, 'create');
200 $this->$dbName = key($options);
206 switch ($fieldDef['type']) {
207 case CRM_Utils_Type
::T_INT
:
208 case CRM_Utils_Type
::T_FLOAT
:
209 case CRM_Utils_Type
::T_MONEY
:
210 if (isset($fieldDef['precision'])) {
211 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
212 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
215 $this->$dbName = $counter;
219 case CRM_Utils_Type
::T_BOOLEAN
:
220 if (isset($fieldDef['default'])) {
221 $this->$dbName = $fieldDef['default'];
223 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
231 case CRM_Utils_Type
::T_DATE
:
232 case CRM_Utils_Type
::T_TIMESTAMP
:
233 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
234 $this->$dbName = '19700101';
235 if ($dbName == 'end_date') {
236 // put this in the future
237 $this->$dbName = '20200101';
241 case CRM_Utils_Type
::T_TIME
:
242 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
243 //$object->$dbName='000000';
245 case CRM_Utils_Type
::T_CCNUM
:
246 $this->$dbName = '4111 1111 1111 1111';
249 case CRM_Utils_Type
::T_URL
:
250 $this->$dbName = 'http://www.civicrm.org';
253 case CRM_Utils_Type
::T_STRING
:
254 case CRM_Utils_Type
::T_BLOB
:
255 case CRM_Utils_Type
::T_MEDIUMBLOB
:
256 case CRM_Utils_Type
::T_TEXT
:
257 case CRM_Utils_Type
::T_LONGTEXT
:
258 case CRM_Utils_Type
::T_EMAIL
:
260 // WAS: if (isset($value['enumValues'])) {
261 // TODO: see if this works with all pseudoconstants
262 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
263 if (isset($fieldDef['default'])) {
264 $this->$dbName = $fieldDef['default'];
267 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
268 if (is_array($options)) {
269 $this->$dbName = $options[0];
272 $defaultValues = explode(',', $options);
273 $this->$dbName = $defaultValues[0];
278 $this->$dbName = $dbName . '_' . $counter;
279 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
280 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
281 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
289 * Reset the DAO object.
291 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
293 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
295 public function reset() {
297 foreach (array_keys($this->table()) as $field) {
298 unset($this->$field);
302 * reset the various DB_DAO structures manually
304 $this->_query
= array();
311 * @param string $tableName
315 public static function getLocaleTableName($tableName) {
318 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
319 if (in_array($tableName, $tables)) {
320 return $tableName . $dbLocale;
327 * Execute a query by the current DAO, localizing it along the way (if needed).
329 * @param string $query
330 * The SQL query for execution.
331 * @param bool $i18nRewrite
332 * Whether to rewrite the query.
335 * the current DAO object after the query execution
337 public function query($query, $i18nRewrite = TRUE) {
338 // rewrite queries that should use $dbLocale-based views for multi-language installs
339 global $dbLocale, $_DB_DATAOBJECT;
341 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
342 $orig_options = $conn->options
;
343 $this->_setDBOptions($this->_options
);
345 if ($i18nRewrite and $dbLocale) {
346 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
349 $ret = parent
::query($query);
351 $this->_setDBOptions($orig_options);
356 * Static function to set the factory instance for this class.
358 * @param object $factory
359 * The factory application object.
361 public static function setFactory(&$factory) {
362 self
::$_factory = &$factory;
366 * Factory method to instantiate a new object from a table name.
368 * @param string $table
370 public function factory($table = '') {
371 if (!isset(self
::$_factory)) {
372 return parent
::factory($table);
375 return self
::$_factory->create($table);
379 * Initialization for all DAO objects. Since we access DB_DO programatically
380 * we need to set the links manually.
382 public function initialize() {
384 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
385 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
386 // This occurs very early in bootstrap - error handlers may not be wired up.
387 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
388 CRM_Utils_System
::civiExit();
393 * Defines the default key as 'id'.
398 public function keys() {
407 * Tells DB_DataObject which keys use autoincrement.
408 * 'id' is autoincrementing by default.
413 public function sequenceKey() {
414 static $sequenceKeys;
415 if (!isset($sequenceKeys)) {
416 $sequenceKeys = array('id', TRUE);
418 return $sequenceKeys;
422 * Returns list of FK relationships.
426 * Array of CRM_Core_Reference_Interface
428 public static function getReferenceColumns() {
433 * Returns all the column names of this table.
438 public static function &fields() {
444 * Get/set an associative array of table columns
449 public function table() {
450 $fields = &$this->fields();
454 foreach ($fields as $name => $value) {
455 $table[$value['name']] = $value['type'];
456 if (!empty($value['required'])) {
457 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
470 * @return CRM_Core_DAO
472 public function save($hook = TRUE) {
473 if (!empty($this->id
)) {
477 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
478 \Civi
::service('dispatcher')->dispatch("DAO::post-update", $event);
485 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
486 \Civi
::service('dispatcher')->dispatch("DAO::post-insert", $event);
492 CRM_Utils_Hook
::postSave($this);
499 * Deletes items from table which match current objects variables.
501 * Returns the true on success
505 * Designed to be extended
507 * $object = new mytable();
509 * echo $object->delete(); // builds a conditon
511 * $object = new mytable();
512 * $object->whereAdd('age > 12');
514 * $object->orderBy('age DESC');
515 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
517 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
518 * we will build the condition only using the whereAdd's. Default is to
519 * build the condition only using the object parameters.
521 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
523 public function delete($useWhere = FALSE) {
524 $result = parent
::delete($useWhere);
526 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
527 \Civi
::service('dispatcher')->dispatch("DAO::post-delete", $event);
534 * @param bool $created
536 public function log($created = FALSE) {
539 if (!$this->getLog()) {
544 $session = CRM_Core_Session
::singleton();
545 $cid = $session->get('userID');
548 // return is we dont have handle to FK
553 $dao = new CRM_Core_DAO_Log();
554 $dao->entity_table
= $this->getTableName();
555 $dao->entity_id
= $this->id
;
556 $dao->modified_id
= $cid;
557 $dao->modified_date
= date("YmdHis");
562 * Given an associative array of name/value pairs, extract all the values
563 * that belong to this object and initialize the object with said values
565 * @param array $params
566 * (reference ) associative array of name/value pairs.
569 * Did we copy all null values into the object
571 public function copyValues(&$params) {
572 $fields = &$this->fields();
574 foreach ($fields as $name => $value) {
575 $dbName = $value['name'];
576 if (array_key_exists($dbName, $params)) {
577 $pValue = $params[$dbName];
580 elseif (array_key_exists($name, $params)) {
581 $pValue = $params[$name];
588 // if there is no value then make the variable NULL
590 if ($pValue === '') {
591 $this->$dbName = 'null';
594 $this->$dbName = $pValue;
603 * Store all the values from this object in an associative array
604 * this is a destructive store, calling function is responsible
605 * for keeping sanity of id's.
607 * @param object $object
608 * The object that we are extracting data from.
609 * @param array $values
610 * (reference ) associative array of name/value pairs.
612 public static function storeValues(&$object, &$values) {
613 $fields = &$object->fields();
614 foreach ($fields as $name => $value) {
615 $dbName = $value['name'];
616 if (isset($object->$dbName) && $object->$dbName !== 'null') {
617 $values[$dbName] = $object->$dbName;
618 if ($name != $dbName) {
619 $values[$name] = $object->$dbName;
626 * Create an attribute for this specific field. We only do this for strings and text
628 * @param array $field
629 * The field under task.
632 * the attributes for the object
634 public static function makeAttribute($field) {
636 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
637 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
638 $size = CRM_Utils_Array
::value('size', $field);
639 if ($maxLength ||
$size) {
640 $attributes = array();
642 $attributes['maxlength'] = $maxLength;
645 $attributes['size'] = $size;
650 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
651 $rows = CRM_Utils_Array
::value('rows', $field);
655 $cols = CRM_Utils_Array
::value('cols', $field);
660 $attributes = array();
661 $attributes['rows'] = $rows;
662 $attributes['cols'] = $cols;
665 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
) {
666 $attributes['size'] = 6;
667 $attributes['maxlength'] = 14;
675 * Get the size and maxLength attributes for this text field.
676 * (or for all text fields) in the DAO object.
678 * @param string $class
680 * @param string $fieldName
681 * Field that i'm interested in or null if.
682 * you want the attributes for all DAO text fields
685 * assoc array of name => attribute pairs
687 public static function getAttribute($class, $fieldName = NULL) {
688 $object = new $class();
689 $fields = &$object->fields();
690 if ($fieldName != NULL) {
691 $field = CRM_Utils_Array
::value($fieldName, $fields);
692 return self
::makeAttribute($field);
695 $attributes = array();
696 foreach ($fields as $name => $field) {
697 $attribute = self
::makeAttribute($field);
699 $attributes[$name] = $attribute;
703 if (!empty($attributes)) {
715 public static function transaction($type) {
716 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
720 * Check if there is a record with the same name in the db.
722 * @param string $value
723 * The value of the field we are checking.
724 * @param string $daoName
725 * The dao object name.
726 * @param string $daoID
727 * The id of the object being updated. u can change your name.
728 * as long as there is no conflict
729 * @param string $fieldName
730 * The name of the field in the DAO.
733 * true if object exists
735 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
736 $object = new $daoName();
737 $object->$fieldName = $value;
739 $config = CRM_Core_Config
::singleton();
741 if ($object->find(TRUE)) {
742 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
750 * Check if there is a given column in a specific table.
752 * @param string $tableName
753 * @param string $columnName
754 * @param bool $i18nRewrite
755 * Whether to rewrite the query on multilingual setups.
758 * true if exists, else false
760 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
766 $params = array(1 => array($columnName, 'String'));
767 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
768 $result = $dao->fetch() ?
TRUE : FALSE;
774 * Scans all the tables using a slow query and table name.
778 public static function getTableNames() {
779 $dao = CRM_Core_DAO
::executeQuery(
781 FROM information_schema.TABLES
782 WHERE TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
783 AND TABLE_NAME LIKE 'civicrm_%'
784 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
785 AND TABLE_NAME NOT LIKE '%_temp%'
788 while ($dao->fetch()) {
789 $values[] = $dao->TABLE_NAME
;
796 * @param int $maxTablesToCheck
800 public static function isDBMyISAM($maxTablesToCheck = 10) {
801 return CRM_Core_DAO
::singleValueQuery(
803 FROM information_schema.TABLES
804 WHERE ENGINE = 'MyISAM'
805 AND TABLE_SCHEMA = '" . CRM_Core_DAO
::getDatabaseName() . "'
806 AND TABLE_NAME LIKE 'civicrm_%'
807 AND TABLE_NAME NOT LIKE 'civicrm_import_job_%'
808 AND TABLE_NAME NOT LIKE '%_temp%'
813 * Get the name of the CiviCRM database.
817 public static function getDatabaseName() {
818 $daoObj = new CRM_Core_DAO();
819 return $daoObj->database();
823 * Checks if a constraint exists for a specified table.
825 * @param string $tableName
826 * @param string $constraint
829 * true if constraint exists, false otherwise
831 public static function checkConstraintExists($tableName, $constraint) {
832 static $show = array();
834 if (!array_key_exists($tableName, $show)) {
835 $query = "SHOW CREATE TABLE $tableName";
836 $dao = CRM_Core_DAO
::executeQuery($query);
838 if (!$dao->fetch()) {
839 CRM_Core_Error
::fatal();
843 $show[$tableName] = $dao->Create_Table
;
846 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
850 * Checks if CONSTRAINT keyword exists for a specified table.
852 * @param array $tables
857 * true if CONSTRAINT keyword exists, false otherwise
859 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
861 foreach ($tables as $tableName) {
862 if (!array_key_exists($tableName, $show)) {
863 $query = "SHOW CREATE TABLE $tableName";
864 $dao = CRM_Core_DAO
::executeQuery($query);
866 if (!$dao->fetch()) {
867 CRM_Core_Error
::fatal();
871 $show[$tableName] = $dao->Create_Table
;
874 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
875 if ($result == TRUE) {
886 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
887 * for a specified column of a table.
889 * @param string $tableName
890 * @param string $columnName
893 * true if in format, false otherwise
895 public static function checkFKConstraintInFormat($tableName, $columnName) {
896 static $show = array();
898 if (!array_key_exists($tableName, $show)) {
899 $query = "SHOW CREATE TABLE $tableName";
900 $dao = CRM_Core_DAO
::executeQuery($query);
902 if (!$dao->fetch()) {
903 CRM_Core_Error
::fatal();
907 $show[$tableName] = $dao->Create_Table
;
909 $constraint = "`FK_{$tableName}_{$columnName}`";
910 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
911 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
915 * Check whether a specific column in a specific table has always the same value.
917 * @param string $tableName
918 * @param string $columnName
919 * @param string $columnValue
922 * true if the value is always $columnValue, false otherwise
924 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
925 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
926 $dao = CRM_Core_DAO
::executeQuery($query);
927 $result = $dao->fetch() ?
FALSE : TRUE;
933 * Check whether a specific column in a specific table is always NULL.
935 * @param string $tableName
936 * @param string $columnName
939 * true if if the value is always NULL, false otherwise
941 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
942 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
943 $dao = CRM_Core_DAO
::executeQuery($query);
944 $result = $dao->fetch() ?
FALSE : TRUE;
950 * Check if there is a given table in the database.
952 * @param string $tableName
955 * true if exists, else false
957 public static function checkTableExists($tableName) {
962 $params = array(1 => array($tableName, 'String'));
964 $dao = CRM_Core_DAO
::executeQuery($query, $params);
965 $result = $dao->fetch() ?
TRUE : FALSE;
975 public function checkVersion($version) {
980 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
981 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
985 * Find a DAO object for the given ID and return it.
988 * Id of the DAO object being searched for.
991 * Object of the type of the class that called this function.
993 public static function findById($id) {
994 $object = new static();
996 if (!$object->find(TRUE)) {
997 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1003 * Returns all results as array-encoded records.
1007 public function fetchAll() {
1009 while ($this->fetch()) {
1010 $result[] = $this->toArray();
1016 * Get all the result records as mapping between columns.
1018 * @param string $keyColumn
1020 * @param string $valueColumn
1023 * Ex: ["foo" => "The Foo Bar", "baz" => "The Baz Qux"]
1025 public function fetchMap($keyColumn, $valueColumn) {
1027 while ($this->fetch()) {
1028 $result[$this->{$keyColumn}] = $this->{$valueColumn};
1034 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1036 * @param string $daoName
1037 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1038 * @param int $searchValue
1039 * Value of the column you want to search by.
1040 * @param string $returnColumn
1041 * Name of the column you want to GET the value of.
1042 * @param string $searchColumn
1043 * Name of the column you want to search by.
1044 * @param bool $force
1045 * Skip use of the cache.
1047 * @return string|null
1048 * Value of $returnColumn in the retrieved record
1050 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1052 empty($searchValue) ||
1053 trim(strtolower($searchValue)) == 'null'
1055 // adding this year since developers forget to check for an id
1056 // or for the 'null' (which is a bad DAO kludge)
1057 // and hence we get the first value in the db
1058 CRM_Core_Error
::fatal();
1061 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1062 if (self
::$_dbColumnValueCache === NULL) {
1063 self
::$_dbColumnValueCache = array();
1066 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1067 $object = new $daoName();
1068 $object->$searchColumn = $searchValue;
1069 $object->selectAdd();
1070 $object->selectAdd($returnColumn);
1073 if ($object->find(TRUE)) {
1074 $result = $object->$returnColumn;
1078 self
::$_dbColumnValueCache[$cacheKey] = $result;
1080 return self
::$_dbColumnValueCache[$cacheKey];
1084 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1086 * @param string $daoName
1087 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1088 * @param int $searchValue
1089 * Value of the column you want to search by.
1090 * @param string $setColumn
1091 * Name of the column you want to SET the value of.
1092 * @param string $setValue
1093 * SET the setColumn to this value.
1094 * @param string $searchColumn
1095 * Name of the column you want to search by.
1098 * true if we found and updated the object, else false
1100 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1101 $object = new $daoName();
1102 $object->selectAdd();
1103 $object->selectAdd("$searchColumn, $setColumn");
1104 $object->$searchColumn = $searchValue;
1106 if ($object->find(TRUE)) {
1107 $object->$setColumn = $setValue;
1108 if ($object->save()) {
1119 * @param array|object $sort either array or CRM_Utils_Sort
1120 * @param string $default
1121 * Default sort value.
1126 public static function getSortString($sort, $default = NULL) {
1127 // check if sort is of type CRM_Utils_Sort
1128 if (is_a($sort, 'CRM_Utils_Sort')) {
1129 return $sort->orderBy();
1132 // is it an array specified as $field => $sortDirection ?
1134 foreach ($sort as $k => $v) {
1135 $sortString .= "$k $v,";
1137 return rtrim($sortString, ',');
1143 * Fetch object based on array of properties.
1145 * @param string $daoName
1146 * Name of the dao object.
1147 * @param array $params
1148 * (reference ) an assoc array of name/value pairs.
1149 * @param array $defaults
1150 * (reference ) an assoc array to hold the flattened values.
1151 * @param array $returnProperities
1152 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1155 * an object of type referenced by daoName
1157 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1158 $object = new $daoName();
1159 $object->copyValues($params);
1161 // return only specific fields if returnproperties are sent
1162 if (!empty($returnProperities)) {
1163 $object->selectAdd();
1164 $object->selectAdd(implode(',', $returnProperities));
1167 if ($object->find(TRUE)) {
1168 self
::storeValues($object, $defaults);
1175 * Delete the object records that are associated with this contact.
1177 * @param string $daoName
1178 * Name of the dao object.
1179 * @param int $contactId
1180 * Id of the contact to delete.
1182 public static function deleteEntityContact($daoName, $contactId) {
1183 $object = new $daoName();
1185 $object->entity_table
= 'civicrm_contact';
1186 $object->entity_id
= $contactId;
1191 * execute an unbuffered query. This is a wrapper around new functionality
1192 * exposed with CRM-17748.
1194 * @param string $query query to be executed
1196 * @return Object CRM_Core_DAO object that points to an unbuffered result set
1200 static public function executeUnbufferedQuery(
1206 $i18nRewrite = TRUE,
1207 $trapException = FALSE
1209 $queryStr = self
::composeQuery($query, $params, $abort);
1210 //CRM_Core_Error::debug( 'q', $queryStr );
1212 $dao = new CRM_Core_DAO();
1215 $dao = new $daoName();
1218 if ($trapException) {
1219 CRM_Core_Error
::ignoreException();
1222 // set the DAO object to use an unbuffered query
1223 $dao->setOptions(array('result_buffering' => 0));
1225 $result = $dao->query($queryStr, $i18nRewrite);
1227 if ($trapException) {
1228 CRM_Core_Error
::setCallback();
1231 if (is_a($result, 'DB_Error')) {
1235 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1239 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1241 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1251 * @param string $query
1252 * Query to be executed.
1254 * @param array $params
1255 * @param bool $abort
1256 * @param null $daoName
1257 * @param bool $freeDAO
1258 * @param bool $i18nRewrite
1259 * @param bool $trapException
1261 * @return CRM_Core_DAO|object
1262 * object that holds the results of the query
1263 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1264 * out all the properties that are not part of the DAO
1266 public static function &executeQuery(
1272 $i18nRewrite = TRUE,
1273 $trapException = FALSE
1275 $queryStr = self
::composeQuery($query, $params, $abort);
1278 $dao = new CRM_Core_DAO();
1281 $dao = new $daoName();
1284 if ($trapException) {
1285 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1288 $result = $dao->query($queryStr, $i18nRewrite);
1290 if (is_a($result, 'DB_Error')) {
1295 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1297 // we typically do this for insert/update/delete statements OR if explicitly asked to
1305 * Execute a query and get the single result.
1307 * @param string $query
1308 * Query to be executed.
1309 * @param array $params
1310 * @param bool $abort
1311 * @param bool $i18nRewrite
1312 * @return string|null
1313 * the result of the query if any
1316 public static function &singleValueQuery(
1322 $queryStr = self
::composeQuery($query, $params, $abort);
1324 static $_dao = NULL;
1327 $_dao = new CRM_Core_DAO();
1330 $_dao->query($queryStr, $i18nRewrite);
1332 $result = $_dao->getDatabaseResult();
1335 $row = $result->fetchRow();
1345 * Compose the query by merging the parameters into it.
1347 * @param string $query
1348 * @param array $params
1349 * @param bool $abort
1354 public static function composeQuery($query, $params, $abort = TRUE) {
1356 foreach ($params as $key => $item) {
1357 if (is_numeric($key)) {
1358 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1359 $item[0] = self
::escapeString($item[0]);
1360 if ($item[1] == 'String' ||
1361 $item[1] == 'Memo' ||
1364 // Support class constants stipulating wildcard characters and/or
1365 // non-quoting of strings. Also support legacy code which may be
1366 // passing in TRUE or 1 for $item[2], which used to indicate the
1367 // use of wildcard characters.
1368 if (!empty($item[2])) {
1369 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1370 $item[0] = "'%{$item[0]}%'";
1372 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1373 $item[0] = "'{$item[0]}'";
1377 $item[0] = "'{$item[0]}'";
1381 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1382 strlen($item[0]) == 0
1387 $tr['%' . $key] = $item[0];
1390 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1395 return strtr($query, $tr);
1401 public static function freeResult($ids = NULL) {
1402 global $_DB_DATAOBJECT;
1405 if (!$_DB_DATAOBJECT ||
1406 !isset($_DB_DATAOBJECT['RESULTS'])
1410 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1413 foreach ($ids as $id) {
1414 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1415 $_DB_DATAOBJECT['RESULTS'][$id]->free();
1416 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1419 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1420 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1426 * make a shallow copy of an object.
1427 * and all the fields in the object
1429 * @param string $daoName
1431 * @param array $criteria
1432 * Array of all the fields & values.
1433 * on which basis to copy
1434 * @param array $newData
1435 * Array of all the fields & values.
1436 * to be copied besides the other fields
1437 * @param string $fieldsFix
1438 * Array of fields that you want to prefix/suffix/replace.
1439 * @param string $blockCopyOfDependencies
1440 * Fields that you want to block from.
1444 * @return CRM_Core_DAO
1445 * the newly created copy of the object
1447 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1448 $object = new $daoName();
1450 $object->id
= $criteria['id'];
1453 foreach ($criteria as $key => $value) {
1454 $object->$key = $value;
1459 while ($object->fetch()) {
1461 // all the objects except with $blockCopyOfDependencies set
1462 // be copied - addresses #CRM-1962
1464 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1468 $newObject = new $daoName();
1470 $fields = &$object->fields();
1471 if (!is_array($fieldsFix)) {
1472 $fieldsToPrefix = array();
1473 $fieldsToSuffix = array();
1474 $fieldsToReplace = array();
1476 if (!empty($fieldsFix['prefix'])) {
1477 $fieldsToPrefix = $fieldsFix['prefix'];
1479 if (!empty($fieldsFix['suffix'])) {
1480 $fieldsToSuffix = $fieldsFix['suffix'];
1482 if (!empty($fieldsFix['replace'])) {
1483 $fieldsToReplace = $fieldsFix['replace'];
1486 foreach ($fields as $name => $value) {
1487 if ($name == 'id' ||
$value['name'] == 'id') {
1488 // copy everything but the id!
1492 $dbName = $value['name'];
1493 $type = CRM_Utils_Type
::typeToString($value['type']);
1494 $newObject->$dbName = $object->$dbName;
1495 if (isset($fieldsToPrefix[$dbName])) {
1496 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1498 if (isset($fieldsToSuffix[$dbName])) {
1499 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1501 if (isset($fieldsToReplace[$dbName])) {
1502 $newObject->$dbName = $fieldsToReplace[$dbName];
1505 if ($type == 'Timestamp' ||
$type == 'Date') {
1506 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1510 foreach ($newData as $k => $v) {
1511 $newObject->$k = $v;
1521 * Cascade update through related entities.
1523 * @param string $daoName
1526 * @param array $newData
1530 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1531 $object = new $daoName();
1532 $object->id
= $fromId;
1534 if ($object->find(TRUE)) {
1535 $newObject = new $daoName();
1536 $newObject->id
= $toId;
1538 if ($newObject->find(TRUE)) {
1539 $fields = &$object->fields();
1540 foreach ($fields as $name => $value) {
1541 if ($name == 'id' ||
$value['name'] == 'id') {
1542 // copy everything but the id!
1546 $colName = $value['name'];
1547 $newObject->$colName = $object->$colName;
1549 if (substr($name, -5) == '_date' ||
1550 substr($name, -10) == '_date_time'
1552 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1555 foreach ($newData as $k => $v) {
1556 $newObject->$k = $v;
1562 return CRM_Core_DAO
::$_nullObject;
1566 * Given the component id, compute the contact id
1567 * since its used for things like send email
1569 * @param $componentIDs
1570 * @param string $tableName
1574 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1575 $contactIDs = array();
1577 if (empty($componentIDs)) {
1581 $IDs = implode(',', $componentIDs);
1585 WHERE id IN ( $IDs )
1588 $dao = CRM_Core_DAO
::executeQuery($query);
1589 while ($dao->fetch()) {
1590 $contactIDs[] = $dao->contact_id
;
1596 * Fetch object based on array of properties.
1598 * @param string $daoName
1599 * Name of the dao object.
1600 * @param string $fieldIdName
1601 * @param int $fieldId
1603 * @param array $returnProperities
1604 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1607 * an object of type referenced by daoName
1609 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1610 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1611 $object = new $daoName();
1612 $object->$fieldIdName = $fieldId;
1614 // return only specific fields if returnproperties are sent
1615 if (!empty($returnProperities)) {
1616 $object->selectAdd();
1617 $object->selectAdd('id');
1618 $object->selectAdd(implode(',', $returnProperities));
1622 while ($object->fetch()) {
1623 $defaults = array();
1624 self
::storeValues($object, $defaults);
1625 $details[$object->id
] = $defaults;
1631 public static function dropAllTables() {
1633 // first drop all the custom tables we've created
1634 CRM_Core_BAO_CustomGroup
::dropAllTables();
1636 // drop all multilingual views
1637 CRM_Core_I18n_Schema
::dropAllViews();
1639 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1640 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1641 '..' . DIRECTORY_SEPARATOR
.
1642 '..' . DIRECTORY_SEPARATOR
.
1643 'sql' . DIRECTORY_SEPARATOR
.
1644 'civicrm_drop.mysql'
1653 public static function escapeString($string) {
1654 static $_dao = NULL;
1656 // If this is an atypical case (e.g. preparing .sql file before CiviCRM
1657 // has been installed), then we fallback DB-less str_replace escaping, as
1658 // we can't use mysqli_real_escape_string, as there is no DB connection.
1659 // Note: In typical usage, escapeString() will only check one conditional
1660 // ("if !$_dao") rather than two conditionals ("if !defined(DSN)")
1661 if (!defined('CIVICRM_DSN')) {
1662 // See http://php.net/manual/en/mysqli.real-escape-string.php for the
1663 // list of characters mysqli_real_escape_string escapes.
1664 $search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
1665 $replace = array("\\\\", "\\0", "\\n", "\\r", "\'", '\"', "\\Z");
1666 return str_replace($search, $replace, $string);
1668 $_dao = new CRM_Core_DAO();
1670 return $_dao->escape($string);
1674 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1676 * @param array $strings
1677 * @param string $default
1678 * the value to use if $strings has no elements.
1680 * eg "abc","def","ghi"
1682 public static function escapeStrings($strings, $default = NULL) {
1683 static $_dao = NULL;
1685 $_dao = new CRM_Core_DAO();
1688 if (empty($strings)) {
1692 $escapes = array_map(array($_dao, 'escape'), $strings);
1693 return '"' . implode('","', $escapes) . '"';
1701 public static function escapeWildCardString($string) {
1703 // ensure we escape the single characters % and _ which are mysql wild
1704 // card characters and could come in via sortByCharacter
1705 // note that mysql does not escape these characters
1706 if ($string && in_array($string,
1707 array('%', '_', '%%', '_%')
1710 return '\\' . $string;
1713 return self
::escapeString($string);
1717 * Creates a test object, including any required objects it needs via recursion
1718 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1719 * ONLY USE FOR TESTING
1721 * @param string $daoName
1722 * @param array $params
1723 * @param int $numObjects
1724 * @param bool $createOnly
1726 * @return object|array|NULL
1727 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1729 public static function createTestObject(
1735 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1736 // so we re-set here in case
1737 $config = CRM_Core_Config
::singleton();
1738 $config->backtrace
= TRUE;
1740 static $counter = 0;
1741 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1742 'CRM_Core_DAO_Worldregion',
1743 'CRM_Core_DAO_StateProvince',
1744 'CRM_Core_DAO_Country',
1745 'CRM_Core_DAO_Domain',
1746 'CRM_Financial_DAO_FinancialType',
1747 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1750 // Prefer to instantiate BAO's instead of DAO's (when possible)
1751 // so that assignTestValue()/assignTestFK() can be overloaded.
1752 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1753 if (class_exists($baoName)) {
1754 $daoName = $baoName;
1757 for ($i = 0; $i < $numObjects; ++
$i) {
1760 /** @var CRM_Core_DAO $object */
1761 $object = new $daoName();
1763 $fields = &$object->fields();
1764 foreach ($fields as $fieldName => $fieldDef) {
1765 $dbName = $fieldDef['name'];
1766 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1767 $required = CRM_Utils_Array
::value('required', $fieldDef);
1769 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1770 $object->$dbName = $params[$dbName];
1773 elseif ($dbName != 'id') {
1774 if ($FKClassName != NULL) {
1775 $object->assignTestFK($fieldName, $fieldDef, $params);
1779 $object->assignTestValue($fieldName, $fieldDef, $counter);
1787 $objects[$i] = $object;
1797 elseif ($numObjects == 1) {
1806 * Deletes the this object plus any dependent objects that are associated with it.
1807 * ONLY USE FOR TESTING
1809 * @param string $daoName
1810 * @param array $params
1812 public static function deleteTestObjects($daoName, $params = array()) {
1813 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1814 // so we re-set here in case
1815 $config = CRM_Core_Config
::singleton();
1816 $config->backtrace
= TRUE;
1818 $object = new $daoName();
1819 $object->id
= CRM_Utils_Array
::value('id', $params);
1821 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1822 if ($object->find(TRUE)) {
1824 $fields = &$object->fields();
1825 foreach ($fields as $name => $value) {
1827 $dbName = $value['name'];
1829 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1830 $required = CRM_Utils_Array
::value('required', $value);
1831 if ($FKClassName != NULL
1833 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1834 && ($required ||
$dbName == 'contact_id')
1835 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1836 // to make this test process pass - line below makes pass for now
1837 && $dbName != 'member_of_contact_id'
1839 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1846 foreach ($deletions as $deletion) {
1847 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1852 * Set defaults when creating new entity.
1853 * (don't call this set defaults as already in use with different signature in some places)
1855 * @param array $params
1858 public static function setCreateDefaults(&$params, $defaults) {
1859 if (!empty($params['id'])) {
1862 foreach ($defaults as $key => $value) {
1863 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1864 $params[$key] = $value;
1870 * @param string $prefix
1871 * @param bool $addRandomString
1872 * @param null $string
1876 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1877 $tableName = $prefix . "_temp";
1879 if ($addRandomString) {
1881 $tableName .= "_" . $string;
1884 $tableName .= "_" . md5(uniqid('', TRUE));
1892 * @param bool $trigger
1896 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1897 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1899 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1900 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1901 $dao = new CRM_Core_DAO();
1903 $result = $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1904 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1910 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1911 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1913 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1918 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1919 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1921 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1928 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1929 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1938 * @param null $message
1939 * @param bool $printDAO
1941 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1942 CRM_Utils_System
::xMemory("{$message}: ");
1945 global $_DB_DATAOBJECT;
1947 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1948 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1950 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1955 * Build a list of triggers via hook and add them to (err, reconcile them
1956 * with) the database.
1958 * @param string $tableName
1959 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1960 * @param bool $force
1965 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1966 Civi
::service('sql_triggers')->rebuild($tableName, $force);
1970 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1971 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1972 * TODO: Alternative solutions might be
1973 * * Stop using functions and find another way to strip numeric characters from phones
1974 * * Give better error messages (currently a missing fn fatals with "unknown error")
1976 public static function checkSqlFunctionsExist() {
1977 if (!self
::$_checkedSqlFunctionsExist) {
1978 self
::$_checkedSqlFunctionsExist = TRUE;
1979 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1980 if (!$dao->fetch()) {
1981 self
::triggerRebuild();
1987 * Wrapper function to drop triggers.
1989 * @param string $tableName
1990 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1993 public static function dropTriggers($tableName = NULL) {
1994 Civi
::service('sql_triggers')->dropTriggers($tableName);
1998 * @param array $info
1999 * per hook_civicrm_triggerInfo.
2000 * @param string $onlyTableName
2001 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2004 public static function createTriggers(&$info, $onlyTableName = NULL) {
2005 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2009 * Given a list of fields, create a list of references.
2011 * @param string $className
2012 * BAO/DAO class name.
2013 * @return array<CRM_Core_Reference_Interface>
2015 public static function createReferenceColumns($className) {
2017 $fields = $className::fields();
2018 foreach ($fields as $field) {
2019 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2020 $result[] = new CRM_Core_Reference_OptionValue(
2021 $className::getTableName(),
2023 'civicrm_option_value',
2024 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2025 $field['pseudoconstant']['optionGroupName']
2033 * Find all records which refer to this entity.
2036 * Array of objects referencing this
2038 public function findReferences() {
2039 $links = self
::getReferencesToTable(static::getTableName());
2041 $occurrences = array();
2042 foreach ($links as $refSpec) {
2043 /** @var $refSpec CRM_Core_Reference_Interface */
2044 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2045 $result = $refSpec->findReferences($this);
2047 while ($result->fetch()) {
2048 $obj = new $daoName();
2049 $obj->id
= $result->id
;
2050 $occurrences[] = $obj;
2055 return $occurrences;
2060 * each item has keys:
2064 * - table: string|null SQL table name
2065 * - key: string|null SQL column name
2067 public function getReferenceCounts() {
2068 $links = self
::getReferencesToTable(static::getTableName());
2071 foreach ($links as $refSpec) {
2072 /** @var $refSpec CRM_Core_Reference_Interface */
2073 $count = $refSpec->getReferenceCount($this);
2074 if ($count['count'] != 0) {
2079 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2080 /** @var $component CRM_Core_Component_Info */
2081 $counts = array_merge($counts, $component->getReferenceCounts($this));
2083 CRM_Utils_Hook
::referenceCounts($this, $counts);
2089 * List all tables which have hard foreign keys to this table.
2091 * For now, this returns a description of every entity_id/entity_table
2093 * TODO: filter dynamic entity references on the $tableName, based on
2094 * schema metadata in dynamicForeignKey which enumerates a restricted
2095 * set of possible entity_table's.
2097 * @param string $tableName
2098 * Table referred to.
2101 * structure of table and column, listing every table with a
2102 * foreign key reference to $tableName, and the column where the key appears.
2104 public static function getReferencesToTable($tableName) {
2105 $refsFound = array();
2106 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2107 $links = $daoClassName::getReferenceColumns();
2108 $daoTableName = $daoClassName::getTableName();
2110 foreach ($links as $refSpec) {
2111 /** @var $refSpec CRM_Core_Reference_Interface */
2112 if ($refSpec->matchesTargetTable($tableName)) {
2113 $refsFound[] = $refSpec;
2121 * Lookup the value of a MySQL global configuration variable.
2123 * @param string $name
2124 * E.g. "thread_stack".
2125 * @param mixed $default
2128 public static function getGlobalSetting($name, $default = NULL) {
2129 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2130 // that has been reported to fail under MySQL 5.0 for OS X
2131 $escapedName = self
::escapeString($name);
2132 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2133 if ($dao->fetch()) {
2142 * Get options for the called BAO object's field.
2144 * This function can be overridden by each BAO to add more logic related to context.
2145 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2147 * @param string $fieldName
2148 * @param string $context
2149 * @see CRM_Core_DAO::buildOptionsContext
2150 * @param array $props
2151 * whatever is known about this bao object.
2153 * @return array|bool
2155 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2156 // If a given bao does not override this function
2157 $baoName = get_called_class();
2158 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2162 * Populate option labels for this object's fields.
2164 * @throws exception if called directly on the base class
2166 public function getOptionLabels() {
2167 $fields = $this->fields();
2168 if ($fields === NULL) {
2169 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2171 foreach ($fields as $field) {
2172 $name = CRM_Utils_Array
::value('name', $field);
2173 if ($name && isset($this->$name)) {
2174 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2175 if ($label !== FALSE) {
2176 // Append 'label' onto the field name
2177 $labelName = $name . '_label';
2178 $this->$labelName = $label;
2185 * Provides documentation and validation for the buildOptions $context param
2187 * @param string $context
2192 public static function buildOptionsContext($context = NULL) {
2194 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2195 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2196 'search' => "search: searchable options are returned; labels are translated.",
2197 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2198 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2199 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2201 // Validation: enforce uniformity of this param
2202 if ($context !== NULL && !isset($contexts[$context])) {
2203 throw new Exception("'$context' is not a valid context for buildOptions.");
2209 * @param string $fieldName
2210 * @return bool|array
2212 public function getFieldSpec($fieldName) {
2213 $fields = $this->fields();
2214 $fieldKeys = $this->fieldKeys();
2216 // Support "unique names" as well as sql names
2217 $fieldKey = $fieldName;
2218 if (empty($fields[$fieldKey])) {
2219 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2221 // If neither worked then this field doesn't exist. Return false.
2222 if (empty($fields[$fieldKey])) {
2225 return $fields[$fieldKey];
2229 * Get SQL where clause for SQL filter syntax input parameters.
2231 * SQL version of api function to assign filters to the DAO based on the syntax
2232 * $field => array('IN' => array(4,6,9))
2234 * $field => array('LIKE' => array('%me%))
2237 * @param string $fieldName
2239 * @param array $filter
2240 * filter to be applied indexed by operator.
2241 * @param string $type
2242 * type of field (not actually used - nor in api @todo ).
2243 * @param string $alias
2244 * alternative field name ('as') @todo- not actually used.
2245 * @param bool $returnSanitisedArray
2246 * Return a sanitised array instead of a clause.
2247 * this is primarily so we can add filters @ the api level to the Query object based fields
2251 * @return NULL|string|array
2252 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2253 * depending on whether it is supported as yet
2255 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2256 foreach ($filter as $operator => $criteria) {
2257 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2258 switch ($operator) {
2262 if (!$returnSanitisedArray) {
2263 return (sprintf('%s %s', $fieldName, $operator));
2266 return (sprintf('%s %s ', $fieldName, $operator));
2270 // ternary operators
2273 if (empty($criteria[0]) ||
empty($criteria[1])) {
2274 throw new Exception("invalid criteria for $operator");
2276 if (!$returnSanitisedArray) {
2277 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2280 return NULL; // not yet implemented (tests required to implement)
2287 if (empty($criteria)) {
2288 throw new Exception("invalid criteria for $operator");
2290 $escapedCriteria = array_map(array(
2294 if (!$returnSanitisedArray) {
2295 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2297 return $escapedCriteria;
2302 if (!$returnSanitisedArray) {
2303 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2306 return NULL; // not yet implemented (tests required to implement)
2314 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2315 * support for other syntaxes is discussed in ticket but being put off for now
2318 public static function acceptedSQLOperators() {
2339 * SQL has a limit of 64 characters on various names:
2340 * table name, trigger name, column name ...
2342 * For custom groups and fields we generated names from user entered input
2343 * which can be longer than this length, this function helps with creating
2344 * strings that meet various criteria.
2346 * @param string $string
2347 * The string to be shortened.
2348 * @param int $length
2349 * The max length of the string.
2351 * @param bool $makeRandom
2355 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2356 // early return for strings that meet the requirements
2357 if (strlen($string) <= $length) {
2361 // easy return for calls that dont need a randomized uniq string
2363 return substr($string, 0, $length);
2366 // the string is longer than the length and we need a uniq string
2367 // for the same tablename we need the same uniq string every time
2368 // hence we use md5 on the string, which is not random
2369 // we'll append 8 characters to the end of the tableName
2370 $md5string = substr(md5($string), 0, 8);
2371 return substr($string, 0, $length - 8) . "_{$md5string}";
2375 * https://issues.civicrm.org/jira/browse/CRM-17748
2376 * Sets the internal options to be used on a query
2378 * @param array $options
2381 public function setOptions($options) {
2382 if (is_array($options)) {
2383 $this->_options
= $options;
2388 * https://issues.civicrm.org/jira/browse/CRM-17748
2389 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2391 * @param array $options
2394 protected function _setDBOptions($options) {
2395 global $_DB_DATAOBJECT;
2397 if (is_array($options) && count($options)) {
2398 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2399 foreach ($options as $option_name => $option_value) {
2400 $conn->setOption($option_name, $option_value);
2407 * @param array $params
2409 public function setApiFilter(&$params) {
2413 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2415 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2418 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2422 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2426 public function addSelectWhereClause() {
2427 // This is the default fallback, and works for contact-related entities like Email, Relationship, etc.
2429 foreach ($this->fields() as $fieldName => $field) {
2430 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2431 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2434 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2439 * This returns the final permissioned query string for this entity
2441 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2443 * @param string $tableAlias
2446 public static function getSelectWhereClause($tableAlias = NULL) {
2447 $bao = new static();
2448 if ($tableAlias === NULL) {
2449 $tableAlias = $bao->tableName();
2452 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2453 $clauses[$field] = NULL;
2455 $clauses[$field] = "`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals);
2462 * function to check valid db name containing only characters in [0-9,a-z,A-Z_]
2468 public static function requireValidDBName($database) {
2471 "/^[0-9]*[a-zA-Z_]+[a-zA-Z0-9_]*$/",
2475 if (empty($matches)) {