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