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 $newObject->$dbName = $object->$dbName;
1169 if (isset($fieldsToPrefix[$dbName])) {
1170 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1172 if (isset($fieldsToSuffix[$dbName])) {
1173 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1175 if (isset($fieldsToReplace[$dbName])) {
1176 $newObject->$dbName = $fieldsToReplace[$dbName];
1179 if (substr($name, -5) == '_date' ||
1180 substr($name, -10) == '_date_time'
1182 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1186 foreach ($newData as $k => $v) {
1187 $newObject->$k = $v;
1197 * Given the component id, compute the contact id
1198 * since its used for things like send email
1200 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1201 $contactIDs = array();
1203 if (empty($componentIDs)) {
1207 $IDs = implode(',', $componentIDs);
1211 WHERE id IN ( $IDs )
1214 $dao = CRM_Core_DAO
::executeQuery($query);
1215 while ($dao->fetch()) {
1216 $contactIDs[] = $dao->contact_id
;
1222 * Takes a bunch of params that are needed to match certain criteria and
1223 * retrieves the relevant objects. Typically the valid params are only
1224 * contact_id. We'll tweak this function to be more full featured over a period
1225 * of time. This is the inverse function of create. It also stores all the retrieved
1226 * values in the default array
1228 * @param string $daoName name of the dao object
1229 * @param string $fieldIdName
1232 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1234 * @internal param array $params (reference ) an assoc array of name/value pairs
1235 * @internal param array $defaults (reference ) an assoc array to hold the flattened values
1236 * @return object an object of type referenced by daoName
1240 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1241 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1242 $object = new $daoName( );
1243 $object->$fieldIdName = $fieldId;
1245 // return only specific fields if returnproperties are sent
1246 if (!empty($returnProperities)) {
1247 $object->selectAdd();
1248 $object->selectAdd('id');
1249 $object->selectAdd(implode(',', $returnProperities));
1253 while ($object->fetch()) {
1254 $defaults = array();
1255 self
::storeValues($object, $defaults);
1256 $details[$object->id
] = $defaults;
1262 static function dropAllTables() {
1264 // first drop all the custom tables we've created
1265 CRM_Core_BAO_CustomGroup
::dropAllTables();
1267 // drop all multilingual views
1268 CRM_Core_I18n_Schema
::dropAllViews();
1270 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1271 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1272 '..' . DIRECTORY_SEPARATOR
.
1273 '..' . DIRECTORY_SEPARATOR
.
1274 'sql' . DIRECTORY_SEPARATOR
.
1275 'civicrm_drop.mysql'
1284 static function escapeString($string) {
1285 static $_dao = NULL;
1288 $_dao = new CRM_Core_DAO();
1291 return $_dao->escape($string);
1295 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1297 * @param $strings array
1298 * @param $default string the value to use if $strings has no elements
1299 * @return string eg "abc","def","ghi"
1301 static function escapeStrings($strings, $default = NULL) {
1302 static $_dao = NULL;
1304 $_dao = new CRM_Core_DAO();
1307 if (empty($strings)) {
1311 $escapes = array_map(array($_dao, 'escape'), $strings);
1312 return '"' . implode('","', $escapes) . '"';
1320 static function escapeWildCardString($string) {
1322 // ensure we escape the single characters % and _ which are mysql wild
1323 // card characters and could come in via sortByCharacter
1324 // note that mysql does not escape these characters
1325 if ($string && in_array($string,
1326 array('%', '_', '%%', '_%')
1328 return '\\' . $string;
1331 return self
::escapeString($string);
1335 * Creates a test object, including any required objects it needs via recursion
1336 *createOnly: only create in database, do not store or return the objects (useful for perf testing)
1337 *ONLY USE FOR TESTING
1339 static function createTestObject(
1345 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1346 // so we re-set here in case
1347 $config = CRM_Core_Config
::singleton();
1348 $config->backtrace
= TRUE;
1350 static $counter = 0;
1351 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1352 'CRM_Core_DAO_Worldregion',
1353 'CRM_Core_DAO_StateProvince',
1354 'CRM_Core_DAO_Country',
1355 'CRM_Core_DAO_Domain',
1358 for ($i = 0; $i < $numObjects; ++
$i) {
1361 $object = new $daoName();
1363 $fields = &$object->fields();
1364 foreach ($fields as $name => $value) {
1365 $dbName = $value['name'];
1366 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1367 //coming up with a rule to set this is too complex let's not set it
1370 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1371 $required = CRM_Utils_Array
::value('required', $value);
1372 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1373 $object->$dbName = $params[$dbName];
1376 elseif ($dbName != 'id') {
1377 if ($FKClassName != NULL) {
1378 //skip the FK if it is not required
1379 // if it's contact id we should create even if not required
1380 // we'll have a go @ fetching first though
1381 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
1382 if($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
1385 if (!$required && $dbName != 'contact_id') {
1386 $fkDAO = new $FKClassName;
1387 if($fkDAO->find(TRUE)){
1388 $object->$dbName = $fkDAO->id
;
1393 if(in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)){
1394 $depObject = new $FKClassName();
1395 $depObject->find(TRUE);
1396 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1397 // FIXME: the fields() metadata is not specific enough
1398 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1400 //if it is required we need to generate the dependency object first
1401 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
1403 $object->$dbName = $depObject->id
;
1408 // Pick an option value if needed
1409 if ($value['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
1410 $options = $daoName::buildOptions($dbName, 'create');
1412 $object->$dbName = key($options);
1417 switch ($value['type']) {
1418 case CRM_Utils_Type
::T_INT
:
1419 case CRM_Utils_Type
::T_FLOAT
:
1420 case CRM_Utils_Type
::T_MONEY
:
1421 if (isset($value['precision'])) {
1422 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
1423 $object->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $value['precision']);
1425 $object->$dbName = $counter;
1429 case CRM_Utils_Type
::T_BOOLEAN
:
1430 if (isset($value['default'])) {
1431 $object->$dbName = $value['default'];
1433 elseif ($value['name'] == 'is_deleted' ||
$value['name'] == 'is_test') {
1434 $object->$dbName = 0;
1437 $object->$dbName = 1;
1441 case CRM_Utils_Type
::T_DATE
:
1442 case CRM_Utils_Type
::T_TIMESTAMP
:
1443 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1444 $object->$dbName = '19700101';
1445 if($dbName == 'end_date') {
1446 // put this in the future
1447 $object->$dbName = '20200101';
1451 case CRM_Utils_Type
::T_TIME
:
1452 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
1453 //$object->$dbName='000000';
1455 case CRM_Utils_Type
::T_CCNUM
:
1456 $object->$dbName = '4111 1111 1111 1111';
1459 case CRM_Utils_Type
::T_URL
:
1460 $object->$dbName = 'http://www.civicrm.org';
1463 case CRM_Utils_Type
::T_STRING
:
1464 case CRM_Utils_Type
::T_BLOB
:
1465 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1466 case CRM_Utils_Type
::T_TEXT
:
1467 case CRM_Utils_Type
::T_LONGTEXT
:
1468 case CRM_Utils_Type
::T_EMAIL
:
1470 // WAS: if (isset($value['enumValues'])) {
1471 // TODO: see if this works with all pseudoconstants
1472 if (isset($value['pseudoconstant'], $value['pseudoconstant']['callback'])) {
1473 if (isset($value['default'])) {
1474 $object->$dbName = $value['default'];
1477 $options = CRM_Core_PseudoConstant
::get($daoName, $name);
1478 if (is_array($options)) {
1479 $object->$dbName = $options[0];
1482 $defaultValues = explode(',', $options);
1483 $object->$dbName = $defaultValues[0];
1488 $object->$dbName = $dbName . '_' . $counter;
1489 $maxlength = CRM_Utils_Array
::value('maxlength', $value);
1490 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1491 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1501 $objects[$i] = $object;
1504 else unset($object);
1512 elseif ($numObjects == 1) { return $objects[0];}
1513 else return $objects;
1517 * deletes the this object plus any dependent objects that are associated with it
1518 * ONLY USE FOR TESTING
1520 static function deleteTestObjects($daoName, $params = array(
1522 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1523 // so we re-set here in case
1524 $config = CRM_Core_Config
::singleton();
1525 $config->backtrace
= TRUE;
1527 $object = new $daoName();
1528 $object->id
= CRM_Utils_Array
::value('id', $params);
1530 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1531 if ($object->find(TRUE)) {
1533 $fields = &$object->fields();
1534 foreach ($fields as $name => $value) {
1536 $dbName = $value['name'];
1538 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1539 $required = CRM_Utils_Array
::value('required', $value);
1540 if ($FKClassName != NULL
1542 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1543 && ($required ||
$dbName == 'contact_id')) {
1544 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1551 foreach ($deletions as $deletion) {
1552 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1557 * @param string $prefix
1558 * @param bool $addRandomString
1559 * @param null $string
1563 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1564 $tableName = $prefix . "_temp";
1566 if ($addRandomString) {
1568 $tableName .= "_" . $string;
1571 $tableName .= "_" . md5(uniqid('', TRUE));
1579 * @param bool $trigger
1583 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1584 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1586 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1587 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1588 $dao = new CRM_Core_DAO();
1590 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1591 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1597 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1598 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1600 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1605 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1606 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1608 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1615 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1616 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1625 * @param null $message
1626 * @param bool $printDAO
1628 static function debugPrint($message = NULL, $printDAO = TRUE) {
1629 CRM_Utils_System
::xMemory("{$message}: ");
1632 global $_DB_DATAOBJECT;
1634 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1635 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1637 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1642 * Build a list of triggers via hook and add them to (err, reconcile them
1643 * with) the database.
1645 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1646 * @param bool $force
1650 static function triggerRebuild($tableName = NULL, $force = FALSE) {
1653 $logging = new CRM_Logging_Schema
;
1654 $logging->triggerInfo($info, $tableName, $force);
1656 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1657 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1659 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1661 // drop all existing triggers on all tables
1662 $logging->dropTriggers($tableName);
1664 // now create the set of new triggers
1665 self
::createTriggers($info);
1669 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1670 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1671 * TODO: Alternative solutions might be
1672 * * Stop using functions and find another way to strip numeric characters from phones
1673 * * Give better error messages (currently a missing fn fatals with "unknown error")
1675 static function checkSqlFunctionsExist() {
1676 if (!self
::$_checkedSqlFunctionsExist) {
1677 self
::$_checkedSqlFunctionsExist = TRUE;
1678 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1679 if (!$dao->fetch()) {
1680 self
::triggerRebuild();
1686 * Wrapper function to drop triggers
1688 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1690 static function dropTriggers($tableName = NULL) {
1693 $logging = new CRM_Logging_Schema
;
1694 $logging->triggerInfo($info, $tableName);
1696 // drop all existing triggers on all tables
1697 $logging->dropTriggers($tableName);
1701 * @param $info array per hook_civicrm_triggerInfo
1702 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1704 static function createTriggers(&$info, $onlyTableName = NULL) {
1705 // Validate info array, should probably raise errors?
1706 if (is_array($info) == FALSE) {
1710 $triggers = array();
1712 // now enumerate the tables and the events and collect the same set in a different format
1713 foreach ($info as $value) {
1715 // clean the incoming data, skip malformed entries
1716 // TODO: malformed entries should raise errors or get logged.
1717 if (isset($value['table']) == FALSE ||
1718 isset($value['event']) == FALSE ||
1719 isset($value['when']) == FALSE ||
1720 isset($value['sql']) == FALSE
1725 if (is_string($value['table']) == TRUE) {
1726 $tables = array($value['table']);
1729 $tables = $value['table'];
1732 if (is_string($value['event']) == TRUE) {
1733 $events = array(strtolower($value['event']));
1736 $events = array_map('strtolower', $value['event']);
1739 $whenName = strtolower($value['when']);
1741 foreach ($tables as $tableName) {
1742 if (!isset($triggers[$tableName])) {
1743 $triggers[$tableName] = array();
1746 foreach ($events as $eventName) {
1747 $template_params = array('{tableName}', '{eventName}');
1748 $template_values = array($tableName, $eventName);
1750 $sql = str_replace($template_params,
1754 $variables = str_replace($template_params,
1756 CRM_Utils_Array
::value('variables', $value)
1759 if (!isset($triggers[$tableName][$eventName])) {
1760 $triggers[$tableName][$eventName] = array();
1763 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1764 // We're leaving out cursors, conditions, and handlers for now
1765 // they are kind of dangerous in this context anyway
1766 // better off putting them in stored procedures
1767 $triggers[$tableName][$eventName][$whenName] = array(
1768 'variables' => array(),
1774 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1777 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1782 // now spit out the sql
1783 foreach ($triggers as $tableName => $tables) {
1784 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1787 foreach ($tables as $eventName => $events) {
1788 foreach ($events as $whenName => $parts) {
1789 $varString = implode("\n", $parts['variables']);
1790 $sqlString = implode("\n", $parts['sql']);
1791 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1792 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1793 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1795 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1796 CRM_Core_DAO
::executeQuery(
1810 * Given a list of fields, create a list of references.
1812 * @param string $className BAO/DAO class name
1813 * @return array<CRM_Core_Reference_Interface>
1815 static function createReferenceColumns($className) {
1817 $fields = $className::fields();
1818 foreach ($fields as $field) {
1819 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1820 $result[] = new CRM_Core_Reference_OptionValue(
1821 $className::getTableName(),
1823 'civicrm_option_value',
1824 CRM_Utils_Array
::value('keyColumn', $field['pseudoconstant'], 'value'),
1825 $field['pseudoconstant']['optionGroupName']
1833 * Find all records which refer to this entity.
1835 * @return array of objects referencing this
1837 function findReferences() {
1838 $links = self
::getReferencesToTable(static::getTableName());
1840 $occurrences = array();
1841 foreach ($links as $refSpec) {
1842 /** @var $refSpec CRM_Core_Reference_Interface */
1843 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
1844 $result = $refSpec->findReferences($this);
1846 while ($result->fetch()) {
1847 $obj = new $daoName();
1848 $obj->id
= $result->id
;
1849 $occurrences[] = $obj;
1854 return $occurrences;
1860 function getReferenceCounts() {
1861 $links = self
::getReferencesToTable(static::getTableName());
1864 foreach ($links as $refSpec) {
1865 /** @var $refSpec CRM_Core_Reference_Interface */
1866 $count = $refSpec->getReferenceCount($this);
1867 if ($count['count'] != 0) {
1872 foreach (CRM_Core_Component
::getEnabledComponents() as $component) {
1873 /** @var $component CRM_Core_Component_Info */
1874 $counts = array_merge($counts, $component->getReferenceCounts($this));
1876 CRM_Utils_Hook
::referenceCounts($this, $counts);
1882 * List all tables which have hard foreign keys to this table.
1884 * For now, this returns a description of every entity_id/entity_table
1886 * TODO: filter dynamic entity references on the $tableName, based on
1887 * schema metadata in dynamicForeignKey which enumerates a restricted
1888 * set of possible entity_table's.
1890 * @param string $tableName table referred to
1892 * @return array structure of table and column, listing every table with a
1893 * foreign key reference to $tableName, and the column where the key appears.
1895 static function getReferencesToTable($tableName) {
1896 $refsFound = array();
1897 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
1898 $links = $daoClassName::getReferenceColumns();
1899 $daoTableName = $daoClassName::getTableName();
1901 foreach ($links as $refSpec) {
1902 /** @var $refSpec CRM_Core_Reference_Interface */
1903 if ($refSpec->matchesTargetTable($tableName)) {
1904 $refsFound[] = $refSpec;
1912 * Lookup the value of a MySQL global configuration variable.
1914 * @param string $name e.g. "thread_stack"
1915 * @param mixed $default
1918 public static function getGlobalSetting($name, $default = NULL) {
1919 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1920 // that has been reported to fail under MySQL 5.0 for OS X
1921 $escapedName = self
::escapeString($name);
1922 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1923 if ($dao->fetch()) {
1932 * Get options for the called BAO object's field.
1933 * This function can be overridden by each BAO to add more logic related to context.
1934 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
1936 * @param string $fieldName
1937 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1938 * @param array $props : whatever is known about this bao object
1940 * @return Array|bool
1942 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1943 // If a given bao does not override this function
1944 $baoName = get_called_class();
1945 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
1949 * Populate option labels for this object's fields.
1951 * @throws exception if called directly on the base class
1953 public function getOptionLabels() {
1954 $fields = $this->fields();
1955 if ($fields === NULL) {
1956 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
1958 foreach ($fields as $field) {
1959 $name = CRM_Utils_Array
::value('name', $field);
1960 if ($name && isset($this->$name)) {
1961 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
1962 if ($label !== FALSE) {
1963 // Append 'label' onto the field name
1964 $labelName = $name . '_label';
1965 $this->$labelName = $label;
1972 * Provides documentation and validation for the buildOptions $context param
1974 * @param String $context
1979 public static function buildOptionsContext($context = NULL) {
1981 'get' => "All options are returned, even if they are disabled. Labels are translated.",
1982 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
1983 'search' => "Searchable options are returned. Labels are translated.",
1984 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
1986 // Validation: enforce uniformity of this param
1987 if ($context !== NULL && !isset($contexts[$context])) {
1988 throw new Exception("'$context' is not a valid context for buildOptions.");
1995 * @return bool|array
1997 function getFieldSpec($fieldName) {
1998 $fields = $this->fields();
1999 $fieldKeys = $this->fieldKeys();
2001 // Support "unique names" as well as sql names
2002 $fieldKey = $fieldName;
2003 if (empty($fields[$fieldKey])) {
2004 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
2006 // If neither worked then this field doesn't exist. Return false.
2007 if (empty($fields[$fieldKey])) {
2010 return $fields[$fieldKey];
2014 * SQL version of api function to assign filters to the DAO based on the syntax
2015 * $field => array('IN' => array(4,6,9))
2017 * $field => array('LIKE' => array('%me%))
2021 * @param $filter array filter to be applied indexed by operator
2022 * @param $type String type of field (not actually used - nor in api @todo )
2023 * @param $alias String alternative field name ('as') @todo- not actually used
2024 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
2025 * this is primarily so we can add filters @ the api level to the Query object based fields
2028 * @internal param string $fieldname name of fields
2029 * @todo a better solutution would be for the query object to apply these filters based on the
2030 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2031 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2032 * required to extend further & it may be the comments per above should be implemented. It may be
2033 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2034 * in one place has some advantages as we try to extend this format
2036 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2037 * depending on whether it is supported as yet
2039 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2040 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2041 // support for other syntaxes is discussed in ticket but being put off for now
2042 foreach ($filter as $operator => $criteria) {
2043 if (in_array($operator, self
::acceptedSQLOperators())) {
2044 switch ($operator) {
2048 if(!$returnSanitisedArray) {
2049 return (sprintf('%s %s', $fieldName, $operator));
2052 return NULL; // not yet implemented (tests required to implement)
2056 // ternary operators
2059 if (empty($criteria[0]) ||
empty($criteria[1])) {
2060 throw new Exception("invalid criteria for $operator");
2062 if(!$returnSanitisedArray) {
2063 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
2066 return NULL; // not yet implemented (tests required to implement)
2073 if (empty($criteria)) {
2074 throw new Exception("invalid criteria for $operator");
2076 $escapedCriteria = array_map(array(
2080 if(!$returnSanitisedArray) {
2081 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2083 return $escapedCriteria;
2089 if(!$returnSanitisedArray) {
2090 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
2093 return NULL; // not yet implemented (tests required to implement)
2101 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2102 * support for other syntaxes is discussed in ticket but being put off for now
2105 public static function acceptedSQLOperators() {
2106 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
2110 * SQL has a limit of 64 characters on various names:
2111 * table name, trigger name, column name ...
2113 * For custom groups and fields we generated names from user entered input
2114 * which can be longer than this length, this function helps with creating
2115 * strings that meet various criteria.
2117 * @param string $string - the string to be shortened
2118 * @param int $length - the max length of the string
2120 * @param bool $makeRandom
2124 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2125 // early return for strings that meet the requirements
2126 if (strlen($string) <= $length) {
2130 // easy return for calls that dont need a randomized uniq string
2131 if (! $makeRandom) {
2132 return substr($string, 0, $length);
2135 // the string is longer than the length and we need a uniq string
2136 // for the same tablename we need the same uniq string everytime
2137 // hence we use md5 on the string, which is not random
2138 // we'll append 8 characters to the end of the tableName
2139 $md5string = substr(md5($string), 0, 8);
2140 return substr($string, 0, $length - 8) . "_{$md5string}";
2146 function setApiFilter(&$params) {}