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