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