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 require_once 'PEAR.php';
36 require_once 'DB/DataObject.php';
38 require_once 'CRM/Core/I18n.php';
43 class CRM_Core_DAO
extends DB_DataObject
{
46 * A null object so we can pass it as reference if / when needed
48 static $_nullObject = NULL;
49 static $_nullArray = array();
51 static $_dbColumnValueCache = NULL;
52 const NOT_NULL
= 1, IS_NULL
= 2,
54 VALUE_SEPARATOR
= "\ 1",
55 BULK_INSERT_COUNT
= 200,
56 BULK_INSERT_HIGH_COUNT
= 200,
57 QUERY_FORMAT_WILDCARD
= 1,
58 QUERY_FORMAT_NO_QUOTES
= 2;
61 * Define entities that shouldn't be created or deleted when creating/ deleting
62 * test objects - this prevents world regions, countries etc from being added / deleted
65 static $_testEntitiesToSkip = array();
67 * The factory class for this application.
70 static $_factory = NULL;
72 static $_checkedSqlFunctionsExist = FALSE;
75 * https://issues.civicrm.org/jira/browse/CRM-17748
76 * internal variable for DAO to hold per-query settings
78 protected $_options = array();
83 * @return \CRM_Core_DAO
85 public function __construct() {
87 $this->__table
= $this->getTableName();
91 * Empty definition for virtual function.
93 public static function getTableName() {
98 * Initialize the DAO object.
101 * The database connection string.
103 public static function init($dsn) {
104 Civi
::$statics[__CLASS__
]['init'] = 1;
105 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
106 $options['database'] = $dsn;
107 if (defined('CIVICRM_DAO_DEBUG')) {
108 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
110 CRM_Core_DAO
::setFactory(new CRM_Contact_DAO_Factory());
111 if (CRM_Utils_Constant
::value('CIVICRM_MYSQL_STRICT', CRM_Utils_System
::isDevelopment())) {
112 CRM_Core_DAO
::executeQuery('SET SESSION sql_mode = STRICT_TRANS_TABLES');
114 CRM_Core_DAO
::executeQuery('SET NAMES utf8');
115 CRM_Core_DAO
::executeQuery('SET @uniqueID = %1', array(1 => array(CRM_Utils_Request
::id(), 'String')));
121 public static function getConnection() {
122 global $_DB_DATAOBJECT;
123 $dao = new CRM_Core_DAO();
124 return $_DB_DATAOBJECT['CONNECTIONS'][$dao->_database_dsn_md5
];
128 * @param string $fieldName
130 * @param array $params
132 protected function assignTestFK($fieldName, $fieldDef, $params) {
133 $required = CRM_Utils_Array
::value('required', $fieldDef);
134 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
135 $dbName = $fieldDef['name'];
136 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
138 // skip the FK if it is not required
139 // if it's contact id we should create even if not required
140 // we'll have a go @ fetching first though
141 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
142 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
145 if (!$required && $dbName != 'contact_id') {
146 $fkDAO = new $FKClassName();
147 if ($fkDAO->find(TRUE)) {
148 $this->$dbName = $fkDAO->id
;
153 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
154 $depObject = new $FKClassName();
155 $depObject->find(TRUE);
156 $this->$dbName = $depObject->id
;
159 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
160 // FIXME: the fields() metadata is not specific enough
161 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
162 $this->$dbName = $depObject->id
;
166 //if it is required we need to generate the dependency object first
167 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
168 $this->$dbName = $depObject->id
;
174 * Generate and assign an arbitrary value to a field of a test object.
176 * @param string $fieldName
177 * @param array $fieldDef
178 * @param int $counter
179 * The globally-unique ID of the test object.
181 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
182 $dbName = $fieldDef['name'];
183 $daoName = get_class($this);
186 if (!$handled && $dbName == 'contact_sub_type') {
187 //coming up with a rule to set this is too complex let's not set it
191 // Pick an option value if needed
192 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
193 $options = $daoName::buildOptions($dbName, 'create');
195 $this->$dbName = key($options);
201 switch ($fieldDef['type']) {
202 case CRM_Utils_Type
::T_INT
:
203 case CRM_Utils_Type
::T_FLOAT
:
204 case CRM_Utils_Type
::T_MONEY
:
205 if (isset($fieldDef['precision'])) {
206 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
207 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
210 $this->$dbName = $counter;
214 case CRM_Utils_Type
::T_BOOLEAN
:
215 if (isset($fieldDef['default'])) {
216 $this->$dbName = $fieldDef['default'];
218 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
226 case CRM_Utils_Type
::T_DATE
:
227 case CRM_Utils_Type
::T_TIMESTAMP
:
228 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
229 $this->$dbName = '19700101';
230 if ($dbName == 'end_date') {
231 // put this in the future
232 $this->$dbName = '20200101';
236 case CRM_Utils_Type
::T_TIME
:
237 CRM_Core_Error
::fatal("T_TIME shouldn't be used.");
238 //$object->$dbName='000000';
240 case CRM_Utils_Type
::T_CCNUM
:
241 $this->$dbName = '4111 1111 1111 1111';
244 case CRM_Utils_Type
::T_URL
:
245 $this->$dbName = 'http://www.civicrm.org';
248 case CRM_Utils_Type
::T_STRING
:
249 case CRM_Utils_Type
::T_BLOB
:
250 case CRM_Utils_Type
::T_MEDIUMBLOB
:
251 case CRM_Utils_Type
::T_TEXT
:
252 case CRM_Utils_Type
::T_LONGTEXT
:
253 case CRM_Utils_Type
::T_EMAIL
:
255 // WAS: if (isset($value['enumValues'])) {
256 // TODO: see if this works with all pseudoconstants
257 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
258 if (isset($fieldDef['default'])) {
259 $this->$dbName = $fieldDef['default'];
262 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
263 if (is_array($options)) {
264 $this->$dbName = $options[0];
267 $defaultValues = explode(',', $options);
268 $this->$dbName = $defaultValues[0];
273 $this->$dbName = $dbName . '_' . $counter;
274 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
275 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
276 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
284 * Reset the DAO object.
286 * DAO is kinda crappy in that there is an unwritten rule of one query per DAO.
288 * We attempt to get around this crappy restriction by resetting some of DAO's internal fields. Use this with caution
290 public function reset() {
292 foreach (array_keys($this->table()) as $field) {
293 unset($this->$field);
297 * reset the various DB_DAO structures manually
299 $this->_query
= array();
306 * @param string $tableName
310 public static function getLocaleTableName($tableName) {
313 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
314 if (in_array($tableName, $tables)) {
315 return $tableName . $dbLocale;
322 * Execute a query by the current DAO, localizing it along the way (if needed).
324 * @param string $query
325 * The SQL query for execution.
326 * @param bool $i18nRewrite
327 * Whether to rewrite the query.
330 * the current DAO object after the query execution
332 public function query($query, $i18nRewrite = TRUE) {
333 // rewrite queries that should use $dbLocale-based views for multi-language installs
334 global $dbLocale, $_DB_DATAOBJECT;
336 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
337 $orig_options = $conn->options
;
338 $this->_setDBOptions($this->_options
);
340 if ($i18nRewrite and $dbLocale) {
341 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
344 $ret = parent
::query($query);
346 $this->_setDBOptions($orig_options);
351 * Static function to set the factory instance for this class.
353 * @param object $factory
354 * The factory application object.
356 public static function setFactory(&$factory) {
357 self
::$_factory = &$factory;
361 * Factory method to instantiate a new object from a table name.
363 * @param string $table
365 public function factory($table = '') {
366 if (!isset(self
::$_factory)) {
367 return parent
::factory($table);
370 return self
::$_factory->create($table);
374 * Initialization for all DAO objects. Since we access DB_DO programatically
375 * we need to set the links manually.
377 public function initialize() {
379 if (empty(Civi
::$statics[__CLASS__
]['init'])) {
380 // CRM_Core_DAO::init() must be called before CRM_Core_DAO->initialize().
381 // This occurs very early in bootstrap - error handlers may not be wired up.
382 echo "Inconsistent system initialization sequence. Premature access of (" . get_class($this) . ")";
383 CRM_Utils_System
::civiExit();
388 * Defines the default key as 'id'.
393 public function keys() {
402 * Tells DB_DataObject which keys use autoincrement.
403 * 'id' is autoincrementing by default.
408 public function sequenceKey() {
409 static $sequenceKeys;
410 if (!isset($sequenceKeys)) {
411 $sequenceKeys = array('id', TRUE);
413 return $sequenceKeys;
417 * Returns list of FK relationships.
421 * Array of CRM_Core_Reference_Interface
423 public static function getReferenceColumns() {
428 * Returns all the column names of this table.
433 public static function &fields() {
439 * Get/set an associative array of table columns
444 public function table() {
445 $fields = &$this->fields();
449 foreach ($fields as $name => $value) {
450 $table[$value['name']] = $value['type'];
451 if (!empty($value['required'])) {
452 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
467 public function save($hook = TRUE) {
468 if (!empty($this->id
)) {
472 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
473 \Civi
::service('dispatcher')->dispatch("DAO::post-update", $event);
480 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
481 \Civi
::service('dispatcher')->dispatch("DAO::post-insert", $event);
487 CRM_Utils_Hook
::postSave($this);
494 * Deletes items from table which match current objects variables.
496 * Returns the true on success
500 * Designed to be extended
502 * $object = new mytable();
504 * echo $object->delete(); // builds a conditon
506 * $object = new mytable();
507 * $object->whereAdd('age > 12');
509 * $object->orderBy('age DESC');
510 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
512 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
513 * we will build the condition only using the whereAdd's. Default is to
514 * build the condition only using the object parameters.
516 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
518 public function delete($useWhere = FALSE) {
519 $result = parent
::delete($useWhere);
521 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
522 \Civi
::service('dispatcher')->dispatch("DAO::post-delete", $event);
528 * @param bool $created
530 public function log($created = FALSE) {
533 if (!$this->getLog()) {
538 $session = CRM_Core_Session
::singleton();
539 $cid = $session->get('userID');
542 // return is we dont have handle to FK
547 $dao = new CRM_Core_DAO_Log();
548 $dao->entity_table
= $this->getTableName();
549 $dao->entity_id
= $this->id
;
550 $dao->modified_id
= $cid;
551 $dao->modified_date
= date("YmdHis");
556 * Given an associative array of name/value pairs, extract all the values
557 * that belong to this object and initialize the object with said values
559 * @param array $params
560 * (reference ) associative array of name/value pairs.
563 * Did we copy all null values into the object
565 public function copyValues(&$params) {
566 $fields = &$this->fields();
568 foreach ($fields as $name => $value) {
569 $dbName = $value['name'];
570 if (array_key_exists($dbName, $params)) {
571 $pValue = $params[$dbName];
574 elseif (array_key_exists($name, $params)) {
575 $pValue = $params[$name];
582 // if there is no value then make the variable NULL
584 if ($pValue === '') {
585 $this->$dbName = 'null';
588 $this->$dbName = $pValue;
597 * Store all the values from this object in an associative array
598 * this is a destructive store, calling function is responsible
599 * for keeping sanity of id's.
601 * @param object $object
602 * The object that we are extracting data from.
603 * @param array $values
604 * (reference ) associative array of name/value pairs.
606 public static function storeValues(&$object, &$values) {
607 $fields = &$object->fields();
608 foreach ($fields as $name => $value) {
609 $dbName = $value['name'];
610 if (isset($object->$dbName) && $object->$dbName !== 'null') {
611 $values[$dbName] = $object->$dbName;
612 if ($name != $dbName) {
613 $values[$name] = $object->$dbName;
620 * Create an attribute for this specific field. We only do this for strings and text
622 * @param array $field
623 * The field under task.
626 * the attributes for the object
628 public static function makeAttribute($field) {
630 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
631 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
632 $size = CRM_Utils_Array
::value('size', $field);
633 if ($maxLength ||
$size) {
634 $attributes = array();
636 $attributes['maxlength'] = $maxLength;
639 $attributes['size'] = $size;
644 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
645 $rows = CRM_Utils_Array
::value('rows', $field);
649 $cols = CRM_Utils_Array
::value('cols', $field);
654 $attributes = array();
655 $attributes['rows'] = $rows;
656 $attributes['cols'] = $cols;
659 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
) {
660 $attributes['size'] = 6;
661 $attributes['maxlength'] = 14;
669 * Get the size and maxLength attributes for this text field.
670 * (or for all text fields) in the DAO object.
672 * @param string $class
674 * @param string $fieldName
675 * Field that i'm interested in or null if.
676 * you want the attributes for all DAO text fields
679 * assoc array of name => attribute pairs
681 public static function getAttribute($class, $fieldName = NULL) {
682 $object = new $class();
683 $fields = &$object->fields();
684 if ($fieldName != NULL) {
685 $field = CRM_Utils_Array
::value($fieldName, $fields);
686 return self
::makeAttribute($field);
689 $attributes = array();
690 foreach ($fields as $name => $field) {
691 $attribute = self
::makeAttribute($field);
693 $attributes[$name] = $attribute;
697 if (!empty($attributes)) {
709 public static function transaction($type) {
710 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
714 * Check if there is a record with the same name in the db.
716 * @param string $value
717 * The value of the field we are checking.
718 * @param string $daoName
719 * The dao object name.
720 * @param string $daoID
721 * The id of the object being updated. u can change your name.
722 * as long as there is no conflict
723 * @param string $fieldName
724 * The name of the field in the DAO.
727 * true if object exists
729 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
730 $object = new $daoName();
731 $object->$fieldName = $value;
733 $config = CRM_Core_Config
::singleton();
735 if ($object->find(TRUE)) {
736 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
744 * Check if there is a given column in a specific table.
746 * @param string $tableName
747 * @param string $columnName
748 * @param bool $i18nRewrite
749 * Whether to rewrite the query on multilingual setups.
752 * true if exists, else false
754 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
760 $params = array(1 => array($columnName, 'String'));
761 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
762 $result = $dao->fetch() ?
TRUE : FALSE;
768 * Returns the storage engine used by given table-name(optional).
769 * Otherwise scans all the tables and return an array of all the
770 * distinct storage engines being used.
772 * @param string $tableName
774 * @param int $maxTablesToCheck
775 * @param string $fieldName
779 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
781 $query = "SHOW TABLE STATUS LIKE %1";
785 if (isset($tableName)) {
786 $params = array(1 => array($tableName, 'String'));
789 $params = array(1 => array('civicrm_%', 'String'));
792 $dao = CRM_Core_DAO
::executeQuery($query, $params);
795 while ($dao->fetch()) {
796 if (isset($values[$dao->$fieldName]) ||
797 // ignore import and other temp tables
798 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
799 strpos($dao->Name
, '_temp') !== FALSE
803 $values[$dao->$fieldName] = 1;
805 if ($maxTablesToCheck &&
806 $count >= $maxTablesToCheck
816 * @param int $maxTablesToCheck
820 public static function isDBMyISAM($maxTablesToCheck = 10) {
821 // show error if any of the tables, use 'MyISAM' storage engine.
822 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
823 if (array_key_exists('MyISAM', $engines)) {
830 * Checks if a constraint exists for a specified table.
832 * @param string $tableName
833 * @param string $constraint
836 * true if constraint exists, false otherwise
838 public static function checkConstraintExists($tableName, $constraint) {
839 static $show = array();
841 if (!array_key_exists($tableName, $show)) {
842 $query = "SHOW CREATE TABLE $tableName";
843 $dao = CRM_Core_DAO
::executeQuery($query);
845 if (!$dao->fetch()) {
846 CRM_Core_Error
::fatal();
850 $show[$tableName] = $dao->Create_Table
;
853 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
857 * Checks if CONSTRAINT keyword exists for a specified table.
859 * @param array $tables
864 * true if CONSTRAINT keyword exists, false otherwise
866 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
868 foreach ($tables as $tableName) {
869 if (!array_key_exists($tableName, $show)) {
870 $query = "SHOW CREATE TABLE $tableName";
871 $dao = CRM_Core_DAO
::executeQuery($query);
873 if (!$dao->fetch()) {
874 CRM_Core_Error
::fatal();
878 $show[$tableName] = $dao->Create_Table
;
881 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
882 if ($result == TRUE) {
893 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
894 * for a specified column of a table.
896 * @param string $tableName
897 * @param string $columnName
900 * true if in format, false otherwise
902 public static function checkFKConstraintInFormat($tableName, $columnName) {
903 static $show = array();
905 if (!array_key_exists($tableName, $show)) {
906 $query = "SHOW CREATE TABLE $tableName";
907 $dao = CRM_Core_DAO
::executeQuery($query);
909 if (!$dao->fetch()) {
910 CRM_Core_Error
::fatal();
914 $show[$tableName] = $dao->Create_Table
;
916 $constraint = "`FK_{$tableName}_{$columnName}`";
917 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
918 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ?
TRUE : FALSE;
922 * Check whether a specific column in a specific table has always the same value.
924 * @param string $tableName
925 * @param string $columnName
926 * @param string $columnValue
929 * true if the value is always $columnValue, false otherwise
931 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
932 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
933 $dao = CRM_Core_DAO
::executeQuery($query);
934 $result = $dao->fetch() ?
FALSE : TRUE;
940 * Check whether a specific column in a specific table is always NULL.
942 * @param string $tableName
943 * @param string $columnName
946 * true if if the value is always NULL, false otherwise
948 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
949 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
950 $dao = CRM_Core_DAO
::executeQuery($query);
951 $result = $dao->fetch() ?
FALSE : TRUE;
957 * Check if there is a given table in the database.
959 * @param string $tableName
962 * true if exists, else false
964 public static function checkTableExists($tableName) {
969 $params = array(1 => array($tableName, 'String'));
971 $dao = CRM_Core_DAO
::executeQuery($query, $params);
972 $result = $dao->fetch() ?
TRUE : FALSE;
982 public function checkVersion($version) {
987 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
988 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
992 * Find a DAO object for the given ID and return it.
995 * Id of the DAO object being searched for.
998 * Object of the type of the class that called this function.
1000 public static function findById($id) {
1001 $object = new static();
1003 if (!$object->find(TRUE)) {
1004 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
1010 * Returns all results as array-encoded records.
1014 public function fetchAll() {
1016 while ($this->fetch()) {
1017 $result[] = $this->toArray();
1023 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
1025 * @param string $daoName
1026 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1027 * @param int $searchValue
1028 * Value of the column you want to search by.
1029 * @param string $returnColumn
1030 * Name of the column you want to GET the value of.
1031 * @param string $searchColumn
1032 * Name of the column you want to search by.
1033 * @param bool $force
1034 * Skip use of the cache.
1036 * @return string|null
1037 * Value of $returnColumn in the retrieved record
1039 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1041 empty($searchValue) ||
1042 trim(strtolower($searchValue)) == 'null'
1044 // adding this year since developers forget to check for an id
1045 // or for the 'null' (which is a bad DAO kludge)
1046 // and hence we get the first value in the db
1047 CRM_Core_Error
::fatal();
1050 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1051 if (self
::$_dbColumnValueCache === NULL) {
1052 self
::$_dbColumnValueCache = array();
1055 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1056 $object = new $daoName();
1057 $object->$searchColumn = $searchValue;
1058 $object->selectAdd();
1059 $object->selectAdd($returnColumn);
1062 if ($object->find(TRUE)) {
1063 $result = $object->$returnColumn;
1067 self
::$_dbColumnValueCache[$cacheKey] = $result;
1069 return self
::$_dbColumnValueCache[$cacheKey];
1073 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1075 * @param string $daoName
1076 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1077 * @param int $searchValue
1078 * Value of the column you want to search by.
1079 * @param string $setColumn
1080 * Name of the column you want to SET the value of.
1081 * @param string $setValue
1082 * SET the setColumn to this value.
1083 * @param string $searchColumn
1084 * Name of the column you want to search by.
1087 * true if we found and updated the object, else false
1089 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1090 $object = new $daoName();
1091 $object->selectAdd();
1092 $object->selectAdd("$searchColumn, $setColumn");
1093 $object->$searchColumn = $searchValue;
1095 if ($object->find(TRUE)) {
1096 $object->$setColumn = $setValue;
1097 if ($object->save()) {
1108 * @param array|object $sort either array or CRM_Utils_Sort
1109 * @param string $default
1110 * Default sort value.
1115 public static function getSortString($sort, $default = NULL) {
1116 // check if sort is of type CRM_Utils_Sort
1117 if (is_a($sort, 'CRM_Utils_Sort')) {
1118 return $sort->orderBy();
1121 // is it an array specified as $field => $sortDirection ?
1123 foreach ($sort as $k => $v) {
1124 $sortString .= "$k $v,";
1126 return rtrim($sortString, ',');
1132 * Fetch object based on array of properties.
1134 * @param string $daoName
1135 * Name of the dao object.
1136 * @param array $params
1137 * (reference ) an assoc array of name/value pairs.
1138 * @param array $defaults
1139 * (reference ) an assoc array to hold the flattened values.
1140 * @param array $returnProperities
1141 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1144 * an object of type referenced by daoName
1146 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1147 $object = new $daoName();
1148 $object->copyValues($params);
1150 // return only specific fields if returnproperties are sent
1151 if (!empty($returnProperities)) {
1152 $object->selectAdd();
1153 $object->selectAdd(implode(',', $returnProperities));
1156 if ($object->find(TRUE)) {
1157 self
::storeValues($object, $defaults);
1164 * Delete the object records that are associated with this contact.
1166 * @param string $daoName
1167 * Name of the dao object.
1168 * @param int $contactId
1169 * Id of the contact to delete.
1171 public static function deleteEntityContact($daoName, $contactId) {
1172 $object = new $daoName();
1174 $object->entity_table
= 'civicrm_contact';
1175 $object->entity_id
= $contactId;
1180 * execute an unbuffered query. This is a wrapper around new functionality
1181 * exposed with CRM-17748.
1183 * @param string $query query to be executed
1185 * @return Object CRM_Core_DAO object that points to an unbuffered result set
1189 static public function executeUnbufferedQuery(
1195 $i18nRewrite = TRUE,
1196 $trapException = FALSE
1198 $queryStr = self
::composeQuery($query, $params, $abort);
1199 //CRM_Core_Error::debug( 'q', $queryStr );
1201 $dao = new CRM_Core_DAO();
1204 $dao = new $daoName();
1207 if ($trapException) {
1208 CRM_Core_Error
::ignoreException();
1211 // set the DAO object to use an unbuffered query
1212 $dao->setOptions(array('result_buffering' => 0));
1214 $result = $dao->query($queryStr, $i18nRewrite);
1216 if ($trapException) {
1217 CRM_Core_Error
::setCallback();
1220 if (is_a($result, 'DB_Error')) {
1224 // since it is unbuffered, ($dao->N==0) is true. This blocks the standard fetch() mechanism.
1228 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1230 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1240 * @param string $query
1241 * Query to be executed.
1243 * @param array $params
1244 * @param bool $abort
1245 * @param null $daoName
1246 * @param bool $freeDAO
1247 * @param bool $i18nRewrite
1248 * @param bool $trapException
1250 * @return CRM_Core_DAO|object
1251 * object that holds the results of the query
1252 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1253 * out all the properties that are not part of the DAO
1255 public static function &executeQuery(
1261 $i18nRewrite = TRUE,
1262 $trapException = FALSE
1264 $queryStr = self
::composeQuery($query, $params, $abort);
1267 $dao = new CRM_Core_DAO();
1270 $dao = new $daoName();
1273 if ($trapException) {
1274 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1277 $result = $dao->query($queryStr, $i18nRewrite);
1279 if (is_a($result, 'DB_Error')) {
1284 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1286 // we typically do this for insert/update/delete statements OR if explicitly asked to
1294 * Execute a query and get the single result.
1296 * @param string $query
1297 * Query to be executed.
1298 * @param array $params
1299 * @param bool $abort
1300 * @param bool $i18nRewrite
1301 * @return string|null
1302 * the result of the query if any
1305 public static function &singleValueQuery(
1311 $queryStr = self
::composeQuery($query, $params, $abort);
1313 static $_dao = NULL;
1316 $_dao = new CRM_Core_DAO();
1319 $_dao->query($queryStr, $i18nRewrite);
1321 $result = $_dao->getDatabaseResult();
1324 $row = $result->fetchRow();
1334 * Compose the query by merging the parameters into it.
1336 * @param string $query
1337 * @param array $params
1338 * @param bool $abort
1343 public static function composeQuery($query, $params, $abort = TRUE) {
1345 foreach ($params as $key => $item) {
1346 if (is_numeric($key)) {
1347 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1348 $item[0] = self
::escapeString($item[0]);
1349 if ($item[1] == 'String' ||
1350 $item[1] == 'Memo' ||
1353 // Support class constants stipulating wildcard characters and/or
1354 // non-quoting of strings. Also support legacy code which may be
1355 // passing in TRUE or 1 for $item[2], which used to indicate the
1356 // use of wildcard characters.
1357 if (!empty($item[2])) {
1358 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1359 $item[0] = "'%{$item[0]}%'";
1361 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1362 $item[0] = "'{$item[0]}'";
1366 $item[0] = "'{$item[0]}'";
1370 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1371 strlen($item[0]) == 0
1376 $tr['%' . $key] = $item[0];
1379 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1384 return strtr($query, $tr);
1390 public static function freeResult($ids = NULL) {
1391 global $_DB_DATAOBJECT;
1394 if (!$_DB_DATAOBJECT ||
1395 !isset($_DB_DATAOBJECT['RESULTS'])
1399 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1402 foreach ($ids as $id) {
1403 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1404 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1405 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1407 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1410 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1411 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1417 * make a shallow copy of an object.
1418 * and all the fields in the object
1420 * @param string $daoName
1422 * @param array $criteria
1423 * Array of all the fields & values.
1424 * on which basis to copy
1425 * @param array $newData
1426 * Array of all the fields & values.
1427 * to be copied besides the other fields
1428 * @param string $fieldsFix
1429 * Array of fields that you want to prefix/suffix/replace.
1430 * @param string $blockCopyOfDependencies
1431 * Fields that you want to block from.
1435 * @return CRM_Core_DAO
1436 * the newly created copy of the object
1438 public static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1439 $object = new $daoName();
1441 $object->id
= $criteria['id'];
1444 foreach ($criteria as $key => $value) {
1445 $object->$key = $value;
1450 while ($object->fetch()) {
1452 // all the objects except with $blockCopyOfDependencies set
1453 // be copied - addresses #CRM-1962
1455 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1459 $newObject = new $daoName();
1461 $fields = &$object->fields();
1462 if (!is_array($fieldsFix)) {
1463 $fieldsToPrefix = array();
1464 $fieldsToSuffix = array();
1465 $fieldsToReplace = array();
1467 if (!empty($fieldsFix['prefix'])) {
1468 $fieldsToPrefix = $fieldsFix['prefix'];
1470 if (!empty($fieldsFix['suffix'])) {
1471 $fieldsToSuffix = $fieldsFix['suffix'];
1473 if (!empty($fieldsFix['replace'])) {
1474 $fieldsToReplace = $fieldsFix['replace'];
1477 foreach ($fields as $name => $value) {
1478 if ($name == 'id' ||
$value['name'] == 'id') {
1479 // copy everything but the id!
1483 $dbName = $value['name'];
1484 $type = CRM_Utils_Type
::typeToString($value['type']);
1485 $newObject->$dbName = $object->$dbName;
1486 if (isset($fieldsToPrefix[$dbName])) {
1487 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1489 if (isset($fieldsToSuffix[$dbName])) {
1490 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1492 if (isset($fieldsToReplace[$dbName])) {
1493 $newObject->$dbName = $fieldsToReplace[$dbName];
1496 if ($type == 'Timestamp' ||
$type == 'Date') {
1497 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1501 foreach ($newData as $k => $v) {
1502 $newObject->$k = $v;
1512 * Cascade update through related entities.
1514 * @param string $daoName
1517 * @param array $newData
1521 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1522 $object = new $daoName();
1523 $object->id
= $fromId;
1525 if ($object->find(TRUE)) {
1526 $newObject = new $daoName();
1527 $newObject->id
= $toId;
1529 if ($newObject->find(TRUE)) {
1530 $fields = &$object->fields();
1531 foreach ($fields as $name => $value) {
1532 if ($name == 'id' ||
$value['name'] == 'id') {
1533 // copy everything but the id!
1537 $colName = $value['name'];
1538 $newObject->$colName = $object->$colName;
1540 if (substr($name, -5) == '_date' ||
1541 substr($name, -10) == '_date_time'
1543 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1546 foreach ($newData as $k => $v) {
1547 $newObject->$k = $v;
1553 return CRM_Core_DAO
::$_nullObject;
1557 * Given the component id, compute the contact id
1558 * since its used for things like send email
1560 * @param $componentIDs
1561 * @param string $tableName
1565 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1566 $contactIDs = array();
1568 if (empty($componentIDs)) {
1572 $IDs = implode(',', $componentIDs);
1576 WHERE id IN ( $IDs )
1579 $dao = CRM_Core_DAO
::executeQuery($query);
1580 while ($dao->fetch()) {
1581 $contactIDs[] = $dao->contact_id
;
1587 * Fetch object based on array of properties.
1589 * @param string $daoName
1590 * Name of the dao object.
1591 * @param string $fieldIdName
1592 * @param int $fieldId
1594 * @param array $returnProperities
1595 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1598 * an object of type referenced by daoName
1600 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1601 require_once str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php";
1602 $object = new $daoName();
1603 $object->$fieldIdName = $fieldId;
1605 // return only specific fields if returnproperties are sent
1606 if (!empty($returnProperities)) {
1607 $object->selectAdd();
1608 $object->selectAdd('id');
1609 $object->selectAdd(implode(',', $returnProperities));
1613 while ($object->fetch()) {
1614 $defaults = array();
1615 self
::storeValues($object, $defaults);
1616 $details[$object->id
] = $defaults;
1622 public static function dropAllTables() {
1624 // first drop all the custom tables we've created
1625 CRM_Core_BAO_CustomGroup
::dropAllTables();
1627 // drop all multilingual views
1628 CRM_Core_I18n_Schema
::dropAllViews();
1630 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1631 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1632 '..' . DIRECTORY_SEPARATOR
.
1633 '..' . DIRECTORY_SEPARATOR
.
1634 'sql' . DIRECTORY_SEPARATOR
.
1635 'civicrm_drop.mysql'
1644 public static function escapeString($string) {
1645 static $_dao = NULL;
1648 // If this is an atypical case (e.g. preparing .sql files
1649 // before Civi has been installed), then we fallback to
1650 // DB-less escaping helper (mysql_real_escape_string).
1651 // Note: In typical usage, escapeString() will only
1652 // check one conditional ("if !$_dao") rather than
1653 // two conditionals ("if !defined(DSN)")
1654 if (!defined('CIVICRM_DSN')) {
1655 if (function_exists('mysql_real_escape_string')) {
1656 return mysql_real_escape_string($string);
1659 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1663 $_dao = new CRM_Core_DAO();
1666 return $_dao->escape($string);
1670 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1672 * @param array $strings
1673 * @param string $default
1674 * the value to use if $strings has no elements.
1676 * eg "abc","def","ghi"
1678 public static function escapeStrings($strings, $default = NULL) {
1679 static $_dao = NULL;
1681 $_dao = new CRM_Core_DAO();
1684 if (empty($strings)) {
1688 $escapes = array_map(array($_dao, 'escape'), $strings);
1689 return '"' . implode('","', $escapes) . '"';
1697 public static function escapeWildCardString($string) {
1699 // ensure we escape the single characters % and _ which are mysql wild
1700 // card characters and could come in via sortByCharacter
1701 // note that mysql does not escape these characters
1702 if ($string && in_array($string,
1703 array('%', '_', '%%', '_%')
1706 return '\\' . $string;
1709 return self
::escapeString($string);
1713 * Creates a test object, including any required objects it needs via recursion
1714 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1715 * ONLY USE FOR TESTING
1717 * @param string $daoName
1718 * @param array $params
1719 * @param int $numObjects
1720 * @param bool $createOnly
1722 * @return object|array|NULL
1723 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1725 public static function createTestObject(
1731 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1732 // so we re-set here in case
1733 $config = CRM_Core_Config
::singleton();
1734 $config->backtrace
= TRUE;
1736 static $counter = 0;
1737 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1738 'CRM_Core_DAO_Worldregion',
1739 'CRM_Core_DAO_StateProvince',
1740 'CRM_Core_DAO_Country',
1741 'CRM_Core_DAO_Domain',
1742 'CRM_Financial_DAO_FinancialType',
1743 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1746 // Prefer to instantiate BAO's instead of DAO's (when possible)
1747 // so that assignTestValue()/assignTestFK() can be overloaded.
1748 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1749 if (class_exists($baoName)) {
1750 $daoName = $baoName;
1753 for ($i = 0; $i < $numObjects; ++
$i) {
1756 /** @var CRM_Core_DAO $object */
1757 $object = new $daoName();
1759 $fields = &$object->fields();
1760 foreach ($fields as $fieldName => $fieldDef) {
1761 $dbName = $fieldDef['name'];
1762 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1763 $required = CRM_Utils_Array
::value('required', $fieldDef);
1765 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1766 $object->$dbName = $params[$dbName];
1769 elseif ($dbName != 'id') {
1770 if ($FKClassName != NULL) {
1771 $object->assignTestFK($fieldName, $fieldDef, $params);
1775 $object->assignTestValue($fieldName, $fieldDef, $counter);
1783 $objects[$i] = $object;
1793 elseif ($numObjects == 1) {
1802 * Deletes the this object plus any dependent objects that are associated with it.
1803 * ONLY USE FOR TESTING
1805 * @param string $daoName
1806 * @param array $params
1808 public static function deleteTestObjects($daoName, $params = array()) {
1809 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1810 // so we re-set here in case
1811 $config = CRM_Core_Config
::singleton();
1812 $config->backtrace
= TRUE;
1814 $object = new $daoName();
1815 $object->id
= CRM_Utils_Array
::value('id', $params);
1817 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1818 if ($object->find(TRUE)) {
1820 $fields = &$object->fields();
1821 foreach ($fields as $name => $value) {
1823 $dbName = $value['name'];
1825 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1826 $required = CRM_Utils_Array
::value('required', $value);
1827 if ($FKClassName != NULL
1829 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1830 && ($required ||
$dbName == 'contact_id')
1831 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1832 // to make this test process pass - line below makes pass for now
1833 && $dbName != 'member_of_contact_id'
1835 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1842 foreach ($deletions as $deletion) {
1843 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1848 * Set defaults when creating new entity.
1849 * (don't call this set defaults as already in use with different signature in some places)
1851 * @param array $params
1854 public static function setCreateDefaults(&$params, $defaults) {
1855 if (!empty($params['id'])) {
1858 foreach ($defaults as $key => $value) {
1859 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1860 $params[$key] = $value;
1866 * @param string $prefix
1867 * @param bool $addRandomString
1868 * @param null $string
1872 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1873 $tableName = $prefix . "_temp";
1875 if ($addRandomString) {
1877 $tableName .= "_" . $string;
1880 $tableName .= "_" . md5(uniqid('', TRUE));
1888 * @param bool $trigger
1892 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1893 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1895 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1896 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1897 $dao = new CRM_Core_DAO();
1899 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1900 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1906 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1907 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1909 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1914 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1915 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1917 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1924 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1925 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1934 * @param null $message
1935 * @param bool $printDAO
1937 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1938 CRM_Utils_System
::xMemory("{$message}: ");
1941 global $_DB_DATAOBJECT;
1943 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1944 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1946 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1951 * Build a list of triggers via hook and add them to (err, reconcile them
1952 * with) the database.
1954 * @param string $tableName
1955 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1956 * @param bool $force
1961 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1962 Civi
::service('sql_triggers')->rebuild($tableName, $force);
1966 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1967 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1968 * TODO: Alternative solutions might be
1969 * * Stop using functions and find another way to strip numeric characters from phones
1970 * * Give better error messages (currently a missing fn fatals with "unknown error")
1972 public static function checkSqlFunctionsExist() {
1973 if (!self
::$_checkedSqlFunctionsExist) {
1974 self
::$_checkedSqlFunctionsExist = TRUE;
1975 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1976 if (!$dao->fetch()) {
1977 self
::triggerRebuild();
1983 * Wrapper function to drop triggers.
1985 * @param string $tableName
1986 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1989 public static function dropTriggers($tableName = NULL) {
1990 Civi
::service('sql_triggers')->dropTriggers($tableName);
1994 * @param array $info
1995 * per hook_civicrm_triggerInfo.
1996 * @param string $onlyTableName
1997 * the specific table requiring a rebuild; or NULL to rebuild all tables.
2000 public static function createTriggers(&$info, $onlyTableName = NULL) {
2001 Civi
::service('sql_triggers')->createTriggers($info, $onlyTableName);
2005 * Given a list of fields, create a list of references.
2007 * @param string $className
2008 * BAO/DAO class name.
2009 * @return array<CRM_Core_Reference_Interface>
2011 public static function createReferenceColumns($className) {
2013 $fields = $className::fields();
2014 foreach ($fields as $field) {
2015 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2016 $result[] = new CRM_Core_Reference_OptionValue(
2017 $className::getTableName(),
2019 'civicrm_option_value',
2020 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2021 $field['pseudoconstant']['optionGroupName']
2029 * Find all records which refer to this entity.
2032 * Array of objects referencing this
2034 public function findReferences() {
2035 $links = self
::getReferencesToTable(static::getTableName());
2037 $occurrences = array();
2038 foreach ($links as $refSpec) {
2039 /** @var $refSpec CRM_Core_Reference_Interface */
2040 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2041 $result = $refSpec->findReferences($this);
2043 while ($result->fetch()) {
2044 $obj = new $daoName();
2045 $obj->id
= $result->id
;
2046 $occurrences[] = $obj;
2051 return $occurrences;
2056 * each item has keys:
2060 * - table: string|null SQL table name
2061 * - key: string|null SQL column name
2063 public function getReferenceCounts() {
2064 $links = self
::getReferencesToTable(static::getTableName());
2067 foreach ($links as $refSpec) {
2068 /** @var $refSpec CRM_Core_Reference_Interface */
2069 $count = $refSpec->getReferenceCount($this);
2070 if ($count['count'] != 0) {
2075 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2076 /** @var $component CRM_Core_Component_Info */
2077 $counts = array_merge($counts, $component->getReferenceCounts($this));
2079 CRM_Utils_Hook
::referenceCounts($this, $counts);
2085 * List all tables which have hard foreign keys to this table.
2087 * For now, this returns a description of every entity_id/entity_table
2089 * TODO: filter dynamic entity references on the $tableName, based on
2090 * schema metadata in dynamicForeignKey which enumerates a restricted
2091 * set of possible entity_table's.
2093 * @param string $tableName
2094 * Table referred to.
2097 * structure of table and column, listing every table with a
2098 * foreign key reference to $tableName, and the column where the key appears.
2100 public static function getReferencesToTable($tableName) {
2101 $refsFound = array();
2102 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2103 $links = $daoClassName::getReferenceColumns();
2104 $daoTableName = $daoClassName::getTableName();
2106 foreach ($links as $refSpec) {
2107 /** @var $refSpec CRM_Core_Reference_Interface */
2108 if ($refSpec->matchesTargetTable($tableName)) {
2109 $refsFound[] = $refSpec;
2117 * Lookup the value of a MySQL global configuration variable.
2119 * @param string $name
2120 * E.g. "thread_stack".
2121 * @param mixed $default
2124 public static function getGlobalSetting($name, $default = NULL) {
2125 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2126 // that has been reported to fail under MySQL 5.0 for OS X
2127 $escapedName = self
::escapeString($name);
2128 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2129 if ($dao->fetch()) {
2138 * Get options for the called BAO object's field.
2139 * This function can be overridden by each BAO to add more logic related to context.
2140 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2142 * @param string $fieldName
2143 * @param string $context
2144 * @see CRM_Core_DAO::buildOptionsContext
2145 * @param array $props
2146 * whatever is known about this bao object.
2148 * @return array|bool
2150 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2151 // If a given bao does not override this function
2152 $baoName = get_called_class();
2153 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2157 * Populate option labels for this object's fields.
2159 * @throws exception if called directly on the base class
2161 public function getOptionLabels() {
2162 $fields = $this->fields();
2163 if ($fields === NULL) {
2164 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2166 foreach ($fields as $field) {
2167 $name = CRM_Utils_Array
::value('name', $field);
2168 if ($name && isset($this->$name)) {
2169 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2170 if ($label !== FALSE) {
2171 // Append 'label' onto the field name
2172 $labelName = $name . '_label';
2173 $this->$labelName = $label;
2180 * Provides documentation and validation for the buildOptions $context param
2182 * @param string $context
2187 public static function buildOptionsContext($context = NULL) {
2189 'get' => "get: all options are returned, even if they are disabled; labels are translated.",
2190 'create' => "create: options are filtered appropriately for the object being created/updated; labels are translated.",
2191 'search' => "search: searchable options are returned; labels are translated.",
2192 'validate' => "validate: all options are returned, even if they are disabled; machine names are used in place of labels.",
2193 'abbreviate' => "abbreviate: enabled options are returned; labels are replaced with abbreviations.",
2194 'match' => "match: enabled options are returned using machine names as keys; labels are translated.",
2196 // Validation: enforce uniformity of this param
2197 if ($context !== NULL && !isset($contexts[$context])) {
2198 throw new Exception("'$context' is not a valid context for buildOptions.");
2204 * @param string $fieldName
2205 * @return bool|array
2207 public function getFieldSpec($fieldName) {
2208 $fields = $this->fields();
2209 $fieldKeys = $this->fieldKeys();
2211 // Support "unique names" as well as sql names
2212 $fieldKey = $fieldName;
2213 if (empty($fields[$fieldKey])) {
2214 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2216 // If neither worked then this field doesn't exist. Return false.
2217 if (empty($fields[$fieldKey])) {
2220 return $fields[$fieldKey];
2224 * Get SQL where clause for SQL filter syntax input parameters.
2226 * SQL version of api function to assign filters to the DAO based on the syntax
2227 * $field => array('IN' => array(4,6,9))
2229 * $field => array('LIKE' => array('%me%))
2232 * @param string $fieldName
2234 * @param array $filter
2235 * filter to be applied indexed by operator.
2236 * @param string $type
2237 * type of field (not actually used - nor in api @todo ).
2238 * @param string $alias
2239 * alternative field name ('as') @todo- not actually used.
2240 * @param bool $returnSanitisedArray
2241 * Return a sanitised array instead of a clause.
2242 * this is primarily so we can add filters @ the api level to the Query object based fields
2246 * @return NULL|string|array
2247 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2248 * depending on whether it is supported as yet
2250 public static function createSQLFilter($fieldName, $filter, $type = NULL, $alias = NULL, $returnSanitisedArray = FALSE) {
2251 foreach ($filter as $operator => $criteria) {
2252 if (in_array($operator, self
::acceptedSQLOperators(), TRUE)) {
2253 switch ($operator) {
2257 if (!$returnSanitisedArray) {
2258 return (sprintf('%s %s', $fieldName, $operator));
2261 return (sprintf('%s %s ', $fieldName, $operator));
2265 // ternary operators
2268 if (empty($criteria[0]) ||
empty($criteria[1])) {
2269 throw new Exception("invalid criteria for $operator");
2271 if (!$returnSanitisedArray) {
2272 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2275 return NULL; // not yet implemented (tests required to implement)
2282 if (empty($criteria)) {
2283 throw new Exception("invalid criteria for $operator");
2285 $escapedCriteria = array_map(array(
2289 if (!$returnSanitisedArray) {
2290 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2292 return $escapedCriteria;
2297 if (!$returnSanitisedArray) {
2298 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2301 return NULL; // not yet implemented (tests required to implement)
2309 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2310 * support for other syntaxes is discussed in ticket but being put off for now
2313 public static function acceptedSQLOperators() {
2334 * SQL has a limit of 64 characters on various names:
2335 * table name, trigger name, column name ...
2337 * For custom groups and fields we generated names from user entered input
2338 * which can be longer than this length, this function helps with creating
2339 * strings that meet various criteria.
2341 * @param string $string
2342 * The string to be shortened.
2343 * @param int $length
2344 * The max length of the string.
2346 * @param bool $makeRandom
2350 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2351 // early return for strings that meet the requirements
2352 if (strlen($string) <= $length) {
2356 // easy return for calls that dont need a randomized uniq string
2358 return substr($string, 0, $length);
2361 // the string is longer than the length and we need a uniq string
2362 // for the same tablename we need the same uniq string every time
2363 // hence we use md5 on the string, which is not random
2364 // we'll append 8 characters to the end of the tableName
2365 $md5string = substr(md5($string), 0, 8);
2366 return substr($string, 0, $length - 8) . "_{$md5string}";
2370 * https://issues.civicrm.org/jira/browse/CRM-17748
2371 * Sets the internal options to be used on a query
2373 * @param array $options
2376 public function setOptions($options) {
2377 if (is_array($options)) {
2378 $this->_options
= $options;
2383 * https://issues.civicrm.org/jira/browse/CRM-17748
2384 * wrapper to pass internal DAO options down to DB_mysql/DB_Common level
2386 * @param array $options
2389 protected function _setDBOptions($options) {
2390 global $_DB_DATAOBJECT;
2392 if (is_array($options) && count($options)) {
2393 $conn = &$_DB_DATAOBJECT['CONNECTIONS'][$this->_database_dsn_md5
];
2394 foreach ($options as $option_name => $option_value) {
2395 $conn->setOption($option_name, $option_value);
2402 * @param array $params
2404 public function setApiFilter(&$params) {
2408 * Generates acl clauses suitable for adding to WHERE or ON when doing an api.get for this entity
2410 * Return format is in the form of fieldname => clauses starting with an operator. e.g.:
2413 * 'location_type_id' => array('IS NOT NULL', 'IN (1,2,3)')
2417 * Note that all array keys must be actual field names in this entity. Use subqueries to filter on other tables e.g. custom values.
2421 public function addSelectWhereClause() {
2422 // This is the default fallback, and works for contact-related entities like Email, Relationship, etc.
2424 foreach ($this->fields() as $fieldName => $field) {
2425 if (strpos($fieldName, 'contact_id') === 0 && CRM_Utils_Array
::value('FKClassName', $field) == 'CRM_Contact_DAO_Contact') {
2426 $clauses[$fieldName] = CRM_Utils_SQL
::mergeSubquery('Contact');
2429 CRM_Utils_Hook
::selectWhereClause($this, $clauses);
2434 * This returns the final permissioned query string for this entity
2436 * With acls from related entities + additional clauses from hook_civicrm_selectWhereClause
2438 * @param string $tableAlias
2441 public static function getSelectWhereClause($tableAlias = NULL) {
2442 $bao = new static();
2443 if ($tableAlias === NULL) {
2444 $tableAlias = $bao->tableName();
2447 foreach ((array) $bao->addSelectWhereClause() as $field => $vals) {
2448 $clauses[$field] = NULL;
2450 $clauses[$field] = "`$tableAlias`.`$field` " . implode(" AND `$tableAlias`.`$field` ", (array) $vals);
2457 * function to check valid db name containing only characters in [0-9,a-z,A-Z_]
2463 public static function requireValidDBName($database) {
2466 "/^[0-9]*[a-zA-Z_]+[a-zA-Z0-9_]*$/",
2470 if (empty($matches)) {