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