ae59e51092f162d5f91a77d9c4bf0b7c0912239e
[civicrm-core.git] / CRM / Core / DAO.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
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
37 require_once 'PEAR.php';
38 require_once 'DB/DataObject.php';
39
40 require_once 'CRM/Core/I18n.php';
41 class 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
58 BULK_MAIL_INSERT_COUNT = 10,
59 QUERY_FORMAT_WILDCARD = 1,
60 QUERY_FORMAT_NO_QUOTES = 2;
61
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
73 static $_checkedSqlFunctionsExist = FALSE;
74
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() {
198 $this->_connect();
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 *
235 * @static
236 * @access public
237 *
238 * @return array of CRM_Core_EntityReference
239 */
240 static function getReferenceColumns() {
241 return array();
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
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 = "
503 SHOW COLUMNS
504 FROM $tableName
505 LIKE %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 */
603 static function schemaRequiresRebuilding($tables = array("civicrm_contact")) {
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 = "
703 SHOW TABLES
704 LIKE %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 = "
716 SELECT version
717 FROM 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 */
736 static function getFieldValue($daoName, $searchValue, $returnColumn = 'name', $searchColumn = 'id', $force = FALSE) {
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 ) {
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 }
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
1004 return strtr($query, $tr);
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 */
1137 public static function &getContactIDsFromComponent(&$componentIDs, $tableName) {
1138 $contactIDs = array();
1139
1140 if (empty($componentIDs)) {
1141 return $contactIDs;
1142 }
1143
1144 $IDs = implode(',', $componentIDs);
1145 $query = "
1146 SELECT 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
1275 for ($i = 0; $i < $numObjects; ++$i) {
1276
1277 ++$counter;
1278 $object = new $daoName();
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 // we WILL create campaigns though for so tests with a campaign pseudoconstant will complete
1299 if($FKClassName === 'CRM_Campaign_DAO_Campaign' && $daoName != $FKClassName) {
1300 $required = TRUE;
1301 }
1302 if (!$required && $dbName != 'contact_id') {
1303 $fkDAO = new $FKClassName;
1304 if($fkDAO->find(TRUE)){
1305 $object->$dbName = $fkDAO->id;
1306 }
1307 unset($fkDAO);
1308 continue;
1309 }
1310 if(in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)){
1311 $depObject = new $FKClassName();
1312 $depObject->find(TRUE);
1313 } elseif ($daoName == 'CRM_Member_DAO_MembershipType' && $name == 'member_of_contact_id') {
1314 // FIXME: the fields() metadata is not specific enough
1315 $depObject = CRM_Core_DAO::createTestObject($FKClassName, array('contact_type' => 'Organization'));
1316 }else{
1317 //if it is required we need to generate the dependency object first
1318 $depObject = CRM_Core_DAO::createTestObject($FKClassName, CRM_Utils_Array::value($dbName, $params, 1));
1319 }
1320 $object->$dbName = $depObject->id;
1321 unset($depObject);
1322
1323 continue;
1324 }
1325 // Pick an option value if needed
1326 if ($value['type'] !== CRM_Utils_Type::T_BOOLEAN) {
1327 $options = $daoName::buildOptions($dbName, 'create');
1328 if ($options) {
1329 $object->$dbName = key($options);
1330 continue;
1331 }
1332 }
1333
1334 switch ($value['type']) {
1335 case CRM_Utils_Type::T_INT:
1336 case CRM_Utils_Type::T_FLOAT:
1337 case CRM_Utils_Type::T_MONEY:
1338 $object->$dbName = $counter;
1339 break;
1340
1341 case CRM_Utils_Type::T_BOOLEAN:
1342 if (isset($value['default'])) {
1343 $object->$dbName = $value['default'];
1344 }
1345 elseif ($value['name'] == 'is_deleted' || $value['name'] == 'is_test') {
1346 $object->$dbName = 0;
1347 }
1348 else {
1349 $object->$dbName = 1;
1350 }
1351 break;
1352
1353 case CRM_Utils_Type::T_DATE:
1354 case CRM_Utils_Type::T_TIMESTAMP:
1355 case CRM_Utils_Type::T_DATE + CRM_Utils_Type::T_TIME:
1356 $object->$dbName = '19700101';
1357 if($dbName == 'end_date') {
1358 // put this in the future
1359 $object->$dbName = '20200101';
1360 }
1361 break;
1362
1363 case CRM_Utils_Type::T_TIME:
1364 CRM_Core_Error::fatal('T_TIME shouldnt be used.');
1365 //$object->$dbName='000000';
1366 //break;
1367 case CRM_Utils_Type::T_CCNUM:
1368 $object->$dbName = '4111 1111 1111 1111';
1369 break;
1370
1371 case CRM_Utils_Type::T_URL:
1372 $object->$dbName = 'http://www.civicrm.org';
1373 break;
1374
1375 case CRM_Utils_Type::T_STRING:
1376 case CRM_Utils_Type::T_BLOB:
1377 case CRM_Utils_Type::T_MEDIUMBLOB:
1378 case CRM_Utils_Type::T_TEXT:
1379 case CRM_Utils_Type::T_LONGTEXT:
1380 case CRM_Utils_Type::T_EMAIL:
1381 default:
1382 if (isset($value['enumValues'])) {
1383 if (isset($value['default'])) {
1384 $object->$dbName = $value['default'];
1385 }
1386 else {
1387 if (is_array($value['enumValues'])) {
1388 $object->$dbName = $value['enumValues'][0];
1389 }
1390 else {
1391 $defaultValues = explode(',', $value['enumValues']);
1392 $object->$dbName = $defaultValues[0];
1393 }
1394 }
1395 }
1396 else {
1397 $object->$dbName = $dbName . '_' . $counter;
1398 $maxlength = CRM_Utils_Array::value('maxlength', $value);
1399 if ($maxlength > 0 && strlen($object->$dbName) > $maxlength) {
1400 $object->$dbName = substr($object->$dbName, 0, $value['maxlength']);
1401 }
1402 }
1403 }
1404 }
1405 }
1406 $object->save();
1407
1408 if (!$createOnly) {
1409
1410 $objects[$i] = $object;
1411
1412 }
1413 else unset($object);
1414 }
1415
1416 if ($createOnly) {
1417
1418 return;
1419
1420 }
1421 elseif ($numObjects == 1) { return $objects[0];}
1422 else return $objects;
1423 }
1424
1425 //deletes the this object plus any dependent objects that are associated with it
1426 //ONLY USE FOR TESTING
1427
1428 static function deleteTestObjects($daoName, $params = array(
1429 )) {
1430
1431 $object = new $daoName ( );
1432 $object->id = CRM_Utils_Array::value('id', $params);
1433
1434 $deletions = array(); // array(array(0 => $daoName, 1 => $daoParams))
1435 if ($object->find(TRUE)) {
1436
1437 $fields = &$object->fields();
1438 foreach ($fields as $name => $value) {
1439
1440 $dbName = $value['name'];
1441
1442 $FKClassName = CRM_Utils_Array::value('FKClassName', $value);
1443 $required = CRM_Utils_Array::value('required', $value);
1444 if ($FKClassName != NULL
1445 && $object->$dbName
1446 && !in_array($FKClassName, CRM_Core_DAO::$_testEntitiesToSkip)
1447 && ($required || $dbName == 'contact_id')) {
1448 $deletions[] = array($FKClassName, array('id' => $object->$dbName)); // x
1449 }
1450 }
1451 }
1452
1453 $object->delete();
1454
1455 foreach ($deletions as $deletion) {
1456 CRM_Core_DAO::deleteTestObjects($deletion[0], $deletion[1]);
1457 }
1458 }
1459
1460 static function createTempTableName($prefix = 'civicrm', $addRandomString = TRUE, $string = NULL) {
1461 $tableName = $prefix . "_temp";
1462
1463 if ($addRandomString) {
1464 if ($string) {
1465 $tableName .= "_" . $string;
1466 }
1467 else {
1468 $tableName .= "_" . md5(uniqid('', TRUE));
1469 }
1470 }
1471 return $tableName;
1472 }
1473
1474 static function checkTriggerViewPermission($view = TRUE, $trigger = TRUE) {
1475 // test for create view and trigger permissions and if allowed, add the option to go multilingual
1476 // and logging
1477 // I'm not sure why we use the getStaticProperty for an error, rather than checking for DB_Error
1478 CRM_Core_Error::ignoreException();
1479 $dao = new CRM_Core_DAO();
1480 if ($view) {
1481 $dao->query('CREATE OR REPLACE VIEW civicrm_domain_view AS SELECT * FROM civicrm_domain');
1482 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1483 CRM_Core_Error::setCallback();
1484 return FALSE;
1485 }
1486 }
1487
1488 if ($trigger) {
1489 $result = $dao->query('CREATE TRIGGER civicrm_domain_trigger BEFORE INSERT ON civicrm_domain FOR EACH ROW BEGIN END');
1490 if (PEAR::getStaticProperty('DB_DataObject', 'lastError') || is_a($result, 'DB_Error')) {
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 $dao->query('DROP TRIGGER IF EXISTS civicrm_domain_trigger');
1499 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1500 CRM_Core_Error::setCallback();
1501 if ($view) {
1502 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1503 }
1504 return FALSE;
1505 }
1506 }
1507
1508 if ($view) {
1509 $dao->query('DROP VIEW IF EXISTS civicrm_domain_view');
1510 if (PEAR::getStaticProperty('DB_DataObject', 'lastError')) {
1511 CRM_Core_Error::setCallback();
1512 return FALSE;
1513 }
1514 }
1515 CRM_Core_Error::setCallback();
1516
1517 return TRUE;
1518 }
1519
1520 static function debugPrint($message = NULL, $printDAO = TRUE) {
1521 CRM_Utils_System::xMemory("{$message}: ");
1522
1523 if ($printDAO) {
1524 global $_DB_DATAOBJECT;
1525 $q = array();
1526 foreach (array_keys($_DB_DATAOBJECT['RESULTS']) as $id) {
1527 $q[] = $_DB_DATAOBJECT['RESULTS'][$id]->query;
1528 }
1529 CRM_Core_Error::debug('_DB_DATAOBJECT', $q);
1530 }
1531 }
1532
1533 /**
1534 * Build a list of triggers via hook and add them to (err, reconcile them
1535 * with) the database.
1536 *
1537 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1538 * @see CRM-9716
1539 */
1540 static function triggerRebuild($tableName = NULL, $force = FALSE) {
1541 $info = array();
1542
1543 $logging = new CRM_Logging_Schema;
1544 $logging->triggerInfo($info, $tableName, $force);
1545
1546 CRM_Core_I18n_Schema::triggerInfo($info, $tableName);
1547 CRM_Contact_BAO_Contact::triggerInfo($info, $tableName);
1548
1549 CRM_Utils_Hook::triggerInfo($info, $tableName);
1550
1551 // drop all existing triggers on all tables
1552 $logging->dropTriggers($tableName);
1553
1554 // now create the set of new triggers
1555 self::createTriggers($info);
1556 }
1557
1558 /**
1559 * Because sql functions are sometimes lost, esp during db migration, we check here to avoid numerous support requests
1560 * @see http://issues.civicrm.org/jira/browse/CRM-13822
1561 * TODO: Alternative solutions might be
1562 * * Stop using functions and find another way to strip numeric characters from phones
1563 * * Give better error messages (currently a missing fn fatals with "unknown error")
1564 */
1565 static function checkSqlFunctionsExist() {
1566 if (!self::$_checkedSqlFunctionsExist) {
1567 self::$_checkedSqlFunctionsExist = TRUE;
1568 $dao = CRM_Core_DAO::executeQuery("SHOW function status WHERE db = database() AND name = 'civicrm_strip_non_numeric'");
1569 if (!$dao->fetch()) {
1570 self::triggerRebuild();
1571 }
1572 }
1573 }
1574
1575 /**
1576 * Wrapper function to drop triggers
1577 *
1578 * @param $tableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1579 */
1580 static function dropTriggers($tableName = NULL) {
1581 $info = array();
1582
1583 $logging = new CRM_Logging_Schema;
1584 $logging->triggerInfo($info, $tableName);
1585
1586 // drop all existing triggers on all tables
1587 $logging->dropTriggers($tableName);
1588 }
1589
1590 /**
1591 * @param $info array per hook_civicrm_triggerInfo
1592 * @param $onlyTableName string the specific table requiring a rebuild; or NULL to rebuild all tables
1593 */
1594 static function createTriggers(&$info, $onlyTableName = NULL) {
1595 // Validate info array, should probably raise errors?
1596 if (is_array($info) == FALSE) {
1597 return;
1598 }
1599
1600 $triggers = array();
1601
1602 // now enumerate the tables and the events and collect the same set in a different format
1603 foreach ($info as $value) {
1604
1605 // clean the incoming data, skip malformed entries
1606 // TODO: malformed entries should raise errors or get logged.
1607 if (isset($value['table']) == FALSE ||
1608 isset($value['event']) == FALSE ||
1609 isset($value['when']) == FALSE ||
1610 isset($value['sql']) == FALSE
1611 ) {
1612 continue;
1613 }
1614
1615 if (is_string($value['table']) == TRUE) {
1616 $tables = array($value['table']);
1617 }
1618 else {
1619 $tables = $value['table'];
1620 }
1621
1622 if (is_string($value['event']) == TRUE) {
1623 $events = array(strtolower($value['event']));
1624 }
1625 else {
1626 $events = array_map('strtolower', $value['event']);
1627 }
1628
1629 $whenName = strtolower($value['when']);
1630
1631 foreach ($tables as $tableName) {
1632 if (!isset($triggers[$tableName])) {
1633 $triggers[$tableName] = array();
1634 }
1635
1636 foreach ($events as $eventName) {
1637 $template_params = array('{tableName}', '{eventName}');
1638 $template_values = array($tableName, $eventName);
1639
1640 $sql = str_replace($template_params,
1641 $template_values,
1642 $value['sql']
1643 );
1644 $variables = str_replace($template_params,
1645 $template_values,
1646 CRM_Utils_Array::value('variables', $value)
1647 );
1648
1649 if (!isset($triggers[$tableName][$eventName])) {
1650 $triggers[$tableName][$eventName] = array();
1651 }
1652
1653 if (!isset($triggers[$tableName][$eventName][$whenName])) {
1654 // We're leaving out cursors, conditions, and handlers for now
1655 // they are kind of dangerous in this context anyway
1656 // better off putting them in stored procedures
1657 $triggers[$tableName][$eventName][$whenName] = array(
1658 'variables' => array(),
1659 'sql' => array(),
1660 );
1661 }
1662
1663 if ($variables) {
1664 $triggers[$tableName][$eventName][$whenName]['variables'][] = $variables;
1665 }
1666
1667 $triggers[$tableName][$eventName][$whenName]['sql'][] = $sql;
1668 }
1669 }
1670 }
1671
1672 // now spit out the sql
1673 foreach ($triggers as $tableName => $tables) {
1674 if ($onlyTableName != NULL && $onlyTableName != $tableName) {
1675 continue;
1676 }
1677 foreach ($tables as $eventName => $events) {
1678 foreach ($events as $whenName => $parts) {
1679 $varString = implode("\n", $parts['variables']);
1680 $sqlString = implode("\n", $parts['sql']);
1681 $validName = CRM_Core_DAO::shortenSQLName($tableName, 48, TRUE);
1682 $triggerName = "{$validName}_{$whenName}_{$eventName}";
1683 $triggerSQL = "CREATE TRIGGER $triggerName $whenName $eventName ON $tableName FOR EACH ROW BEGIN $varString $sqlString END";
1684
1685 CRM_Core_DAO::executeQuery("DROP TRIGGER IF EXISTS $triggerName");
1686 CRM_Core_DAO::executeQuery(
1687 $triggerSQL,
1688 array(),
1689 TRUE,
1690 NULL,
1691 FALSE,
1692 FALSE
1693 );
1694 }
1695 }
1696 }
1697 }
1698
1699 /**
1700 * Find all records which refer to this entity.
1701 *
1702 * @return array of objects referencing this
1703 */
1704 function findReferences() {
1705 $links = self::getReferencesToTable(static::getTableName());
1706
1707 $occurrences = array();
1708 foreach ($links as $refSpec) {
1709 $refColumn = $refSpec->getReferenceKey();
1710 $targetColumn = $refSpec->getTargetKey();
1711 $params = array(1 => array($this->$targetColumn, 'String'));
1712 $sql = <<<EOS
1713 SELECT id
1714 FROM {$refSpec->getReferenceTable()}
1715 WHERE {$refColumn} = %1
1716 EOS;
1717 if ($refSpec->isGeneric()) {
1718 $params[2] = array(static::getTableName(), 'String');
1719 $sql .= <<<EOS
1720 AND {$refSpec->getTypeColumn()} = %2
1721 EOS;
1722 }
1723 $daoName = CRM_Core_DAO_AllCoreTables::getClassForTable($refSpec->getReferenceTable());
1724 $result = self::executeQuery($sql, $params, TRUE, $daoName);
1725 while ($result->fetch()) {
1726 $obj = new $daoName();
1727 $obj->id = $result->id;
1728 $occurrences[] = $obj;
1729 }
1730 }
1731
1732 return $occurrences;
1733 }
1734
1735 /**
1736 * List all tables which have hard foreign keys to this table.
1737 *
1738 * For now, this returns a description of every entity_id/entity_table
1739 * reference.
1740 * TODO: filter dynamic entity references on the $tableName, based on
1741 * schema metadata in dynamicForeignKey which enumerates a restricted
1742 * set of possible entity_table's.
1743 *
1744 * @param string $tableName table referred to
1745 *
1746 * @return array structure of table and column, listing every table with a
1747 * foreign key reference to $tableName, and the column where the key appears.
1748 */
1749 static function getReferencesToTable($tableName) {
1750 $refsFound = array();
1751 foreach (CRM_Core_DAO_AllCoreTables::getClasses() as $daoClassName) {
1752 $links = $daoClassName::getReferenceColumns();
1753 $daoTableName = $daoClassName::getTableName();
1754
1755 foreach ($links as $refSpec) {
1756 if ($refSpec->getTargetTable() === $tableName
1757 or $refSpec->isGeneric()
1758 ) {
1759 $refsFound[] = $refSpec;
1760 }
1761 }
1762 }
1763 return $refsFound;
1764 }
1765
1766 /**
1767 * Lookup the value of a MySQL global configuration variable.
1768 *
1769 * @param string $name e.g. "thread_stack"
1770 * @param mixed $default
1771 * @return mixed
1772 */
1773 public static function getGlobalSetting($name, $default = NULL) {
1774 // Alternatively, SELECT @@GLOBAL.thread_stack, but
1775 // that has been reported to fail under MySQL 5.0 for OS X
1776 $escapedName = self::escapeString($name);
1777 $dao = CRM_Core_DAO::executeQuery("SHOW VARIABLES LIKE '$escapedName'");
1778 if ($dao->fetch()) {
1779 return $dao->Value;
1780 }
1781 else {
1782 return $default;
1783 }
1784 }
1785
1786 /**
1787 * Get options for the called BAO object's field.
1788 * This function can be overridden by each BAO to add more logic related to context.
1789 * The overriding function will generally call the lower-level CRM_Core_PseudoConstant::get
1790 *
1791 * @param string $fieldName
1792 * @param string $context: @see CRM_Core_DAO::buildOptionsContext
1793 * @param array $props: whatever is known about this bao object
1794 */
1795 public static function buildOptions($fieldName, $context = NULL, $props = array()) {
1796 // If a given bao does not override this function
1797 $baoName = get_called_class();
1798 return CRM_Core_PseudoConstant::get($baoName, $fieldName, array(), $context);
1799 }
1800
1801 /**
1802 * Populate option labels for this object's fields.
1803 *
1804 * @throws exception if called directly on the base class
1805 */
1806 public function getOptionLabels() {
1807 $fields = $this->fields();
1808 if ($fields === NULL) {
1809 throw new Exception ('Cannot call getOptionLabels on CRM_Core_DAO');
1810 }
1811 foreach ($fields as $field) {
1812 $name = CRM_Utils_Array::value('name', $field);
1813 if ($name && isset($this->$name)) {
1814 $label = CRM_Core_PseudoConstant::getLabel(get_class($this), $name, $this->$name);
1815 if ($label !== FALSE) {
1816 // Append 'label' onto the field name
1817 $labelName = $name . '_label';
1818 $this->$labelName = $label;
1819 }
1820 }
1821 }
1822 }
1823
1824 /**
1825 * Provides documentation and validation for the buildOptions $context param
1826 *
1827 * @param String $context
1828 */
1829 public static function buildOptionsContext($context = NULL) {
1830 $contexts = array(
1831 'get' => "All options are returned, even if they are disabled. Labels are translated.",
1832 'create' => "Options are filtered appropriately for the object being created/updated. Labels are translated.",
1833 'search' => "Searchable options are returned. Labels are translated.",
1834 'validate' => "All options are returned, even if they are disabled. Machine names are used in place of labels.",
1835 );
1836 // Validation: enforce uniformity of this param
1837 if ($context !== NULL && !isset($contexts[$context])) {
1838 throw new Exception("'$context' is not a valid context for buildOptions.");
1839 }
1840 return $contexts;
1841 }
1842
1843 /**
1844 * SQL version of api function to assign filters to the DAO based on the syntax
1845 * $field => array('IN' => array(4,6,9))
1846 * OR
1847 * $field => array('LIKE' => array('%me%))
1848 * etc
1849 *
1850 * @param $fieldname string name of fields
1851 * @param $filter array filter to be applied indexed by operator
1852 * @param $type String type of field (not actually used - nor in api @todo )
1853 * @param $alias String alternative field name ('as') @todo- not actually used
1854 * @param bool $returnSanitisedArray return a sanitised array instead of a clause
1855 * this is primarily so we can add filters @ the api level to the Query object based fields
1856 * @todo a better solutution would be for the query object to apply these filters based on the
1857 * api supported format (but we don't want to risk breakage in alpha stage & query class is scary
1858 * @todo @time of writing only IN & NOT IN are supported for the array style syntax (as test is
1859 * required to extend further & it may be the comments per above should be implemented. It may be
1860 * preferable to not double-banger the return context next refactor of this - but keeping the attention
1861 * in one place has some advantages as we try to extend this format
1862 *
1863 * @return NULL|string|array a string is returned if $returnSanitisedArray is not set, otherwise and Array or NULL
1864 * depending on whether it is supported as yet
1865 **/
1866 public static function createSQLFilter($fieldName, $filter, $type, $alias = NULL, $returnSanitisedArray = FALSE) {
1867 // http://issues.civicrm.org/jira/browse/CRM-9150 - stick with 'simple' operators for now
1868 // support for other syntaxes is discussed in ticket but being put off for now
1869 $acceptedSQLOperators = array('=', '<=', '>=', '>', '<', 'LIKE', "<>", "!=", "NOT LIKE", 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN');
1870 foreach ($filter as $operator => $criteria) {
1871 if (in_array($operator, $acceptedSQLOperators)) {
1872 switch ($operator) {
1873 // unary operators
1874 case 'IS NULL':
1875 case 'IS NOT NULL':
1876 if(!$returnSanitisedArray) {
1877 return (sprintf('%s %s', $fieldName, $operator));
1878 }
1879 else{
1880 return NULL; // not yet implemented (tests required to implement)
1881 }
1882 break;
1883
1884 // ternary operators
1885 case 'BETWEEN':
1886 case 'NOT BETWEEN':
1887 if (empty($criteria[0]) || empty($criteria[1])) {
1888 throw new Exception("invalid criteria for $operator");
1889 }
1890 if(!$returnSanitisedArray) {
1891 return (sprintf('%s ' . $operator . ' "%s" AND "%s"', $fieldName, CRM_Core_DAO::escapeString($criteria[0]), CRM_Core_DAO::escapeString($criteria[1])));
1892 }
1893 else{
1894 return NULL; // not yet implemented (tests required to implement)
1895 }
1896 break;
1897
1898 // n-ary operators
1899 case 'IN':
1900 case 'NOT IN':
1901 if (empty($criteria)) {
1902 throw new Exception("invalid criteria for $operator");
1903 }
1904 $escapedCriteria = array_map(array(
1905 'CRM_Core_DAO',
1906 'escapeString'
1907 ), $criteria);
1908 if(!$returnSanitisedArray) {
1909 return (sprintf('%s %s ("%s")', $fieldName, $operator, implode('", "', $escapedCriteria)));
1910 }
1911 return $escapedCriteria;
1912 break;
1913
1914 // binary operators
1915
1916 default:
1917 if(!$returnSanitisedArray) {
1918 return(sprintf('%s %s "%s"', $fieldName, $operator, CRM_Core_DAO::escapeString($criteria)));
1919 }
1920 else{
1921 return NULL; // not yet implemented (tests required to implement)
1922 }
1923 }
1924 }
1925 }
1926 }
1927
1928 /**
1929 * SQL has a limit of 64 characters on various names:
1930 * table name, trigger name, column name ...
1931 *
1932 * For custom groups and fields we generated names from user entered input
1933 * which can be longer than this length, this function helps with creating
1934 * strings that meet various criteria.
1935 *
1936 * @param string $string - the string to be shortened
1937 * @param int $length - the max length of the string
1938 */
1939 public static function shortenSQLName($string, $length = 60, $makeRandom = FALSE) {
1940 // early return for strings that meet the requirements
1941 if (strlen($string) <= $length) {
1942 return $string;
1943 }
1944
1945 // easy return for calls that dont need a randomized uniq string
1946 if (! $makeRandom) {
1947 return substr($string, 0, $length);
1948 }
1949
1950 // the string is longer than the length and we need a uniq string
1951 // for the same tablename we need the same uniq string everytime
1952 // hence we use md5 on the string, which is not random
1953 // we'll append 8 characters to the end of the tableName
1954 $md5string = substr(md5($string), 0, 8);
1955 return substr($string, 0, $length - 8) . "_{$md5string}";
1956 }
1957
1958 function setApiFilter(&$params) {}
1959
1960 }