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