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