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
);
115 * reset the DAO object. DAO is kinda crappy in that there is an unwritten
116 * rule of one query per DAO. We attempt to get around this crappy restricrion
117 * by resetting some of DAO's internal fields. Use this with caution
125 foreach (array_keys($this->table()) as $field) {
126 unset($this->$field);
130 * reset the various DB_DAO structures manually
132 $this->_query
= array();
143 static function getLocaleTableName($tableName) {
146 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
147 if (in_array($tableName, $tables)) {
148 return $tableName . $dbLocale;
155 * Execute a query by the current DAO, localizing it along the way (if needed).
157 * @param string $query the SQL query for execution
158 * @param bool $i18nRewrite whether to rewrite the query
160 * @return object the current DAO object after the query execution
162 function query($query, $i18nRewrite = TRUE) {
163 // rewrite queries that should use $dbLocale-based views for multi-language installs
165 if ($i18nRewrite and $dbLocale) {
166 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
169 return parent
::query($query);
173 * Static function to set the factory instance for this class.
175 * @param object $factory the factory application object
181 static function setFactory(&$factory) {
182 self
::$_factory = &$factory;
186 * Factory method to instantiate a new object from a table name.
188 * @param string $table
193 function factory($table = '') {
194 if (!isset(self
::$_factory)) {
195 return parent
::factory($table);
198 return self
::$_factory->create($table);
202 * Initialization for all DAO objects. Since we access DB_DO programatically
203 * we need to set the links manually.
208 function initialize() {
210 $this->query("SET NAMES utf8");
214 * Defines the default key as 'id'.
229 * Tells DB_DataObject which keys use autoincrement.
230 * 'id' is autoincrementing by default.
236 function sequenceKey() {
237 static $sequenceKeys;
238 if (!isset($sequenceKeys)) {
239 $sequenceKeys = array('id', TRUE);
241 return $sequenceKeys;
245 * returns list of FK relationships
250 * @return array of CRM_Core_Reference_Interface
252 static function getReferenceColumns() {
257 * returns all the column names of this table
263 static function &fields() {
269 * get/set an associative array of table columns
272 * @param array key=>type array
273 * @return array (associative)
276 $fields = &$this->fields();
280 foreach ($fields as $name => $value) {
281 $table[$value['name']] = $value['type'];
282 if (!empty($value['required'])) {
283 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
295 if (!empty($this->id
)) {
303 CRM_Utils_Hook
::postSave($this);
309 * @param bool $created
311 function log($created = FALSE) {
314 if (!$this->getLog()) {
319 $session = CRM_Core_Session
::singleton();
320 $cid = $session->get('userID');
323 // return is we dont have handle to FK
328 $dao = new CRM_Core_DAO_Log();
329 $dao->entity_table
= $this->getTableName();
330 $dao->entity_id
= $this->id
;
331 $dao->modified_id
= $cid;
332 $dao->modified_date
= date("YmdHis");
337 * Given an associative array of name/value pairs, extract all the values
338 * that belong to this object and initialize the object with said values
340 * @param array $params (reference ) associative array of name/value pairs
342 * @return boolean did we copy all null values into the object
345 function copyValues(&$params) {
346 $fields = &$this->fields();
348 foreach ($fields as $name => $value) {
349 $dbName = $value['name'];
350 if (array_key_exists($dbName, $params)) {
351 $pValue = $params[$dbName];
354 elseif (array_key_exists($name, $params)) {
355 $pValue = $params[$name];
362 // if there is no value then make the variable NULL
364 if ($pValue === '') {
365 $this->$dbName = 'null';
368 $this->$dbName = $pValue;
377 * Store all the values from this object in an associative array
378 * this is a destructive store, calling function is responsible
379 * for keeping sanity of id's.
381 * @param object $object the object that we are extracting data from
382 * @param array $values (reference ) associative array of name/value pairs
388 static function storeValues(&$object, &$values) {
389 $fields = &$object->fields();
390 foreach ($fields as $name => $value) {
391 $dbName = $value['name'];
392 if (isset($object->$dbName) && $object->$dbName !== 'null') {
393 $values[$dbName] = $object->$dbName;
394 if ($name != $dbName) {
395 $values[$name] = $object->$dbName;
402 * create an attribute for this specific field. We only do this for strings and text
404 * @param array $field the field under task
406 * @return array|null the attributes for the object
410 static function makeAttribute($field) {
412 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
413 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
414 $size = CRM_Utils_Array
::value('size', $field);
415 if ($maxLength ||
$size) {
416 $attributes = array();
418 $attributes['maxlength'] = $maxLength;
421 $attributes['size'] = $size;
426 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
427 $rows = CRM_Utils_Array
::value('rows', $field);
431 $cols = CRM_Utils_Array
::value('cols', $field);
436 $attributes = array();
437 $attributes['rows'] = $rows;
438 $attributes['cols'] = $cols;
441 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
) {
442 $attributes['size'] = 6;
443 $attributes['maxlength'] = 14;
451 * Get the size and maxLength attributes for this text field
452 * (or for all text fields) in the DAO object.
454 * @param string $class name of DAO class
455 * @param string $fieldName field that i'm interested in or null if
456 * you want the attributes for all DAO text fields
458 * @return array assoc array of name => attribute pairs
462 static function getAttribute($class, $fieldName = NULL) {
463 $object = new $class( );
464 $fields = &$object->fields();
465 if ($fieldName != NULL) {
466 $field = CRM_Utils_Array
::value($fieldName, $fields);
467 return self
::makeAttribute($field);
470 $attributes = array();
471 foreach ($fields as $name => $field) {
472 $attribute = self
::makeAttribute($field);
474 $attributes[$name] = $attribute;
478 if (!empty($attributes)) {
490 static function transaction($type) {
491 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
495 * Check if there is a record with the same name in the db
497 * @param string $value the value of the field we are checking
498 * @param string $daoName the dao object name
499 * @param string $daoID the id of the object being updated. u can change your name
500 * as long as there is no conflict
501 * @param string $fieldName the name of the field in the DAO
503 * @return boolean true if object exists
507 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
508 $object = new $daoName( );
509 $object->$fieldName = $value;
511 $config = CRM_Core_Config
::singleton();
513 if ($object->find(TRUE)) {
514 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
522 * Check if there is a given column in a specific table
524 * @param string $tableName
525 * @param string $columnName
526 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
528 * @return boolean true if exists, else false
531 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
537 $params = array(1 => array($columnName, 'String'));
538 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
539 $result = $dao->fetch() ?
TRUE : FALSE;
545 * Returns the storage engine used by given table-name(optional).
546 * Otherwise scans all the tables and return an array of all the
547 * distinct storage engines being used.
549 * @param string $tableName
551 * @param int $maxTablesToCheck
552 * @param string $fieldName
557 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
559 $query = "SHOW TABLE STATUS LIKE %1";
563 if (isset($tableName)) {
564 $params = array(1 => array($tableName, 'String'));
567 $params = array(1 => array('civicrm_%', 'String'));
570 $dao = CRM_Core_DAO
::executeQuery($query, $params);
573 while ($dao->fetch()) {
574 if (isset($values[$dao->$fieldName]) ||
575 // ignore import and other temp tables
576 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
577 strpos($dao->Name
, '_temp') !== FALSE
581 $values[$dao->$fieldName] = 1;
583 if ($maxTablesToCheck &&
584 $count >= $maxTablesToCheck
594 * @param int $maxTablesToCheck
598 static function isDBMyISAM($maxTablesToCheck = 10) {
599 // show error if any of the tables, use 'MyISAM' storage engine.
600 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
601 if (array_key_exists('MyISAM', $engines)) {
608 * Checks if a constraint exists for a specified table.
610 * @param string $tableName
611 * @param string $constraint
613 * @return boolean true if constraint exists, false otherwise
616 static function checkConstraintExists($tableName, $constraint) {
617 static $show = array();
619 if (!array_key_exists($tableName, $show)) {
620 $query = "SHOW CREATE TABLE $tableName";
621 $dao = CRM_Core_DAO
::executeQuery($query);
623 if (!$dao->fetch()) {
624 CRM_Core_Error
::fatal();
628 $show[$tableName] = $dao->Create_Table
;
631 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
635 * Checks if CONSTRAINT keyword exists for a specified table.
637 * @param array $tables
640 * @internal param string $tableName
642 * @return boolean true if CONSTRAINT keyword exists, false otherwise
644 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
646 foreach($tables as $tableName){
647 if (!array_key_exists($tableName, $show)) {
648 $query = "SHOW CREATE TABLE $tableName";
649 $dao = CRM_Core_DAO
::executeQuery($query);
651 if (!$dao->fetch()) {
652 CRM_Core_Error
::fatal();
656 $show[$tableName] = $dao->Create_Table
;
659 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
671 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
672 * for a specified column of a table.
674 * @param string $tableName
675 * @param string $columnName
677 * @return boolean true if in format, false otherwise
680 static function checkFKConstraintInFormat($tableName, $columnName) {
681 static $show = array();
683 if (!array_key_exists($tableName, $show)) {
684 $query = "SHOW CREATE TABLE $tableName";
685 $dao = CRM_Core_DAO
::executeQuery($query);
687 if (!$dao->fetch()) {
688 CRM_Core_Error
::fatal();
692 $show[$tableName] = $dao->Create_Table
;
694 $constraint = "`FK_{$tableName}_{$columnName}`";
695 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
696 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
700 * Check whether a specific column in a specific table has always the same value
702 * @param string $tableName
703 * @param string $columnName
704 * @param string $columnValue
706 * @return boolean true if the value is always $columnValue, false otherwise
709 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
710 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
711 $dao = CRM_Core_DAO
::executeQuery($query);
712 $result = $dao->fetch() ?
FALSE : TRUE;
718 * Check whether a specific column in a specific table is always NULL
720 * @param string $tableName
721 * @param string $columnName
723 * @return boolean true if if the value is always NULL, false otherwise
726 static function checkFieldIsAlwaysNull($tableName, $columnName) {
727 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
728 $dao = CRM_Core_DAO
::executeQuery($query);
729 $result = $dao->fetch() ?
FALSE : TRUE;
735 * Check if there is a given table in the database
737 * @param string $tableName
739 * @return boolean true if exists, else false
742 static function checkTableExists($tableName) {
747 $params = array(1 => array($tableName, 'String'));
749 $dao = CRM_Core_DAO
::executeQuery($query, $params);
750 $result = $dao->fetch() ?
TRUE : FALSE;
760 function checkVersion($version) {
765 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
766 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
770 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
772 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
773 * @param int $searchValue Value of the column you want to search by
774 * @param string $returnColumn Name of the column you want to GET the value of
775 * @param string $searchColumn Name of the column you want to search by
776 * @param boolean $force Skip use of the cache
778 * @return string|null Value of $returnColumn in the retrieved record
782 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
784 empty($searchValue) ||
785 trim(strtolower($searchValue)) == 'null'
787 // adding this year since developers forget to check for an id
788 // or for the 'null' (which is a bad DAO kludge)
789 // and hence we get the first value in the db
790 CRM_Core_Error
::fatal();
793 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
794 if (self
::$_dbColumnValueCache === NULL) {
795 self
::$_dbColumnValueCache = array();
798 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
799 $object = new $daoName( );
800 $object->$searchColumn = $searchValue;
801 $object->selectAdd();
802 $object->selectAdd($returnColumn);
805 if ($object->find(TRUE)) {
806 $result = $object->$returnColumn;
810 self
::$_dbColumnValueCache[$cacheKey] = $result;
812 return self
::$_dbColumnValueCache[$cacheKey];
816 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
818 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
819 * @param int $searchValue Value of the column you want to search by
820 * @param string $setColumn Name of the column you want to SET the value of
821 * @param string $setValue SET the setColumn to this value
822 * @param string $searchColumn Name of the column you want to search by
824 * @return boolean true if we found and updated the object, else false
828 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
829 $object = new $daoName( );
830 $object->selectAdd();
831 $object->selectAdd("$searchColumn, $setColumn");
832 $object->$searchColumn = $searchValue;
834 if ($object->find(TRUE)) {
835 $object->$setColumn = $setValue;
836 if ($object->save()) {
847 * @param array|object $sort either array or CRM_Utils_Sort
848 * @param string $default - default sort value
850 * @return string - sortString
854 static function getSortString($sort, $default = NULL) {
855 // check if sort is of type CRM_Utils_Sort
856 if (is_a($sort, 'CRM_Utils_Sort')) {
857 return $sort->orderBy();
860 // is it an array specified as $field => $sortDirection ?
862 foreach ($sort as $k => $v) {
863 $sortString .= "$k $v,";
865 return rtrim($sortString, ',');
871 * Takes a bunch of params that are needed to match certain criteria and
872 * retrieves the relevant objects. Typically the valid params are only
873 * contact_id. We'll tweak this function to be more full featured over a period
874 * of time. This is the inverse function of create. It also stores all the retrieved
875 * values in the default array
877 * @param string $daoName name of the dao object
878 * @param array $params (reference ) an assoc array of name/value pairs
879 * @param array $defaults (reference ) an assoc array to hold the flattened values
880 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
882 * @return object an object of type referenced by daoName
886 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
887 $object = new $daoName( );
888 $object->copyValues($params);
890 // return only specific fields if returnproperties are sent
891 if (!empty($returnProperities)) {
892 $object->selectAdd();
893 $object->selectAdd(implode(',', $returnProperities));
896 if ($object->find(TRUE)) {
897 self
::storeValues($object, $defaults);
904 * Delete the object records that are associated with this contact
906 * @param string $daoName name of the dao object
907 * @param int $contactId id of the contact to delete
913 static function deleteEntityContact($daoName, $contactId) {
914 $object = new $daoName( );
916 $object->entity_table
= 'civicrm_contact';
917 $object->entity_id
= $contactId;
924 * @param string $query query to be executed
926 * @param array $params
928 * @param null $daoName
929 * @param bool $freeDAO
930 * @param bool $i18nRewrite
931 * @param bool $trapException
933 * @return Object CRM_Core_DAO object that holds the results of the query
937 static function &executeQuery(
944 $trapException = FALSE
946 $queryStr = self
::composeQuery($query, $params, $abort);
947 //CRM_Core_Error::debug( 'q', $queryStr );
950 $dao = new CRM_Core_DAO();
953 $dao = new $daoName( );
956 if ($trapException) {
957 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
960 $result = $dao->query($queryStr, $i18nRewrite);
962 if (is_a($result, 'DB_Error')) {
967 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
969 // we typically do this for insert/update/delete stataments OR if explicitly asked to
977 * execute a query and get the single result
979 * @param string $query query to be executed
980 * @param array $params
982 * @param bool $i18nRewrite
983 * @return string|null the result of the query if any
988 static function &singleValueQuery($query,
993 $queryStr = self
::composeQuery($query, $params, $abort);
998 $_dao = new CRM_Core_DAO();
1001 $_dao->query($queryStr, $i18nRewrite);
1003 $result = $_dao->getDatabaseResult();
1006 $row = $result->fetchRow();
1018 * @param bool $abort
1023 static function composeQuery($query, &$params, $abort = TRUE) {
1025 foreach ($params as $key => $item) {
1026 if (is_numeric($key)) {
1027 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
1028 $item[0] = self
::escapeString($item[0]);
1029 if ($item[1] == 'String' ||
1030 $item[1] == 'Memo' ||
1033 // Support class constants stipulating wildcard characters and/or
1034 // non-quoting of strings. Also support legacy code which may be
1035 // passing in TRUE or 1 for $item[2], which used to indicate the
1036 // use of wildcard characters.
1037 if (!empty($item[2])) {
1038 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
1039 $item[0] = "'%{$item[0]}%'";
1041 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
1042 $item[0] = "'{$item[0]}'";
1046 $item[0] = "'{$item[0]}'";
1050 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1051 strlen($item[0]) == 0
1056 $tr['%' . $key] = $item[0];
1059 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1064 return strtr($query, $tr);
1070 static function freeResult($ids = NULL) {
1071 global $_DB_DATAOBJECT;
1075 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1076 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1078 CRM_Core_Error::debug( 'k', $q );
1083 if (!$_DB_DATAOBJECT ||
1084 !isset($_DB_DATAOBJECT['RESULTS'])
1088 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1091 foreach ($ids as $id) {
1092 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1093 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1094 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1096 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1099 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1100 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1106 * This function is to make a shallow copy of an object
1107 * and all the fields in the object
1109 * @param string $daoName name of the dao
1110 * @param array $criteria array of all the fields & values
1111 * on which basis to copy
1112 * @param array $newData array of all the fields & values
1113 * to be copied besides the other fields
1114 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1115 * @param string $blockCopyOfDependencies fields that you want to block from
1119 * @return (reference ) the newly created copy of the object
1122 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1123 $object = new $daoName( );
1125 $object->id
= $criteria['id'];
1128 foreach ($criteria as $key => $value) {
1129 $object->$key = $value;
1134 while ($object->fetch()) {
1136 // all the objects except with $blockCopyOfDependencies set
1137 // be copied - addresses #CRM-1962
1139 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1143 $newObject = new $daoName( );
1145 $fields = &$object->fields();
1146 if (!is_array($fieldsFix)) {
1147 $fieldsToPrefix = array();
1148 $fieldsToSuffix = array();
1149 $fieldsToReplace = array();
1151 if (!empty($fieldsFix['prefix'])) {
1152 $fieldsToPrefix = $fieldsFix['prefix'];
1154 if (!empty($fieldsFix['suffix'])) {
1155 $fieldsToSuffix = $fieldsFix['suffix'];
1157 if (!empty($fieldsFix['replace'])) {
1158 $fieldsToReplace = $fieldsFix['replace'];
1161 foreach ($fields as $name => $value) {
1162 if ($name == 'id' ||
$value['name'] == 'id') {
1163 // copy everything but the id!
1167 $dbName = $value['name'];
1168 $type = CRM_Utils_Type
::typeToString($value['type']);
1169 $newObject->$dbName = $object->$dbName;
1170 if (isset($fieldsToPrefix[$dbName])) {
1171 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1173 if (isset($fieldsToSuffix[$dbName])) {
1174 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1176 if (isset($fieldsToReplace[$dbName])) {
1177 $newObject->$dbName = $fieldsToReplace[$dbName];
1180 if ($type == 'Timestamp' ||
$type == 'Date') {
1181 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1185 foreach ($newData as $k => $v) {
1186 $newObject->$k = $v;
1196 * Given the component id, compute the contact id
1197 * since its used for things like send email
1199 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1200 $contactIDs = array();
1202 if (empty($componentIDs)) {
1206 $IDs = implode(',', $componentIDs);
1210 WHERE id IN ( $IDs )
1213 $dao = CRM_Core_DAO
::executeQuery($query);
1214 while ($dao->fetch()) {
1215 $contactIDs[] = $dao->contact_id
;
1221 * Takes a bunch of params that are needed to match certain criteria and
1222 * retrieves the relevant objects. Typically the valid params are only
1223 * contact_id. We'll tweak this function to be more full featured over a period
1224 * of time. This is the inverse function of create. It also stores all the retrieved
1225 * values in the default array
1227 * @param string $daoName name of the dao object
1228 * @param string $fieldIdName
1231 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1233 * @internal param array $params (reference ) an assoc array of name/value pairs
1234 * @internal param array $defaults (reference ) an assoc array to hold the flattened values
1235 * @return object an object of type referenced by daoName
1239 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1240 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1241 $object = new $daoName( );
1242 $object->$fieldIdName = $fieldId;
1244 // return only specific fields if returnproperties are sent
1245 if (!empty($returnProperities)) {
1246 $object->selectAdd();
1247 $object->selectAdd('id');
1248 $object->selectAdd(implode(',', $returnProperities));
1252 while ($object->fetch()) {
1253 $defaults = array();
1254 self
::storeValues($object, $defaults);
1255 $details[$object->id
] = $defaults;
1261 static function dropAllTables() {
1263 // first drop all the custom tables we've created
1264 CRM_Core_BAO_CustomGroup
::dropAllTables();
1266 // drop all multilingual views
1267 CRM_Core_I18n_Schema
::dropAllViews();
1269 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1270 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1271 '..' . DIRECTORY_SEPARATOR
.
1272 '..' . DIRECTORY_SEPARATOR
.
1273 'sql' . DIRECTORY_SEPARATOR
.
1274 'civicrm_drop.mysql'
1283 static function escapeString($string) {
1284 static $_dao = NULL;
1287 $_dao = new CRM_Core_DAO();
1290 return $_dao->escape($string);
1294 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1296 * @param $strings array
1297 * @param $default string the value to use if $strings has no elements
1298 * @return string eg "abc","def","ghi"
1300 static function escapeStrings($strings, $default = NULL) {
1301 static $_dao = NULL;
1303 $_dao = new CRM_Core_DAO();
1306 if (empty($strings)) {
1310 $escapes = array_map(array($_dao, 'escape'), $strings);
1311 return '"' . implode('","', $escapes) . '"';
1319 static function escapeWildCardString($string) {
1321 // ensure we escape the single characters % and _ which are mysql wild
1322 // card characters and could come in via sortByCharacter
1323 // note that mysql does not escape these characters
1324 if ($string && in_array($string,
1325 array('%', '_', '%%', '_%')
1327 return '\\' . $string;
1330 return self
::escapeString($string);
1334 * Creates a test object, including any required objects it needs via recursion
1335 *createOnly: only create in database, do not store or return the objects (useful for perf testing)
1336 *ONLY USE FOR TESTING
1338 static function createTestObject(
1344 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1345 // so we re-set here in case
1346 $config = CRM_Core_Config
::singleton();
1347 $config->backtrace
= TRUE;
1349 static $counter = 0;
1350 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1351 'CRM_Core_DAO_Worldregion',
1352 'CRM_Core_DAO_StateProvince',
1353 'CRM_Core_DAO_Country',
1354 'CRM_Core_DAO_Domain',
1357 for ($i = 0; $i < $numObjects; ++
$i) {
1360 $object = new $daoName();
1362 $fields = &$object->fields();
1363 foreach ($fields as $name => $value) {
1364 $dbName = $value['name'];
1365 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1366 //coming up with a rule to set this is too complex let's not set it
1369 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1370 $required = CRM_Utils_Array
::value('required', $value);
1371 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1372 $object->$dbName = $params[$dbName];
1375 elseif ($dbName != 'id') {
1376 if ($FKClassName != NULL) {
1377 //skip the FK if it is not required
1378 // if it's contact id we should create even if not required
1379 // we'll have a go @ fetching first though
1380 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
1381 if($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
1384 if (!$required && $dbName != 'contact_id') {
1385 $fkDAO = new $FKClassName;
1386 if($fkDAO->find(TRUE)){
1387 $object->$dbName = $fkDAO->id
;
1392 if(in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)){
1393 $depObject = new $FKClassName();
1394 $depObject->find(TRUE);
1395 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1396 // FIXME: the fields() metadata is not specific enough
1397 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1399 //if it is required we need to generate the dependency object first
1400 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
1402 $object->$dbName = $depObject->id
;
1407 // Pick an option value if needed
1408 if ($value['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
1409 $options = $daoName::buildOptions($dbName, 'create');
1411 $object->$dbName = key($options);
1416 switch ($value['type']) {
1417 case CRM_Utils_Type
::T_INT
:
1418 case CRM_Utils_Type
::T_FLOAT
:
1419 case CRM_Utils_Type
::T_MONEY
:
1420 if (isset($value['precision'])) {
1421 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
1422 $object->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $value['precision']);
1424 $object->$dbName = $counter;
1428 case CRM_Utils_Type
::T_BOOLEAN
:
1429 if (isset($value['default'])) {
1430 $object->$dbName = $value['default'];
1432 elseif ($value['name'] == 'is_deleted' ||
$value['name'] == 'is_test') {
1433 $object->$dbName = 0;
1436 $object->$dbName = 1;
1440 case CRM_Utils_Type
::T_DATE
:
1441 case CRM_Utils_Type
::T_TIMESTAMP
:
1442 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1443 $object->$dbName = '19700101';
1444 if($dbName == 'end_date') {
1445 // put this in the future
1446 $object->$dbName = '20200101';
1450 case CRM_Utils_Type
::T_TIME
:
1451 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
1452 //$object->$dbName='000000';
1454 case CRM_Utils_Type
::T_CCNUM
:
1455 $object->$dbName = '4111 1111 1111 1111';
1458 case CRM_Utils_Type
::T_URL
:
1459 $object->$dbName = 'http://www.civicrm.org';
1462 case CRM_Utils_Type
::T_STRING
:
1463 case CRM_Utils_Type
::T_BLOB
:
1464 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1465 case CRM_Utils_Type
::T_TEXT
:
1466 case CRM_Utils_Type
::T_LONGTEXT
:
1467 case CRM_Utils_Type
::T_EMAIL
:
1469 // WAS: if (isset($value['enumValues'])) {
1470 // TODO: see if this works with all pseudoconstants
1471 if (isset($value['pseudoconstant'], $value['pseudoconstant']['callback'])) {
1472 if (isset($value['default'])) {
1473 $object->$dbName = $value['default'];
1476 $options = CRM_Core_PseudoConstant
::get($daoName, $name);
1477 if (is_array($options)) {
1478 $object->$dbName = $options[0];
1481 $defaultValues = explode(',', $options);
1482 $object->$dbName = $defaultValues[0];
1487 $object->$dbName = $dbName . '_' . $counter;
1488 $maxlength = CRM_Utils_Array
::value('maxlength', $value);
1489 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1490 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1500 $objects[$i] = $object;
1503 else unset($object);
1511 elseif ($numObjects == 1) { return $objects[0];}
1512 else return $objects;
1516 * deletes the this object plus any dependent objects that are associated with it
1517 * ONLY USE FOR TESTING
1519 static function deleteTestObjects($daoName, $params = array(
1521 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1522 // so we re-set here in case
1523 $config = CRM_Core_Config
::singleton();
1524 $config->backtrace
= TRUE;
1526 $object = new $daoName();
1527 $object->id
= CRM_Utils_Array
::value('id', $params);
1529 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1530 if ($object->find(TRUE)) {
1532 $fields = &$object->fields();
1533 foreach ($fields as $name => $value) {
1535 $dbName = $value['name'];
1537 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1538 $required = CRM_Utils_Array
::value('required', $value);
1539 if ($FKClassName != NULL
1541 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1542 && ($required ||
$dbName == 'contact_id')) {
1543 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1550 foreach ($deletions as $deletion) {
1551 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1556 * @param string $prefix
1557 * @param bool $addRandomString
1558 * @param null $string
1562 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1563 $tableName = $prefix . "_temp";
1565 if ($addRandomString) {
1567 $tableName .= "_" . $string;
1570 $tableName .= "_" . md5(uniqid('', TRUE));
1578 * @param bool $trigger
1582 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1583 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1585 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1586 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1587 $dao = new CRM_Core_DAO();
1589 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1590 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1596 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1597 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1599 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1604 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1605 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1607 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1614 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1615 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1624 * @param null $message
1625 * @param bool $printDAO
1627 static function debugPrint($message = NULL, $printDAO = TRUE) {
1628 CRM_Utils_System
::xMemory("{$message}: ");
1631 global $_DB_DATAOBJECT;
1633 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1634 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1636 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1641 * Build a list of triggers via hook and add them to (err, reconcile them
1642 * with) the database.
1644 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1645 * @param bool $force
1649 static function triggerRebuild($tableName = NULL, $force = FALSE) {
1652 $logging = new CRM_Logging_Schema
;
1653 $logging->triggerInfo($info, $tableName, $force);
1655 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1656 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1658 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1660 // drop all existing triggers on all tables
1661 $logging->dropTriggers($tableName);
1663 // now create the set of new triggers
1664 self
::createTriggers($info);
1668 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1669 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1670 * TODO: Alternative solutions might be
1671 * * Stop using functions and find another way to strip numeric characters from phones
1672 * * Give better error messages (currently a missing fn fatals with "unknown error")
1674 static function checkSqlFunctionsExist() {
1675 if (!self
::$_checkedSqlFunctionsExist) {
1676 self
::$_checkedSqlFunctionsExist = TRUE;
1677 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1678 if (!$dao->fetch()) {
1679 self
::triggerRebuild();
1685 * Wrapper function to drop triggers
1687 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1689 static function dropTriggers($tableName = NULL) {
1692 $logging = new CRM_Logging_Schema
;
1693 $logging->triggerInfo($info, $tableName);
1695 // drop all existing triggers on all tables
1696 $logging->dropTriggers($tableName);
1700 * @param $info array per hook_civicrm_triggerInfo
1701 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1703 static function createTriggers(&$info, $onlyTableName = NULL) {
1704 // Validate info array, should probably raise errors?
1705 if (is_array($info) == FALSE) {
1709 $triggers = array();
1711 // now enumerate the tables and the events and collect the same set in a different format
1712 foreach ($info as $value) {
1714 // clean the incoming data, skip malformed entries
1715 // TODO: malformed entries should raise errors or get logged.
1716 if (isset($value['table']) == FALSE ||
1717 isset($value['event']) == FALSE ||
1718 isset($value['when']) == FALSE ||
1719 isset($value['sql']) == FALSE
1724 if (is_string($value['table']) == TRUE) {
1725 $tables = array($value['table']);
1728 $tables = $value['table'];
1731 if (is_string($value['event']) == TRUE) {
1732 $events = array(strtolower($value['event']));
1735 $events = array_map('strtolower', $value['event']);
1738 $whenName = strtolower($value['when']);
1740 foreach ($tables as $tableName) {
1741 if (!isset($triggers[$tableName])) {
1742 $triggers[$tableName] = array();
1745 foreach ($events as $eventName) {
1746 $template_params = array('{tableName}', '{eventName}');
1747 $template_values = array($tableName, $eventName);
1749 $sql = str_replace($template_params,
1753 $variables = str_replace($template_params,
1755 CRM_Utils_Array
::value('variables', $value)
1758 if (!isset($triggers[$tableName][$eventName])) {
1759 $triggers[$tableName][$eventName] = array();
1762 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1763 // We're leaving out cursors, conditions, and handlers for now
1764 // they are kind of dangerous in this context anyway
1765 // better off putting them in stored procedures
1766 $triggers[$tableName][$eventName][$whenName] = array(
1767 'variables' => array(),
1773 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1776 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1781 // now spit out the sql
1782 foreach ($triggers as $tableName => $tables) {
1783 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1786 foreach ($tables as $eventName => $events) {
1787 foreach ($events as $whenName => $parts) {
1788 $varString = implode("\n", $parts['variables']);
1789 $sqlString = implode("\n", $parts['sql']);
1790 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1791 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1792 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1794 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1795 CRM_Core_DAO
::executeQuery(
1809 * Given a list of fields, create a list of references.
1811 * @param string $className BAO/DAO class name
1812 * @return array<CRM_Core_Reference_Interface>
1814 static function createReferenceColumns($className) {
1816 $fields = $className::fields();
1817 foreach ($fields as $field) {
1818 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1819 $result[] = new CRM_Core_Reference_OptionValue(
1820 $className::getTableName(),
1822 'civicrm_option_value',
1823 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
1824 $field['pseudoconstant']['optionGroupName']
1832 * Find all records which refer to this entity.
1834 * @return array of objects referencing this
1836 function findReferences() {
1837 $links = self
::getReferencesToTable(static::getTableName());
1839 $occurrences = array();
1840 foreach ($links as $refSpec) {
1841 /** @var $refSpec CRM_Core_Reference_Interface */
1842 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
1843 $result = $refSpec->findReferences($this);
1845 while ($result->fetch()) {
1846 $obj = new $daoName();
1847 $obj->id
= $result->id
;
1848 $occurrences[] = $obj;
1853 return $occurrences;
1857 * @return array each item has keys:
1861 * - table: string|null SQL table name
1862 * - key: string|null SQL column name
1864 function getReferenceCounts() {
1865 $links = self
::getReferencesToTable(static::getTableName());
1868 foreach ($links as $refSpec) {
1869 /** @var $refSpec CRM_Core_Reference_Interface */
1870 $count = $refSpec->getReferenceCount($this);
1871 if ($count['count'] != 0) {
1876 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
1877 /** @var $component CRM_Core_Component_Info */
1878 $counts = array_merge($counts, $component->getReferenceCounts($this));
1880 CRM_Utils_Hook
::referenceCounts($this, $counts);
1886 * List all tables which have hard foreign keys to this table.
1888 * For now, this returns a description of every entity_id/entity_table
1890 * TODO: filter dynamic entity references on the $tableName, based on
1891 * schema metadata in dynamicForeignKey which enumerates a restricted
1892 * set of possible entity_table's.
1894 * @param string $tableName table referred to
1896 * @return array structure of table and column, listing every table with a
1897 * foreign key reference to $tableName, and the column where the key appears.
1899 static function getReferencesToTable($tableName) {
1900 $refsFound = array();
1901 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
1902 $links = $daoClassName::getReferenceColumns();
1903 $daoTableName = $daoClassName::getTableName();
1905 foreach ($links as $refSpec) {
1906 /** @var $refSpec CRM_Core_Reference_Interface */
1907 if ($refSpec->matchesTargetTable($tableName)) {
1908 $refsFound[] = $refSpec;
1916 * Lookup the value of a MySQL global configuration variable.
1918 * @param string $name e.g. "thread_stack"
1919 * @param mixed $default
1922 public static function getGlobalSetting($name, $default = NULL) {
1923 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1924 // that has been reported to fail under MySQL 5.0 for OS X
1925 $escapedName = self
::escapeString($name);
1926 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1927 if ($dao->fetch()) {
1936 * Get options for the called BAO object's field.
1937 * This function can be overridden by each BAO to add more logic related to context.
1938 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
1940 * @param string $fieldName
1941 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1942 * @param array $props : whatever is known about this bao object
1944 * @return Array|bool
1946 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1947 // If a given bao does not override this function
1948 $baoName = get_called_class();
1949 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
1953 * Populate option labels for this object's fields.
1955 * @throws exception if called directly on the base class
1957 public function getOptionLabels() {
1958 $fields = $this->fields();
1959 if ($fields === NULL) {
1960 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
1962 foreach ($fields as $field) {
1963 $name = CRM_Utils_Array
::value('name', $field);
1964 if ($name && isset($this->$name)) {
1965 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
1966 if ($label !== FALSE) {
1967 // Append 'label' onto the field name
1968 $labelName = $name . '_label';
1969 $this->$labelName = $label;
1976 * Provides documentation and validation for the buildOptions $context param
1978 * @param String $context
1983 public static function buildOptionsContext($context = NULL) {
1985 'get' => "All options are returned, even if they are disabled. Labels are translated.",
1986 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
1987 'search' => "Searchable options are returned. Labels are translated.",
1988 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
1990 // Validation: enforce uniformity of this param
1991 if ($context !== NULL && !isset($contexts[$context])) {
1992 throw new Exception("'$context' is not a valid context for buildOptions.");
1999 * @return bool|array
2001 function getFieldSpec($fieldName) {
2002 $fields = $this->fields();
2003 $fieldKeys = $this->fieldKeys();
2005 // Support "unique names" as well as sql names
2006 $fieldKey = $fieldName;
2007 if (empty($fields[$fieldKey])) {
2008 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2010 // If neither worked then this field doesn't exist. Return false.
2011 if (empty($fields[$fieldKey])) {
2014 return $fields[$fieldKey];
2018 * SQL version of api function to assign filters to the DAO based on the syntax
2019 * $field => array('IN' => array(4,6,9))
2021 * $field => array('LIKE' => array('%me%))
2025 * @param $filter array filter to be applied indexed by operator
2026 * @param $type String type of field (not actually used - nor in api @todo )
2027 * @param $alias String alternative field name ('as') @todo- not actually used
2028 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
2029 * this is primarily so we can add filters @ the api level to the Query object based fields
2032 * @internal param string $fieldname name of fields
2033 * @todo a better solution would be for the query object to apply these filters based on the
2034 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2035 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2036 * required to extend further & it may be the comments per above should be implemented. It may be
2037 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2038 * in one place has some advantages as we try to extend this format
2040 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2041 * depending on whether it is supported as yet
2043 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2044 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2045 // support for other syntaxes is discussed in ticket but being put off for now
2046 foreach ($filter as $operator => $criteria) {
2047 if (in_array($operator, self
::acceptedSQLOperators())) {
2048 switch ($operator) {
2052 if(!$returnSanitisedArray) {
2053 return (sprintf('%s %s', $fieldName, $operator));
2056 return (sprintf('%s %s ', $fieldName, $operator));
2060 // ternary operators
2063 if (empty($criteria[0]) ||
empty($criteria[1])) {
2064 throw new Exception("invalid criteria for $operator");
2066 if(!$returnSanitisedArray) {
2067 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2070 return NULL; // not yet implemented (tests required to implement)
2077 if (empty($criteria)) {
2078 throw new Exception("invalid criteria for $operator");
2080 $escapedCriteria = array_map(array(
2084 if(!$returnSanitisedArray) {
2085 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2087 return $escapedCriteria;
2093 if(!$returnSanitisedArray) {
2094 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2097 return NULL; // not yet implemented (tests required to implement)
2105 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2106 * support for other syntaxes is discussed in ticket but being put off for now
2109 public static function acceptedSQLOperators() {
2110 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
2114 * SQL has a limit of 64 characters on various names:
2115 * table name, trigger name, column name ...
2117 * For custom groups and fields we generated names from user entered input
2118 * which can be longer than this length, this function helps with creating
2119 * strings that meet various criteria.
2121 * @param string $string - the string to be shortened
2122 * @param int $length - the max length of the string
2124 * @param bool $makeRandom
2128 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2129 // early return for strings that meet the requirements
2130 if (strlen($string) <= $length) {
2134 // easy return for calls that dont need a randomized uniq string
2135 if (! $makeRandom) {
2136 return substr($string, 0, $length);
2139 // the string is longer than the length and we need a uniq string
2140 // for the same tablename we need the same uniq string everytime
2141 // hence we use md5 on the string, which is not random
2142 // we'll append 8 characters to the end of the tableName
2143 $md5string = substr(md5($string), 0, 8);
2144 return substr($string, 0, $length - 8) . "_{$md5string}";
2150 function setApiFilter(&$params) {}