Merge branch 'master' of git://github.com/civicrm/civicrm-core into codingstandards-12
[civicrm-core.git] / CRM / Core / DAO.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Our base DAO class. All DAO classes should inherit from this class.
30 *
31 * @package CRM
32 * @copyright CiviCRM LLC (c) 2004-2014
33 * $Id$
34 *
35 */
36
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
39
40 require_once 'CRM/Core/I18n.php';
41
42 /**
43 * Class CRM_Core_DAO
44 */
45 class CRM_Core_DAO extends DB_DataObject {
46
47 /**
48 * A null object so we can pass it as reference if / when needed
49 */
50 static $_nullObject = NULL;
51 static $_nullArray = array();
52
53 static $_dbColumnValueCache = NULL;
54 const NOT_NULL = 1, IS_NULL = 2,
55 DB_DAO_NOTNULL = 128,
56 VALUE_SEPARATOR = "\ 1",
57 BULK_INSERT_COUNT = 200,
58 BULK_INSERT_HIGH_COUNT = 200,
59 // special value for mail bulk inserts to avoid
60 // potential duplication, assuming a smaller number reduces number of queries
61 // by some factor, so some tradeoff. CRM-8678
62 BULK_MAIL_INSERT_COUNT = 10,
63 QUERY_FORMAT_WILDCARD = 1,
64 QUERY_FORMAT_NO_QUOTES = 2;
65
66 /**
67 * Define entities that shouldn't be created or deleted when creating/ deleting
68 * test objects - this prevents world regions, countries etc from being added / deleted
69 * @var array
70 */
71 static $_testEntitiesToSkip = array();
72 /**
73 * The factory class for this application
74 * @var object
75 */
76 static $_factory = NULL;
77
78 static $_checkedSqlFunctionsExist = FALSE;
79
80 /**
81 * Class constructor
82 *
83 * @return \CRM_Core_DAO
84 */
85 public function __construct() {
86 $this->initialize();
87 $this->__table = $this->getTableName();
88 }
89
90 /**
91 * Empty definition for virtual function
92 */
93 public static function getTableName() {
94 return NULL;
95 }
96
97 /**
98 * Initialize the DAO object
99 *
100 * @param string $dsn
101 * The database connection string.
102 *
103 * @return void
104 */
105 public static function init($dsn) {
106 $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
107 $options['database'] = $dsn;
108 if (defined('CIVICRM_DAO_DEBUG')) {
109 self::DebugLevel(CIVICRM_DAO_DEBUG);
110 }
111 }
112
113 /**
114 * @param string $fieldName
115 * @param $fieldDef
116 * @param array $params
117 */
118 protected function assignTestFK($fieldName, $fieldDef, $params) {
119 $required = CRM_Utils_Array::value('required', $fieldDef);
120 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
121 $dbName = $fieldDef['name'];
122 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
123
124 // skip the FK if it is not required
125 // if it's contact id we should create even if not required
126 // we'll have a go @ fetching first though
127 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
128 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
129 $required = TRUE;
130 }
131 if (!$required && $dbName != 'contact_id') {
132 $fkDAO = new $FKClassName();
133 if ($fkDAO->find(TRUE)) {
134 $this->$dbName = $fkDAO->id;
135 }
136 unset($fkDAO);
137 }
138
139 elseif (in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)) {
140 $depObject = new $FKClassName();
141 $depObject->find(TRUE);
142 $this->$dbName = $depObject->id;
143 unset($depObject);
144 }
145 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
146 // FIXME: the fields() metadata is not specific enough
147 $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
148 $this->$dbName = $depObject->id;
149 unset($depObject);
150 }
151 else {
152 //if it is required we need to generate the dependency object first
153 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
154 $this->$dbName = $depObject->id;
155 unset($depObject);
156 }
157 }
158
159 /**
160 * Generate and assign an arbitrary value to a field of a test object.
161 *
162 * @param string $fieldName
163 * @param array $fieldDef
164 * @param int $counter
165 * The globally-unique ID of the test object.
166 */
167 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
168 $dbName = $fieldDef['name'];
169 $daoName = get_class($this);
170 $handled = FALSE;
171
172 if (!$handled && $dbName == 'contact_sub_type') {
173 //coming up with a rule to set this is too complex let's not set it
174 $handled = TRUE;
175 }
176
177 // Pick an option value if needed
178 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type::T_BOOLEAN) {
179 $options = $daoName::buildOptions($dbName, 'create');
180 if ($options) {
181 $this->$dbName = key($options);
182 $handled = TRUE;
183 }
184 }
185
186 if (!$handled) {
187 switch ($fieldDef['type']) {
188 case CRM_Utils_Type::T_INT:
189 case CRM_Utils_Type::T_FLOAT:
190 case CRM_Utils_Type::T_MONEY:
191 if (isset($fieldDef['precision'])) {
192 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
193 $this->$dbName = CRM_Utils_Number::createTruncatedDecimal($counter, $fieldDef['precision']);
194 }
195 else {
196 $this->$dbName = $counter;
197 }
198 break;
199
200 case CRM_Utils_Type::T_BOOLEAN:
201 if (isset($fieldDef['default'])) {
202 $this->$dbName = $fieldDef['default'];
203 }
204 elseif ($fieldDef['name'] == 'is_deleted' || $fieldDef['name'] == 'is_test') {
205 $this->$dbName = 0;
206 }
207 else {
208 $this->$dbName = 1;
209 }
210 break;
211
212 case CRM_Utils_Type::T_DATE:
213 case CRM_Utils_Type::T_TIMESTAMP:
214 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
215 $this->$dbName = '19700101';
216 if ($dbName == 'end_date') {
217 // put this in the future
218 $this->$dbName = '20200101';
219 }
220 break;
221
222 case CRM_Utils_Type::T_TIME:
223 CRM_Core_Error::fatal('T_TIME shouldnt be used.');
224 //$object->$dbName='000000';
225 //break;
226 case CRM_Utils_Type::T_CCNUM:
227 $this->$dbName = '4111 1111 1111 1111';
228 break;
229
230 case CRM_Utils_Type::T_URL:
231 $this->$dbName = 'http://www.civicrm.org';
232 break;
233
234 case CRM_Utils_Type::T_STRING:
235 case CRM_Utils_Type::T_BLOB:
236 case CRM_Utils_Type::T_MEDIUMBLOB:
237 case CRM_Utils_Type::T_TEXT:
238 case CRM_Utils_Type::T_LONGTEXT:
239 case CRM_Utils_Type::T_EMAIL:
240 default:
241 // WAS: if (isset($value['enumValues'])) {
242 // TODO: see if this works with all pseudoconstants
243 if (isset($fieldDef['pseudoconstant'], $fieldDef['pseudoconstant']['callback'])) {
244 if (isset($fieldDef['default'])) {
245 $this->$dbName = $fieldDef['default'];
246 }
247 else {
248 $options = CRM_Core_PseudoConstant::get($daoName, $fieldName);
249 if (is_array($options)) {
250 $this->$dbName = $options[0];
251 }
252 else {
253 $defaultValues = explode(',', $options);
254 $this->$dbName = $defaultValues[0];
255 }
256 }
257 }
258 else {
259 $this->$dbName = $dbName . '_' . $counter;
260 $maxlength = CRM_Utils_Array::value('maxlength', $fieldDef);
261 if ($maxlength > 0 && strlen($this->$dbName) > $maxlength) {
262 $this->$dbName = substr($this->$dbName, 0, $fieldDef['maxlength']);
263 }
264 }
265 }
266 }
267 }
268
269 /**
270 * Reset the DAO object. DAO is kinda crappy in that there is an unwritten
271 * rule of one query per DAO. We attempt to get around this crappy restricrion
272 * by resetting some of DAO's internal fields. Use this with caution
273 *
274 * @return void
275 */
276 public function reset() {
277
278 foreach (array_keys($this->table()) as $field) {
279 unset($this->$field);
280 }
281
282 /**
283 * reset the various DB_DAO structures manually
284 */
285 $this->_query = array();
286 $this->whereAdd();
287 $this->selectAdd();
288 $this->joinAdd();
289 }
290
291 /**
292 * @param string $tableName
293 *
294 * @return string
295 */
296 public static function getLocaleTableName($tableName) {
297 global $dbLocale;
298 if ($dbLocale) {
299 $tables = CRM_Core_I18n_Schema::schemaStructureTables();
300 if (in_array($tableName, $tables)) {
301 return $tableName . $dbLocale;
302 }
303 }
304 return $tableName;
305 }
306
307 /**
308 * Execute a query by the current DAO, localizing it along the way (if needed).
309 *
310 * @param string $query
311 * The SQL query for execution.
312 * @param bool $i18nRewrite
313 * Whether to rewrite the query.
314 *
315 * @return object
316 * the current DAO object after the query execution
317 */
318 public function query($query, $i18nRewrite = TRUE) {
319 // rewrite queries that should use $dbLocale-based views for multi-language installs
320 global $dbLocale;
321 if ($i18nRewrite and $dbLocale) {
322 $query = CRM_Core_I18n_Schema::rewriteQuery($query);
323 }
324
325 return parent::query($query);
326 }
327
328 /**
329 * Static function to set the factory instance for this class.
330 *
331 * @param object $factory
332 * The factory application object.
333 *
334 * @return void
335 */
336 public static function setFactory(&$factory) {
337 self::$_factory = &$factory;
338 }
339
340 /**
341 * Factory method to instantiate a new object from a table name.
342 *
343 * @param string $table
344 *
345 * @return void
346 */
347 public function factory($table = '') {
348 if (!isset(self::$_factory)) {
349 return parent::factory($table);
350 }
351
352 return self::$_factory->create($table);
353 }
354
355 /**
356 * Initialization for all DAO objects. Since we access DB_DO programatically
357 * we need to set the links manually.
358 *
359 * @return void
360 */
361 public function initialize() {
362 $this->_connect();
363 $this->query("SET NAMES utf8");
364 }
365
366 /**
367 * Defines the default key as 'id'.
368 *
369 *
370 * @return array
371 */
372 public function keys() {
373 static $keys;
374 if (!isset($keys)) {
375 $keys = array('id');
376 }
377 return $keys;
378 }
379
380 /**
381 * Tells DB_DataObject which keys use autoincrement.
382 * 'id' is autoincrementing by default.
383 *
384 *
385 * @return array
386 */
387 public function sequenceKey() {
388 static $sequenceKeys;
389 if (!isset($sequenceKeys)) {
390 $sequenceKeys = array('id', TRUE);
391 }
392 return $sequenceKeys;
393 }
394
395 /**
396 * Returns list of FK relationships
397 *
398 *
399 * @return array
400 * Array of CRM_Core_Reference_Interface
401 */
402 public static function getReferenceColumns() {
403 return array();
404 }
405
406 /**
407 * Returns all the column names of this table
408 *
409 *
410 * @return array
411 */
412 public static function &fields() {
413 $result = NULL;
414 return $result;
415 }
416
417 /**
418 * Get/set an associative array of table columns
419 *
420 * @return array
421 * (associative)
422 */
423 public function table() {
424 $fields = &$this->fields();
425
426 $table = array();
427 if ($fields) {
428 foreach ($fields as $name => $value) {
429 $table[$value['name']] = $value['type'];
430 if (!empty($value['required'])) {
431 $table[$value['name']] += self::DB_DAO_NOTNULL;
432 }
433 }
434 }
435
436 return $table;
437 }
438
439 /**
440 * @return $this
441 */
442 public function save() {
443 if (!empty($this->id)) {
444 $this->update();
445
446 $event = new \Civi\Core\DAO\Event\PostUpdate($this);
447 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
448 }
449 else {
450 $this->insert();
451
452 $event = new \Civi\Core\DAO\Event\PostUpdate($this);
453 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
454 }
455 $this->free();
456
457 CRM_Utils_Hook::postSave($this);
458
459 return $this;
460 }
461
462 public function delete($useWhere = FALSE) {
463 $result = parent::delete($useWhere);
464
465 $event = new \Civi\Core\DAO\Event\PostDelete($this, $result);
466 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
467
468 return $result;
469 }
470
471 /**
472 * @param bool $created
473 */
474 public function log($created = FALSE) {
475 static $cid = NULL;
476
477 if (!$this->getLog()) {
478 return;
479 }
480
481 if (!$cid) {
482 $session = CRM_Core_Session::singleton();
483 $cid = $session->get('userID');
484 }
485
486 // return is we dont have handle to FK
487 if (!$cid) {
488 return;
489 }
490
491 $dao = new CRM_Core_DAO_Log();
492 $dao->entity_table = $this->getTableName();
493 $dao->entity_id = $this->id;
494 $dao->modified_id = $cid;
495 $dao->modified_date = date("YmdHis");
496 $dao->insert();
497 }
498
499 /**
500 * Given an associative array of name/value pairs, extract all the values
501 * that belong to this object and initialize the object with said values
502 *
503 * @param array $params
504 * (reference ) associative array of name/value pairs.
505 *
506 * @return bool
507 * Did we copy all null values into the object
508 */
509 public function copyValues(&$params) {
510 $fields = &$this->fields();
511 $allNull = TRUE;
512 foreach ($fields as $name => $value) {
513 $dbName = $value['name'];
514 if (array_key_exists($dbName, $params)) {
515 $pValue = $params[$dbName];
516 $exists = TRUE;
517 }
518 elseif (array_key_exists($name, $params)) {
519 $pValue = $params[$name];
520 $exists = TRUE;
521 }
522 else {
523 $exists = FALSE;
524 }
525
526 // if there is no value then make the variable NULL
527 if ($exists) {
528 if ($pValue === '') {
529 $this->$dbName = 'null';
530 }
531 else {
532 $this->$dbName = $pValue;
533 $allNull = FALSE;
534 }
535 }
536 }
537 return $allNull;
538 }
539
540 /**
541 * Store all the values from this object in an associative array
542 * this is a destructive store, calling function is responsible
543 * for keeping sanity of id's.
544 *
545 * @param object $object
546 * The object that we are extracting data from.
547 * @param array $values
548 * (reference ) associative array of name/value pairs.
549 *
550 * @return void
551 */
552 public static function storeValues(&$object, &$values) {
553 $fields = &$object->fields();
554 foreach ($fields as $name => $value) {
555 $dbName = $value['name'];
556 if (isset($object->$dbName) && $object->$dbName !== 'null') {
557 $values[$dbName] = $object->$dbName;
558 if ($name != $dbName) {
559 $values[$name] = $object->$dbName;
560 }
561 }
562 }
563 }
564
565 /**
566 * Create an attribute for this specific field. We only do this for strings and text
567 *
568 * @param array $field
569 * The field under task.
570 *
571 * @return array|null
572 * the attributes for the object
573 */
574 public static function makeAttribute($field) {
575 if ($field) {
576 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
577 $maxLength = CRM_Utils_Array::value('maxlength', $field);
578 $size = CRM_Utils_Array::value('size', $field);
579 if ($maxLength || $size) {
580 $attributes = array();
581 if ($maxLength) {
582 $attributes['maxlength'] = $maxLength;
583 }
584 if ($size) {
585 $attributes['size'] = $size;
586 }
587 return $attributes;
588 }
589 }
590 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) {
591 $rows = CRM_Utils_Array::value('rows', $field);
592 if (!isset($rows)) {
593 $rows = 2;
594 }
595 $cols = CRM_Utils_Array::value('cols', $field);
596 if (!isset($cols)) {
597 $cols = 80;
598 }
599
600 $attributes = array();
601 $attributes['rows'] = $rows;
602 $attributes['cols'] = $cols;
603 return $attributes;
604 }
605 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) {
606 $attributes['size'] = 6;
607 $attributes['maxlength'] = 14;
608 return $attributes;
609 }
610 }
611 return NULL;
612 }
613
614 /**
615 * Get the size and maxLength attributes for this text field
616 * (or for all text fields) in the DAO object.
617 *
618 * @param string $class
619 * Name of DAO class.
620 * @param string $fieldName
621 * Field that i'm interested in or null if.
622 * you want the attributes for all DAO text fields
623 *
624 * @return array
625 * assoc array of name => attribute pairs
626 */
627 public static function getAttribute($class, $fieldName = NULL) {
628 $object = new $class();
629 $fields = &$object->fields();
630 if ($fieldName != NULL) {
631 $field = CRM_Utils_Array::value($fieldName, $fields);
632 return self::makeAttribute($field);
633 }
634 else {
635 $attributes = array();
636 foreach ($fields as $name => $field) {
637 $attribute = self::makeAttribute($field);
638 if ($attribute) {
639 $attributes[$name] = $attribute;
640 }
641 }
642
643 if (!empty($attributes)) {
644 return $attributes;
645 }
646 }
647 return NULL;
648 }
649
650 /**
651 * @param $type
652 *
653 * @throws Exception
654 */
655 public static function transaction($type) {
656 CRM_Core_Error::fatal('This function is obsolete, please use CRM_Core_Transaction');
657 }
658
659 /**
660 * Check if there is a record with the same name in the db
661 *
662 * @param string $value
663 * The value of the field we are checking.
664 * @param string $daoName
665 * The dao object name.
666 * @param string $daoID
667 * The id of the object being updated. u can change your name.
668 * as long as there is no conflict
669 * @param string $fieldName
670 * The name of the field in the DAO.
671 *
672 * @return bool
673 * true if object exists
674 */
675 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
676 $object = new $daoName();
677 $object->$fieldName = $value;
678
679 $config = CRM_Core_Config::singleton();
680
681 if ($object->find(TRUE)) {
682 return ($daoID && $object->id == $daoID) ? TRUE : FALSE;
683 }
684 else {
685 return TRUE;
686 }
687 }
688
689 /**
690 * Check if there is a given column in a specific table
691 *
692 * @param string $tableName
693 * @param string $columnName
694 * @param bool $i18nRewrite
695 * Whether to rewrite the query on multilingual setups.
696 *
697 * @return bool
698 * true if exists, else false
699 */
700 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
701 $query = "
702 SHOW COLUMNS
703 FROM $tableName
704 LIKE %1
705 ";
706 $params = array(1 => array($columnName, 'String'));
707 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
708 $result = $dao->fetch() ? TRUE : FALSE;
709 $dao->free();
710 return $result;
711 }
712
713 /**
714 * Returns the storage engine used by given table-name(optional).
715 * Otherwise scans all the tables and return an array of all the
716 * distinct storage engines being used.
717 *
718 * @param string $tableName
719 *
720 * @param int $maxTablesToCheck
721 * @param string $fieldName
722 *
723 * @return array
724 */
725 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
726 $values = array();
727 $query = "SHOW TABLE STATUS LIKE %1";
728
729 $params = array();
730
731 if (isset($tableName)) {
732 $params = array(1 => array($tableName, 'String'));
733 }
734 else {
735 $params = array(1 => array('civicrm_%', 'String'));
736 }
737
738 $dao = CRM_Core_DAO::executeQuery($query, $params);
739
740 $count = 0;
741 while ($dao->fetch()) {
742 if (isset($values[$dao->$fieldName]) ||
743 // ignore import and other temp tables
744 strpos($dao->Name, 'civicrm_import_job_') !== FALSE ||
745 strpos($dao->Name, '_temp') !== FALSE
746 ) {
747 continue;
748 }
749 $values[$dao->$fieldName] = 1;
750 $count++;
751 if ($maxTablesToCheck &&
752 $count >= $maxTablesToCheck
753 ) {
754 break;
755 }
756 }
757 $dao->free();
758 return $values;
759 }
760
761 /**
762 * @param int $maxTablesToCheck
763 *
764 * @return bool
765 */
766 public static function isDBMyISAM($maxTablesToCheck = 10) {
767 // show error if any of the tables, use 'MyISAM' storage engine.
768 $engines = self::getStorageValues(NULL, $maxTablesToCheck);
769 if (array_key_exists('MyISAM', $engines)) {
770 return TRUE;
771 }
772 return FALSE;
773 }
774
775 /**
776 * Checks if a constraint exists for a specified table.
777 *
778 * @param string $tableName
779 * @param string $constraint
780 *
781 * @return bool
782 * true if constraint exists, false otherwise
783 */
784 public static function checkConstraintExists($tableName, $constraint) {
785 static $show = array();
786
787 if (!array_key_exists($tableName, $show)) {
788 $query = "SHOW CREATE TABLE $tableName";
789 $dao = CRM_Core_DAO::executeQuery($query);
790
791 if (!$dao->fetch()) {
792 CRM_Core_Error::fatal();
793 }
794
795 $dao->free();
796 $show[$tableName] = $dao->Create_Table;
797 }
798
799 return preg_match("/\b$constraint\b/i", $show[$tableName]) ? TRUE : FALSE;
800 }
801
802 /**
803 * Checks if CONSTRAINT keyword exists for a specified table.
804 *
805 * @param array $tables
806 *
807 * @throws Exception
808 *
809 * @return bool
810 * true if CONSTRAINT keyword exists, false otherwise
811 */
812 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
813 $show = array();
814 foreach ($tables as $tableName) {
815 if (!array_key_exists($tableName, $show)) {
816 $query = "SHOW CREATE TABLE $tableName";
817 $dao = CRM_Core_DAO::executeQuery($query);
818
819 if (!$dao->fetch()) {
820 CRM_Core_Error::fatal();
821 }
822
823 $dao->free();
824 $show[$tableName] = $dao->Create_Table;
825 }
826
827 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ? TRUE : FALSE;
828 if ($result == TRUE) {
829 continue;
830 }
831 else {
832 return FALSE;
833 }
834 }
835 return TRUE;
836 }
837
838 /**
839 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
840 * for a specified column of a table.
841 *
842 * @param string $tableName
843 * @param string $columnName
844 *
845 * @return bool
846 * true if in format, false otherwise
847 */
848 public static function checkFKConstraintInFormat($tableName, $columnName) {
849 static $show = array();
850
851 if (!array_key_exists($tableName, $show)) {
852 $query = "SHOW CREATE TABLE $tableName";
853 $dao = CRM_Core_DAO::executeQuery($query);
854
855 if (!$dao->fetch()) {
856 CRM_Core_Error::fatal();
857 }
858
859 $dao->free();
860 $show[$tableName] = $dao->Create_Table;
861 }
862 $constraint = "`FK_{$tableName}_{$columnName}`";
863 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
864 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ? TRUE : FALSE;
865 }
866
867 /**
868 * Check whether a specific column in a specific table has always the same value
869 *
870 * @param string $tableName
871 * @param string $columnName
872 * @param string $columnValue
873 *
874 * @return bool
875 * true if the value is always $columnValue, false otherwise
876 */
877 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
878 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
879 $dao = CRM_Core_DAO::executeQuery($query);
880 $result = $dao->fetch() ? FALSE : TRUE;
881 $dao->free();
882 return $result;
883 }
884
885 /**
886 * Check whether a specific column in a specific table is always NULL
887 *
888 * @param string $tableName
889 * @param string $columnName
890 *
891 * @return bool
892 * true if if the value is always NULL, false otherwise
893 */
894 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
895 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
896 $dao = CRM_Core_DAO::executeQuery($query);
897 $result = $dao->fetch() ? FALSE : TRUE;
898 $dao->free();
899 return $result;
900 }
901
902 /**
903 * Check if there is a given table in the database
904 *
905 * @param string $tableName
906 *
907 * @return bool
908 * true if exists, else false
909 */
910 public static function checkTableExists($tableName) {
911 $query = "
912 SHOW TABLES
913 LIKE %1
914 ";
915 $params = array(1 => array($tableName, 'String'));
916
917 $dao = CRM_Core_DAO::executeQuery($query, $params);
918 $result = $dao->fetch() ? TRUE : FALSE;
919 $dao->free();
920 return $result;
921 }
922
923 /**
924 * @param $version
925 *
926 * @return bool
927 */
928 public function checkVersion($version) {
929 $query = "
930 SELECT version
931 FROM civicrm_domain
932 ";
933 $dbVersion = CRM_Core_DAO::singleValueQuery($query);
934 return trim($version) == trim($dbVersion) ? TRUE : FALSE;
935 }
936
937 /**
938 * Find a DAO object for the given ID and return it.
939 *
940 * @param int $id
941 * Id of the DAO object being searched for.
942 *
943 * @return object
944 * Object of the type of the class that called this function.
945 */
946 public static function findById($id) {
947 $object = new static();
948 $object->id = $id;
949 if (!$object->find(TRUE)) {
950 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
951 }
952 return $object;
953 }
954
955 /**
956 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
957 *
958 * @param string $daoName
959 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
960 * @param int $searchValue
961 * Value of the column you want to search by.
962 * @param string $returnColumn
963 * Name of the column you want to GET the value of.
964 * @param string $searchColumn
965 * Name of the column you want to search by.
966 * @param bool $force
967 * Skip use of the cache.
968 *
969 * @return string|null
970 * Value of $returnColumn in the retrieved record
971 */
972 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
973 if (
974 empty($searchValue) ||
975 trim(strtolower($searchValue)) == 'null'
976 ) {
977 // adding this year since developers forget to check for an id
978 // or for the 'null' (which is a bad DAO kludge)
979 // and hence we get the first value in the db
980 CRM_Core_Error::fatal();
981 }
982
983 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
984 if (self::$_dbColumnValueCache === NULL) {
985 self::$_dbColumnValueCache = array();
986 }
987
988 if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
989 $object = new $daoName();
990 $object->$searchColumn = $searchValue;
991 $object->selectAdd();
992 $object->selectAdd($returnColumn);
993
994 $result = NULL;
995 if ($object->find(TRUE)) {
996 $result = $object->$returnColumn;
997 }
998 $object->free();
999
1000 self::$_dbColumnValueCache[$cacheKey] = $result;
1001 }
1002 return self::$_dbColumnValueCache[$cacheKey];
1003 }
1004
1005 /**
1006 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1007 *
1008 * @param string $daoName
1009 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1010 * @param int $searchValue
1011 * Value of the column you want to search by.
1012 * @param string $setColumn
1013 * Name of the column you want to SET the value of.
1014 * @param string $setValue
1015 * SET the setColumn to this value.
1016 * @param string $searchColumn
1017 * Name of the column you want to search by.
1018 *
1019 * @return bool
1020 * true if we found and updated the object, else false
1021 */
1022 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1023 $object = new $daoName();
1024 $object->selectAdd();
1025 $object->selectAdd("$searchColumn, $setColumn");
1026 $object->$searchColumn = $searchValue;
1027 $result = FALSE;
1028 if ($object->find(TRUE)) {
1029 $object->$setColumn = $setValue;
1030 if ($object->save()) {
1031 $result = TRUE;
1032 }
1033 }
1034 $object->free();
1035 return $result;
1036 }
1037
1038 /**
1039 * Get sort string
1040 *
1041 * @param array|object $sort either array or CRM_Utils_Sort
1042 * @param string $default
1043 * Default sort value.
1044 *
1045 * @return string
1046 * sortString
1047 */
1048 public static function getSortString($sort, $default = NULL) {
1049 // check if sort is of type CRM_Utils_Sort
1050 if (is_a($sort, 'CRM_Utils_Sort')) {
1051 return $sort->orderBy();
1052 }
1053
1054 // is it an array specified as $field => $sortDirection ?
1055 if ($sort) {
1056 foreach ($sort as $k => $v) {
1057 $sortString .= "$k $v,";
1058 }
1059 return rtrim($sortString, ',');
1060 }
1061 return $default;
1062 }
1063
1064 /**
1065 * Fetch object based on array of properties
1066 *
1067 * @param string $daoName
1068 * Name of the dao object.
1069 * @param array $params
1070 * (reference ) an assoc array of name/value pairs.
1071 * @param array $defaults
1072 * (reference ) an assoc array to hold the flattened values.
1073 * @param array $returnProperities
1074 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1075 *
1076 * @return object
1077 * an object of type referenced by daoName
1078 */
1079 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1080 $object = new $daoName();
1081 $object->copyValues($params);
1082
1083 // return only specific fields if returnproperties are sent
1084 if (!empty($returnProperities)) {
1085 $object->selectAdd();
1086 $object->selectAdd(implode(',', $returnProperities));
1087 }
1088
1089 if ($object->find(TRUE)) {
1090 self::storeValues($object, $defaults);
1091 return $object;
1092 }
1093 return NULL;
1094 }
1095
1096 /**
1097 * Delete the object records that are associated with this contact
1098 *
1099 * @param string $daoName
1100 * Name of the dao object.
1101 * @param int $contactId
1102 * Id of the contact to delete.
1103 *
1104 * @return void
1105 */
1106 public static function deleteEntityContact($daoName, $contactId) {
1107 $object = new $daoName();
1108
1109 $object->entity_table = 'civicrm_contact';
1110 $object->entity_id = $contactId;
1111 $object->delete();
1112 }
1113
1114 /**
1115 * Execute a query
1116 *
1117 * @param string $query
1118 * Query to be executed.
1119 *
1120 * @param array $params
1121 * @param bool $abort
1122 * @param null $daoName
1123 * @param bool $freeDAO
1124 * @param bool $i18nRewrite
1125 * @param bool $trapException
1126 *
1127 * @return CRM_Core_DAO|object
1128 * object that holds the results of the query
1129 * NB - if this is defined as just returning a DAO phpstorm keeps pointing
1130 * out all the properties that are not part of the DAO
1131 */
1132 public 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 statements 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 public 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 public 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 object|array|NULL
1588 * NULL if $createOnly. A single object if $numObjects==1. Otherwise, an array of multiple objects.
1589 */
1590 public static function createTestObject(
1591 $daoName,
1592 $params = array(),
1593 $numObjects = 1,
1594 $createOnly = FALSE
1595 ) {
1596 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1597 // so we re-set here in case
1598 $config = CRM_Core_Config::singleton();
1599 $config->backtrace = TRUE;
1600
1601 static $counter = 0;
1602 CRM_Core_DAO::$_testEntitiesToSkip = array(
1603 'CRM_Core_DAO_Worldregion',
1604 'CRM_Core_DAO_StateProvince',
1605 'CRM_Core_DAO_Country',
1606 'CRM_Core_DAO_Domain',
1607 'CRM_Financial_DAO_FinancialType',
1608 //because valid ones exist & we use pick them due to pseudoconstant can't reliably create & delete these
1609 );
1610
1611 // Prefer to instantiate BAO's instead of DAO's (when possible)
1612 // so that assignTestValue()/assignTestFK() can be overloaded.
1613 $baoName = str_replace('_DAO_', '_BAO_', $daoName);
1614 if (class_exists($baoName)) {
1615 $daoName = $baoName;
1616 }
1617
1618 for ($i = 0; $i < $numObjects; ++$i) {
1619
1620 ++$counter;
1621 /** @var CRM_Core_DAO $object */
1622 $object = new $daoName();
1623
1624 $fields = &$object->fields();
1625 foreach ($fields as $fieldName => $fieldDef) {
1626 $dbName = $fieldDef['name'];
1627 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
1628 $required = CRM_Utils_Array::value('required', $fieldDef);
1629
1630 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1631 $object->$dbName = $params[$dbName];
1632 }
1633
1634 elseif ($dbName != 'id') {
1635 if ($FKClassName != NULL) {
1636 $object->assignTestFK($fieldName, $fieldDef, $params);
1637 continue;
1638 }
1639 else {
1640 $object->assignTestValue($fieldName, $fieldDef, $counter);
1641 }
1642 }
1643 }
1644
1645 $object->save();
1646
1647 if (!$createOnly) {
1648 $objects[$i] = $object;
1649 }
1650 else {
1651 unset($object);
1652 }
1653 }
1654
1655 if ($createOnly) {
1656 return NULL;
1657 }
1658 elseif ($numObjects == 1) {
1659 return $objects[0];
1660 }
1661 else {
1662 return $objects;
1663 }
1664 }
1665
1666 /**
1667 * Deletes the this object plus any dependent objects that are associated with it
1668 * ONLY USE FOR TESTING
1669 *
1670 * @param string $daoName
1671 * @param array $params
1672 */
1673 public static function deleteTestObjects($daoName, $params = array()) {
1674 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1675 // so we re-set here in case
1676 $config = CRM_Core_Config::singleton();
1677 $config->backtrace = TRUE;
1678
1679 $object = new $daoName();
1680 $object->id = CRM_Utils_Array::value('id', $params);
1681
1682 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1683 if ($object->find(TRUE)) {
1684
1685 $fields = &$object->fields();
1686 foreach ($fields as $name => $value) {
1687
1688 $dbName = $value['name'];
1689
1690 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1691 $required = CRM_Utils_Array::value('required', $value);
1692 if ($FKClassName != NULL
1693 && $object->$dbName
1694 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
1695 && ($required || $dbName == 'contact_id')
1696 //I'm a bit stuck on this one - we might need to change the singleValueAlter so that the entities don't share a contact
1697 // to make this test process pass - line below makes pass for now
1698 && $dbName != 'member_of_contact_id'
1699 ) {
1700 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1701 }
1702 }
1703 }
1704
1705 $object->delete();
1706
1707 foreach ($deletions as $deletion) {
1708 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
1709 }
1710 }
1711
1712 /**
1713 * Set defaults when creating new entity
1714 * (don't call this set defaults as already in use with different signature in some places)
1715 *
1716 * @param array $params
1717 * @param $defaults
1718 */
1719 public static function setCreateDefaults(&$params, $defaults) {
1720 if (isset($params['id'])) {
1721 return;
1722 }
1723 foreach ($defaults as $key => $value) {
1724 if (!array_key_exists($key, $params) || $params[$key] === NULL) {
1725 $params[$key] = $value;
1726 }
1727 }
1728 }
1729
1730 /**
1731 * @param string $prefix
1732 * @param bool $addRandomString
1733 * @param null $string
1734 *
1735 * @return string
1736 */
1737 public static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1738 $tableName = $prefix . "_temp";
1739
1740 if ($addRandomString) {
1741 if ($string) {
1742 $tableName .= "_" . $string;
1743 }
1744 else {
1745 $tableName .= "_" . md5(uniqid('', TRUE));
1746 }
1747 }
1748 return $tableName;
1749 }
1750
1751 /**
1752 * @param bool $view
1753 * @param bool $trigger
1754 *
1755 * @return bool
1756 */
1757 public static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1758 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1759 // and logging
1760 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1761 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
1762 $dao = new CRM_Core_DAO();
1763 if ($view) {
1764 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1765 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1766 return FALSE;
1767 }
1768 }
1769
1770 if ($trigger) {
1771 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1772 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
1773 if ($view) {
1774 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1775 }
1776 return FALSE;
1777 }
1778
1779 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1780 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1781 if ($view) {
1782 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1783 }
1784 return FALSE;
1785 }
1786 }
1787
1788 if ($view) {
1789 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1790 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1791 return FALSE;
1792 }
1793 }
1794
1795 return TRUE;
1796 }
1797
1798 /**
1799 * @param null $message
1800 * @param bool $printDAO
1801 */
1802 public static function debugPrint($message = NULL, $printDAO = TRUE) {
1803 CRM_Utils_System::xMemory("{$message}: ");
1804
1805 if ($printDAO) {
1806 global $_DB_DATAOBJECT;
1807 $q = array();
1808 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1809 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1810 }
1811 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
1812 }
1813 }
1814
1815 /**
1816 * Build a list of triggers via hook and add them to (err, reconcile them
1817 * with) the database.
1818 *
1819 * @param string $tableName
1820 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1821 * @param bool $force
1822 *
1823 * @see CRM-9716
1824 */
1825 public static function triggerRebuild($tableName = NULL, $force = FALSE) {
1826 $info = array();
1827
1828 $logging = new CRM_Logging_Schema();
1829 $logging->triggerInfo($info, $tableName, $force);
1830
1831 CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
1832 CRM_Contact_BAO_Contact::triggerInfo($info, $tableName);
1833
1834 CRM_Utils_Hook::triggerInfo($info, $tableName);
1835
1836 // drop all existing triggers on all tables
1837 $logging->dropTriggers($tableName);
1838
1839 // now create the set of new triggers
1840 self::createTriggers($info, $tableName);
1841 }
1842
1843 /**
1844 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1845 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1846 * TODO: Alternative solutions might be
1847 * * Stop using functions and find another way to strip numeric characters from phones
1848 * * Give better error messages (currently a missing fn fatals with "unknown error")
1849 */
1850 public static function checkSqlFunctionsExist() {
1851 if (!self::$_checkedSqlFunctionsExist) {
1852 self::$_checkedSqlFunctionsExist = TRUE;
1853 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1854 if (!$dao->fetch()) {
1855 self::triggerRebuild();
1856 }
1857 }
1858 }
1859
1860 /**
1861 * Wrapper function to drop triggers
1862 *
1863 * @param string $tableName
1864 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1865 */
1866 public static function dropTriggers($tableName = NULL) {
1867 $info = array();
1868
1869 $logging = new CRM_Logging_Schema();
1870 $logging->triggerInfo($info, $tableName);
1871
1872 // drop all existing triggers on all tables
1873 $logging->dropTriggers($tableName);
1874 }
1875
1876 /**
1877 * @param array $info
1878 * per hook_civicrm_triggerInfo.
1879 * @param string $onlyTableName
1880 * the specific table requiring a rebuild; or NULL to rebuild all tables.
1881 */
1882 public static function createTriggers(&$info, $onlyTableName = NULL) {
1883 // Validate info array, should probably raise errors?
1884 if (is_array($info) == FALSE) {
1885 return;
1886 }
1887
1888 $triggers = array();
1889
1890 // now enumerate the tables and the events and collect the same set in a different format
1891 foreach ($info as $value) {
1892
1893 // clean the incoming data, skip malformed entries
1894 // TODO: malformed entries should raise errors or get logged.
1895 if (isset($value['table']) == FALSE ||
1896 isset($value['event']) == FALSE ||
1897 isset($value['when']) == FALSE ||
1898 isset($value['sql']) == FALSE
1899 ) {
1900 continue;
1901 }
1902
1903 if (is_string($value['table']) == TRUE) {
1904 $tables = array($value['table']);
1905 }
1906 else {
1907 $tables = $value['table'];
1908 }
1909
1910 if (is_string($value['event']) == TRUE) {
1911 $events = array(strtolower($value['event']));
1912 }
1913 else {
1914 $events = array_map('strtolower', $value['event']);
1915 }
1916
1917 $whenName = strtolower($value['when']);
1918
1919 foreach ($tables as $tableName) {
1920 if (!isset($triggers[$tableName])) {
1921 $triggers[$tableName] = array();
1922 }
1923
1924 foreach ($events as $eventName) {
1925 $template_params = array('{tableName}', '{eventName}');
1926 $template_values = array($tableName, $eventName);
1927
1928 $sql = str_replace($template_params,
1929 $template_values,
1930 $value['sql']
1931 );
1932 $variables = str_replace($template_params,
1933 $template_values,
1934 CRM_Utils_Array::value('variables', $value)
1935 );
1936
1937 if (!isset($triggers[$tableName][$eventName])) {
1938 $triggers[$tableName][$eventName] = array();
1939 }
1940
1941 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1942 // We're leaving out cursors, conditions, and handlers for now
1943 // they are kind of dangerous in this context anyway
1944 // better off putting them in stored procedures
1945 $triggers[$tableName][$eventName][$whenName] = array(
1946 'variables' => array(),
1947 'sql' => array(),
1948 );
1949 }
1950
1951 if ($variables) {
1952 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1953 }
1954
1955 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1956 }
1957 }
1958 }
1959
1960 // now spit out the sql
1961 foreach ($triggers as $tableName => $tables) {
1962 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1963 continue;
1964 }
1965 foreach ($tables as $eventName => $events) {
1966 foreach ($events as $whenName => $parts) {
1967 $varString = implode("\n", $parts['variables']);
1968 $sqlString = implode("\n", $parts['sql']);
1969 $validName = CRM_Core_DAO::shortenSQLName($tableName, 48, TRUE);
1970 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1971 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1972
1973 CRM_Core_DAO::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1974 CRM_Core_DAO::executeQuery(
1975 $triggerSQL,
1976 array(),
1977 TRUE,
1978 NULL,
1979 FALSE,
1980 FALSE
1981 );
1982 }
1983 }
1984 }
1985 }
1986
1987 /**
1988 * Given a list of fields, create a list of references.
1989 *
1990 * @param string $className
1991 * BAO/DAO class name.
1992 * @return array<CRM_Core_Reference_Interface>
1993 */
1994 public static function createReferenceColumns($className) {
1995 $result = array();
1996 $fields = $className::fields();
1997 foreach ($fields as $field) {
1998 if (isset($field['pseudoconstant'], $field['pseudoconstant']['optionGroupName'])) {
1999 $result[] = new CRM_Core_Reference_OptionValue(
2000 $className::getTableName(),
2001 $field['name'],
2002 'civicrm_option_value',
2003 CRM_Utils_Array::value('keyColumn', $field['pseudoconstant'], 'value'),
2004 $field['pseudoconstant']['optionGroupName']
2005 );
2006 }
2007 }
2008 return $result;
2009 }
2010
2011 /**
2012 * Find all records which refer to this entity.
2013 *
2014 * @return array
2015 * Array of objects referencing this
2016 */
2017 public function findReferences() {
2018 $links = self::getReferencesToTable(static::getTableName());
2019
2020 $occurrences = array();
2021 foreach ($links as $refSpec) {
2022 /** @var $refSpec CRM_Core_Reference_Interface */
2023 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
2024 $result = $refSpec->findReferences($this);
2025 if ($result) {
2026 while ($result->fetch()) {
2027 $obj = new $daoName();
2028 $obj->id = $result->id;
2029 $occurrences[] = $obj;
2030 }
2031 }
2032 }
2033
2034 return $occurrences;
2035 }
2036
2037 /**
2038 * @return array
2039 * each item has keys:
2040 * - name: string
2041 * - type: string
2042 * - count: int
2043 * - table: string|null SQL table name
2044 * - key: string|null SQL column name
2045 */
2046 public function getReferenceCounts() {
2047 $links = self::getReferencesToTable(static::getTableName());
2048
2049 $counts = array();
2050 foreach ($links as $refSpec) {
2051 /** @var $refSpec CRM_Core_Reference_Interface */
2052 $count = $refSpec->getReferenceCount($this);
2053 if ($count['count'] != 0) {
2054 $counts[] = $count;
2055 }
2056 }
2057
2058 foreach (CRM_Core_Component::getEnabledComponents() as $component) {
2059 /** @var $component CRM_Core_Component_Info */
2060 $counts = array_merge($counts, $component->getReferenceCounts($this));
2061 }
2062 CRM_Utils_Hook::referenceCounts($this, $counts);
2063
2064 return $counts;
2065 }
2066
2067 /**
2068 * List all tables which have hard foreign keys to this table.
2069 *
2070 * For now, this returns a description of every entity_id/entity_table
2071 * reference.
2072 * TODO: filter dynamic entity references on the $tableName, based on
2073 * schema metadata in dynamicForeignKey which enumerates a restricted
2074 * set of possible entity_table's.
2075 *
2076 * @param string $tableName
2077 * Table referred to.
2078 *
2079 * @return array
2080 * structure of table and column, listing every table with a
2081 * foreign key reference to $tableName, and the column where the key appears.
2082 */
2083 public static function getReferencesToTable($tableName) {
2084 $refsFound = array();
2085 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
2086 $links = $daoClassName::getReferenceColumns();
2087 $daoTableName = $daoClassName::getTableName();
2088
2089 foreach ($links as $refSpec) {
2090 /** @var $refSpec CRM_Core_Reference_Interface */
2091 if ($refSpec->matchesTargetTable($tableName)) {
2092 $refsFound[] = $refSpec;
2093 }
2094 }
2095 }
2096 return $refsFound;
2097 }
2098
2099 /**
2100 * Lookup the value of a MySQL global configuration variable.
2101 *
2102 * @param string $name
2103 * E.g. "thread_stack".
2104 * @param mixed $default
2105 * @return mixed
2106 */
2107 public static function getGlobalSetting($name, $default = NULL) {
2108 // Alternatively, SELECT @@GLOBAL.thread_stack, but
2109 // that has been reported to fail under MySQL 5.0 for OS X
2110 $escapedName = self::escapeString($name);
2111 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
2112 if ($dao->fetch()) {
2113 return $dao->Value;
2114 }
2115 else {
2116 return $default;
2117 }
2118 }
2119
2120 /**
2121 * Get options for the called BAO object's field.
2122 * This function can be overridden by each BAO to add more logic related to context.
2123 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
2124 *
2125 * @param string $fieldName
2126 * @param string $context
2127 * @see CRM_Core_DAO::buildOptionsContext
2128 * @param array $props
2129 * whatever is known about this bao object.
2130 *
2131 * @return array|bool
2132 */
2133 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2134 // If a given bao does not override this function
2135 $baoName = get_called_class();
2136 return CRM_Core_PseudoConstant::get($baoName, $fieldName, array(), $context);
2137 }
2138
2139 /**
2140 * Populate option labels for this object's fields.
2141 *
2142 * @throws exception if called directly on the base class
2143 */
2144 public function getOptionLabels() {
2145 $fields = $this->fields();
2146 if ($fields === NULL) {
2147 throw new Exception('Cannot call getOptionLabels on CRM_Core_DAO');
2148 }
2149 foreach ($fields as $field) {
2150 $name = CRM_Utils_Array::value('name', $field);
2151 if ($name && isset($this->$name)) {
2152 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
2153 if ($label !== FALSE) {
2154 // Append 'label' onto the field name
2155 $labelName = $name . '_label';
2156 $this->$labelName = $label;
2157 }
2158 }
2159 }
2160 }
2161
2162 /**
2163 * Provides documentation and validation for the buildOptions $context param
2164 *
2165 * @param string $context
2166 *
2167 * @throws Exception
2168 * @return array
2169 */
2170 public static function buildOptionsContext($context = NULL) {
2171 $contexts = array(
2172 'get' => "All options are returned, even if they are disabled. Labels are translated.",
2173 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
2174 'search' => "Searchable options are returned. Labels are translated.",
2175 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
2176 );
2177 // Validation: enforce uniformity of this param
2178 if ($context !== NULL && !isset($contexts[$context])) {
2179 throw new Exception("'$context' is not a valid context for buildOptions.");
2180 }
2181 return $contexts;
2182 }
2183
2184 /**
2185 * @param string $fieldName
2186 * @return bool|array
2187 */
2188 public function getFieldSpec($fieldName) {
2189 $fields = $this->fields();
2190 $fieldKeys = $this->fieldKeys();
2191
2192 // Support "unique names" as well as sql names
2193 $fieldKey = $fieldName;
2194 if (empty($fields[$fieldKey])) {
2195 $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys);
2196 }
2197 // If neither worked then this field doesn't exist. Return false.
2198 if (empty($fields[$fieldKey])) {
2199 return FALSE;
2200 }
2201 return $fields[$fieldKey];
2202 }
2203
2204 /**
2205 * SQL version of api function to assign filters to the DAO based on the syntax
2206 * $field => array('IN' => array(4,6,9))
2207 * OR
2208 * $field => array('LIKE' => array('%me%))
2209 * etc
2210 *
2211 * @param string $fieldName
2212 * Name of fields.
2213 * @param array $filter
2214 * filter to be applied indexed by operator.
2215 * @param string $type
2216 * type of field (not actually used - nor in api @todo ).
2217 * @param string $alias
2218 * alternative field name ('as') @todo- not actually used.
2219 * @param bool $returnSanitisedArray
2220 * Return a sanitised array instead of a clause.
2221 * this is primarily so we can add filters @ the api level to the Query object based fields
2222 *
2223 * @throws Exception
2224 *
2225 * @todo a better solution would be for the query object to apply these filters based on the
2226 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2227 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2228 * required to extend further & it may be the comments per above should be implemented. It may be
2229 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2230 * in one place has some advantages as we try to extend this format
2231 *
2232 * @return NULL|string|array
2233 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2234 * depending on whether it is supported as yet
2235 */
2236 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2237 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2238 // support for other syntaxes is discussed in ticket but being put off for now
2239 foreach ($filter as $operator => $criteria) {
2240 if (in_array($operator, self::acceptedSQLOperators())) {
2241 switch ($operator) {
2242 // unary operators
2243 case 'IS NULL':
2244 case 'IS NOT NULL':
2245 if (!$returnSanitisedArray) {
2246 return (sprintf('%s %s', $fieldName, $operator));
2247 }
2248 else {
2249 return (sprintf('%s %s ', $fieldName, $operator));
2250 }
2251 break;
2252
2253 // ternary operators
2254 case 'BETWEEN':
2255 case 'NOT BETWEEN':
2256 if (empty($criteria[0]) || empty($criteria[1])) {
2257 throw new Exception("invalid criteria for $operator");
2258 }
2259 if (!$returnSanitisedArray) {
2260 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
2261 }
2262 else {
2263 return NULL; // not yet implemented (tests required to implement)
2264 }
2265 break;
2266
2267 // n-ary operators
2268 case 'IN':
2269 case 'NOT IN':
2270 if (empty($criteria)) {
2271 throw new Exception("invalid criteria for $operator");
2272 }
2273 $escapedCriteria = array_map(array(
2274 'CRM_Core_DAO',
2275 'escapeString',
2276 ), $criteria);
2277 if (!$returnSanitisedArray) {
2278 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2279 }
2280 return $escapedCriteria;
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 }