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