CRM_Core_DAO::assignTestFK() - Fix FK checks on BAOs
[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 } else {
1523 throw new CRM_Core_Exception("Cannot generate SQL. \"mysql_real_escape_string\" is missing. Have you installed PHP \"mysql\" extension?");
1524 }
1525 }
1526
1527 $_dao = new CRM_Core_DAO();
1528 }
1529
1530 return $_dao->escape($string);
1531 }
1532
1533 /**
1534 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1535 *
1536 * @param $strings
1537 * Array.
1538 * @param $default
1539 * String the value to use if $strings has no elements.
1540 * @return string eg "abc","def","ghi"
1541 */
1542 public static function escapeStrings($strings, $default = NULL) {
1543 static $_dao = NULL;
1544 if (!$_dao) {
1545 $_dao = new CRM_Core_DAO();
1546 }
1547
1548 if (empty($strings)) {
1549 return $default;
1550 }
1551
1552 $escapes = array_map(array($_dao, 'escape'), $strings);
1553 return '"' . implode('","', $escapes) . '"';
1554 }
1555
1556 /**
1557 * @param $string
1558 *
1559 * @return string
1560 */
1561 public static function escapeWildCardString($string) {
1562 // CRM-9155
1563 // ensure we escape the single characters % and _ which are mysql wild
1564 // card characters and could come in via sortByCharacter
1565 // note that mysql does not escape these characters
1566 if ($string && in_array($string,
1567 array('%', '_', '%%', '_%')
1568 )) {
1569 return '\\' . $string;
1570 }
1571
1572 return self::escapeString($string);
1573 }
1574
1575 /**
1576 * Creates a test object, including any required objects it needs via recursion
1577 * createOnly: only create in database, do not store or return the objects (useful for perf testing)
1578 * ONLY USE FOR TESTING
1579 *
1580 * @param string $daoName
1581 * @param array $params
1582 * @param int $numObjects
1583 * @param bool $createOnly
1584 *
1585 * @return
1586 */
1587 static function createTestObject(
1588 $daoName,
1589 $params = array(),
1590 $numObjects = 1,
1591 $createOnly = FALSE
1592 ) {
1593 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1594 // so we re-set here in case
1595 $config = CRM_Core_Config::singleton();
1596 $config->backtrace = TRUE;
1597
1598 static $counter = 0;
1599 CRM_Core_DAO::$_testEntitiesToSkip = array(
1600 'CRM_Core_DAO_Worldregion',
1601 'CRM_Core_DAO_StateProvince',
1602 'CRM_Core_DAO_Country',
1603 'CRM_Core_DAO_Domain',
1604 'CRM_Financial_DAO_FinancialType'//because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1605 );
1606
1607 // Prefer to instantiate BAO's instead of DAO's (when possible)
1608 // so that assignTestValue()/assignTestFK() can be overloaded.
1609 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1610 if (class_exists($baoName)) {
1611 $daoName = $baoName;
1612 }
1613
1614 for ($i = 0; $i < $numObjects; ++$i) {
1615
1616 ++$counter;
1617 /** @var CRM_Core_DAO $object */
1618 $object = new $daoName();
1619
1620 $fields = & $object->fields();
1621 foreach ($fields as $fieldName => $fieldDef) {
1622 $dbName = $fieldDef['name'];
1623 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
1624 $required = CRM_Utils_Array::value('required', $fieldDef);
1625
1626 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1627 $object->$dbName = $params[$dbName];
1628 }
1629
1630 elseif ($dbName != 'id') {
1631 if ($FKClassName != NULL) {
1632 $object->assignTestFK($fieldName, $fieldDef, $params);
1633 continue;
1634 } else {
1635 $object->assignTestValue($fieldName, $fieldDef, $counter);
1636 }
1637 }
1638 }
1639
1640 $object->save();
1641
1642 if (!$createOnly) {
1643 $objects[$i] = $object;
1644 }
1645 else {
1646 unset($object);
1647 }
1648 }
1649
1650 if ($createOnly) {
1651 return;
1652 }
1653 elseif ($numObjects == 1) {
1654 return $objects[0];
1655 }
1656 else {
1657 return $objects;
1658 }
1659 }
1660
1661 /**
1662 * Deletes the this object plus any dependent objects that are associated with it
1663 * ONLY USE FOR TESTING
1664 *
1665 * @param string $daoName
1666 * @param array $params
1667 */
1668 public static function deleteTestObjects($daoName, $params = array()) {
1669 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1670 // so we re-set here in case
1671 $config = CRM_Core_Config::singleton();
1672 $config->backtrace = TRUE;
1673
1674 $object = new $daoName();
1675 $object->id = CRM_Utils_Array::value('id', $params);
1676
1677 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1678 if ($object->find(TRUE)) {
1679
1680 $fields = &$object->fields();
1681 foreach ($fields as $name => $value) {
1682
1683 $dbName = $value['name'];
1684
1685 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1686 $required = CRM_Utils_Array::value('required', $value);
1687 if ($FKClassName != NULL
1688 && $object->$dbName
1689 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
1690 && ($required || $dbName == 'contact_id')
1691 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1692 // to make this test process pass - line below makes pass for now
1693 && $dbName != 'member_of_contact_id') {
1694 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1695 }
1696 }
1697 }
1698
1699 $object->delete();
1700
1701 foreach ($deletions as $deletion) {
1702 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
1703 }
1704 }
1705
1706 /**
1707 * Set defaults when creating new entity
1708 * (don't call this set defaults as already in use with different signature in some places)
1709 *
1710 * @param array $params
1711 * @param $defaults
1712 */
1713 public static function setCreateDefaults(&$params, $defaults) {
1714 if (isset($params['id'])) {
1715 return;
1716 }
1717 foreach ($defaults as $key => $value) {
1718 if (!array_key_exists($key, $params) || $params[$key] === NULL) {
1719 $params[$key] = $value;
1720 }
1721 }
1722 }
1723
1724 /**
1725 * @param string $prefix
1726 * @param bool $addRandomString
1727 * @param null $string
1728 *
1729 * @return string
1730 */
1731 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1732 $tableName = $prefix . "_temp";
1733
1734 if ($addRandomString) {
1735 if ($string) {
1736 $tableName .= "_" . $string;
1737 }
1738 else {
1739 $tableName .= "_" . md5(uniqid('', TRUE));
1740 }
1741 }
1742 return $tableName;
1743 }
1744
1745 /**
1746 * @param bool $view
1747 * @param bool $trigger
1748 *
1749 * @return bool
1750 */
1751 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1752 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1753 // and logging
1754 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1755 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
1756 $dao = new CRM_Core_DAO();
1757 if ($view) {
1758 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1759 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1760 return FALSE;
1761 }
1762 }
1763
1764 if ($trigger) {
1765 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1766 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
1767 if ($view) {
1768 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1769 }
1770 return FALSE;
1771 }
1772
1773 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1774 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1775 if ($view) {
1776 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1777 }
1778 return FALSE;
1779 }
1780 }
1781
1782 if ($view) {
1783 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1784 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1785 return FALSE;
1786 }
1787 }
1788
1789 return TRUE;
1790 }
1791
1792 /**
1793 * @param null $message
1794 * @param bool $printDAO
1795 */
1796 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1797 CRM_Utils_System::xMemory("{$message}: ");
1798
1799 if ($printDAO) {
1800 global $_DB_DATAOBJECT;
1801 $q = array();
1802 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1803 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1804 }
1805 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
1806 }
1807 }
1808
1809 /**
1810 * Build a list of triggers via hook and add them to (err, reconcile them
1811 * with) the database.
1812 *
1813 * @param $tableName
1814 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1815 * @param bool $force
1816 *
1817 * @see CRM-9716
1818 */
1819 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1820 $info = array();
1821
1822 $logging = new CRM_Logging_Schema;
1823 $logging->triggerInfo($info, $tableName, $force);
1824
1825 CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
1826 CRM_Contact_BAO_Contact::triggerInfo($info, $tableName);
1827
1828 CRM_Utils_Hook::triggerInfo($info, $tableName);
1829
1830 // drop all existing triggers on all tables
1831 $logging->dropTriggers($tableName);
1832
1833 // now create the set of new triggers
1834 self::createTriggers($info, $tableName);
1835 }
1836
1837 /**
1838 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1839 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1840 * TODO: Alternative solutions might be
1841 * * Stop using functions and find another way to strip numeric characters from phones
1842 * * Give better error messages (currently a missing fn fatals with "unknown error")
1843 */
1844 public static function checkSqlFunctionsExist() {
1845 if (!self::$_checkedSqlFunctionsExist) {
1846 self::$_checkedSqlFunctionsExist = TRUE;
1847 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1848 if (!$dao->fetch()) {
1849 self::triggerRebuild();
1850 }
1851 }
1852 }
1853
1854 /**
1855 * Wrapper function to drop triggers
1856 *
1857 * @param $tableName
1858 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1859 */
1860 public static function dropTriggers($tableName = NULL) {
1861 $info = array();
1862
1863 $logging = new CRM_Logging_Schema;
1864 $logging->triggerInfo($info, $tableName);
1865
1866 // drop all existing triggers on all tables
1867 $logging->dropTriggers($tableName);
1868 }
1869
1870 /**
1871 * @param $info
1872 * Array per hook_civicrm_triggerInfo.
1873 * @param $onlyTableName
1874 * String the specific table requiring a rebuild; or NULL to rebuild all tables.
1875 */
1876 public static function createTriggers(&$info, $onlyTableName = NULL) {
1877 // Validate info array, should probably raise errors?
1878 if (is_array($info) == FALSE) {
1879 return;
1880 }
1881
1882 $triggers = array();
1883
1884 // now enumerate the tables and the events and collect the same set in a different format
1885 foreach ($info as $value) {
1886
1887 // clean the incoming data, skip malformed entries
1888 // TODO: malformed entries should raise errors or get logged.
1889 if (isset($value['table']) == FALSE ||
1890 isset($value['event']) == FALSE ||
1891 isset($value['when']) == FALSE ||
1892 isset($value['sql']) == FALSE
1893 ) {
1894 continue;
1895 }
1896
1897 if (is_string($value['table']) == TRUE) {
1898 $tables = array($value['table']);
1899 }
1900 else {
1901 $tables = $value['table'];
1902 }
1903
1904 if (is_string($value['event']) == TRUE) {
1905 $events = array(strtolower($value['event']));
1906 }
1907 else {
1908 $events = array_map('strtolower', $value['event']);
1909 }
1910
1911 $whenName = strtolower($value['when']);
1912
1913 foreach ($tables as $tableName) {
1914 if (!isset($triggers[$tableName])) {
1915 $triggers[$tableName] = array();
1916 }
1917
1918 foreach ($events as $eventName) {
1919 $template_params = array('{tableName}', '{eventName}');
1920 $template_values = array($tableName, $eventName);
1921
1922 $sql = str_replace($template_params,
1923 $template_values,
1924 $value['sql']
1925 );
1926 $variables = str_replace($template_params,
1927 $template_values,
1928 CRM_Utils_Array::value('variables', $value)
1929 );
1930
1931 if (!isset($triggers[$tableName][$eventName])) {
1932 $triggers[$tableName][$eventName] = array();
1933 }
1934
1935 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1936 // We're leaving out cursors, conditions, and handlers for now
1937 // they are kind of dangerous in this context anyway
1938 // better off putting them in stored procedures
1939 $triggers[$tableName][$eventName][$whenName] = array(
1940 'variables' => array(),
1941 'sql' => array(),
1942 );
1943 }
1944
1945 if ($variables) {
1946 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1947 }
1948
1949 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1950 }
1951 }
1952 }
1953
1954 // now spit out the sql
1955 foreach ($triggers as $tableName => $tables) {
1956 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1957 continue;
1958 }
1959 foreach ($tables as $eventName => $events) {
1960 foreach ($events as $whenName => $parts) {
1961 $varString = implode("\n", $parts['variables']);
1962 $sqlString = implode("\n", $parts['sql']);
1963 $validName = CRM_Core_DAO::shortenSQLName($tableName, 48, TRUE);
1964 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1965 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1966
1967 CRM_Core_DAO::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1968 CRM_Core_DAO::executeQuery(
1969 $triggerSQL,
1970 array(),
1971 TRUE,
1972 NULL,
1973 FALSE,
1974 FALSE
1975 );
1976 }
1977 }
1978 }
1979 }
1980
1981 /**
1982 * Given a list of fields, create a list of references.
1983 *
1984 * @param string $className
1985 * BAO/DAO class name.
1986 * @return array<CRM_Core_Reference_Interface>
1987 */
1988 public static function createReferenceColumns($className) {
1989 $result = array();
1990 $fields = $className::fields();
1991 foreach ($fields as $field) {
1992 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1993 $result[] = new CRM_Core_Reference_OptionValue(
1994 $className::getTableName(),
1995 $field['name'],
1996 'civicrm_option_value',
1997 CRM_Utils_Array::value('keyColumn', $field['pseudoconstant'], 'value'),
1998 $field['pseudoconstant']['optionGroupName']
1999 );
2000 }
2001 }
2002 return $result;
2003 }
2004
2005 /**
2006 * Find all records which refer to this entity.
2007 *
2008 * @return array of objects referencing this
2009 */
2010 public function findReferences() {
2011 $links = self::getReferencesToTable(static::getTableName());
2012
2013 $occurrences = array();
2014 foreach ($links as $refSpec) {
2015 /** @var $refSpec CRM_Core_Reference_Interface */
2016 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
2017 $result = $refSpec->findReferences($this);
2018 if ($result) {
2019 while ($result->fetch()) {
2020 $obj = new $daoName();
2021 $obj->id = $result->id;
2022 $occurrences[] = $obj;
2023 }
2024 }
2025 }
2026
2027 return $occurrences;
2028 }
2029
2030 /**
2031 * @return array each item has keys:
2032 * - name: string
2033 * - type: string
2034 * - count: int
2035 * - table: string|null SQL table name
2036 * - key: string|null SQL column name
2037 */
2038 public function getReferenceCounts() {
2039 $links = self::getReferencesToTable(static::getTableName());
2040
2041 $counts = array();
2042 foreach ($links as $refSpec) {
2043 /** @var $refSpec CRM_Core_Reference_Interface */
2044 $count = $refSpec->getReferenceCount($this);
2045 if ($count['count'] != 0) {
2046 $counts[] = $count;
2047 }
2048 }
2049
2050 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
2051 /** @var $component CRM_Core_Component_Info */
2052 $counts = array_merge($counts, $component->getReferenceCounts($this));
2053 }
2054 CRM_Utils_Hook::referenceCounts($this, $counts);
2055
2056 return $counts;
2057 }
2058
2059 /**
2060 * List all tables which have hard foreign keys to this table.
2061 *
2062 * For now, this returns a description of every entity_id/entity_table
2063 * reference.
2064 * TODO: filter dynamic entity references on the $tableName, based on
2065 * schema metadata in dynamicForeignKey which enumerates a restricted
2066 * set of possible entity_table's.
2067 *
2068 * @param string $tableName
2069 * Table referred to.
2070 *
2071 * @return array structure of table and column, listing every table with a
2072 * foreign key reference to $tableName, and the column where the key appears.
2073 */
2074 public static function getReferencesToTable($tableName) {
2075 $refsFound = array();
2076 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
2077 $links = $daoClassName::getReferenceColumns();
2078 $daoTableName = $daoClassName::getTableName();
2079
2080 foreach ($links as $refSpec) {
2081 /** @var $refSpec CRM_Core_Reference_Interface */
2082 if ($refSpec->matchesTargetTable($tableName)) {
2083 $refsFound[] = $refSpec;
2084 }
2085 }
2086 }
2087 return $refsFound;
2088 }
2089
2090 /**
2091 * Lookup the value of a MySQL global configuration variable.
2092 *
2093 * @param string $name
2094 * E.g. "thread_stack".
2095 * @param mixed $default
2096 * @return mixed
2097 */
2098 public static function getGlobalSetting($name, $default = NULL) {
2099 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2100 // that has been reported to fail under MySQL 5.0 for OS X
2101 $escapedName = self::escapeString($name);
2102 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2103 if ($dao->fetch()) {
2104 return $dao->Value;
2105 }
2106 else {
2107 return $default;
2108 }
2109 }
2110
2111 /**
2112 * Get options for the called BAO object's field.
2113 * This function can be overridden by each BAO to add more logic related to context.
2114 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2115 *
2116 * @param string $fieldName
2117 * @param string $context
2118 * : @see CRM_Core_DAO::buildOptionsContext.
2119 * @param array $props
2120 * : whatever is known about this bao object.
2121 *
2122 * @return Array|bool
2123 */
2124 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2125 // If a given bao does not override this function
2126 $baoName = get_called_class();
2127 return CRM_Core_PseudoConstant::get($baoName, $fieldName, array(), $context);
2128 }
2129
2130 /**
2131 * Populate option labels for this object's fields.
2132 *
2133 * @throws exception if called directly on the base class
2134 */
2135 public function getOptionLabels() {
2136 $fields = $this->fields();
2137 if ($fields === NULL) {
2138 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2139 }
2140 foreach ($fields as $field) {
2141 $name = CRM_Utils_Array::value('name', $field);
2142 if ($name && isset($this->$name)) {
2143 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
2144 if ($label !== FALSE) {
2145 // Append 'label' onto the field name
2146 $labelName = $name . '_label';
2147 $this->$labelName = $label;
2148 }
2149 }
2150 }
2151 }
2152
2153 /**
2154 * Provides documentation and validation for the buildOptions $context param
2155 *
2156 * @param string $context
2157 *
2158 * @throws Exception
2159 * @return array
2160 */
2161 public static function buildOptionsContext($context = NULL) {
2162 $contexts = array(
2163 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2164 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2165 'search' => "Searchable options are returned. Labels are translated.",
2166 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2167 );
2168 // Validation: enforce uniformity of this param
2169 if ($context !== NULL && !isset($contexts[$context])) {
2170 throw new Exception("'$context' is not a valid context for buildOptions.");
2171 }
2172 return $contexts;
2173 }
2174
2175 /**
2176 * @param string $fieldName
2177 * @return bool|array
2178 */
2179 public function getFieldSpec($fieldName) {
2180 $fields = $this->fields();
2181 $fieldKeys = $this->fieldKeys();
2182
2183 // Support "unique names" as well as sql names
2184 $fieldKey = $fieldName;
2185 if (empty($fields[$fieldKey])) {
2186 $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys);
2187 }
2188 // If neither worked then this field doesn't exist. Return false.
2189 if (empty($fields[$fieldKey])) {
2190 return FALSE;
2191 }
2192 return $fields[$fieldKey];
2193 }
2194
2195 /**
2196 * SQL version of api function to assign filters to the DAO based on the syntax
2197 * $field => array('IN' => array(4,6,9))
2198 * OR
2199 * $field => array('LIKE' => array('%me%))
2200 * etc
2201 *
2202 * @param string $fieldName
2203 * Name of fields.
2204 * @param $filter
2205 * Array filter to be applied indexed by operator.
2206 * @param $type
2207 * String type of field (not actually used - nor in api @todo ).
2208 * @param $alias
2209 * String alternative field name ('as') @todo- not actually used.
2210 * @param bool $returnSanitisedArray
2211 * Return a sanitised array instead of a clause.
2212 * this is primarily so we can add filters @ the api level to the Query object based fields
2213 *
2214 * @throws Exception
2215 *
2216 * @todo a better solution would be for the query object to apply these filters based on the
2217 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2218 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2219 * required to extend further & it may be the comments per above should be implemented. It may be
2220 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2221 * in one place has some advantages as we try to extend this format
2222 *
2223 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2224 * depending on whether it is supported as yet
2225 */
2226 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2227 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2228 // support for other syntaxes is discussed in ticket but being put off for now
2229 foreach ($filter as $operator => $criteria) {
2230 if (in_array($operator, self::acceptedSQLOperators())) {
2231 switch ($operator) {
2232 // unary operators
2233 case 'IS NULL':
2234 case 'IS NOT NULL':
2235 if (!$returnSanitisedArray) {
2236 return (sprintf('%s %s', $fieldName, $operator));
2237 }
2238 else {
2239 return (sprintf('%s %s ', $fieldName, $operator));
2240 }
2241 break;
2242
2243 // ternary operators
2244 case 'BETWEEN':
2245 case 'NOT BETWEEN':
2246 if (empty($criteria[0]) || empty($criteria[1])) {
2247 throw new Exception("invalid criteria for $operator");
2248 }
2249 if (!$returnSanitisedArray) {
2250 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
2251 }
2252 else {
2253 return NULL; // not yet implemented (tests required to implement)
2254 }
2255 break;
2256
2257 // n-ary operators
2258 case 'IN':
2259 case 'NOT IN':
2260 if (empty($criteria)) {
2261 throw new Exception("invalid criteria for $operator");
2262 }
2263 $escapedCriteria = array_map(array(
2264 'CRM_Core_DAO',
2265 'escapeString'
2266 ), $criteria);
2267 if (!$returnSanitisedArray) {
2268 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2269 }
2270 return $escapedCriteria;
2271 break;
2272
2273 // binary operators
2274
2275 default:
2276 if (!$returnSanitisedArray) {
2277 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
2278 }
2279 else {
2280 return NULL; // not yet implemented (tests required to implement)
2281 }
2282 }
2283 }
2284 }
2285 }
2286
2287 /**
2288 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2289 * support for other syntaxes is discussed in ticket but being put off for now
2290 * @return array
2291 */
2292 public static function acceptedSQLOperators() {
2293 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'IS NOT NULL', 'IS NULL');
2294 }
2295
2296 /**
2297 * SQL has a limit of 64 characters on various names:
2298 * table name, trigger name, column name ...
2299 *
2300 * For custom groups and fields we generated names from user entered input
2301 * which can be longer than this length, this function helps with creating
2302 * strings that meet various criteria.
2303 *
2304 * @param string $string
2305 * The string to be shortened.
2306 * @param int $length
2307 * The max length of the string.
2308 *
2309 * @param bool $makeRandom
2310 *
2311 * @return string
2312 */
2313 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2314 // early return for strings that meet the requirements
2315 if (strlen($string) <= $length) {
2316 return $string;
2317 }
2318
2319 // easy return for calls that dont need a randomized uniq string
2320 if (!$makeRandom) {
2321 return substr($string, 0, $length);
2322 }
2323
2324 // the string is longer than the length and we need a uniq string
2325 // for the same tablename we need the same uniq string everytime
2326 // hence we use md5 on the string, which is not random
2327 // we'll append 8 characters to the end of the tableName
2328 $md5string = substr(md5($string), 0, 8);
2329 return substr($string, 0, $length - 8) . "_{$md5string}";
2330 }
2331
2332 /**
2333 * @param array $params
2334 */
2335 public function setApiFilter(&$params) {}
2336
2337 }