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