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