[BUGFIX] Remove early return in PageTreeDataProvider
[Packages/TYPO3.CMS.git] / t3lib / class.t3lib_userauthgroup.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28 * Contains an extension class specifically for authentication/initialization of backend users in TYPO3
29 *
30 * Revised for TYPO3 3.6 July/2003 by Kasper Skårhøj
31 *
32 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
33 */
34
35
36 /**
37 * Extension to class.t3lib_userauth.php; Authentication of users in TYPO3 Backend
38 *
39 * Actually this class is extended again by t3lib_beuserauth which is the actual backend user class that will be instantiated.
40 * In fact the two classes t3lib_beuserauth and this class could just as well be one, single class since t3lib_userauthgroup is not - to my knowledge - used separately elsewhere. But for historical reasons they are two separate classes.
41 *
42 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
43 * @package TYPO3
44 * @subpackage t3lib
45 */
46 abstract class t3lib_userAuthGroup extends t3lib_userAuth {
47 var $usergroup_column = 'usergroup'; // Should be set to the usergroup-column (id-list) in the user-record
48 var $usergroup_table = 'be_groups'; // The name of the group-table
49
50 // internal
51 var $groupData = array( // This array holds lists of eg. tables, fields and other values related to the permission-system. See fetchGroupData
52 'filemounts' => array() // Filemounts are loaded here
53 );
54 var $workspace = -99; // User workspace. -99 is ERROR (none available), -1 is offline, 0 is online, >0 is custom workspaces.
55 var $workspaceRec = array(); // Custom workspace record if any
56
57 var $userGroups = array(); // This array will hold the groups that the user is a member of
58 var $userGroupsUID = array(); // This array holds the uid's of the groups in the listed order
59 var $groupList = ''; // This is $this->userGroupsUID imploded to a comma list... Will correspond to the 'usergroup_cached_list'
60 var $dataLists = array( // Used internally to accumulate data for the user-group. DONT USE THIS EXTERNALLY! Use $this->groupData instead
61 'webmount_list' => '',
62 'filemount_list' => '',
63 'fileoper_perms' => 0,
64 'modList' => '',
65 'tables_select' => '',
66 'tables_modify' => '',
67 'pagetypes_select' => '',
68 'non_exclude_fields' => '',
69 'explicit_allowdeny' => '',
70 'allowed_languages' => '',
71 'workspace_perms' => '',
72 'custom_options' => '',
73 );
74 var $includeHierarchy = array(); // For debugging/display of order in which subgroups are included.
75 var $includeGroupArray = array(); // List of group_id's in the order they are processed.
76
77 var $OS = ''; // Set to 'WIN', if windows
78 var $TSdataArray = array(); // Used to accumulate the TSconfig data of the user
79 var $userTS_text = ''; // Contains the non-parsed user TSconfig
80 var $userTS = array(); // Contains the parsed user TSconfig
81 var $userTSUpdated = 0; // Set internally if the user TSconfig was parsed and needs to be cached.
82 var $userTS_dontGetCached = 0; // Set this from outside if you want the user TSconfig to ALWAYS be parsed and not fetched from cache.
83
84 var $RTE_errors = array(); // RTE availability errors collected.
85 var $errorMsg = ''; // Contains last error message
86
87 var $checkWorkspaceCurrent_cache = NULL; // Cache for checkWorkspaceCurrent()
88
89
90 /************************************
91 *
92 * Permission checking functions:
93 *
94 ************************************/
95
96 /**
97 * Returns TRUE if user is admin
98 * Basically this function evaluates if the ->user[admin] field has bit 0 set. If so, user is admin.
99 *
100 * @return boolean
101 */
102 function isAdmin() {
103 return (($this->user['admin'] & 1) == 1);
104 }
105
106 /**
107 * Returns TRUE if the current user is a member of group $groupId
108 * $groupId must be set. $this->groupList must contain groups
109 * Will return TRUE also if the user is a member of a group through subgroups.
110 *
111 * @param integer Group ID to look for in $this->groupList
112 * @return boolean
113 */
114 function isMemberOfGroup($groupId) {
115 $groupId = intval($groupId);
116 if ($this->groupList && $groupId) {
117 return t3lib_div::inList($this->groupList, $groupId);
118 }
119 }
120
121 /**
122 * Checks if the permissions is granted based on a page-record ($row) and $perms (binary and'ed)
123 *
124 * Bits for permissions, see $perms variable:
125 *
126 * 1 - Show: See/Copy page and the pagecontent.
127 * 16- Edit pagecontent: Change/Add/Delete/Move pagecontent.
128 * 2- Edit page: Change/Move the page, eg. change title, startdate, hidden.
129 * 4- Delete page: Delete the page and pagecontent.
130 * 8- New pages: Create new pages under the page.
131 *
132 * @param array $row is the pagerow for which the permissions is checked
133 * @param integer $perms is the binary representation of the permission we are going to check. Every bit in this number represents a permission that must be set. See function explanation.
134 * @return boolean TRUE or False upon evaluation
135 */
136 function doesUserHaveAccess($row, $perms) {
137 $userPerms = $this->calcPerms($row);
138 return ($userPerms & $perms) == $perms;
139 }
140
141 /**
142 * Checks if the page id, $id, is found within the webmounts set up for the user.
143 * This should ALWAYS be checked for any page id a user works with, whether it's about reading, writing or whatever.
144 * The point is that this will add the security that a user can NEVER touch parts outside his mounted pages in the page tree. This is otherwise possible if the raw page permissions allows for it. So this security check just makes it easier to make safe user configurations.
145 * If the user is admin OR if this feature is disabled (fx. by setting TYPO3_CONF_VARS['BE']['lockBeUserToDBmounts']=0) then it returns "1" right away
146 * Otherwise the function will return the uid of the webmount which was first found in the rootline of the input page $id
147 *
148 * @param integer Page ID to check
149 * @param string Content of "->getPagePermsClause(1)" (read-permissions). If not set, they will be internally calculated (but if you have the correct value right away you can save that database lookup!)
150 * @param boolean If set, then the function will exit with an error message.
151 * @return integer The page UID of a page in the rootline that matched a mount point
152 */
153 function isInWebMount($id, $readPerms = '', $exitOnError = 0) {
154 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['lockBeUserToDBmounts'] || $this->isAdmin()) {
155 return 1;
156 }
157 $id = intval($id);
158
159 // Check if input id is an offline version page in which case we will map id to the online version:
160 $checkRec = t3lib_beFUnc::getRecord('pages', $id, 'pid,t3ver_oid');
161 if ($checkRec['pid'] == -1) {
162 $id = intval($checkRec['t3ver_oid']);
163 }
164
165 if (!$readPerms) {
166 $readPerms = $this->getPagePermsClause(1);
167 }
168 if ($id > 0) {
169 $wM = $this->returnWebmounts();
170 $rL = t3lib_BEfunc::BEgetRootLine($id, ' AND ' . $readPerms);
171
172 foreach ($rL as $v) {
173 if ($v['uid'] && in_array($v['uid'], $wM)) {
174 return $v['uid'];
175 }
176 }
177 }
178 if ($exitOnError) {
179 throw new RuntimeException('Access Error: This page is not within your DB-mounts', 1294586445);
180 }
181 }
182
183 /**
184 * Checks access to a backend module with the $MCONF passed as first argument
185 *
186 * @param array $MCONF array of a backend module!
187 * @param boolean If set, an array will issue an error message and exit.
188 * @return boolean Will return TRUE if $MCONF['access'] is not set at all, if the BE_USER is admin or if the module is enabled in the be_users/be_groups records of the user (specifically enabled). Will return FALSE if the module name is not even found in $TBE_MODULES
189 */
190 function modAccess($conf, $exitOnError) {
191 if (!t3lib_BEfunc::isModuleSetInTBE_MODULES($conf['name'])) {
192 if ($exitOnError) {
193 throw new RuntimeException('Fatal Error: This module "' . $conf['name'] . '" is not enabled in TBE_MODULES', 1294586446);
194 }
195 return FALSE;
196 }
197
198 // Workspaces check:
199
200 if (t3lib_extMgm::isLoaded('workspaces') && $conf['workspaces']) {
201 if (($this->workspace === 0 && t3lib_div::inList($conf['workspaces'], 'online')) ||
202 ($this->workspace === -1 && t3lib_div::inList($conf['workspaces'], 'offline')) ||
203 ($this->workspace > 0 && t3lib_div::inList($conf['workspaces'], 'custom'))) {
204 // ok, go on...
205 } else {
206 if ($exitOnError) {
207 throw new RuntimeException('Workspace Error: This module "' . $conf['name'] . '" is not available under the current workspace', 1294586447);
208 }
209 return FALSE;
210 }
211 }
212
213 // Returns TRUE if conf[access] is not set at all or if the user is admin
214 if (!$conf['access'] || $this->isAdmin()) {
215 return TRUE;
216 }
217
218 // If $conf['access'] is set but not with 'admin' then we return TRUE, if the module is found in the modList
219 if (!strstr($conf['access'], 'admin') && $conf['name']) {
220 $acs = $this->check('modules', $conf['name']);
221 }
222 if (!$acs && $exitOnError) {
223 throw new RuntimeException('Access Error: You don\'t have access to this module.', 1294586448);
224 } else {
225 return $acs;
226 }
227 }
228
229 /**
230 * Returns a WHERE-clause for the pages-table where user permissions according to input argument, $perms, is validated.
231 * $perms is the "mask" used to select. Fx. if $perms is 1 then you'll get all pages that a user can actually see!
232 * 2^0 = show (1)
233 * 2^1 = edit (2)
234 * 2^2 = delete (4)
235 * 2^3 = new (8)
236 * If the user is 'admin' " 1=1" is returned (no effect)
237 * If the user is not set at all (->user is not an array), then " 1=0" is returned (will cause no selection results at all)
238 * The 95% use of this function is "->getPagePermsClause(1)" which will return WHERE clauses for *selecting* pages in backend listings - in other words this will check read permissions.
239 *
240 * @param integer Permission mask to use, see function description
241 * @return string Part of where clause. Prefix " AND " to this.
242 */
243 function getPagePermsClause($perms) {
244 if (is_array($this->user)) {
245 if ($this->isAdmin()) {
246 return ' 1=1';
247 }
248
249 $perms = intval($perms); // Make sure it's integer.
250 $str = ' (' .
251 '(pages.perms_everybody & ' . $perms . ' = ' . $perms . ')' . // Everybody
252 ' OR (pages.perms_userid = ' . $this->user['uid'] . ' AND pages.perms_user & ' . $perms . ' = ' . $perms . ')'; // User
253 if ($this->groupList) {
254 $str .= ' OR (pages.perms_groupid in (' . $this->groupList . ') AND pages.perms_group & ' . $perms . ' = ' . $perms . ')'; // Group (if any is set)
255 }
256 $str .= ')';
257
258 // ****************
259 // getPagePermsClause-HOOK
260 // ****************
261 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'])) {
262
263 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['getPagePermsClause'] as $_funcRef) {
264 $_params = array('currentClause' => $str, 'perms' => $perms);
265 $str = t3lib_div::callUserFunction($_funcRef, $_params, $this);
266 }
267 }
268
269 return $str;
270 } else {
271 return ' 1=0';
272 }
273 }
274
275 /**
276 * Returns a combined binary representation of the current users permissions for the page-record, $row.
277 * The perms for user, group and everybody is OR'ed together (provided that the page-owner is the user and for the groups that the user is a member of the group
278 * If the user is admin, 31 is returned (full permissions for all five flags)
279 *
280 * @param array Input page row with all perms_* fields available.
281 * @return integer Bitwise representation of the users permissions in relation to input page row, $row
282 */
283 function calcPerms($row) {
284 if ($this->isAdmin()) {
285 return 31;
286 } // Return 31 for admin users.
287
288 $out = 0;
289 if (isset($row['perms_userid']) && isset($row['perms_user']) && isset($row['perms_groupid']) && isset($row['perms_group']) && isset($row['perms_everybody']) && isset($this->groupList)) {
290 if ($this->user['uid'] == $row['perms_userid']) {
291 $out |= $row['perms_user'];
292 }
293 if ($this->isMemberOfGroup($row['perms_groupid'])) {
294 $out |= $row['perms_group'];
295 }
296 $out |= $row['perms_everybody'];
297 }
298
299 // ****************
300 // CALCPERMS hook
301 // ****************
302 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'])) {
303 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['calcPerms'] as $_funcRef) {
304 $_params = array(
305 'row' => $row,
306 'outputPermissions' => $out
307 );
308 $out = t3lib_div::callUserFunction($_funcRef, $_params, $this);
309 }
310 }
311
312 return $out;
313 }
314
315 /**
316 * Returns TRUE if the RTE (Rich Text Editor) can be enabled for the user
317 * Strictly this is not permissions being checked but rather a series of settings like a loaded extension, browser/client type and a configuration option in ->uc[edit_RTE]
318 * The reasons for a FALSE return can be found in $this->RTE_errors
319 *
320 * @return boolean
321 */
322 function isRTE() {
323 // Start:
324 $this->RTE_errors = array();
325 if (!$this->uc['edit_RTE']) {
326 $this->RTE_errors[] = 'RTE is not enabled for user!';
327 }
328 if (!$GLOBALS['TYPO3_CONF_VARS']['BE']['RTEenabled']) {
329 $this->RTE_errors[] = 'RTE is not enabled in $TYPO3_CONF_VARS["BE"]["RTEenabled"]';
330 }
331
332
333 // Acquire RTE object:
334 $RTE = t3lib_BEfunc::RTEgetObj();
335 if (!is_object($RTE)) {
336 $this->RTE_errors = array_merge($this->RTE_errors, $RTE);
337 }
338
339 if (!count($this->RTE_errors)) {
340 return TRUE;
341 } else {
342 return FALSE;
343 }
344 }
345
346 /**
347 * Returns TRUE if the $value is found in the list in a $this->groupData[] index pointed to by $type (array key).
348 * Can thus be users to check for modules, exclude-fields, select/modify permissions for tables etc.
349 * If user is admin TRUE is also returned
350 * Please see the document Inside TYPO3 for examples.
351 *
352 * @param string The type value; "webmounts", "filemounts", "pagetypes_select", "tables_select", "tables_modify", "non_exclude_fields", "modules"
353 * @param string String to search for in the groupData-list
354 * @return boolean TRUE if permission is granted (that is, the value was found in the groupData list - or the BE_USER is "admin")
355 */
356 function check($type, $value) {
357 if (isset($this->groupData[$type])) {
358 if ($this->isAdmin() || t3lib_div::inList($this->groupData[$type], $value)) {
359 return TRUE;
360 }
361 }
362 return FALSE;
363 }
364
365 /**
366 * Checking the authMode of a select field with authMode set
367 *
368 * @param string Table name
369 * @param string Field name (must be configured in TCA and of type "select" with authMode set!)
370 * @param string Value to evaluation (single value, must not contain any of the chars ":,|")
371 * @param string Auth mode keyword (explicitAllow, explicitDeny, individual)
372 * @return boolean TRUE or FALSE whether access is granted or not.
373 */
374 function checkAuthMode($table, $field, $value, $authMode) {
375
376 // Admin users can do anything:
377 if ($this->isAdmin()) {
378 return TRUE;
379 }
380
381 // Allow all blank values:
382 if (!strcmp($value, '')) {
383 return TRUE;
384 }
385
386 // Certain characters are not allowed in the value
387 if (preg_match('/[:|,]/', $value)) {
388 return FALSE;
389 }
390
391 // Initialize:
392 $testValue = $table . ':' . $field . ':' . $value;
393 $out = TRUE;
394
395 // Checking value:
396 switch ((string) $authMode) {
397 case 'explicitAllow':
398 if (!t3lib_div::inList($this->groupData['explicit_allowdeny'], $testValue . ':ALLOW')) {
399 $out = FALSE;
400 }
401 break;
402 case 'explicitDeny':
403 if (t3lib_div::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
404 $out = FALSE;
405 }
406 break;
407 case 'individual':
408 t3lib_div::loadTCA($table);
409 if (is_array($GLOBALS['TCA'][$table]) && is_array($GLOBALS['TCA'][$table]['columns'][$field])) {
410 $items = $GLOBALS['TCA'][$table]['columns'][$field]['config']['items'];
411 if (is_array($items)) {
412 foreach ($items as $iCfg) {
413 if (!strcmp($iCfg[1], $value) && $iCfg[4]) {
414 switch ((string) $iCfg[4]) {
415 case 'EXPL_ALLOW':
416 if (!t3lib_div::inList($this->groupData['explicit_allowdeny'], $testValue . ':ALLOW')) {
417 $out = FALSE;
418 }
419 break;
420 case 'EXPL_DENY':
421 if (t3lib_div::inList($this->groupData['explicit_allowdeny'], $testValue . ':DENY')) {
422 $out = FALSE;
423 }
424 break;
425 }
426 break;
427 }
428 }
429 }
430 }
431 break;
432 }
433
434 return $out;
435 }
436
437 /**
438 * Checking if a language value (-1, 0 and >0 for sys_language records) is allowed to be edited by the user.
439 *
440 * @param integer Language value to evaluate
441 * @return boolean Returns TRUE if the language value is allowed, otherwise FALSE.
442 */
443 function checkLanguageAccess($langValue) {
444 if (strcmp(trim($this->groupData['allowed_languages']), '')) { // The users language list must be non-blank - otherwise all languages are allowed.
445 $langValue = intval($langValue);
446 if ($langValue != -1 && !$this->check('allowed_languages', $langValue)) { // Language must either be explicitly allowed OR the lang Value be "-1" (all languages)
447 return FALSE;
448 }
449 }
450 return TRUE;
451 }
452
453 /**
454 * Check if user has access to all existing localizations for a certain record
455 *
456 * @param string the table
457 * @param array the current record
458 * @return boolean
459 */
460 function checkFullLanguagesAccess($table, $record) {
461 $recordLocalizationAccess = $this->checkLanguageAccess(0);
462 if ($recordLocalizationAccess
463 && (
464 t3lib_BEfunc::isTableLocalizable($table)
465 || isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])
466 )
467 ) {
468
469 if (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable'])) {
470 $l10nTable = $GLOBALS['TCA'][$table]['ctrl']['transForeignTable'];
471 $pointerField = $GLOBALS['TCA'][$l10nTable]['ctrl']['transOrigPointerField'];
472 $pointerValue = $record['uid'];
473 } else {
474 $l10nTable = $table;
475 $pointerField = $GLOBALS['TCA'][$l10nTable]['ctrl']['transOrigPointerField'];
476 $pointerValue = $record[$pointerField] > 0 ? $record[$pointerField] : $record['uid'];
477 }
478
479 $recordLocalizations = t3lib_BEfunc::getRecordsByField(
480 $l10nTable,
481 $pointerField,
482 $pointerValue,
483 '',
484 '',
485 '',
486 '1'
487 );
488
489 if (is_array($recordLocalizations)) {
490 foreach ($recordLocalizations as $localization) {
491 $recordLocalizationAccess = $recordLocalizationAccess
492 && $this->checkLanguageAccess($localization[$GLOBALS['TCA'][$l10nTable]['ctrl']['languageField']]);
493 if (!$recordLocalizationAccess) {
494 break;
495 }
496 }
497 }
498
499 }
500 return $recordLocalizationAccess;
501 }
502
503 /**
504 * Checking if a user has editing access to a record from a $GLOBALS['TCA'] table.
505 * The checks does not take page permissions and other "environmental" things into account. It only deal with record internals; If any values in the record fields disallows it.
506 * For instance languages settings, authMode selector boxes are evaluated (and maybe more in the future).
507 * It will check for workspace dependent access.
508 * The function takes an ID (integer) or row (array) as second argument.
509 *
510 * @param string Table name
511 * @param mixed If integer, then this is the ID of the record. If Array this just represents fields in the record.
512 * @param boolean Set, if testing a new (non-existing) record array. Will disable certain checks that doesn't make much sense in that context.
513 * @param boolean Set, if testing a deleted record array.
514 * @param boolean Set, whenever access to all translations of the record is required
515 * @return boolean TRUE if OK, otherwise FALSE
516 */
517 function recordEditAccessInternals($table, $idOrRow, $newRecord = FALSE, $deletedRecord = FALSE, $checkFullLanguageAccess = FALSE) {
518 if (isset($GLOBALS['TCA'][$table])) {
519 t3lib_div::loadTCA($table);
520
521 // Always return TRUE for Admin users.
522 if ($this->isAdmin()) {
523 return TRUE;
524 }
525
526 // Fetching the record if the $idOrRow variable was not an array on input:
527 if (!is_array($idOrRow)) {
528 if ($deletedRecord) {
529 $idOrRow = t3lib_BEfunc::getRecord($table, $idOrRow, '*', '', FALSE);
530 } else {
531 $idOrRow = t3lib_BEfunc::getRecord($table, $idOrRow);
532 }
533 if (!is_array($idOrRow)) {
534 $this->errorMsg = 'ERROR: Record could not be fetched.';
535 return FALSE;
536 }
537 }
538
539 // Checking languages:
540 if ($GLOBALS['TCA'][$table]['ctrl']['languageField']) {
541 if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) { // Language field must be found in input row - otherwise it does not make sense.
542 if (!$this->checkLanguageAccess($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']])) {
543 $this->errorMsg = 'ERROR: Language was not allowed.';
544 return FALSE;
545 } elseif ($checkFullLanguageAccess && $idOrRow[$GLOBALS['TCA'][$table]['ctrl']['languageField']] == 0 && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
546 $this->errorMsg = 'ERROR: Related/affected language was not allowed.';
547 return FALSE;
548 }
549 } else {
550 $this->errorMsg = 'ERROR: The "languageField" field named "' .
551 $GLOBALS['TCA'][$table]['ctrl']['languageField'] .
552 '" was not found in testing record!';
553 return FALSE;
554 }
555 } elseif (isset($GLOBALS['TCA'][$table]['ctrl']['transForeignTable']) && $checkFullLanguageAccess && !$this->checkFullLanguagesAccess($table, $idOrRow)) {
556 return FALSE;
557 }
558
559 // Checking authMode fields:
560 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
561 foreach ($GLOBALS['TCA'][$table]['columns'] as $fieldName => $fieldValue) {
562 if (isset($idOrRow[$fieldName])) {
563 if ($fieldValue['config']['type'] == 'select' && $fieldValue['config']['authMode'] && !strcmp($fieldValue['config']['authMode_enforce'], 'strict')) {
564 if (!$this->checkAuthMode($table, $fieldName, $idOrRow[$fieldName], $fieldValue['config']['authMode'])) {
565 $this->errorMsg = 'ERROR: authMode "' . $fieldValue['config']['authMode'] . '" failed for field "' . $fieldName . '" with value "' . $idOrRow[$fieldName] . '" evaluated';
566 return FALSE;
567 }
568 }
569 }
570 }
571 }
572
573 // Checking "editlock" feature (doesn't apply to new records)
574 if (!$newRecord && $GLOBALS['TCA'][$table]['ctrl']['editlock']) {
575 if (isset($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']])) {
576 if ($idOrRow[$GLOBALS['TCA'][$table]['ctrl']['editlock']]) {
577 $this->errorMsg = 'ERROR: Record was locked for editing. Only admin users can change this state.';
578 return FALSE;
579 }
580 } else {
581 $this->errorMsg = 'ERROR: The "editLock" field named "' .
582 $GLOBALS['TCA'][$table]['ctrl']['editlock'] .
583 '" was not found in testing record!';
584 return FALSE;
585 }
586 }
587
588 // Checking record permissions
589 // THIS is where we can include a check for "perms_" fields for other records than pages...
590
591 // Process any hooks
592 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'])) {
593 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['recordEditAccessInternals'] as $funcRef) {
594 $params = array(
595 'table' => $table,
596 'idOrRow' => $idOrRow,
597 'newRecord' => $newRecord
598 );
599 if (!t3lib_div::callUserFunction($funcRef, $params, $this)) {
600 return FALSE;
601 }
602 }
603 }
604
605 // Finally, return TRUE if all is well.
606 return TRUE;
607 }
608 }
609
610 /**
611 * Checks a type of permission against the compiled permission integer, $compiledPermissions, and in relation to table, $tableName
612 *
613 * @param integer $compiledPermissions could typically be the "compiled permissions" integer returned by ->calcPerms
614 * @param string $tableName is the tablename to check: If "pages" table then edit,new,delete and editcontent permissions can be checked. Other tables will be checked for "editcontent" only (and $type will be ignored)
615 * @param string For $tableName='pages' this can be 'edit' (2), 'new' (8 or 16), 'delete' (4), 'editcontent' (16). For all other tables this is ignored. (16 is used)
616 * @return boolean
617 * @access public (used by typo3/alt_clickmenu.php)
618 */
619 public function isPSet($compiledPermissions, $tableName, $actionType = '') {
620 if ($this->isAdmin()) {
621 $result = TRUE;
622 }
623 elseif ($tableName == 'pages') {
624 switch ($actionType) {
625 case 'edit':
626 $result = ($compiledPermissions & 2) !== 0;
627 break;
628 case 'new':
629 // Create new page OR page content
630 $result = ($compiledPermissions & (8 + 16)) !== 0;
631 break;
632 case 'delete':
633 $result = ($compiledPermissions & 4) !== 0;
634 break;
635 case 'editcontent':
636 $result = ($compiledPermissions & 16) !== 0;
637 break;
638 default:
639 $result = FALSE;
640 }
641 } else {
642 $result = ($compiledPermissions & 16) !== 0;
643 }
644 return $result;
645 }
646
647 /**
648 * Returns TRUE if the BE_USER is allowed to *create* shortcuts in the backend modules
649 *
650 * @return boolean
651 */
652 function mayMakeShortcut() {
653 return $this->getTSConfigVal('options.enableBookmarks') && !$this->getTSConfigVal('options.mayNotCreateEditBookmarks');
654 }
655
656 /**
657 * Checking if editing of an existing record is allowed in current workspace if that is offline.
658 * Rules for editing in offline mode:
659 * - record supports versioning and is an offline version from workspace and has the corrent stage
660 * - or record (any) is in a branch where there is a page which is a version from the workspace and where the stage is not preventing records
661 *
662 * @param string Table of record
663 * @param array Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
664 * @return string String error code, telling the failure state. FALSE=All ok
665 */
666 function workspaceCannotEditRecord($table, $recData) {
667
668 if ($this->workspace !== 0) { // Only test offline spaces:
669
670 if (!is_array($recData)) {
671 $recData = t3lib_BEfunc::getRecord($table, $recData, 'pid' . ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] ? ',t3ver_wsid,t3ver_stage' : ''));
672 }
673
674 if (is_array($recData)) {
675 if ((int) $recData['pid'] === -1) { // We are testing a "version" (identified by a pid of -1): it can be edited provided that workspace matches and versioning is enabled for the table.
676 if (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) { // No versioning, basic error, inconsistency even! Such records should not have a pid of -1!
677 return 'Versioning disabled for table';
678 } elseif ((int) $recData['t3ver_wsid'] !== $this->workspace) { // So does workspace match?
679 return 'Workspace ID of record didn\'t match current workspace';
680 } else {
681 // So is the user allowed to "use" the edit stage within the workspace?
682 return $this->workspaceCheckStageForCurrent(0) ? FALSE : 'User\'s access level did not allow for editing';
683 }
684 } else { // We are testing a "live" record:
685 if ($res = $this->workspaceAllowLiveRecordsInPID($recData['pid'], $table)) { // For "Live" records, check that PID for table allows editing
686 // Live records are OK in this branch, but what about the stage of branch point, if any:
687 return $res > 0 ? FALSE : 'Stage for versioning root point and users access level did not allow for editing'; // OK
688 } else { // If not offline and not in versionized branch, output error:
689 return 'Online record was not in versionized branch!';
690 }
691 }
692 } else {
693 return 'No record';
694 }
695 } else {
696 return FALSE; // OK because workspace is 0
697 }
698 }
699
700 /**
701 * Evaluates if a user is allowed to edit the offline version
702 *
703 * @param string Table of record
704 * @param array Integer (record uid) or array where fields are at least: pid, t3ver_wsid, t3ver_stage (if versioningWS is set)
705 * @return string String error code, telling the failure state. FALSE=All ok
706 * @see workspaceCannotEditRecord()
707 */
708 function workspaceCannotEditOfflineVersion($table, $recData) {
709 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
710
711 if (!is_array($recData)) {
712 $recData = t3lib_BEfunc::getRecord($table, $recData, 'uid,pid,t3ver_wsid,t3ver_stage');
713 }
714 if (is_array($recData)) {
715 if ((int) $recData['pid'] === -1) {
716 return $this->workspaceCannotEditRecord($table, $recData);
717 } else {
718 return 'Not an offline version';
719 }
720 } else {
721 return 'No record';
722 }
723 } else {
724 return 'Table does not support versioning.';
725 }
726 }
727
728 /**
729 * Check if "live" records from $table may be created or edited in this PID.
730 * If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
731 * If the answer is 1 or 2 it means it is OK to create a record, if -1 it means that it is OK in terms of versioning because the element was within a versionized branch but NOT ok in terms of the state the root point had!
732 *
733 * @param integer PID value to check for.
734 * @param string Table name
735 * @return mixed Returns FALSE if a live record cannot be created and must be versionized in order to do so. 2 means a) Workspace is "Live" or workspace allows "live edit" of records from non-versionized tables (and the $table is not versionizable). 1 and -1 means the pid is inside a versionized branch where -1 means that the branch-point did NOT allow a new record according to its state.
736 */
737 function workspaceAllowLiveRecordsInPID($pid, $table) {
738
739 // Always for Live workspace AND if live-edit is enabled and tables are completely without versioning it is ok as well.
740 if ($this->workspace === 0 || ($this->workspaceRec['live_edit'] && !$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) || $GLOBALS['TCA'][$table]['ctrl']['versioningWS_alwaysAllowLiveEdit']) {
741 return 2; // OK to create for this table.
742 } elseif (t3lib_BEfunc::isPidInVersionizedBranch($pid, $table)) { // Check if records from $table can be created with this PID: Either if inside "branch" versioning type or a "versioning_followPages" table on a "page" versioning type.
743 // Now, check what the stage of that "page" or "branch" version type is:
744 $stage = t3lib_BEfunc::isPidInVersionizedBranch($pid, $table, TRUE);
745 return $this->workspaceCheckStageForCurrent($stage) ? 1 : -1;
746 } else {
747 return FALSE; // If the answer is FALSE it means the only valid way to create or edit records in the PID is by versioning
748 }
749 }
750
751 /**
752 * Evaluates if a record from $table can be created in $pid
753 *
754 * @param integer Page id. This value must be the _ORIG_uid if available: So when you have pages versionized as "page" or "element" you must supply the id of the page version in the workspace!
755 * @param string Table name
756 * @return boolean TRUE if OK.
757 */
758 function workspaceCreateNewRecord($pid, $table) {
759 if ($res = $this->workspaceAllowLiveRecordsInPID($pid, $table)) { // If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
760 if ($res < 0) {
761 return FALSE; // Stage for versioning root point and users access level did not allow for editing
762 }
763 } elseif (!$GLOBALS['TCA'][$table]['ctrl']['versioningWS']) { // So, if no live records were allowed, we have to create a new version of this record:
764 return FALSE;
765 }
766 return TRUE;
767 }
768
769 /**
770 * Evaluates if auto creation of a version of a record is allowed.
771 *
772 * @param string Table of the record
773 * @param integer UID of record
774 * @param integer PID of record
775 * @return boolean TRUE if ok.
776 */
777 function workspaceAllowAutoCreation($table, $id, $recpid) {
778 // Auto-creation of version: In offline workspace, test if versioning is enabled and look for workspace version of input record. If there is no versionized record found we will create one and save to that.
779 if ($this->workspace !== 0 // Only in draft workspaces
780 && !$this->workspaceRec['disable_autocreate'] // Auto-creation must not be disabled.
781 && $GLOBALS['TCA'][$table]['ctrl']['versioningWS'] // Table must be versionizable
782 && $recpid >= 0 // The PID of the record must NOT be -1 or less (would indicate that it already was a version!)
783 && !t3lib_BEfunc::getWorkspaceVersionOfRecord($this->workspace, $table, $id, 'uid') // There must be no existing version of this record in workspace.
784 && !t3lib_BEfunc::isPidInVersionizedBranch($recpid, $table)) { // PID must NOT be in a versionized branch either
785 return TRUE;
786 } elseif ($this->workspaceRec['disable_autocreate']) {
787 t3lib_div::deprecationLog('Usage of disable_autocreate feature is deprecated since 4.5.');
788 }
789 }
790
791 /**
792 * Checks if an element stage allows access for the user in the current workspace
793 * In workspaces 0 (Live) and -1 (Default draft) access is always granted for any stage.
794 * Admins are always allowed.
795 * An option for custom workspaces allows members to also edit when the stage is "Review"
796 *
797 * @param integer Stage id from an element: -1,0 = editing, 1 = reviewer, >1 = owner
798 * @return boolean TRUE if user is allowed access
799 */
800 function workspaceCheckStageForCurrent($stage) {
801 $stage = intval($stage);
802 if ($this->isAdmin()) {
803 return TRUE;
804 }
805
806 if ($this->workspace > 0 && t3lib_extMgm::isLoaded('workspaces')) {
807 $stat = $this->checkWorkspaceCurrent();
808
809 // Check if custom staging is activated
810 $workspaceRec = t3lib_BEfunc::getRecord('sys_workspace', $stat['uid']);
811 if ($workspaceRec['custom_stages'] > 0 && $stage !== 0 && $stage !== '-10') {
812
813 // Get custom stage record
814 $workspaceStageRec = t3lib_BEfunc::getRecord('sys_workspace_stage', $stage);
815 // Check if the user is responsible for the current stage
816 if ((t3lib_div::inList($workspaceStageRec['responsible_persons'], 'be_users_' . $this->user['uid'])
817 && $stat['_ACCESS'] === 'member')
818 || $stat['_ACCESS'] === 'owner') {
819 return TRUE;
820 }
821
822 // Check if the user is in a group which is responsible for the current stage
823 foreach ($this->userGroupsUID as $groupUid) {
824 if ((t3lib_div::inList($workspaceStageRec['responsible_persons'], 'be_groups_' . $groupUid)
825 && $stat['_ACCESS'] === 'member')
826 || $stat['_ACCESS'] === 'owner') {
827 return TRUE;
828 }
829 }
830 // only owner is allowed to change records which are "ready to publish"
831 } elseif ($stage == '-10' || $stage == '-20') {
832 if ($stat['_ACCESS'] === 'owner') {
833 return TRUE;
834 } else {
835 return FALSE;
836 }
837 } else {
838 $memberStageLimit = $this->workspaceRec['review_stage_edit'] ? 1 : 0;
839 if (($stage <= $memberStageLimit && $stat['_ACCESS'] === 'member')
840 || ($stage <= 1 && $stat['_ACCESS'] === 'reviewer')
841 || $stat['_ACCESS'] === 'owner') {
842 return TRUE;
843 }
844 }
845 } else {
846 return TRUE;
847 } // Always OK for live and draft workspaces.
848 }
849
850 /**
851 * Returns TRUE if the user has access to publish content from the workspace ID given.
852 * Admin-users are always granted access to do this
853 * If the workspace ID is 0 (live) all users have access also
854 * For custom workspaces it depends on whether the user is owner OR like with draft workspace if the user has access to Live workspace.
855 *
856 * @param integer Workspace UID; 0,1+
857 * @return boolean Returns TRUE if the user has access to publish content from the workspace ID given.
858 */
859 function workspacePublishAccess($wsid) {
860 if ($this->isAdmin()) {
861 return TRUE;
862 }
863
864 // If no access to workspace, of course you cannot publish!
865 $retVal = FALSE;
866
867 $wsAccess = $this->checkWorkspace($wsid);
868 if ($wsAccess) {
869 switch ($wsAccess['uid']) {
870 case 0: // Live workspace
871 $retVal = TRUE; // If access to Live workspace, no problem.
872 break;
873 default: // Custom workspace
874 $retVal = $wsAccess['_ACCESS'] === 'owner' || ($this->checkWorkspace(0) && !($wsAccess['publish_access'] & 2)); // Either be an adminuser OR have access to online workspace which is OK as well as long as publishing access is not limited by workspace option.
875 break;
876 }
877 }
878 return $retVal;
879 }
880
881 /**
882 * Workspace swap-mode access?
883 *
884 * @return boolean Returns TRUE if records can be swapped in the current workspace, otherwise FALSE
885 */
886 function workspaceSwapAccess() {
887 if ($this->workspace > 0 && (int) $this->workspaceRec['swap_modes'] === 2) {
888 return FALSE;
889 } else {
890 return TRUE;
891 }
892 }
893
894 /**
895 * Workspace Versioning type access. Check wether the requsted type of versioning (element/page/branch) is allowd in current workspace
896 * (element/pages/branches type of versioning can/could be set on custom workspaces on filed "vtype")
897 *
898 * @todo workspacecleanup: this seems mostly obsolete and should be removed
899 * @param integer Versioning type to evaluation: -1, 0, >1
900 * 0 = page (deprecated)
901 * -1 = element
902 * >1 = branch (deprecated), indicating the "nesting" level
903 * @return boolean TRUE if OK
904 */
905 function workspaceVersioningTypeAccess($type) {
906 $retVal = FALSE;
907
908 $type = t3lib_utility_Math::forceIntegerInRange($type, -1);
909
910 // Check if only element versioning is allowed:
911 if ($type != -1) {
912 return FALSE;
913 }
914
915 if ($this->workspace > 0 && !$this->isAdmin()) {
916 $stat = $this->checkWorkspaceCurrent();
917 if ($stat['_ACCESS'] !== 'owner') {
918
919 switch ((int) $type) {
920 case -1:
921 $retVal = $this->workspaceRec['vtypes'] & 1 ? FALSE : TRUE;
922 break;
923 case 0:
924 $retVal = $this->workspaceRec['vtypes'] & 2 ? FALSE : TRUE;
925 break;
926 default:
927 $retVal = $this->workspaceRec['vtypes'] & 4 ? FALSE : TRUE;
928 break;
929 }
930 } else {
931 $retVal = TRUE;
932 }
933 } else {
934 $retVal = TRUE;
935 }
936
937 return $retVal;
938 }
939
940 /**
941 * Finding "closest" versioning type, used for creation of new records.
942 *
943 * @see workspaceVersioningTypeAccess() for hints on $type
944 * @param integer Versioning type to evaluation: -1, 0, >1
945 * @return integer Returning versioning type
946 */
947 function workspaceVersioningTypeGetClosest($type) {
948 $type = t3lib_utility_Math::forceIntegerInRange($type, -1);
949
950 if ($this->workspace > 0) {
951 switch ((int) $type) {
952 case -1:
953 $type = -1;
954 break;
955 case 0:
956 $type = $this->workspaceVersioningTypeAccess($type) ? $type : -1;
957 break;
958 default:
959 $type = $this->workspaceVersioningTypeAccess($type) ? $type : ($this->workspaceVersioningTypeAccess(0) ? 0 : -1);
960 break;
961 }
962 }
963 return $type;
964 }
965
966
967 /*************************************
968 *
969 * Miscellaneous functions
970 *
971 *************************************/
972
973 /**
974 * Returns the value/properties of a TS-object as given by $objectString, eg. 'options.dontMountAdminMounts'
975 * Nice (general!) function for returning a part of a TypoScript array!
976 *
977 * @param string Pointer to an "object" in the TypoScript array, fx. 'options.dontMountAdminMounts'
978 * @param array Optional TSconfig array: If array, then this is used and not $this->userTS. If not array, $this->userTS is used.
979 * @return array An array with two keys, "value" and "properties" where "value" is a string with the value of the objectsting and "properties" is an array with the properties of the objectstring.
980 * @params array An array with the TypoScript where the $objectString is located. If this argument is not an array, then internal ->userTS (User TSconfig for the current BE_USER) will be used instead.
981 */
982 function getTSConfig($objectString, $config = '') {
983 if (!is_array($config)) {
984 $config = $this->userTS; // Getting Root-ts if not sent
985 }
986 $TSConf = array();
987 $parts = explode('.', $objectString, 2);
988 $key = $parts[0];
989 if (trim($key)) {
990 if (count($parts) > 1 && trim($parts[1])) {
991 // Go on, get the next level
992 if (is_array($config[$key . '.'])) {
993 $TSConf = $this->getTSConfig($parts[1], $config[$key . '.']);
994 }
995 } else {
996 $TSConf['value'] = $config[$key];
997 $TSConf['properties'] = $config[$key . '.'];
998 }
999 }
1000 return $TSConf;
1001 }
1002
1003 /**
1004 * Returns the "value" of the $objectString from the BE_USERS "User TSconfig" array
1005 *
1006 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
1007 * @return string The value for that object string (object path)
1008 * @see getTSConfig()
1009 */
1010 function getTSConfigVal($objectString) {
1011 $TSConf = $this->getTSConfig($objectString);
1012 return $TSConf['value'];
1013 }
1014
1015 /**
1016 * Returns the "properties" of the $objectString from the BE_USERS "User TSconfig" array
1017 *
1018 * @param string Object string, eg. "somestring.someproperty.somesubproperty"
1019 * @return array The properties for that object string (object path) - if any
1020 * @see getTSConfig()
1021 */
1022 function getTSConfigProp($objectString) {
1023 $TSConf = $this->getTSConfig($objectString);
1024 return $TSConf['properties'];
1025 }
1026
1027 /**
1028 * Returns TRUE if $item is in $in_list
1029 *
1030 * @param string Comma list with items, no spaces between items!
1031 * @param string The string to find in the list of items
1032 * @return string Boolean
1033 * @deprecated since TYPO3 4.7, should be removed in TYPO3 4.9, use equivalent function t3lib_div::inList()
1034 */
1035 function inList($in_list, $item) {
1036 t3lib_div::logDeprecatedFunction();
1037 return t3lib_div::inList($in_list, $item);
1038 }
1039
1040 /**
1041 * Returns an array with the webmounts.
1042 * If no webmounts, and empty array is returned.
1043 * NOTICE: Deleted pages WILL NOT be filtered out! So if a mounted page has been deleted it is STILL coming out as a webmount. This is not checked due to performance.
1044 *
1045 * @return array
1046 */
1047 function returnWebmounts() {
1048 return (string) ($this->groupData['webmounts']) != '' ? explode(',', $this->groupData['webmounts']) : array();
1049 }
1050
1051 /**
1052 * Returns an array with the filemounts for the user. Each filemount is represented with an array of a "name", "path" and "type".
1053 * If no filemounts an empty array is returned.
1054 *
1055 * @return array
1056 */
1057 function returnFilemounts() {
1058 return $this->groupData['filemounts'];
1059 }
1060
1061 /**
1062 * Returns an integer bitmask that represents the permissions for file operations.
1063 * Permissions of the user and groups the user is a member of were combined by a logical OR.
1064 *
1065 * Meaning of each bit:
1066 * 1 - Files: Upload,Copy,Move,Delete,Rename
1067 * 2 - Files: Unzip
1068 * 4 - Directory: Move,Delete,Rename,New
1069 * 8 - Directory: Copy
1070 * 16 - Directory: Delete recursively (rm -Rf)
1071 *
1072 * @return integer File operation permission bitmask
1073 */
1074 public function getFileoperationPermissions() {
1075 if ($this->isAdmin()) {
1076 return 31;
1077 } else {
1078 return $this->groupData['fileoper_perms'];
1079 }
1080 }
1081
1082 /**
1083 * Returns TRUE or FALSE, depending if an alert popup (a javascript confirmation) should be shown
1084 * call like $GLOBALS['BE_USER']->jsConfirmation($BITMASK)
1085 *
1086 * 1 - typeChange
1087 * 2 - copy/move/paste
1088 * 4 - delete
1089 * 8 - frontend editing
1090 * 128 - other (not used yet)
1091 *
1092 * @param integer Bitmask
1093 * @return boolean TRUE if the confirmation should be shown
1094 */
1095 function jsConfirmation($bitmask) {
1096 $alertPopup = $GLOBALS['BE_USER']->getTSConfig('options.alertPopups');
1097 if (empty($alertPopup['value'])) {
1098 $alertPopup = 255; // default: show all warnings
1099 } else {
1100 $alertPopup = (int) $alertPopup['value'];
1101 }
1102 if (($alertPopup & $bitmask) == $bitmask) { // show confirmation
1103 return 1;
1104 } else { // don't show confirmation
1105 return 0;
1106 }
1107 }
1108
1109
1110 /*************************************
1111 *
1112 * Authentication methods
1113 *
1114 *************************************/
1115
1116
1117 /**
1118 * Initializes a lot of stuff like the access-lists, database-mountpoints and filemountpoints
1119 * This method is called by ->backendCheckLogin() (from extending class t3lib_beuserauth) if the backend user login has verified OK.
1120 * Generally this is required initialization of a backend user.
1121 *
1122 * @return void
1123 * @access private
1124 * @see t3lib_TSparser
1125 */
1126 function fetchGroupData() {
1127 if ($this->user['uid']) {
1128
1129 // Get lists for the be_user record and set them as default/primary values.
1130 $this->dataLists['modList'] = $this->user['userMods']; // Enabled Backend Modules
1131 $this->dataLists['allowed_languages'] = $this->user['allowed_languages']; // Add Allowed Languages
1132 $this->dataLists['workspace_perms'] = $this->user['workspace_perms']; // Set user value for workspace permissions.
1133 $this->dataLists['webmount_list'] = $this->user['db_mountpoints']; // Database mountpoints
1134 $this->dataLists['filemount_list'] = $this->user['file_mountpoints']; // File mountpoints
1135 $this->dataLists['fileoper_perms'] = (int) $this->user['fileoper_perms']; // Fileoperation permissions
1136
1137 // Setting default User TSconfig:
1138 $this->TSdataArray[] = $this->addTScomment('From $GLOBALS["TYPO3_CONF_VARS"]["BE"]["defaultUserTSconfig"]:') .
1139 $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultUserTSconfig'];
1140
1141 // Default TSconfig for admin-users
1142 if ($this->isAdmin()) {
1143 $this->TSdataArray[] = $this->addTScomment('"admin" user presets:') . '
1144 admPanel.enable.all = 1
1145 ';
1146 if (t3lib_extMgm::isLoaded('sys_note')) {
1147 $this->TSdataArray[] = '
1148 // Setting defaults for sys_note author / email...
1149 TCAdefaults.sys_note.author = ' . $this->user['realName'] . '
1150 TCAdefaults.sys_note.email = ' . $this->user['email'] . '
1151 ';
1152 }
1153 }
1154
1155 // FILE MOUNTS:
1156 // Admin users has the base fileadmin dir mounted
1157 if ($this->isAdmin() && $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
1158 $this->addFileMount($GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], '', PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'], 0, '');
1159 }
1160
1161 // If userHomePath is set, we attempt to mount it
1162 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath']) {
1163 // First try and mount with [uid]_[username]
1164 $didMount = $this->addFileMount($this->user['username'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'] . $this->user['uid'] . '_' . $this->user['username'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'], 0, 'user');
1165 if (!$didMount) {
1166 // If that failed, try and mount with only [uid]
1167 $this->addFileMount($this->user['username'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['userHomePath'] . $this->user['uid'] . $GLOBALS['TYPO3_CONF_VARS']['BE']['userUploadDir'], 0, 'user');
1168 }
1169 }
1170
1171 // BE_GROUPS:
1172 // Get the groups...
1173 # $grList = t3lib_BEfunc::getSQLselectableList($this->user[$this->usergroup_column],$this->usergroup_table,$this->usergroup_table);
1174 $grList = $GLOBALS['TYPO3_DB']->cleanIntList($this->user[$this->usergroup_column]); // 240203: Since the group-field never contains any references to groups with a prepended table name we think it's safe to just intExplode and re-implode - which should be much faster than the other function call.
1175 if ($grList) {
1176 // Fetch groups will add a lot of information to the internal arrays: modules, accesslists, TSconfig etc. Refer to fetchGroups() function.
1177 $this->fetchGroups($grList);
1178 }
1179
1180 // Add the TSconfig for this specific user:
1181 $this->TSdataArray[] = $this->addTScomment('USER TSconfig field') . $this->user['TSconfig'];
1182 // Check include lines.
1183 $this->TSdataArray = t3lib_TSparser::checkIncludeLines_array($this->TSdataArray);
1184
1185 $this->userTS_text = implode(LF . '[GLOBAL]' . LF, $this->TSdataArray); // Imploding with "[global]" will make sure that non-ended confinements with braces are ignored.
1186
1187 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['TSconfigConditions'] && !$this->userTS_dontGetCached) {
1188 // Perform TS-Config parsing with condition matching
1189 $parseObj = t3lib_div::makeInstance('t3lib_TSparser_TSconfig');
1190 $res = $parseObj->parseTSconfig($this->userTS_text, 'userTS');
1191 if ($res) {
1192 $this->userTS = $res['TSconfig'];
1193 $this->userTSUpdated = ($res['cached'] ? 0 : 1);
1194 }
1195 } else {
1196 // Parsing the user TSconfig (or getting from cache)
1197 $hash = md5('userTS:' . $this->userTS_text);
1198 $cachedContent = t3lib_BEfunc::getHash($hash);
1199 if (isset($cachedContent) && !$this->userTS_dontGetCached) {
1200 $this->userTS = unserialize($cachedContent);
1201 } else {
1202 $parseObj = t3lib_div::makeInstance('t3lib_TSparser');
1203 $parseObj->parse($this->userTS_text);
1204 $this->userTS = $parseObj->setup;
1205 t3lib_BEfunc::storeHash($hash, serialize($this->userTS), 'BE_USER_TSconfig');
1206 // Update UC:
1207 $this->userTSUpdated = 1;
1208 }
1209 }
1210
1211 // Processing webmounts
1212 if ($this->isAdmin() && !$this->getTSConfigVal('options.dontMountAdminMounts')) { // Admin's always have the root mounted
1213 $this->dataLists['webmount_list'] = '0,' . $this->dataLists['webmount_list'];
1214 }
1215
1216 // Processing filemounts
1217 t3lib_div::loadTCA('sys_filemounts');
1218 $orderBy = $GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby'] ? $GLOBALS['TYPO3_DB']->stripOrderBy($GLOBALS['TCA']['sys_filemounts']['ctrl']['default_sortby']) : 'sorting';
1219 $this->dataLists['filemount_list'] = t3lib_div::uniqueList($this->dataLists['filemount_list']);
1220 if ($this->dataLists['filemount_list']) {
1221 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_filemounts', 'deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $this->dataLists['filemount_list'] . ')', '', $orderBy);
1222 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1223 $this->addFileMount($row['title'], $row['path'], $row['path'], $row['base'] ? 1 : 0, '');
1224 }
1225 }
1226
1227 // The lists are cleaned for duplicates
1228 $this->groupData['webmounts'] = t3lib_div::uniqueList($this->dataLists['webmount_list']);
1229 $this->groupData['pagetypes_select'] = t3lib_div::uniqueList($this->dataLists['pagetypes_select']);
1230 $this->groupData['tables_select'] = t3lib_div::uniqueList($this->dataLists['tables_modify'] . ',' . $this->dataLists['tables_select']);
1231 $this->groupData['tables_modify'] = t3lib_div::uniqueList($this->dataLists['tables_modify']);
1232 $this->groupData['non_exclude_fields'] = t3lib_div::uniqueList($this->dataLists['non_exclude_fields']);
1233 $this->groupData['explicit_allowdeny'] = t3lib_div::uniqueList($this->dataLists['explicit_allowdeny']);
1234 $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->dataLists['allowed_languages']);
1235 $this->groupData['custom_options'] = t3lib_div::uniqueList($this->dataLists['custom_options']);
1236 $this->groupData['modules'] = t3lib_div::uniqueList($this->dataLists['modList']);
1237 $this->groupData['fileoper_perms'] = $this->dataLists['fileoper_perms'];
1238 $this->groupData['workspace_perms'] = $this->dataLists['workspace_perms'];
1239
1240 // populating the $this->userGroupsUID -array with the groups in the order in which they were LAST included.!!
1241 $this->userGroupsUID = array_reverse(array_unique(array_reverse($this->includeGroupArray)));
1242
1243 // Finally this is the list of group_uid's in the order they are parsed (including subgroups!) and without duplicates (duplicates are presented with their last entrance in the list, which thus reflects the order of the TypoScript in TSconfig)
1244 $this->groupList = implode(',', $this->userGroupsUID);
1245 $this->setCachedList($this->groupList);
1246
1247 // Checking read access to webmounts:
1248 if (trim($this->groupData['webmounts']) !== '') {
1249 $webmounts = explode(',', $this->groupData['webmounts']); // Explode mounts
1250 $MProws = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid', 'pages', 'deleted=0 AND uid IN (' . $this->groupData['webmounts'] . ') AND ' . $this->getPagePermsClause(1), '', '', '', 'uid'); // Selecting all webmounts with permission clause for reading
1251 foreach ($webmounts as $idx => $mountPointUid) {
1252 if ($mountPointUid > 0 && !isset($MProws[$mountPointUid])) { // If the mount ID is NOT found among selected pages, unset it:
1253 unset($webmounts[$idx]);
1254 }
1255 }
1256 $this->groupData['webmounts'] = implode(',', $webmounts); // Implode mounts in the end.
1257 }
1258
1259 // Setting up workspace situation (after webmounts are processed!):
1260 $this->workspaceInit();
1261 }
1262 }
1263
1264 /**
1265 * Fetches the group records, subgroups and fills internal arrays.
1266 * Function is called recursively to fetch subgroups
1267 *
1268 * @param string Commalist of be_groups uid numbers
1269 * @param string List of already processed be_groups-uids so the function will not fall into a eternal recursion.
1270 * @return void
1271 * @access private
1272 */
1273 function fetchGroups($grList, $idList = '') {
1274 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
1275 $lockToDomain_SQL = ' AND (lockToDomain=\'\' OR lockToDomain IS NULL OR lockToDomain=\'' . t3lib_div::getIndpEnv('HTTP_HOST') . '\')';
1276 $whereSQL = 'deleted=0 AND hidden=0 AND pid=0 AND uid IN (' . $grList . ')' . $lockToDomain_SQL;
1277
1278 // Hook for manipulation of the WHERE sql sentence which controls which BE-groups are included
1279 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'])) {
1280 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroupQuery'] as $classRef) {
1281 $hookObj = t3lib_div::getUserObj($classRef);
1282 if (method_exists($hookObj, 'fetchGroupQuery_processQuery')) {
1283 $whereSQL = $hookObj->fetchGroupQuery_processQuery($this, $grList, $idList, $whereSQL);
1284 }
1285 }
1286 }
1287
1288 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->usergroup_table, $whereSQL);
1289
1290 // The userGroups array is filled
1291 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1292 $this->userGroups[$row['uid']] = $row;
1293 }
1294
1295 // Traversing records in the correct order
1296 $include_staticArr = t3lib_div::intExplode(',', $grList);
1297 // traversing list
1298 foreach ($include_staticArr as $key => $uid) {
1299
1300 // Get row:
1301 $row = $this->userGroups[$uid];
1302 if (is_array($row) && !t3lib_div::inList($idList, $uid)) { // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
1303
1304 // Include sub groups
1305 if (trim($row['subgroup'])) {
1306 $theList = implode(',', t3lib_div::intExplode(',', $row['subgroup'])); // Make integer list
1307 $this->fetchGroups($theList, $idList . ',' . $uid); // Call recursively, pass along list of already processed groups so they are not recursed again.
1308 }
1309 // Add the group uid, current list, TSconfig to the internal arrays.
1310 $this->includeGroupArray[] = $uid;
1311 $this->includeHierarchy[] = $idList;
1312 $this->TSdataArray[] = $this->addTScomment('Group "' . $row['title'] . '" [' . $row['uid'] . '] TSconfig field:') . $row['TSconfig'];
1313
1314 // Mount group database-mounts
1315 if (($this->user['options'] & 1) == 1) {
1316 $this->dataLists['webmount_list'] .= ',' . $row['db_mountpoints'];
1317 }
1318
1319 // Mount group file-mounts
1320 if (($this->user['options'] & 2) == 2) {
1321 $this->dataLists['filemount_list'] .= ',' . $row['file_mountpoints'];
1322 }
1323
1324 // Mount group home-dirs
1325 if (($this->user['options'] & 2) == 2) {
1326 // If groupHomePath is set, we attempt to mount it
1327 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath']) {
1328 $this->addFileMount($row['title'], '', $GLOBALS['TYPO3_CONF_VARS']['BE']['groupHomePath'] . $row['uid'], 0, 'group');
1329 }
1330 }
1331
1332 // The lists are made: groupMods, tables_select, tables_modify, pagetypes_select, non_exclude_fields, explicit_allowdeny, allowed_languages, custom_options
1333 if ($row['inc_access_lists'] == 1) {
1334 $this->dataLists['modList'] .= ',' . $row['groupMods'];
1335 $this->dataLists['tables_select'] .= ',' . $row['tables_select'];
1336 $this->dataLists['tables_modify'] .= ',' . $row['tables_modify'];
1337 $this->dataLists['pagetypes_select'] .= ',' . $row['pagetypes_select'];
1338 $this->dataLists['non_exclude_fields'] .= ',' . $row['non_exclude_fields'];
1339 $this->dataLists['explicit_allowdeny'] .= ',' . $row['explicit_allowdeny'];
1340 $this->dataLists['allowed_languages'] .= ',' . $row['allowed_languages'];
1341 $this->dataLists['custom_options'] .= ',' . $row['custom_options'];
1342 }
1343
1344 // Setting fileoperation permissions
1345 $this->dataLists['fileoper_perms'] |= (int) $row['fileoper_perms'];
1346
1347 // Setting workspace permissions:
1348 $this->dataLists['workspace_perms'] |= $row['workspace_perms'];
1349
1350 // If this function is processing the users OWN group-list (not subgroups) AND if the ->firstMainGroup is not set, then the ->firstMainGroup will be set.
1351 if (!strcmp($idList, '') && !$this->firstMainGroup) {
1352 $this->firstMainGroup = $uid;
1353 }
1354 }
1355 }
1356
1357 // ****************
1358 // HOOK: fetchGroups_postProcessing
1359 // ****************
1360 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'])) {
1361 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauthgroup.php']['fetchGroups_postProcessing'] as $_funcRef) {
1362 $_params = array();
1363 t3lib_div::callUserFunction($_funcRef, $_params, $this);
1364 }
1365 }
1366 }
1367
1368 /**
1369 * Updates the field be_users.usergroup_cached_list if the groupList of the user has changed/is different from the current list.
1370 * The field "usergroup_cached_list" contains the list of groups which the user is a member of. After authentication (where these functions are called...) one can depend on this list being a representation of the exact groups/subgroups which the BE_USER has membership with.
1371 *
1372 * @param string The newly compiled group-list which must be compared with the current list in the user record and possibly stored if a difference is detected.
1373 * @return void
1374 * @access private
1375 */
1376 function setCachedList($cList) {
1377 if ((string) $cList != (string) $this->user['usergroup_cached_list']) {
1378 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('usergroup_cached_list' => $cList));
1379 }
1380 }
1381
1382 /**
1383 * Adds a filemount to the users array of filemounts, $this->groupData['filemounts'][hash_key] = Array ('name'=>$name, 'path'=>$path, 'type'=>$type);
1384 * Is a part of the authentication proces of the user.
1385 * A final requirement for a path being mounted is that a) it MUST return TRUE on is_dir(), b) must contain either PATH_site+'fileadminDir' OR 'lockRootPath' - if lockRootPath is set - as first part of string!
1386 * Paths in the mounted information will always be absolute and have a trailing slash.
1387 *
1388 * @param string $title will be the (root)name of the filemount in the folder tree
1389 * @param string $altTitle will be the (root)name of the filemount IF $title is not TRUE (blank or zero)
1390 * @param string $path is the path which should be mounted. Will accept backslash in paths on windows servers (will substituted with forward slash). The path should be 1) relative to TYPO3_CONF_VARS[BE][fileadminDir] if $webspace is set, otherwise absolute.
1391 * @param boolean If $webspace is set, the $path is relative to 'fileadminDir' in TYPO3_CONF_VARS, otherwise $path is absolute. 'fileadminDir' must be set to allow mounting of relative paths.
1392 * @param string Type of filemount; Can be blank (regular) or "user" / "group" (for user and group filemounts presumably). Probably sets the icon first and foremost.
1393 * @return boolean Returns "1" if the requested filemount was mounted, otherwise no return value.
1394 * @access private
1395 */
1396 function addFileMount($title, $altTitle, $path, $webspace, $type) {
1397 // Return FALSE if fileadminDir is not set and we try to mount a relative path
1398 if ($webspace && !$GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']) {
1399 return FALSE;
1400 }
1401
1402 // Trimming and pre-processing
1403 $path = trim($path);
1404 if ($this->OS == 'WIN') { // with WINDOWS convert backslash to slash!!
1405 $path = str_replace('\\', '/', $path);
1406 }
1407 // If the path is TRUE and validates as a valid path string:
1408 if ($path && t3lib_div::validPathStr($path)) {
1409 // normalize path: remove leading '/' and './', and trailing '/' and '/.'
1410 $path = trim($path);
1411 $path = preg_replace('#^\.?/|/\.?$#', '', $path);
1412
1413 if ($path) { // there must be some chars in the path
1414 $fdir = PATH_site . $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir']; // fileadmin dir, absolute
1415 if ($webspace) {
1416 $path = $fdir . $path; // PATH_site + fileadmin dir is prepended
1417 } else {
1418 if ($this->OS != 'WIN') { // with WINDOWS no prepending!!
1419 $path = '/' . $path; // root-level is the start...
1420 }
1421 }
1422 $path .= '/';
1423
1424 // We now have a path with slash after and slash before (if unix)
1425 if (@is_dir($path) &&
1426 (($GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'] && t3lib_div::isFirstPartOfStr($path, $GLOBALS['TYPO3_CONF_VARS']['BE']['lockRootPath'])) || t3lib_div::isFirstPartOfStr($path, $fdir))) {
1427 // Alternative title?
1428 $name = $title ? $title : $altTitle;
1429 // Adds the filemount. The same filemount with same name, type and path cannot be set up twice because of the hash string used as key.
1430 $this->groupData['filemounts'][md5($name . '|' . $path . '|' . $type)] = array('name' => $name, 'path' => $path, 'type' => $type);
1431 // Return TRUE - went well, success!
1432 return 1;
1433 }
1434 }
1435 }
1436 }
1437
1438 /**
1439 * Creates a TypoScript comment with the string text inside.
1440 *
1441 * @param string The text to wrap in comment prefixes and delimiters.
1442 * @return string TypoScript comment with the string text inside.
1443 */
1444 function addTScomment($str) {
1445 $delimiter = '# ***********************************************';
1446
1447 $out = $delimiter . LF;
1448 $lines = t3lib_div::trimExplode(LF, $str);
1449 foreach ($lines as $v) {
1450 $out .= '# ' . $v . LF;
1451 }
1452 $out .= $delimiter . LF;
1453 return $out;
1454 }
1455
1456
1457 /************************************
1458 *
1459 * Workspaces
1460 *
1461 ************************************/
1462
1463 /**
1464 * Initializing workspace.
1465 * Called from within this function, see fetchGroupData()
1466 *
1467 * @return void
1468 * @see fetchGroupData()
1469 */
1470 function workspaceInit() {
1471
1472 // Initializing workspace by evaluating and setting the workspace, possibly updating it in the user record!
1473 $this->setWorkspace($this->user['workspace_id']);
1474
1475 // Limiting the DB mountpoints if there any selected in the workspace record
1476 $dbMountpoints = trim($this->workspaceRec['db_mountpoints']);
1477 if ($this->workspace > 0 && $dbMountpoints != '') {
1478 $filteredDbMountpoints = array();
1479 $readPerms = '1=1'; // Notice: We cannot call $this->getPagePermsClause(1); as usual because the group-list is not available at this point. But bypassing is fine because all we want here is check if the workspace mounts are inside the current webmounts rootline. The actual permission checking on page level is done elsewhere as usual anyway before the page tree is rendered.
1480
1481 // Traverse mount points of the
1482 $dbMountpoints = t3lib_div::intExplode(',', $dbMountpoints);
1483 foreach ($dbMountpoints as $mpId) {
1484 if ($this->isInWebMount($mpId, $readPerms)) {
1485 $filteredDbMountpoints[] = $mpId;
1486 }
1487 }
1488
1489 // Re-insert webmounts:
1490 $filteredDbMountpoints = array_unique($filteredDbMountpoints);
1491 $this->groupData['webmounts'] = implode(',', $filteredDbMountpoints);
1492 }
1493
1494 // Filtering the file mountpoints
1495 // if there some selected in the workspace record
1496 if ($this->workspace !== 0) {
1497 $usersFileMounts = $this->groupData['filemounts'];
1498 $this->groupData['filemounts'] = array();
1499 }
1500 $fileMountpoints = trim($this->workspaceRec['file_mountpoints']);
1501 if ($this->workspace > 0) {
1502
1503 // no custom filemounts that should serve as filter or user is admin
1504 // so all user mountpoints are re-applied
1505 if ($this->isAdmin() || $fileMountpoints === '') {
1506 $this->groupData['filemounts'] = $usersFileMounts;
1507 } else {
1508 // Fetching all filemounts from the workspace
1509 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1510 '*',
1511 'sys_filemounts',
1512 'deleted = 0 AND hidden = 0 AND pid = 0 AND uid IN (' . $GLOBALS['TYPO3_DB']->cleanIntList($fileMountpoints) . ')'
1513 );
1514
1515 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1516 // add every filemount of this workspace record
1517 $this->addFileMount($row['title'], $row['path'], $row['path'], ($row['base'] ? 1 : 0), '');
1518
1519 // get the added entry, and check if it was in the users' original filemounts
1520 // if not, remove it from the new filemount list again
1521 // see self::addFileMount
1522 end($this->groupData['filemounts']);
1523 $md5hash = key($this->groupData['filemounts']);
1524 if (!array_key_exists($md5hash, $usersFileMounts)) {
1525 unset($this->groupData['filemounts'][$md5hash]);
1526 }
1527 }
1528 }
1529 }
1530
1531 if ($allowed_languages = $this->getTSConfigVal('options.workspaces.allowed_languages.' . $this->workspace)) {
1532 $this->groupData['allowed_languages'] = $allowed_languages;
1533 $this->groupData['allowed_languages'] = t3lib_div::uniqueList($this->groupData['allowed_languages']);
1534 }
1535 }
1536
1537 /**
1538 * Checking if a workspace is allowed for backend user
1539 *
1540 * @param mixed If integer, workspace record is looked up, if array it is seen as a Workspace record with at least uid, title, members and adminusers columns. Can be faked for workspaces uid 0 and -1 (online and offline)
1541 * @param string List of fields to select. Default fields are: uid,title,adminusers,members,reviewers,publish_access,stagechg_notification
1542 * @return array TRUE if access. Output will also show how access was granted. Admin users will have a true output regardless of input.
1543 */
1544 function checkWorkspace($wsRec, $fields = 'uid,title,adminusers,members,reviewers,publish_access,stagechg_notification') {
1545 $retVal = FALSE;
1546
1547 // If not array, look up workspace record:
1548 if (!is_array($wsRec)) {
1549 switch ((string) $wsRec) {
1550 case '0':
1551 $wsRec = array('uid' => $wsRec);
1552 break;
1553 default:
1554 if (t3lib_extMgm::isLoaded('workspaces')) {
1555 $wsRec = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow(
1556 $fields,
1557 'sys_workspace',
1558 'pid=0 AND uid=' . intval($wsRec) .
1559 t3lib_BEfunc::deleteClause('sys_workspace'),
1560 '',
1561 'title'
1562 );
1563 }
1564 break;
1565 }
1566 }
1567
1568 // If wsRec is set to an array, evaluate it:
1569 if (is_array($wsRec)) {
1570 if ($this->isAdmin()) {
1571 return array_merge($wsRec, array('_ACCESS' => 'admin'));
1572 } else {
1573
1574 switch ((string) $wsRec['uid']) {
1575 case '0':
1576 $retVal = ($this->groupData['workspace_perms'] & 1) ? array_merge($wsRec, array('_ACCESS' => 'online')) : FALSE;
1577 break;
1578 default:
1579 // Checking if the guy is admin:
1580 if (t3lib_div::inList($wsRec['adminusers'], 'be_users_' . $this->user['uid'])) {
1581 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1582 }
1583 // Checking if he is owner through a user group of his:
1584 foreach ($this->userGroupsUID as $groupUid) {
1585 if (t3lib_div::inList($wsRec['adminusers'], 'be_groups_' . $groupUid)) {
1586 return array_merge($wsRec, array('_ACCESS' => 'owner'));
1587 }
1588 }
1589 // Checking if he is reviewer user:
1590 if (t3lib_div::inList($wsRec['reviewers'], 'be_users_' . $this->user['uid'])) {
1591 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1592 }
1593 // Checking if he is reviewer through a user group of his:
1594 foreach ($this->userGroupsUID as $groupUid) {
1595 if (t3lib_div::inList($wsRec['reviewers'], 'be_groups_' . $groupUid)) {
1596 return array_merge($wsRec, array('_ACCESS' => 'reviewer'));
1597 }
1598 }
1599 // Checking if he is member as user:
1600 if (t3lib_div::inList($wsRec['members'], 'be_users_' . $this->user['uid'])) {
1601 return array_merge($wsRec, array('_ACCESS' => 'member'));
1602 }
1603 // Checking if he is member through a user group of his:
1604 foreach ($this->userGroupsUID as $groupUid) {
1605 if (t3lib_div::inList($wsRec['members'], 'be_groups_' . $groupUid)) {
1606 return array_merge($wsRec, array('_ACCESS' => 'member'));
1607 }
1608 }
1609 break;
1610 }
1611 }
1612 }
1613
1614 return $retVal;
1615 }
1616
1617 /**
1618 * Uses checkWorkspace() to check if current workspace is available for user. This function caches the result and so can be called many times with no performance loss.
1619 *
1620 * @return array See checkWorkspace()
1621 * @see checkWorkspace()
1622 */
1623 function checkWorkspaceCurrent() {
1624 if (!isset($this->checkWorkspaceCurrent_cache)) {
1625 $this->checkWorkspaceCurrent_cache = $this->checkWorkspace($this->workspace);
1626 }
1627 return $this->checkWorkspaceCurrent_cache;
1628 }
1629
1630 /**
1631 * Setting workspace ID
1632 *
1633 * @param integer ID of workspace to set for backend user. If not valid the default workspace for BE user is found and set.
1634 * @return void
1635 */
1636 function setWorkspace($workspaceId) {
1637
1638 // Check workspace validity and if not found, revert to default workspace.
1639 if ($this->workspaceRec = $this->checkWorkspace($workspaceId, '*')) {
1640 // Set workspace ID internally
1641 $this->workspace = (int) $workspaceId;
1642 } else {
1643 $this->workspace = (int) $this->getDefaultWorkspace();
1644 $this->workspaceRec = $this->checkWorkspace($this->workspace, '*');
1645 }
1646
1647 // Unset access cache:
1648 unset($this->checkWorkspaceCurrent_cache);
1649
1650 // If ID is different from the stored one, change it:
1651 if (strcmp($this->workspace, $this->user['workspace_id'])) {
1652 $this->user['workspace_id'] = $this->workspace;
1653 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('workspace_id' => $this->user['workspace_id']));
1654 $this->simplelog('User changed workspace to "' . $this->workspace . '"');
1655 }
1656 }
1657
1658 /**
1659 * Setting workspace preview state for user:
1660 *
1661 * @param boolean State of user preview.
1662 * @return void
1663 */
1664 function setWorkspacePreview($previewState) {
1665 $this->user['workspace_preview'] = $previewState;
1666 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('be_users', 'uid=' . intval($this->user['uid']), array('workspace_preview' => $this->user['workspace_preview']));
1667 }
1668
1669 /**
1670 * Return default workspace ID for user,
1671 * If EXT:workspaces is not installed the user will be pushed the the
1672 * Live workspace
1673 *
1674 * @return integer Default workspace id. If no workspace is available it will be "-99"
1675 */
1676 function getDefaultWorkspace() {
1677
1678 $defaultWorkspace = -99;
1679
1680 if (!t3lib_extMgm::isLoaded('workspaces') || $this->checkWorkspace(0)) { // Check online
1681 $defaultWorkspace = 0;
1682 } elseif ($this->checkWorkspace(-1)) { // Check offline
1683 $defaultWorkspace = -1;
1684 } elseif (t3lib_extMgm::isLoaded('workspaces')) { // Traverse custom workspaces:
1685 $workspaces = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,title,adminusers,members,reviewers', 'sys_workspace', 'pid=0' . t3lib_BEfunc::deleteClause('sys_workspace'), '', 'title');
1686 foreach ($workspaces as $rec) {
1687 if ($this->checkWorkspace($rec)) {
1688 $defaultWorkspace = $rec['uid'];
1689 break;
1690 }
1691 }
1692 }
1693 return $defaultWorkspace;
1694 }
1695
1696
1697 /************************************
1698 *
1699 * Logging
1700 *
1701 ************************************/
1702
1703 /**
1704 * Writes an entry in the logfile/table
1705 * Documentation in "TYPO3 Core API"
1706 *
1707 * @param integer Denotes which module that has submitted the entry. See "TYPO3 Core API". Use "4" for extensions.
1708 * @param integer Denotes which specific operation that wrote the entry. Use "0" when no sub-categorizing applies
1709 * @param integer Flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1710 * @param integer The message number. Specific for each $type and $action. This will make it possible to translate errormessages to other languages
1711 * @param string Default text that follows the message (in english!). Possibly translated by identification through type/action/details_nr
1712 * @param array Data that follows the log. Might be used to carry special information. If an array the first 5 entries (0-4) will be sprintf'ed with the details-text
1713 * @param string Table name. Special field used by tce_main.php.
1714 * @param integer Record UID. Special field used by tce_main.php.
1715 * @param integer Record PID. Special field used by tce_main.php. OBSOLETE
1716 * @param integer The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
1717 * @param string Special field used by tce_main.php. NEWid string of newly created records.
1718 * @param integer Alternative Backend User ID (used for logging login actions where this is not yet known).
1719 * @return integer Log entry ID.
1720 */
1721 function writelog($type, $action, $error, $details_nr, $details, $data, $tablename = '', $recuid = '', $recpid = '', $event_pid = -1, $NEWid = '', $userId = 0) {
1722
1723 $fields_values = array(
1724 'userid' => $userId ? $userId : intval($this->user['uid']),
1725 'type' => intval($type),
1726 'action' => intval($action),
1727 'error' => intval($error),
1728 'details_nr' => intval($details_nr),
1729 'details' => $details,
1730 'log_data' => serialize($data),
1731 'tablename' => $tablename,
1732 'recuid' => intval($recuid),
1733 # 'recpid' => intval($recpid),
1734 'IP' => t3lib_div::getIndpEnv('REMOTE_ADDR'),
1735 'tstamp' => $GLOBALS['EXEC_TIME'],
1736 'event_pid' => intval($event_pid),
1737 'NEWid' => $NEWid,
1738 'workspace' => $this->workspace
1739 );
1740
1741 $GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_log', $fields_values);
1742 return $GLOBALS['TYPO3_DB']->sql_insert_id();
1743 }
1744
1745 /**
1746 * Simple logging function
1747 *
1748 * @param string Log message
1749 * @param string Option extension key / module name
1750 * @param integer Error level. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1751 * @return integer Log entry UID
1752 */
1753 function simplelog($message, $extKey = '', $error = 0) {
1754 return $this->writelog(
1755 4,
1756 0,
1757 $error,
1758 0,
1759 ($extKey ? '[' . $extKey . '] ' : '') . $message,
1760 array()
1761 );
1762 }
1763
1764 /**
1765 * Sends a warning to $email if there has been a certain amount of failed logins during a period.
1766 * If a login fails, this function is called. It will look up the sys_log to see if there has been more than $max failed logins the last $secondsBack seconds (default 3600). If so, an email with a warning is sent to $email.
1767 *
1768 * @param string Email address
1769 * @param integer Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance.
1770 * @param integer Max allowed failures before a warning mail is sent
1771 * @return void
1772 * @access private
1773 */
1774 function checkLogFailures($email, $secondsBack = 3600, $max = 3) {
1775
1776 if ($email) {
1777
1778 // get last flag set in the log for sending
1779 $theTimeBack = $GLOBALS['EXEC_TIME'] - $secondsBack;
1780 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1781 'tstamp',
1782 'sys_log',
1783 'type=255 AND action=4 AND tstamp>' . intval($theTimeBack),
1784 '',
1785 'tstamp DESC',
1786 '1'
1787 );
1788 if ($testRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1789 $theTimeBack = $testRow['tstamp'];
1790 }
1791
1792 // Check for more than $max number of error failures with the last period.
1793 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1794 '*',
1795 'sys_log',
1796 'type=255 AND action=3 AND error<>0 AND tstamp>' . intval($theTimeBack),
1797 '',
1798 'tstamp'
1799 );
1800 if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) > $max) {
1801 // OK, so there were more than the max allowed number of login failures - so we will send an email then.
1802 $subject = 'TYPO3 Login Failure Warning (at ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . ')';
1803 $email_body = 'There have been some attempts (' . $GLOBALS['TYPO3_DB']->sql_num_rows($res) . ') to login at the TYPO3
1804 site "' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . '" (' . t3lib_div::getIndpEnv('HTTP_HOST') . ').
1805
1806 This is a dump of the failures:
1807
1808 ';
1809 while ($testRows = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1810 $theData = unserialize($testRows['log_data']);
1811 $email_body .= date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] . ' ' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $testRows['tstamp']) . ': ' . @sprintf($testRows['details'], '' . $theData[0], '' . $theData[1], '' . $theData[2]);
1812 $email_body .= LF;
1813 }
1814 $from = t3lib_utility_Mail::getSystemFrom();
1815 /** @var $mail t3lib_mail_Message */
1816 $mail = t3lib_div::makeInstance('t3lib_mail_Message');
1817 $mail->setTo($email)
1818 ->setFrom($from)
1819 ->setSubject($subject)
1820 ->setBody($email_body);
1821 $mail->send();
1822 $this->writelog(255, 4, 0, 3, 'Failure warning (%s failures within %s seconds) sent by email to %s', array($GLOBALS['TYPO3_DB']->sql_num_rows($res), $secondsBack, $email)); // Logout written to log
1823 }
1824 }
1825 }
1826 }
1827
1828
1829 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php'])) {
1830 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_userauthgroup.php']);
1831 }
1832
1833 ?>