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