Merge pull request #4865 from eileenmcnaughton/my-first-factory
[civicrm-core.git] / CRM / Core / DAO.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Our base DAO class. All DAO classes should inherit from this class.
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
39
40 require_once 'CRM/Core/I18n.php';
41
42 /**
43 * Class CRM_Core_DAO
44 */
45 class CRM_Core_DAO extends DB_DataObject {
46
47 /**
48 * A null object so we can pass it as reference if / when needed
49 */
50 static $_nullObject = NULL;
51 static $_nullArray = array();
52
53 static $_dbColumnValueCache = NULL;
54 const NOT_NULL = 1, IS_NULL = 2,
55 DB_DAO_NOTNULL = 128,
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;
65
66 /*
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
69 */
70 static $_testEntitiesToSkip = array();
71 /**
72 * The factory class for this application
73 * @var object
74 */
75 static $_factory = NULL;
76
77 static $_checkedSqlFunctionsExist = FALSE;
78
79 /**
80 * Class constructor
81 *
82 * @return \CRM_Core_DAO
83 @access public
84 */
85 public function __construct() {
86 $this->initialize();
87 $this->__table = $this->getTableName();
88 }
89
90 /**
91 * Empty definition for virtual function
92 */
93 public static function getTableName() {
94 return NULL;
95 }
96
97 /**
98 * Initialize the DAO object
99 *
100 * @param string $dsn
101 * The database connection string.
102 *
103 * @return void
104 * @static
105 */
106 public static function init($dsn) {
107 $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
108 $options['database'] = $dsn;
109 if (defined('CIVICRM_DAO_DEBUG')) {
110 self::DebugLevel(CIVICRM_DAO_DEBUG);
111 }
112 }
113
114 /**
115 * @param string $fieldName
116 * @param $fieldDef
117 * @param array $params
118 *
119 */
120 protected function assignTestFK($fieldName, $fieldDef, $params) {
121 $required = CRM_Utils_Array::value('required', $fieldDef);
122 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
123 $dbName = $fieldDef['name'];
124 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
125
126 // skip the FK if it is not required
127 // if it's contact id we should create even if not required
128 // we'll have a go @ fetching first though
129 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
130 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
131 $required = TRUE;
132 }
133 if (!$required && $dbName != 'contact_id') {
134 $fkDAO = new $FKClassName;
135 if ($fkDAO->find(TRUE)) {
136 $this->$dbName = $fkDAO->id;
137 }
138 unset($fkDAO);
139 }
140
141 elseif (in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)) {
142 $depObject = new $FKClassName();
143 $depObject->find(TRUE);
144 $this->$dbName = $depObject->id;
145 unset($depObject);
146 }
147 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
148 // FIXME: the fields() metadata is not specific enough
149 $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
150 $this->$dbName = $depObject->id;
151 unset($depObject);
152 }
153 else {
154 //if it is required we need to generate the dependency object first
155 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
156 $this->$dbName = $depObject->id;
157 unset($depObject);
158 }
159 }
160
161 /**
162 * Generate and assign an arbitrary value to a field of a test object.
163 *
164 * @param string $fieldName
165 * @param array $fieldDef
166 * @param int $counter
167 * The globally-unique ID of the test object.
168 */
169 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
170 $dbName = $fieldDef['name'];
171 $daoName = get_class($this);
172 $handled = FALSE;
173
174 if (!$handled && $dbName == 'contact_sub_type') {
175 //coming up with a rule to set this is too complex let's not set it
176 $handled = TRUE;
177 }
178
179 // Pick an option value if needed
180 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type::T_BOOLEAN) {
181 $options = $daoName::buildOptions($dbName, 'create');
182 if ($options) {
183 $this->$dbName = key($options);
184 $handled = TRUE;
185 }
186 }
187
188 if (!$handled) {
189 switch ($fieldDef['type']) {
190 case CRM_Utils_Type::T_INT:
191 case CRM_Utils_Type::T_FLOAT:
192 case CRM_Utils_Type::T_MONEY:
193 if (isset($fieldDef['precision'])) {
194 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
195 $this->$dbName = CRM_Utils_Number::createTruncatedDecimal($counter, $fieldDef['precision']);
196 }
197 else {
198 $this->$dbName = $counter;
199 }
200 break;
201
202 case CRM_Utils_Type::T_BOOLEAN:
203 if (isset($fieldDef['default'])) {
204 $this->$dbName = $fieldDef['default'];
205 }
206 elseif ($fieldDef['name'] == 'is_deleted' || $fieldDef['name'] == 'is_test') {
207 $this->$dbName = 0;
208 }
209 else {
210 $this->$dbName = 1;
211 }
212 break;
213
214 case CRM_Utils_Type::T_DATE:
215 case CRM_Utils_Type::T_TIMESTAMP:
216 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
217 $this->$dbName = '19700101';
218 if ($dbName == 'end_date') {
219 // put this in the future
220 $this->$dbName = '20200101';
221 }
222 break;
223
224 case CRM_Utils_Type::T_TIME:
225 CRM_Core_Error::fatal('T_TIME shouldnt be used.');
226 //$object->$dbName='000000';
227 //break;
228 case CRM_Utils_Type::T_CCNUM:
229 $this->$dbName = '4111 1111 1111 1111';
230 break;
231
232 case CRM_Utils_Type::T_URL:
233 $this->$dbName = 'http://www.civicrm.org';
234 break;
235
236 case CRM_Utils_Type::T_STRING:
237 case CRM_Utils_Type::T_BLOB:
238 case CRM_Utils_Type::T_MEDIUMBLOB:
239 case CRM_Utils_Type::T_TEXT:
240 case CRM_Utils_Type::T_LONGTEXT:
241 case CRM_Utils_Type::T_EMAIL:
242 default:
243 // WAS: if (isset($value['enumValues'])) {
244 // TODO: see if this works with all pseudoconstants
245 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
246 if (isset($fieldDef['default'])) {
247 $this->$dbName = $fieldDef['default'];
248 }
249 else {
250 $options = CRM_Core_PseudoConstant::get($daoName, $fieldName);
251 if (is_array($options)) {
252 $this->$dbName = $options[0];
253 }
254 else {
255 $defaultValues = explode(',', $options);
256 $this->$dbName = $defaultValues[0];
257 }
258 }
259 }
260 else {
261 $this->$dbName = $dbName . '_' . $counter;
262 $maxlength = CRM_Utils_Array::value('maxlength', $fieldDef);
263 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
264 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
265 }
266 }
267 }
268 }
269 }
270
271 /**
272 * Reset the DAO object. DAO is kinda crappy in that there is an unwritten
273 * rule of one query per DAO. We attempt to get around this crappy restricrion
274 * by resetting some of DAO's internal fields. Use this with caution
275 *
276 * @return void
277 *
278 */
279 public function reset() {
280
281 foreach (array_keys($this->table()) as $field) {
282 unset($this->$field);
283 }
284
285 /**
286 * reset the various DB_DAO structures manually
287 */
288 $this->_query = array();
289 $this->whereAdd();
290 $this->selectAdd();
291 $this->joinAdd();
292 }
293
294 /**
295 * @param string $tableName
296 *
297 * @return string
298 */
299 public static function getLocaleTableName($tableName) {
300 global $dbLocale;
301 if ($dbLocale) {
302 $tables = CRM_Core_I18n_Schema::schemaStructureTables();
303 if (in_array($tableName, $tables)) {
304 return $tableName . $dbLocale;
305 }
306 }
307 return $tableName;
308 }
309
310 /**
311 * Execute a query by the current DAO, localizing it along the way (if needed).
312 *
313 * @param string $query
314 * The SQL query for execution.
315 * @param bool $i18nRewrite
316 * Whether to rewrite the query.
317 *
318 * @return object the current DAO object after the query execution
319 */
320 public function query($query, $i18nRewrite = TRUE) {
321 // rewrite queries that should use $dbLocale-based views for multi-language installs
322 global $dbLocale;
323 if ($i18nRewrite and $dbLocale) {
324 $query = CRM_Core_I18n_Schema::rewriteQuery($query);
325 }
326
327 return parent::query($query);
328 }
329
330 /**
331 * Static function to set the factory instance for this class.
332 *
333 * @param object $factory
334 * The factory application object.
335 *
336 * @return void
337 * @static
338 */
339 public static function setFactory(&$factory) {
340 self::$_factory = &$factory;
341 }
342
343 /**
344 * Factory method to instantiate a new object from a table name.
345 *
346 * @param string $table
347 *
348 * @return void
349 */
350 public function factory($table = '') {
351 if (!isset(self::$_factory)) {
352 return parent::factory($table);
353 }
354
355 return self::$_factory->create($table);
356 }
357
358 /**
359 * Initialization for all DAO objects. Since we access DB_DO programatically
360 * we need to set the links manually.
361 *
362 * @return void
363 */
364 public function initialize() {
365 $this->_connect();
366 $this->query("SET NAMES utf8");
367 }
368
369 /**
370 * Defines the default key as 'id'.
371 *
372 *
373 * @return array
374 */
375 public function keys() {
376 static $keys;
377 if (!isset($keys)) {
378 $keys = array('id');
379 }
380 return $keys;
381 }
382
383 /**
384 * Tells DB_DataObject which keys use autoincrement.
385 * 'id' is autoincrementing by default.
386 *
387 *
388 * @return array
389 */
390 public function sequenceKey() {
391 static $sequenceKeys;
392 if (!isset($sequenceKeys)) {
393 $sequenceKeys = array('id', TRUE);
394 }
395 return $sequenceKeys;
396 }
397
398 /**
399 * Returns list of FK relationships
400 *
401 * @static
402 *
403 * @return array of CRM_Core_Reference_Interface
404 */
405 public static function getReferenceColumns() {
406 return array();
407 }
408
409 /**
410 * Returns all the column names of this table
411 *
412 *
413 * @return array
414 */
415 static function &fields() {
416 $result = NULL;
417 return $result;
418 }
419
420 /**
421 * Get/set an associative array of table columns
422 *
423 * @param array key=>type array
424 * @return array (associative)
425 */
426 public function table() {
427 $fields = &$this->fields();
428
429 $table = array();
430 if ($fields) {
431 foreach ($fields as $name => $value) {
432 $table[$value['name']] = $value['type'];
433 if (!empty($value['required'])) {
434 $table[$value['name']] += self::DB_DAO_NOTNULL;
435 }
436 }
437 }
438
439 return $table;
440 }
441
442 /**
443 * @return $this
444 */
445 public function save() {
446 if (!empty($this->id)) {
447 $this->update();
448
449 $event = new \Civi\Core\DAO\Event\PostUpdate($this);
450 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
451 }
452 else {
453 $this->insert();
454
455 $event = new \Civi\Core\DAO\Event\PostUpdate($this);
456 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
457 }
458 $this->free();
459
460 CRM_Utils_Hook::postSave($this);
461
462 return $this;
463 }
464
465 public function delete($useWhere = FALSE) {
466 $result = parent::delete($useWhere);
467
468 $event = new \Civi\Core\DAO\Event\PostDelete($this, $result);
469 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
470
471 return $result;
472 }
473
474 /**
475 * @param bool $created
476 */
477 public function log($created = FALSE) {
478 static $cid = NULL;
479
480 if (!$this->getLog()) {
481 return;
482 }
483
484 if (!$cid) {
485 $session = CRM_Core_Session::singleton();
486 $cid = $session->get('userID');
487 }
488
489 // return is we dont have handle to FK
490 if (!$cid) {
491 return;
492 }
493
494 $dao = new CRM_Core_DAO_Log();
495 $dao->entity_table = $this->getTableName();
496 $dao->entity_id = $this->id;
497 $dao->modified_id = $cid;
498 $dao->modified_date = date("YmdHis");
499 $dao->insert();
500 }
501
502 /**
503 * Given an associative array of name/value pairs, extract all the values
504 * that belong to this object and initialize the object with said values
505 *
506 * @param array $params
507 * (reference ) associative array of name/value pairs.
508 *
509 * @return boolean did we copy all null values into the object
510 */
511 public function copyValues(&$params) {
512 $fields = &$this->fields();
513 $allNull = TRUE;
514 foreach ($fields as $name => $value) {
515 $dbName = $value['name'];
516 if (array_key_exists($dbName, $params)) {
517 $pValue = $params[$dbName];
518 $exists = TRUE;
519 }
520 elseif (array_key_exists($name, $params)) {
521 $pValue = $params[$name];
522 $exists = TRUE;
523 }
524 else {
525 $exists = FALSE;
526 }
527
528 // if there is no value then make the variable NULL
529 if ($exists) {
530 if ($pValue === '') {
531 $this->$dbName = 'null';
532 }
533 else {
534 $this->$dbName = $pValue;
535 $allNull = FALSE;
536 }
537 }
538 }
539 return $allNull;
540 }
541
542 /**
543 * Store all the values from this object in an associative array
544 * this is a destructive store, calling function is responsible
545 * for keeping sanity of id's.
546 *
547 * @param object $object
548 * The object that we are extracting data from.
549 * @param array $values
550 * (reference ) associative array of name/value pairs.
551 *
552 * @return void
553 * @static
554 */
555 public static function storeValues(&$object, &$values) {
556 $fields = &$object->fields();
557 foreach ($fields as $name => $value) {
558 $dbName = $value['name'];
559 if (isset($object->$dbName) && $object->$dbName !== 'null') {
560 $values[$dbName] = $object->$dbName;
561 if ($name != $dbName) {
562 $values[$name] = $object->$dbName;
563 }
564 }
565 }
566 }
567
568 /**
569 * Create an attribute for this specific field. We only do this for strings and text
570 *
571 * @param array $field
572 * The field under task.
573 *
574 * @return array|null the attributes for the object
575 * @static
576 */
577 public static function makeAttribute($field) {
578 if ($field) {
579 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
580 $maxLength = CRM_Utils_Array::value('maxlength', $field);
581 $size = CRM_Utils_Array::value('size', $field);
582 if ($maxLength || $size) {
583 $attributes = array();
584 if ($maxLength) {
585 $attributes['maxlength'] = $maxLength;
586 }
587 if ($size) {
588 $attributes['size'] = $size;
589 }
590 return $attributes;
591 }
592 }
593 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) {
594 $rows = CRM_Utils_Array::value('rows', $field);
595 if (!isset($rows)) {
596 $rows = 2;
597 }
598 $cols = CRM_Utils_Array::value('cols', $field);
599 if (!isset($cols)) {
600 $cols = 80;
601 }
602
603 $attributes = array();
604 $attributes['rows'] = $rows;
605 $attributes['cols'] = $cols;
606 return $attributes;
607 }
608 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_INT || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_FLOAT || CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_MONEY) {
609 $attributes['size'] = 6;
610 $attributes['maxlength'] = 14;
611 return $attributes;
612 }
613 }
614 return NULL;
615 }
616
617 /**
618 * Get the size and maxLength attributes for this text field
619 * (or for all text fields) in the DAO object.
620 *
621 * @param string $class
622 * Name of DAO class.
623 * @param string $fieldName
624 * Field that i'm interested in or null if.
625 * you want the attributes for all DAO text fields
626 *
627 * @return array assoc array of name => attribute pairs
628 * @static
629 */
630 public static function getAttribute($class, $fieldName = NULL) {
631 $object = new $class( );
632 $fields = &$object->fields();
633 if ($fieldName != NULL) {
634 $field = CRM_Utils_Array::value($fieldName, $fields);
635 return self::makeAttribute($field);
636 }
637 else {
638 $attributes = array();
639 foreach ($fields as $name => $field) {
640 $attribute = self::makeAttribute($field);
641 if ($attribute) {
642 $attributes[$name] = $attribute;
643 }
644 }
645
646 if (!empty($attributes)) {
647 return $attributes;
648 }
649 }
650 return NULL;
651 }
652
653 /**
654 * @param $type
655 *
656 * @throws Exception
657 */
658 public static function transaction($type) {
659 CRM_Core_Error::fatal('This function is obsolete, please use CRM_Core_Transaction');
660 }
661
662 /**
663 * Check if there is a record with the same name in the db
664 *
665 * @param string $value
666 * The value of the field we are checking.
667 * @param string $daoName
668 * The dao object name.
669 * @param string $daoID
670 * The id of the object being updated. u can change your name.
671 * as long as there is no conflict
672 * @param string $fieldName
673 * The name of the field in the DAO.
674 *
675 * @return boolean true if object exists
676 * @static
677 */
678 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
679 $object = new $daoName( );
680 $object->$fieldName = $value;
681
682 $config = CRM_Core_Config::singleton();
683
684 if ($object->find(TRUE)) {
685 return ($daoID && $object->id == $daoID) ? TRUE : FALSE;
686 }
687 else {
688 return TRUE;
689 }
690 }
691
692 /**
693 * Check if there is a given column in a specific table
694 *
695 * @param string $tableName
696 * @param string $columnName
697 * @param bool $i18nRewrite
698 * Whether to rewrite the query on multilingual setups.
699 *
700 * @return boolean true if exists, else false
701 * @static
702 */
703 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
704 $query = "
705 SHOW COLUMNS
706 FROM $tableName
707 LIKE %1
708 ";
709 $params = array(1 => array($columnName, 'String'));
710 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
711 $result = $dao->fetch() ? TRUE : FALSE;
712 $dao->free();
713 return $result;
714 }
715
716 /**
717 * Returns the storage engine used by given table-name(optional).
718 * Otherwise scans all the tables and return an array of all the
719 * distinct storage engines being used.
720 *
721 * @param string $tableName
722 *
723 * @param int $maxTablesToCheck
724 * @param string $fieldName
725 *
726 * @return array
727 * @static
728 */
729 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
730 $values = array();
731 $query = "SHOW TABLE STATUS LIKE %1";
732
733 $params = array();
734
735 if (isset($tableName)) {
736 $params = array(1 => array($tableName, 'String'));
737 }
738 else {
739 $params = array(1 => array('civicrm_%', 'String'));
740 }
741
742 $dao = CRM_Core_DAO::executeQuery($query, $params);
743
744 $count = 0;
745 while ($dao->fetch()) {
746 if (isset($values[$dao->$fieldName]) ||
747 // ignore import and other temp tables
748 strpos($dao->Name, 'civicrm_import_job_') !== FALSE ||
749 strpos($dao->Name, '_temp') !== FALSE
750 ) {
751 continue;
752 }
753 $values[$dao->$fieldName] = 1;
754 $count++;
755 if ($maxTablesToCheck &&
756 $count >= $maxTablesToCheck
757 ) {
758 break;
759 }
760 }
761 $dao->free();
762 return $values;
763 }
764
765 /**
766 * @param int $maxTablesToCheck
767 *
768 * @return bool
769 */
770 public static function isDBMyISAM($maxTablesToCheck = 10) {
771 // show error if any of the tables, use 'MyISAM' storage engine.
772 $engines = self::getStorageValues(NULL, $maxTablesToCheck);
773 if (array_key_exists('MyISAM', $engines)) {
774 return TRUE;
775 }
776 return FALSE;
777 }
778
779 /**
780 * Checks if a constraint exists for a specified table.
781 *
782 * @param string $tableName
783 * @param string $constraint
784 *
785 * @return boolean true if constraint exists, false otherwise
786 * @static
787 */
788 public static function checkConstraintExists($tableName, $constraint) {
789 static $show = array();
790
791 if (!array_key_exists($tableName, $show)) {
792 $query = "SHOW CREATE TABLE $tableName";
793 $dao = CRM_Core_DAO::executeQuery($query);
794
795 if (!$dao->fetch()) {
796 CRM_Core_Error::fatal();
797 }
798
799 $dao->free();
800 $show[$tableName] = $dao->Create_Table;
801 }
802
803 return preg_match("/\b$constraint\b/i", $show[$tableName]) ? TRUE : FALSE;
804 }
805
806 /**
807 * Checks if CONSTRAINT keyword exists for a specified table.
808 *
809 * @param array $tables
810 *
811 * @throws Exception
812 *
813 * @return boolean true if CONSTRAINT keyword exists, false otherwise
814 */
815 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
816 $show = array();
817 foreach ($tables as $tableName) {
818 if (!array_key_exists($tableName, $show)) {
819 $query = "SHOW CREATE TABLE $tableName";
820 $dao = CRM_Core_DAO::executeQuery($query);
821
822 if (!$dao->fetch()) {
823 CRM_Core_Error::fatal();
824 }
825
826 $dao->free();
827 $show[$tableName] = $dao->Create_Table;
828 }
829
830 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ? TRUE : FALSE;
831 if ($result == TRUE) {
832 continue;
833 }
834 else {
835 return FALSE;
836 }
837 }
838 return TRUE;
839 }
840
841 /**
842 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
843 * for a specified column of a table.
844 *
845 * @param string $tableName
846 * @param string $columnName
847 *
848 * @return boolean true if in format, false otherwise
849 * @static
850 */
851 public static function checkFKConstraintInFormat($tableName, $columnName) {
852 static $show = array();
853
854 if (!array_key_exists($tableName, $show)) {
855 $query = "SHOW CREATE TABLE $tableName";
856 $dao = CRM_Core_DAO::executeQuery($query);
857
858 if (!$dao->fetch()) {
859 CRM_Core_Error::fatal();
860 }
861
862 $dao->free();
863 $show[$tableName] = $dao->Create_Table;
864 }
865 $constraint = "`FK_{$tableName}_{$columnName}`";
866 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
867 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ? TRUE : FALSE;
868 }
869
870 /**
871 * Check whether a specific column in a specific table has always the same value
872 *
873 * @param string $tableName
874 * @param string $columnName
875 * @param string $columnValue
876 *
877 * @return boolean true if the value is always $columnValue, false otherwise
878 * @static
879 */
880 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
881 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
882 $dao = CRM_Core_DAO::executeQuery($query);
883 $result = $dao->fetch() ? FALSE : TRUE;
884 $dao->free();
885 return $result;
886 }
887
888 /**
889 * Check whether a specific column in a specific table is always NULL
890 *
891 * @param string $tableName
892 * @param string $columnName
893 *
894 * @return boolean true if if the value is always NULL, false otherwise
895 * @static
896 */
897 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
898 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
899 $dao = CRM_Core_DAO::executeQuery($query);
900 $result = $dao->fetch() ? FALSE : TRUE;
901 $dao->free();
902 return $result;
903 }
904
905 /**
906 * Check if there is a given table in the database
907 *
908 * @param string $tableName
909 *
910 * @return boolean true if exists, else false
911 * @static
912 */
913 public static function checkTableExists($tableName) {
914 $query = "
915 SHOW TABLES
916 LIKE %1
917 ";
918 $params = array(1 => array($tableName, 'String'));
919
920 $dao = CRM_Core_DAO::executeQuery($query, $params);
921 $result = $dao->fetch() ? TRUE : FALSE;
922 $dao->free();
923 return $result;
924 }
925
926 /**
927 * @param $version
928 *
929 * @return bool
930 */
931 public function checkVersion($version) {
932 $query = "
933 SELECT version
934 FROM civicrm_domain
935 ";
936 $dbVersion = CRM_Core_DAO::singleValueQuery($query);
937 return trim($version) == trim($dbVersion) ? TRUE : FALSE;
938 }
939
940 /**
941 * Find a DAO object for the given ID and return it.
942 *
943 * @param int $id
944 * Id of the DAO object being searched for.
945 *
946 * @return object Object of the type of the class that called this function.
947 */
948 public static function findById($id) {
949 $object = new static();
950 $object->id = $id;
951 if (!$object->find(TRUE)) {
952 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
953 }
954 return $object;
955 }
956
957 /**
958 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
959 *
960 * @param string $daoName
961 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
962 * @param int $searchValue
963 * Value of the column you want to search by.
964 * @param string $returnColumn
965 * Name of the column you want to GET the value of.
966 * @param string $searchColumn
967 * Name of the column you want to search by.
968 * @param bool $force
969 * Skip use of the cache.
970 *
971 * @return string|null Value of $returnColumn in the retrieved record
972 * @static
973 */
974 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
975 if (
976 empty($searchValue) ||
977 trim(strtolower($searchValue)) == 'null'
978 ) {
979 // adding this year since developers forget to check for an id
980 // or for the 'null' (which is a bad DAO kludge)
981 // and hence we get the first value in the db
982 CRM_Core_Error::fatal();
983 }
984
985 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
986 if (self::$_dbColumnValueCache === NULL) {
987 self::$_dbColumnValueCache = array();
988 }
989
990 if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
991 $object = new $daoName( );
992 $object->$searchColumn = $searchValue;
993 $object->selectAdd();
994 $object->selectAdd($returnColumn);
995
996 $result = NULL;
997 if ($object->find(TRUE)) {
998 $result = $object->$returnColumn;
999 }
1000 $object->free();
1001
1002 self::$_dbColumnValueCache[$cacheKey] = $result;
1003 }
1004 return self::$_dbColumnValueCache[$cacheKey];
1005 }
1006
1007 /**
1008 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1009 *
1010 * @param string $daoName
1011 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1012 * @param int $searchValue
1013 * Value of the column you want to search by.
1014 * @param string $setColumn
1015 * Name of the column you want to SET the value of.
1016 * @param string $setValue
1017 * SET the setColumn to this value.
1018 * @param string $searchColumn
1019 * Name of the column you want to search by.
1020 *
1021 * @return boolean true if we found and updated the object, else false
1022 * @static
1023 */
1024 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1025 $object = new $daoName( );
1026 $object->selectAdd();
1027 $object->selectAdd("$searchColumn, $setColumn");
1028 $object->$searchColumn = $searchValue;
1029 $result = FALSE;
1030 if ($object->find(TRUE)) {
1031 $object->$setColumn = $setValue;
1032 if ($object->save()) {
1033 $result = TRUE;
1034 }
1035 }
1036 $object->free();
1037 return $result;
1038 }
1039
1040 /**
1041 * Get sort string
1042 *
1043 * @param array|object $sort either array or CRM_Utils_Sort
1044 * @param string $default
1045 * Default sort value.
1046 *
1047 * @return string - sortString
1048 * @static
1049 */
1050 public static function getSortString($sort, $default = NULL) {
1051 // check if sort is of type CRM_Utils_Sort
1052 if (is_a($sort, 'CRM_Utils_Sort')) {
1053 return $sort->orderBy();
1054 }
1055
1056 // is it an array specified as $field => $sortDirection ?
1057 if ($sort) {
1058 foreach ($sort as $k => $v) {
1059 $sortString .= "$k $v,";
1060 }
1061 return rtrim($sortString, ',');
1062 }
1063 return $default;
1064 }
1065
1066 /**
1067 * Fetch object based on array of properties
1068 *
1069 * @param string $daoName
1070 * Name of the dao object.
1071 * @param array $params
1072 * (reference ) an assoc array of name/value pairs.
1073 * @param array $defaults
1074 * (reference ) an assoc array to hold the flattened values.
1075 * @param array $returnProperities
1076 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1077 *
1078 * @return object an object of type referenced by daoName
1079 * @static
1080 */
1081 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1082 $object = new $daoName( );
1083 $object->copyValues($params);
1084
1085 // return only specific fields if returnproperties are sent
1086 if (!empty($returnProperities)) {
1087 $object->selectAdd();
1088 $object->selectAdd(implode(',', $returnProperities));
1089 }
1090
1091 if ($object->find(TRUE)) {
1092 self::storeValues($object, $defaults);
1093 return $object;
1094 }
1095 return NULL;
1096 }
1097
1098 /**
1099 * Delete the object records that are associated with this contact
1100 *
1101 * @param string $daoName
1102 * Name of the dao object.
1103 * @param int $contactId
1104 * Id of the contact to delete.
1105 *
1106 * @return void
1107 * @static
1108 */
1109 public static function deleteEntityContact($daoName, $contactId) {
1110 $object = new $daoName( );
1111
1112 $object->entity_table = 'civicrm_contact';
1113 $object->entity_id = $contactId;
1114 $object->delete();
1115 }
1116
1117 /**
1118 * Execute a query
1119 *
1120 * @param string $query
1121 * Query to be executed.
1122 *
1123 * @param array $params
1124 * @param bool $abort
1125 * @param null $daoName
1126 * @param bool $freeDAO
1127 * @param bool $i18nRewrite
1128 * @param bool $trapException
1129 *
1130 * @return CRM_Core_DAO object that holds the results of the query
1131 * @static
1132 */
1133 static function &executeQuery(
1134 $query,
1135 $params = array(),
1136 $abort = TRUE,
1137 $daoName = NULL,
1138 $freeDAO = FALSE,
1139 $i18nRewrite = TRUE,
1140 $trapException = FALSE
1141 ) {
1142 $queryStr = self::composeQuery($query, $params, $abort);
1143
1144 if (!$daoName) {
1145 $dao = new CRM_Core_DAO();
1146 }
1147 else {
1148 $dao = new $daoName( );
1149 }
1150
1151 if ($trapException) {
1152 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
1153 }
1154
1155 $result = $dao->query($queryStr, $i18nRewrite);
1156
1157 if (is_a($result, 'DB_Error')) {
1158 return $result;
1159 }
1160
1161 if ($freeDAO ||
1162 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
1163 ) {
1164 // we typically do this for insert/update/delete stataments OR if explicitly asked to
1165 // free the dao
1166 $dao->free();
1167 }
1168 return $dao;
1169 }
1170
1171 /**
1172 * Execute a query and get the single result
1173 *
1174 * @param string $query
1175 * Query to be executed.
1176 * @param array $params
1177 * @param bool $abort
1178 * @param bool $i18nRewrite
1179 * @return string|null the result of the query if any
1180 *
1181 * @static
1182 */
1183 static function &singleValueQuery(
1184 $query,
1185 $params = array(),
1186 $abort = TRUE,
1187 $i18nRewrite = TRUE
1188 ) {
1189 $queryStr = self::composeQuery($query, $params, $abort);
1190
1191 static $_dao = NULL;
1192
1193 if (!$_dao) {
1194 $_dao = new CRM_Core_DAO();
1195 }
1196
1197 $_dao->query($queryStr, $i18nRewrite);
1198
1199 $result = $_dao->getDatabaseResult();
1200 $ret = NULL;
1201 if ($result) {
1202 $row = $result->fetchRow();
1203 if ($row) {
1204 $ret = $row[0];
1205 }
1206 }
1207 $_dao->free();
1208 return $ret;
1209 }
1210
1211 /**
1212 * @param $query
1213 * @param array $params
1214 * @param bool $abort
1215 *
1216 * @return string
1217 * @throws Exception
1218 */
1219 public static function composeQuery($query, &$params, $abort = TRUE) {
1220 $tr = array();
1221 foreach ($params as $key => $item) {
1222 if (is_numeric($key)) {
1223 if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) {
1224 $item[0] = self::escapeString($item[0]);
1225 if ($item[1] == 'String' ||
1226 $item[1] == 'Memo' ||
1227 $item[1] == 'Link'
1228 ) {
1229 // Support class constants stipulating wildcard characters and/or
1230 // non-quoting of strings. Also support legacy code which may be
1231 // passing in TRUE or 1 for $item[2], which used to indicate the
1232 // use of wildcard characters.
1233 if (!empty($item[2])) {
1234 if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) {
1235 $item[0] = "'%{$item[0]}%'";
1236 }
1237 elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) {
1238 $item[0] = "'{$item[0]}'";
1239 }
1240 }
1241 else {
1242 $item[0] = "'{$item[0]}'";
1243 }
1244 }
1245
1246 if (($item[1] == 'Date' || $item[1] == 'Timestamp') &&
1247 strlen($item[0]) == 0
1248 ) {
1249 $item[0] = 'null';
1250 }
1251
1252 $tr['%' . $key] = $item[0];
1253 }
1254 elseif ($abort) {
1255 CRM_Core_Error::fatal("{$item[0]} is not of type {$item[1]}");
1256 }
1257 }
1258 }
1259
1260 return strtr($query, $tr);
1261 }
1262
1263 /**
1264 * @param null $ids
1265 */
1266 public static function freeResult($ids = NULL) {
1267 global $_DB_DATAOBJECT;
1268
1269 if (!$ids) {
1270 if (!$_DB_DATAOBJECT ||
1271 !isset($_DB_DATAOBJECT['RESULTS'])
1272 ) {
1273 return;
1274 }
1275 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1276 }
1277
1278 foreach ($ids as $id) {
1279 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1280 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result)) {
1281 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result);
1282 }
1283 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1284 }
1285
1286 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1287 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1288 }
1289 }
1290 }
1291
1292 /**
1293 * This function is to make a shallow copy of an object
1294 * and all the fields in the object
1295 *
1296 * @param string $daoName
1297 * Name of the dao.
1298 * @param array $criteria
1299 * Array of all the fields & values.
1300 * on which basis to copy
1301 * @param array $newData
1302 * Array of all the fields & values.
1303 * to be copied besides the other fields
1304 * @param string $fieldsFix
1305 * Array of fields that you want to prefix/suffix/replace.
1306 * @param string $blockCopyOfDependencies
1307 * Fields that you want to block from.
1308 * getting copied
1309 *
1310 *
1311 * @return (reference ) the newly created copy of the object
1312 */
1313 static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1314 $object = new $daoName( );
1315 if (!$newData) {
1316 $object->id = $criteria['id'];
1317 }
1318 else {
1319 foreach ($criteria as $key => $value) {
1320 $object->$key = $value;
1321 }
1322 }
1323
1324 $object->find();
1325 while ($object->fetch()) {
1326
1327 // all the objects except with $blockCopyOfDependencies set
1328 // be copied - addresses #CRM-1962
1329
1330 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1331 break;
1332 }
1333
1334 $newObject = new $daoName( );
1335
1336 $fields = &$object->fields();
1337 if (!is_array($fieldsFix)) {
1338 $fieldsToPrefix = array();
1339 $fieldsToSuffix = array();
1340 $fieldsToReplace = array();
1341 }
1342 if (!empty($fieldsFix['prefix'])) {
1343 $fieldsToPrefix = $fieldsFix['prefix'];
1344 }
1345 if (!empty($fieldsFix['suffix'])) {
1346 $fieldsToSuffix = $fieldsFix['suffix'];
1347 }
1348 if (!empty($fieldsFix['replace'])) {
1349 $fieldsToReplace = $fieldsFix['replace'];
1350 }
1351
1352 foreach ($fields as $name => $value) {
1353 if ($name == 'id' || $value['name'] == 'id') {
1354 // copy everything but the id!
1355 continue;
1356 }
1357
1358 $dbName = $value['name'];
1359 $type = CRM_Utils_Type::typeToString($value['type']);
1360 $newObject->$dbName = $object->$dbName;
1361 if (isset($fieldsToPrefix[$dbName])) {
1362 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1363 }
1364 if (isset($fieldsToSuffix[$dbName])) {
1365 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1366 }
1367 if (isset($fieldsToReplace[$dbName])) {
1368 $newObject->$dbName = $fieldsToReplace[$dbName];
1369 }
1370
1371 if ($type == 'Timestamp' || $type == 'Date') {
1372 $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName);
1373 }
1374
1375 if ($newData) {
1376 foreach ($newData as $k => $v) {
1377 $newObject->$k = $v;
1378 }
1379 }
1380 }
1381 $newObject->save();
1382 }
1383 return $newObject;
1384 }
1385
1386 public static function cascadeUpdate($daoName, $fromId, $toId, $newData = array()) {
1387 $object = new $daoName( );
1388 $object->id = $fromId;
1389
1390 if ($object->find(TRUE)) {
1391 $newObject = new $daoName( );
1392 $newObject->id = $toId;
1393
1394 if ($newObject->find(TRUE)) {
1395 $fields = &$object->fields();
1396 foreach ($fields as $name => $value) {
1397 if ($name == 'id' || $value['name'] == 'id') {
1398 // copy everything but the id!
1399 continue;
1400 }
1401
1402 $colName = $value['name'];
1403 $newObject->$colName = $object->$colName;
1404
1405 if (substr($name, -5) == '_date' ||
1406 substr($name, -10) == '_date_time'
1407 ) {
1408 $newObject->$colName = CRM_Utils_Date::isoToMysql($newObject->$colName);
1409 }
1410 }
1411 foreach ($newData as $k => $v) {
1412 $newObject->$k = $v;
1413 }
1414 $newObject->save();
1415 return $newObject;
1416 }
1417 }
1418 return CRM_Core_DAO::$_nullObject;
1419 }
1420
1421 /**
1422 * Given the component id, compute the contact id
1423 * since its used for things like send email
1424 *
1425 * @param $componentIDs
1426 * @param string $tableName
1427 *
1428 * @return array
1429 */
1430 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1431 $contactIDs = array();
1432
1433 if (empty($componentIDs)) {
1434 return $contactIDs;
1435 }
1436
1437 $IDs = implode(',', $componentIDs);
1438 $query = "
1439 SELECT contact_id
1440 FROM $tableName
1441 WHERE id IN ( $IDs )
1442 ";
1443
1444 $dao = CRM_Core_DAO::executeQuery($query);
1445 while ($dao->fetch()) {
1446 $contactIDs[] = $dao->contact_id;
1447 }
1448 return $contactIDs;
1449 }
1450
1451 /**
1452 * Fetch object based on array of properties
1453 *
1454 * @param string $daoName
1455 * Name of the dao object.
1456 * @param string $fieldIdName
1457 * @param int $fieldId
1458 * @param $details
1459 * @param array $returnProperities
1460 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1461 *
1462 * @return object an object of type referenced by daoName
1463 * @static
1464 */
1465 public static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1466 require_once (str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php");
1467 $object = new $daoName( );
1468 $object->$fieldIdName = $fieldId;
1469
1470 // return only specific fields if returnproperties are sent
1471 if (!empty($returnProperities)) {
1472 $object->selectAdd();
1473 $object->selectAdd('id');
1474 $object->selectAdd(implode(',', $returnProperities));
1475 }
1476
1477 $object->find();
1478 while ($object->fetch()) {
1479 $defaults = array();
1480 self::storeValues($object, $defaults);
1481 $details[$object->id] = $defaults;
1482 }
1483
1484 return $details;
1485 }
1486
1487 public static function dropAllTables() {
1488
1489 // first drop all the custom tables we've created
1490 CRM_Core_BAO_CustomGroup::dropAllTables();
1491
1492 // drop all multilingual views
1493 CRM_Core_I18n_Schema::dropAllViews();
1494
1495 CRM_Utils_File::sourceSQLFile(CIVICRM_DSN,
1496 dirname(__FILE__) . DIRECTORY_SEPARATOR .
1497 '..' . DIRECTORY_SEPARATOR .
1498 '..' . DIRECTORY_SEPARATOR .
1499 'sql' . DIRECTORY_SEPARATOR .
1500 'civicrm_drop.mysql'
1501 );
1502 }
1503
1504 /**
1505 * @param $string
1506 *
1507 * @return string
1508 */
1509 public static function escapeString($string) {
1510 static $_dao = NULL;
1511
1512 if (!$_dao) {
1513 // If this is an atypical case (e.g. preparing .sql files
1514 // before Civi has been installed), then we fallback to
1515 // DB-less escaping helper (mysql_real_escape_string).
1516 // Note: In typical usage, escapeString() will only
1517 // check one conditional ("if !$_dao") rather than
1518 // two conditionals ("if !defined(DSN)")
1519 if (!defined('CIVICRM_DSN')) {
1520 if (function_exists('mysql_real_escape_string')) {
1521 return mysql_real_escape_string($string);
1522 }
1523 else {
1524 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1525 }
1526 }
1527
1528 $_dao = new CRM_Core_DAO();
1529 }
1530
1531 return $_dao->escape($string);
1532 }
1533
1534 /**
1535 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1536 *
1537 * @param $strings
1538 * Array.
1539 * @param $default
1540 * String the value to use if $strings has no elements.
1541 * @return string eg "abc","def","ghi"
1542 */
1543 public static function escapeStrings($strings, $default = NULL) {
1544 static $_dao = NULL;
1545 if (!$_dao) {
1546 $_dao = new CRM_Core_DAO();
1547 }
1548
1549 if (empty($strings)) {
1550 return $default;
1551 }
1552
1553 $escapes = array_map(array($_dao, 'escape'), $strings);
1554 return '"' . implode('","', $escapes) . '"';
1555 }
1556
1557 /**
1558 * @param $string
1559 *
1560 * @return string
1561 */
1562 public static function escapeWildCardString($string) {
1563 // CRM-9155
1564 // ensure we escape the single characters % and _ which are mysql wild
1565 // card characters and could come in via sortByCharacter
1566 // note that mysql does not escape these characters
1567 if ($string && in_array($string,
1568 array('%', '_', '%%', '_%')
1569 )) {
1570 return '\\' . $string;
1571 }
1572
1573 return self::escapeString($string);
1574 }
1575
1576 /**
1577 * Creates a test object, including any required objects it needs via recursion
1578 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1579 * ONLY USE FOR TESTING
1580 *
1581 * @param string $daoName
1582 * @param array $params
1583 * @param int $numObjects
1584 * @param bool $createOnly
1585 *
1586 * @return
1587 */
1588 static function createTestObject(
1589 $daoName,
1590 $params = array(),
1591 $numObjects = 1,
1592 $createOnly = FALSE
1593 ) {
1594 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1595 // so we re-set here in case
1596 $config = CRM_Core_Config::singleton();
1597 $config->backtrace = TRUE;
1598
1599 static $counter = 0;
1600 CRM_Core_DAO::$_testEntitiesToSkip = array(
1601 'CRM_Core_DAO_Worldregion',
1602 'CRM_Core_DAO_StateProvince',
1603 'CRM_Core_DAO_Country',
1604 'CRM_Core_DAO_Domain',
1605 'CRM_Financial_DAO_FinancialType'//because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1606 );
1607
1608 // Prefer to instantiate BAO's instead of DAO's (when possible)
1609 // so that assignTestValue()/assignTestFK() can be overloaded.
1610 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1611 if (class_exists($baoName)) {
1612 $daoName = $baoName;
1613 }
1614
1615 for ($i = 0; $i < $numObjects; ++$i) {
1616
1617 ++$counter;
1618 /** @var CRM_Core_DAO $object */
1619 $object = new $daoName();
1620
1621 $fields = & $object->fields();
1622 foreach ($fields as $fieldName => $fieldDef) {
1623 $dbName = $fieldDef['name'];
1624 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
1625 $required = CRM_Utils_Array::value('required', $fieldDef);
1626
1627 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1628 $object->$dbName = $params[$dbName];
1629 }
1630
1631 elseif ($dbName != 'id') {
1632 if ($FKClassName != NULL) {
1633 $object->assignTestFK($fieldName, $fieldDef, $params);
1634 continue;
1635 }
1636 else {
1637 $object->assignTestValue($fieldName, $fieldDef, $counter);
1638 }
1639 }
1640 }
1641
1642 $object->save();
1643
1644 if (!$createOnly) {
1645 $objects[$i] = $object;
1646 }
1647 else {
1648 unset($object);
1649 }
1650 }
1651
1652 if ($createOnly) {
1653 return;
1654 }
1655 elseif ($numObjects == 1) {
1656 return $objects[0];
1657 }
1658 else {
1659 return $objects;
1660 }
1661 }
1662
1663 /**
1664 * Deletes the this object plus any dependent objects that are associated with it
1665 * ONLY USE FOR TESTING
1666 *
1667 * @param string $daoName
1668 * @param array $params
1669 */
1670 public static function deleteTestObjects($daoName, $params = array()) {
1671 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1672 // so we re-set here in case
1673 $config = CRM_Core_Config::singleton();
1674 $config->backtrace = TRUE;
1675
1676 $object = new $daoName();
1677 $object->id = CRM_Utils_Array::value('id', $params);
1678
1679 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1680 if ($object->find(TRUE)) {
1681
1682 $fields = &$object->fields();
1683 foreach ($fields as $name => $value) {
1684
1685 $dbName = $value['name'];
1686
1687 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1688 $required = CRM_Utils_Array::value('required', $value);
1689 if ($FKClassName != NULL
1690 && $object->$dbName
1691 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
1692 && ($required || $dbName == 'contact_id')
1693 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1694 // to make this test process pass - line below makes pass for now
1695 && $dbName != 'member_of_contact_id') {
1696 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1697 }
1698 }
1699 }
1700
1701 $object->delete();
1702
1703 foreach ($deletions as $deletion) {
1704 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
1705 }
1706 }
1707
1708 /**
1709 * Set defaults when creating new entity
1710 * (don't call this set defaults as already in use with different signature in some places)
1711 *
1712 * @param array $params
1713 * @param $defaults
1714 */
1715 public static function setCreateDefaults(&$params, $defaults) {
1716 if (isset($params['id'])) {
1717 return;
1718 }
1719 foreach ($defaults as $key => $value) {
1720 if (!array_key_exists($key, $params) || $params[$key] === NULL) {
1721 $params[$key] = $value;
1722 }
1723 }
1724 }
1725
1726 /**
1727 * @param string $prefix
1728 * @param bool $addRandomString
1729 * @param null $string
1730 *
1731 * @return string
1732 */
1733 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1734 $tableName = $prefix . "_temp";
1735
1736 if ($addRandomString) {
1737 if ($string) {
1738 $tableName .= "_" . $string;
1739 }
1740 else {
1741 $tableName .= "_" . md5(uniqid('', TRUE));
1742 }
1743 }
1744 return $tableName;
1745 }
1746
1747 /**
1748 * @param bool $view
1749 * @param bool $trigger
1750 *
1751 * @return bool
1752 */
1753 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1754 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1755 // and logging
1756 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1757 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
1758 $dao = new CRM_Core_DAO();
1759 if ($view) {
1760 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1761 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1762 return FALSE;
1763 }
1764 }
1765
1766 if ($trigger) {
1767 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1768 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
1769 if ($view) {
1770 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1771 }
1772 return FALSE;
1773 }
1774
1775 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1776 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1777 if ($view) {
1778 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1779 }
1780 return FALSE;
1781 }
1782 }
1783
1784 if ($view) {
1785 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1786 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1787 return FALSE;
1788 }
1789 }
1790
1791 return TRUE;
1792 }
1793
1794 /**
1795 * @param null $message
1796 * @param bool $printDAO
1797 */
1798 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1799 CRM_Utils_System::xMemory("{$message}: ");
1800
1801 if ($printDAO) {
1802 global $_DB_DATAOBJECT;
1803 $q = array();
1804 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1805 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1806 }
1807 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
1808 }
1809 }
1810
1811 /**
1812 * Build a list of triggers via hook and add them to (err, reconcile them
1813 * with) the database.
1814 *
1815 * @param $tableName
1816 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1817 * @param bool $force
1818 *
1819 * @see CRM-9716
1820 */
1821 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1822 $info = array();
1823
1824 $logging = new CRM_Logging_Schema;
1825 $logging->triggerInfo($info, $tableName, $force);
1826
1827 CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
1828 CRM_Contact_BAO_Contact::triggerInfo($info, $tableName);
1829
1830 CRM_Utils_Hook::triggerInfo($info, $tableName);
1831
1832 // drop all existing triggers on all tables
1833 $logging->dropTriggers($tableName);
1834
1835 // now create the set of new triggers
1836 self::createTriggers($info, $tableName);
1837 }
1838
1839 /**
1840 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1841 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1842 * TODO: Alternative solutions might be
1843 * * Stop using functions and find another way to strip numeric characters from phones
1844 * * Give better error messages (currently a missing fn fatals with "unknown error")
1845 */
1846 public static function checkSqlFunctionsExist() {
1847 if (!self::$_checkedSqlFunctionsExist) {
1848 self::$_checkedSqlFunctionsExist = TRUE;
1849 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1850 if (!$dao->fetch()) {
1851 self::triggerRebuild();
1852 }
1853 }
1854 }
1855
1856 /**
1857 * Wrapper function to drop triggers
1858 *
1859 * @param $tableName
1860 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1861 */
1862 public static function dropTriggers($tableName = NULL) {
1863 $info = array();
1864
1865 $logging = new CRM_Logging_Schema;
1866 $logging->triggerInfo($info, $tableName);
1867
1868 // drop all existing triggers on all tables
1869 $logging->dropTriggers($tableName);
1870 }
1871
1872 /**
1873 * @param $info
1874 * Array per hook_civicrm_triggerInfo.
1875 * @param $onlyTableName
1876 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1877 */
1878 public static function createTriggers(&$info, $onlyTableName = NULL) {
1879 // Validate info array, should probably raise errors?
1880 if (is_array($info) == FALSE) {
1881 return;
1882 }
1883
1884 $triggers = array();
1885
1886 // now enumerate the tables and the events and collect the same set in a different format
1887 foreach ($info as $value) {
1888
1889 // clean the incoming data, skip malformed entries
1890 // TODO: malformed entries should raise errors or get logged.
1891 if (isset($value['table']) == FALSE ||
1892 isset($value['event']) == FALSE ||
1893 isset($value['when']) == FALSE ||
1894 isset($value['sql']) == FALSE
1895 ) {
1896 continue;
1897 }
1898
1899 if (is_string($value['table']) == TRUE) {
1900 $tables = array($value['table']);
1901 }
1902 else {
1903 $tables = $value['table'];
1904 }
1905
1906 if (is_string($value['event']) == TRUE) {
1907 $events = array(strtolower($value['event']));
1908 }
1909 else {
1910 $events = array_map('strtolower', $value['event']);
1911 }
1912
1913 $whenName = strtolower($value['when']);
1914
1915 foreach ($tables as $tableName) {
1916 if (!isset($triggers[$tableName])) {
1917 $triggers[$tableName] = array();
1918 }
1919
1920 foreach ($events as $eventName) {
1921 $template_params = array('{tableName}', '{eventName}');
1922 $template_values = array($tableName, $eventName);
1923
1924 $sql = str_replace($template_params,
1925 $template_values,
1926 $value['sql']
1927 );
1928 $variables = str_replace($template_params,
1929 $template_values,
1930 CRM_Utils_Array::value('variables', $value)
1931 );
1932
1933 if (!isset($triggers[$tableName][$eventName])) {
1934 $triggers[$tableName][$eventName] = array();
1935 }
1936
1937 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1938 // We're leaving out cursors, conditions, and handlers for now
1939 // they are kind of dangerous in this context anyway
1940 // better off putting them in stored procedures
1941 $triggers[$tableName][$eventName][$whenName] = array(
1942 'variables' => array(),
1943 'sql' => array(),
1944 );
1945 }
1946
1947 if ($variables) {
1948 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1949 }
1950
1951 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1952 }
1953 }
1954 }
1955
1956 // now spit out the sql
1957 foreach ($triggers as $tableName => $tables) {
1958 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1959 continue;
1960 }
1961 foreach ($tables as $eventName => $events) {
1962 foreach ($events as $whenName => $parts) {
1963 $varString = implode("\n", $parts['variables']);
1964 $sqlString = implode("\n", $parts['sql']);
1965 $validName = CRM_Core_DAO::shortenSQLName($tableName, 48, TRUE);
1966 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1967 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1968
1969 CRM_Core_DAO::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1970 CRM_Core_DAO::executeQuery(
1971 $triggerSQL,
1972 array(),
1973 TRUE,
1974 NULL,
1975 FALSE,
1976 FALSE
1977 );
1978 }
1979 }
1980 }
1981 }
1982
1983 /**
1984 * Given a list of fields, create a list of references.
1985 *
1986 * @param string $className
1987 * BAO/DAO class name.
1988 * @return array<CRM_Core_Reference_Interface>
1989 */
1990 public static function createReferenceColumns($className) {
1991 $result = array();
1992 $fields = $className::fields();
1993 foreach ($fields as $field) {
1994 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1995 $result[] = new CRM_Core_Reference_OptionValue(
1996 $className::getTableName(),
1997 $field['name'],
1998 'civicrm_option_value',
1999 CRM_Utils_Array::value('keyColumn', $field['pseudoconstant'], 'value'),
2000 $field['pseudoconstant']['optionGroupName']
2001 );
2002 }
2003 }
2004 return $result;
2005 }
2006
2007 /**
2008 * Find all records which refer to this entity.
2009 *
2010 * @return array of objects referencing this
2011 */
2012 public function findReferences() {
2013 $links = self::getReferencesToTable(static::getTableName());
2014
2015 $occurrences = array();
2016 foreach ($links as $refSpec) {
2017 /** @var $refSpec CRM_Core_Reference_Interface */
2018 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
2019 $result = $refSpec->findReferences($this);
2020 if ($result) {
2021 while ($result->fetch()) {
2022 $obj = new $daoName();
2023 $obj->id = $result->id;
2024 $occurrences[] = $obj;
2025 }
2026 }
2027 }
2028
2029 return $occurrences;
2030 }
2031
2032 /**
2033 * @return array each item has keys:
2034 * - name: string
2035 * - type: string
2036 * - count: int
2037 * - table: string|null SQL table name
2038 * - key: string|null SQL column name
2039 */
2040 public function getReferenceCounts() {
2041 $links = self::getReferencesToTable(static::getTableName());
2042
2043 $counts = array();
2044 foreach ($links as $refSpec) {
2045 /** @var $refSpec CRM_Core_Reference_Interface */
2046 $count = $refSpec->getReferenceCount($this);
2047 if ($count['count'] != 0) {
2048 $counts[] = $count;
2049 }
2050 }
2051
2052 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
2053 /** @var $component CRM_Core_Component_Info */
2054 $counts = array_merge($counts, $component->getReferenceCounts($this));
2055 }
2056 CRM_Utils_Hook::referenceCounts($this, $counts);
2057
2058 return $counts;
2059 }
2060
2061 /**
2062 * List all tables which have hard foreign keys to this table.
2063 *
2064 * For now, this returns a description of every entity_id/entity_table
2065 * reference.
2066 * TODO: filter dynamic entity references on the $tableName, based on
2067 * schema metadata in dynamicForeignKey which enumerates a restricted
2068 * set of possible entity_table's.
2069 *
2070 * @param string $tableName
2071 * Table referred to.
2072 *
2073 * @return array structure of table and column, listing every table with a
2074 * foreign key reference to $tableName, and the column where the key appears.
2075 */
2076 public static function getReferencesToTable($tableName) {
2077 $refsFound = array();
2078 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
2079 $links = $daoClassName::getReferenceColumns();
2080 $daoTableName = $daoClassName::getTableName();
2081
2082 foreach ($links as $refSpec) {
2083 /** @var $refSpec CRM_Core_Reference_Interface */
2084 if ($refSpec->matchesTargetTable($tableName)) {
2085 $refsFound[] = $refSpec;
2086 }
2087 }
2088 }
2089 return $refsFound;
2090 }
2091
2092 /**
2093 * Lookup the value of a MySQL global configuration variable.
2094 *
2095 * @param string $name
2096 * E.g. "thread_stack".
2097 * @param mixed $default
2098 * @return mixed
2099 */
2100 public static function getGlobalSetting($name, $default = NULL) {
2101 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2102 // that has been reported to fail under MySQL 5.0 for OS X
2103 $escapedName = self::escapeString($name);
2104 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2105 if ($dao->fetch()) {
2106 return $dao->Value;
2107 }
2108 else {
2109 return $default;
2110 }
2111 }
2112
2113 /**
2114 * Get options for the called BAO object's field.
2115 * This function can be overridden by each BAO to add more logic related to context.
2116 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2117 *
2118 * @param string $fieldName
2119 * @param string $context
2120 * : @see CRM_Core_DAO::buildOptionsContext.
2121 * @param array $props
2122 * : whatever is known about this bao object.
2123 *
2124 * @return Array|bool
2125 */
2126 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2127 // If a given bao does not override this function
2128 $baoName = get_called_class();
2129 return CRM_Core_PseudoConstant::get($baoName, $fieldName, array(), $context);
2130 }
2131
2132 /**
2133 * Populate option labels for this object's fields.
2134 *
2135 * @throws exception if called directly on the base class
2136 */
2137 public function getOptionLabels() {
2138 $fields = $this->fields();
2139 if ($fields === NULL) {
2140 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2141 }
2142 foreach ($fields as $field) {
2143 $name = CRM_Utils_Array::value('name', $field);
2144 if ($name && isset($this->$name)) {
2145 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
2146 if ($label !== FALSE) {
2147 // Append 'label' onto the field name
2148 $labelName = $name . '_label';
2149 $this->$labelName = $label;
2150 }
2151 }
2152 }
2153 }
2154
2155 /**
2156 * Provides documentation and validation for the buildOptions $context param
2157 *
2158 * @param string $context
2159 *
2160 * @throws Exception
2161 * @return array
2162 */
2163 public static function buildOptionsContext($context = NULL) {
2164 $contexts = array(
2165 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2166 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2167 'search' => "Searchable options are returned. Labels are translated.",
2168 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2169 );
2170 // Validation: enforce uniformity of this param
2171 if ($context !== NULL && !isset($contexts[$context])) {
2172 throw new Exception("'$context' is not a valid context for buildOptions.");
2173 }
2174 return $contexts;
2175 }
2176
2177 /**
2178 * @param string $fieldName
2179 * @return bool|array
2180 */
2181 public function getFieldSpec($fieldName) {
2182 $fields = $this->fields();
2183 $fieldKeys = $this->fieldKeys();
2184
2185 // Support "unique names" as well as sql names
2186 $fieldKey = $fieldName;
2187 if (empty($fields[$fieldKey])) {
2188 $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys);
2189 }
2190 // If neither worked then this field doesn't exist. Return false.
2191 if (empty($fields[$fieldKey])) {
2192 return FALSE;
2193 }
2194 return $fields[$fieldKey];
2195 }
2196
2197 /**
2198 * SQL version of api function to assign filters to the DAO based on the syntax
2199 * $field => array('IN' => array(4,6,9))
2200 * OR
2201 * $field => array('LIKE' => array('%me%))
2202 * etc
2203 *
2204 * @param string $fieldName
2205 * Name of fields.
2206 * @param $filter
2207 * Array filter to be applied indexed by operator.
2208 * @param $type
2209 * String type of field (not actually used - nor in api @todo ).
2210 * @param $alias
2211 * String alternative field name ('as') @todo- not actually used.
2212 * @param bool $returnSanitisedArray
2213 * Return a sanitised array instead of a clause.
2214 * this is primarily so we can add filters @ the api level to the Query object based fields
2215 *
2216 * @throws Exception
2217 *
2218 * @todo a better solution would be for the query object to apply these filters based on the
2219 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2220 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2221 * required to extend further & it may be the comments per above should be implemented. It may be
2222 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2223 * in one place has some advantages as we try to extend this format
2224 *
2225 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2226 * depending on whether it is supported as yet
2227 */
2228 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2229 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2230 // support for other syntaxes is discussed in ticket but being put off for now
2231 foreach ($filter as $operator => $criteria) {
2232 if (in_array($operator, self::acceptedSQLOperators())) {
2233 switch ($operator) {
2234 // unary operators
2235 case 'IS NULL':
2236 case 'IS NOT NULL':
2237 if (!$returnSanitisedArray) {
2238 return (sprintf('%s %s', $fieldName, $operator));
2239 }
2240 else {
2241 return (sprintf('%s %s ', $fieldName, $operator));
2242 }
2243 break;
2244
2245 // ternary operators
2246 case 'BETWEEN':
2247 case 'NOT BETWEEN':
2248 if (empty($criteria[0]) || empty($criteria[1])) {
2249 throw new Exception("invalid criteria for $operator");
2250 }
2251 if (!$returnSanitisedArray) {
2252 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
2253 }
2254 else {
2255 return NULL; // not yet implemented (tests required to implement)
2256 }
2257 break;
2258
2259 // n-ary operators
2260 case 'IN':
2261 case 'NOT IN':
2262 if (empty($criteria)) {
2263 throw new Exception("invalid criteria for $operator");
2264 }
2265 $escapedCriteria = array_map(array(
2266 'CRM_Core_DAO',
2267 'escapeString'
2268 ), $criteria);
2269 if (!$returnSanitisedArray) {
2270 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2271 }
2272 return $escapedCriteria;
2273 break;
2274
2275 // binary operators
2276
2277 default:
2278 if (!$returnSanitisedArray) {
2279 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
2280 }
2281 else {
2282 return NULL; // not yet implemented (tests required to implement)
2283 }
2284 }
2285 }
2286 }
2287 }
2288
2289 /**
2290 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2291 * support for other syntaxes is discussed in ticket but being put off for now
2292 * @return array
2293 */
2294 public static function acceptedSQLOperators() {
2295 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
2296 }
2297
2298 /**
2299 * SQL has a limit of 64 characters on various names:
2300 * table name, trigger name, column name ...
2301 *
2302 * For custom groups and fields we generated names from user entered input
2303 * which can be longer than this length, this function helps with creating
2304 * strings that meet various criteria.
2305 *
2306 * @param string $string
2307 * The string to be shortened.
2308 * @param int $length
2309 * The max length of the string.
2310 *
2311 * @param bool $makeRandom
2312 *
2313 * @return string
2314 */
2315 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2316 // early return for strings that meet the requirements
2317 if (strlen($string) <= $length) {
2318 return $string;
2319 }
2320
2321 // easy return for calls that dont need a randomized uniq string
2322 if (!$makeRandom) {
2323 return substr($string, 0, $length);
2324 }
2325
2326 // the string is longer than the length and we need a uniq string
2327 // for the same tablename we need the same uniq string everytime
2328 // hence we use md5 on the string, which is not random
2329 // we'll append 8 characters to the end of the tableName
2330 $md5string = substr(md5($string), 0, 8);
2331 return substr($string, 0, $length - 8) . "_{$md5string}";
2332 }
2333
2334 /**
2335 * @param array $params
2336 */
2337 public function setApiFilter(&$params) {}
2338
2339 }