CRM-16373 - Config - Migrate fiscalYearStart
[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 * $Id$
34 *
35 */
36
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
39
40 require_once 'CRM/Core/I18n.php';
41
42 /**
43 * Class CRM_Core_DAO
44 */
45 class CRM_Core_DAO extends DB_DataObject {
46
47 /**
48 * A null object so we can pass it as reference if / when needed
49 */
50 static $_nullObject = NULL;
51 static $_nullArray = array();
52
53 static $_dbColumnValueCache = NULL;
54 const NOT_NULL = 1, IS_NULL = 2,
55 DB_DAO_NOTNULL = 128,
56 VALUE_SEPARATOR = "\ 1",
57 BULK_INSERT_COUNT = 200,
58 BULK_INSERT_HIGH_COUNT = 200,
59 // special value for mail bulk inserts to avoid
60 // potential duplication, assuming a smaller number reduces number of queries
61 // by some factor, so some tradeoff. CRM-8678
62 BULK_MAIL_INSERT_COUNT = 10,
63 QUERY_FORMAT_WILDCARD = 1,
64 QUERY_FORMAT_NO_QUOTES = 2;
65
66 /**
67 * Define entities that shouldn't be created or deleted when creating/ deleting
68 * test objects - this prevents world regions, countries etc from being added / deleted
69 * @var array
70 */
71 static $_testEntitiesToSkip = array();
72 /**
73 * The factory class for this application.
74 * @var object
75 */
76 static $_factory = NULL;
77
78 static $_checkedSqlFunctionsExist = FALSE;
79
80 /**
81 * Class constructor.
82 *
83 * @return \CRM_Core_DAO
84 */
85 public function __construct() {
86 $this->initialize();
87 $this->__table = $this->getTableName();
88 }
89
90 /**
91 * Empty definition for virtual function.
92 */
93 public static function getTableName() {
94 return NULL;
95 }
96
97 /**
98 * Initialize the DAO object.
99 *
100 * @param string $dsn
101 * The database connection string.
102 *
103 * @return void
104 */
105 public static function init($dsn) {
106 $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
107 $options['database'] = $dsn;
108 if (defined('CIVICRM_DAO_DEBUG')) {
109 self::DebugLevel(CIVICRM_DAO_DEBUG);
110 }
111 }
112
113 /**
114 * @param string $fieldName
115 * @param $fieldDef
116 * @param array $params
117 */
118 protected function assignTestFK($fieldName, $fieldDef, $params) {
119 $required = CRM_Utils_Array::value('required', $fieldDef);
120 $FKClassName = CRM_Utils_Array::value('FKClassName', $fieldDef);
121 $dbName = $fieldDef['name'];
122 $daoName = str_replace('_BAO_', '_DAO_', get_class($this));
123
124 // skip the FK if it is not required
125 // if it's contact id we should create even if not required
126 // we'll have a go @ fetching first though
127 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
128 if ($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
129 $required = TRUE;
130 }
131 if (!$required && $dbName != 'contact_id') {
132 $fkDAO = new $FKClassName();
133 if ($fkDAO->find(TRUE)) {
134 $this->$dbName = $fkDAO->id;
135 }
136 unset($fkDAO);
137 }
138
139 elseif (in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)) {
140 $depObject = new $FKClassName();
141 $depObject->find(TRUE);
142 $this->$dbName = $depObject->id;
143 unset($depObject);
144 }
145 elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $fieldName == 'member_of_contact_id') {
146 // FIXME: the fields() metadata is not specific enough
147 $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
148 $this->$dbName = $depObject->id;
149 unset($depObject);
150 }
151 else {
152 //if it is required we need to generate the dependency object first
153 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
154 $this->$dbName = $depObject->id;
155 unset($depObject);
156 }
157 }
158
159 /**
160 * Generate and assign an arbitrary value to a field of a test object.
161 *
162 * @param string $fieldName
163 * @param array $fieldDef
164 * @param int $counter
165 * The globally-unique ID of the test object.
166 */
167 protected function assignTestValue($fieldName, &$fieldDef, $counter) {
168 $dbName = $fieldDef['name'];
169 $daoName = get_class($this);
170 $handled = FALSE;
171
172 if (!$handled && $dbName == 'contact_sub_type') {
173 //coming up with a rule to set this is too complex let's not set it
174 $handled = TRUE;
175 }
176
177 // Pick an option value if needed
178 if (!$handled && $fieldDef['type'] !== CRM_Utils_Type::T_BOOLEAN) {
179 $options = $daoName::buildOptions($dbName, 'create');
180 if ($options) {
181 $this->$dbName = key($options);
182 $handled = TRUE;
183 }
184 }
185
186 if (!$handled) {
187 switch ($fieldDef['type']) {
188 case CRM_Utils_Type::T_INT:
189 case CRM_Utils_Type::T_FLOAT:
190 case CRM_Utils_Type::T_MONEY:
191 if (isset($fieldDef['precision'])) {
192 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
193 $this->$dbName = CRM_Utils_Number::createTruncatedDecimal($counter, $fieldDef['precision']);
194 }
195 else {
196 $this->$dbName = $counter;
197 }
198 break;
199
200 case CRM_Utils_Type::T_BOOLEAN:
201 if (isset($fieldDef['default'])) {
202 $this->$dbName = $fieldDef['default'];
203 }
204 elseif ($fieldDef['name'] == 'is_deleted' || $fieldDef['name'] == 'is_test') {
205 $this->$dbName = 0;
206 }
207 else {
208 $this->$dbName = 1;
209 }
210 break;
211
212 case CRM_Utils_Type::T_DATE:
213 case CRM_Utils_Type::T_TIMESTAMP:
214 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
215 $this->$dbName = '19700101';
216 if ($dbName == 'end_date') {
217 // put this in the future
218 $this->$dbName = '20200101';
219 }
220 break;
221
222 case CRM_Utils_Type::T_TIME:
223 CRM_Core_Error::fatal("T_TIME 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. DAO is kinda crappy in that there is an unwritten
271 * rule of one query per DAO. We attempt to get around this crappy restricrion
272 * by resetting some of DAO's internal fields. Use this with caution
273 *
274 * @return void
275 */
276 public function reset() {
277
278 foreach (array_keys($this->table()) as $field) {
279 unset($this->$field);
280 }
281
282 /**
283 * reset the various DB_DAO structures manually
284 */
285 $this->_query = array();
286 $this->whereAdd();
287 $this->selectAdd();
288 $this->joinAdd();
289 }
290
291 /**
292 * @param string $tableName
293 *
294 * @return string
295 */
296 public static function getLocaleTableName($tableName) {
297 global $dbLocale;
298 if ($dbLocale) {
299 $tables = CRM_Core_I18n_Schema::schemaStructureTables();
300 if (in_array($tableName, $tables)) {
301 return $tableName . $dbLocale;
302 }
303 }
304 return $tableName;
305 }
306
307 /**
308 * Execute a query by the current DAO, localizing it along the way (if needed).
309 *
310 * @param string $query
311 * The SQL query for execution.
312 * @param bool $i18nRewrite
313 * Whether to rewrite the query.
314 *
315 * @return object
316 * the current DAO object after the query execution
317 */
318 public function query($query, $i18nRewrite = TRUE) {
319 // rewrite queries that should use $dbLocale-based views for multi-language installs
320 global $dbLocale;
321 if ($i18nRewrite and $dbLocale) {
322 $query = CRM_Core_I18n_Schema::rewriteQuery($query);
323 }
324
325 return parent::query($query);
326 }
327
328 /**
329 * Static function to set the factory instance for this class.
330 *
331 * @param object $factory
332 * The factory application object.
333 *
334 * @return void
335 */
336 public static function setFactory(&$factory) {
337 self::$_factory = &$factory;
338 }
339
340 /**
341 * Factory method to instantiate a new object from a table name.
342 *
343 * @param string $table
344 *
345 * @return void
346 */
347 public function factory($table = '') {
348 if (!isset(self::$_factory)) {
349 return parent::factory($table);
350 }
351
352 return self::$_factory->create($table);
353 }
354
355 /**
356 * Initialization for all DAO objects. Since we access DB_DO programatically
357 * we need to set the links manually.
358 *
359 * @return void
360 */
361 public function initialize() {
362 $this->_connect();
363 $this->query("SET NAMES utf8");
364 }
365
366 /**
367 * Defines the default key as 'id'.
368 *
369 *
370 * @return array
371 */
372 public function keys() {
373 static $keys;
374 if (!isset($keys)) {
375 $keys = array('id');
376 }
377 return $keys;
378 }
379
380 /**
381 * Tells DB_DataObject which keys use autoincrement.
382 * 'id' is autoincrementing by default.
383 *
384 *
385 * @return array
386 */
387 public function sequenceKey() {
388 static $sequenceKeys;
389 if (!isset($sequenceKeys)) {
390 $sequenceKeys = array('id', TRUE);
391 }
392 return $sequenceKeys;
393 }
394
395 /**
396 * Returns list of FK relationships.
397 *
398 *
399 * @return array
400 * Array of CRM_Core_Reference_Interface
401 */
402 public static function getReferenceColumns() {
403 return array();
404 }
405
406 /**
407 * Returns all the column names of this table.
408 *
409 *
410 * @return array
411 */
412 public static function &fields() {
413 $result = NULL;
414 return $result;
415 }
416
417 /**
418 * Get/set an associative array of table columns
419 *
420 * @return array
421 * (associative)
422 */
423 public function table() {
424 $fields = &$this->fields();
425
426 $table = array();
427 if ($fields) {
428 foreach ($fields as $name => $value) {
429 $table[$value['name']] = $value['type'];
430 if (!empty($value['required'])) {
431 $table[$value['name']] += self::DB_DAO_NOTNULL;
432 }
433 }
434 }
435
436 return $table;
437 }
438
439 /**
440 * @return $this
441 */
442 public function save() {
443 if (!empty($this->id)) {
444 $this->update();
445
446 $event = new \Civi\Core\DAO\Event\PostUpdate($this);
447 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-update", $event);
448 }
449 else {
450 $this->insert();
451
452 $event = new \Civi\Core\DAO\Event\PostUpdate($this);
453 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-insert", $event);
454 }
455 $this->free();
456
457 CRM_Utils_Hook::postSave($this);
458
459 return $this;
460 }
461
462 /**
463 * Deletes items from table which match current objects variables.
464 *
465 * Returns the true on success
466 *
467 * for example
468 *
469 * Designed to be extended
470 *
471 * $object = new mytable();
472 * $object->ID=123;
473 * echo $object->delete(); // builds a conditon
474 *
475 * $object = new mytable();
476 * $object->whereAdd('age > 12');
477 * $object->limit(1);
478 * $object->orderBy('age DESC');
479 * $object->delete(true); // dont use object vars, use the conditions, limit and order.
480 *
481 * @param bool $useWhere (optional) If DB_DATAOBJECT_WHEREADD_ONLY is passed in then
482 * we will build the condition only using the whereAdd's. Default is to
483 * build the condition only using the object parameters.
484 *
485 * * @return mixed Int (No. of rows affected) on success, false on failure, 0 on no data affected
486 */
487 public function delete($useWhere = FALSE) {
488 $result = parent::delete($useWhere);
489
490 $event = new \Civi\Core\DAO\Event\PostDelete($this, $result);
491 \Civi\Core\Container::singleton()->get('dispatcher')->dispatch("DAO::post-delete", $event);
492
493 return $result;
494 }
495
496 /**
497 * @param bool $created
498 */
499 public function log($created = FALSE) {
500 static $cid = NULL;
501
502 if (!$this->getLog()) {
503 return;
504 }
505
506 if (!$cid) {
507 $session = CRM_Core_Session::singleton();
508 $cid = $session->get('userID');
509 }
510
511 // return is we dont have handle to FK
512 if (!$cid) {
513 return;
514 }
515
516 $dao = new CRM_Core_DAO_Log();
517 $dao->entity_table = $this->getTableName();
518 $dao->entity_id = $this->id;
519 $dao->modified_id = $cid;
520 $dao->modified_date = date("YmdHis");
521 $dao->insert();
522 }
523
524 /**
525 * Given an associative array of name/value pairs, extract all the values
526 * that belong to this object and initialize the object with said values
527 *
528 * @param array $params
529 * (reference ) associative array of name/value pairs.
530 *
531 * @return bool
532 * Did we copy all null values into the object
533 */
534 public function copyValues(&$params) {
535 $fields = &$this->fields();
536 $allNull = TRUE;
537 foreach ($fields as $name => $value) {
538 $dbName = $value['name'];
539 if (array_key_exists($dbName, $params)) {
540 $pValue = $params[$dbName];
541 $exists = TRUE;
542 }
543 elseif (array_key_exists($name, $params)) {
544 $pValue = $params[$name];
545 $exists = TRUE;
546 }
547 else {
548 $exists = FALSE;
549 }
550
551 // if there is no value then make the variable NULL
552 if ($exists) {
553 if ($pValue === '') {
554 $this->$dbName = 'null';
555 }
556 else {
557 $this->$dbName = $pValue;
558 $allNull = FALSE;
559 }
560 }
561 }
562 return $allNull;
563 }
564
565 /**
566 * Store all the values from this object in an associative array
567 * this is a destructive store, calling function is responsible
568 * for keeping sanity of id's.
569 *
570 * @param object $object
571 * The object that we are extracting data from.
572 * @param array $values
573 * (reference ) associative array of name/value pairs.
574 *
575 * @return void
576 */
577 public static function storeValues(&$object, &$values) {
578 $fields = &$object->fields();
579 foreach ($fields as $name => $value) {
580 $dbName = $value['name'];
581 if (isset($object->$dbName) && $object->$dbName !== 'null') {
582 $values[$dbName] = $object->$dbName;
583 if ($name != $dbName) {
584 $values[$name] = $object->$dbName;
585 }
586 }
587 }
588 }
589
590 /**
591 * Create an attribute for this specific field. We only do this for strings and text
592 *
593 * @param array $field
594 * The field under task.
595 *
596 * @return array|null
597 * the attributes for the object
598 */
599 public static function makeAttribute($field) {
600 if ($field) {
601 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
602 $maxLength = CRM_Utils_Array::value('maxlength', $field);
603 $size = CRM_Utils_Array::value('size', $field);
604 if ($maxLength || $size) {
605 $attributes = array();
606 if ($maxLength) {
607 $attributes['maxlength'] = $maxLength;
608 }
609 if ($size) {
610 $attributes['size'] = $size;
611 }
612 return $attributes;
613 }
614 }
615 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) {
616 $rows = CRM_Utils_Array::value('rows', $field);
617 if (!isset($rows)) {
618 $rows = 2;
619 }
620 $cols = CRM_Utils_Array::value('cols', $field);
621 if (!isset($cols)) {
622 $cols = 80;
623 }
624
625 $attributes = array();
626 $attributes['rows'] = $rows;
627 $attributes['cols'] = $cols;
628 return $attributes;
629 }
630 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) {
631 $attributes['size'] = 6;
632 $attributes['maxlength'] = 14;
633 return $attributes;
634 }
635 }
636 return NULL;
637 }
638
639 /**
640 * Get the size and maxLength attributes for this text field.
641 * (or for all text fields) in the DAO object.
642 *
643 * @param string $class
644 * Name of DAO class.
645 * @param string $fieldName
646 * Field that i'm interested in or null if.
647 * you want the attributes for all DAO text fields
648 *
649 * @return array
650 * assoc array of name => attribute pairs
651 */
652 public static function getAttribute($class, $fieldName = NULL) {
653 $object = new $class();
654 $fields = &$object->fields();
655 if ($fieldName != NULL) {
656 $field = CRM_Utils_Array::value($fieldName, $fields);
657 return self::makeAttribute($field);
658 }
659 else {
660 $attributes = array();
661 foreach ($fields as $name => $field) {
662 $attribute = self::makeAttribute($field);
663 if ($attribute) {
664 $attributes[$name] = $attribute;
665 }
666 }
667
668 if (!empty($attributes)) {
669 return $attributes;
670 }
671 }
672 return NULL;
673 }
674
675 /**
676 * @param $type
677 *
678 * @throws Exception
679 */
680 public static function transaction($type) {
681 CRM_Core_Error::fatal('This function is obsolete, please use CRM_Core_Transaction');
682 }
683
684 /**
685 * Check if there is a record with the same name in the db.
686 *
687 * @param string $value
688 * The value of the field we are checking.
689 * @param string $daoName
690 * The dao object name.
691 * @param string $daoID
692 * The id of the object being updated. u can change your name.
693 * as long as there is no conflict
694 * @param string $fieldName
695 * The name of the field in the DAO.
696 *
697 * @return bool
698 * true if object exists
699 */
700 public static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
701 $object = new $daoName();
702 $object->$fieldName = $value;
703
704 $config = CRM_Core_Config::singleton();
705
706 if ($object->find(TRUE)) {
707 return ($daoID && $object->id == $daoID) ? TRUE : FALSE;
708 }
709 else {
710 return TRUE;
711 }
712 }
713
714 /**
715 * Check if there is a given column in a specific table.
716 *
717 * @param string $tableName
718 * @param string $columnName
719 * @param bool $i18nRewrite
720 * Whether to rewrite the query on multilingual setups.
721 *
722 * @return bool
723 * true if exists, else false
724 */
725 public static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
726 $query = "
727 SHOW COLUMNS
728 FROM $tableName
729 LIKE %1
730 ";
731 $params = array(1 => array($columnName, 'String'));
732 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
733 $result = $dao->fetch() ? TRUE : FALSE;
734 $dao->free();
735 return $result;
736 }
737
738 /**
739 * Returns the storage engine used by given table-name(optional).
740 * Otherwise scans all the tables and return an array of all the
741 * distinct storage engines being used.
742 *
743 * @param string $tableName
744 *
745 * @param int $maxTablesToCheck
746 * @param string $fieldName
747 *
748 * @return array
749 */
750 public static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
751 $values = array();
752 $query = "SHOW TABLE STATUS LIKE %1";
753
754 $params = array();
755
756 if (isset($tableName)) {
757 $params = array(1 => array($tableName, 'String'));
758 }
759 else {
760 $params = array(1 => array('civicrm_%', 'String'));
761 }
762
763 $dao = CRM_Core_DAO::executeQuery($query, $params);
764
765 $count = 0;
766 while ($dao->fetch()) {
767 if (isset($values[$dao->$fieldName]) ||
768 // ignore import and other temp tables
769 strpos($dao->Name, 'civicrm_import_job_') !== FALSE ||
770 strpos($dao->Name, '_temp') !== FALSE
771 ) {
772 continue;
773 }
774 $values[$dao->$fieldName] = 1;
775 $count++;
776 if ($maxTablesToCheck &&
777 $count >= $maxTablesToCheck
778 ) {
779 break;
780 }
781 }
782 $dao->free();
783 return $values;
784 }
785
786 /**
787 * @param int $maxTablesToCheck
788 *
789 * @return bool
790 */
791 public static function isDBMyISAM($maxTablesToCheck = 10) {
792 // show error if any of the tables, use 'MyISAM' storage engine.
793 $engines = self::getStorageValues(NULL, $maxTablesToCheck);
794 if (array_key_exists('MyISAM', $engines)) {
795 return TRUE;
796 }
797 return FALSE;
798 }
799
800 /**
801 * Checks if a constraint exists for a specified table.
802 *
803 * @param string $tableName
804 * @param string $constraint
805 *
806 * @return bool
807 * true if constraint exists, false otherwise
808 */
809 public static function checkConstraintExists($tableName, $constraint) {
810 static $show = array();
811
812 if (!array_key_exists($tableName, $show)) {
813 $query = "SHOW CREATE TABLE $tableName";
814 $dao = CRM_Core_DAO::executeQuery($query);
815
816 if (!$dao->fetch()) {
817 CRM_Core_Error::fatal();
818 }
819
820 $dao->free();
821 $show[$tableName] = $dao->Create_Table;
822 }
823
824 return preg_match("/\b$constraint\b/i", $show[$tableName]) ? TRUE : FALSE;
825 }
826
827 /**
828 * Checks if CONSTRAINT keyword exists for a specified table.
829 *
830 * @param array $tables
831 *
832 * @throws Exception
833 *
834 * @return bool
835 * true if CONSTRAINT keyword exists, false otherwise
836 */
837 public static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
838 $show = array();
839 foreach ($tables as $tableName) {
840 if (!array_key_exists($tableName, $show)) {
841 $query = "SHOW CREATE TABLE $tableName";
842 $dao = CRM_Core_DAO::executeQuery($query);
843
844 if (!$dao->fetch()) {
845 CRM_Core_Error::fatal();
846 }
847
848 $dao->free();
849 $show[$tableName] = $dao->Create_Table;
850 }
851
852 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ? TRUE : FALSE;
853 if ($result == TRUE) {
854 continue;
855 }
856 else {
857 return FALSE;
858 }
859 }
860 return TRUE;
861 }
862
863 /**
864 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
865 * for a specified column of a table.
866 *
867 * @param string $tableName
868 * @param string $columnName
869 *
870 * @return bool
871 * true if in format, false otherwise
872 */
873 public static function checkFKConstraintInFormat($tableName, $columnName) {
874 static $show = array();
875
876 if (!array_key_exists($tableName, $show)) {
877 $query = "SHOW CREATE TABLE $tableName";
878 $dao = CRM_Core_DAO::executeQuery($query);
879
880 if (!$dao->fetch()) {
881 CRM_Core_Error::fatal();
882 }
883
884 $dao->free();
885 $show[$tableName] = $dao->Create_Table;
886 }
887 $constraint = "`FK_{$tableName}_{$columnName}`";
888 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
889 return preg_match(sprintf($pattern, $constraint), $show[$tableName]) ? TRUE : FALSE;
890 }
891
892 /**
893 * Check whether a specific column in a specific table has always the same value.
894 *
895 * @param string $tableName
896 * @param string $columnName
897 * @param string $columnValue
898 *
899 * @return bool
900 * true if the value is always $columnValue, false otherwise
901 */
902 public static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
903 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
904 $dao = CRM_Core_DAO::executeQuery($query);
905 $result = $dao->fetch() ? FALSE : TRUE;
906 $dao->free();
907 return $result;
908 }
909
910 /**
911 * Check whether a specific column in a specific table is always NULL.
912 *
913 * @param string $tableName
914 * @param string $columnName
915 *
916 * @return bool
917 * true if if the value is always NULL, false otherwise
918 */
919 public static function checkFieldIsAlwaysNull($tableName, $columnName) {
920 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
921 $dao = CRM_Core_DAO::executeQuery($query);
922 $result = $dao->fetch() ? FALSE : TRUE;
923 $dao->free();
924 return $result;
925 }
926
927 /**
928 * Check if there is a given table in the database.
929 *
930 * @param string $tableName
931 *
932 * @return bool
933 * true if exists, else false
934 */
935 public static function checkTableExists($tableName) {
936 $query = "
937 SHOW TABLES
938 LIKE %1
939 ";
940 $params = array(1 => array($tableName, 'String'));
941
942 $dao = CRM_Core_DAO::executeQuery($query, $params);
943 $result = $dao->fetch() ? TRUE : FALSE;
944 $dao->free();
945 return $result;
946 }
947
948 /**
949 * @param $version
950 *
951 * @return bool
952 */
953 public function checkVersion($version) {
954 $query = "
955 SELECT version
956 FROM civicrm_domain
957 ";
958 $dbVersion = CRM_Core_DAO::singleValueQuery($query);
959 return trim($version) == trim($dbVersion) ? TRUE : FALSE;
960 }
961
962 /**
963 * Find a DAO object for the given ID and return it.
964 *
965 * @param int $id
966 * Id of the DAO object being searched for.
967 *
968 * @return object
969 * Object of the type of the class that called this function.
970 */
971 public static function findById($id) {
972 $object = new static();
973 $object->id = $id;
974 if (!$object->find(TRUE)) {
975 throw new Exception("Unable to find a " . get_called_class() . " with id {$id}.");
976 }
977 return $object;
978 }
979
980 /**
981 * Returns all results as array-encoded records.
982 *
983 * @return array
984 */
985 public function fetchAll() {
986 $result = array();
987 while ($this->fetch()) {
988 $result[] = $this->toArray();
989 }
990 return $result;
991 }
992
993 /**
994 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
995 *
996 * @param string $daoName
997 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
998 * @param int $searchValue
999 * Value of the column you want to search by.
1000 * @param string $returnColumn
1001 * Name of the column you want to GET the value of.
1002 * @param string $searchColumn
1003 * Name of the column you want to search by.
1004 * @param bool $force
1005 * Skip use of the cache.
1006 *
1007 * @return string|null
1008 * Value of $returnColumn in the retrieved record
1009 */
1010 public static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
1011 if (
1012 empty($searchValue) ||
1013 trim(strtolower($searchValue)) == 'null'
1014 ) {
1015 // adding this year since developers forget to check for an id
1016 // or for the 'null' (which is a bad DAO kludge)
1017 // and hence we get the first value in the db
1018 CRM_Core_Error::fatal();
1019 }
1020
1021 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
1022 if (self::$_dbColumnValueCache === NULL) {
1023 self::$_dbColumnValueCache = array();
1024 }
1025
1026 if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
1027 $object = new $daoName();
1028 $object->$searchColumn = $searchValue;
1029 $object->selectAdd();
1030 $object->selectAdd($returnColumn);
1031
1032 $result = NULL;
1033 if ($object->find(TRUE)) {
1034 $result = $object->$returnColumn;
1035 }
1036 $object->free();
1037
1038 self::$_dbColumnValueCache[$cacheKey] = $result;
1039 }
1040 return self::$_dbColumnValueCache[$cacheKey];
1041 }
1042
1043 /**
1044 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
1045 *
1046 * @param string $daoName
1047 * Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact).
1048 * @param int $searchValue
1049 * Value of the column you want to search by.
1050 * @param string $setColumn
1051 * Name of the column you want to SET the value of.
1052 * @param string $setValue
1053 * SET the setColumn to this value.
1054 * @param string $searchColumn
1055 * Name of the column you want to search by.
1056 *
1057 * @return bool
1058 * true if we found and updated the object, else false
1059 */
1060 public static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
1061 $object = new $daoName();
1062 $object->selectAdd();
1063 $object->selectAdd("$searchColumn, $setColumn");
1064 $object->$searchColumn = $searchValue;
1065 $result = FALSE;
1066 if ($object->find(TRUE)) {
1067 $object->$setColumn = $setValue;
1068 if ($object->save()) {
1069 $result = TRUE;
1070 }
1071 }
1072 $object->free();
1073 return $result;
1074 }
1075
1076 /**
1077 * Get sort string.
1078 *
1079 * @param array|object $sort either array or CRM_Utils_Sort
1080 * @param string $default
1081 * Default sort value.
1082 *
1083 * @return string
1084 * sortString
1085 */
1086 public static function getSortString($sort, $default = NULL) {
1087 // check if sort is of type CRM_Utils_Sort
1088 if (is_a($sort, 'CRM_Utils_Sort')) {
1089 return $sort->orderBy();
1090 }
1091
1092 // is it an array specified as $field => $sortDirection ?
1093 if ($sort) {
1094 foreach ($sort as $k => $v) {
1095 $sortString .= "$k $v,";
1096 }
1097 return rtrim($sortString, ',');
1098 }
1099 return $default;
1100 }
1101
1102 /**
1103 * Fetch object based on array of properties.
1104 *
1105 * @param string $daoName
1106 * Name of the dao object.
1107 * @param array $params
1108 * (reference ) an assoc array of name/value pairs.
1109 * @param array $defaults
1110 * (reference ) an assoc array to hold the flattened values.
1111 * @param array $returnProperities
1112 * An assoc array of fields that need to be returned, eg array( 'first_name', 'last_name').
1113 *
1114 * @return object
1115 * an object of type referenced by daoName
1116 */
1117 public static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
1118 $object = new $daoName();
1119 $object->copyValues($params);
1120
1121 // return only specific fields if returnproperties are sent
1122 if (!empty($returnProperities)) {
1123 $object->selectAdd();
1124 $object->selectAdd(implode(',', $returnProperities));
1125 }
1126
1127 if ($object->find(TRUE)) {
1128 self::storeValues($object, $defaults);
1129 return $object;
1130 }
1131 return NULL;
1132 }
1133
1134 /**
1135 * Delete the object records that are associated with this contact.
1136 *
1137 * @param string $daoName
1138 * Name of the dao object.
1139 * @param int $contactId
1140 * Id of the contact to delete.
1141 *
1142 * @return void
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 * SQL version of api function to assign filters to the DAO based on the syntax
2256 * $field => array('IN' => array(4,6,9))
2257 * OR
2258 * $field => array('LIKE' => array('%me%))
2259 * etc
2260 *
2261 * @param string $fieldName
2262 * Name of fields.
2263 * @param array $filter
2264 * filter to be applied indexed by operator.
2265 * @param string $type
2266 * type of field (not actually used - nor in api @todo ).
2267 * @param string $alias
2268 * alternative field name ('as') @todo- not actually used.
2269 * @param bool $returnSanitisedArray
2270 * Return a sanitised array instead of a clause.
2271 * this is primarily so we can add filters @ the api level to the Query object based fields
2272 *
2273 * @throws Exception
2274 *
2275 * @todo a better solution would be for the query object to apply these filters based on the
2276 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
2277 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
2278 * required to extend further & it may be the comments per above should be implemented. It may be
2279 * preferable to not double-banger the return context next refactor of this - but keeping the attention
2280 * in one place has some advantages as we try to extend this format
2281 *
2282 * @return NULL|string|array
2283 * a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
2284 * depending on whether it is supported as yet
2285 */
2286 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
2287 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
2288 // support for other syntaxes is discussed in ticket but being put off for now
2289 foreach ($filter as $operator => $criteria) {
2290 if (in_array($operator, self::acceptedSQLOperators(), TRUE)) {
2291 switch ($operator) {
2292 // unary operators
2293 case 'IS NULL':
2294 case 'IS NOT NULL':
2295 if (!$returnSanitisedArray) {
2296 return (sprintf('%s %s', $fieldName, $operator));
2297 }
2298 else {
2299 return (sprintf('%s %s ', $fieldName, $operator));
2300 }
2301 break;
2302
2303 // ternary operators
2304 case 'BETWEEN':
2305 case 'NOT BETWEEN':
2306 if (empty($criteria[0]) || empty($criteria[1])) {
2307 throw new Exception("invalid criteria for $operator");
2308 }
2309 if (!$returnSanitisedArray) {
2310 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
2311 }
2312 else {
2313 return NULL; // not yet implemented (tests required to implement)
2314 }
2315 break;
2316
2317 // n-ary operators
2318 case 'IN':
2319 case 'NOT IN':
2320 if (empty($criteria)) {
2321 throw new Exception("invalid criteria for $operator");
2322 }
2323 $escapedCriteria = array_map(array(
2324 'CRM_Core_DAO',
2325 'escapeString',
2326 ), $criteria);
2327 if (!$returnSanitisedArray) {
2328 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
2329 }
2330 return $escapedCriteria;
2331
2332 // binary operators
2333
2334 default:
2335 if (!$returnSanitisedArray) {
2336 return (sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
2337 }
2338 else {
2339 return NULL; // not yet implemented (tests required to implement)
2340 }
2341 }
2342 }
2343 }
2344 }
2345
2346 /**
2347 * @see http://issues.civicrm.org/jira/browse/CRM-9150
2348 * support for other syntaxes is discussed in ticket but being put off for now
2349 * @return array
2350 */
2351 public static function acceptedSQLOperators() {
2352 return array(
2353 '=',
2354 '<=',
2355 '>=',
2356 '>',
2357 '<',
2358 'LIKE',
2359 "<>",
2360 "!=",
2361 "NOT LIKE",
2362 'IN',
2363 'NOT IN',
2364 'BETWEEN',
2365 'NOT BETWEEN',
2366 'IS NOT NULL',
2367 'IS NULL',
2368 );
2369 }
2370
2371 /**
2372 * SQL has a limit of 64 characters on various names:
2373 * table name, trigger name, column name ...
2374 *
2375 * For custom groups and fields we generated names from user entered input
2376 * which can be longer than this length, this function helps with creating
2377 * strings that meet various criteria.
2378 *
2379 * @param string $string
2380 * The string to be shortened.
2381 * @param int $length
2382 * The max length of the string.
2383 *
2384 * @param bool $makeRandom
2385 *
2386 * @return string
2387 */
2388 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2389 // early return for strings that meet the requirements
2390 if (strlen($string) <= $length) {
2391 return $string;
2392 }
2393
2394 // easy return for calls that dont need a randomized uniq string
2395 if (!$makeRandom) {
2396 return substr($string, 0, $length);
2397 }
2398
2399 // the string is longer than the length and we need a uniq string
2400 // for the same tablename we need the same uniq string every time
2401 // hence we use md5 on the string, which is not random
2402 // we'll append 8 characters to the end of the tableName
2403 $md5string = substr(md5($string), 0, 8);
2404 return substr($string, 0, $length - 8) . "_{$md5string}";
2405 }
2406
2407 /**
2408 * @param array $params
2409 */
2410 public function setApiFilter(&$params) {
2411 }
2412
2413 }