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