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';
41 class CRM_Core_DAO
extends DB_DataObject
{
44 * a null object so we can pass it as reference if / when needed
46 static $_nullObject = NULL;
47 static $_nullArray = array();
49 static $_dbColumnValueCache = NULL;
50 CONST NOT_NULL
= 1, IS_NULL
= 2,
52 VALUE_SEPARATOR
= "\ 1",
53 BULK_INSERT_COUNT
= 200,
54 BULK_INSERT_HIGH_COUNT
= 200,
55 // special value for mail bulk inserts to avoid
56 // potential duplication, assuming a smaller number reduces number of queries
57 // by some factor, so some tradeoff. CRM-8678
58 BULK_MAIL_INSERT_COUNT
= 10,
59 QUERY_FORMAT_WILDCARD
= 1,
60 QUERY_FORMAT_NO_QUOTES
= 2;
63 * Define entities that shouldn't be created or deleted when creating/ deleting
64 * test objects - this prevents world regions, countries etc from being added / deleted
66 static $_testEntitiesToSkip = array();
68 * the factory class for this application
71 static $_factory = NULL;
73 static $_checkedSqlFunctionsExist = FALSE;
78 * @return \CRM_Core_DAO
81 function __construct() {
83 $this->__table
= $this->getTableName();
87 * empty definition for virtual function
89 static function getTableName() {
94 * initialize the DAO object
96 * @param string $dsn the database connection string
102 static function init($dsn) {
103 $options = &PEAR
::getStaticProperty('DB_DataObject', 'options');
104 $options['database'] = $dsn;
105 if (defined('CIVICRM_DAO_DEBUG')) {
106 self
::DebugLevel(CIVICRM_DAO_DEBUG
);
111 * reset the DAO object. DAO is kinda crappy in that there is an unwritten
112 * rule of one query per DAO. We attempt to get around this crappy restricrion
113 * by resetting some of DAO's internal fields. Use this with caution
121 foreach (array_keys($this->table()) as $field) {
122 unset($this->$field);
126 * reset the various DB_DAO structures manually
128 $this->_query
= array();
134 static function getLocaleTableName($tableName) {
137 $tables = CRM_Core_I18n_Schema
::schemaStructureTables();
138 if (in_array($tableName, $tables)) {
139 return $tableName . $dbLocale;
146 * Execute a query by the current DAO, localizing it along the way (if needed).
148 * @param string $query the SQL query for execution
149 * @param bool $i18nRewrite whether to rewrite the query
151 * @return object the current DAO object after the query execution
153 function query($query, $i18nRewrite = TRUE) {
154 // rewrite queries that should use $dbLocale-based views for multi-language installs
156 if ($i18nRewrite and $dbLocale) {
157 $query = CRM_Core_I18n_Schema
::rewriteQuery($query);
160 return parent
::query($query);
164 * Static function to set the factory instance for this class.
166 * @param object $factory the factory application object
172 static function setFactory(&$factory) {
173 self
::$_factory = &$factory;
177 * Factory method to instantiate a new object from a table name.
179 * @param string $table
184 function factory($table = '') {
185 if (!isset(self
::$_factory)) {
186 return parent
::factory($table);
189 return self
::$_factory->create($table);
193 * Initialization for all DAO objects. Since we access DB_DO programatically
194 * we need to set the links manually.
199 function initialize() {
201 $this->query("SET NAMES utf8");
205 * Defines the default key as 'id'.
220 * Tells DB_DataObject which keys use autoincrement.
221 * 'id' is autoincrementing by default.
227 function sequenceKey() {
228 static $sequenceKeys;
229 if (!isset($sequenceKeys)) {
230 $sequenceKeys = array('id', TRUE);
232 return $sequenceKeys;
236 * returns list of FK relationships
241 * @return array of CRM_Core_EntityReference
243 static function getReferenceColumns() {
248 * returns all the column names of this table
254 static function &fields() {
260 $fields = &$this->fields();
264 foreach ($fields as $name => $value) {
265 $table[$value['name']] = $value['type'];
266 if (!empty($value['required'])) {
267 $table[$value['name']] +
= self
::DB_DAO_NOTNULL
;
276 if (!empty($this->id
)) {
284 CRM_Utils_Hook
::postSave($this);
289 function log($created = FALSE) {
292 if (!$this->getLog()) {
297 $session = CRM_Core_Session
::singleton();
298 $cid = $session->get('userID');
301 // return is we dont have handle to FK
306 $dao = new CRM_Core_DAO_Log();
307 $dao->entity_table
= $this->getTableName();
308 $dao->entity_id
= $this->id
;
309 $dao->modified_id
= $cid;
310 $dao->modified_date
= date("YmdHis");
315 * Given an associative array of name/value pairs, extract all the values
316 * that belong to this object and initialize the object with said values
318 * @param array $params (reference ) associative array of name/value pairs
320 * @return boolean did we copy all null values into the object
323 function copyValues(&$params) {
324 $fields = &$this->fields();
326 foreach ($fields as $name => $value) {
327 $dbName = $value['name'];
328 if (array_key_exists($dbName, $params)) {
329 $pValue = $params[$dbName];
332 elseif (array_key_exists($name, $params)) {
333 $pValue = $params[$name];
340 // if there is no value then make the variable NULL
342 if ($pValue === '') {
343 $this->$dbName = 'null';
346 $this->$dbName = $pValue;
355 * Store all the values from this object in an associative array
356 * this is a destructive store, calling function is responsible
357 * for keeping sanity of id's.
359 * @param object $object the object that we are extracting data from
360 * @param array $values (reference ) associative array of name/value pairs
366 static function storeValues(&$object, &$values) {
367 $fields = &$object->fields();
368 foreach ($fields as $name => $value) {
369 $dbName = $value['name'];
370 if (isset($object->$dbName) && $object->$dbName !== 'null') {
371 $values[$dbName] = $object->$dbName;
372 if ($name != $dbName) {
373 $values[$name] = $object->$dbName;
380 * create an attribute for this specific field. We only do this for strings and text
382 * @param array $field the field under task
384 * @return array|null the attributes for the object
388 static function makeAttribute($field) {
390 if (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_STRING
) {
391 $maxLength = CRM_Utils_Array
::value('maxlength', $field);
392 $size = CRM_Utils_Array
::value('size', $field);
393 if ($maxLength ||
$size) {
394 $attributes = array();
396 $attributes['maxlength'] = $maxLength;
399 $attributes['size'] = $size;
404 elseif (CRM_Utils_Array
::value('type', $field) == CRM_Utils_Type
::T_TEXT
) {
405 $rows = CRM_Utils_Array
::value('rows', $field);
409 $cols = CRM_Utils_Array
::value('cols', $field);
414 $attributes = array();
415 $attributes['rows'] = $rows;
416 $attributes['cols'] = $cols;
419 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
) {
420 $attributes['size'] = 6;
421 $attributes['maxlength'] = 14;
429 * Get the size and maxLength attributes for this text field
430 * (or for all text fields) in the DAO object.
432 * @param string $class name of DAO class
433 * @param string $fieldName field that i'm interested in or null if
434 * you want the attributes for all DAO text fields
436 * @return array assoc array of name => attribute pairs
440 static function getAttribute($class, $fieldName = NULL) {
441 $object = new $class( );
442 $fields = &$object->fields();
443 if ($fieldName != NULL) {
444 $field = CRM_Utils_Array
::value($fieldName, $fields);
445 return self
::makeAttribute($field);
448 $attributes = array();
449 foreach ($fields as $name => $field) {
450 $attribute = self
::makeAttribute($field);
452 $attributes[$name] = $attribute;
456 if (!empty($attributes)) {
463 static function transaction($type) {
464 CRM_Core_Error
::fatal('This function is obsolete, please use CRM_Core_Transaction');
468 * Check if there is a record with the same name in the db
470 * @param string $value the value of the field we are checking
471 * @param string $daoName the dao object name
472 * @param string $daoID the id of the object being updated. u can change your name
473 * as long as there is no conflict
474 * @param string $fieldName the name of the field in the DAO
476 * @return boolean true if object exists
480 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
481 $object = new $daoName( );
482 $object->$fieldName = $value;
484 $config = CRM_Core_Config
::singleton();
486 if ($object->find(TRUE)) {
487 return ($daoID && $object->id
== $daoID) ?
TRUE : FALSE;
495 * Check if there is a given column in a specific table
497 * @param string $tableName
498 * @param string $columnName
499 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
501 * @return boolean true if exists, else false
504 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
510 $params = array(1 => array($columnName, 'String'));
511 $dao = CRM_Core_DAO
::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
512 $result = $dao->fetch() ?
TRUE : FALSE;
518 * Returns the storage engine used by given table-name(optional).
519 * Otherwise scans all the tables and return an array of all the
520 * distinct storage engines being used.
522 * @param string $tableName
524 * @param int $maxTablesToCheck
525 * @param string $fieldName
530 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
532 $query = "SHOW TABLE STATUS LIKE %1";
536 if (isset($tableName)) {
537 $params = array(1 => array($tableName, 'String'));
540 $params = array(1 => array('civicrm_%', 'String'));
543 $dao = CRM_Core_DAO
::executeQuery($query, $params);
546 while ($dao->fetch()) {
547 if (isset($values[$dao->$fieldName]) ||
548 // ignore import and other temp tables
549 strpos($dao->Name
, 'civicrm_import_job_') !== FALSE ||
550 strpos($dao->Name
, '_temp') !== FALSE
554 $values[$dao->$fieldName] = 1;
556 if ($maxTablesToCheck &&
557 $count >= $maxTablesToCheck
566 static function isDBMyISAM($maxTablesToCheck = 10) {
567 // show error if any of the tables, use 'MyISAM' storage engine.
568 $engines = self
::getStorageValues(NULL, $maxTablesToCheck);
569 if (array_key_exists('MyISAM', $engines)) {
576 * Checks if a constraint exists for a specified table.
578 * @param string $tableName
579 * @param string $constraint
581 * @return boolean true if constraint exists, false otherwise
584 static function checkConstraintExists($tableName, $constraint) {
585 static $show = array();
587 if (!array_key_exists($tableName, $show)) {
588 $query = "SHOW CREATE TABLE $tableName";
589 $dao = CRM_Core_DAO
::executeQuery($query);
591 if (!$dao->fetch()) {
592 CRM_Core_Error
::fatal();
596 $show[$tableName] = $dao->Create_Table
;
599 return preg_match("/\b$constraint\b/i", $show[$tableName]) ?
TRUE : FALSE;
603 * Checks if CONSTRAINT keyword exists for a specified table.
605 * @param array $tables
608 * @internal param string $tableName
610 * @return boolean true if CONSTRAINT keyword exists, false otherwise
612 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
614 foreach($tables as $tableName){
615 if (!array_key_exists($tableName, $show)) {
616 $query = "SHOW CREATE TABLE $tableName";
617 $dao = CRM_Core_DAO
::executeQuery($query);
619 if (!$dao->fetch()) {
620 CRM_Core_Error
::fatal();
624 $show[$tableName] = $dao->Create_Table
;
627 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ?
TRUE : FALSE;
639 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
640 * for a specified column of a table.
642 * @param string $tableName
643 * @param string $columnName
645 * @return boolean true if in format, false otherwise
648 static function checkFKConstraintInFormat($tableName, $columnName) {
649 static $show = array();
651 if (!array_key_exists($tableName, $show)) {
652 $query = "SHOW CREATE TABLE $tableName";
653 $dao = CRM_Core_DAO
::executeQuery($query);
655 if (!$dao->fetch()) {
656 CRM_Core_Error
::fatal();
660 $show[$tableName] = $dao->Create_Table
;
662 $constraint = "`FK_{$tableName}_{$columnName}`";
663 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
664 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ?
TRUE : FALSE;
668 * Check whether a specific column in a specific table has always the same value
670 * @param string $tableName
671 * @param string $columnName
672 * @param string $columnValue
674 * @return boolean true if the value is always $columnValue, false otherwise
677 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
678 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
679 $dao = CRM_Core_DAO
::executeQuery($query);
680 $result = $dao->fetch() ?
FALSE : TRUE;
686 * Check whether a specific column in a specific table is always NULL
688 * @param string $tableName
689 * @param string $columnName
691 * @return boolean true if if the value is always NULL, false otherwise
694 static function checkFieldIsAlwaysNull($tableName, $columnName) {
695 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
696 $dao = CRM_Core_DAO
::executeQuery($query);
697 $result = $dao->fetch() ?
FALSE : TRUE;
703 * Check if there is a given table in the database
705 * @param string $tableName
707 * @return boolean true if exists, else false
710 static function checkTableExists($tableName) {
715 $params = array(1 => array($tableName, 'String'));
717 $dao = CRM_Core_DAO
::executeQuery($query, $params);
718 $result = $dao->fetch() ?
TRUE : FALSE;
723 function checkVersion($version) {
728 $dbVersion = CRM_Core_DAO
::singleValueQuery($query);
729 return trim($version) == trim($dbVersion) ?
TRUE : FALSE;
733 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
735 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
736 * @param int $searchValue Value of the column you want to search by
737 * @param string $returnColumn Name of the column you want to GET the value of
738 * @param string $searchColumn Name of the column you want to search by
739 * @param boolean $force Skip use of the cache
741 * @return string|null Value of $returnColumn in the retrieved record
745 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
747 empty($searchValue) ||
748 trim(strtolower($searchValue)) == 'null'
750 // adding this year since developers forget to check for an id
751 // or for the 'null' (which is a bad DAO kludge)
752 // and hence we get the first value in the db
753 CRM_Core_Error
::fatal();
756 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
757 if (self
::$_dbColumnValueCache === NULL) {
758 self
::$_dbColumnValueCache = array();
761 if (!array_key_exists($cacheKey, self
::$_dbColumnValueCache) ||
$force) {
762 $object = new $daoName( );
763 $object->$searchColumn = $searchValue;
764 $object->selectAdd();
765 $object->selectAdd($returnColumn);
768 if ($object->find(TRUE)) {
769 $result = $object->$returnColumn;
773 self
::$_dbColumnValueCache[$cacheKey] = $result;
775 return self
::$_dbColumnValueCache[$cacheKey];
779 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
781 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
782 * @param int $searchValue Value of the column you want to search by
783 * @param string $setColumn Name of the column you want to SET the value of
784 * @param string $setValue SET the setColumn to this value
785 * @param string $searchColumn Name of the column you want to search by
787 * @return boolean true if we found and updated the object, else false
791 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
792 $object = new $daoName( );
793 $object->selectAdd();
794 $object->selectAdd("$searchColumn, $setColumn");
795 $object->$searchColumn = $searchValue;
797 if ($object->find(TRUE)) {
798 $object->$setColumn = $setValue;
799 if ($object->save()) {
810 * @param array|object $sort either array or CRM_Utils_Sort
811 * @param string $default - default sort value
813 * @return string - sortString
817 static function getSortString($sort, $default = NULL) {
818 // check if sort is of type CRM_Utils_Sort
819 if (is_a($sort, 'CRM_Utils_Sort')) {
820 return $sort->orderBy();
823 // is it an array specified as $field => $sortDirection ?
825 foreach ($sort as $k => $v) {
826 $sortString .= "$k $v,";
828 return rtrim($sortString, ',');
834 * Takes a bunch of params that are needed to match certain criteria and
835 * retrieves the relevant objects. Typically the valid params are only
836 * contact_id. We'll tweak this function to be more full featured over a period
837 * of time. This is the inverse function of create. It also stores all the retrieved
838 * values in the default array
840 * @param string $daoName name of the dao object
841 * @param array $params (reference ) an assoc array of name/value pairs
842 * @param array $defaults (reference ) an assoc array to hold the flattened values
843 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
845 * @return object an object of type referenced by daoName
849 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
850 $object = new $daoName( );
851 $object->copyValues($params);
853 // return only specific fields if returnproperties are sent
854 if (!empty($returnProperities)) {
855 $object->selectAdd();
856 $object->selectAdd(implode(',', $returnProperities));
859 if ($object->find(TRUE)) {
860 self
::storeValues($object, $defaults);
867 * Delete the object records that are associated with this contact
869 * @param string $daoName name of the dao object
870 * @param int $contactId id of the contact to delete
876 static function deleteEntityContact($daoName, $contactId) {
877 $object = new $daoName( );
879 $object->entity_table
= 'civicrm_contact';
880 $object->entity_id
= $contactId;
887 * @param string $query query to be executed
889 * @param array $params
891 * @param null $daoName
892 * @param bool $freeDAO
893 * @param bool $i18nRewrite
894 * @param bool $trapException
896 * @return Object CRM_Core_DAO object that holds the results of the query
900 static function &executeQuery(
907 $trapException = FALSE
909 $queryStr = self
::composeQuery($query, $params, $abort);
910 //CRM_Core_Error::debug( 'q', $queryStr );
913 $dao = new CRM_Core_DAO();
916 $dao = new $daoName( );
919 if ($trapException) {
920 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
923 $result = $dao->query($queryStr, $i18nRewrite);
925 if (is_a($result, 'DB_Error')) {
930 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
932 // we typically do this for insert/update/delete stataments OR if explicitly asked to
940 * execute a query and get the single result
942 * @param string $query query to be executed
943 * @param array $params
945 * @param bool $i18nRewrite
946 * @return string|null the result of the query if any
951 static function &singleValueQuery($query,
956 $queryStr = self
::composeQuery($query, $params, $abort);
961 $_dao = new CRM_Core_DAO();
964 $_dao->query($queryStr, $i18nRewrite);
966 $result = $_dao->getDatabaseResult();
969 $row = $result->fetchRow();
978 static function composeQuery($query, &$params, $abort = TRUE) {
980 foreach ($params as $key => $item) {
981 if (is_numeric($key)) {
982 if (CRM_Utils_Type
::validate($item[0], $item[1]) !== NULL) {
983 $item[0] = self
::escapeString($item[0]);
984 if ($item[1] == 'String' ||
985 $item[1] == 'Memo' ||
988 // Support class constants stipulating wildcard characters and/or
989 // non-quoting of strings. Also support legacy code which may be
990 // passing in TRUE or 1 for $item[2], which used to indicate the
991 // use of wildcard characters.
992 if (!empty($item[2])) {
993 if ($item[2] & CRM_Core_DAO
::QUERY_FORMAT_WILDCARD ||
$item[2] === TRUE) {
994 $item[0] = "'%{$item[0]}%'";
996 elseif (!($item[2] & CRM_Core_DAO
::QUERY_FORMAT_NO_QUOTES
)) {
997 $item[0] = "'{$item[0]}'";
1001 $item[0] = "'{$item[0]}'";
1005 if (($item[1] == 'Date' ||
$item[1] == 'Timestamp') &&
1006 strlen($item[0]) == 0
1011 $tr['%' . $key] = $item[0];
1014 CRM_Core_Error
::fatal("{$item[0]} is not of type {$item[1]}");
1019 return strtr($query, $tr);
1022 static function freeResult($ids = NULL) {
1023 global $_DB_DATAOBJECT;
1027 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1028 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1030 CRM_Core_Error::debug( 'k', $q );
1035 if (!$_DB_DATAOBJECT ||
1036 !isset($_DB_DATAOBJECT['RESULTS'])
1040 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1043 foreach ($ids as $id) {
1044 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1045 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result
)) {
1046 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result
);
1048 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1051 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1052 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1058 * This function is to make a shallow copy of an object
1059 * and all the fields in the object
1061 * @param string $daoName name of the dao
1062 * @param array $criteria array of all the fields & values
1063 * on which basis to copy
1064 * @param array $newData array of all the fields & values
1065 * to be copied besides the other fields
1066 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1067 * @param string $blockCopyOfDependencies fields that you want to block from
1071 * @return (reference ) the newly created copy of the object
1074 static function ©Generic($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1075 $object = new $daoName( );
1077 $object->id
= $criteria['id'];
1080 foreach ($criteria as $key => $value) {
1081 $object->$key = $value;
1086 while ($object->fetch()) {
1088 // all the objects except with $blockCopyOfDependencies set
1089 // be copied - addresses #CRM-1962
1091 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1095 $newObject = new $daoName( );
1097 $fields = &$object->fields();
1098 if (!is_array($fieldsFix)) {
1099 $fieldsToPrefix = array();
1100 $fieldsToSuffix = array();
1101 $fieldsToReplace = array();
1103 if (!empty($fieldsFix['prefix'])) {
1104 $fieldsToPrefix = $fieldsFix['prefix'];
1106 if (!empty($fieldsFix['suffix'])) {
1107 $fieldsToSuffix = $fieldsFix['suffix'];
1109 if (!empty($fieldsFix['replace'])) {
1110 $fieldsToReplace = $fieldsFix['replace'];
1113 foreach ($fields as $name => $value) {
1114 if ($name == 'id' ||
$value['name'] == 'id') {
1115 // copy everything but the id!
1119 $dbName = $value['name'];
1120 $newObject->$dbName = $object->$dbName;
1121 if (isset($fieldsToPrefix[$dbName])) {
1122 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1124 if (isset($fieldsToSuffix[$dbName])) {
1125 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1127 if (isset($fieldsToReplace[$dbName])) {
1128 $newObject->$dbName = $fieldsToReplace[$dbName];
1131 if (substr($name, -5) == '_date' ||
1132 substr($name, -10) == '_date_time'
1134 $newObject->$dbName = CRM_Utils_Date
::isoToMysql($newObject->$dbName);
1138 foreach ($newData as $k => $v) {
1139 $newObject->$k = $v;
1149 * Given the component id, compute the contact id
1150 * since its used for things like send email
1152 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1153 $contactIDs = array();
1155 if (empty($componentIDs)) {
1159 $IDs = implode(',', $componentIDs);
1163 WHERE id IN ( $IDs )
1166 $dao = CRM_Core_DAO
::executeQuery($query);
1167 while ($dao->fetch()) {
1168 $contactIDs[] = $dao->contact_id
;
1174 * Takes a bunch of params that are needed to match certain criteria and
1175 * retrieves the relevant objects. Typically the valid params are only
1176 * contact_id. We'll tweak this function to be more full featured over a period
1177 * of time. This is the inverse function of create. It also stores all the retrieved
1178 * values in the default array
1180 * @param string $daoName name of the dao object
1181 * @param string $fieldIdName
1184 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1186 * @internal param array $params (reference ) an assoc array of name/value pairs
1187 * @internal param array $defaults (reference ) an assoc array to hold the flattened values
1188 * @return object an object of type referenced by daoName
1192 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1193 require_once (str_replace('_', DIRECTORY_SEPARATOR
, $daoName) . ".php");
1194 $object = new $daoName( );
1195 $object->$fieldIdName = $fieldId;
1197 // return only specific fields if returnproperties are sent
1198 if (!empty($returnProperities)) {
1199 $object->selectAdd();
1200 $object->selectAdd('id');
1201 $object->selectAdd(implode(',', $returnProperities));
1205 while ($object->fetch()) {
1206 $defaults = array();
1207 self
::storeValues($object, $defaults);
1208 $details[$object->id
] = $defaults;
1214 static function dropAllTables() {
1216 // first drop all the custom tables we've created
1217 CRM_Core_BAO_CustomGroup
::dropAllTables();
1219 // drop all multilingual views
1220 CRM_Core_I18n_Schema
::dropAllViews();
1222 CRM_Utils_File
::sourceSQLFile(CIVICRM_DSN
,
1223 dirname(__FILE__
) . DIRECTORY_SEPARATOR
.
1224 '..' . DIRECTORY_SEPARATOR
.
1225 '..' . DIRECTORY_SEPARATOR
.
1226 'sql' . DIRECTORY_SEPARATOR
.
1227 'civicrm_drop.mysql'
1231 static function escapeString($string) {
1232 static $_dao = NULL;
1235 $_dao = new CRM_Core_DAO();
1238 return $_dao->escape($string);
1242 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1244 * @param $strings array
1245 * @param $default string the value to use if $strings has no elements
1246 * @return string eg "abc","def","ghi"
1248 static function escapeStrings($strings, $default = NULL) {
1249 static $_dao = NULL;
1251 $_dao = new CRM_Core_DAO();
1254 if (empty($strings)) {
1258 $escapes = array_map(array($_dao, 'escape'), $strings);
1259 return '"' . implode('","', $escapes) . '"';
1262 static function escapeWildCardString($string) {
1264 // ensure we escape the single characters % and _ which are mysql wild
1265 // card characters and could come in via sortByCharacter
1266 // note that mysql does not escape these characters
1267 if ($string && in_array($string,
1268 array('%', '_', '%%', '_%')
1270 return '\\' . $string;
1273 return self
::escapeString($string);
1277 * Creates a test object, including any required objects it needs via recursion
1278 *createOnly: only create in database, do not store or return the objects (useful for perf testing)
1279 *ONLY USE FOR TESTING
1281 static function createTestObject(
1287 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1288 // so we re-set here in case
1289 $config = CRM_Core_Config
::singleton();
1290 $config->backtrace
= TRUE;
1292 static $counter = 0;
1293 CRM_Core_DAO
::$_testEntitiesToSkip = array(
1294 'CRM_Core_DAO_Worldregion',
1295 'CRM_Core_DAO_StateProvince',
1296 'CRM_Core_DAO_Country',
1297 'CRM_Core_DAO_Domain',
1300 for ($i = 0; $i < $numObjects; ++
$i) {
1303 $object = new $daoName();
1305 $fields = &$object->fields();
1306 foreach ($fields as $name => $value) {
1307 $dbName = $value['name'];
1308 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1309 //coming up with a rule to set this is too complex let's not set it
1312 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1313 $required = CRM_Utils_Array
::value('required', $value);
1314 if (CRM_Utils_Array
::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1315 $object->$dbName = $params[$dbName];
1318 elseif ($dbName != 'id') {
1319 if ($FKClassName != NULL) {
1320 //skip the FK if it is not required
1321 // if it's contact id we should create even if not required
1322 // we'll have a go @ fetching first though
1323 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
1324 if($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
1327 if (!$required && $dbName != 'contact_id') {
1328 $fkDAO = new $FKClassName;
1329 if($fkDAO->find(TRUE)){
1330 $object->$dbName = $fkDAO->id
;
1335 if(in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)){
1336 $depObject = new $FKClassName();
1337 $depObject->find(TRUE);
1338 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1339 // FIXME: the fields() metadata is not specific enough
1340 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1342 //if it is required we need to generate the dependency object first
1343 $depObject = CRM_Core_DAO
::createTestObject($FKClassName, CRM_Utils_Array
::value($dbName, $params, 1));
1345 $object->$dbName = $depObject->id
;
1350 // Pick an option value if needed
1351 if ($value['type'] !== CRM_Utils_Type
::T_BOOLEAN
) {
1352 $options = $daoName::buildOptions($dbName, 'create');
1354 $object->$dbName = key($options);
1359 switch ($value['type']) {
1360 case CRM_Utils_Type
::T_INT
:
1361 case CRM_Utils_Type
::T_FLOAT
:
1362 case CRM_Utils_Type
::T_MONEY
:
1363 if (isset($value['precision'])) {
1364 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
1365 $object->$dbName = CRM_Utils_Number
::createTruncatedDecimal($counter, $value['precision']);
1367 $object->$dbName = $counter;
1371 case CRM_Utils_Type
::T_BOOLEAN
:
1372 if (isset($value['default'])) {
1373 $object->$dbName = $value['default'];
1375 elseif ($value['name'] == 'is_deleted' ||
$value['name'] == 'is_test') {
1376 $object->$dbName = 0;
1379 $object->$dbName = 1;
1383 case CRM_Utils_Type
::T_DATE
:
1384 case CRM_Utils_Type
::T_TIMESTAMP
:
1385 case CRM_Utils_Type
::T_DATE + CRM_Utils_Type
::T_TIME
:
1386 $object->$dbName = '19700101';
1387 if($dbName == 'end_date') {
1388 // put this in the future
1389 $object->$dbName = '20200101';
1393 case CRM_Utils_Type
::T_TIME
:
1394 CRM_Core_Error
::fatal('T_TIME shouldnt be used.');
1395 //$object->$dbName='000000';
1397 case CRM_Utils_Type
::T_CCNUM
:
1398 $object->$dbName = '4111 1111 1111 1111';
1401 case CRM_Utils_Type
::T_URL
:
1402 $object->$dbName = 'http://www.civicrm.org';
1405 case CRM_Utils_Type
::T_STRING
:
1406 case CRM_Utils_Type
::T_BLOB
:
1407 case CRM_Utils_Type
::T_MEDIUMBLOB
:
1408 case CRM_Utils_Type
::T_TEXT
:
1409 case CRM_Utils_Type
::T_LONGTEXT
:
1410 case CRM_Utils_Type
::T_EMAIL
:
1412 // WAS: if (isset($value['enumValues'])) {
1413 // TODO: see if this works with all pseudoconstants
1414 if (isset($value['pseudoconstant'], $value['pseudoconstant']['callback'])) {
1415 if (isset($value['default'])) {
1416 $object->$dbName = $value['default'];
1419 $options = CRM_Core_PseudoConstant
::get($daoName, $name);
1420 if (is_array($options)) {
1421 $object->$dbName = $options[0];
1424 $defaultValues = explode(',', $options);
1425 $object->$dbName = $defaultValues[0];
1430 $object->$dbName = $dbName . '_' . $counter;
1431 $maxlength = CRM_Utils_Array
::value('maxlength', $value);
1432 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1433 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1443 $objects[$i] = $object;
1446 else unset($object);
1454 elseif ($numObjects == 1) { return $objects[0];}
1455 else return $objects;
1459 * deletes the this object plus any dependent objects that are associated with it
1460 * ONLY USE FOR TESTING
1462 static function deleteTestObjects($daoName, $params = array(
1464 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1465 // so we re-set here in case
1466 $config = CRM_Core_Config
::singleton();
1467 $config->backtrace
= TRUE;
1469 $object = new $daoName();
1470 $object->id
= CRM_Utils_Array
::value('id', $params);
1472 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1473 if ($object->find(TRUE)) {
1475 $fields = &$object->fields();
1476 foreach ($fields as $name => $value) {
1478 $dbName = $value['name'];
1480 $FKClassName = CRM_Utils_Array
::value('FKClassName', $value);
1481 $required = CRM_Utils_Array
::value('required', $value);
1482 if ($FKClassName != NULL
1484 && !in_array($FKClassName, CRM_Core_DAO
::$_testEntitiesToSkip)
1485 && ($required ||
$dbName == 'contact_id')) {
1486 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1493 foreach ($deletions as $deletion) {
1494 CRM_Core_DAO
::deleteTestObjects($deletion[0], $deletion[1]);
1498 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1499 $tableName = $prefix . "_temp";
1501 if ($addRandomString) {
1503 $tableName .= "_" . $string;
1506 $tableName .= "_" . md5(uniqid('', TRUE));
1512 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1513 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1515 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1516 $errorScope = CRM_Core_TemporaryErrorScope
::ignoreException();
1517 $dao = new CRM_Core_DAO();
1519 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1520 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1526 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1527 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError') ||
is_a($result, 'DB_Error')) {
1529 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1534 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1535 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1537 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1544 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1545 if (PEAR
::getStaticProperty('DB_DataObject', 'lastError')) {
1553 static function debugPrint($message = NULL, $printDAO = TRUE) {
1554 CRM_Utils_System
::xMemory("{$message}: ");
1557 global $_DB_DATAOBJECT;
1559 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1560 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query
;
1562 CRM_Core_Error
::debug('_DB_DATAOBJECT', $q);
1567 * Build a list of triggers via hook and add them to (err, reconcile them
1568 * with) the database.
1570 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1571 * @param bool $force
1575 static function triggerRebuild($tableName = NULL, $force = FALSE) {
1578 $logging = new CRM_Logging_Schema
;
1579 $logging->triggerInfo($info, $tableName, $force);
1581 CRM_Core_I18n_Schema
::triggerInfo($info, $tableName);
1582 CRM_Contact_BAO_Contact
::triggerInfo($info, $tableName);
1584 CRM_Utils_Hook
::triggerInfo($info, $tableName);
1586 // drop all existing triggers on all tables
1587 $logging->dropTriggers($tableName);
1589 // now create the set of new triggers
1590 self
::createTriggers($info);
1594 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1595 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1596 * TODO: Alternative solutions might be
1597 * * Stop using functions and find another way to strip numeric characters from phones
1598 * * Give better error messages (currently a missing fn fatals with "unknown error")
1600 static function checkSqlFunctionsExist() {
1601 if (!self
::$_checkedSqlFunctionsExist) {
1602 self
::$_checkedSqlFunctionsExist = TRUE;
1603 $dao = CRM_Core_DAO
::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1604 if (!$dao->fetch()) {
1605 self
::triggerRebuild();
1611 * Wrapper function to drop triggers
1613 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1615 static function dropTriggers($tableName = NULL) {
1618 $logging = new CRM_Logging_Schema
;
1619 $logging->triggerInfo($info, $tableName);
1621 // drop all existing triggers on all tables
1622 $logging->dropTriggers($tableName);
1626 * @param $info array per hook_civicrm_triggerInfo
1627 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1629 static function createTriggers(&$info, $onlyTableName = NULL) {
1630 // Validate info array, should probably raise errors?
1631 if (is_array($info) == FALSE) {
1635 $triggers = array();
1637 // now enumerate the tables and the events and collect the same set in a different format
1638 foreach ($info as $value) {
1640 // clean the incoming data, skip malformed entries
1641 // TODO: malformed entries should raise errors or get logged.
1642 if (isset($value['table']) == FALSE ||
1643 isset($value['event']) == FALSE ||
1644 isset($value['when']) == FALSE ||
1645 isset($value['sql']) == FALSE
1650 if (is_string($value['table']) == TRUE) {
1651 $tables = array($value['table']);
1654 $tables = $value['table'];
1657 if (is_string($value['event']) == TRUE) {
1658 $events = array(strtolower($value['event']));
1661 $events = array_map('strtolower', $value['event']);
1664 $whenName = strtolower($value['when']);
1666 foreach ($tables as $tableName) {
1667 if (!isset($triggers[$tableName])) {
1668 $triggers[$tableName] = array();
1671 foreach ($events as $eventName) {
1672 $template_params = array('{tableName}', '{eventName}');
1673 $template_values = array($tableName, $eventName);
1675 $sql = str_replace($template_params,
1679 $variables = str_replace($template_params,
1681 CRM_Utils_Array
::value('variables', $value)
1684 if (!isset($triggers[$tableName][$eventName])) {
1685 $triggers[$tableName][$eventName] = array();
1688 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1689 // We're leaving out cursors, conditions, and handlers for now
1690 // they are kind of dangerous in this context anyway
1691 // better off putting them in stored procedures
1692 $triggers[$tableName][$eventName][$whenName] = array(
1693 'variables' => array(),
1699 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1702 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1707 // now spit out the sql
1708 foreach ($triggers as $tableName => $tables) {
1709 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1712 foreach ($tables as $eventName => $events) {
1713 foreach ($events as $whenName => $parts) {
1714 $varString = implode("\n", $parts['variables']);
1715 $sqlString = implode("\n", $parts['sql']);
1716 $validName = CRM_Core_DAO
::shortenSQLName($tableName, 48, TRUE);
1717 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1718 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1720 CRM_Core_DAO
::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1721 CRM_Core_DAO
::executeQuery(
1735 * Find all records which refer to this entity.
1737 * @return array of objects referencing this
1739 function findReferences() {
1740 $links = self
::getReferencesToTable(static::getTableName());
1742 $occurrences = array();
1743 foreach ($links as $refSpec) {
1744 $refColumn = $refSpec->getReferenceKey();
1745 $targetColumn = $refSpec->getTargetKey();
1746 $params = array(1 => array($this->$targetColumn, 'String'));
1749 FROM {$refSpec->getReferenceTable()}
1750 WHERE {$refColumn} = %1
1752 if ($refSpec->isGeneric()) {
1753 $params[2] = array(static::getTableName(), 'String');
1755 AND {$refSpec->getTypeColumn()} = %2
1758 $daoName = CRM_Core_DAO_AllCoreTables
::getClassForTable($refSpec->getReferenceTable());
1759 $result = self
::executeQuery($sql, $params, TRUE, $daoName);
1760 while ($result->fetch()) {
1761 $obj = new $daoName();
1762 $obj->id
= $result->id
;
1763 $occurrences[] = $obj;
1767 return $occurrences;
1771 * List all tables which have hard foreign keys to this table.
1773 * For now, this returns a description of every entity_id/entity_table
1775 * TODO: filter dynamic entity references on the $tableName, based on
1776 * schema metadata in dynamicForeignKey which enumerates a restricted
1777 * set of possible entity_table's.
1779 * @param string $tableName table referred to
1781 * @return array structure of table and column, listing every table with a
1782 * foreign key reference to $tableName, and the column where the key appears.
1784 static function getReferencesToTable($tableName) {
1785 $refsFound = array();
1786 foreach (CRM_Core_DAO_AllCoreTables
::getClasses() as $daoClassName) {
1787 $links = $daoClassName::getReferenceColumns();
1788 $daoTableName = $daoClassName::getTableName();
1790 foreach ($links as $refSpec) {
1791 if ($refSpec->getTargetTable() === $tableName
1792 or $refSpec->isGeneric()
1794 $refsFound[] = $refSpec;
1802 * Lookup the value of a MySQL global configuration variable.
1804 * @param string $name e.g. "thread_stack"
1805 * @param mixed $default
1808 public static function getGlobalSetting($name, $default = NULL) {
1809 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1810 // that has been reported to fail under MySQL 5.0 for OS X
1811 $escapedName = self
::escapeString($name);
1812 $dao = CRM_Core_DAO
::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1813 if ($dao->fetch()) {
1822 * Get options for the called BAO object's field.
1823 * This function can be overridden by each BAO to add more logic related to context.
1824 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
1826 * @param string $fieldName
1827 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1828 * @param array $props : whatever is known about this bao object
1830 * @return Array|bool
1832 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1833 // If a given bao does not override this function
1834 $baoName = get_called_class();
1835 return CRM_Core_PseudoConstant
::get($baoName, $fieldName, array(), $context);
1839 * Populate option labels for this object's fields.
1841 * @throws exception if called directly on the base class
1843 public function getOptionLabels() {
1844 $fields = $this->fields();
1845 if ($fields === NULL) {
1846 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
1848 foreach ($fields as $field) {
1849 $name = CRM_Utils_Array
::value('name', $field);
1850 if ($name && isset($this->$name)) {
1851 $label = CRM_Core_PseudoConstant
::getLabel(get_class($this), $name, $this->$name);
1852 if ($label !== FALSE) {
1853 // Append 'label' onto the field name
1854 $labelName = $name . '_label';
1855 $this->$labelName = $label;
1862 * Provides documentation and validation for the buildOptions $context param
1864 * @param String $context
1869 public static function buildOptionsContext($context = NULL) {
1871 'get' => "All options are returned, even if they are disabled. Labels are translated.",
1872 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
1873 'search' => "Searchable options are returned. Labels are translated.",
1874 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
1876 // Validation: enforce uniformity of this param
1877 if ($context !== NULL && !isset($contexts[$context])) {
1878 throw new Exception("'$context' is not a valid context for buildOptions.");
1885 * @return bool|array
1887 function getFieldSpec($fieldName) {
1888 $fields = $this->fields();
1889 $fieldKeys = $this->fieldKeys();
1891 // Support "unique names" as well as sql names
1892 $fieldKey = $fieldName;
1893 if (empty($fields[$fieldKey])) {
1894 $fieldKey = CRM_Utils_Array
::value($fieldName, $fieldKeys);
1896 // If neither worked then this field doesn't exist. Return false.
1897 if (empty($fields[$fieldKey])) {
1900 return $fields[$fieldKey];
1904 * SQL version of api function to assign filters to the DAO based on the syntax
1905 * $field => array('IN' => array(4,6,9))
1907 * $field => array('LIKE' => array('%me%))
1911 * @param $filter array filter to be applied indexed by operator
1912 * @param $type String type of field (not actually used - nor in api @todo )
1913 * @param $alias String alternative field name ('as') @todo- not actually used
1914 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
1915 * this is primarily so we can add filters @ the api level to the Query object based fields
1918 * @internal param string $fieldname name of fields
1919 * @todo a better solutution would be for the query object to apply these filters based on the
1920 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
1921 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
1922 * required to extend further & it may be the comments per above should be implemented. It may be
1923 * preferable to not double-banger the return context next refactor of this - but keeping the attention
1924 * in one place has some advantages as we try to extend this format
1926 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
1927 * depending on whether it is supported as yet
1929 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
1930 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
1931 // support for other syntaxes is discussed in ticket but being put off for now
1932 foreach ($filter as $operator => $criteria) {
1933 if (in_array($operator, self
::acceptedSQLOperators())) {
1934 switch ($operator) {
1938 if(!$returnSanitisedArray) {
1939 return (sprintf('%s %s', $fieldName, $operator));
1942 return NULL; // not yet implemented (tests required to implement)
1946 // ternary operators
1949 if (empty($criteria[0]) ||
empty($criteria[1])) {
1950 throw new Exception("invalid criteria for $operator");
1952 if(!$returnSanitisedArray) {
1953 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO
::escapeString($criteria[0]), CRM_Core_DAO
::escapeString($criteria[1])));
1956 return NULL; // not yet implemented (tests required to implement)
1963 if (empty($criteria)) {
1964 throw new Exception("invalid criteria for $operator");
1966 $escapedCriteria = array_map(array(
1970 if(!$returnSanitisedArray) {
1971 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
1973 return $escapedCriteria;
1979 if(!$returnSanitisedArray) {
1980 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO
::escapeString($criteria)));
1983 return NULL; // not yet implemented (tests required to implement)
1991 * @see http://issues.civicrm.org/jira/browse/CRM-9150
1992 * support for other syntaxes is discussed in ticket but being put off for now
1995 public static function acceptedSQLOperators() {
1996 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
2000 * SQL has a limit of 64 characters on various names:
2001 * table name, trigger name, column name ...
2003 * For custom groups and fields we generated names from user entered input
2004 * which can be longer than this length, this function helps with creating
2005 * strings that meet various criteria.
2007 * @param string $string - the string to be shortened
2008 * @param int $length - the max length of the string
2010 * @param bool $makeRandom
2014 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2015 // early return for strings that meet the requirements
2016 if (strlen($string) <= $length) {
2020 // easy return for calls that dont need a randomized uniq string
2021 if (! $makeRandom) {
2022 return substr($string, 0, $length);
2025 // the string is longer than the length and we need a uniq string
2026 // for the same tablename we need the same uniq string everytime
2027 // hence we use md5 on the string, which is not random
2028 // we'll append 8 characters to the end of the tableName
2029 $md5string = substr(md5($string), 0, 8);
2030 return substr($string, 0, $length - 8) . "_{$md5string}";
2033 function setApiFilter(&$params) {}