3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
29 * Our base DAO class. All DAO classes should inherit from this class.
32 * @copyright CiviCRM LLC (c) 2004-2014
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
40 require_once 'CRM/Core/I18n.php';
45 class CRM_Core_DAO
extends DB_DataObject
{
48 * a null object so we can pass it as reference if / when needed
50 static $_nullObject = NULL;
51 static $_nullArray = array();
53 static $_dbColumnValueCache = NULL;
54 CONST NOT_NULL
= 1, IS_NULL
= 2,
56 VALUE_SEPARATOR
= "\ 1",
57 BULK_INSERT_COUNT
= 200,
58 BULK_INSERT_HIGH_COUNT
= 200,
59 // special value for mail bulk inserts to avoid
60 // potential duplication, assuming a smaller number reduces number of queries
61 // by some factor, so some tradeoff. CRM-8678
62 BULK_MAIL_INSERT_COUNT
= 10,
63 QUERY_FORMAT_WILDCARD
= 1,
64 QUERY_FORMAT_NO_QUOTES
= 2;
67 * Define entities that shouldn't be created or deleted when creating/ deleting
68 * test objects - this prevents world regions, countries etc from being added / deleted
70 static $_testEntitiesToSkip = array();
72 * the factory class for this application
75 static $_factory = NULL;
77 static $_checkedSqlFunctionsExist = FALSE;
82 * @return \CRM_Core_DAO
85 function __construct() {
87 $this->__table
= $this->getTableName();
91 * empty definition for virtual function
93 static function getTableName() {
98 * initialize the DAO object
100 * @param string $dsn the database connection string
106 static function init($dsn) {
107 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
108 $options['database'] = $dsn;
109 if (defined('CIVICRM_DAO_DEBUG')) {
110 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
120 protected function assignTestFK($fieldName, $fieldDef, $params) {
121 $required = CRM_Utils_Array
::value('required', $fieldDef);
122 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
123 $dbName = $fieldDef['name'];
124 $daoName = get_class($this);
126 // skip the FK if it is not required
127 // if it's contact id we should create even if not required
128 // we'll have a go @ fetching first though
129 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
130 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
133 if (!$required && $dbName != 'contact_id') {
134 $fkDAO = new $FKClassName;
135 if ($fkDAO->find(TRUE)) {
136 $this->$dbName = $fkDAO->id
;
141 elseif (in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)) {
142 $depObject = new $FKClassName();
143 $depObject->find(TRUE);
144 $this->$dbName = $depObject->id
;
147 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
148 // FIXME: the fields() metadata is not specific enough
149 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
150 $this->$dbName = $depObject->id
;
154 //if it is required we need to generate the dependency object first
155 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
156 $this->$dbName = $depObject->id
;
162 * Generate and assign an arbitrary value to a field of a test object.
164 * @param string $fieldName
165 * @param array $fieldDef
166 * @param int $counter the globally-unique ID of the test object
168 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
169 $dbName = $fieldDef['name'];
170 $daoName = get_class($this);
173 if (!$handled && $dbName == 'contact_sub_type') {
174 //coming up with a rule to set this is too complex let's not set it
178 // Pick an option value if needed
179 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
180 $options = $daoName::buildOptions($dbName, 'create');
182 $this->$dbName = key($options);
188 switch ($fieldDef['type']) {
189 case CRM_Utils_Type
::T_INT
:
190 case CRM_Utils_Type
::T_FLOAT
:
191 case CRM_Utils_Type
::T_MONEY
:
192 if (isset($fieldDef['precision'])) {
193 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
194 $this->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $fieldDef['precision']);
197 $this->$dbName = $counter;
201 case CRM_Utils_Type
::T_BOOLEAN
:
202 if (isset($fieldDef['default'])) {
203 $this->$dbName = $fieldDef['default'];
205 elseif ($fieldDef['name'] == 'is_deleted' ||
$fieldDef['name'] == 'is_test') {
213 case CRM_Utils_Type
::T_DATE
:
214 case CRM_Utils_Type
::T_TIMESTAMP
:
215 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
216 $this->$dbName = '19700101';
217 if ($dbName == 'end_date') {
218 // put this in the future
219 $this->$dbName = '20200101';
223 case CRM_Utils_Type
::T_TIME
:
224 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
225 //$object->$dbName='000000';
227 case CRM_Utils_Type
::T_CCNUM
:
228 $this->$dbName = '4111 1111 1111 1111';
231 case CRM_Utils_Type
::T_URL
:
232 $this->$dbName = 'http://www.civicrm.org';
235 case CRM_Utils_Type
::T_STRING
:
236 case CRM_Utils_Type
::T_BLOB
:
237 case CRM_Utils_Type
::T_MEDIUMBLOB
:
238 case CRM_Utils_Type
::T_TEXT
:
239 case CRM_Utils_Type
::T_LONGTEXT
:
240 case CRM_Utils_Type
::T_EMAIL
:
242 // WAS: if (isset($value['enumValues'])) {
243 // TODO: see if this works with all pseudoconstants
244 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
245 if (isset($fieldDef['default'])) {
246 $this->$dbName = $fieldDef['default'];
249 $options = CRM_Core_PseudoConstant
::get($daoName, $fieldName);
250 if (is_array($options)) {
251 $this->$dbName = $options[0];
254 $defaultValues = explode(',', $options);
255 $this->$dbName = $defaultValues[0];
260 $this->$dbName = $dbName . '_' . $counter;
261 $maxlength = CRM_Utils_Array
::value('maxlength', $fieldDef);
262 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
263 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
271 * reset the DAO object. DAO is kinda crappy in that there is an unwritten
272 * rule of one query per DAO. We attempt to get around this crappy restricrion
273 * by resetting some of DAO's internal fields. Use this with caution
281 foreach (array_keys($this->table()) as $field) {
282 unset($this->$field);
286 * reset the various DB_DAO structures manually
288 $this->_query
= array();
299 static function getLocaleTableName($tableName) {
302 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
303 if (in_array($tableName, $tables)) {
304 return $tableName . $dbLocale;
311 * Execute a query by the current DAO, localizing it along the way (if needed).
313 * @param string $query the SQL query for execution
314 * @param bool $i18nRewrite whether to rewrite the query
316 * @return object the current DAO object after the query execution
318 function query($query, $i18nRewrite = TRUE) {
319 // rewrite queries that should use $dbLocale-based views for multi-language installs
321 if ($i18nRewrite and $dbLocale) {
322 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
325 return parent
::query($query);
329 * Static function to set the factory instance for this class.
331 * @param object $factory the factory application object
337 static function setFactory(&$factory) {
338 self
::$_factory = &$factory;
342 * Factory method to instantiate a new object from a table name.
344 * @param string $table
349 function factory($table = '') {
350 if (!isset(self
::$_factory)) {
351 return parent
::factory($table);
354 return self
::$_factory->create($table);
358 * Initialization for all DAO objects. Since we access DB_DO programatically
359 * we need to set the links manually.
364 function initialize() {
366 $this->query("SET NAMES utf8");
370 * Defines the default key as 'id'.
385 * Tells DB_DataObject which keys use autoincrement.
386 * 'id' is autoincrementing by default.
392 function sequenceKey() {
393 static $sequenceKeys;
394 if (!isset($sequenceKeys)) {
395 $sequenceKeys = array('id', TRUE);
397 return $sequenceKeys;
401 * returns list of FK relationships
406 * @return array of CRM_Core_Reference_Interface
408 static function getReferenceColumns() {
413 * returns all the column names of this table
419 static function &fields() {
425 * get/set an associative array of table columns
428 * @param array key=>type array
429 * @return array (associative)
432 $fields = &$this->fields();
436 foreach ($fields as $name => $value) {
437 $table[$value['name']] = $value['type'];
438 if (!empty($value['required'])) {
439 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
451 if (!empty($this->id
)) {
459 CRM_Utils_Hook
::postSave($this);
465 * @param bool $created
467 function log($created = FALSE) {
470 if (!$this->getLog()) {
475 $session = CRM_Core_Session
::singleton();
476 $cid = $session->get('userID');
479 // return is we dont have handle to FK
484 $dao = new CRM_Core_DAO_Log();
485 $dao->entity_table
= $this->getTableName();
486 $dao->entity_id
= $this->id
;
487 $dao->modified_id
= $cid;
488 $dao->modified_date
= date("YmdHis");
493 * Given an associative array of name/value pairs, extract all the values
494 * that belong to this object and initialize the object with said values
496 * @param array $params (reference ) associative array of name/value pairs
498 * @return boolean did we copy all null values into the object
501 function copyValues(&$params) {
502 $fields = &$this->fields();
504 foreach ($fields as $name => $value) {
505 $dbName = $value['name'];
506 if (array_key_exists($dbName, $params)) {
507 $pValue = $params[$dbName];
510 elseif (array_key_exists($name, $params)) {
511 $pValue = $params[$name];
518 // if there is no value then make the variable NULL
520 if ($pValue === '') {
521 $this->$dbName = 'null';
524 $this->$dbName = $pValue;
533 * Store all the values from this object in an associative array
534 * this is a destructive store, calling function is responsible
535 * for keeping sanity of id's.
537 * @param object $object the object that we are extracting data from
538 * @param array $values (reference ) associative array of name/value pairs
544 static function storeValues(&$object, &$values) {
545 $fields = &$object->fields();
546 foreach ($fields as $name => $value) {
547 $dbName = $value['name'];
548 if (isset($object->$dbName) && $object->$dbName !== 'null') {
549 $values[$dbName] = $object->$dbName;
550 if ($name != $dbName) {
551 $values[$name] = $object->$dbName;
558 * create an attribute for this specific field. We only do this for strings and text
560 * @param array $field the field under task
562 * @return array|null the attributes for the object
566 static function makeAttribute($field) {
568 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
569 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
570 $size = CRM_Utils_Array
::value('size', $field);
571 if ($maxLength ||
$size) {
572 $attributes = array();
574 $attributes['maxlength'] = $maxLength;
577 $attributes['size'] = $size;
582 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
583 $rows = CRM_Utils_Array
::value('rows', $field);
587 $cols = CRM_Utils_Array
::value('cols', $field);
592 $attributes = array();
593 $attributes['rows'] = $rows;
594 $attributes['cols'] = $cols;
597 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
) {
598 $attributes['size'] = 6;
599 $attributes['maxlength'] = 14;
607 * Get the size and maxLength attributes for this text field
608 * (or for all text fields) in the DAO object.
610 * @param string $class name of DAO class
611 * @param string $fieldName field that i'm interested in or null if
612 * you want the attributes for all DAO text fields
614 * @return array assoc array of name => attribute pairs
618 static function getAttribute($class, $fieldName = NULL) {
619 $object = new $class( );
620 $fields = &$object->fields();
621 if ($fieldName != NULL) {
622 $field = CRM_Utils_Array
::value($fieldName, $fields);
623 return self
::makeAttribute($field);
626 $attributes = array();
627 foreach ($fields as $name => $field) {
628 $attribute = self
::makeAttribute($field);
630 $attributes[$name] = $attribute;
634 if (!empty($attributes)) {
646 static function transaction($type) {
647 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
651 * Check if there is a record with the same name in the db
653 * @param string $value the value of the field we are checking
654 * @param string $daoName the dao object name
655 * @param string $daoID the id of the object being updated. u can change your name
656 * as long as there is no conflict
657 * @param string $fieldName the name of the field in the DAO
659 * @return boolean true if object exists
663 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
664 $object = new $daoName( );
665 $object->$fieldName = $value;
667 $config = CRM_Core_Config
::singleton();
669 if ($object->find(TRUE)) {
670 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
678 * Check if there is a given column in a specific table
680 * @param string $tableName
681 * @param string $columnName
682 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
684 * @return boolean true if exists, else false
687 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
693 $params = array(1 => array($columnName, 'String'));
694 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
695 $result = $dao->fetch() ?
TRUE : FALSE;
701 * Returns the storage engine used by given table-name(optional).
702 * Otherwise scans all the tables and return an array of all the
703 * distinct storage engines being used.
705 * @param string $tableName
707 * @param int $maxTablesToCheck
708 * @param string $fieldName
713 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
715 $query = "SHOW TABLE STATUS LIKE %1";
719 if (isset($tableName)) {
720 $params = array(1 => array($tableName, 'String'));
723 $params = array(1 => array('civicrm_%', 'String'));
726 $dao = CRM_Core_DAO
::executeQuery($query, $params);
729 while ($dao->fetch()) {
730 if (isset($values[$dao->$fieldName]) ||
731 // ignore import and other temp tables
732 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
733 strpos($dao->Name
, '_temp') !== FALSE
737 $values[$dao->$fieldName] = 1;
739 if ($maxTablesToCheck &&
740 $count >= $maxTablesToCheck
750 * @param int $maxTablesToCheck
754 static function isDBMyISAM($maxTablesToCheck = 10) {
755 // show error if any of the tables, use 'MyISAM' storage engine.
756 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
757 if (array_key_exists('MyISAM', $engines)) {
764 * Checks if a constraint exists for a specified table.
766 * @param string $tableName
767 * @param string $constraint
769 * @return boolean true if constraint exists, false otherwise
772 static function checkConstraintExists($tableName, $constraint) {
773 static $show = array();
775 if (!array_key_exists($tableName, $show)) {
776 $query = "SHOW CREATE TABLE $tableName";
777 $dao = CRM_Core_DAO
::executeQuery($query);
779 if (!$dao->fetch()) {
780 CRM_Core_Error
::fatal();
784 $show[$tableName] = $dao->Create_Table
;
787 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
791 * Checks if CONSTRAINT keyword exists for a specified table.
793 * @param array $tables
796 * @internal param string $tableName
798 * @return boolean true if CONSTRAINT keyword exists, false otherwise
800 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
802 foreach($tables as $tableName){
803 if (!array_key_exists($tableName, $show)) {
804 $query = "SHOW CREATE TABLE $tableName";
805 $dao = CRM_Core_DAO
::executeQuery($query);
807 if (!$dao->fetch()) {
808 CRM_Core_Error
::fatal();
812 $show[$tableName] = $dao->Create_Table
;
815 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
827 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
828 * for a specified column of a table.
830 * @param string $tableName
831 * @param string $columnName
833 * @return boolean true if in format, false otherwise
836 static function checkFKConstraintInFormat($tableName, $columnName) {
837 static $show = array();
839 if (!array_key_exists($tableName, $show)) {
840 $query = "SHOW CREATE TABLE $tableName";
841 $dao = CRM_Core_DAO
::executeQuery($query);
843 if (!$dao->fetch()) {
844 CRM_Core_Error
::fatal();
848 $show[$tableName] = $dao->Create_Table
;
850 $constraint = "`FK_{$tableName}_{$columnName}`";
851 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
852 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
856 * Check whether a specific column in a specific table has always the same value
858 * @param string $tableName
859 * @param string $columnName
860 * @param string $columnValue
862 * @return boolean true if the value is always $columnValue, false otherwise
865 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
866 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
867 $dao = CRM_Core_DAO
::executeQuery($query);
868 $result = $dao->fetch() ?
FALSE : TRUE;
874 * Check whether a specific column in a specific table is always NULL
876 * @param string $tableName
877 * @param string $columnName
879 * @return boolean true if if the value is always NULL, false otherwise
882 static function checkFieldIsAlwaysNull($tableName, $columnName) {
883 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
884 $dao = CRM_Core_DAO
::executeQuery($query);
885 $result = $dao->fetch() ?
FALSE : TRUE;
891 * Check if there is a given table in the database
893 * @param string $tableName
895 * @return boolean true if exists, else false
898 static function checkTableExists($tableName) {
903 $params = array(1 => array($tableName, 'String'));
905 $dao = CRM_Core_DAO
::executeQuery($query, $params);
906 $result = $dao->fetch() ?
TRUE : FALSE;
916 function checkVersion($version) {
921 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
922 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
926 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
928 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
929 * @param int $searchValue Value of the column you want to search by
930 * @param string $returnColumn Name of the column you want to GET the value of
931 * @param string $searchColumn Name of the column you want to search by
932 * @param boolean $force Skip use of the cache
934 * @return string|null Value of $returnColumn in the retrieved record
938 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
940 empty($searchValue) ||
941 trim(strtolower($searchValue)) == 'null'
943 // adding this year since developers forget to check for an id
944 // or for the 'null' (which is a bad DAO kludge)
945 // and hence we get the first value in the db
946 CRM_Core_Error
::fatal();
949 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
950 if (self
::$_dbColumnValueCache === NULL) {
951 self
::$_dbColumnValueCache = array();
954 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
955 $object = new $daoName( );
956 $object->$searchColumn = $searchValue;
957 $object->selectAdd();
958 $object->selectAdd($returnColumn);
961 if ($object->find(TRUE)) {
962 $result = $object->$returnColumn;
966 self
::$_dbColumnValueCache[$cacheKey] = $result;
968 return self
::$_dbColumnValueCache[$cacheKey];
972 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
974 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
975 * @param int $searchValue Value of the column you want to search by
976 * @param string $setColumn Name of the column you want to SET the value of
977 * @param string $setValue SET the setColumn to this value
978 * @param string $searchColumn Name of the column you want to search by
980 * @return boolean true if we found and updated the object, else false
984 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
985 $object = new $daoName( );
986 $object->selectAdd();
987 $object->selectAdd("$searchColumn, $setColumn");
988 $object->$searchColumn = $searchValue;
990 if ($object->find(TRUE)) {
991 $object->$setColumn = $setValue;
992 if ($object->save()) {
1003 * @param array|object $sort either array or CRM_Utils_Sort
1004 * @param string $default - default sort value
1006 * @return string - sortString
1010 static function getSortString($sort, $default = NULL) {
1011 // check if sort is of type CRM_Utils_Sort
1012 if (is_a($sort, 'CRM_Utils_Sort')) {
1013 return $sort->orderBy();
1016 // is it an array specified as $field => $sortDirection ?
1018 foreach ($sort as $k => $v) {
1019 $sortString .= "$k $v,";
1021 return rtrim($sortString, ',');
1027 * Takes a bunch of params that are needed to match certain criteria and
1028 * retrieves the relevant objects. Typically the valid params are only
1029 * contact_id. We'll tweak this function to be more full featured over a period
1030 * of time. This is the inverse function of create. It also stores all the retrieved
1031 * values in the default array
1033 * @param string $daoName name of the dao object
1034 * @param array $params (reference ) an assoc array of name/value pairs
1035 * @param array $defaults (reference ) an assoc array to hold the flattened values
1036 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1038 * @return object an object of type referenced by daoName
1042 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1043 $object = new $daoName( );
1044 $object->copyValues($params);
1046 // return only specific fields if returnproperties are sent
1047 if (!empty($returnProperities)) {
1048 $object->selectAdd();
1049 $object->selectAdd(implode(',', $returnProperities));
1052 if ($object->find(TRUE)) {
1053 self
::storeValues($object, $defaults);
1060 * Delete the object records that are associated with this contact
1062 * @param string $daoName name of the dao object
1063 * @param int $contactId id of the contact to delete
1069 static function deleteEntityContact($daoName, $contactId) {
1070 $object = new $daoName( );
1072 $object->entity_table
= 'civicrm_contact';
1073 $object->entity_id
= $contactId;
1080 * @param string $query query to be executed
1082 * @param array $params
1083 * @param bool $abort
1084 * @param null $daoName
1085 * @param bool $freeDAO
1086 * @param bool $i18nRewrite
1087 * @param bool $trapException
1089 * @return Object CRM_Core_DAO object that holds the results of the query
1093 static function &executeQuery(
1099 $i18nRewrite = TRUE,
1100 $trapException = FALSE
1102 $queryStr = self
::composeQuery($query, $params, $abort);
1103 //CRM_Core_Error::debug( 'q', $queryStr );
1106 $dao = new CRM_Core_DAO();
1109 $dao = new $daoName( );
1112 if ($trapException) {
1113 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1116 $result = $dao->query($queryStr, $i18nRewrite);
1118 if (is_a($result, 'DB_Error')) {
1123 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1125 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1133 * execute a query and get the single result
1135 * @param string $query query to be executed
1136 * @param array $params
1137 * @param bool $abort
1138 * @param bool $i18nRewrite
1139 * @return string|null the result of the query if any
1144 static function &singleValueQuery($query,
1149 $queryStr = self
::composeQuery($query, $params, $abort);
1151 static $_dao = NULL;
1154 $_dao = new CRM_Core_DAO();
1157 $_dao->query($queryStr, $i18nRewrite);
1159 $result = $_dao->getDatabaseResult();
1162 $row = $result->fetchRow();
1174 * @param bool $abort
1179 static function composeQuery($query, &$params, $abort = TRUE) {
1181 foreach ($params as $key => $item) {
1182 if (is_numeric($key)) {
1183 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1184 $item[0] = self
::escapeString($item[0]);
1185 if ($item[1] == 'String' ||
1186 $item[1] == 'Memo' ||
1189 // Support class constants stipulating wildcard characters and/or
1190 // non-quoting of strings. Also support legacy code which may be
1191 // passing in TRUE or 1 for $item[2], which used to indicate the
1192 // use of wildcard characters.
1193 if (!empty($item[2])) {
1194 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1195 $item[0] = "'%{$item[0]}%'";
1197 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1198 $item[0] = "'{$item[0]}'";
1202 $item[0] = "'{$item[0]}'";
1206 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1207 strlen($item[0]) == 0
1212 $tr['%' . $key] = $item[0];
1215 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1220 return strtr($query, $tr);
1226 static function freeResult($ids = NULL) {
1227 global $_DB_DATAOBJECT;
1231 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1232 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1234 CRM_Core_Error::debug( 'k', $q );
1239 if (!$_DB_DATAOBJECT ||
1240 !isset($_DB_DATAOBJECT['RESULTS'])
1244 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1247 foreach ($ids as $id) {
1248 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1249 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1250 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1252 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1255 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1256 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1262 * This function is to make a shallow copy of an object
1263 * and all the fields in the object
1265 * @param string $daoName name of the dao
1266 * @param array $criteria array of all the fields & values
1267 * on which basis to copy
1268 * @param array $newData array of all the fields & values
1269 * to be copied besides the other fields
1270 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1271 * @param string $blockCopyOfDependencies fields that you want to block from
1275 * @return (reference ) the newly created copy of the object
1278 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1279 $object = new $daoName( );
1281 $object->id
= $criteria['id'];
1284 foreach ($criteria as $key => $value) {
1285 $object->$key = $value;
1290 while ($object->fetch()) {
1292 // all the objects except with $blockCopyOfDependencies set
1293 // be copied - addresses #CRM-1962
1295 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1299 $newObject = new $daoName( );
1301 $fields = &$object->fields();
1302 if (!is_array($fieldsFix)) {
1303 $fieldsToPrefix = array();
1304 $fieldsToSuffix = array();
1305 $fieldsToReplace = array();
1307 if (!empty($fieldsFix['prefix'])) {
1308 $fieldsToPrefix = $fieldsFix['prefix'];
1310 if (!empty($fieldsFix['suffix'])) {
1311 $fieldsToSuffix = $fieldsFix['suffix'];
1313 if (!empty($fieldsFix['replace'])) {
1314 $fieldsToReplace = $fieldsFix['replace'];
1317 foreach ($fields as $name => $value) {
1318 if ($name == 'id' ||
$value['name'] == 'id') {
1319 // copy everything but the id!
1323 $dbName = $value['name'];
1324 $type = CRM_Utils_Type
::typeToString($value['type']);
1325 $newObject->$dbName = $object->$dbName;
1326 if (isset($fieldsToPrefix[$dbName])) {
1327 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1329 if (isset($fieldsToSuffix[$dbName])) {
1330 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1332 if (isset($fieldsToReplace[$dbName])) {
1333 $newObject->$dbName = $fieldsToReplace[$dbName];
1336 if ($type == 'Timestamp' ||
$type == 'Date') {
1337 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1341 foreach ($newData as $k => $v) {
1342 $newObject->$k = $v;
1352 * Given the component id, compute the contact id
1353 * since its used for things like send email
1355 * @param $componentIDs
1360 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1361 $contactIDs = array();
1363 if (empty($componentIDs)) {
1367 $IDs = implode(',', $componentIDs);
1371 WHERE id IN ( $IDs )
1374 $dao = CRM_Core_DAO
::executeQuery($query);
1375 while ($dao->fetch()) {
1376 $contactIDs[] = $dao->contact_id
;
1382 * Takes a bunch of params that are needed to match certain criteria and
1383 * retrieves the relevant objects. Typically the valid params are only
1384 * contact_id. We'll tweak this function to be more full featured over a period
1385 * of time. This is the inverse function of create. It also stores all the retrieved
1386 * values in the default array
1388 * @param string $daoName name of the dao object
1389 * @param string $fieldIdName
1392 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1394 * @internal param array $params (reference ) an assoc array of name/value pairs
1395 * @internal param array $defaults (reference ) an assoc array to hold the flattened values
1396 * @return object an object of type referenced by daoName
1400 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1401 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1402 $object = new $daoName( );
1403 $object->$fieldIdName = $fieldId;
1405 // return only specific fields if returnproperties are sent
1406 if (!empty($returnProperities)) {
1407 $object->selectAdd();
1408 $object->selectAdd('id');
1409 $object->selectAdd(implode(',', $returnProperities));
1413 while ($object->fetch()) {
1414 $defaults = array();
1415 self
::storeValues($object, $defaults);
1416 $details[$object->id
] = $defaults;
1422 static function dropAllTables() {
1424 // first drop all the custom tables we've created
1425 CRM_Core_BAO_CustomGroup
::dropAllTables();
1427 // drop all multilingual views
1428 CRM_Core_I18n_Schema
::dropAllViews();
1430 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1431 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1432 '..' . DIRECTORY_SEPARATOR
.
1433 '..' . DIRECTORY_SEPARATOR
.
1434 'sql' . DIRECTORY_SEPARATOR
.
1435 'civicrm_drop.mysql'
1444 static function escapeString($string) {
1445 static $_dao = NULL;
1448 $_dao = new CRM_Core_DAO();
1451 return $_dao->escape($string);
1455 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1457 * @param $strings array
1458 * @param $default string the value to use if $strings has no elements
1459 * @return string eg "abc","def","ghi"
1461 static function escapeStrings($strings, $default = NULL) {
1462 static $_dao = NULL;
1464 $_dao = new CRM_Core_DAO();
1467 if (empty($strings)) {
1471 $escapes = array_map(array($_dao, 'escape'), $strings);
1472 return '"' . implode('","', $escapes) . '"';
1480 static function escapeWildCardString($string) {
1482 // ensure we escape the single characters % and _ which are mysql wild
1483 // card characters and could come in via sortByCharacter
1484 // note that mysql does not escape these characters
1485 if ($string && in_array($string,
1486 array('%', '_', '%%', '_%')
1488 return '\\' . $string;
1491 return self
::escapeString($string);
1495 * Creates a test object, including any required objects it needs via recursion
1496 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1497 * ONLY USE FOR TESTING
1500 * @param array $params
1501 * @param int $numObjects
1502 * @param bool $createOnly
1506 static function createTestObject(
1512 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1513 // so we re-set here in case
1514 $config = CRM_Core_Config
::singleton();
1515 $config->backtrace
= TRUE;
1517 static $counter = 0;
1518 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1519 'CRM_Core_DAO_Worldregion',
1520 'CRM_Core_DAO_StateProvince',
1521 'CRM_Core_DAO_Country',
1522 'CRM_Core_DAO_Domain',
1525 for ($i = 0; $i < $numObjects; ++
$i) {
1528 /** @var CRM_Core_DAO $object */
1529 $object = new $daoName();
1531 $fields = & $object->fields();
1532 foreach ($fields as $fieldName => $fieldDef) {
1533 $dbName = $fieldDef['name'];
1534 $FKClassName = CRM_Utils_Array
::value('FKClassName', $fieldDef);
1535 $required = CRM_Utils_Array
::value('required', $fieldDef);
1537 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1538 $object->$dbName = $params[$dbName];
1541 elseif ($dbName != 'id') {
1542 if ($FKClassName != NULL) {
1543 $object->assignTestFK($fieldName, $fieldDef, $params);
1546 $object->assignTestValue($fieldName, $fieldDef, $counter);
1554 $objects[$i] = $object;
1564 elseif ($numObjects == 1) {
1573 * deletes the this object plus any dependent objects that are associated with it
1574 * ONLY USE FOR TESTING
1577 * @param array $params
1579 static function deleteTestObjects($daoName, $params = array(
1581 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1582 // so we re-set here in case
1583 $config = CRM_Core_Config
::singleton();
1584 $config->backtrace
= TRUE;
1586 $object = new $daoName();
1587 $object->id
= CRM_Utils_Array
::value('id', $params);
1589 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1590 if ($object->find(TRUE)) {
1592 $fields = &$object->fields();
1593 foreach ($fields as $name => $value) {
1595 $dbName = $value['name'];
1597 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1598 $required = CRM_Utils_Array
::value('required', $value);
1599 if ($FKClassName != NULL
1601 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1602 && ($required ||
$dbName == 'contact_id')) {
1603 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1610 foreach ($deletions as $deletion) {
1611 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1616 * @param string $prefix
1617 * @param bool $addRandomString
1618 * @param null $string
1622 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1623 $tableName = $prefix . "_temp";
1625 if ($addRandomString) {
1627 $tableName .= "_" . $string;
1630 $tableName .= "_" . md5(uniqid('', TRUE));
1638 * @param bool $trigger
1642 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1643 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1645 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1646 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1647 $dao = new CRM_Core_DAO();
1649 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1650 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1656 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1657 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1659 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1664 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1665 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1667 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1674 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1675 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1684 * @param null $message
1685 * @param bool $printDAO
1687 static function debugPrint($message = NULL, $printDAO = TRUE) {
1688 CRM_Utils_System
::xMemory("{$message}: ");
1691 global $_DB_DATAOBJECT;
1693 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1694 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1696 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1701 * Build a list of triggers via hook and add them to (err, reconcile them
1702 * with) the database.
1704 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1705 * @param bool $force
1709 static function triggerRebuild($tableName = NULL, $force = FALSE) {
1712 $logging = new CRM_Logging_Schema
;
1713 $logging->triggerInfo($info, $tableName, $force);
1715 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1716 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1718 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1720 // drop all existing triggers on all tables
1721 $logging->dropTriggers($tableName);
1723 // now create the set of new triggers
1724 self
::createTriggers($info, $tableName);
1728 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1729 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1730 * TODO: Alternative solutions might be
1731 * * Stop using functions and find another way to strip numeric characters from phones
1732 * * Give better error messages (currently a missing fn fatals with "unknown error")
1734 static function checkSqlFunctionsExist() {
1735 if (!self
::$_checkedSqlFunctionsExist) {
1736 self
::$_checkedSqlFunctionsExist = TRUE;
1737 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1738 if (!$dao->fetch()) {
1739 self
::triggerRebuild();
1745 * Wrapper function to drop triggers
1747 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1749 static function dropTriggers($tableName = NULL) {
1752 $logging = new CRM_Logging_Schema
;
1753 $logging->triggerInfo($info, $tableName);
1755 // drop all existing triggers on all tables
1756 $logging->dropTriggers($tableName);
1760 * @param $info array per hook_civicrm_triggerInfo
1761 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1763 static function createTriggers(&$info, $onlyTableName = NULL) {
1764 // Validate info array, should probably raise errors?
1765 if (is_array($info) == FALSE) {
1769 $triggers = array();
1771 // now enumerate the tables and the events and collect the same set in a different format
1772 foreach ($info as $value) {
1774 // clean the incoming data, skip malformed entries
1775 // TODO: malformed entries should raise errors or get logged.
1776 if (isset($value['table']) == FALSE ||
1777 isset($value['event']) == FALSE ||
1778 isset($value['when']) == FALSE ||
1779 isset($value['sql']) == FALSE
1784 if (is_string($value['table']) == TRUE) {
1785 $tables = array($value['table']);
1788 $tables = $value['table'];
1791 if (is_string($value['event']) == TRUE) {
1792 $events = array(strtolower($value['event']));
1795 $events = array_map('strtolower', $value['event']);
1798 $whenName = strtolower($value['when']);
1800 foreach ($tables as $tableName) {
1801 if (!isset($triggers[$tableName])) {
1802 $triggers[$tableName] = array();
1805 foreach ($events as $eventName) {
1806 $template_params = array('{tableName}', '{eventName}');
1807 $template_values = array($tableName, $eventName);
1809 $sql = str_replace($template_params,
1813 $variables = str_replace($template_params,
1815 CRM_Utils_Array
::value('variables', $value)
1818 if (!isset($triggers[$tableName][$eventName])) {
1819 $triggers[$tableName][$eventName] = array();
1822 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1823 // We're leaving out cursors, conditions, and handlers for now
1824 // they are kind of dangerous in this context anyway
1825 // better off putting them in stored procedures
1826 $triggers[$tableName][$eventName][$whenName] = array(
1827 'variables' => array(),
1833 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1836 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1841 // now spit out the sql
1842 foreach ($triggers as $tableName => $tables) {
1843 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1846 foreach ($tables as $eventName => $events) {
1847 foreach ($events as $whenName => $parts) {
1848 $varString = implode("\n", $parts['variables']);
1849 $sqlString = implode("\n", $parts['sql']);
1850 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1851 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1852 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1854 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1855 CRM_Core_DAO
::executeQuery(
1869 * Given a list of fields, create a list of references.
1871 * @param string $className BAO/DAO class name
1872 * @return array<CRM_Core_Reference_Interface>
1874 static function createReferenceColumns($className) {
1876 $fields = $className::fields();
1877 foreach ($fields as $field) {
1878 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1879 $result[] = new CRM_Core_Reference_OptionValue(
1880 $className::getTableName(),
1882 'civicrm_option_value',
1883 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
1884 $field['pseudoconstant']['optionGroupName']
1892 * Find all records which refer to this entity.
1894 * @return array of objects referencing this
1896 function findReferences() {
1897 $links = self
::getReferencesToTable(static::getTableName());
1899 $occurrences = array();
1900 foreach ($links as $refSpec) {
1901 /** @var $refSpec CRM_Core_Reference_Interface */
1902 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
1903 $result = $refSpec->findReferences($this);
1905 while ($result->fetch()) {
1906 $obj = new $daoName();
1907 $obj->id
= $result->id
;
1908 $occurrences[] = $obj;
1913 return $occurrences;
1917 * @return array each item has keys:
1921 * - table: string|null SQL table name
1922 * - key: string|null SQL column name
1924 function getReferenceCounts() {
1925 $links = self
::getReferencesToTable(static::getTableName());
1928 foreach ($links as $refSpec) {
1929 /** @var $refSpec CRM_Core_Reference_Interface */
1930 $count = $refSpec->getReferenceCount($this);
1931 if ($count['count'] != 0) {
1936 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
1937 /** @var $component CRM_Core_Component_Info */
1938 $counts = array_merge($counts, $component->getReferenceCounts($this));
1940 CRM_Utils_Hook
::referenceCounts($this, $counts);
1946 * List all tables which have hard foreign keys to this table.
1948 * For now, this returns a description of every entity_id/entity_table
1950 * TODO: filter dynamic entity references on the $tableName, based on
1951 * schema metadata in dynamicForeignKey which enumerates a restricted
1952 * set of possible entity_table's.
1954 * @param string $tableName table referred to
1956 * @return array structure of table and column, listing every table with a
1957 * foreign key reference to $tableName, and the column where the key appears.
1959 static function getReferencesToTable($tableName) {
1960 $refsFound = array();
1961 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
1962 $links = $daoClassName::getReferenceColumns();
1963 $daoTableName = $daoClassName::getTableName();
1965 foreach ($links as $refSpec) {
1966 /** @var $refSpec CRM_Core_Reference_Interface */
1967 if ($refSpec->matchesTargetTable($tableName)) {
1968 $refsFound[] = $refSpec;
1976 * Lookup the value of a MySQL global configuration variable.
1978 * @param string $name e.g. "thread_stack"
1979 * @param mixed $default
1982 public static function getGlobalSetting($name, $default = NULL) {
1983 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1984 // that has been reported to fail under MySQL 5.0 for OS X
1985 $escapedName = self
::escapeString($name);
1986 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1987 if ($dao->fetch()) {
1996 * Get options for the called BAO object's field.
1997 * This function can be overridden by each BAO to add more logic related to context.
1998 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2000 * @param string $fieldName
2001 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
2002 * @param array $props : whatever is known about this bao object
2004 * @return Array|bool
2006 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2007 // If a given bao does not override this function
2008 $baoName = get_called_class();
2009 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
2013 * Populate option labels for this object's fields.
2015 * @throws exception if called directly on the base class
2017 public function getOptionLabels() {
2018 $fields = $this->fields();
2019 if ($fields === NULL) {
2020 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2022 foreach ($fields as $field) {
2023 $name = CRM_Utils_Array
::value('name', $field);
2024 if ($name && isset($this->$name)) {
2025 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
2026 if ($label !== FALSE) {
2027 // Append 'label' onto the field name
2028 $labelName = $name . '_label';
2029 $this->$labelName = $label;
2036 * Provides documentation and validation for the buildOptions $context param
2038 * @param String $context
2043 public static function buildOptionsContext($context = NULL) {
2045 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2046 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2047 'search' => "Searchable options are returned. Labels are translated.",
2048 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2050 // Validation: enforce uniformity of this param
2051 if ($context !== NULL && !isset($contexts[$context])) {
2052 throw new Exception("'$context' is not a valid context for buildOptions.");
2059 * @return bool|array
2061 function getFieldSpec($fieldName) {
2062 $fields = $this->fields();
2063 $fieldKeys = $this->fieldKeys();
2065 // Support "unique names" as well as sql names
2066 $fieldKey = $fieldName;
2067 if (empty($fields[$fieldKey])) {
2068 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2070 // If neither worked then this field doesn't exist. Return false.
2071 if (empty($fields[$fieldKey])) {
2074 return $fields[$fieldKey];
2078 * SQL version of api function to assign filters to the DAO based on the syntax
2079 * $field => array('IN' => array(4,6,9))
2081 * $field => array('LIKE' => array('%me%))
2085 * @param $filter array filter to be applied indexed by operator
2086 * @param $type String type of field (not actually used - nor in api @todo )
2087 * @param $alias String alternative field name ('as') @todo- not actually used
2088 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
2089 * this is primarily so we can add filters @ the api level to the Query object based fields
2092 * @internal param string $fieldname name of fields
2093 * @todo a better solution would be for the query object to apply these filters based on the
2094 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2095 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2096 * required to extend further & it may be the comments per above should be implemented. It may be
2097 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2098 * in one place has some advantages as we try to extend this format
2100 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2101 * depending on whether it is supported as yet
2103 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2104 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2105 // support for other syntaxes is discussed in ticket but being put off for now
2106 foreach ($filter as $operator => $criteria) {
2107 if (in_array($operator, self
::acceptedSQLOperators())) {
2108 switch ($operator) {
2112 if(!$returnSanitisedArray) {
2113 return (sprintf('%s %s', $fieldName, $operator));
2116 return (sprintf('%s %s ', $fieldName, $operator));
2120 // ternary operators
2123 if (empty($criteria[0]) ||
empty($criteria[1])) {
2124 throw new Exception("invalid criteria for $operator");
2126 if(!$returnSanitisedArray) {
2127 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2130 return NULL; // not yet implemented (tests required to implement)
2137 if (empty($criteria)) {
2138 throw new Exception("invalid criteria for $operator");
2140 $escapedCriteria = array_map(array(
2144 if(!$returnSanitisedArray) {
2145 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2147 return $escapedCriteria;
2153 if(!$returnSanitisedArray) {
2154 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2157 return NULL; // not yet implemented (tests required to implement)
2165 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2166 * support for other syntaxes is discussed in ticket but being put off for now
2169 public static function acceptedSQLOperators() {
2170 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
2174 * SQL has a limit of 64 characters on various names:
2175 * table name, trigger name, column name ...
2177 * For custom groups and fields we generated names from user entered input
2178 * which can be longer than this length, this function helps with creating
2179 * strings that meet various criteria.
2181 * @param string $string - the string to be shortened
2182 * @param int $length - the max length of the string
2184 * @param bool $makeRandom
2188 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2189 // early return for strings that meet the requirements
2190 if (strlen($string) <= $length) {
2194 // easy return for calls that dont need a randomized uniq string
2195 if (! $makeRandom) {
2196 return substr($string, 0, $length);
2199 // the string is longer than the length and we need a uniq string
2200 // for the same tablename we need the same uniq string everytime
2201 // hence we use md5 on the string, which is not random
2202 // we'll append 8 characters to the end of the tableName
2203 $md5string = substr(md5($string), 0, 8);
2204 return substr($string, 0, $length - 8) . "_{$md5string}";
2210 function setApiFilter(&$params) {}