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