3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
40 require_once 'CRM/Core/I18n.php';
45 class CRM_Core_DAO
extends DB_DataObject
{
48 * a null object so we can pass it as reference if / when needed
50 static $_nullObject = NULL;
51 static $_nullArray = array();
53 static $_dbColumnValueCache = NULL;
54 CONST NOT_NULL
= 1, IS_NULL
= 2,
56 VALUE_SEPARATOR
= "\ 1",
57 BULK_INSERT_COUNT
= 200,
58 BULK_INSERT_HIGH_COUNT
= 200,
59 // special value for mail bulk inserts to avoid
60 // potential duplication, assuming a smaller number reduces number of queries
61 // by some factor, so some tradeoff. CRM-8678
62 BULK_MAIL_INSERT_COUNT
= 10,
63 QUERY_FORMAT_WILDCARD
= 1,
64 QUERY_FORMAT_NO_QUOTES
= 2;
67 * Define entities that shouldn't be created or deleted when creating/ deleting
68 * test objects - this prevents world regions, countries etc from being added / deleted
70 static $_testEntitiesToSkip = array();
72 * the factory class for this application
75 static $_factory = NULL;
77 static $_checkedSqlFunctionsExist = FALSE;
82 * @return \CRM_Core_DAO
85 function __construct() {
87 $this->__table
= $this->getTableName();
91 * empty definition for virtual function
93 static function getTableName() {
98 * initialize the DAO object
100 * @param string $dsn the database connection string
106 static function init($dsn) {
107 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
108 $options['database'] = $dsn;
109 if (defined('CIVICRM_DAO_DEBUG')) {
110 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
120 protected function assignTestFK($fieldName, $fieldDef, $params) {
121 $required = CRM_Utils_Array
::value('required', $fieldDef);
122 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
123 $dbName = $fieldDef['name'];
124 $daoName = get_class($this);
126 // skip the FK if it is not required
127 // if it's contact id we should create even if not required
128 // we'll have a go @ fetching first though
129 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
130 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
133 if (!$required && $dbName != 'contact_id') {
134 $fkDAO = new $FKClassName;
135 if ($fkDAO->find(TRUE)) {
136 $this->$dbName = $fkDAO->id
;
141 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
142 $depObject = new $FKClassName();
143 $depObject->find(TRUE);
144 $this->$dbName = $depObject->id
;
147 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
148 // FIXME: the fields() metadata is not specific enough
149 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
150 $this->$dbName = $depObject->id
;
154 //if it is required we need to generate the dependency object first
155 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
156 $this->$dbName = $depObject->id
;
162 * Generate and assign an arbitrary value to a field of a test object.
164 * @param string $fieldName
165 * @param array $fieldDef
166 * @param int $counter the globally-unique ID of the test object
168 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
169 $dbName = $fieldDef['name'];
170 $daoName = get_class($this);
173 if (!$handled && $dbName == 'contact_sub_type') {
174 //coming up with a rule to set this is too complex let's not set it
178 // Pick an option value if needed
179 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
180 $options = $daoName::buildOptions($dbName, 'create');
182 $this->$dbName = key($options);
188 switch ($fieldDef['type']) {
189 case CRM_Utils_Type
::T_INT
:
190 case CRM_Utils_Type
::T_FLOAT
:
191 case CRM_Utils_Type
::T_MONEY
:
192 if (isset($fieldDef['precision'])) {
193 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
194 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
197 $this->$dbName = $counter;
201 case CRM_Utils_Type
::T_BOOLEAN
:
202 if (isset($fieldDef['default'])) {
203 $this->$dbName = $fieldDef['default'];
205 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
213 case CRM_Utils_Type
::T_DATE
:
214 case CRM_Utils_Type
::T_TIMESTAMP
:
215 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
216 $this->$dbName = '19700101';
217 if ($dbName == 'end_date') {
218 // put this in the future
219 $this->$dbName = '20200101';
223 case CRM_Utils_Type
::T_TIME
:
224 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
225 //$object->$dbName='000000';
227 case CRM_Utils_Type
::T_CCNUM
:
228 $this->$dbName = '4111 1111 1111 1111';
231 case CRM_Utils_Type
::T_URL
:
232 $this->$dbName = 'http://www.civicrm.org';
235 case CRM_Utils_Type
::T_STRING
:
236 case CRM_Utils_Type
::T_BLOB
:
237 case CRM_Utils_Type
::T_MEDIUMBLOB
:
238 case CRM_Utils_Type
::T_TEXT
:
239 case CRM_Utils_Type
::T_LONGTEXT
:
240 case CRM_Utils_Type
::T_EMAIL
:
242 // WAS: if (isset($value['enumValues'])) {
243 // TODO: see if this works with all pseudoconstants
244 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
245 if (isset($fieldDef['default'])) {
246 $this->$dbName = $fieldDef['default'];
249 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
250 if (is_array($options)) {
251 $this->$dbName = $options[0];
254 $defaultValues = explode(',', $options);
255 $this->$dbName = $defaultValues[0];
260 $this->$dbName = $dbName . '_' . $counter;
261 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
262 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
263 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
271 * reset the DAO object. DAO is kinda crappy in that there is an unwritten
272 * rule of one query per DAO. We attempt to get around this crappy restricrion
273 * by resetting some of DAO's internal fields. Use this with caution
281 foreach (array_keys($this->table()) as $field) {
282 unset($this->$field);
286 * reset the various DB_DAO structures manually
288 $this->_query
= array();
299 static function getLocaleTableName($tableName) {
302 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
303 if (in_array($tableName, $tables)) {
304 return $tableName . $dbLocale;
311 * Execute a query by the current DAO, localizing it along the way (if needed).
313 * @param string $query the SQL query for execution
314 * @param bool $i18nRewrite whether to rewrite the query
316 * @return object the current DAO object after the query execution
318 function query($query, $i18nRewrite = TRUE) {
319 // rewrite queries that should use $dbLocale-based views for multi-language installs
321 if ($i18nRewrite and $dbLocale) {
322 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
325 return parent
::query($query);
329 * Static function to set the factory instance for this class.
331 * @param object $factory the factory application object
337 static function setFactory(&$factory) {
338 self
::$_factory = &$factory;
342 * Factory method to instantiate a new object from a table name.
344 * @param string $table
349 function factory($table = '') {
350 if (!isset(self
::$_factory)) {
351 return parent
::factory($table);
354 return self
::$_factory->create($table);
358 * Initialization for all DAO objects. Since we access DB_DO programatically
359 * we need to set the links manually.
364 function initialize() {
366 $this->query("SET NAMES utf8");
370 * Defines the default key as 'id'.
385 * Tells DB_DataObject which keys use autoincrement.
386 * 'id' is autoincrementing by default.
392 function sequenceKey() {
393 static $sequenceKeys;
394 if (!isset($sequenceKeys)) {
395 $sequenceKeys = array('id', TRUE);
397 return $sequenceKeys;
401 * returns list of FK relationships
406 * @return array of CRM_Core_Reference_Interface
408 static function getReferenceColumns() {
413 * returns all the column names of this table
419 static function &fields() {
425 * get/set an associative array of table columns
428 * @param array key=>type array
429 * @return array (associative)
432 $fields = &$this->fields();
436 foreach ($fields as $name => $value) {
437 $table[$value['name']] = $value['type'];
438 if (!empty($value['required'])) {
439 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
451 if (!empty($this->id
)) {
454 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
455 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
460 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
461 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
465 CRM_Utils_Hook
::postSave($this);
470 function delete($useWhere = FALSE) {
471 $result = parent
::delete($useWhere);
473 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
474 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
480 * @param bool $created
482 function log($created = FALSE) {
485 if (!$this->getLog()) {
490 $session = CRM_Core_Session
::singleton();
491 $cid = $session->get('userID');
494 // return is we dont have handle to FK
499 $dao = new CRM_Core_DAO_Log();
500 $dao->entity_table
= $this->getTableName();
501 $dao->entity_id
= $this->id
;
502 $dao->modified_id
= $cid;
503 $dao->modified_date
= date("YmdHis");
508 * Given an associative array of name/value pairs, extract all the values
509 * that belong to this object and initialize the object with said values
511 * @param array $params (reference ) associative array of name/value pairs
513 * @return boolean did we copy all null values into the object
516 function copyValues(&$params) {
517 $fields = &$this->fields();
519 foreach ($fields as $name => $value) {
520 $dbName = $value['name'];
521 if (array_key_exists($dbName, $params)) {
522 $pValue = $params[$dbName];
525 elseif (array_key_exists($name, $params)) {
526 $pValue = $params[$name];
533 // if there is no value then make the variable NULL
535 if ($pValue === '') {
536 $this->$dbName = 'null';
539 $this->$dbName = $pValue;
548 * Store all the values from this object in an associative array
549 * this is a destructive store, calling function is responsible
550 * for keeping sanity of id's.
552 * @param object $object the object that we are extracting data from
553 * @param array $values (reference ) associative array of name/value pairs
559 static function storeValues(&$object, &$values) {
560 $fields = &$object->fields();
561 foreach ($fields as $name => $value) {
562 $dbName = $value['name'];
563 if (isset($object->$dbName) && $object->$dbName !== 'null') {
564 $values[$dbName] = $object->$dbName;
565 if ($name != $dbName) {
566 $values[$name] = $object->$dbName;
573 * create an attribute for this specific field. We only do this for strings and text
575 * @param array $field the field under task
577 * @return array|null the attributes for the object
581 static function makeAttribute($field) {
583 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
584 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
585 $size = CRM_Utils_Array
::value('size', $field);
586 if ($maxLength ||
$size) {
587 $attributes = array();
589 $attributes['maxlength'] = $maxLength;
592 $attributes['size'] = $size;
597 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
598 $rows = CRM_Utils_Array
::value('rows', $field);
602 $cols = CRM_Utils_Array
::value('cols', $field);
607 $attributes = array();
608 $attributes['rows'] = $rows;
609 $attributes['cols'] = $cols;
612 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
) {
613 $attributes['size'] = 6;
614 $attributes['maxlength'] = 14;
622 * Get the size and maxLength attributes for this text field
623 * (or for all text fields) in the DAO object.
625 * @param string $class name of DAO class
626 * @param string $fieldName field that i'm interested in or null if
627 * you want the attributes for all DAO text fields
629 * @return array assoc array of name => attribute pairs
633 static function getAttribute($class, $fieldName = NULL) {
634 $object = new $class( );
635 $fields = &$object->fields();
636 if ($fieldName != NULL) {
637 $field = CRM_Utils_Array
::value($fieldName, $fields);
638 return self
::makeAttribute($field);
641 $attributes = array();
642 foreach ($fields as $name => $field) {
643 $attribute = self
::makeAttribute($field);
645 $attributes[$name] = $attribute;
649 if (!empty($attributes)) {
661 static function transaction($type) {
662 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
666 * Check if there is a record with the same name in the db
668 * @param string $value the value of the field we are checking
669 * @param string $daoName the dao object name
670 * @param string $daoID the id of the object being updated. u can change your name
671 * as long as there is no conflict
672 * @param string $fieldName the name of the field in the DAO
674 * @return boolean true if object exists
678 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
679 $object = new $daoName( );
680 $object->$fieldName = $value;
682 $config = CRM_Core_Config
::singleton();
684 if ($object->find(TRUE)) {
685 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
693 * Check if there is a given column in a specific table
695 * @param string $tableName
696 * @param string $columnName
697 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
699 * @return boolean true if exists, else false
702 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
708 $params = array(1 => array($columnName, 'String'));
709 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
710 $result = $dao->fetch() ?
TRUE : FALSE;
716 * Returns the storage engine used by given table-name(optional).
717 * Otherwise scans all the tables and return an array of all the
718 * distinct storage engines being used.
720 * @param string $tableName
722 * @param int $maxTablesToCheck
723 * @param string $fieldName
728 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
730 $query = "SHOW TABLE STATUS LIKE %1";
734 if (isset($tableName)) {
735 $params = array(1 => array($tableName, 'String'));
738 $params = array(1 => array('civicrm_%', 'String'));
741 $dao = CRM_Core_DAO
::executeQuery($query, $params);
744 while ($dao->fetch()) {
745 if (isset($values[$dao->$fieldName]) ||
746 // ignore import and other temp tables
747 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
748 strpos($dao->Name
, '_temp') !== FALSE
752 $values[$dao->$fieldName] = 1;
754 if ($maxTablesToCheck &&
755 $count >= $maxTablesToCheck
765 * @param int $maxTablesToCheck
769 static function isDBMyISAM($maxTablesToCheck = 10) {
770 // show error if any of the tables, use 'MyISAM' storage engine.
771 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
772 if (array_key_exists('MyISAM', $engines)) {
779 * Checks if a constraint exists for a specified table.
781 * @param string $tableName
782 * @param string $constraint
784 * @return boolean true if constraint exists, false otherwise
787 static function checkConstraintExists($tableName, $constraint) {
788 static $show = array();
790 if (!array_key_exists($tableName, $show)) {
791 $query = "SHOW CREATE TABLE $tableName";
792 $dao = CRM_Core_DAO
::executeQuery($query);
794 if (!$dao->fetch()) {
795 CRM_Core_Error
::fatal();
799 $show[$tableName] = $dao->Create_Table
;
802 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
806 * Checks if CONSTRAINT keyword exists for a specified table.
808 * @param array $tables
811 * @internal param string $tableName
813 * @return boolean true if CONSTRAINT keyword exists, false otherwise
815 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
817 foreach($tables as $tableName){
818 if (!array_key_exists($tableName, $show)) {
819 $query = "SHOW CREATE TABLE $tableName";
820 $dao = CRM_Core_DAO
::executeQuery($query);
822 if (!$dao->fetch()) {
823 CRM_Core_Error
::fatal();
827 $show[$tableName] = $dao->Create_Table
;
830 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
842 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
843 * for a specified column of a table.
845 * @param string $tableName
846 * @param string $columnName
848 * @return boolean true if in format, false otherwise
851 static function checkFKConstraintInFormat($tableName, $columnName) {
852 static $show = array();
854 if (!array_key_exists($tableName, $show)) {
855 $query = "SHOW CREATE TABLE $tableName";
856 $dao = CRM_Core_DAO
::executeQuery($query);
858 if (!$dao->fetch()) {
859 CRM_Core_Error
::fatal();
863 $show[$tableName] = $dao->Create_Table
;
865 $constraint = "`FK_{$tableName}_{$columnName}`";
866 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
867 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
871 * Check whether a specific column in a specific table has always the same value
873 * @param string $tableName
874 * @param string $columnName
875 * @param string $columnValue
877 * @return boolean true if the value is always $columnValue, false otherwise
880 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
881 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
882 $dao = CRM_Core_DAO
::executeQuery($query);
883 $result = $dao->fetch() ?
FALSE : TRUE;
889 * Check whether a specific column in a specific table is always NULL
891 * @param string $tableName
892 * @param string $columnName
894 * @return boolean true if if the value is always NULL, false otherwise
897 static function checkFieldIsAlwaysNull($tableName, $columnName) {
898 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
899 $dao = CRM_Core_DAO
::executeQuery($query);
900 $result = $dao->fetch() ?
FALSE : TRUE;
906 * Check if there is a given table in the database
908 * @param string $tableName
910 * @return boolean true if exists, else false
913 static function checkTableExists($tableName) {
918 $params = array(1 => array($tableName, 'String'));
920 $dao = CRM_Core_DAO
::executeQuery($query, $params);
921 $result = $dao->fetch() ?
TRUE : FALSE;
931 function checkVersion($version) {
936 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
937 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
941 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
943 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
944 * @param int $searchValue Value of the column you want to search by
945 * @param string $returnColumn Name of the column you want to GET the value of
946 * @param string $searchColumn Name of the column you want to search by
947 * @param boolean $force Skip use of the cache
949 * @return string|null Value of $returnColumn in the retrieved record
953 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
955 empty($searchValue) ||
956 trim(strtolower($searchValue)) == 'null'
958 // adding this year since developers forget to check for an id
959 // or for the 'null' (which is a bad DAO kludge)
960 // and hence we get the first value in the db
961 CRM_Core_Error
::fatal();
964 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
965 if (self
::$_dbColumnValueCache === NULL) {
966 self
::$_dbColumnValueCache = array();
969 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
970 $object = new $daoName( );
971 $object->$searchColumn = $searchValue;
972 $object->selectAdd();
973 $object->selectAdd($returnColumn);
976 if ($object->find(TRUE)) {
977 $result = $object->$returnColumn;
981 self
::$_dbColumnValueCache[$cacheKey] = $result;
983 return self
::$_dbColumnValueCache[$cacheKey];
987 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
989 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
990 * @param int $searchValue Value of the column you want to search by
991 * @param string $setColumn Name of the column you want to SET the value of
992 * @param string $setValue SET the setColumn to this value
993 * @param string $searchColumn Name of the column you want to search by
995 * @return boolean true if we found and updated the object, else false
999 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1000 $object = new $daoName( );
1001 $object->selectAdd();
1002 $object->selectAdd("$searchColumn, $setColumn");
1003 $object->$searchColumn = $searchValue;
1005 if ($object->find(TRUE)) {
1006 $object->$setColumn = $setValue;
1007 if ($object->save()) {
1018 * @param array|object $sort either array or CRM_Utils_Sort
1019 * @param string $default - default sort value
1021 * @return string - sortString
1025 static function getSortString($sort, $default = NULL) {
1026 // check if sort is of type CRM_Utils_Sort
1027 if (is_a($sort, 'CRM_Utils_Sort')) {
1028 return $sort->orderBy();
1031 // is it an array specified as $field => $sortDirection ?
1033 foreach ($sort as $k => $v) {
1034 $sortString .= "$k $v,";
1036 return rtrim($sortString, ',');
1042 * Takes a bunch of params that are needed to match certain criteria and
1043 * retrieves the relevant objects. Typically the valid params are only
1044 * contact_id. We'll tweak this function to be more full featured over a period
1045 * of time. This is the inverse function of create. It also stores all the retrieved
1046 * values in the default array
1048 * @param string $daoName name of the dao object
1049 * @param array $params (reference ) an assoc array of name/value pairs
1050 * @param array $defaults (reference ) an assoc array to hold the flattened values
1051 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1053 * @return object an object of type referenced by daoName
1057 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1058 $object = new $daoName( );
1059 $object->copyValues($params);
1061 // return only specific fields if returnproperties are sent
1062 if (!empty($returnProperities)) {
1063 $object->selectAdd();
1064 $object->selectAdd(implode(',', $returnProperities));
1067 if ($object->find(TRUE)) {
1068 self
::storeValues($object, $defaults);
1075 * Delete the object records that are associated with this contact
1077 * @param string $daoName name of the dao object
1078 * @param int $contactId id of the contact to delete
1084 static function deleteEntityContact($daoName, $contactId) {
1085 $object = new $daoName( );
1087 $object->entity_table
= 'civicrm_contact';
1088 $object->entity_id
= $contactId;
1095 * @param string $query query to be executed
1097 * @param array $params
1098 * @param bool $abort
1099 * @param null $daoName
1100 * @param bool $freeDAO
1101 * @param bool $i18nRewrite
1102 * @param bool $trapException
1104 * @return Object CRM_Core_DAO object that holds the results of the query
1108 static function &executeQuery(
1114 $i18nRewrite = TRUE,
1115 $trapException = FALSE
1117 $queryStr = self
::composeQuery($query, $params, $abort);
1118 //CRM_Core_Error::debug( 'q', $queryStr );
1121 $dao = new CRM_Core_DAO();
1124 $dao = new $daoName( );
1127 if ($trapException) {
1128 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1131 $result = $dao->query($queryStr, $i18nRewrite);
1133 if (is_a($result, 'DB_Error')) {
1138 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1140 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1148 * execute a query and get the single result
1150 * @param string $query query to be executed
1151 * @param array $params
1152 * @param bool $abort
1153 * @param bool $i18nRewrite
1154 * @return string|null the result of the query if any
1159 static function &singleValueQuery($query,
1164 $queryStr = self
::composeQuery($query, $params, $abort);
1166 static $_dao = NULL;
1169 $_dao = new CRM_Core_DAO();
1172 $_dao->query($queryStr, $i18nRewrite);
1174 $result = $_dao->getDatabaseResult();
1177 $row = $result->fetchRow();
1189 * @param bool $abort
1194 static function composeQuery($query, &$params, $abort = TRUE) {
1196 foreach ($params as $key => $item) {
1197 if (is_numeric($key)) {
1198 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1199 $item[0] = self
::escapeString($item[0]);
1200 if ($item[1] == 'String' ||
1201 $item[1] == 'Memo' ||
1204 // Support class constants stipulating wildcard characters and/or
1205 // non-quoting of strings. Also support legacy code which may be
1206 // passing in TRUE or 1 for $item[2], which used to indicate the
1207 // use of wildcard characters.
1208 if (!empty($item[2])) {
1209 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1210 $item[0] = "'%{$item[0]}%'";
1212 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1213 $item[0] = "'{$item[0]}'";
1217 $item[0] = "'{$item[0]}'";
1221 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1222 strlen($item[0]) == 0
1227 $tr['%' . $key] = $item[0];
1230 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1235 return strtr($query, $tr);
1241 static function freeResult($ids = NULL) {
1242 global $_DB_DATAOBJECT;
1246 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1247 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1249 CRM_Core_Error::debug( 'k', $q );
1254 if (!$_DB_DATAOBJECT ||
1255 !isset($_DB_DATAOBJECT['RESULTS'])
1259 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1262 foreach ($ids as $id) {
1263 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1264 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1265 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1267 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1270 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1271 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1277 * This function is to make a shallow copy of an object
1278 * and all the fields in the object
1280 * @param string $daoName name of the dao
1281 * @param array $criteria array of all the fields & values
1282 * on which basis to copy
1283 * @param array $newData array of all the fields & values
1284 * to be copied besides the other fields
1285 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1286 * @param string $blockCopyOfDependencies fields that you want to block from
1290 * @return (reference ) the newly created copy of the object
1293 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1294 $object = new $daoName( );
1296 $object->id
= $criteria['id'];
1299 foreach ($criteria as $key => $value) {
1300 $object->$key = $value;
1305 while ($object->fetch()) {
1307 // all the objects except with $blockCopyOfDependencies set
1308 // be copied - addresses #CRM-1962
1310 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1314 $newObject = new $daoName( );
1316 $fields = &$object->fields();
1317 if (!is_array($fieldsFix)) {
1318 $fieldsToPrefix = array();
1319 $fieldsToSuffix = array();
1320 $fieldsToReplace = array();
1322 if (!empty($fieldsFix['prefix'])) {
1323 $fieldsToPrefix = $fieldsFix['prefix'];
1325 if (!empty($fieldsFix['suffix'])) {
1326 $fieldsToSuffix = $fieldsFix['suffix'];
1328 if (!empty($fieldsFix['replace'])) {
1329 $fieldsToReplace = $fieldsFix['replace'];
1332 foreach ($fields as $name => $value) {
1333 if ($name == 'id' ||
$value['name'] == 'id') {
1334 // copy everything but the id!
1338 $dbName = $value['name'];
1339 $type = CRM_Utils_Type
::typeToString($value['type']);
1340 $newObject->$dbName = $object->$dbName;
1341 if (isset($fieldsToPrefix[$dbName])) {
1342 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1344 if (isset($fieldsToSuffix[$dbName])) {
1345 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1347 if (isset($fieldsToReplace[$dbName])) {
1348 $newObject->$dbName = $fieldsToReplace[$dbName];
1351 if ($type == 'Timestamp' ||
$type == 'Date') {
1352 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1356 foreach ($newData as $k => $v) {
1357 $newObject->$k = $v;
1366 static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1367 $object = new $daoName( );
1368 $object->id
= $fromId;
1370 if ($object->find(TRUE)) {
1371 $newObject = new $daoName( );
1372 $newObject->id
= $toId;
1374 if ($newObject->find(TRUE)) {
1375 $fields = &$object->fields();
1376 foreach ($fields as $name => $value) {
1377 if ($name == 'id' ||
$value['name'] == 'id') {
1378 // copy everything but the id!
1382 $colName = $value['name'];
1383 $newObject->$colName = $object->$colName;
1385 if (substr($name, -5) == '_date' ||
1386 substr($name, -10) == '_date_time'
1388 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1391 foreach ($newData as $k => $v) {
1392 $newObject->$k = $v;
1398 return CRM_Core_DAO
::$_nullObject;
1402 * Given the component id, compute the contact id
1403 * since its used for things like send email
1405 * @param $componentIDs
1410 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1411 $contactIDs = array();
1413 if (empty($componentIDs)) {
1417 $IDs = implode(',', $componentIDs);
1421 WHERE id IN ( $IDs )
1424 $dao = CRM_Core_DAO
::executeQuery($query);
1425 while ($dao->fetch()) {
1426 $contactIDs[] = $dao->contact_id
;
1432 * Takes a bunch of params that are needed to match certain criteria and
1433 * retrieves the relevant objects. Typically the valid params are only
1434 * contact_id. We'll tweak this function to be more full featured over a period
1435 * of time. This is the inverse function of create. It also stores all the retrieved
1436 * values in the default array
1438 * @param string $daoName name of the dao object
1439 * @param string $fieldIdName
1442 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1444 * @internal param array $params (reference ) an assoc array of name/value pairs
1445 * @internal param array $defaults (reference ) an assoc array to hold the flattened values
1446 * @return object an object of type referenced by daoName
1450 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1451 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1452 $object = new $daoName( );
1453 $object->$fieldIdName = $fieldId;
1455 // return only specific fields if returnproperties are sent
1456 if (!empty($returnProperities)) {
1457 $object->selectAdd();
1458 $object->selectAdd('id');
1459 $object->selectAdd(implode(',', $returnProperities));
1463 while ($object->fetch()) {
1464 $defaults = array();
1465 self
::storeValues($object, $defaults);
1466 $details[$object->id
] = $defaults;
1472 static function dropAllTables() {
1474 // first drop all the custom tables we've created
1475 CRM_Core_BAO_CustomGroup
::dropAllTables();
1477 // drop all multilingual views
1478 CRM_Core_I18n_Schema
::dropAllViews();
1480 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1481 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1482 '..' . DIRECTORY_SEPARATOR
.
1483 '..' . DIRECTORY_SEPARATOR
.
1484 'sql' . DIRECTORY_SEPARATOR
.
1485 'civicrm_drop.mysql'
1494 static function escapeString($string) {
1495 static $_dao = NULL;
1498 $_dao = new CRM_Core_DAO();
1501 return $_dao->escape($string);
1505 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1507 * @param $strings array
1508 * @param $default string the value to use if $strings has no elements
1509 * @return string eg "abc","def","ghi"
1511 static function escapeStrings($strings, $default = NULL) {
1512 static $_dao = NULL;
1514 $_dao = new CRM_Core_DAO();
1517 if (empty($strings)) {
1521 $escapes = array_map(array($_dao, 'escape'), $strings);
1522 return '"' . implode('","', $escapes) . '"';
1530 static function escapeWildCardString($string) {
1532 // ensure we escape the single characters % and _ which are mysql wild
1533 // card characters and could come in via sortByCharacter
1534 // note that mysql does not escape these characters
1535 if ($string && in_array($string,
1536 array('%', '_', '%%', '_%')
1538 return '\\' . $string;
1541 return self
::escapeString($string);
1545 * Creates a test object, including any required objects it needs via recursion
1546 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1547 * ONLY USE FOR TESTING
1550 * @param array $params
1551 * @param int $numObjects
1552 * @param bool $createOnly
1556 static function createTestObject(
1562 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1563 // so we re-set here in case
1564 $config = CRM_Core_Config
::singleton();
1565 $config->backtrace
= TRUE;
1567 static $counter = 0;
1568 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1569 'CRM_Core_DAO_Worldregion',
1570 'CRM_Core_DAO_StateProvince',
1571 'CRM_Core_DAO_Country',
1572 'CRM_Core_DAO_Domain',
1573 'CRM_Financial_DAO_FinancialType'//because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1576 for ($i = 0; $i < $numObjects; ++
$i) {
1579 /** @var CRM_Core_DAO $object */
1580 $object = new $daoName();
1582 $fields = & $object->fields();
1583 foreach ($fields as $fieldName => $fieldDef) {
1584 $dbName = $fieldDef['name'];
1585 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1586 $required = CRM_Utils_Array
::value('required', $fieldDef);
1588 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1589 $object->$dbName = $params[$dbName];
1592 elseif ($dbName != 'id') {
1593 if ($FKClassName != NULL) {
1594 $object->assignTestFK($fieldName, $fieldDef, $params);
1597 $object->assignTestValue($fieldName, $fieldDef, $counter);
1605 $objects[$i] = $object;
1615 elseif ($numObjects == 1) {
1624 * deletes the this object plus any dependent objects that are associated with it
1625 * ONLY USE FOR TESTING
1628 * @param array $params
1630 static function deleteTestObjects($daoName, $params = array(
1632 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1633 // so we re-set here in case
1634 $config = CRM_Core_Config
::singleton();
1635 $config->backtrace
= TRUE;
1637 $object = new $daoName();
1638 $object->id
= CRM_Utils_Array
::value('id', $params);
1640 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1641 if ($object->find(TRUE)) {
1643 $fields = &$object->fields();
1644 foreach ($fields as $name => $value) {
1646 $dbName = $value['name'];
1648 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1649 $required = CRM_Utils_Array
::value('required', $value);
1650 if ($FKClassName != NULL
1652 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1653 && ($required ||
$dbName == 'contact_id')
1654 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1655 // to make this test process pass - line below makes pass for now
1656 && $dbName != 'member_of_contact_id') {
1657 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1664 foreach ($deletions as $deletion) {
1665 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1670 * Set defaults when creating new entity
1671 * (don't call this set defaults as already in use with different signature in some places)
1676 static function setCreateDefaults(&$params, $defaults) {
1677 if (isset($params['id'])) {
1680 foreach ($defaults as $key => $value) {
1681 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1682 $params[$key] = $value;
1688 * @param string $prefix
1689 * @param bool $addRandomString
1690 * @param null $string
1694 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1695 $tableName = $prefix . "_temp";
1697 if ($addRandomString) {
1699 $tableName .= "_" . $string;
1702 $tableName .= "_" . md5(uniqid('', TRUE));
1710 * @param bool $trigger
1714 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1715 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1717 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1718 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1719 $dao = new CRM_Core_DAO();
1721 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1722 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1728 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1729 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1731 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1736 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1737 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1739 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1746 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1747 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1756 * @param null $message
1757 * @param bool $printDAO
1759 static function debugPrint($message = NULL, $printDAO = TRUE) {
1760 CRM_Utils_System
::xMemory("{$message}: ");
1763 global $_DB_DATAOBJECT;
1765 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1766 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1768 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1773 * Build a list of triggers via hook and add them to (err, reconcile them
1774 * with) the database.
1776 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1777 * @param bool $force
1781 static function triggerRebuild($tableName = NULL, $force = FALSE) {
1784 $logging = new CRM_Logging_Schema
;
1785 $logging->triggerInfo($info, $tableName, $force);
1787 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1788 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1790 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1792 // drop all existing triggers on all tables
1793 $logging->dropTriggers($tableName);
1795 // now create the set of new triggers
1796 self
::createTriggers($info);
1800 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1801 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1802 * TODO: Alternative solutions might be
1803 * * Stop using functions and find another way to strip numeric characters from phones
1804 * * Give better error messages (currently a missing fn fatals with "unknown error")
1806 static function checkSqlFunctionsExist() {
1807 if (!self
::$_checkedSqlFunctionsExist) {
1808 self
::$_checkedSqlFunctionsExist = TRUE;
1809 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1810 if (!$dao->fetch()) {
1811 self
::triggerRebuild();
1817 * Wrapper function to drop triggers
1819 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1821 static function dropTriggers($tableName = NULL) {
1824 $logging = new CRM_Logging_Schema
;
1825 $logging->triggerInfo($info, $tableName);
1827 // drop all existing triggers on all tables
1828 $logging->dropTriggers($tableName);
1832 * @param $info array per hook_civicrm_triggerInfo
1833 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1835 static function createTriggers(&$info, $onlyTableName = NULL) {
1836 // Validate info array, should probably raise errors?
1837 if (is_array($info) == FALSE) {
1841 $triggers = array();
1843 // now enumerate the tables and the events and collect the same set in a different format
1844 foreach ($info as $value) {
1846 // clean the incoming data, skip malformed entries
1847 // TODO: malformed entries should raise errors or get logged.
1848 if (isset($value['table']) == FALSE ||
1849 isset($value['event']) == FALSE ||
1850 isset($value['when']) == FALSE ||
1851 isset($value['sql']) == FALSE
1856 if (is_string($value['table']) == TRUE) {
1857 $tables = array($value['table']);
1860 $tables = $value['table'];
1863 if (is_string($value['event']) == TRUE) {
1864 $events = array(strtolower($value['event']));
1867 $events = array_map('strtolower', $value['event']);
1870 $whenName = strtolower($value['when']);
1872 foreach ($tables as $tableName) {
1873 if (!isset($triggers[$tableName])) {
1874 $triggers[$tableName] = array();
1877 foreach ($events as $eventName) {
1878 $template_params = array('{tableName}', '{eventName}');
1879 $template_values = array($tableName, $eventName);
1881 $sql = str_replace($template_params,
1885 $variables = str_replace($template_params,
1887 CRM_Utils_Array
::value('variables', $value)
1890 if (!isset($triggers[$tableName][$eventName])) {
1891 $triggers[$tableName][$eventName] = array();
1894 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1895 // We're leaving out cursors, conditions, and handlers for now
1896 // they are kind of dangerous in this context anyway
1897 // better off putting them in stored procedures
1898 $triggers[$tableName][$eventName][$whenName] = array(
1899 'variables' => array(),
1905 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1908 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1913 // now spit out the sql
1914 foreach ($triggers as $tableName => $tables) {
1915 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1918 foreach ($tables as $eventName => $events) {
1919 foreach ($events as $whenName => $parts) {
1920 $varString = implode("\n", $parts['variables']);
1921 $sqlString = implode("\n", $parts['sql']);
1922 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1923 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1924 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1926 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1927 CRM_Core_DAO
::executeQuery(
1941 * Given a list of fields, create a list of references.
1943 * @param string $className BAO/DAO class name
1944 * @return array<CRM_Core_Reference_Interface>
1946 static function createReferenceColumns($className) {
1948 $fields = $className::fields();
1949 foreach ($fields as $field) {
1950 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1951 $result[] = new CRM_Core_Reference_OptionValue(
1952 $className::getTableName(),
1954 'civicrm_option_value',
1955 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
1956 $field['pseudoconstant']['optionGroupName']
1964 * Find all records which refer to this entity.
1966 * @return array of objects referencing this
1968 function findReferences() {
1969 $links = self
::getReferencesToTable(static::getTableName());
1971 $occurrences = array();
1972 foreach ($links as $refSpec) {
1973 /** @var $refSpec CRM_Core_Reference_Interface */
1974 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
1975 $result = $refSpec->findReferences($this);
1977 while ($result->fetch()) {
1978 $obj = new $daoName();
1979 $obj->id
= $result->id
;
1980 $occurrences[] = $obj;
1985 return $occurrences;
1989 * @return array each item has keys:
1993 * - table: string|null SQL table name
1994 * - key: string|null SQL column name
1996 function getReferenceCounts() {
1997 $links = self
::getReferencesToTable(static::getTableName());
2000 foreach ($links as $refSpec) {
2001 /** @var $refSpec CRM_Core_Reference_Interface */
2002 $count = $refSpec->getReferenceCount($this);
2003 if ($count['count'] != 0) {
2008 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2009 /** @var $component CRM_Core_Component_Info */
2010 $counts = array_merge($counts, $component->getReferenceCounts($this));
2012 CRM_Utils_Hook
::referenceCounts($this, $counts);
2018 * List all tables which have hard foreign keys to this table.
2020 * For now, this returns a description of every entity_id/entity_table
2022 * TODO: filter dynamic entity references on the $tableName, based on
2023 * schema metadata in dynamicForeignKey which enumerates a restricted
2024 * set of possible entity_table's.
2026 * @param string $tableName table referred to
2028 * @return array structure of table and column, listing every table with a
2029 * foreign key reference to $tableName, and the column where the key appears.
2031 static function getReferencesToTable($tableName) {
2032 $refsFound = array();
2033 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2034 $links = $daoClassName::getReferenceColumns();
2035 $daoTableName = $daoClassName::getTableName();
2037 foreach ($links as $refSpec) {
2038 /** @var $refSpec CRM_Core_Reference_Interface */
2039 if ($refSpec->matchesTargetTable($tableName)) {
2040 $refsFound[] = $refSpec;
2048 * Lookup the value of a MySQL global configuration variable.
2050 * @param string $name e.g. "thread_stack"
2051 * @param mixed $default
2054 public static function getGlobalSetting($name, $default = NULL) {
2055 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2056 // that has been reported to fail under MySQL 5.0 for OS X
2057 $escapedName = self
::escapeString($name);
2058 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2059 if ($dao->fetch()) {
2068 * Get options for the called BAO object's field.
2069 * This function can be overridden by each BAO to add more logic related to context.
2070 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2072 * @param string $fieldName
2073 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2074 * @param array $props : whatever is known about this bao object
2076 * @return Array|bool
2078 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2079 // If a given bao does not override this function
2080 $baoName = get_called_class();
2081 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2085 * Populate option labels for this object's fields.
2087 * @throws exception if called directly on the base class
2089 public function getOptionLabels() {
2090 $fields = $this->fields();
2091 if ($fields === NULL) {
2092 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2094 foreach ($fields as $field) {
2095 $name = CRM_Utils_Array
::value('name', $field);
2096 if ($name && isset($this->$name)) {
2097 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2098 if ($label !== FALSE) {
2099 // Append 'label' onto the field name
2100 $labelName = $name . '_label';
2101 $this->$labelName = $label;
2108 * Provides documentation and validation for the buildOptions $context param
2110 * @param String $context
2115 public static function buildOptionsContext($context = NULL) {
2117 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2118 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2119 'search' => "Searchable options are returned. Labels are translated.",
2120 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2122 // Validation: enforce uniformity of this param
2123 if ($context !== NULL && !isset($contexts[$context])) {
2124 throw new Exception("'$context' is not a valid context for buildOptions.");
2131 * @return bool|array
2133 function getFieldSpec($fieldName) {
2134 $fields = $this->fields();
2135 $fieldKeys = $this->fieldKeys();
2137 // Support "unique names" as well as sql names
2138 $fieldKey = $fieldName;
2139 if (empty($fields[$fieldKey])) {
2140 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2142 // If neither worked then this field doesn't exist. Return false.
2143 if (empty($fields[$fieldKey])) {
2146 return $fields[$fieldKey];
2150 * SQL version of api function to assign filters to the DAO based on the syntax
2151 * $field => array('IN' => array(4,6,9))
2153 * $field => array('LIKE' => array('%me%))
2157 * @param $filter array filter to be applied indexed by operator
2158 * @param $type String type of field (not actually used - nor in api @todo )
2159 * @param $alias String alternative field name ('as') @todo- not actually used
2160 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
2161 * this is primarily so we can add filters @ the api level to the Query object based fields
2164 * @internal param string $fieldname name of fields
2165 * @todo a better solution would be for the query object to apply these filters based on the
2166 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2167 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2168 * required to extend further & it may be the comments per above should be implemented. It may be
2169 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2170 * in one place has some advantages as we try to extend this format
2172 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2173 * depending on whether it is supported as yet
2175 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2176 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2177 // support for other syntaxes is discussed in ticket but being put off for now
2178 foreach ($filter as $operator => $criteria) {
2179 if (in_array($operator, self
::acceptedSQLOperators())) {
2180 switch ($operator) {
2184 if(!$returnSanitisedArray) {
2185 return (sprintf('%s %s', $fieldName, $operator));
2188 return (sprintf('%s %s ', $fieldName, $operator));
2192 // ternary operators
2195 if (empty($criteria[0]) ||
empty($criteria[1])) {
2196 throw new Exception("invalid criteria for $operator");
2198 if(!$returnSanitisedArray) {
2199 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2202 return NULL; // not yet implemented (tests required to implement)
2209 if (empty($criteria)) {
2210 throw new Exception("invalid criteria for $operator");
2212 $escapedCriteria = array_map(array(
2216 if(!$returnSanitisedArray) {
2217 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2219 return $escapedCriteria;
2225 if(!$returnSanitisedArray) {
2226 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2229 return NULL; // not yet implemented (tests required to implement)
2237 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2238 * support for other syntaxes is discussed in ticket but being put off for now
2241 public static function acceptedSQLOperators() {
2242 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
2246 * SQL has a limit of 64 characters on various names:
2247 * table name, trigger name, column name ...
2249 * For custom groups and fields we generated names from user entered input
2250 * which can be longer than this length, this function helps with creating
2251 * strings that meet various criteria.
2253 * @param string $string - the string to be shortened
2254 * @param int $length - the max length of the string
2256 * @param bool $makeRandom
2260 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2261 // early return for strings that meet the requirements
2262 if (strlen($string) <= $length) {
2266 // easy return for calls that dont need a randomized uniq string
2267 if (! $makeRandom) {
2268 return substr($string, 0, $length);
2271 // the string is longer than the length and we need a uniq string
2272 // for the same tablename we need the same uniq string everytime
2273 // hence we use md5 on the string, which is not random
2274 // we'll append 8 characters to the end of the tableName
2275 $md5string = substr(md5($string), 0, 8);
2276 return substr($string, 0, $length - 8) . "_{$md5string}";
2282 function setApiFilter(&$params) {}