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