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