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