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