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