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