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