Changes for generation of Invoice
[civicrm-core.git] / CRM / Core / DAO.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
06b69b18 4 | CiviCRM version 4.5 |
6a488035 5 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
6a488035
TO
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
06b69b18 32 * @copyright CiviCRM LLC (c) 2004-2014
6a488035
TO
33 * $Id$
34 *
35 */
36
37require_once 'PEAR.php';
38require_once 'DB/DataObject.php';
39
40require_once 'CRM/Core/I18n.php';
41class CRM_Core_DAO extends DB_DataObject {
42
43 /**
44 * a null object so we can pass it as reference if / when needed
45 */
46 static $_nullObject = NULL;
47 static $_nullArray = array();
48
49 static $_dbColumnValueCache = NULL;
50 CONST NOT_NULL = 1, IS_NULL = 2,
51 DB_DAO_NOTNULL = 128,
52 VALUE_SEPARATOR = "\ 1",
53 BULK_INSERT_COUNT = 200,
54 BULK_INSERT_HIGH_COUNT = 200,
55 // special value for mail bulk inserts to avoid
56 // potential duplication, assuming a smaller number reduces number of queries
57 // by some factor, so some tradeoff. CRM-8678
887a4028
A
58 BULK_MAIL_INSERT_COUNT = 10,
59 QUERY_FORMAT_WILDCARD = 1,
60 QUERY_FORMAT_NO_QUOTES = 2;
61
6a488035
TO
62 /*
63 * Define entities that shouldn't be created or deleted when creating/ deleting
64 * test objects - this prevents world regions, countries etc from being added / deleted
65 */
66 static $_testEntitiesToSkip = array();
67 /**
68 * the factory class for this application
69 * @var object
70 */
71 static $_factory = NULL;
72
aca2de91
CW
73 static $_checkedSqlFunctionsExist = FALSE;
74
6a488035
TO
75 /**
76 * Class constructor
77 *
77b97be7
EM
78 * @return \CRM_Core_DAO
79 @access public
6a488035
TO
80 */
81 function __construct() {
82 $this->initialize();
83 $this->__table = $this->getTableName();
84 }
85
86 /**
87 * empty definition for virtual function
88 */
89 static function getTableName() {
90 return NULL;
91 }
92
93 /**
94 * initialize the DAO object
95 *
96 * @param string $dsn the database connection string
97 *
98 * @return void
99 * @access private
100 * @static
101 */
102 static function init($dsn) {
103 $options = &PEAR::getStaticProperty('DB_DataObject', 'options');
104 $options['database'] = $dsn;
105 if (defined('CIVICRM_DAO_DEBUG')) {
106 self::DebugLevel(CIVICRM_DAO_DEBUG);
107 }
108 }
109
110 /**
111 * reset the DAO object. DAO is kinda crappy in that there is an unwritten
112 * rule of one query per DAO. We attempt to get around this crappy restricrion
113 * by resetting some of DAO's internal fields. Use this with caution
114 *
115 * @return void
116 * @access public
117 *
118 */
119 function reset() {
120
121 foreach (array_keys($this->table()) as $field) {
122 unset($this->$field);
123 }
124
125 /**
126 * reset the various DB_DAO structures manually
127 */
128 $this->_query = array();
129 $this->whereAdd();
130 $this->selectAdd();
131 $this->joinAdd();
132 }
133
134 static function getLocaleTableName($tableName) {
135 global $dbLocale;
136 if ($dbLocale) {
137 $tables = CRM_Core_I18n_Schema::schemaStructureTables();
138 if (in_array($tableName, $tables)) {
139 return $tableName . $dbLocale;
140 }
141 }
142 return $tableName;
143 }
144
145 /**
146 * Execute a query by the current DAO, localizing it along the way (if needed).
147 *
148 * @param string $query the SQL query for execution
149 * @param bool $i18nRewrite whether to rewrite the query
150 *
151 * @return object the current DAO object after the query execution
152 */
153 function query($query, $i18nRewrite = TRUE) {
154 // rewrite queries that should use $dbLocale-based views for multi-language installs
155 global $dbLocale;
156 if ($i18nRewrite and $dbLocale) {
157 $query = CRM_Core_I18n_Schema::rewriteQuery($query);
158 }
159
160 return parent::query($query);
161 }
162
163 /**
164 * Static function to set the factory instance for this class.
165 *
166 * @param object $factory the factory application object
167 *
168 * @return void
169 * @access public
170 * @static
171 */
172 static function setFactory(&$factory) {
173 self::$_factory = &$factory;
174 }
175
176 /**
177 * Factory method to instantiate a new object from a table name.
178 *
da6b46f4
EM
179 * @param string $table
180 *
6a488035
TO
181 * @return void
182 * @access public
183 */
184 function factory($table = '') {
185 if (!isset(self::$_factory)) {
186 return parent::factory($table);
187 }
188
189 return self::$_factory->create($table);
190 }
191
192 /**
193 * Initialization for all DAO objects. Since we access DB_DO programatically
194 * we need to set the links manually.
195 *
196 * @return void
197 * @access protected
198 */
199 function initialize() {
6a488035 200 $this->_connect();
bf5c2dc5 201 $this->query("SET NAMES utf8");
6a488035
TO
202 }
203
204 /**
205 * Defines the default key as 'id'.
206 *
207 * @access protected
208 *
209 * @return array
210 */
211 function keys() {
212 static $keys;
213 if (!isset($keys)) {
214 $keys = array('id');
215 }
216 return $keys;
217 }
218
219 /**
220 * Tells DB_DataObject which keys use autoincrement.
221 * 'id' is autoincrementing by default.
222 *
223 * @access protected
224 *
225 * @return array
226 */
227 function sequenceKey() {
228 static $sequenceKeys;
229 if (!isset($sequenceKeys)) {
230 $sequenceKeys = array('id', TRUE);
231 }
232 return $sequenceKeys;
233 }
234
235 /**
236 * returns list of FK relationships
237 *
71e5aa5c 238 * @static
6a488035
TO
239 * @access public
240 *
71e5aa5c 241 * @return array of CRM_Core_EntityReference
6a488035 242 */
71e5aa5c
ARW
243 static function getReferenceColumns() {
244 return array();
6a488035
TO
245 }
246
247 /**
248 * returns all the column names of this table
249 *
250 * @access public
251 *
252 * @return array
253 */
254 static function &fields() {
255 $result = NULL;
256 return $result;
257 }
258
259 function table() {
260 $fields = &$this->fields();
261
262 $table = array();
263 if ($fields) {
264 foreach ($fields as $name => $value) {
265 $table[$value['name']] = $value['type'];
a7488080 266 if (!empty($value['required'])) {
6a488035
TO
267 $table[$value['name']] += self::DB_DAO_NOTNULL;
268 }
269 }
270 }
271
6a488035
TO
272 return $table;
273 }
274
275 function save() {
276 if (!empty($this->id)) {
277 $this->update();
278 }
279 else {
280 $this->insert();
281 }
282 $this->free();
283
284 CRM_Utils_Hook::postSave($this);
285
286 return $this;
287 }
288
289 function log($created = FALSE) {
290 static $cid = NULL;
291
292 if (!$this->getLog()) {
293 return;
294 }
295
296 if (!$cid) {
297 $session = CRM_Core_Session::singleton();
298 $cid = $session->get('userID');
299 }
300
301 // return is we dont have handle to FK
302 if (!$cid) {
303 return;
304 }
305
306 $dao = new CRM_Core_DAO_Log();
307 $dao->entity_table = $this->getTableName();
308 $dao->entity_id = $this->id;
309 $dao->modified_id = $cid;
310 $dao->modified_date = date("YmdHis");
311 $dao->insert();
312 }
313
314 /**
315 * Given an associative array of name/value pairs, extract all the values
316 * that belong to this object and initialize the object with said values
317 *
318 * @param array $params (reference ) associative array of name/value pairs
319 *
320 * @return boolean did we copy all null values into the object
321 * @access public
322 */
323 function copyValues(&$params) {
324 $fields = &$this->fields();
325 $allNull = TRUE;
326 foreach ($fields as $name => $value) {
327 $dbName = $value['name'];
328 if (array_key_exists($dbName, $params)) {
329 $pValue = $params[$dbName];
330 $exists = TRUE;
331 }
332 elseif (array_key_exists($name, $params)) {
333 $pValue = $params[$name];
334 $exists = TRUE;
335 }
336 else {
337 $exists = FALSE;
338 }
339
340 // if there is no value then make the variable NULL
341 if ($exists) {
342 if ($pValue === '') {
343 $this->$dbName = 'null';
344 }
345 else {
346 $this->$dbName = $pValue;
347 $allNull = FALSE;
348 }
349 }
350 }
351 return $allNull;
352 }
353
354 /**
355 * Store all the values from this object in an associative array
356 * this is a destructive store, calling function is responsible
357 * for keeping sanity of id's.
358 *
359 * @param object $object the object that we are extracting data from
360 * @param array $values (reference ) associative array of name/value pairs
361 *
362 * @return void
363 * @access public
364 * @static
365 */
366 static function storeValues(&$object, &$values) {
367 $fields = &$object->fields();
368 foreach ($fields as $name => $value) {
369 $dbName = $value['name'];
370 if (isset($object->$dbName) && $object->$dbName !== 'null') {
371 $values[$dbName] = $object->$dbName;
372 if ($name != $dbName) {
373 $values[$name] = $object->$dbName;
374 }
375 }
376 }
377 }
378
379 /**
380 * create an attribute for this specific field. We only do this for strings and text
381 *
382 * @param array $field the field under task
383 *
384 * @return array|null the attributes for the object
385 * @access public
386 * @static
387 */
388 static function makeAttribute($field) {
389 if ($field) {
390 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
391 $maxLength = CRM_Utils_Array::value('maxlength', $field);
392 $size = CRM_Utils_Array::value('size', $field);
393 if ($maxLength || $size) {
394 $attributes = array();
395 if ($maxLength) {
396 $attributes['maxlength'] = $maxLength;
397 }
398 if ($size) {
399 $attributes['size'] = $size;
400 }
401 return $attributes;
402 }
403 }
404 elseif (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_TEXT) {
405 $rows = CRM_Utils_Array::value('rows', $field);
406 if (!isset($rows)) {
407 $rows = 2;
408 }
409 $cols = CRM_Utils_Array::value('cols', $field);
410 if (!isset($cols)) {
411 $cols = 80;
412 }
413
414 $attributes = array();
415 $attributes['rows'] = $rows;
416 $attributes['cols'] = $cols;
417 return $attributes;
418 }
419 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) {
420 $attributes['size'] = 6;
421 $attributes['maxlength'] = 14;
422 return $attributes;
423 }
424 }
425 return NULL;
426 }
427
428 /**
429 * Get the size and maxLength attributes for this text field
430 * (or for all text fields) in the DAO object.
431 *
432 * @param string $class name of DAO class
433 * @param string $fieldName field that i'm interested in or null if
434 * you want the attributes for all DAO text fields
435 *
436 * @return array assoc array of name => attribute pairs
437 * @access public
438 * @static
439 */
440 static function getAttribute($class, $fieldName = NULL) {
441 $object = new $class( );
442 $fields = &$object->fields();
443 if ($fieldName != NULL) {
444 $field = CRM_Utils_Array::value($fieldName, $fields);
445 return self::makeAttribute($field);
446 }
447 else {
448 $attributes = array();
449 foreach ($fields as $name => $field) {
450 $attribute = self::makeAttribute($field);
451 if ($attribute) {
452 $attributes[$name] = $attribute;
453 }
454 }
455
456 if (!empty($attributes)) {
457 return $attributes;
458 }
459 }
460 return NULL;
461 }
462
463 static function transaction($type) {
464 CRM_Core_Error::fatal('This function is obsolete, please use CRM_Core_Transaction');
465 }
466
467 /**
468 * Check if there is a record with the same name in the db
469 *
470 * @param string $value the value of the field we are checking
471 * @param string $daoName the dao object name
472 * @param string $daoID the id of the object being updated. u can change your name
473 * as long as there is no conflict
474 * @param string $fieldName the name of the field in the DAO
475 *
476 * @return boolean true if object exists
477 * @access public
478 * @static
479 */
480 static function objectExists($value, $daoName, $daoID, $fieldName = 'name') {
481 $object = new $daoName( );
482 $object->$fieldName = $value;
483
484 $config = CRM_Core_Config::singleton();
485
486 if ($object->find(TRUE)) {
487 return ($daoID && $object->id == $daoID) ? TRUE : FALSE;
488 }
489 else {
490 return TRUE;
491 }
492 }
493
494 /**
495 * Check if there is a given column in a specific table
496 *
497 * @param string $tableName
498 * @param string $columnName
499 * @param bool $i18nRewrite whether to rewrite the query on multilingual setups
500 *
501 * @return boolean true if exists, else false
502 * @static
503 */
504 static function checkFieldExists($tableName, $columnName, $i18nRewrite = TRUE) {
505 $query = "
506SHOW COLUMNS
507FROM $tableName
508LIKE %1
509";
510 $params = array(1 => array($columnName, 'String'));
511 $dao = CRM_Core_DAO::executeQuery($query, $params, TRUE, NULL, FALSE, $i18nRewrite);
512 $result = $dao->fetch() ? TRUE : FALSE;
513 $dao->free();
514 return $result;
515 }
516
517 /**
518 * Returns the storage engine used by given table-name(optional).
519 * Otherwise scans all the tables and return an array of all the
520 * distinct storage engines being used.
521 *
522 * @param string $tableName
523 *
2a6da8d7
EM
524 * @param int $maxTablesToCheck
525 * @param string $fieldName
526 *
6a488035
TO
527 * @return array
528 * @static
529 */
530 static function getStorageValues($tableName = NULL, $maxTablesToCheck = 10, $fieldName = 'Engine') {
531 $values = array();
532 $query = "SHOW TABLE STATUS LIKE %1";
533
534 $params = array();
535
536 if (isset($tableName)) {
537 $params = array(1 => array($tableName, 'String'));
538 }
539 else {
540 $params = array(1 => array('civicrm_%', 'String'));
541 }
542
543 $dao = CRM_Core_DAO::executeQuery($query, $params);
544
545 $count = 0;
546 while ($dao->fetch()) {
547 if (isset($values[$dao->$fieldName]) ||
548 // ignore import and other temp tables
549 strpos($dao->Name, 'civicrm_import_job_') !== FALSE ||
550 strpos($dao->Name, '_temp') !== FALSE
551 ) {
552 continue;
553 }
554 $values[$dao->$fieldName] = 1;
555 $count++;
556 if ($maxTablesToCheck &&
557 $count >= $maxTablesToCheck
558 ) {
559 break;
560 }
561 }
562 $dao->free();
563 return $values;
564 }
565
566 static function isDBMyISAM($maxTablesToCheck = 10) {
567 // show error if any of the tables, use 'MyISAM' storage engine.
568 $engines = self::getStorageValues(NULL, $maxTablesToCheck);
569 if (array_key_exists('MyISAM', $engines)) {
570 return TRUE;
571 }
572 return FALSE;
573 }
574
575 /**
576 * Checks if a constraint exists for a specified table.
577 *
578 * @param string $tableName
579 * @param string $constraint
580 *
581 * @return boolean true if constraint exists, false otherwise
582 * @static
583 */
584 static function checkConstraintExists($tableName, $constraint) {
585 static $show = array();
586
587 if (!array_key_exists($tableName, $show)) {
588 $query = "SHOW CREATE TABLE $tableName";
589 $dao = CRM_Core_DAO::executeQuery($query);
590
591 if (!$dao->fetch()) {
592 CRM_Core_Error::fatal();
593 }
594
595 $dao->free();
596 $show[$tableName] = $dao->Create_Table;
597 }
598
599 return preg_match("/\b$constraint\b/i", $show[$tableName]) ? TRUE : FALSE;
600 }
601
602 /**
603 * Checks if CONSTRAINT keyword exists for a specified table.
604 *
2a6da8d7
EM
605 * @param array $tables
606 *
607 * @throws Exception
608 * @internal param string $tableName
6a488035
TO
609 *
610 * @return boolean true if CONSTRAINT keyword exists, false otherwise
611 */
f59b722f 612 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
6a488035
TO
613 $show = array();
614 foreach($tables as $tableName){
615 if (!array_key_exists($tableName, $show)) {
616 $query = "SHOW CREATE TABLE $tableName";
617 $dao = CRM_Core_DAO::executeQuery($query);
618
619 if (!$dao->fetch()) {
620 CRM_Core_Error::fatal();
621 }
622
623 $dao->free();
624 $show[$tableName] = $dao->Create_Table;
625 }
626
627 $result = preg_match("/\bCONSTRAINT\b\s/i", $show[$tableName]) ? TRUE : FALSE;
628 if($result == TRUE){
629 continue;
630 }
631 else{
632 return FALSE;
633 }
634 }
635 return TRUE;
636 }
637
638 /**
639 * Checks if the FK constraint name is in the format 'FK_tableName_columnName'
640 * for a specified column of a table.
641 *
642 * @param string $tableName
643 * @param string $columnName
644 *
645 * @return boolean true if in format, false otherwise
646 * @static
647 */
648 static function checkFKConstraintInFormat($tableName, $columnName) {
649 static $show = array();
650
651 if (!array_key_exists($tableName, $show)) {
652 $query = "SHOW CREATE TABLE $tableName";
653 $dao = CRM_Core_DAO::executeQuery($query);
654
655 if (!$dao->fetch()) {
656 CRM_Core_Error::fatal();
657 }
658
659 $dao->free();
660 $show[$tableName] = $dao->Create_Table;
661 }
662 $constraint = "`FK_{$tableName}_{$columnName}`";
663 $pattern = "/\bCONSTRAINT\b\s+%s\s+\bFOREIGN\s+KEY\b\s/i";
664 return preg_match(sprintf($pattern, $constraint),$show[$tableName]) ? TRUE : FALSE;
665 }
666
667 /**
668 * Check whether a specific column in a specific table has always the same value
669 *
670 * @param string $tableName
671 * @param string $columnName
672 * @param string $columnValue
673 *
674 * @return boolean true if the value is always $columnValue, false otherwise
675 * @static
676 */
677 static function checkFieldHasAlwaysValue($tableName, $columnName, $columnValue) {
678 $query = "SELECT * FROM $tableName WHERE $columnName != '$columnValue'";
679 $dao = CRM_Core_DAO::executeQuery($query);
680 $result = $dao->fetch() ? FALSE : TRUE;
681 $dao->free();
682 return $result;
683 }
684
685 /**
686 * Check whether a specific column in a specific table is always NULL
687 *
688 * @param string $tableName
689 * @param string $columnName
690 *
691 * @return boolean true if if the value is always NULL, false otherwise
692 * @static
693 */
694 static function checkFieldIsAlwaysNull($tableName, $columnName) {
695 $query = "SELECT * FROM $tableName WHERE $columnName IS NOT NULL";
696 $dao = CRM_Core_DAO::executeQuery($query);
697 $result = $dao->fetch() ? FALSE : TRUE;
698 $dao->free();
699 return $result;
700 }
701
702 /**
703 * Check if there is a given table in the database
704 *
705 * @param string $tableName
706 *
707 * @return boolean true if exists, else false
708 * @static
709 */
710 static function checkTableExists($tableName) {
711 $query = "
712SHOW TABLES
713LIKE %1
714";
715 $params = array(1 => array($tableName, 'String'));
716
717 $dao = CRM_Core_DAO::executeQuery($query, $params);
718 $result = $dao->fetch() ? TRUE : FALSE;
719 $dao->free();
720 return $result;
721 }
722
723 function checkVersion($version) {
724 $query = "
725SELECT version
726FROM civicrm_domain
727";
728 $dbVersion = CRM_Core_DAO::singleValueQuery($query);
729 return trim($version) == trim($dbVersion) ? TRUE : FALSE;
730 }
731
732 /**
733 * Given a DAO name, a column name and a column value, find the record and GET the value of another column in that record
734 *
735 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
736 * @param int $searchValue Value of the column you want to search by
737 * @param string $returnColumn Name of the column you want to GET the value of
738 * @param string $searchColumn Name of the column you want to search by
739 * @param boolean $force Skip use of the cache
740 *
741 * @return string|null Value of $returnColumn in the retrieved record
742 * @static
743 * @access public
744 */
032c9d10 745 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
6a488035
TO
746 if (
747 empty($searchValue) ||
748 trim(strtolower($searchValue)) == 'null'
749 ) {
750 // adding this year since developers forget to check for an id
751 // or for the 'null' (which is a bad DAO kludge)
752 // and hence we get the first value in the db
753 CRM_Core_Error::fatal();
754 }
755
756 $cacheKey = "{$daoName}:{$searchValue}:{$returnColumn}:{$searchColumn}";
757 if (self::$_dbColumnValueCache === NULL) {
758 self::$_dbColumnValueCache = array();
759 }
760
761 if (!array_key_exists($cacheKey, self::$_dbColumnValueCache) || $force) {
762 $object = new $daoName( );
763 $object->$searchColumn = $searchValue;
764 $object->selectAdd();
765 $object->selectAdd($returnColumn);
766
767 $result = NULL;
768 if ($object->find(TRUE)) {
769 $result = $object->$returnColumn;
770 }
771 $object->free();
772
773 self::$_dbColumnValueCache[$cacheKey] = $result;
774 }
775 return self::$_dbColumnValueCache[$cacheKey];
776 }
777
778 /**
779 * Given a DAO name, a column name and a column value, find the record and SET the value of another column in that record
780 *
781 * @param string $daoName Name of the DAO (Example: CRM_Contact_DAO_Contact to retrieve value from a contact)
782 * @param int $searchValue Value of the column you want to search by
783 * @param string $setColumn Name of the column you want to SET the value of
784 * @param string $setValue SET the setColumn to this value
785 * @param string $searchColumn Name of the column you want to search by
786 *
787 * @return boolean true if we found and updated the object, else false
788 * @static
789 * @access public
790 */
791 static function setFieldValue($daoName, $searchValue, $setColumn, $setValue, $searchColumn = 'id') {
792 $object = new $daoName( );
793 $object->selectAdd();
794 $object->selectAdd("$searchColumn, $setColumn");
795 $object->$searchColumn = $searchValue;
796 $result = FALSE;
797 if ($object->find(TRUE)) {
798 $object->$setColumn = $setValue;
799 if ($object->save()) {
800 $result = TRUE;
801 }
802 }
803 $object->free();
804 return $result;
805 }
806
807 /**
808 * Get sort string
809 *
810 * @param array|object $sort either array or CRM_Utils_Sort
811 * @param string $default - default sort value
812 *
813 * @return string - sortString
814 * @access public
815 * @static
816 */
817 static function getSortString($sort, $default = NULL) {
818 // check if sort is of type CRM_Utils_Sort
819 if (is_a($sort, 'CRM_Utils_Sort')) {
820 return $sort->orderBy();
821 }
822
823 // is it an array specified as $field => $sortDirection ?
824 if ($sort) {
825 foreach ($sort as $k => $v) {
826 $sortString .= "$k $v,";
827 }
828 return rtrim($sortString, ',');
829 }
830 return $default;
831 }
832
833 /**
834 * Takes a bunch of params that are needed to match certain criteria and
835 * retrieves the relevant objects. Typically the valid params are only
836 * contact_id. We'll tweak this function to be more full featured over a period
837 * of time. This is the inverse function of create. It also stores all the retrieved
838 * values in the default array
839 *
840 * @param string $daoName name of the dao object
841 * @param array $params (reference ) an assoc array of name/value pairs
842 * @param array $defaults (reference ) an assoc array to hold the flattened values
843 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
844 *
845 * @return object an object of type referenced by daoName
846 * @access public
847 * @static
848 */
849 static function commonRetrieve($daoName, &$params, &$defaults, $returnProperities = NULL) {
850 $object = new $daoName( );
851 $object->copyValues($params);
852
853 // return only specific fields if returnproperties are sent
854 if (!empty($returnProperities)) {
855 $object->selectAdd();
856 $object->selectAdd(implode(',', $returnProperities));
857 }
858
859 if ($object->find(TRUE)) {
860 self::storeValues($object, $defaults);
861 return $object;
862 }
863 return NULL;
864 }
865
866 /**
867 * Delete the object records that are associated with this contact
868 *
869 * @param string $daoName name of the dao object
870 * @param int $contactId id of the contact to delete
871 *
872 * @return void
873 * @access public
874 * @static
875 */
876 static function deleteEntityContact($daoName, $contactId) {
877 $object = new $daoName( );
878
879 $object->entity_table = 'civicrm_contact';
880 $object->entity_id = $contactId;
881 $object->delete();
882 }
883
884 /**
885 * execute a query
886 *
887 * @param string $query query to be executed
888 *
2a6da8d7
EM
889 * @param array $params
890 * @param bool $abort
891 * @param null $daoName
892 * @param bool $freeDAO
893 * @param bool $i18nRewrite
894 * @param bool $trapException
895 *
6a488035
TO
896 * @return Object CRM_Core_DAO object that holds the results of the query
897 * @static
898 * @access public
899 */
900 static function &executeQuery(
901 $query,
902 $params = array(),
903 $abort = TRUE,
904 $daoName = NULL,
905 $freeDAO = FALSE,
906 $i18nRewrite = TRUE,
907 $trapException = FALSE
908 ) {
909 $queryStr = self::composeQuery($query, $params, $abort);
910 //CRM_Core_Error::debug( 'q', $queryStr );
911
912 if (!$daoName) {
913 $dao = new CRM_Core_DAO();
914 }
915 else {
916 $dao = new $daoName( );
917 }
918
919 if ($trapException) {
6a4257d4 920 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
921 }
922
923 $result = $dao->query($queryStr, $i18nRewrite);
924
6a488035
TO
925 if (is_a($result, 'DB_Error')) {
926 return $result;
927 }
928
929 if ($freeDAO ||
930 preg_match('/^(insert|update|delete|create|drop|replace)/i', $queryStr)
931 ) {
932 // we typically do this for insert/update/delete stataments OR if explicitly asked to
933 // free the dao
934 $dao->free();
935 }
936 return $dao;
937 }
938
939 /**
940 * execute a query and get the single result
941 *
942 * @param string $query query to be executed
e869b07d
CW
943 * @param array $params
944 * @param bool $abort
945 * @param bool $i18nRewrite
946 * @return string|null the result of the query if any
6a488035 947 *
6a488035
TO
948 * @static
949 * @access public
950 */
951 static function &singleValueQuery($query,
952 $params = array(),
953 $abort = TRUE,
954 $i18nRewrite = TRUE
955 ) {
956 $queryStr = self::composeQuery($query, $params, $abort);
957
958 static $_dao = NULL;
959
960 if (!$_dao) {
961 $_dao = new CRM_Core_DAO();
962 }
963
964 $_dao->query($queryStr, $i18nRewrite);
965
966 $result = $_dao->getDatabaseResult();
967 $ret = NULL;
968 if ($result) {
969 $row = $result->fetchRow();
970 if ($row) {
971 $ret = $row[0];
972 }
973 }
974 $_dao->free();
975 return $ret;
976 }
977
978 static function composeQuery($query, &$params, $abort = TRUE) {
979 $tr = array();
980 foreach ($params as $key => $item) {
981 if (is_numeric($key)) {
982 if (CRM_Utils_Type::validate($item[0], $item[1]) !== NULL) {
983 $item[0] = self::escapeString($item[0]);
984 if ($item[1] == 'String' ||
985 $item[1] == 'Memo' ||
986 $item[1] == 'Link'
987 ) {
887a4028
A
988 // Support class constants stipulating wildcard characters and/or
989 // non-quoting of strings. Also support legacy code which may be
990 // passing in TRUE or 1 for $item[2], which used to indicate the
991 // use of wildcard characters.
992 if (!empty($item[2])) {
993 if ($item[2] & CRM_Core_DAO::QUERY_FORMAT_WILDCARD || $item[2] === TRUE) {
994 $item[0] = "'%{$item[0]}%'";
995 }
996 elseif (!($item[2] & CRM_Core_DAO::QUERY_FORMAT_NO_QUOTES)) {
997 $item[0] = "'{$item[0]}'";
998 }
6a488035
TO
999 }
1000 else {
1001 $item[0] = "'{$item[0]}'";
1002 }
1003 }
1004
1005 if (($item[1] == 'Date' || $item[1] == 'Timestamp') &&
1006 strlen($item[0]) == 0
1007 ) {
1008 $item[0] = 'null';
1009 }
1010
1011 $tr['%' . $key] = $item[0];
1012 }
1013 elseif ($abort) {
1014 CRM_Core_Error::fatal("{$item[0]} is not of type {$item[1]}");
1015 }
1016 }
1017 }
1018
e2508c90 1019 return strtr($query, $tr);
6a488035
TO
1020 }
1021
1022 static function freeResult($ids = NULL) {
1023 global $_DB_DATAOBJECT;
1024
1025 /***
1026 $q = array( );
1027 foreach ( array_keys( $_DB_DATAOBJECT['RESULTS'] ) as $id ) {
1028 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1029 }
1030 CRM_Core_Error::debug( 'k', $q );
1031 return;
1032 ***/
1033
1034 if (!$ids) {
1035 if (!$_DB_DATAOBJECT ||
1036 !isset($_DB_DATAOBJECT['RESULTS'])
1037 ) {
1038 return;
1039 }
1040 $ids = array_keys($_DB_DATAOBJECT['RESULTS']);
1041 }
1042
1043 foreach ($ids as $id) {
1044 if (isset($_DB_DATAOBJECT['RESULTS'][$id])) {
1045 if (is_resource($_DB_DATAOBJECT['RESULTS'][$id]->result)) {
1046 mysql_free_result($_DB_DATAOBJECT['RESULTS'][$id]->result);
1047 }
1048 unset($_DB_DATAOBJECT['RESULTS'][$id]);
1049 }
1050
1051 if (isset($_DB_DATAOBJECT['RESULTFIELDS'][$id])) {
1052 unset($_DB_DATAOBJECT['RESULTFIELDS'][$id]);
1053 }
1054 }
1055 }
1056
1057 /**
1058 * This function is to make a shallow copy of an object
1059 * and all the fields in the object
1060 *
1061 * @param string $daoName name of the dao
1062 * @param array $criteria array of all the fields & values
1063 * on which basis to copy
1064 * @param array $newData array of all the fields & values
1065 * to be copied besides the other fields
1066 * @param string $fieldsFix array of fields that you want to prefix/suffix/replace
1067 * @param string $blockCopyOfDependencies fields that you want to block from
1068 * getting copied
1069 *
1070 *
1071 * @return (reference ) the newly created copy of the object
1072 * @access public
1073 */
1074 static function &copyGeneric($daoName, $criteria, $newData = NULL, $fieldsFix = NULL, $blockCopyOfDependencies = NULL) {
1075 $object = new $daoName( );
1076 if (!$newData) {
1077 $object->id = $criteria['id'];
1078 }
1079 else {
1080 foreach ($criteria as $key => $value) {
1081 $object->$key = $value;
1082 }
1083 }
1084
1085 $object->find();
1086 while ($object->fetch()) {
1087
1088 // all the objects except with $blockCopyOfDependencies set
1089 // be copied - addresses #CRM-1962
1090
1091 if ($blockCopyOfDependencies && $object->$blockCopyOfDependencies) {
1092 break;
1093 }
1094
1095 $newObject = new $daoName( );
1096
1097 $fields = &$object->fields();
1098 if (!is_array($fieldsFix)) {
1099 $fieldsToPrefix = array();
1100 $fieldsToSuffix = array();
1101 $fieldsToReplace = array();
1102 }
a7488080 1103 if (!empty($fieldsFix['prefix'])) {
6a488035
TO
1104 $fieldsToPrefix = $fieldsFix['prefix'];
1105 }
a7488080 1106 if (!empty($fieldsFix['suffix'])) {
6a488035
TO
1107 $fieldsToSuffix = $fieldsFix['suffix'];
1108 }
a7488080 1109 if (!empty($fieldsFix['replace'])) {
6a488035
TO
1110 $fieldsToReplace = $fieldsFix['replace'];
1111 }
1112
1113 foreach ($fields as $name => $value) {
1114 if ($name == 'id' || $value['name'] == 'id') {
1115 // copy everything but the id!
1116 continue;
1117 }
1118
1119 $dbName = $value['name'];
1120 $newObject->$dbName = $object->$dbName;
1121 if (isset($fieldsToPrefix[$dbName])) {
1122 $newObject->$dbName = $fieldsToPrefix[$dbName] . $newObject->$dbName;
1123 }
1124 if (isset($fieldsToSuffix[$dbName])) {
1125 $newObject->$dbName .= $fieldsToSuffix[$dbName];
1126 }
1127 if (isset($fieldsToReplace[$dbName])) {
1128 $newObject->$dbName = $fieldsToReplace[$dbName];
1129 }
1130
1131 if (substr($name, -5) == '_date' ||
1132 substr($name, -10) == '_date_time'
1133 ) {
1134 $newObject->$dbName = CRM_Utils_Date::isoToMysql($newObject->$dbName);
1135 }
1136
1137 if ($newData) {
1138 foreach ($newData as $k => $v) {
1139 $newObject->$k = $v;
1140 }
1141 }
1142 }
1143 $newObject->save();
1144 }
1145 return $newObject;
1146 }
1147
1148 /**
1149 * Given the component id, compute the contact id
1150 * since its used for things like send email
1151 */
a5611c8e 1152 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
6a488035
TO
1153 $contactIDs = array();
1154
1155 if (empty($componentIDs)) {
1156 return $contactIDs;
1157 }
1158
1159 $IDs = implode(',', $componentIDs);
1160 $query = "
1161SELECT contact_id
1162 FROM $tableName
1163 WHERE id IN ( $IDs )
1164";
1165
1166 $dao = CRM_Core_DAO::executeQuery($query);
1167 while ($dao->fetch()) {
1168 $contactIDs[] = $dao->contact_id;
1169 }
1170 return $contactIDs;
1171 }
1172
1173 /**
1174 * Takes a bunch of params that are needed to match certain criteria and
1175 * retrieves the relevant objects. Typically the valid params are only
1176 * contact_id. We'll tweak this function to be more full featured over a period
1177 * of time. This is the inverse function of create. It also stores all the retrieved
1178 * values in the default array
1179 *
dd244018
EM
1180 * @param string $daoName name of the dao object
1181 * @param string $fieldIdName
1182 * @param $fieldId
1183 * @param $details
1184 * @param array $returnProperities an assoc array of fields that need to be returned, eg array( 'first_name', 'last_name')
1185 *
1186 * @internal param array $params (reference ) an assoc array of name/value pairs
1187 * @internal param array $defaults (reference ) an assoc array to hold the flattened values
6a488035
TO
1188 * @return object an object of type referenced by daoName
1189 * @access public
1190 * @static
1191 */
1192 static function commonRetrieveAll($daoName, $fieldIdName = 'id', $fieldId, &$details, $returnProperities = NULL) {
1193 require_once (str_replace('_', DIRECTORY_SEPARATOR, $daoName) . ".php");
1194 $object = new $daoName( );
1195 $object->$fieldIdName = $fieldId;
1196
1197 // return only specific fields if returnproperties are sent
1198 if (!empty($returnProperities)) {
1199 $object->selectAdd();
1200 $object->selectAdd('id');
1201 $object->selectAdd(implode(',', $returnProperities));
1202 }
1203
1204 $object->find();
1205 while ($object->fetch()) {
1206 $defaults = array();
1207 self::storeValues($object, $defaults);
1208 $details[$object->id] = $defaults;
1209 }
1210
1211 return $details;
1212 }
1213
1214 static function dropAllTables() {
1215
1216 // first drop all the custom tables we've created
1217 CRM_Core_BAO_CustomGroup::dropAllTables();
1218
1219 // drop all multilingual views
1220 CRM_Core_I18n_Schema::dropAllViews();
1221
1222 CRM_Utils_File::sourceSQLFile(CIVICRM_DSN,
1223 dirname(__FILE__) . DIRECTORY_SEPARATOR .
1224 '..' . DIRECTORY_SEPARATOR .
1225 '..' . DIRECTORY_SEPARATOR .
1226 'sql' . DIRECTORY_SEPARATOR .
1227 'civicrm_drop.mysql'
1228 );
1229 }
1230
1231 static function escapeString($string) {
1232 static $_dao = NULL;
1233
1234 if (!$_dao) {
1235 $_dao = new CRM_Core_DAO();
1236 }
1237
1238 return $_dao->escape($string);
1239 }
1240
1241 /**
1242 * Escape a list of strings for use with "WHERE X IN (...)" queries.
1243 *
1244 * @param $strings array
1245 * @param $default string the value to use if $strings has no elements
1246 * @return string eg "abc","def","ghi"
1247 */
1248 static function escapeStrings($strings, $default = NULL) {
1249 static $_dao = NULL;
1250 if (!$_dao) {
1251 $_dao = new CRM_Core_DAO();
1252 }
1253
1254 if (empty($strings)) {
1255 return $default;
1256 }
1257
1258 $escapes = array_map(array($_dao, 'escape'), $strings);
1259 return '"' . implode('","', $escapes) . '"';
1260 }
1261
1262 static function escapeWildCardString($string) {
1263 // CRM-9155
1264 // ensure we escape the single characters % and _ which are mysql wild
1265 // card characters and could come in via sortByCharacter
1266 // note that mysql does not escape these characters
1267 if ($string && in_array($string,
1268 array('%', '_', '%%', '_%')
1269 )) {
1270 return '\\' . $string;
1271 }
1272
1273 return self::escapeString($string);
1274 }
1275
92b83508
EM
1276 /**
1277 * Creates a test object, including any required objects it needs via recursion
1278 *createOnly: only create in database, do not store or return the objects (useful for perf testing)
1279 *ONLY USE FOR TESTING
1280 */
6a488035
TO
1281 static function createTestObject(
1282 $daoName,
1283 $params = array(),
1284 $numObjects = 1,
1285 $createOnly = FALSE
1286 ) {
b6262a4c
EM
1287 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1288 // so we re-set here in case
1289 $config = CRM_Core_Config::singleton();
1290 $config->backtrace = TRUE;
1291
6a488035
TO
1292 static $counter = 0;
1293 CRM_Core_DAO::$_testEntitiesToSkip = array(
1294 'CRM_Core_DAO_Worldregion',
1295 'CRM_Core_DAO_StateProvince',
1296 'CRM_Core_DAO_Country',
1297 'CRM_Core_DAO_Domain',
1298 );
1299
6a488035
TO
1300 for ($i = 0; $i < $numObjects; ++$i) {
1301
1302 ++$counter;
ab9aa379 1303 $object = new $daoName();
6a488035
TO
1304
1305 $fields = &$object->fields();
1306 foreach ($fields as $name => $value) {
1307 $dbName = $value['name'];
1308 if($dbName == 'contact_sub_type' && empty($params['contact_sub_type'])){
1309 //coming up with a rule to set this is too complex let's not set it
1310 continue;
1311 }
1312 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1313 $required = CRM_Utils_Array::value('required', $value);
1314 if (CRM_Utils_Array::value($dbName, $params) !== NULL && !is_array($params[$dbName])) {
1315 $object->$dbName = $params[$dbName];
1316 }
1317
1318 elseif ($dbName != 'id') {
1319 if ($FKClassName != NULL) {
1320 //skip the FK if it is not required
1321 // if it's contact id we should create even if not required
1322 // we'll have a go @ fetching first though
76396c9b
E
1323 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
1324 if($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
1325 $required = TRUE;
1326 }
6a488035
TO
1327 if (!$required && $dbName != 'contact_id') {
1328 $fkDAO = new $FKClassName;
1329 if($fkDAO->find(TRUE)){
1330 $object->$dbName = $fkDAO->id;
1331 }
1332 unset($fkDAO);
1333 continue;
1334 }
1335 if(in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)){
1336 $depObject = new $FKClassName();
032c9d10 1337 $depObject->find(TRUE);
6a488035
TO
1338 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1339 // FIXME: the fields() metadata is not specific enough
1340 $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1341 }else{
1342 //if it is required we need to generate the dependency object first
1343 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
1344 }
1345 $object->$dbName = $depObject->id;
1346 unset($depObject);
1347
1348 continue;
1349 }
ab9aa379 1350 // Pick an option value if needed
b29e2e8b 1351 if ($value['type'] !== CRM_Utils_Type::T_BOOLEAN) {
5d3b3d60
CW
1352 $options = $daoName::buildOptions($dbName, 'create');
1353 if ($options) {
1354 $object->$dbName = key($options);
1355 continue;
1356 }
6a488035 1357 }
ab9aa379 1358
6a488035
TO
1359 switch ($value['type']) {
1360 case CRM_Utils_Type::T_INT:
1361 case CRM_Utils_Type::T_FLOAT:
1362 case CRM_Utils_Type::T_MONEY:
ac5f2ccd
TO
1363 if (isset($value['precision'])) {
1364 // $object->$dbName = CRM_Utils_Number::createRandomDecimal($value['precision']);
1365 $object->$dbName = CRM_Utils_Number::createTruncatedDecimal($counter, $value['precision']);
1366 } else {
1367 $object->$dbName = $counter;
1368 }
6a488035
TO
1369 break;
1370
b29e2e8b 1371 case CRM_Utils_Type::T_BOOLEAN:
6a488035
TO
1372 if (isset($value['default'])) {
1373 $object->$dbName = $value['default'];
1374 }
1375 elseif ($value['name'] == 'is_deleted' || $value['name'] == 'is_test') {
1376 $object->$dbName = 0;
1377 }
1378 else {
1379 $object->$dbName = 1;
1380 }
1381 break;
1382
1383 case CRM_Utils_Type::T_DATE:
1384 case CRM_Utils_Type::T_TIMESTAMP:
76396c9b 1385 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
6a488035 1386 $object->$dbName = '19700101';
76396c9b
E
1387 if($dbName == 'end_date') {
1388 // put this in the future
1389 $object->$dbName = '20200101';
1390 }
6a488035
TO
1391 break;
1392
1393 case CRM_Utils_Type::T_TIME:
1394 CRM_Core_Error::fatal('T_TIME shouldnt be used.');
1395 //$object->$dbName='000000';
1396 //break;
1397 case CRM_Utils_Type::T_CCNUM:
1398 $object->$dbName = '4111 1111 1111 1111';
1399 break;
1400
1401 case CRM_Utils_Type::T_URL:
1402 $object->$dbName = 'http://www.civicrm.org';
1403 break;
1404
1405 case CRM_Utils_Type::T_STRING:
1406 case CRM_Utils_Type::T_BLOB:
1407 case CRM_Utils_Type::T_MEDIUMBLOB:
1408 case CRM_Utils_Type::T_TEXT:
1409 case CRM_Utils_Type::T_LONGTEXT:
1410 case CRM_Utils_Type::T_EMAIL:
1411 default:
121875d9
TO
1412 // WAS: if (isset($value['enumValues'])) {
1413 // TODO: see if this works with all pseudoconstants
1414 if (isset($value['pseudoconstant'], $value['pseudoconstant']['callback'])) {
1415 if (isset($value['default'])) {
1416 $object->$dbName = $value['default'];
1417 }
1418 else {
1419 $options = CRM_Core_PseudoConstant::get($daoName, $name);
1420 if (is_array($options)) {
1421 $object->$dbName = $options[0];
1422 }
1423 else {
1424 $defaultValues = explode(',', $options);
1425 $object->$dbName = $defaultValues[0];
1426 }
1427 }
1428 }
1429 else {
1430 $object->$dbName = $dbName . '_' . $counter;
1431 $maxlength = CRM_Utils_Array::value('maxlength', $value);
1432 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1433 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1434 }
6a488035
TO
1435 }
1436 }
1437 }
1438 }
1439 $object->save();
1440
1441 if (!$createOnly) {
1442
1443 $objects[$i] = $object;
1444
1445 }
1446 else unset($object);
1447 }
1448
1449 if ($createOnly) {
1450
1451 return;
1452
1453 }
1454 elseif ($numObjects == 1) { return $objects[0];}
1455 else return $objects;
1456 }
1457
92b83508
EM
1458 /**
1459 * deletes the this object plus any dependent objects that are associated with it
1460 * ONLY USE FOR TESTING
1461 */
6a488035
TO
1462 static function deleteTestObjects($daoName, $params = array(
1463 )) {
b6262a4c
EM
1464 //this is a test function also backtrace is set for the test suite it sometimes unsets itself
1465 // so we re-set here in case
1466 $config = CRM_Core_Config::singleton();
1467 $config->backtrace = TRUE;
6a488035 1468
b6262a4c 1469 $object = new $daoName();
6a488035
TO
1470 $object->id = CRM_Utils_Array::value('id', $params);
1471
1472 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1473 if ($object->find(TRUE)) {
1474
1475 $fields = &$object->fields();
1476 foreach ($fields as $name => $value) {
1477
1478 $dbName = $value['name'];
1479
1480 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1481 $required = CRM_Utils_Array::value('required', $value);
1482 if ($FKClassName != NULL
1483 && $object->$dbName
1484 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
1485 && ($required || $dbName == 'contact_id')) {
1486 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1487 }
1488 }
1489 }
1490
1491 $object->delete();
1492
1493 foreach ($deletions as $deletion) {
1494 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
1495 }
1496 }
1497
1498 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1499 $tableName = $prefix . "_temp";
1500
1501 if ($addRandomString) {
1502 if ($string) {
1503 $tableName .= "_" . $string;
1504 }
1505 else {
1506 $tableName .= "_" . md5(uniqid('', TRUE));
1507 }
1508 }
1509 return $tableName;
1510 }
1511
1512 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1513 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1514 // and logging
1515 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
6a4257d4 1516 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035
TO
1517 $dao = new CRM_Core_DAO();
1518 if ($view) {
1519 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1520 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1521 return FALSE;
1522 }
1523 }
1524
1525 if ($trigger) {
1526 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1527 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
6a488035
TO
1528 if ($view) {
1529 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1530 }
1531 return FALSE;
1532 }
1533
1534 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1535 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1536 if ($view) {
1537 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1538 }
1539 return FALSE;
1540 }
1541 }
1542
1543 if ($view) {
1544 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1545 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
6a488035
TO
1546 return FALSE;
1547 }
1548 }
6a488035
TO
1549
1550 return TRUE;
1551 }
1552
1553 static function debugPrint($message = NULL, $printDAO = TRUE) {
1554 CRM_Utils_System::xMemory("{$message}: ");
1555
1556 if ($printDAO) {
1557 global $_DB_DATAOBJECT;
1558 $q = array();
1559 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1560 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1561 }
1562 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
1563 }
1564 }
1565
77b97be7
EM
1566 /**
1567 * Build a list of triggers via hook and add them to (err, reconcile them
1568 * with) the database.
1569 *
1570 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1571 * @param bool $force
1572 *
1573 * @see CRM-9716
1574 */
e53944ef 1575 static function triggerRebuild($tableName = NULL, $force = FALSE) {
6a488035
TO
1576 $info = array();
1577
1578 $logging = new CRM_Logging_Schema;
e53944ef 1579 $logging->triggerInfo($info, $tableName, $force);
6a488035
TO
1580
1581 CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
1582 CRM_Contact_BAO_Contact::triggerInfo($info, $tableName);
1583
1584 CRM_Utils_Hook::triggerInfo($info, $tableName);
1585
1586 // drop all existing triggers on all tables
1587 $logging->dropTriggers($tableName);
1588
1589 // now create the set of new triggers
1590 self::createTriggers($info);
1591 }
1592
aca2de91
CW
1593 /**
1594 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1595 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1596 * TODO: Alternative solutions might be
1597 * * Stop using functions and find another way to strip numeric characters from phones
1598 * * Give better error messages (currently a missing fn fatals with "unknown error")
1599 */
1600 static function checkSqlFunctionsExist() {
1601 if (!self::$_checkedSqlFunctionsExist) {
1602 self::$_checkedSqlFunctionsExist = TRUE;
1603 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1604 if (!$dao->fetch()) {
1605 self::triggerRebuild();
1606 }
1607 }
1608 }
1609
6a488035
TO
1610 /**
1611 * Wrapper function to drop triggers
1612 *
1613 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1614 */
1615 static function dropTriggers($tableName = NULL) {
1616 $info = array();
1617
1618 $logging = new CRM_Logging_Schema;
1619 $logging->triggerInfo($info, $tableName);
1620
1621 // drop all existing triggers on all tables
1622 $logging->dropTriggers($tableName);
1623 }
1624
1625 /**
1626 * @param $info array per hook_civicrm_triggerInfo
1627 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1628 */
1629 static function createTriggers(&$info, $onlyTableName = NULL) {
1630 // Validate info array, should probably raise errors?
1631 if (is_array($info) == FALSE) {
1632 return;
1633 }
1634
1635 $triggers = array();
1636
1637 // now enumerate the tables and the events and collect the same set in a different format
1638 foreach ($info as $value) {
1639
1640 // clean the incoming data, skip malformed entries
1641 // TODO: malformed entries should raise errors or get logged.
1642 if (isset($value['table']) == FALSE ||
1643 isset($value['event']) == FALSE ||
1644 isset($value['when']) == FALSE ||
1645 isset($value['sql']) == FALSE
1646 ) {
1647 continue;
1648 }
1649
1650 if (is_string($value['table']) == TRUE) {
1651 $tables = array($value['table']);
1652 }
1653 else {
1654 $tables = $value['table'];
1655 }
1656
1657 if (is_string($value['event']) == TRUE) {
1658 $events = array(strtolower($value['event']));
1659 }
1660 else {
1661 $events = array_map('strtolower', $value['event']);
1662 }
1663
1664 $whenName = strtolower($value['when']);
1665
1666 foreach ($tables as $tableName) {
1667 if (!isset($triggers[$tableName])) {
1668 $triggers[$tableName] = array();
1669 }
1670
1671 foreach ($events as $eventName) {
1672 $template_params = array('{tableName}', '{eventName}');
1673 $template_values = array($tableName, $eventName);
1674
1675 $sql = str_replace($template_params,
1676 $template_values,
1677 $value['sql']
1678 );
1679 $variables = str_replace($template_params,
1680 $template_values,
1681 CRM_Utils_Array::value('variables', $value)
1682 );
1683
1684 if (!isset($triggers[$tableName][$eventName])) {
1685 $triggers[$tableName][$eventName] = array();
1686 }
1687
1688 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1689 // We're leaving out cursors, conditions, and handlers for now
1690 // they are kind of dangerous in this context anyway
1691 // better off putting them in stored procedures
1692 $triggers[$tableName][$eventName][$whenName] = array(
1693 'variables' => array(),
1694 'sql' => array(),
1695 );
1696 }
1697
1698 if ($variables) {
1699 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1700 }
1701
1702 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1703 }
1704 }
1705 }
1706
1707 // now spit out the sql
1708 foreach ($triggers as $tableName => $tables) {
1709 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1710 continue;
1711 }
1712 foreach ($tables as $eventName => $events) {
1713 foreach ($events as $whenName => $parts) {
1714 $varString = implode("\n", $parts['variables']);
1715 $sqlString = implode("\n", $parts['sql']);
6842bb53
DL
1716 $validName = CRM_Core_DAO::shortenSQLName($tableName, 48, TRUE);
1717 $triggerName = "{$validName}_{$whenName}_{$eventName}";
6a488035
TO
1718 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1719
1720 CRM_Core_DAO::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1721 CRM_Core_DAO::executeQuery(
1722 $triggerSQL,
1723 array(),
1724 TRUE,
1725 NULL,
1726 FALSE,
1727 FALSE
1728 );
1729 }
1730 }
1731 }
1732 }
1733
1734 /**
71e5aa5c
ARW
1735 * Find all records which refer to this entity.
1736 *
1737 * @return array of objects referencing this
1738 */
1739 function findReferences() {
1740 $links = self::getReferencesToTable(static::getTableName());
1741
1742 $occurrences = array();
1743 foreach ($links as $refSpec) {
1744 $refColumn = $refSpec->getReferenceKey();
1745 $targetColumn = $refSpec->getTargetKey();
1746 $params = array(1 => array($this->$targetColumn, 'String'));
1747 $sql = <<<EOS
1748SELECT id
1749FROM {$refSpec->getReferenceTable()}
1750WHERE {$refColumn} = %1
1751EOS;
1752 if ($refSpec->isGeneric()) {
1753 $params[2] = array(static::getTableName(), 'String');
1754 $sql .= <<<EOS
1755 AND {$refSpec->getTypeColumn()} = %2
1756EOS;
1757 }
31bed28c 1758 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
71e5aa5c
ARW
1759 $result = self::executeQuery($sql, $params, TRUE, $daoName);
1760 while ($result->fetch()) {
1761 $obj = new $daoName();
1762 $obj->id = $result->id;
1763 $occurrences[] = $obj;
1764 }
1765 }
1766
1767 return $occurrences;
1768 }
1769
1770 /**
1771 * List all tables which have hard foreign keys to this table.
6a488035 1772 *
71e5aa5c
ARW
1773 * For now, this returns a description of every entity_id/entity_table
1774 * reference.
1775 * TODO: filter dynamic entity references on the $tableName, based on
1776 * schema metadata in dynamicForeignKey which enumerates a restricted
1777 * set of possible entity_table's.
6a488035 1778 *
71e5aa5c 1779 * @param string $tableName table referred to
6a488035 1780 *
71e5aa5c
ARW
1781 * @return array structure of table and column, listing every table with a
1782 * foreign key reference to $tableName, and the column where the key appears.
6a488035 1783 */
71e5aa5c
ARW
1784 static function getReferencesToTable($tableName) {
1785 $refsFound = array();
31bed28c 1786 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
71e5aa5c
ARW
1787 $links = $daoClassName::getReferenceColumns();
1788 $daoTableName = $daoClassName::getTableName();
1789
1790 foreach ($links as $refSpec) {
1791 if ($refSpec->getTargetTable() === $tableName
1792 or $refSpec->isGeneric()
1793 ) {
1794 $refsFound[] = $refSpec;
1795 }
6a488035
TO
1796 }
1797 }
71e5aa5c 1798 return $refsFound;
6a488035 1799 }
032c9d10
TO
1800
1801 /**
1802 * Lookup the value of a MySQL global configuration variable.
1803 *
1804 * @param string $name e.g. "thread_stack"
1805 * @param mixed $default
1806 * @return mixed
1807 */
1808 public static function getGlobalSetting($name, $default = NULL) {
1809 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1810 // that has been reported to fail under MySQL 5.0 for OS X
1811 $escapedName = self::escapeString($name);
1812 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1813 if ($dao->fetch()) {
1814 return $dao->Value;
ab00f69d
DL
1815 }
1816 else {
032c9d10
TO
1817 return $default;
1818 }
1819 }
dc86f881
CW
1820
1821 /**
1822 * Get options for the called BAO object's field.
1823 * This function can be overridden by each BAO to add more logic related to context.
2158332a 1824 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
dc86f881 1825 *
2a3f958d 1826 * @param string $fieldName
9a1b1948
EM
1827 * @param string $context : @see CRM_Core_DAO::buildOptionsContext
1828 * @param array $props : whatever is known about this bao object
1829 *
1830 * @return Array|bool
dc86f881
CW
1831 */
1832 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
2158332a 1833 // If a given bao does not override this function
dc86f881 1834 $baoName = get_called_class();
786ad6e1 1835 return CRM_Core_PseudoConstant::get($baoName, $fieldName, array(), $context);
dc86f881 1836 }
786ad6e1 1837
2a3f958d
CW
1838 /**
1839 * Populate option labels for this object's fields.
1840 *
1841 * @throws exception if called directly on the base class
1842 */
1843 public function getOptionLabels() {
1844 $fields = $this->fields();
1845 if ($fields === NULL) {
395d8dc6 1846 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
2a3f958d
CW
1847 }
1848 foreach ($fields as $field) {
1849 $name = CRM_Utils_Array::value('name', $field);
1850 if ($name && isset($this->$name)) {
a8c23526 1851 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
2a3f958d
CW
1852 if ($label !== FALSE) {
1853 // Append 'label' onto the field name
1854 $labelName = $name . '_label';
1855 $this->$labelName = $label;
1856 }
1857 }
1858 }
1859 }
1860
786ad6e1
CW
1861 /**
1862 * Provides documentation and validation for the buildOptions $context param
1863 *
1864 * @param String $context
77b97be7
EM
1865 *
1866 * @throws Exception
1867 * @return array
786ad6e1
CW
1868 */
1869 public static function buildOptionsContext($context = NULL) {
1870 $contexts = array(
1871 'get' => "All options are returned, even if they are disabled. Labels are translated.",
1872 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
1873 'search' => "Searchable options are returned. Labels are translated.",
1874 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
1875 );
1876 // Validation: enforce uniformity of this param
1877 if ($context !== NULL && !isset($contexts[$context])) {
395d8dc6 1878 throw new Exception("'$context' is not a valid context for buildOptions.");
786ad6e1
CW
1879 }
1880 return $contexts;
1881 }
1882
5fafc9b0
CW
1883 /**
1884 * @param $fieldName
1885 * @return bool|array
1886 */
1887 function getFieldSpec($fieldName) {
1888 $fields = $this->fields();
1889 $fieldKeys = $this->fieldKeys();
1890
1891 // Support "unique names" as well as sql names
1892 $fieldKey = $fieldName;
1893 if (empty($fields[$fieldKey])) {
1894 $fieldKey = CRM_Utils_Array::value($fieldName, $fieldKeys);
1895 }
1896 // If neither worked then this field doesn't exist. Return false.
1897 if (empty($fields[$fieldKey])) {
1898 return FALSE;
1899 }
1900 return $fields[$fieldKey];
1901 }
1902
faf8c53b 1903 /**
1904 * SQL version of api function to assign filters to the DAO based on the syntax
1905 * $field => array('IN' => array(4,6,9))
1906 * OR
1907 * $field => array('LIKE' => array('%me%))
1908 * etc
1909 *
9a1b1948 1910 * @param $fieldName
a038992c 1911 * @param $filter array filter to be applied indexed by operator
1912 * @param $type String type of field (not actually used - nor in api @todo )
1913 * @param $alias String alternative field name ('as') @todo- not actually used
78c0bfc0 1914 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
1915 * this is primarily so we can add filters @ the api level to the Query object based fields
9a1b1948
EM
1916 *
1917 * @throws Exception
1918 * @internal param string $fieldname name of fields
1919 * @todo a better solutution would be for the query object to apply these filters based on the
78c0bfc0 1920 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
9a1b1948 1921 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
06f48f96 1922 * required to extend further & it may be the comments per above should be implemented. It may be
1923 * preferable to not double-banger the return context next refactor of this - but keeping the attention
1924 * in one place has some advantages as we try to extend this format
1925 *
9a1b1948 1926 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
06f48f96 1927 * depending on whether it is supported as yet
9a1b1948 1928 */
3f2d6002 1929 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
faf8c53b 1930 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
1931 // support for other syntaxes is discussed in ticket but being put off for now
faf8c53b 1932 foreach ($filter as $operator => $criteria) {
e4176358 1933 if (in_array($operator, self::acceptedSQLOperators())) {
faf8c53b 1934 switch ($operator) {
1935 // unary operators
faf8c53b 1936 case 'IS NULL':
1937 case 'IS NOT NULL':
78c0bfc0 1938 if(!$returnSanitisedArray) {
1939 return (sprintf('%s %s', $fieldName, $operator));
1940 }
06f48f96 1941 else{
1942 return NULL; // not yet implemented (tests required to implement)
1943 }
faf8c53b 1944 break;
1945
1946 // ternary operators
1947 case 'BETWEEN':
1948 case 'NOT BETWEEN':
1949 if (empty($criteria[0]) || empty($criteria[1])) {
395d8dc6 1950 throw new Exception("invalid criteria for $operator");
faf8c53b 1951 }
78c0bfc0 1952 if(!$returnSanitisedArray) {
1953 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
1954 }
06f48f96 1955 else{
1956 return NULL; // not yet implemented (tests required to implement)
1957 }
faf8c53b 1958 break;
1959
1960 // n-ary operators
1961 case 'IN':
1962 case 'NOT IN':
1963 if (empty($criteria)) {
395d8dc6 1964 throw new Exception("invalid criteria for $operator");
faf8c53b 1965 }
1966 $escapedCriteria = array_map(array(
1967 'CRM_Core_DAO',
1968 'escapeString'
1969 ), $criteria);
78c0bfc0 1970 if(!$returnSanitisedArray) {
1971 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
1972 }
1973 return $escapedCriteria;
faf8c53b 1974 break;
1975
1976 // binary operators
6a488035 1977
faf8c53b 1978 default:
78c0bfc0 1979 if(!$returnSanitisedArray) {
1980 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
1981 }
06f48f96 1982 else{
1983 return NULL; // not yet implemented (tests required to implement)
1984 }
faf8c53b 1985 }
1986 }
1987 }
1988 }
6842bb53 1989
e4176358
CW
1990 /**
1991 * @see http://issues.civicrm.org/jira/browse/CRM-9150
1992 * support for other syntaxes is discussed in ticket but being put off for now
1993 * @return array
1994 */
1995 public static function acceptedSQLOperators() {
1996 return array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
1997 }
1998
6842bb53
DL
1999 /**
2000 * SQL has a limit of 64 characters on various names:
2001 * table name, trigger name, column name ...
2002 *
2003 * For custom groups and fields we generated names from user entered input
2004 * which can be longer than this length, this function helps with creating
2005 * strings that meet various criteria.
2006 *
2007 * @param string $string - the string to be shortened
9a1b1948
EM
2008 * @param int $length - the max length of the string
2009 *
2010 * @param bool $makeRandom
2011 *
2012 * @return string
6842bb53
DL
2013 */
2014 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
2015 // early return for strings that meet the requirements
2016 if (strlen($string) <= $length) {
2017 return $string;
2018 }
2019
2020 // easy return for calls that dont need a randomized uniq string
2021 if (! $makeRandom) {
2022 return substr($string, 0, $length);
2023 }
2024
2025 // the string is longer than the length and we need a uniq string
2026 // for the same tablename we need the same uniq string everytime
2027 // hence we use md5 on the string, which is not random
a8dd306e
DL
2028 // we'll append 8 characters to the end of the tableName
2029 $md5string = substr(md5($string), 0, 8);
2030 return substr($string, 0, $length - 8) . "_{$md5string}";
6842bb53
DL
2031 }
2032
6e1bb60c
N
2033 function setApiFilter(&$params) {}
2034
232624b1 2035}