3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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 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.
106 public 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
);
115 * @param string $fieldName
117 * @param array $params
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 = str_replace('_BAO_', '_DAO_', 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
167 * The globally-unique ID of the test object.
169 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
170 $dbName = $fieldDef['name'];
171 $daoName = get_class($this);
174 if (!$handled && $dbName == 'contact_sub_type') {
175 //coming up with a rule to set this is too complex let's not set it
179 // Pick an option value if needed
180 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
181 $options = $daoName::buildOptions($dbName, 'create');
183 $this->$dbName = key($options);
189 switch ($fieldDef['type']) {
190 case CRM_Utils_Type
::T_INT
:
191 case CRM_Utils_Type
::T_FLOAT
:
192 case CRM_Utils_Type
::T_MONEY
:
193 if (isset($fieldDef['precision'])) {
194 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
195 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
198 $this->$dbName = $counter;
202 case CRM_Utils_Type
::T_BOOLEAN
:
203 if (isset($fieldDef['default'])) {
204 $this->$dbName = $fieldDef['default'];
206 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
214 case CRM_Utils_Type
::T_DATE
:
215 case CRM_Utils_Type
::T_TIMESTAMP
:
216 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
217 $this->$dbName = '19700101';
218 if ($dbName == 'end_date') {
219 // put this in the future
220 $this->$dbName = '20200101';
224 case CRM_Utils_Type
::T_TIME
:
225 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
226 //$object->$dbName='000000';
228 case CRM_Utils_Type
::T_CCNUM
:
229 $this->$dbName = '4111 1111 1111 1111';
232 case CRM_Utils_Type
::T_URL
:
233 $this->$dbName = 'http://www.civicrm.org';
236 case CRM_Utils_Type
::T_STRING
:
237 case CRM_Utils_Type
::T_BLOB
:
238 case CRM_Utils_Type
::T_MEDIUMBLOB
:
239 case CRM_Utils_Type
::T_TEXT
:
240 case CRM_Utils_Type
::T_LONGTEXT
:
241 case CRM_Utils_Type
::T_EMAIL
:
243 // WAS: if (isset($value['enumValues'])) {
244 // TODO: see if this works with all pseudoconstants
245 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
246 if (isset($fieldDef['default'])) {
247 $this->$dbName = $fieldDef['default'];
250 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
251 if (is_array($options)) {
252 $this->$dbName = $options[0];
255 $defaultValues = explode(',', $options);
256 $this->$dbName = $defaultValues[0];
261 $this->$dbName = $dbName . '_' . $counter;
262 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
263 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
264 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
272 * Reset the DAO object. DAO is kinda crappy in that there is an unwritten
273 * rule of one query per DAO. We attempt to get around this crappy restricrion
274 * by resetting some of DAO's internal fields. Use this with caution
279 public function reset() {
281 foreach (array_keys($this->table()) as $field) {
282 unset($this->$field);
286 * reset the various DB_DAO structures manually
288 $this->_query
= array();
295 * @param string $tableName
299 public 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
314 * The SQL query for execution.
315 * @param bool $i18nRewrite
316 * Whether to rewrite the query.
319 * the current DAO object after the query execution
321 public function query($query, $i18nRewrite = TRUE) {
322 // rewrite queries that should use $dbLocale-based views for multi-language installs
324 if ($i18nRewrite and $dbLocale) {
325 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
328 return parent
::query($query);
332 * Static function to set the factory instance for this class.
334 * @param object $factory
335 * The factory application object.
340 public static function setFactory(&$factory) {
341 self
::$_factory = &$factory;
345 * Factory method to instantiate a new object from a table name.
347 * @param string $table
351 public function factory($table = '') {
352 if (!isset(self
::$_factory)) {
353 return parent
::factory($table);
356 return self
::$_factory->create($table);
360 * Initialization for all DAO objects. Since we access DB_DO programatically
361 * we need to set the links manually.
365 public function initialize() {
367 $this->query("SET NAMES utf8");
371 * Defines the default key as 'id'.
376 public function keys() {
385 * Tells DB_DataObject which keys use autoincrement.
386 * 'id' is autoincrementing by default.
391 public function sequenceKey() {
392 static $sequenceKeys;
393 if (!isset($sequenceKeys)) {
394 $sequenceKeys = array('id', TRUE);
396 return $sequenceKeys;
400 * Returns list of FK relationships
405 * of CRM_Core_Reference_Interface
407 public static function getReferenceColumns() {
412 * Returns all the column names of this table
417 static function &fields() {
423 * Get/set an associative array of table columns
425 * @param array key=>type array
429 public function table() {
430 $fields = &$this->fields();
434 foreach ($fields as $name => $value) {
435 $table[$value['name']] = $value['type'];
436 if (!empty($value['required'])) {
437 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
448 public function save() {
449 if (!empty($this->id
)) {
452 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
453 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
458 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
459 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
463 CRM_Utils_Hook
::postSave($this);
468 public function delete($useWhere = FALSE) {
469 $result = parent
::delete($useWhere);
471 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
472 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
478 * @param bool $created
480 public function log($created = FALSE) {
483 if (!$this->getLog()) {
488 $session = CRM_Core_Session
::singleton();
489 $cid = $session->get('userID');
492 // return is we dont have handle to FK
497 $dao = new CRM_Core_DAO_Log();
498 $dao->entity_table
= $this->getTableName();
499 $dao->entity_id
= $this->id
;
500 $dao->modified_id
= $cid;
501 $dao->modified_date
= date("YmdHis");
506 * Given an associative array of name/value pairs, extract all the values
507 * that belong to this object and initialize the object with said values
509 * @param array $params
510 * (reference ) associative array of name/value pairs.
513 * did we copy all null values into the object
515 public function copyValues(&$params) {
516 $fields = &$this->fields();
518 foreach ($fields as $name => $value) {
519 $dbName = $value['name'];
520 if (array_key_exists($dbName, $params)) {
521 $pValue = $params[$dbName];
524 elseif (array_key_exists($name, $params)) {
525 $pValue = $params[$name];
532 // if there is no value then make the variable NULL
534 if ($pValue === '') {
535 $this->$dbName = 'null';
538 $this->$dbName = $pValue;
547 * Store all the values from this object in an associative array
548 * this is a destructive store, calling function is responsible
549 * for keeping sanity of id's.
551 * @param object $object
552 * The object that we are extracting data from.
553 * @param array $values
554 * (reference ) associative array of name/value pairs.
559 public 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
576 * The field under task.
578 * @return array|null the attributes for the object
581 public 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
627 * @param string $fieldName
628 * Field that i'm interested in or null if.
629 * you want the attributes for all DAO text fields
632 * assoc array of name => attribute pairs
635 public static function getAttribute($class, $fieldName = NULL) {
636 $object = new $class( );
637 $fields = &$object->fields();
638 if ($fieldName != NULL) {
639 $field = CRM_Utils_Array
::value($fieldName, $fields);
640 return self
::makeAttribute($field);
643 $attributes = array();
644 foreach ($fields as $name => $field) {
645 $attribute = self
::makeAttribute($field);
647 $attributes[$name] = $attribute;
651 if (!empty($attributes)) {
663 public static function transaction($type) {
664 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
668 * Check if there is a record with the same name in the db
670 * @param string $value
671 * The value of the field we are checking.
672 * @param string $daoName
673 * The dao object name.
674 * @param string $daoID
675 * The id of the object being updated. u can change your name.
676 * as long as there is no conflict
677 * @param string $fieldName
678 * The name of the field in the DAO.
681 * true if object exists
684 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
685 $object = new $daoName( );
686 $object->$fieldName = $value;
688 $config = CRM_Core_Config
::singleton();
690 if ($object->find(TRUE)) {
691 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
699 * Check if there is a given column in a specific table
701 * @param string $tableName
702 * @param string $columnName
703 * @param bool $i18nRewrite
704 * Whether to rewrite the query on multilingual setups.
707 * true if exists, else false
710 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
716 $params = array(1 => array($columnName, 'String'));
717 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
718 $result = $dao->fetch() ?
TRUE : FALSE;
724 * Returns the storage engine used by given table-name(optional).
725 * Otherwise scans all the tables and return an array of all the
726 * distinct storage engines being used.
728 * @param string $tableName
730 * @param int $maxTablesToCheck
731 * @param string $fieldName
736 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
738 $query = "SHOW TABLE STATUS LIKE %1";
742 if (isset($tableName)) {
743 $params = array(1 => array($tableName, 'String'));
746 $params = array(1 => array('civicrm_%', 'String'));
749 $dao = CRM_Core_DAO
::executeQuery($query, $params);
752 while ($dao->fetch()) {
753 if (isset($values[$dao->$fieldName]) ||
754 // ignore import and other temp tables
755 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
756 strpos($dao->Name
, '_temp') !== FALSE
760 $values[$dao->$fieldName] = 1;
762 if ($maxTablesToCheck &&
763 $count >= $maxTablesToCheck
773 * @param int $maxTablesToCheck
777 public static function isDBMyISAM($maxTablesToCheck = 10) {
778 // show error if any of the tables, use 'MyISAM' storage engine.
779 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
780 if (array_key_exists('MyISAM', $engines)) {
787 * Checks if a constraint exists for a specified table.
789 * @param string $tableName
790 * @param string $constraint
793 * true if constraint exists, false otherwise
796 public static function checkConstraintExists($tableName, $constraint) {
797 static $show = array();
799 if (!array_key_exists($tableName, $show)) {
800 $query = "SHOW CREATE TABLE $tableName";
801 $dao = CRM_Core_DAO
::executeQuery($query);
803 if (!$dao->fetch()) {
804 CRM_Core_Error
::fatal();
808 $show[$tableName] = $dao->Create_Table
;
811 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
815 * Checks if CONSTRAINT keyword exists for a specified table.
817 * @param array $tables
822 * true if CONSTRAINT keyword exists, false otherwise
824 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
826 foreach ($tables as $tableName) {
827 if (!array_key_exists($tableName, $show)) {
828 $query = "SHOW CREATE TABLE $tableName";
829 $dao = CRM_Core_DAO
::executeQuery($query);
831 if (!$dao->fetch()) {
832 CRM_Core_Error
::fatal();
836 $show[$tableName] = $dao->Create_Table
;
839 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
840 if ($result == TRUE) {
851 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
852 * for a specified column of a table.
854 * @param string $tableName
855 * @param string $columnName
858 * true if in format, false otherwise
861 public static function checkFKConstraintInFormat($tableName, $columnName) {
862 static $show = array();
864 if (!array_key_exists($tableName, $show)) {
865 $query = "SHOW CREATE TABLE $tableName";
866 $dao = CRM_Core_DAO
::executeQuery($query);
868 if (!$dao->fetch()) {
869 CRM_Core_Error
::fatal();
873 $show[$tableName] = $dao->Create_Table
;
875 $constraint = "`FK_{$tableName}_{$columnName}`";
876 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
877 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
881 * Check whether a specific column in a specific table has always the same value
883 * @param string $tableName
884 * @param string $columnName
885 * @param string $columnValue
888 * true if the value is always $columnValue, false otherwise
891 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
892 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
893 $dao = CRM_Core_DAO
::executeQuery($query);
894 $result = $dao->fetch() ?
FALSE : TRUE;
900 * Check whether a specific column in a specific table is always NULL
902 * @param string $tableName
903 * @param string $columnName
906 * true if if the value is always NULL, false otherwise
909 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
910 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
911 $dao = CRM_Core_DAO
::executeQuery($query);
912 $result = $dao->fetch() ?
FALSE : TRUE;
918 * Check if there is a given table in the database
920 * @param string $tableName
923 * true if exists, else false
926 public static function checkTableExists($tableName) {
931 $params = array(1 => array($tableName, 'String'));
933 $dao = CRM_Core_DAO
::executeQuery($query, $params);
934 $result = $dao->fetch() ?
TRUE : FALSE;
944 public function checkVersion($version) {
949 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
950 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
954 * Find a DAO object for the given ID and return it.
957 * Id of the DAO object being searched for.
960 * Object of the type of the class that called this function.
962 public static function findById($id) {
963 $object = new static();
965 if (!$object->find(TRUE)) {
966 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
972 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
974 * @param string $daoName
975 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
976 * @param int $searchValue
977 * Value of the column you want to search by.
978 * @param string $returnColumn
979 * Name of the column you want to GET the value of.
980 * @param string $searchColumn
981 * Name of the column you want to search by.
983 * Skip use of the cache.
985 * @return string|null Value of $returnColumn in the retrieved record
988 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
990 empty($searchValue) ||
991 trim(strtolower($searchValue)) == 'null'
993 // adding this year since developers forget to check for an id
994 // or for the 'null' (which is a bad DAO kludge)
995 // and hence we get the first value in the db
996 CRM_Core_Error
::fatal();
999 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1000 if (self
::$_dbColumnValueCache === NULL) {
1001 self
::$_dbColumnValueCache = array();
1004 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
1005 $object = new $daoName( );
1006 $object->$searchColumn = $searchValue;
1007 $object->selectAdd();
1008 $object->selectAdd($returnColumn);
1011 if ($object->find(TRUE)) {
1012 $result = $object->$returnColumn;
1016 self
::$_dbColumnValueCache[$cacheKey] = $result;
1018 return self
::$_dbColumnValueCache[$cacheKey];
1022 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1024 * @param string $daoName
1025 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1026 * @param int $searchValue
1027 * Value of the column you want to search by.
1028 * @param string $setColumn
1029 * Name of the column you want to SET the value of.
1030 * @param string $setValue
1031 * SET the setColumn to this value.
1032 * @param string $searchColumn
1033 * Name of the column you want to search by.
1036 * true if we found and updated the object, else false
1039 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1040 $object = new $daoName( );
1041 $object->selectAdd();
1042 $object->selectAdd("$searchColumn, $setColumn");
1043 $object->$searchColumn = $searchValue;
1045 if ($object->find(TRUE)) {
1046 $object->$setColumn = $setValue;
1047 if ($object->save()) {
1058 * @param array|object $sort either array or CRM_Utils_Sort
1059 * @param string $default
1060 * Default sort value.
1066 public static function getSortString($sort, $default = NULL) {
1067 // check if sort is of type CRM_Utils_Sort
1068 if (is_a($sort, 'CRM_Utils_Sort')) {
1069 return $sort->orderBy();
1072 // is it an array specified as $field => $sortDirection ?
1074 foreach ($sort as $k => $v) {
1075 $sortString .= "$k $v,";
1077 return rtrim($sortString, ',');
1083 * Fetch object based on array of properties
1085 * @param string $daoName
1086 * Name of the dao object.
1087 * @param array $params
1088 * (reference ) an assoc array of name/value pairs.
1089 * @param array $defaults
1090 * (reference ) an assoc array to hold the flattened values.
1091 * @param array $returnProperities
1092 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1095 * an object of type referenced by daoName
1098 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1099 $object = new $daoName( );
1100 $object->copyValues($params);
1102 // return only specific fields if returnproperties are sent
1103 if (!empty($returnProperities)) {
1104 $object->selectAdd();
1105 $object->selectAdd(implode(',', $returnProperities));
1108 if ($object->find(TRUE)) {
1109 self
::storeValues($object, $defaults);
1116 * Delete the object records that are associated with this contact
1118 * @param string $daoName
1119 * Name of the dao object.
1120 * @param int $contactId
1121 * Id of the contact to delete.
1126 public static function deleteEntityContact($daoName, $contactId) {
1127 $object = new $daoName( );
1129 $object->entity_table
= 'civicrm_contact';
1130 $object->entity_id
= $contactId;
1137 * @param string $query
1138 * Query to be executed.
1140 * @param array $params
1141 * @param bool $abort
1142 * @param null $daoName
1143 * @param bool $freeDAO
1144 * @param bool $i18nRewrite
1145 * @param bool $trapException
1147 * @return CRM_Core_DAO object that holds the results of the query
1150 static function &executeQuery(
1156 $i18nRewrite = TRUE,
1157 $trapException = FALSE
1159 $queryStr = self
::composeQuery($query, $params, $abort);
1162 $dao = new CRM_Core_DAO();
1165 $dao = new $daoName( );
1168 if ($trapException) {
1169 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1172 $result = $dao->query($queryStr, $i18nRewrite);
1174 if (is_a($result, 'DB_Error')) {
1179 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1181 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1189 * Execute a query and get the single result
1191 * @param string $query
1192 * Query to be executed.
1193 * @param array $params
1194 * @param bool $abort
1195 * @param bool $i18nRewrite
1196 * @return string|null the result of the query if any
1200 static function &singleValueQuery(
1206 $queryStr = self
::composeQuery($query, $params, $abort);
1208 static $_dao = NULL;
1211 $_dao = new CRM_Core_DAO();
1214 $_dao->query($queryStr, $i18nRewrite);
1216 $result = $_dao->getDatabaseResult();
1219 $row = $result->fetchRow();
1230 * @param array $params
1231 * @param bool $abort
1236 public static function composeQuery($query, &$params, $abort = TRUE) {
1238 foreach ($params as $key => $item) {
1239 if (is_numeric($key)) {
1240 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1241 $item[0] = self
::escapeString($item[0]);
1242 if ($item[1] == 'String' ||
1243 $item[1] == 'Memo' ||
1246 // Support class constants stipulating wildcard characters and/or
1247 // non-quoting of strings. Also support legacy code which may be
1248 // passing in TRUE or 1 for $item[2], which used to indicate the
1249 // use of wildcard characters.
1250 if (!empty($item[2])) {
1251 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1252 $item[0] = "'%{$item[0]}%'";
1254 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1255 $item[0] = "'{$item[0]}'";
1259 $item[0] = "'{$item[0]}'";
1263 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1264 strlen($item[0]) == 0
1269 $tr['%' . $key] = $item[0];
1272 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1277 return strtr($query, $tr);
1283 public static function freeResult($ids = NULL) {
1284 global $_DB_DATAOBJECT;
1287 if (!$_DB_DATAOBJECT ||
1288 !isset($_DB_DATAOBJECT['RESULTS'])
1292 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1295 foreach ($ids as $id) {
1296 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1297 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1298 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1300 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1303 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1304 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1310 * make a shallow copy of an object
1311 * and all the fields in the object
1313 * @param string $daoName
1315 * @param array $criteria
1316 * Array of all the fields & values.
1317 * on which basis to copy
1318 * @param array $newData
1319 * Array of all the fields & values.
1320 * to be copied besides the other fields
1321 * @param string $fieldsFix
1322 * Array of fields that you want to prefix/suffix/replace.
1323 * @param string $blockCopyOfDependencies
1324 * Fields that you want to block from.
1328 * @return (reference ) the newly created copy of the object
1330 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1331 $object = new $daoName( );
1333 $object->id
= $criteria['id'];
1336 foreach ($criteria as $key => $value) {
1337 $object->$key = $value;
1342 while ($object->fetch()) {
1344 // all the objects except with $blockCopyOfDependencies set
1345 // be copied - addresses #CRM-1962
1347 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1351 $newObject = new $daoName( );
1353 $fields = &$object->fields();
1354 if (!is_array($fieldsFix)) {
1355 $fieldsToPrefix = array();
1356 $fieldsToSuffix = array();
1357 $fieldsToReplace = array();
1359 if (!empty($fieldsFix['prefix'])) {
1360 $fieldsToPrefix = $fieldsFix['prefix'];
1362 if (!empty($fieldsFix['suffix'])) {
1363 $fieldsToSuffix = $fieldsFix['suffix'];
1365 if (!empty($fieldsFix['replace'])) {
1366 $fieldsToReplace = $fieldsFix['replace'];
1369 foreach ($fields as $name => $value) {
1370 if ($name == 'id' ||
$value['name'] == 'id') {
1371 // copy everything but the id!
1375 $dbName = $value['name'];
1376 $type = CRM_Utils_Type
::typeToString($value['type']);
1377 $newObject->$dbName = $object->$dbName;
1378 if (isset($fieldsToPrefix[$dbName])) {
1379 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1381 if (isset($fieldsToSuffix[$dbName])) {
1382 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1384 if (isset($fieldsToReplace[$dbName])) {
1385 $newObject->$dbName = $fieldsToReplace[$dbName];
1388 if ($type == 'Timestamp' ||
$type == 'Date') {
1389 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1393 foreach ($newData as $k => $v) {
1394 $newObject->$k = $v;
1403 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1404 $object = new $daoName( );
1405 $object->id
= $fromId;
1407 if ($object->find(TRUE)) {
1408 $newObject = new $daoName( );
1409 $newObject->id
= $toId;
1411 if ($newObject->find(TRUE)) {
1412 $fields = &$object->fields();
1413 foreach ($fields as $name => $value) {
1414 if ($name == 'id' ||
$value['name'] == 'id') {
1415 // copy everything but the id!
1419 $colName = $value['name'];
1420 $newObject->$colName = $object->$colName;
1422 if (substr($name, -5) == '_date' ||
1423 substr($name, -10) == '_date_time'
1425 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1428 foreach ($newData as $k => $v) {
1429 $newObject->$k = $v;
1435 return CRM_Core_DAO
::$_nullObject;
1439 * Given the component id, compute the contact id
1440 * since its used for things like send email
1442 * @param $componentIDs
1443 * @param string $tableName
1447 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1448 $contactIDs = array();
1450 if (empty($componentIDs)) {
1454 $IDs = implode(',', $componentIDs);
1458 WHERE id IN ( $IDs )
1461 $dao = CRM_Core_DAO
::executeQuery($query);
1462 while ($dao->fetch()) {
1463 $contactIDs[] = $dao->contact_id
;
1469 * Fetch object based on array of properties
1471 * @param string $daoName
1472 * Name of the dao object.
1473 * @param string $fieldIdName
1474 * @param int $fieldId
1476 * @param array $returnProperities
1477 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1480 * an object of type referenced by daoName
1483 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1484 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1485 $object = new $daoName( );
1486 $object->$fieldIdName = $fieldId;
1488 // return only specific fields if returnproperties are sent
1489 if (!empty($returnProperities)) {
1490 $object->selectAdd();
1491 $object->selectAdd('id');
1492 $object->selectAdd(implode(',', $returnProperities));
1496 while ($object->fetch()) {
1497 $defaults = array();
1498 self
::storeValues($object, $defaults);
1499 $details[$object->id
] = $defaults;
1505 public static function dropAllTables() {
1507 // first drop all the custom tables we've created
1508 CRM_Core_BAO_CustomGroup
::dropAllTables();
1510 // drop all multilingual views
1511 CRM_Core_I18n_Schema
::dropAllViews();
1513 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1514 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1515 '..' . DIRECTORY_SEPARATOR
.
1516 '..' . DIRECTORY_SEPARATOR
.
1517 'sql' . DIRECTORY_SEPARATOR
.
1518 'civicrm_drop.mysql'
1527 public static function escapeString($string) {
1528 static $_dao = NULL;
1531 // If this is an atypical case (e.g. preparing .sql files
1532 // before Civi has been installed), then we fallback to
1533 // DB-less escaping helper (mysql_real_escape_string).
1534 // Note: In typical usage, escapeString() will only
1535 // check one conditional ("if !$_dao") rather than
1536 // two conditionals ("if !defined(DSN)")
1537 if (!defined('CIVICRM_DSN')) {
1538 if (function_exists('mysql_real_escape_string')) {
1539 return mysql_real_escape_string($string);
1542 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1546 $_dao = new CRM_Core_DAO();
1549 return $_dao->escape($string);
1553 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1555 * @param array $strings
1556 * @param string $default
1557 * the value to use if $strings has no elements.
1559 * eg "abc","def","ghi"
1561 public static function escapeStrings($strings, $default = NULL) {
1562 static $_dao = NULL;
1564 $_dao = new CRM_Core_DAO();
1567 if (empty($strings)) {
1571 $escapes = array_map(array($_dao, 'escape'), $strings);
1572 return '"' . implode('","', $escapes) . '"';
1580 public static function escapeWildCardString($string) {
1582 // ensure we escape the single characters % and _ which are mysql wild
1583 // card characters and could come in via sortByCharacter
1584 // note that mysql does not escape these characters
1585 if ($string && in_array($string,
1586 array('%', '_', '%%', '_%')
1588 return '\\' . $string;
1591 return self
::escapeString($string);
1595 * Creates a test object, including any required objects it needs via recursion
1596 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1597 * ONLY USE FOR TESTING
1599 * @param string $daoName
1600 * @param array $params
1601 * @param int $numObjects
1602 * @param bool $createOnly
1606 static function createTestObject(
1612 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1613 // so we re-set here in case
1614 $config = CRM_Core_Config
::singleton();
1615 $config->backtrace
= TRUE;
1617 static $counter = 0;
1618 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1619 'CRM_Core_DAO_Worldregion',
1620 'CRM_Core_DAO_StateProvince',
1621 'CRM_Core_DAO_Country',
1622 'CRM_Core_DAO_Domain',
1623 'CRM_Financial_DAO_FinancialType'//because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1626 // Prefer to instantiate BAO's instead of DAO's (when possible)
1627 // so that assignTestValue()/assignTestFK() can be overloaded.
1628 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1629 if (class_exists($baoName)) {
1630 $daoName = $baoName;
1633 for ($i = 0; $i < $numObjects; ++
$i) {
1636 /** @var CRM_Core_DAO $object */
1637 $object = new $daoName();
1639 $fields = & $object->fields();
1640 foreach ($fields as $fieldName => $fieldDef) {
1641 $dbName = $fieldDef['name'];
1642 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1643 $required = CRM_Utils_Array
::value('required', $fieldDef);
1645 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1646 $object->$dbName = $params[$dbName];
1649 elseif ($dbName != 'id') {
1650 if ($FKClassName != NULL) {
1651 $object->assignTestFK($fieldName, $fieldDef, $params);
1655 $object->assignTestValue($fieldName, $fieldDef, $counter);
1663 $objects[$i] = $object;
1673 elseif ($numObjects == 1) {
1682 * Deletes the this object plus any dependent objects that are associated with it
1683 * ONLY USE FOR TESTING
1685 * @param string $daoName
1686 * @param array $params
1688 public static function deleteTestObjects($daoName, $params = array()) {
1689 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1690 // so we re-set here in case
1691 $config = CRM_Core_Config
::singleton();
1692 $config->backtrace
= TRUE;
1694 $object = new $daoName();
1695 $object->id
= CRM_Utils_Array
::value('id', $params);
1697 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1698 if ($object->find(TRUE)) {
1700 $fields = &$object->fields();
1701 foreach ($fields as $name => $value) {
1703 $dbName = $value['name'];
1705 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1706 $required = CRM_Utils_Array
::value('required', $value);
1707 if ($FKClassName != NULL
1709 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1710 && ($required ||
$dbName == 'contact_id')
1711 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1712 // to make this test process pass - line below makes pass for now
1713 && $dbName != 'member_of_contact_id') {
1714 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1721 foreach ($deletions as $deletion) {
1722 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1727 * Set defaults when creating new entity
1728 * (don't call this set defaults as already in use with different signature in some places)
1730 * @param array $params
1733 public static function setCreateDefaults(&$params, $defaults) {
1734 if (isset($params['id'])) {
1737 foreach ($defaults as $key => $value) {
1738 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1739 $params[$key] = $value;
1745 * @param string $prefix
1746 * @param bool $addRandomString
1747 * @param null $string
1751 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1752 $tableName = $prefix . "_temp";
1754 if ($addRandomString) {
1756 $tableName .= "_" . $string;
1759 $tableName .= "_" . md5(uniqid('', TRUE));
1767 * @param bool $trigger
1771 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1772 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1774 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1775 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1776 $dao = new CRM_Core_DAO();
1778 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1779 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1785 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1786 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1788 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1793 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1794 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1796 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1803 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1804 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1813 * @param null $message
1814 * @param bool $printDAO
1816 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1817 CRM_Utils_System
::xMemory("{$message}: ");
1820 global $_DB_DATAOBJECT;
1822 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1823 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1825 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1830 * Build a list of triggers via hook and add them to (err, reconcile them
1831 * with) the database.
1833 * @param string $tableName
1834 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1835 * @param bool $force
1839 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1842 $logging = new CRM_Logging_Schema
;
1843 $logging->triggerInfo($info, $tableName, $force);
1845 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1846 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1848 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1850 // drop all existing triggers on all tables
1851 $logging->dropTriggers($tableName);
1853 // now create the set of new triggers
1854 self
::createTriggers($info, $tableName);
1858 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1859 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1860 * TODO: Alternative solutions might be
1861 * * Stop using functions and find another way to strip numeric characters from phones
1862 * * Give better error messages (currently a missing fn fatals with "unknown error")
1864 public static function checkSqlFunctionsExist() {
1865 if (!self
::$_checkedSqlFunctionsExist) {
1866 self
::$_checkedSqlFunctionsExist = TRUE;
1867 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1868 if (!$dao->fetch()) {
1869 self
::triggerRebuild();
1875 * Wrapper function to drop triggers
1877 * @param string $tableName
1878 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1880 public static function dropTriggers($tableName = NULL) {
1883 $logging = new CRM_Logging_Schema
;
1884 $logging->triggerInfo($info, $tableName);
1886 // drop all existing triggers on all tables
1887 $logging->dropTriggers($tableName);
1891 * @param array $info
1892 * per hook_civicrm_triggerInfo.
1893 * @param string $onlyTableName
1894 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1896 public static function createTriggers(&$info, $onlyTableName = NULL) {
1897 // Validate info array, should probably raise errors?
1898 if (is_array($info) == FALSE) {
1902 $triggers = array();
1904 // now enumerate the tables and the events and collect the same set in a different format
1905 foreach ($info as $value) {
1907 // clean the incoming data, skip malformed entries
1908 // TODO: malformed entries should raise errors or get logged.
1909 if (isset($value['table']) == FALSE ||
1910 isset($value['event']) == FALSE ||
1911 isset($value['when']) == FALSE ||
1912 isset($value['sql']) == FALSE
1917 if (is_string($value['table']) == TRUE) {
1918 $tables = array($value['table']);
1921 $tables = $value['table'];
1924 if (is_string($value['event']) == TRUE) {
1925 $events = array(strtolower($value['event']));
1928 $events = array_map('strtolower', $value['event']);
1931 $whenName = strtolower($value['when']);
1933 foreach ($tables as $tableName) {
1934 if (!isset($triggers[$tableName])) {
1935 $triggers[$tableName] = array();
1938 foreach ($events as $eventName) {
1939 $template_params = array('{tableName}', '{eventName}');
1940 $template_values = array($tableName, $eventName);
1942 $sql = str_replace($template_params,
1946 $variables = str_replace($template_params,
1948 CRM_Utils_Array
::value('variables', $value)
1951 if (!isset($triggers[$tableName][$eventName])) {
1952 $triggers[$tableName][$eventName] = array();
1955 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1956 // We're leaving out cursors, conditions, and handlers for now
1957 // they are kind of dangerous in this context anyway
1958 // better off putting them in stored procedures
1959 $triggers[$tableName][$eventName][$whenName] = array(
1960 'variables' => array(),
1966 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1969 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1974 // now spit out the sql
1975 foreach ($triggers as $tableName => $tables) {
1976 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1979 foreach ($tables as $eventName => $events) {
1980 foreach ($events as $whenName => $parts) {
1981 $varString = implode("\n", $parts['variables']);
1982 $sqlString = implode("\n", $parts['sql']);
1983 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1984 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1985 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1987 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1988 CRM_Core_DAO
::executeQuery(
2002 * Given a list of fields, create a list of references.
2004 * @param string $className
2005 * BAO/DAO class name.
2006 * @return array<CRM_Core_Reference_Interface>
2008 public static function createReferenceColumns($className) {
2010 $fields = $className::fields();
2011 foreach ($fields as $field) {
2012 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
2013 $result[] = new CRM_Core_Reference_OptionValue(
2014 $className::getTableName(),
2016 'civicrm_option_value',
2017 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
2018 $field['pseudoconstant']['optionGroupName']
2026 * Find all records which refer to this entity.
2029 * of objects referencing this
2031 public function findReferences() {
2032 $links = self
::getReferencesToTable(static::getTableName());
2034 $occurrences = array();
2035 foreach ($links as $refSpec) {
2036 /** @var $refSpec CRM_Core_Reference_Interface */
2037 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2038 $result = $refSpec->findReferences($this);
2040 while ($result->fetch()) {
2041 $obj = new $daoName();
2042 $obj->id
= $result->id
;
2043 $occurrences[] = $obj;
2048 return $occurrences;
2053 * each item has keys:
2057 * - table: string|null SQL table name
2058 * - key: string|null SQL column name
2060 public function getReferenceCounts() {
2061 $links = self
::getReferencesToTable(static::getTableName());
2064 foreach ($links as $refSpec) {
2065 /** @var $refSpec CRM_Core_Reference_Interface */
2066 $count = $refSpec->getReferenceCount($this);
2067 if ($count['count'] != 0) {
2072 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2073 /** @var $component CRM_Core_Component_Info */
2074 $counts = array_merge($counts, $component->getReferenceCounts($this));
2076 CRM_Utils_Hook
::referenceCounts($this, $counts);
2082 * List all tables which have hard foreign keys to this table.
2084 * For now, this returns a description of every entity_id/entity_table
2086 * TODO: filter dynamic entity references on the $tableName, based on
2087 * schema metadata in dynamicForeignKey which enumerates a restricted
2088 * set of possible entity_table's.
2090 * @param string $tableName
2091 * Table referred to.
2094 * structure of table and column, listing every table with a
2095 * foreign key reference to $tableName, and the column where the key appears.
2097 public static function getReferencesToTable($tableName) {
2098 $refsFound = array();
2099 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2100 $links = $daoClassName::getReferenceColumns();
2101 $daoTableName = $daoClassName::getTableName();
2103 foreach ($links as $refSpec) {
2104 /** @var $refSpec CRM_Core_Reference_Interface */
2105 if ($refSpec->matchesTargetTable($tableName)) {
2106 $refsFound[] = $refSpec;
2114 * Lookup the value of a MySQL global configuration variable.
2116 * @param string $name
2117 * E.g. "thread_stack".
2118 * @param mixed $default
2121 public static function getGlobalSetting($name, $default = NULL) {
2122 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2123 // that has been reported to fail under MySQL 5.0 for OS X
2124 $escapedName = self
::escapeString($name);
2125 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2126 if ($dao->fetch()) {
2135 * Get options for the called BAO object's field.
2136 * This function can be overridden by each BAO to add more logic related to context.
2137 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2139 * @param string $fieldName
2140 * @param string $context
2141 * : @see CRM_Core_DAO::buildOptionsContext.
2142 * @param array $props
2143 * : whatever is known about this bao object.
2145 * @return Array|bool
2147 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2148 // If a given bao does not override this function
2149 $baoName = get_called_class();
2150 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2154 * Populate option labels for this object's fields.
2156 * @throws exception if called directly on the base class
2158 public function getOptionLabels() {
2159 $fields = $this->fields();
2160 if ($fields === NULL) {
2161 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2163 foreach ($fields as $field) {
2164 $name = CRM_Utils_Array
::value('name', $field);
2165 if ($name && isset($this->$name)) {
2166 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2167 if ($label !== FALSE) {
2168 // Append 'label' onto the field name
2169 $labelName = $name . '_label';
2170 $this->$labelName = $label;
2177 * Provides documentation and validation for the buildOptions $context param
2179 * @param string $context
2184 public static function buildOptionsContext($context = NULL) {
2186 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2187 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2188 'search' => "Searchable options are returned. Labels are translated.",
2189 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2191 // Validation: enforce uniformity of this param
2192 if ($context !== NULL && !isset($contexts[$context])) {
2193 throw new Exception("'$context' is not a valid context for buildOptions.");
2199 * @param string $fieldName
2200 * @return bool|array
2202 public function getFieldSpec($fieldName) {
2203 $fields = $this->fields();
2204 $fieldKeys = $this->fieldKeys();
2206 // Support "unique names" as well as sql names
2207 $fieldKey = $fieldName;
2208 if (empty($fields[$fieldKey])) {
2209 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2211 // If neither worked then this field doesn't exist. Return false.
2212 if (empty($fields[$fieldKey])) {
2215 return $fields[$fieldKey];
2219 * SQL version of api function to assign filters to the DAO based on the syntax
2220 * $field => array('IN' => array(4,6,9))
2222 * $field => array('LIKE' => array('%me%))
2225 * @param string $fieldName
2227 * @param array $filter
2228 * filter to be applied indexed by operator.
2229 * @param string $type
2230 * type of field (not actually used - nor in api @todo ).
2231 * @param string $alias
2232 * alternative field name ('as') @todo- not actually used.
2233 * @param bool $returnSanitisedArray
2234 * Return a sanitised array instead of a clause.
2235 * this is primarily so we can add filters @ the api level to the Query object based fields
2239 * @todo a better solution would be for the query object to apply these filters based on the
2240 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2241 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2242 * required to extend further & it may be the comments per above should be implemented. It may be
2243 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2244 * in one place has some advantages as we try to extend this format
2246 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2247 * depending on whether it is supported as yet
2249 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2250 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2251 // support for other syntaxes is discussed in ticket but being put off for now
2252 foreach ($filter as $operator => $criteria) {
2253 if (in_array($operator, self
::acceptedSQLOperators())) {
2254 switch ($operator) {
2258 if (!$returnSanitisedArray) {
2259 return (sprintf('%s %s', $fieldName, $operator));
2262 return (sprintf('%s %s ', $fieldName, $operator));
2266 // ternary operators
2269 if (empty($criteria[0]) ||
empty($criteria[1])) {
2270 throw new Exception("invalid criteria for $operator");
2272 if (!$returnSanitisedArray) {
2273 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2276 return NULL; // not yet implemented (tests required to implement)
2283 if (empty($criteria)) {
2284 throw new Exception("invalid criteria for $operator");
2286 $escapedCriteria = array_map(array(
2290 if (!$returnSanitisedArray) {
2291 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2293 return $escapedCriteria;
2299 if (!$returnSanitisedArray) {
2300 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2303 return NULL; // not yet implemented (tests required to implement)
2311 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2312 * support for other syntaxes is discussed in ticket but being put off for now
2315 public static function acceptedSQLOperators() {
2316 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
2320 * SQL has a limit of 64 characters on various names:
2321 * table name, trigger name, column name ...
2323 * For custom groups and fields we generated names from user entered input
2324 * which can be longer than this length, this function helps with creating
2325 * strings that meet various criteria.
2327 * @param string $string
2328 * The string to be shortened.
2329 * @param int $length
2330 * The max length of the string.
2332 * @param bool $makeRandom
2336 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2337 // early return for strings that meet the requirements
2338 if (strlen($string) <= $length) {
2342 // easy return for calls that dont need a randomized uniq string
2344 return substr($string, 0, $length);
2347 // the string is longer than the length and we need a uniq string
2348 // for the same tablename we need the same uniq string everytime
2349 // hence we use md5 on the string, which is not random
2350 // we'll append 8 characters to the end of the tableName
2351 $md5string = substr(md5($string), 0, 8);
2352 return substr($string, 0, $length - 8) . "_{$md5string}";
2356 * @param array $params
2358 public function setApiFilter(&$params) {}