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.
318 * @return object the current DAO object after the query execution
320 public function query($query, $i18nRewrite = TRUE) {
321 // rewrite queries that should use $dbLocale-based views for multi-language installs
323 if ($i18nRewrite and $dbLocale) {
324 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
327 return parent
::query($query);
331 * Static function to set the factory instance for this class.
333 * @param object $factory
334 * The factory application object.
339 public static function setFactory(&$factory) {
340 self
::$_factory = &$factory;
344 * Factory method to instantiate a new object from a table name.
346 * @param string $table
350 public function factory($table = '') {
351 if (!isset(self
::$_factory)) {
352 return parent
::factory($table);
355 return self
::$_factory->create($table);
359 * Initialization for all DAO objects. Since we access DB_DO programatically
360 * we need to set the links manually.
364 public function initialize() {
366 $this->query("SET NAMES utf8");
370 * Defines the default key as 'id'.
375 public function keys() {
384 * Tells DB_DataObject which keys use autoincrement.
385 * 'id' is autoincrementing by default.
390 public function sequenceKey() {
391 static $sequenceKeys;
392 if (!isset($sequenceKeys)) {
393 $sequenceKeys = array('id', TRUE);
395 return $sequenceKeys;
399 * Returns list of FK relationships
403 * @return array of CRM_Core_Reference_Interface
405 public static function getReferenceColumns() {
410 * Returns all the column names of this table
415 static function &fields() {
421 * Get/set an associative array of table columns
423 * @param array key=>type array
424 * @return array (associative)
426 public function table() {
427 $fields = &$this->fields();
431 foreach ($fields as $name => $value) {
432 $table[$value['name']] = $value['type'];
433 if (!empty($value['required'])) {
434 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
445 public function save() {
446 if (!empty($this->id
)) {
449 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
450 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
455 $event = new \Civi\Core\DAO\Event\
PostUpdate($this);
456 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
460 CRM_Utils_Hook
::postSave($this);
465 public function delete($useWhere = FALSE) {
466 $result = parent
::delete($useWhere);
468 $event = new \Civi\Core\DAO\Event\
PostDelete($this, $result);
469 \Civi\Core\Container
::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
475 * @param bool $created
477 public function log($created = FALSE) {
480 if (!$this->getLog()) {
485 $session = CRM_Core_Session
::singleton();
486 $cid = $session->get('userID');
489 // return is we dont have handle to FK
494 $dao = new CRM_Core_DAO_Log();
495 $dao->entity_table
= $this->getTableName();
496 $dao->entity_id
= $this->id
;
497 $dao->modified_id
= $cid;
498 $dao->modified_date
= date("YmdHis");
503 * Given an associative array of name/value pairs, extract all the values
504 * that belong to this object and initialize the object with said values
506 * @param array $params
507 * (reference ) associative array of name/value pairs.
509 * @return boolean did we copy all null values into the object
511 public function copyValues(&$params) {
512 $fields = &$this->fields();
514 foreach ($fields as $name => $value) {
515 $dbName = $value['name'];
516 if (array_key_exists($dbName, $params)) {
517 $pValue = $params[$dbName];
520 elseif (array_key_exists($name, $params)) {
521 $pValue = $params[$name];
528 // if there is no value then make the variable NULL
530 if ($pValue === '') {
531 $this->$dbName = 'null';
534 $this->$dbName = $pValue;
543 * Store all the values from this object in an associative array
544 * this is a destructive store, calling function is responsible
545 * for keeping sanity of id's.
547 * @param object $object
548 * The object that we are extracting data from.
549 * @param array $values
550 * (reference ) associative array of name/value pairs.
555 public static function storeValues(&$object, &$values) {
556 $fields = &$object->fields();
557 foreach ($fields as $name => $value) {
558 $dbName = $value['name'];
559 if (isset($object->$dbName) && $object->$dbName !== 'null') {
560 $values[$dbName] = $object->$dbName;
561 if ($name != $dbName) {
562 $values[$name] = $object->$dbName;
569 * Create an attribute for this specific field. We only do this for strings and text
571 * @param array $field
572 * The field under task.
574 * @return array|null the attributes for the object
577 public static function makeAttribute($field) {
579 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
580 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
581 $size = CRM_Utils_Array
::value('size', $field);
582 if ($maxLength ||
$size) {
583 $attributes = array();
585 $attributes['maxlength'] = $maxLength;
588 $attributes['size'] = $size;
593 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
594 $rows = CRM_Utils_Array
::value('rows', $field);
598 $cols = CRM_Utils_Array
::value('cols', $field);
603 $attributes = array();
604 $attributes['rows'] = $rows;
605 $attributes['cols'] = $cols;
608 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
) {
609 $attributes['size'] = 6;
610 $attributes['maxlength'] = 14;
618 * Get the size and maxLength attributes for this text field
619 * (or for all text fields) in the DAO object.
621 * @param string $class
623 * @param string $fieldName
624 * Field that i'm interested in or null if.
625 * you want the attributes for all DAO text fields
627 * @return array assoc array of name => attribute pairs
630 public static function getAttribute($class, $fieldName = NULL) {
631 $object = new $class( );
632 $fields = &$object->fields();
633 if ($fieldName != NULL) {
634 $field = CRM_Utils_Array
::value($fieldName, $fields);
635 return self
::makeAttribute($field);
638 $attributes = array();
639 foreach ($fields as $name => $field) {
640 $attribute = self
::makeAttribute($field);
642 $attributes[$name] = $attribute;
646 if (!empty($attributes)) {
658 public static function transaction($type) {
659 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
663 * Check if there is a record with the same name in the db
665 * @param string $value
666 * The value of the field we are checking.
667 * @param string $daoName
668 * The dao object name.
669 * @param string $daoID
670 * The id of the object being updated. u can change your name.
671 * as long as there is no conflict
672 * @param string $fieldName
673 * The name of the field in the DAO.
675 * @return boolean true if object exists
678 public 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
698 * Whether to rewrite the query on multilingual setups.
700 * @return boolean true if exists, else false
703 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
709 $params = array(1 => array($columnName, 'String'));
710 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
711 $result = $dao->fetch() ?
TRUE : FALSE;
717 * Returns the storage engine used by given table-name(optional).
718 * Otherwise scans all the tables and return an array of all the
719 * distinct storage engines being used.
721 * @param string $tableName
723 * @param int $maxTablesToCheck
724 * @param string $fieldName
729 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
731 $query = "SHOW TABLE STATUS LIKE %1";
735 if (isset($tableName)) {
736 $params = array(1 => array($tableName, 'String'));
739 $params = array(1 => array('civicrm_%', 'String'));
742 $dao = CRM_Core_DAO
::executeQuery($query, $params);
745 while ($dao->fetch()) {
746 if (isset($values[$dao->$fieldName]) ||
747 // ignore import and other temp tables
748 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
749 strpos($dao->Name
, '_temp') !== FALSE
753 $values[$dao->$fieldName] = 1;
755 if ($maxTablesToCheck &&
756 $count >= $maxTablesToCheck
766 * @param int $maxTablesToCheck
770 public static function isDBMyISAM($maxTablesToCheck = 10) {
771 // show error if any of the tables, use 'MyISAM' storage engine.
772 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
773 if (array_key_exists('MyISAM', $engines)) {
780 * Checks if a constraint exists for a specified table.
782 * @param string $tableName
783 * @param string $constraint
785 * @return boolean true if constraint exists, false otherwise
788 public static function checkConstraintExists($tableName, $constraint) {
789 static $show = array();
791 if (!array_key_exists($tableName, $show)) {
792 $query = "SHOW CREATE TABLE $tableName";
793 $dao = CRM_Core_DAO
::executeQuery($query);
795 if (!$dao->fetch()) {
796 CRM_Core_Error
::fatal();
800 $show[$tableName] = $dao->Create_Table
;
803 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
807 * Checks if CONSTRAINT keyword exists for a specified table.
809 * @param array $tables
813 * @return boolean true if CONSTRAINT keyword exists, false otherwise
815 public 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;
831 if ($result == TRUE){
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 public 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 public 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 public 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 public 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 public function checkVersion($version) {
936 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
937 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
941 * Find a DAO object for the given ID and return it.
944 * Id of the DAO object being searched for.
946 * @return object Object of the type of the class that called this function.
948 public static function findById($id) {
949 $object = new static();
951 if (!$object->find(TRUE)) {
952 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
958 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
960 * @param string $daoName
961 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
962 * @param int $searchValue
963 * Value of the column you want to search by.
964 * @param string $returnColumn
965 * Name of the column you want to GET the value of.
966 * @param string $searchColumn
967 * Name of the column you want to search by.
969 * Skip use of the cache.
971 * @return string|null Value of $returnColumn in the retrieved record
974 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
976 empty($searchValue) ||
977 trim(strtolower($searchValue)) == 'null'
979 // adding this year since developers forget to check for an id
980 // or for the 'null' (which is a bad DAO kludge)
981 // and hence we get the first value in the db
982 CRM_Core_Error
::fatal();
985 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
986 if (self
::$_dbColumnValueCache === NULL) {
987 self
::$_dbColumnValueCache = array();
990 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
991 $object = new $daoName( );
992 $object->$searchColumn = $searchValue;
993 $object->selectAdd();
994 $object->selectAdd($returnColumn);
997 if ($object->find(TRUE)) {
998 $result = $object->$returnColumn;
1002 self
::$_dbColumnValueCache[$cacheKey] = $result;
1004 return self
::$_dbColumnValueCache[$cacheKey];
1008 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1010 * @param string $daoName
1011 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1012 * @param int $searchValue
1013 * Value of the column you want to search by.
1014 * @param string $setColumn
1015 * Name of the column you want to SET the value of.
1016 * @param string $setValue
1017 * SET the setColumn to this value.
1018 * @param string $searchColumn
1019 * Name of the column you want to search by.
1021 * @return boolean true if we found and updated the object, else false
1024 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1025 $object = new $daoName( );
1026 $object->selectAdd();
1027 $object->selectAdd("$searchColumn, $setColumn");
1028 $object->$searchColumn = $searchValue;
1030 if ($object->find(TRUE)) {
1031 $object->$setColumn = $setValue;
1032 if ($object->save()) {
1043 * @param array|object $sort either array or CRM_Utils_Sort
1044 * @param string $default
1045 * Default sort value.
1047 * @return string - sortString
1050 public static function getSortString($sort, $default = NULL) {
1051 // check if sort is of type CRM_Utils_Sort
1052 if (is_a($sort, 'CRM_Utils_Sort')) {
1053 return $sort->orderBy();
1056 // is it an array specified as $field => $sortDirection ?
1058 foreach ($sort as $k => $v) {
1059 $sortString .= "$k $v,";
1061 return rtrim($sortString, ',');
1067 * Fetch object based on array of properties
1069 * @param string $daoName
1070 * Name of the dao object.
1071 * @param array $params
1072 * (reference ) an assoc array of name/value pairs.
1073 * @param array $defaults
1074 * (reference ) an assoc array to hold the flattened values.
1075 * @param array $returnProperities
1076 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1078 * @return object an object of type referenced by daoName
1081 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1082 $object = new $daoName( );
1083 $object->copyValues($params);
1085 // return only specific fields if returnproperties are sent
1086 if (!empty($returnProperities)) {
1087 $object->selectAdd();
1088 $object->selectAdd(implode(',', $returnProperities));
1091 if ($object->find(TRUE)) {
1092 self
::storeValues($object, $defaults);
1099 * Delete the object records that are associated with this contact
1101 * @param string $daoName
1102 * Name of the dao object.
1103 * @param int $contactId
1104 * Id of the contact to delete.
1109 public static function deleteEntityContact($daoName, $contactId) {
1110 $object = new $daoName( );
1112 $object->entity_table
= 'civicrm_contact';
1113 $object->entity_id
= $contactId;
1120 * @param string $query
1121 * Query to be executed.
1123 * @param array $params
1124 * @param bool $abort
1125 * @param null $daoName
1126 * @param bool $freeDAO
1127 * @param bool $i18nRewrite
1128 * @param bool $trapException
1130 * @return CRM_Core_DAO object that holds the results of the query
1133 static function &executeQuery(
1139 $i18nRewrite = TRUE,
1140 $trapException = FALSE
1142 $queryStr = self
::composeQuery($query, $params, $abort);
1145 $dao = new CRM_Core_DAO();
1148 $dao = new $daoName( );
1151 if ($trapException) {
1152 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1155 $result = $dao->query($queryStr, $i18nRewrite);
1157 if (is_a($result, 'DB_Error')) {
1162 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1164 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1172 * Execute a query and get the single result
1174 * @param string $query
1175 * Query to be executed.
1176 * @param array $params
1177 * @param bool $abort
1178 * @param bool $i18nRewrite
1179 * @return string|null the result of the query if any
1183 static function &singleValueQuery(
1189 $queryStr = self
::composeQuery($query, $params, $abort);
1191 static $_dao = NULL;
1194 $_dao = new CRM_Core_DAO();
1197 $_dao->query($queryStr, $i18nRewrite);
1199 $result = $_dao->getDatabaseResult();
1202 $row = $result->fetchRow();
1213 * @param array $params
1214 * @param bool $abort
1219 public static function composeQuery($query, &$params, $abort = TRUE) {
1221 foreach ($params as $key => $item) {
1222 if (is_numeric($key)) {
1223 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1224 $item[0] = self
::escapeString($item[0]);
1225 if ($item[1] == 'String' ||
1226 $item[1] == 'Memo' ||
1229 // Support class constants stipulating wildcard characters and/or
1230 // non-quoting of strings. Also support legacy code which may be
1231 // passing in TRUE or 1 for $item[2], which used to indicate the
1232 // use of wildcard characters.
1233 if (!empty($item[2])) {
1234 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1235 $item[0] = "'%{$item[0]}%'";
1237 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1238 $item[0] = "'{$item[0]}'";
1242 $item[0] = "'{$item[0]}'";
1246 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1247 strlen($item[0]) == 0
1252 $tr['%' . $key] = $item[0];
1255 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1260 return strtr($query, $tr);
1266 public static function freeResult($ids = NULL) {
1267 global $_DB_DATAOBJECT;
1270 if (!$_DB_DATAOBJECT ||
1271 !isset($_DB_DATAOBJECT['RESULTS'])
1275 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1278 foreach ($ids as $id) {
1279 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1280 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1281 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1283 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1286 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1287 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1293 * This function is to make a shallow copy of an object
1294 * and all the fields in the object
1296 * @param string $daoName
1298 * @param array $criteria
1299 * Array of all the fields & values.
1300 * on which basis to copy
1301 * @param array $newData
1302 * Array of all the fields & values.
1303 * to be copied besides the other fields
1304 * @param string $fieldsFix
1305 * Array of fields that you want to prefix/suffix/replace.
1306 * @param string $blockCopyOfDependencies
1307 * Fields that you want to block from.
1311 * @return (reference ) the newly created copy of the object
1313 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1314 $object = new $daoName( );
1316 $object->id
= $criteria['id'];
1319 foreach ($criteria as $key => $value) {
1320 $object->$key = $value;
1325 while ($object->fetch()) {
1327 // all the objects except with $blockCopyOfDependencies set
1328 // be copied - addresses #CRM-1962
1330 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1334 $newObject = new $daoName( );
1336 $fields = &$object->fields();
1337 if (!is_array($fieldsFix)) {
1338 $fieldsToPrefix = array();
1339 $fieldsToSuffix = array();
1340 $fieldsToReplace = array();
1342 if (!empty($fieldsFix['prefix'])) {
1343 $fieldsToPrefix = $fieldsFix['prefix'];
1345 if (!empty($fieldsFix['suffix'])) {
1346 $fieldsToSuffix = $fieldsFix['suffix'];
1348 if (!empty($fieldsFix['replace'])) {
1349 $fieldsToReplace = $fieldsFix['replace'];
1352 foreach ($fields as $name => $value) {
1353 if ($name == 'id' ||
$value['name'] == 'id') {
1354 // copy everything but the id!
1358 $dbName = $value['name'];
1359 $type = CRM_Utils_Type
::typeToString($value['type']);
1360 $newObject->$dbName = $object->$dbName;
1361 if (isset($fieldsToPrefix[$dbName])) {
1362 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1364 if (isset($fieldsToSuffix[$dbName])) {
1365 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1367 if (isset($fieldsToReplace[$dbName])) {
1368 $newObject->$dbName = $fieldsToReplace[$dbName];
1371 if ($type == 'Timestamp' ||
$type == 'Date') {
1372 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1376 foreach ($newData as $k => $v) {
1377 $newObject->$k = $v;
1386 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1387 $object = new $daoName( );
1388 $object->id
= $fromId;
1390 if ($object->find(TRUE)) {
1391 $newObject = new $daoName( );
1392 $newObject->id
= $toId;
1394 if ($newObject->find(TRUE)) {
1395 $fields = &$object->fields();
1396 foreach ($fields as $name => $value) {
1397 if ($name == 'id' ||
$value['name'] == 'id') {
1398 // copy everything but the id!
1402 $colName = $value['name'];
1403 $newObject->$colName = $object->$colName;
1405 if (substr($name, -5) == '_date' ||
1406 substr($name, -10) == '_date_time'
1408 $newObject->$colName = CRM_Utils_Date
::isoToMysql($newObject->$colName);
1411 foreach ($newData as $k => $v) {
1412 $newObject->$k = $v;
1418 return CRM_Core_DAO
::$_nullObject;
1422 * Given the component id, compute the contact id
1423 * since its used for things like send email
1425 * @param $componentIDs
1426 * @param string $tableName
1430 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1431 $contactIDs = array();
1433 if (empty($componentIDs)) {
1437 $IDs = implode(',', $componentIDs);
1441 WHERE id IN ( $IDs )
1444 $dao = CRM_Core_DAO
::executeQuery($query);
1445 while ($dao->fetch()) {
1446 $contactIDs[] = $dao->contact_id
;
1452 * Fetch object based on array of properties
1454 * @param string $daoName
1455 * Name of the dao object.
1456 * @param string $fieldIdName
1457 * @param int $fieldId
1459 * @param array $returnProperities
1460 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1462 * @return object an object of type referenced by daoName
1465 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1466 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1467 $object = new $daoName( );
1468 $object->$fieldIdName = $fieldId;
1470 // return only specific fields if returnproperties are sent
1471 if (!empty($returnProperities)) {
1472 $object->selectAdd();
1473 $object->selectAdd('id');
1474 $object->selectAdd(implode(',', $returnProperities));
1478 while ($object->fetch()) {
1479 $defaults = array();
1480 self
::storeValues($object, $defaults);
1481 $details[$object->id
] = $defaults;
1487 public static function dropAllTables() {
1489 // first drop all the custom tables we've created
1490 CRM_Core_BAO_CustomGroup
::dropAllTables();
1492 // drop all multilingual views
1493 CRM_Core_I18n_Schema
::dropAllViews();
1495 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1496 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1497 '..' . DIRECTORY_SEPARATOR
.
1498 '..' . DIRECTORY_SEPARATOR
.
1499 'sql' . DIRECTORY_SEPARATOR
.
1500 'civicrm_drop.mysql'
1509 public static function escapeString($string) {
1510 static $_dao = NULL;
1513 // If this is an atypical case (e.g. preparing .sql files
1514 // before Civi has been installed), then we fallback to
1515 // DB-less escaping helper (mysql_real_escape_string).
1516 // Note: In typical usage, escapeString() will only
1517 // check one conditional ("if !$_dao") rather than
1518 // two conditionals ("if !defined(DSN)")
1519 if (!defined('CIVICRM_DSN')) {
1520 if (function_exists('mysql_real_escape_string')) {
1521 return mysql_real_escape_string($string);
1523 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1527 $_dao = new CRM_Core_DAO();
1530 return $_dao->escape($string);
1534 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1539 * String the value to use if $strings has no elements.
1540 * @return string eg "abc","def","ghi"
1542 public static function escapeStrings($strings, $default = NULL) {
1543 static $_dao = NULL;
1545 $_dao = new CRM_Core_DAO();
1548 if (empty($strings)) {
1552 $escapes = array_map(array($_dao, 'escape'), $strings);
1553 return '"' . implode('","', $escapes) . '"';
1561 public static function escapeWildCardString($string) {
1563 // ensure we escape the single characters % and _ which are mysql wild
1564 // card characters and could come in via sortByCharacter
1565 // note that mysql does not escape these characters
1566 if ($string && in_array($string,
1567 array('%', '_', '%%', '_%')
1569 return '\\' . $string;
1572 return self
::escapeString($string);
1576 * Creates a test object, including any required objects it needs via recursion
1577 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1578 * ONLY USE FOR TESTING
1580 * @param string $daoName
1581 * @param array $params
1582 * @param int $numObjects
1583 * @param bool $createOnly
1587 static function createTestObject(
1593 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1594 // so we re-set here in case
1595 $config = CRM_Core_Config
::singleton();
1596 $config->backtrace
= TRUE;
1598 static $counter = 0;
1599 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1600 'CRM_Core_DAO_Worldregion',
1601 'CRM_Core_DAO_StateProvince',
1602 'CRM_Core_DAO_Country',
1603 'CRM_Core_DAO_Domain',
1604 'CRM_Financial_DAO_FinancialType'//because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1607 // Prefer to instantiate BAO's instead of DAO's (when possible)
1608 // so that assignTestValue()/assignTestFK() can be overloaded.
1609 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1610 if (class_exists($baoName)) {
1611 $daoName = $baoName;
1614 for ($i = 0; $i < $numObjects; ++
$i) {
1617 /** @var CRM_Core_DAO $object */
1618 $object = new $daoName();
1620 $fields = & $object->fields();
1621 foreach ($fields as $fieldName => $fieldDef) {
1622 $dbName = $fieldDef['name'];
1623 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1624 $required = CRM_Utils_Array
::value('required', $fieldDef);
1626 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1627 $object->$dbName = $params[$dbName];
1630 elseif ($dbName != 'id') {
1631 if ($FKClassName != NULL) {
1632 $object->assignTestFK($fieldName, $fieldDef, $params);
1635 $object->assignTestValue($fieldName, $fieldDef, $counter);
1643 $objects[$i] = $object;
1653 elseif ($numObjects == 1) {
1662 * Deletes the this object plus any dependent objects that are associated with it
1663 * ONLY USE FOR TESTING
1665 * @param string $daoName
1666 * @param array $params
1668 public static function deleteTestObjects($daoName, $params = array()) {
1669 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1670 // so we re-set here in case
1671 $config = CRM_Core_Config
::singleton();
1672 $config->backtrace
= TRUE;
1674 $object = new $daoName();
1675 $object->id
= CRM_Utils_Array
::value('id', $params);
1677 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1678 if ($object->find(TRUE)) {
1680 $fields = &$object->fields();
1681 foreach ($fields as $name => $value) {
1683 $dbName = $value['name'];
1685 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1686 $required = CRM_Utils_Array
::value('required', $value);
1687 if ($FKClassName != NULL
1689 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1690 && ($required ||
$dbName == 'contact_id')
1691 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1692 // to make this test process pass - line below makes pass for now
1693 && $dbName != 'member_of_contact_id') {
1694 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1701 foreach ($deletions as $deletion) {
1702 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1707 * Set defaults when creating new entity
1708 * (don't call this set defaults as already in use with different signature in some places)
1710 * @param array $params
1713 public static function setCreateDefaults(&$params, $defaults) {
1714 if (isset($params['id'])) {
1717 foreach ($defaults as $key => $value) {
1718 if (!array_key_exists($key, $params) ||
$params[$key] === NULL) {
1719 $params[$key] = $value;
1725 * @param string $prefix
1726 * @param bool $addRandomString
1727 * @param null $string
1731 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1732 $tableName = $prefix . "_temp";
1734 if ($addRandomString) {
1736 $tableName .= "_" . $string;
1739 $tableName .= "_" . md5(uniqid('', TRUE));
1747 * @param bool $trigger
1751 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1752 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1754 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1755 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1756 $dao = new CRM_Core_DAO();
1758 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1759 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1765 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1766 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1768 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1773 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1774 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1776 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1783 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1784 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1793 * @param null $message
1794 * @param bool $printDAO
1796 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1797 CRM_Utils_System
::xMemory("{$message}: ");
1800 global $_DB_DATAOBJECT;
1802 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1803 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1805 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1810 * Build a list of triggers via hook and add them to (err, reconcile them
1811 * with) the database.
1814 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1815 * @param bool $force
1819 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1822 $logging = new CRM_Logging_Schema
;
1823 $logging->triggerInfo($info, $tableName, $force);
1825 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1826 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1828 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1830 // drop all existing triggers on all tables
1831 $logging->dropTriggers($tableName);
1833 // now create the set of new triggers
1834 self
::createTriggers($info, $tableName);
1838 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1839 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1840 * TODO: Alternative solutions might be
1841 * * Stop using functions and find another way to strip numeric characters from phones
1842 * * Give better error messages (currently a missing fn fatals with "unknown error")
1844 public static function checkSqlFunctionsExist() {
1845 if (!self
::$_checkedSqlFunctionsExist) {
1846 self
::$_checkedSqlFunctionsExist = TRUE;
1847 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1848 if (!$dao->fetch()) {
1849 self
::triggerRebuild();
1855 * Wrapper function to drop triggers
1858 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1860 public static function dropTriggers($tableName = NULL) {
1863 $logging = new CRM_Logging_Schema
;
1864 $logging->triggerInfo($info, $tableName);
1866 // drop all existing triggers on all tables
1867 $logging->dropTriggers($tableName);
1872 * Array per hook_civicrm_triggerInfo.
1873 * @param $onlyTableName
1874 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1876 public static function createTriggers(&$info, $onlyTableName = NULL) {
1877 // Validate info array, should probably raise errors?
1878 if (is_array($info) == FALSE) {
1882 $triggers = array();
1884 // now enumerate the tables and the events and collect the same set in a different format
1885 foreach ($info as $value) {
1887 // clean the incoming data, skip malformed entries
1888 // TODO: malformed entries should raise errors or get logged.
1889 if (isset($value['table']) == FALSE ||
1890 isset($value['event']) == FALSE ||
1891 isset($value['when']) == FALSE ||
1892 isset($value['sql']) == FALSE
1897 if (is_string($value['table']) == TRUE) {
1898 $tables = array($value['table']);
1901 $tables = $value['table'];
1904 if (is_string($value['event']) == TRUE) {
1905 $events = array(strtolower($value['event']));
1908 $events = array_map('strtolower', $value['event']);
1911 $whenName = strtolower($value['when']);
1913 foreach ($tables as $tableName) {
1914 if (!isset($triggers[$tableName])) {
1915 $triggers[$tableName] = array();
1918 foreach ($events as $eventName) {
1919 $template_params = array('{tableName}', '{eventName}');
1920 $template_values = array($tableName, $eventName);
1922 $sql = str_replace($template_params,
1926 $variables = str_replace($template_params,
1928 CRM_Utils_Array
::value('variables', $value)
1931 if (!isset($triggers[$tableName][$eventName])) {
1932 $triggers[$tableName][$eventName] = array();
1935 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1936 // We're leaving out cursors, conditions, and handlers for now
1937 // they are kind of dangerous in this context anyway
1938 // better off putting them in stored procedures
1939 $triggers[$tableName][$eventName][$whenName] = array(
1940 'variables' => array(),
1946 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1949 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1954 // now spit out the sql
1955 foreach ($triggers as $tableName => $tables) {
1956 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1959 foreach ($tables as $eventName => $events) {
1960 foreach ($events as $whenName => $parts) {
1961 $varString = implode("\n", $parts['variables']);
1962 $sqlString = implode("\n", $parts['sql']);
1963 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1964 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1965 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1967 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1968 CRM_Core_DAO
::executeQuery(
1982 * Given a list of fields, create a list of references.
1984 * @param string $className
1985 * BAO/DAO class name.
1986 * @return array<CRM_Core_Reference_Interface>
1988 public static function createReferenceColumns($className) {
1990 $fields = $className::fields();
1991 foreach ($fields as $field) {
1992 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1993 $result[] = new CRM_Core_Reference_OptionValue(
1994 $className::getTableName(),
1996 'civicrm_option_value',
1997 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
1998 $field['pseudoconstant']['optionGroupName']
2006 * Find all records which refer to this entity.
2008 * @return array of objects referencing this
2010 public function findReferences() {
2011 $links = self
::getReferencesToTable(static::getTableName());
2013 $occurrences = array();
2014 foreach ($links as $refSpec) {
2015 /** @var $refSpec CRM_Core_Reference_Interface */
2016 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
2017 $result = $refSpec->findReferences($this);
2019 while ($result->fetch()) {
2020 $obj = new $daoName();
2021 $obj->id
= $result->id
;
2022 $occurrences[] = $obj;
2027 return $occurrences;
2031 * @return array each item has keys:
2035 * - table: string|null SQL table name
2036 * - key: string|null SQL column name
2038 public function getReferenceCounts() {
2039 $links = self
::getReferencesToTable(static::getTableName());
2042 foreach ($links as $refSpec) {
2043 /** @var $refSpec CRM_Core_Reference_Interface */
2044 $count = $refSpec->getReferenceCount($this);
2045 if ($count['count'] != 0) {
2050 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
2051 /** @var $component CRM_Core_Component_Info */
2052 $counts = array_merge($counts, $component->getReferenceCounts($this));
2054 CRM_Utils_Hook
::referenceCounts($this, $counts);
2060 * List all tables which have hard foreign keys to this table.
2062 * For now, this returns a description of every entity_id/entity_table
2064 * TODO: filter dynamic entity references on the $tableName, based on
2065 * schema metadata in dynamicForeignKey which enumerates a restricted
2066 * set of possible entity_table's.
2068 * @param string $tableName
2069 * Table referred to.
2071 * @return array structure of table and column, listing every table with a
2072 * foreign key reference to $tableName, and the column where the key appears.
2074 public static function getReferencesToTable($tableName) {
2075 $refsFound = array();
2076 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
2077 $links = $daoClassName::getReferenceColumns();
2078 $daoTableName = $daoClassName::getTableName();
2080 foreach ($links as $refSpec) {
2081 /** @var $refSpec CRM_Core_Reference_Interface */
2082 if ($refSpec->matchesTargetTable($tableName)) {
2083 $refsFound[] = $refSpec;
2091 * Lookup the value of a MySQL global configuration variable.
2093 * @param string $name
2094 * E.g. "thread_stack".
2095 * @param mixed $default
2098 public static function getGlobalSetting($name, $default = NULL) {
2099 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2100 // that has been reported to fail under MySQL 5.0 for OS X
2101 $escapedName = self
::escapeString($name);
2102 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2103 if ($dao->fetch()) {
2112 * Get options for the called BAO object's field.
2113 * This function can be overridden by each BAO to add more logic related to context.
2114 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2116 * @param string $fieldName
2117 * @param string $context
2118 * : @see CRM_Core_DAO::buildOptionsContext.
2119 * @param array $props
2120 * : whatever is known about this bao object.
2122 * @return Array|bool
2124 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2125 // If a given bao does not override this function
2126 $baoName = get_called_class();
2127 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2131 * Populate option labels for this object's fields.
2133 * @throws exception if called directly on the base class
2135 public function getOptionLabels() {
2136 $fields = $this->fields();
2137 if ($fields === NULL) {
2138 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2140 foreach ($fields as $field) {
2141 $name = CRM_Utils_Array
::value('name', $field);
2142 if ($name && isset($this->$name)) {
2143 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2144 if ($label !== FALSE) {
2145 // Append 'label' onto the field name
2146 $labelName = $name . '_label';
2147 $this->$labelName = $label;
2154 * Provides documentation and validation for the buildOptions $context param
2156 * @param string $context
2161 public static function buildOptionsContext($context = NULL) {
2163 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2164 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2165 'search' => "Searchable options are returned. Labels are translated.",
2166 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2168 // Validation: enforce uniformity of this param
2169 if ($context !== NULL && !isset($contexts[$context])) {
2170 throw new Exception("'$context' is not a valid context for buildOptions.");
2176 * @param string $fieldName
2177 * @return bool|array
2179 public function getFieldSpec($fieldName) {
2180 $fields = $this->fields();
2181 $fieldKeys = $this->fieldKeys();
2183 // Support "unique names" as well as sql names
2184 $fieldKey = $fieldName;
2185 if (empty($fields[$fieldKey])) {
2186 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2188 // If neither worked then this field doesn't exist. Return false.
2189 if (empty($fields[$fieldKey])) {
2192 return $fields[$fieldKey];
2196 * SQL version of api function to assign filters to the DAO based on the syntax
2197 * $field => array('IN' => array(4,6,9))
2199 * $field => array('LIKE' => array('%me%))
2202 * @param string $fieldName
2205 * Array filter to be applied indexed by operator.
2207 * String type of field (not actually used - nor in api @todo ).
2209 * String alternative field name ('as') @todo- not actually used.
2210 * @param bool $returnSanitisedArray
2211 * Return a sanitised array instead of a clause.
2212 * this is primarily so we can add filters @ the api level to the Query object based fields
2216 * @todo a better solution would be for the query object to apply these filters based on the
2217 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2218 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2219 * required to extend further & it may be the comments per above should be implemented. It may be
2220 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2221 * in one place has some advantages as we try to extend this format
2223 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2224 * depending on whether it is supported as yet
2226 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2227 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2228 // support for other syntaxes is discussed in ticket but being put off for now
2229 foreach ($filter as $operator => $criteria) {
2230 if (in_array($operator, self
::acceptedSQLOperators())) {
2231 switch ($operator) {
2235 if (!$returnSanitisedArray) {
2236 return (sprintf('%s %s', $fieldName, $operator));
2239 return (sprintf('%s %s ', $fieldName, $operator));
2243 // ternary operators
2246 if (empty($criteria[0]) ||
empty($criteria[1])) {
2247 throw new Exception("invalid criteria for $operator");
2249 if (!$returnSanitisedArray) {
2250 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2253 return NULL; // not yet implemented (tests required to implement)
2260 if (empty($criteria)) {
2261 throw new Exception("invalid criteria for $operator");
2263 $escapedCriteria = array_map(array(
2267 if (!$returnSanitisedArray) {
2268 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2270 return $escapedCriteria;
2276 if (!$returnSanitisedArray) {
2277 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2280 return NULL; // not yet implemented (tests required to implement)
2288 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2289 * support for other syntaxes is discussed in ticket but being put off for now
2292 public static function acceptedSQLOperators() {
2293 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
2297 * SQL has a limit of 64 characters on various names:
2298 * table name, trigger name, column name ...
2300 * For custom groups and fields we generated names from user entered input
2301 * which can be longer than this length, this function helps with creating
2302 * strings that meet various criteria.
2304 * @param string $string
2305 * The string to be shortened.
2306 * @param int $length
2307 * The max length of the string.
2309 * @param bool $makeRandom
2313 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2314 // early return for strings that meet the requirements
2315 if (strlen($string) <= $length) {
2319 // easy return for calls that dont need a randomized uniq string
2321 return substr($string, 0, $length);
2324 // the string is longer than the length and we need a uniq string
2325 // for the same tablename we need the same uniq string everytime
2326 // hence we use md5 on the string, which is not random
2327 // we'll append 8 characters to the end of the tableName
2328 $md5string = substr(md5($string), 0, 8);
2329 return substr($string, 0, $length - 8) . "_{$md5string}";
2333 * @param array $params
2335 public function setApiFilter(&$params) {}