b1830b514919b0f9995e6605ff591b0bcacc8ab5
[Packages/TYPO3.CMS.git] / typo3 / sysext / version / class.tx_version_tcemain.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 1999-2011 Kasper Skårhøj (kasperYYYY@typo3.com)
6 * (c) 2010-2011 Benjamin Mack (benni@typo3.org)
7 *
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the textfile GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29 /**
30 *
31 * Contains some parts for staging, versioning and workspaces
32 * to interact with the TYPO3 Core Engine
33 *
34 */
35 class tx_version_tcemain {
36
37 /**
38 * For accumulating information about workspace stages raised
39 * on elements so a single mail is sent as notification.
40 * previously called "accumulateForNotifEmail" in tcemain
41 *
42 * @var array
43 */
44 protected $notificationEmailInfo = array();
45
46 /**
47 * General comment, eg. for staging in workspaces
48 *
49 * @var string
50 */
51 protected $generalComment = '';
52
53 /**
54 * Contains remapped IDs.
55 *
56 * @var array
57 */
58 protected $remappedIds = array();
59
60 /****************************
61 ***** Cmdmap Hooks ******
62 ****************************/
63
64 /**
65 * hook that is called before any cmd of the commandmap is executed
66 *
67 * @param t3lib_TCEmain $tcemainObj reference to the main tcemain object
68 * @return void
69 */
70 public function processCmdmap_beforeStart(t3lib_TCEmain $tcemainObj) {
71 // Reset notification array
72 $this->notificationEmailInfo = array();
73 // Resolve dependencies of version/workspaces actions:
74 $tcemainObj->cmdmap = $this->getCommandMap($tcemainObj, $tcemainObj->cmdmap)->process()->get();
75 }
76
77
78 /**
79 * hook that is called when no prepared command was found
80 *
81 * @param string $command the command to be executed
82 * @param string $table the table of the record
83 * @param integer $id the ID of the record
84 * @param mixed $value the value containing the data
85 * @param boolean $commandIsProcessed can be set so that other hooks or
86 * TCEmain knows that the default cmd doesn't have to be called
87 * @param t3lib_TCEmain $tcemainObj reference to the main tcemain object
88 * @return void
89 */
90 public function processCmdmap($command, $table, $id, $value, &$commandIsProcessed, t3lib_TCEmain $tcemainObj) {
91
92 // custom command "version"
93 if ($command == 'version') {
94 $commandIsProcessed = TRUE;
95 $action = (string) $value['action'];
96 switch ($action) {
97
98 case 'new':
99 // check if page / branch versioning is needed,
100 // or if "element" version can be used
101 $versionizeTree = -1;
102 if (isset($value['treeLevels'])) {
103 $versionizeTree = t3lib_utility_Math::forceIntegerInRange($value['treeLevels'], -1, 100);
104 }
105 if ($table == 'pages' && $versionizeTree >= 0) {
106 $this->versionizePages($id, $value['label'], $versionizeTree, $tcemainObj);
107 } else {
108 $tcemainObj->versionizeRecord($table, $id, $value['label']);
109 }
110 break;
111
112 case 'swap':
113 $this->version_swap($table, $id, $value['swapWith'], $value['swapIntoWS'], $tcemainObj);
114 break;
115
116 case 'clearWSID':
117 $this->version_clearWSID($table, $id, FALSE, $tcemainObj);
118 break;
119
120 case 'flush':
121 $this->version_clearWSID($table, $id, TRUE, $tcemainObj);
122 break;
123
124 case 'setStage':
125 $elementIds = t3lib_div::trimExplode(',', $id, TRUE);
126 foreach ($elementIds as $elementId) {
127 $this->version_setStage($table, $elementId, $value['stageId'],
128 (isset($value['comment']) && $value['comment'] ? $value['comment'] : $this->generalComment),
129 TRUE,
130 $tcemainObj,
131 $value['notificationAlternativeRecipients']
132 );
133 }
134 break;
135 }
136 }
137 }
138
139 /**
140 * Hook that is called after tcemain made most of its decisions.
141 *
142 * NOTE: This fixes an issue related to moving/creating initial-placeholders - if such a new page
143 * is intended to be place behind a move-placeholder tcemain handles the movement/creation,
144 * but does not respect the wsPlaceholder, which leads the new page to be located at the old location of the
145 * page where it was intended to be placed behind.
146 *
147 * @param string $command
148 * @param string $table
149 * @param int $id
150 * @param mixed $value
151 * @param t3lib_TCEmain $tcemain
152 */
153 public function processCmdmap_postProcess($command, $table, $id, $value, t3lib_TCEmain $tcemain) {
154 if ($command === 'move') {
155 if ($value < 0) {
156 $movePlaceHolder = t3lib_BEfunc::getMovePlaceholder($table, abs($value), 'uid');
157 if ($movePlaceHolder !== FALSE) {
158 $destPid = -$movePlaceHolder['uid'];
159 $tcemain->moveRecord_raw($table, $id, $destPid);
160 }
161 }
162 }
163 }
164
165 /**
166 * hook that is called AFTER all commands of the commandmap was
167 * executed
168 *
169 * @param t3lib_TCEmain $tcemainObj reference to the main tcemain object
170 * @return void
171 */
172 public function processCmdmap_afterFinish(t3lib_TCEmain $tcemainObj) {
173 // Empty accumulation array:
174 foreach ($this->notificationEmailInfo as $notifItem) {
175 $this->notifyStageChange($notifItem['shared'][0], $notifItem['shared'][1], implode(', ', $notifItem['elements']), 0, $notifItem['shared'][2], $tcemainObj, $notifItem['alternativeRecipients']);
176 }
177
178 // Reset notification array
179 $this->notificationEmailInfo = array();
180 // Reset remapped IDs
181 $this->remappedIds = array();
182 }
183
184
185 /**
186 * hook that is called AFTER all commands of the commandmap was
187 * executed
188 *
189 * @param string $table the table of the record
190 * @param integer $id the ID of the record
191 * @param array $record The accordant database record
192 * @param boolean $recordWasDeleted can be set so that other hooks or
193 * TCEmain knows that the default delete action doesn't have to be called
194 * @param t3lib_TCEmain $tcemainObj reference to the main tcemain object
195 * @return void
196 */
197 public function processCmdmap_deleteAction($table, $id, array $record, &$recordWasDeleted, t3lib_TCEmain $tcemainObj) {
198 // only process the hook if it wasn't processed
199 // by someone else before
200 if (!$recordWasDeleted) {
201 $recordWasDeleted = TRUE;
202
203 // For Live version, try if there is a workspace version because if so, rather "delete" that instead
204 // Look, if record is an offline version, then delete directly:
205 if ($record['pid'] != -1) {
206 if ($wsVersion = t3lib_BEfunc::getWorkspaceVersionOfRecord($tcemainObj->BE_USER->workspace, $table, $id)) {
207 $record = $wsVersion;
208 $id = $record['uid'];
209 }
210 }
211
212 // Look, if record is an offline version, then delete directly:
213 if ($record['pid'] == -1) {
214 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS']) {
215 // In Live workspace, delete any. In other workspaces there must be match.
216 if ($tcemainObj->BE_USER->workspace == 0 || (int) $record['t3ver_wsid'] == $tcemainObj->BE_USER->workspace) {
217 $liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table, $id, 'uid,t3ver_state');
218
219 // Processing can be skipped if a delete placeholder shall be swapped/published
220 // during the current request. Thus it will be deleted later on...
221 if ($record['t3ver_state'] == 2 && !empty($liveRec['uid'])
222 && !empty($tcemainObj->cmdmap[$table][$liveRec['uid']]['version']['action'])
223 && !empty($tcemainObj->cmdmap[$table][$liveRec['uid']]['version']['swapWith'])
224 && $tcemainObj->cmdmap[$table][$liveRec['uid']]['version']['action'] === 'swap'
225 && $tcemainObj->cmdmap[$table][$liveRec['uid']]['version']['swapWith'] == $id) {
226
227 return NULL;
228 }
229
230 // Delete those in WS 0 + if their live records state was not "Placeholder".
231 if ($record['t3ver_wsid']==0 || (int) $liveRec['t3ver_state'] <= 0) {
232 $tcemainObj->deleteEl($table, $id);
233 } else {
234 // If live record was placeholder (new/deleted), rather clear
235 // it from workspace (because it clears both version and placeholder).
236 $this->version_clearWSID($table, $id, FALSE, $tcemainObj);
237 }
238 } else $tcemainObj->newlog('Tried to delete record from another workspace',1);
239 } else $tcemainObj->newlog('Versioning not enabled for record with PID = -1!',2);
240 } elseif ($res = $tcemainObj->BE_USER->workspaceAllowLiveRecordsInPID($record['pid'], $table)) {
241 // Look, if record is "online" or in a versionized branch, then delete directly.
242 if ($res>0) {
243 $tcemainObj->deleteEl($table, $id);
244 } else {
245 $tcemainObj->newlog('Stage of root point did not allow for deletion',1);
246 }
247 } elseif ((int)$record['t3ver_state']===3) {
248 // Placeholders for moving operations are deletable directly.
249
250 // Get record which its a placeholder for and reset the t3ver_state of that:
251 if ($wsRec = t3lib_BEfunc::getWorkspaceVersionOfRecord($record['t3ver_wsid'], $table, $record['t3ver_move_id'], 'uid')) {
252 // Clear the state flag of the workspace version of the record
253 // Setting placeholder state value for version (so it can know it is currently a new version...)
254 $updateFields = array(
255 't3ver_state' => 0
256 );
257 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($wsRec['uid']), $updateFields);
258 }
259 $tcemainObj->deleteEl($table, $id);
260 } else {
261 // Otherwise, try to delete by versioning:
262 $copyMappingArray = $tcemainObj->copyMappingArray;
263 $tcemainObj->versionizeRecord($table, $id, 'DELETED!', TRUE);
264
265 // Determine newly created versions:
266 // (remove placeholders are copied and modified, thus they appear in the copyMappingArray)
267 $versionizedElements = t3lib_div::arrayDiffAssocRecursive(
268 $tcemainObj->copyMappingArray,
269 $copyMappingArray
270 );
271 // Delete localization overlays:
272 foreach ($versionizedElements as $versionizedTableName => $versionizedOriginalIds) {
273 foreach ($versionizedOriginalIds as $versionizedOriginalId => $_) {
274 $tcemainObj->deleteL10nOverlayRecords($versionizedTableName, $versionizedOriginalId);
275 }
276 }
277 }
278 }
279 }
280
281
282 /**
283 * hook for t3lib_TCEmain::moveRecord that cares about moving records that
284 * are *not* in the live workspace
285 *
286 * @param string $table the table of the record
287 * @param integer $id the ID of the record
288 * @param integer $destPid Position to move to: $destPid: >=0 then it points to
289 * a page-id on which to insert the record (as the first element).
290 * <0 then it points to a uid from its own table after which to insert it
291 * @param array $propArr Record properties, like header and pid (includes workspace overlay)
292 * @param array $moveRec Record properties, like header and pid (without workspace overlay)
293 * @param integer $resolvedPid The final page ID of the record
294 * (workspaces and negative values are resolved)
295 * @param boolean $recordWasMoved can be set so that other hooks or
296 * TCEmain knows that the default move action doesn't have to be called
297 * @param $table the table
298 */
299 public function moveRecord($table, $uid, $destPid, array $propArr, array $moveRec, $resolvedPid, &$recordWasMoved, t3lib_TCEmain $tcemainObj) {
300
301 // Only do something in Draft workspace
302 if ($tcemainObj->BE_USER->workspace !== 0) {
303 $recordWasMoved = TRUE;
304
305 // Get workspace version of the source record, if any:
306 $WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($tcemainObj->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');
307
308 // If no version exists and versioningWS is in version 2, a new placeholder is made automatically:
309 if (!$WSversion['uid'] && (int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2 && (int)$moveRec['t3ver_state'] != 3) {
310 $tcemainObj->versionizeRecord($table, $uid, 'Placeholder version for moving record');
311 $WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($tcemainObj->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid'); // Will not create new versions in live workspace though...
312 }
313
314 // Check workspace permissions:
315 $workspaceAccessBlocked = array();
316 // Element was in "New/Deleted/Moved" so it can be moved...
317 $recIsNewVersion = (int)$moveRec['t3ver_state']>0;
318
319 $destRes = $tcemainObj->BE_USER->workspaceAllowLiveRecordsInPID($resolvedPid, $table);
320 $canMoveRecord = $recIsNewVersion || (int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2;
321
322 // Workspace source check:
323 if (!$recIsNewVersion) {
324 $errorCode = $tcemainObj->BE_USER->workspaceCannotEditRecord($table, $WSversion['uid'] ? $WSversion['uid'] : $uid);
325 if ($errorCode) {
326 $workspaceAccessBlocked['src1'] = 'Record could not be edited in workspace: ' . $errorCode . ' ';
327 } elseif (!$canMoveRecord && $tcemainObj->BE_USER->workspaceAllowLiveRecordsInPID($moveRec['pid'], $table) <= 0) {
328 $workspaceAccessBlocked['src2'] = 'Could not remove record from table "' . $table . '" from its page "'.$moveRec['pid'].'" ';
329 }
330 }
331
332 // Workspace destination check:
333
334 // All records can be inserted if $destRes is greater than zero.
335 // Only new versions can be inserted if $destRes is FALSE.
336 // NO RECORDS can be inserted if $destRes is negative which indicates a stage
337 // not allowed for use. If "versioningWS" is version 2, moving can take place of versions.
338 if (!($destRes > 0 || ($canMoveRecord && !$destRes))) {
339 $workspaceAccessBlocked['dest1'] = 'Could not insert record from table "' . $table . '" in destination PID "' . $resolvedPid . '" ';
340 } elseif ($destRes == 1 && $WSversion['uid']) {
341 $workspaceAccessBlocked['dest2'] = 'Could not insert other versions in destination PID ';
342 }
343
344 if (!count($workspaceAccessBlocked)) {
345 // If the move operation is done on a versioned record, which is
346 // NOT new/deleted placeholder and versioningWS is in version 2, then...
347 if ($WSversion['uid'] && !$recIsNewVersion && (int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) {
348 $this->moveRecord_wsPlaceholders($table, $uid, $destPid, $WSversion['uid'], $tcemainObj);
349 } else {
350 // moving not needed, just behave like in live workspace
351 $recordWasMoved = FALSE;
352 }
353 } else {
354 $tcemainObj->newlog("Move attempt failed due to workspace restrictions: " . implode(' // ', $workspaceAccessBlocked), 1);
355 }
356 }
357 }
358
359
360
361 /****************************
362 ***** Notifications ******
363 ****************************/
364
365 /**
366 * Send an email notification to users in workspace
367 *
368 * @param array $stat Workspace access array (from t3lib_userauthgroup::checkWorkspace())
369 * @param integer $stageId New Stage number: 0 = editing, 1= just ready for review, 10 = ready for publication, -1 = rejected!
370 * @param string $table Table name of element (or list of element names if $id is zero)
371 * @param integer $id Record uid of element (if zero, then $table is used as reference to element(s) alone)
372 * @param string $comment User comment sent along with action
373 * @param t3lib_TCEmain $tcemainObj TCEmain object
374 * @param string $notificationAlternativeRecipients Comma separated list of recipients to notificate instead of be_users selected by sys_workspace, list is generated by workspace extension module
375 * @return void
376 */
377 protected function notifyStageChange(array $stat, $stageId, $table, $id, $comment, t3lib_TCEmain $tcemainObj, $notificationAlternativeRecipients = FALSE) {
378 $workspaceRec = t3lib_BEfunc::getRecord('sys_workspace', $stat['uid']);
379 // So, if $id is not set, then $table is taken to be the complete element name!
380 $elementName = $id ? $table . ':' . $id : $table;
381
382 if (is_array($workspaceRec)) {
383
384 // Get the new stage title from workspaces library, if workspaces extension is installed
385 if (t3lib_extMgm::isLoaded('workspaces')) {
386 $stageService = t3lib_div::makeInstance('Tx_Workspaces_Service_Stages');
387 $newStage = $stageService->getStageTitle((int)$stageId);
388 } else {
389 // TODO: CONSTANTS SHOULD BE USED - tx_service_workspace_workspaces
390 // TODO: use localized labels
391 // Compile label:
392 switch ((int)$stageId) {
393 case 1:
394 $newStage = 'Ready for review';
395 break;
396 case 10:
397 $newStage = 'Ready for publishing';
398 break;
399 case -1:
400 $newStage = 'Element was rejected!';
401 break;
402 case 0:
403 $newStage = 'Rejected element was noticed and edited';
404 break;
405 default:
406 $newStage = 'Unknown state change!?';
407 break;
408 }
409 }
410
411 if ($notificationAlternativeRecipients === FALSE) {
412 // Compile list of recipients:
413 $emails = array();
414 switch ((int)$stat['stagechg_notification']) {
415 case 1:
416 switch ((int)$stageId) {
417 case 1:
418 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']);
419 break;
420 case 10:
421 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], TRUE);
422 break;
423 case -1:
424 # $emails = $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']);
425 # $emails = array_merge($emails,$this->getEmailsForStageChangeNotification($workspaceRec['members']));
426
427 // List of elements to reject:
428 $allElements = explode(',', $elementName);
429 // Traverse them, and find the history of each
430 foreach ($allElements as $elRef) {
431 list($eTable, $eUid) = explode(':', $elRef);
432
433 $rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
434 'log_data,tstamp,userid',
435 'sys_log',
436 'action=6 and details_nr=30
437 AND tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($eTable, 'sys_log') . '
438 AND recuid=' . intval($eUid),
439 '',
440 'uid DESC'
441 );
442 // Find all implicated since the last stage-raise from editing to review:
443 foreach ($rows as $dat) {
444 $data = unserialize($dat['log_data']);
445
446 $emails = t3lib_div::array_merge($emails, $this->getEmailsForStageChangeNotification($dat['userid'], TRUE));
447
448 if ($data['stage'] == 1) {
449 break;
450 }
451 }
452 }
453 break;
454
455 case 0:
456 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['members']);
457 break;
458
459 default:
460 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], TRUE);
461 break;
462 }
463 break;
464 case 10:
465 $emails = $this->getEmailsForStageChangeNotification($workspaceRec['adminusers'], TRUE);
466 $emails = t3lib_div::array_merge($emails, $this->getEmailsForStageChangeNotification($workspaceRec['reviewers']));
467 $emails = t3lib_div::array_merge($emails, $this->getEmailsForStageChangeNotification($workspaceRec['members']));
468 break;
469 }
470 } else {
471 $emails = array();
472 foreach ($notificationAlternativeRecipients as $emailAddress) {
473 $emails[] = array('email' => $emailAddress);
474 }
475 }
476
477 // prepare and then send the emails
478 if (count($emails)) {
479
480 // Path to record is found:
481 list($elementTable, $elementUid) = explode(':', $elementName);
482 $elementUid = intval($elementUid);
483 $elementRecord = t3lib_BEfunc::getRecord($elementTable, $elementUid);
484 $recordTitle = t3lib_BEfunc::getRecordTitle($elementTable, $elementRecord);
485
486 if ($elementTable == 'pages') {
487 $pageUid = $elementUid;
488 } else {
489 t3lib_BEfunc::fixVersioningPid($elementTable, $elementRecord);
490 $pageUid = $elementUid = $elementRecord['pid'];
491 }
492
493 // fetch the TSconfig settings for the email
494
495 // old way, options are TCEMAIN.notificationEmail_body/subject
496 $TCEmainTSConfig = $tcemainObj->getTCEMAIN_TSconfig($pageUid);
497
498 // new way, options are
499 // pageTSconfig: tx_version.workspaces.stageNotificationEmail.subject
500 // userTSconfig: page.tx_version.workspaces.stageNotificationEmail.subject
501 $pageTsConfig = t3lib_BEfunc::getPagesTSconfig($pageUid);
502 $emailConfig = $pageTsConfig['tx_version.']['workspaces.']['stageNotificationEmail.'];
503
504 $markers = array(
505 '###RECORD_TITLE###' => $recordTitle,
506 '###RECORD_PATH###' => t3lib_BEfunc::getRecordPath($elementUid, '', 20),
507 '###SITE_NAME###' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
508 '###SITE_URL###' => t3lib_div::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir,
509 '###WORKSPACE_TITLE###' => $workspaceRec['title'],
510 '###WORKSPACE_UID###' => $workspaceRec['uid'],
511 '###ELEMENT_NAME###' => $elementName,
512 '###NEXT_STAGE###' => $newStage,
513 '###COMMENT###' => $comment,
514 // See: #30212 - keep both markers for compatibility
515 '###USER_REALNAME###' => $tcemainObj->BE_USER->user['realName'],
516 '###USER_FULLNAME###' => $tcemainObj->BE_USER->user['realName'],
517 '###USER_USERNAME###' => $tcemainObj->BE_USER->user['username']
518 );
519
520 // add marker for preview links if workspace extension is loaded
521 if (t3lib_extMgm::isLoaded('workspaces')) {
522 $this->workspaceService = t3lib_div::makeInstance('tx_Workspaces_Service_Workspaces');
523 // only generate the link if the marker is in the template - prevents database from getting to much entries
524 if (t3lib_div::isFirstPartOfStr($emailConfig['message'], 'LLL:')) {
525 $tempEmailMessage = $GLOBALS['LANG']->sL($emailConfig['message']);
526 } else {
527 $tempEmailMessage = $emailConfig['message'];
528 }
529 if (strpos($tempEmailMessage, '###PREVIEW_LINK###') !== FALSE) {
530 $markers['###PREVIEW_LINK###'] = $this->workspaceService->generateWorkspacePreviewLink($elementUid);
531 }
532 unset($tempEmailMessage);
533
534 $markers['###SPLITTED_PREVIEW_LINK###'] = $this->workspaceService->generateWorkspaceSplittedPreviewLink($elementUid, TRUE);
535 }
536
537 // Hook for preprocessing of the content for formmails:
538 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/version/class.tx_version_tcemain.php']['notifyStageChange-postModifyMarkers'])) {
539 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['ext/version/class.tx_version_tcemain.php']['notifyStageChange-postModifyMarkers'] as $_classRef) {
540 $_procObj = &t3lib_div::getUserObj($_classRef);
541 $markers = $_procObj->postModifyMarkers($markers, $this);
542 }
543 }
544
545 // send an email to each individual user, to ensure the
546 // multilanguage version of the email
547 $emailHeaders = $emailConfig['additionalHeaders'];
548 $emailRecipients = array();
549
550 // an array of language objects that are needed
551 // for emails with different languages
552 $languageObjects = array(
553 $GLOBALS['LANG']->lang => $GLOBALS['LANG']
554 );
555
556 // loop through each recipient and send the email
557 foreach ($emails as $recipientData) {
558 // don't send an email twice
559 if (isset($emailRecipients[$recipientData['email']])) {
560 continue;
561 }
562 $emailSubject = $emailConfig['subject'];
563 $emailMessage = $emailConfig['message'];
564 $emailRecipients[$recipientData['email']] = $recipientData['email'];
565
566 // check if the email needs to be localized
567 // in the users' language
568 if (t3lib_div::isFirstPartOfStr($emailSubject, 'LLL:') || t3lib_div::isFirstPartOfStr($emailMessage, 'LLL:')) {
569 $recipientLanguage = ($recipientData['lang'] ? $recipientData['lang'] : 'default');
570 if (!isset($languageObjects[$recipientLanguage])) {
571 // a LANG object in this language hasn't been
572 // instantiated yet, so this is done here
573 /** @var $languageObject language */
574 $languageObject = t3lib_div::makeInstance('language');
575 $languageObject->init($recipientLanguage);
576 $languageObjects[$recipientLanguage] = $languageObject;
577 } else {
578 $languageObject = $languageObjects[$recipientLanguage];
579 }
580
581 if (t3lib_div::isFirstPartOfStr($emailSubject, 'LLL:')) {
582 $emailSubject = $languageObject->sL($emailSubject);
583 }
584
585 if (t3lib_div::isFirstPartOfStr($emailMessage, 'LLL:')) {
586 $emailMessage = $languageObject->sL($emailMessage);
587 }
588 }
589
590 $emailSubject = t3lib_parseHtml::substituteMarkerArray($emailSubject, $markers, '', TRUE, TRUE);
591 $emailMessage = t3lib_parseHtml::substituteMarkerArray($emailMessage, $markers, '', TRUE, TRUE);
592 // Send an email to the recipient
593 t3lib_div::plainMailEncoded(
594 $recipientData['email'],
595 $emailSubject,
596 $emailMessage,
597 $emailHeaders
598 );
599 }
600 $emailRecipients = implode(',', $emailRecipients);
601 $tcemainObj->newlog2('Notification email for stage change was sent to "' . $emailRecipients . '"', $table, $id);
602 }
603 }
604 }
605
606 /**
607 * Return be_users that should be notified on stage change from input list.
608 * previously called notifyStageChange_getEmails() in tcemain
609 *
610 * @param string $listOfUsers List of backend users, on the form "be_users_10,be_users_2" or "10,2" in case noTablePrefix is set.
611 * @param boolean $noTablePrefix If set, the input list are integers and not strings.
612 * @return array Array of emails
613 */
614 protected function getEmailsForStageChangeNotification($listOfUsers, $noTablePrefix = FALSE) {
615 $users = t3lib_div::trimExplode(',', $listOfUsers, 1);
616 $emails = array();
617 foreach ($users as $userIdent) {
618 if ($noTablePrefix) {
619 $id = intval($userIdent);
620 } else {
621 list($table, $id) = t3lib_div::revExplode('_', $userIdent, 2);
622 }
623 if ($table === 'be_users' || $noTablePrefix) {
624 if ($userRecord = t3lib_BEfunc::getRecord('be_users', $id, 'uid,email,lang,realName', t3lib_BEfunc::BEenableFields('be_users'))) {
625 if (strlen(trim($userRecord['email']))) {
626 $emails[$id] = $userRecord;
627 }
628 }
629 }
630 }
631 return $emails;
632 }
633
634
635 /****************************
636 ***** Stage Changes ******
637 ****************************/
638
639 /**
640 * Setting stage of record
641 *
642 * @param string $table Table name
643 * @param integer $integer Record UID
644 * @param integer $stageId Stage ID to set
645 * @param string $comment Comment that goes into log
646 * @param boolean $notificationEmailInfo Accumulate state changes in memory for compiled notification email?
647 * @param t3lib_TCEmain $tcemainObj TCEmain object
648 * @param string $notificationAlternativeRecipients comma separated list of recipients to notificate instead of normal be_users
649 * @return void
650 */
651 protected function version_setStage($table, $id, $stageId, $comment = '', $notificationEmailInfo = FALSE, t3lib_TCEmain $tcemainObj, $notificationAlternativeRecipients = FALSE) {
652 if ($errorCode = $tcemainObj->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
653 $tcemainObj->newlog('Attempt to set stage for record failed: ' . $errorCode, 1);
654 } elseif ($tcemainObj->checkRecordUpdateAccess($table, $id)) {
655 $record = t3lib_BEfunc::getRecord($table, $id);
656 $stat = $tcemainObj->BE_USER->checkWorkspace($record['t3ver_wsid']);
657 // check if the usere is allowed to the current stage, so it's also allowed to send to next stage
658 if ($GLOBALS['BE_USER']->workspaceCheckStageForCurrent($record['t3ver_stage'])) {
659
660 // Set stage of record:
661 $updateData = array(
662 't3ver_stage' => $stageId
663 );
664 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($id), $updateData);
665 $tcemainObj->newlog2('Stage for record was changed to ' . $stageId . '. Comment was: "' . substr($comment, 0, 100) . '"', $table, $id);
666
667 // TEMPORARY, except 6-30 as action/detail number which is observed elsewhere!
668 $tcemainObj->log($table, $id, 6, 0, 0, 'Stage raised...', 30, array('comment' => $comment, 'stage' => $stageId));
669
670 if ((int)$stat['stagechg_notification'] > 0) {
671 if ($notificationEmailInfo) {
672 $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['shared'] = array($stat, $stageId, $comment);
673 $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['elements'][] = $table . ':' . $id;
674 $this->notificationEmailInfo[$stat['uid'] . ':' . $stageId . ':' . $comment]['alternativeRecipients'] = $notificationAlternativeRecipients;
675 } else {
676 $this->notifyStageChange($stat, $stageId, $table, $id, $comment, $tcemainObj, $notificationAlternativeRecipients);
677 }
678 }
679 } else $tcemainObj->newlog('The member user tried to set a stage value "' . $stageId . '" that was not allowed', 1);
680 } else $tcemainObj->newlog('Attempt to set stage for record failed because you do not have edit access', 1);
681 }
682
683
684
685 /*****************************
686 ***** CMD versioning ******
687 *****************************/
688
689 /**
690 * Creates a new version of a page including content and possible subpages.
691 *
692 * @param integer $uid Page uid to create new version of.
693 * @param string $label Version label
694 * @param integer $versionizeTree Indicating "treeLevel" - "page" (0) or "branch" (>=1) ["element" type must call versionizeRecord() directly]
695 * @param t3lib_TCEmain $tcemainObj TCEmain object
696 * @return void
697 * @see copyPages()
698 */
699 protected function versionizePages($uid, $label, $versionizeTree, t3lib_TCEmain $tcemainObj) {
700 $uid = intval($uid);
701 // returns the branch
702 $brExist = $tcemainObj->doesBranchExist('', $uid, $tcemainObj->pMap['show'], 1);
703
704 // Checks if we had permissions
705 if ($brExist != -1) {
706
707 // Make list of tables that should come along with a new version of the page:
708 $verTablesArray = array();
709 $allTables = array_keys($GLOBALS['TCA']);
710 foreach ($allTables as $tableName) {
711 if ($tableName != 'pages' && ($versionizeTree > 0 || $GLOBALS['TCA'][$tableName]['ctrl']['versioning_followPages'])) {
712 $verTablesArray[] = $tableName;
713 }
714 }
715
716 // Remove the possible inline child tables from the tables to be versioniozed automatically:
717 $verTablesArray = array_diff($verTablesArray, $this->getPossibleInlineChildTablesOfParentTable('pages'));
718
719 // Begin to copy pages if we're allowed to:
720 if ($tcemainObj->BE_USER->workspaceVersioningTypeAccess($versionizeTree)) {
721
722 // Versionize this page:
723 $theNewRootID = $tcemainObj->versionizeRecord('pages', $uid, $label, FALSE, $versionizeTree);
724 if ($theNewRootID) {
725 $this->rawCopyPageContent($uid, $theNewRootID, $verTablesArray, $tcemainObj);
726
727 // If we're going to copy recursively...:
728 if ($versionizeTree > 0) {
729
730 // Get ALL subpages to copy (read permissions respected - they should NOT be...):
731 $CPtable = $tcemainObj->int_pageTreeInfo(array(), $uid, intval($versionizeTree), $theNewRootID);
732
733 // Now copying the subpages
734 foreach ($CPtable as $thePageUid => $thePagePid) {
735 $newPid = $tcemainObj->copyMappingArray['pages'][$thePagePid];
736 if (isset($newPid)) {
737 $theNewRootID = $tcemainObj->copyRecord_raw('pages', $thePageUid, $newPid);
738 $this->rawCopyPageContent($thePageUid, $theNewRootID, $verTablesArray, $tcemainObj);
739 } else {
740 $tcemainObj->newlog('Something went wrong during copying branch (for versioning)', 1);
741 break;
742 }
743 }
744 } // else the page was not copied. Too bad...
745 } else $tcemainObj->newlog('The root version could not be created!',1);
746 } else $tcemainObj->newlog('Versioning type "'.$versionizeTree.'" was not allowed in workspace',1);
747 } else $tcemainObj->newlog('Could not read all subpages to versionize.',1);
748 }
749
750
751 /**
752 * Swapping versions of a record
753 * Version from archive (future/past, called "swap version") will get the uid of the "t3ver_oid", the official element with uid = "t3ver_oid" will get the new versions old uid. PIDs are swapped also
754 *
755 * @param string $table Table name
756 * @param integer $id UID of the online record to swap
757 * @param integer $swapWith UID of the archived version to swap with!
758 * @param boolean $swapIntoWS If set, swaps online into workspace instead of publishing out of workspace.
759 * @param t3lib_TCEmain $tcemainObj TCEmain object
760 * @return void
761 */
762 protected function version_swap($table, $id, $swapWith, $swapIntoWS=0, t3lib_TCEmain $tcemainObj) {
763
764 // First, check if we may actually edit the online record
765 if ($tcemainObj->checkRecordUpdateAccess($table, $id)) {
766
767 // Select the two versions:
768 $curVersion = t3lib_BEfunc::getRecord($table, $id, '*');
769 $swapVersion = t3lib_BEfunc::getRecord($table, $swapWith, '*');
770 $movePlh = array();
771 $movePlhID = 0;
772
773 if (is_array($curVersion) && is_array($swapVersion)) {
774 if ($tcemainObj->BE_USER->workspacePublishAccess($swapVersion['t3ver_wsid'])) {
775 $wsAccess = $tcemainObj->BE_USER->checkWorkspace($swapVersion['t3ver_wsid']);
776 if ($swapVersion['t3ver_wsid'] <= 0 || !($wsAccess['publish_access'] & 1) || (int)$swapVersion['t3ver_stage'] === -10) {
777 if ($tcemainObj->doesRecordExist($table,$swapWith,'show') && $tcemainObj->checkRecordUpdateAccess($table,$swapWith)) {
778 if (!$swapIntoWS || $tcemainObj->BE_USER->workspaceSwapAccess()) {
779
780 // Check if the swapWith record really IS a version of the original!
781 if ((int)$swapVersion['pid'] == -1 && (int)$curVersion['pid'] >= 0 && !strcmp($swapVersion['t3ver_oid'], $id)) {
782
783 // Lock file name:
784 $lockFileName = PATH_site.'typo3temp/swap_locking/' . $table . ':' . $id . '.ser';
785
786 if (!@is_file($lockFileName)) {
787
788 // Write lock-file:
789 t3lib_div::writeFileToTypo3tempDir($lockFileName, serialize(array(
790 'tstamp' => $GLOBALS['EXEC_TIME'],
791 'user' => $tcemainObj->BE_USER->user['username'],
792 'curVersion' => $curVersion,
793 'swapVersion' => $swapVersion
794 )));
795
796 // Find fields to keep
797 $keepFields = $tcemainObj->getUniqueFields($table);
798 if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) {
799 $keepFields[] = $GLOBALS['TCA'][$table]['ctrl']['sortby'];
800 }
801 // l10n-fields must be kept otherwise the localization
802 // will be lost during the publishing
803 if (!isset($GLOBALS['TCA'][$table]['ctrl']['transOrigPointerTable']) && $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']) {
804 $keepFields[] = $GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField'];
805 }
806
807 // Swap "keepfields"
808 foreach ($keepFields as $fN) {
809 $tmp = $swapVersion[$fN];
810 $swapVersion[$fN] = $curVersion[$fN];
811 $curVersion[$fN] = $tmp;
812 }
813
814 // Preserve states:
815 $t3ver_state = array();
816 $t3ver_state['swapVersion'] = $swapVersion['t3ver_state'];
817 $t3ver_state['curVersion'] = $curVersion['t3ver_state'];
818
819 // Modify offline version to become online:
820 $tmp_wsid = $swapVersion['t3ver_wsid'];
821 // Set pid for ONLINE
822 $swapVersion['pid'] = intval($curVersion['pid']);
823 // We clear this because t3ver_oid only make sense for offline versions
824 // and we want to prevent unintentional misuse of this
825 // value for online records.
826 $swapVersion['t3ver_oid'] = 0;
827 // In case of swapping and the offline record has a state
828 // (like 2 or 4 for deleting or move-pointer) we set the
829 // current workspace ID so the record is not deselected
830 // in the interface by t3lib_BEfunc::versioningPlaceholderClause()
831 $swapVersion['t3ver_wsid'] = 0;
832 if ($swapIntoWS) {
833 if ($t3ver_state['swapVersion'] > 0) {
834 $swapVersion['t3ver_wsid'] = $tcemainObj->BE_USER->workspace;
835 } else {
836 $swapVersion['t3ver_wsid'] = intval($curVersion['t3ver_wsid']);
837 }
838 }
839 $swapVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
840 $swapVersion['t3ver_stage'] = 0;
841 if (!$swapIntoWS) {
842 $swapVersion['t3ver_state'] = 0;
843 }
844
845 // Moving element.
846 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) {
847 // && $t3ver_state['swapVersion']==4 // Maybe we don't need this?
848 if ($plhRec = t3lib_BEfunc::getMovePlaceholder($table, $id, 't3ver_state,pid,uid' . ($GLOBALS['TCA'][$table]['ctrl']['sortby'] ? ',' . $GLOBALS['TCA'][$table]['ctrl']['sortby'] : ''))) {
849 $movePlhID = $plhRec['uid'];
850 $movePlh['pid'] = $swapVersion['pid'];
851 $swapVersion['pid'] = intval($plhRec['pid']);
852
853 $curVersion['t3ver_state'] = intval($swapVersion['t3ver_state']);
854 $swapVersion['t3ver_state'] = 0;
855
856 if ($GLOBALS['TCA'][$table]['ctrl']['sortby']) {
857 // sortby is a "keepFields" which is why this will work...
858 $movePlh[$GLOBALS['TCA'][$table]['ctrl']['sortby']] = $swapVersion[$GLOBALS['TCA'][$table]['ctrl']['sortby']];
859 $swapVersion[$GLOBALS['TCA'][$table]['ctrl']['sortby']] = $plhRec[$GLOBALS['TCA'][$table]['ctrl']['sortby']];
860 }
861 }
862 }
863
864 // Take care of relations in each field (e.g. IRRE):
865 if (is_array($GLOBALS['TCA'][$table]['columns'])) {
866 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $fieldConf) {
867 $this->version_swap_procBasedOnFieldType(
868 $table, $field, $fieldConf['config'], $curVersion, $swapVersion, $tcemainObj
869 );
870 }
871 }
872 unset($swapVersion['uid']);
873
874 // Modify online version to become offline:
875 unset($curVersion['uid']);
876 // Set pid for OFFLINE
877 $curVersion['pid'] = -1;
878 $curVersion['t3ver_oid'] = intval($id);
879 $curVersion['t3ver_wsid'] = ($swapIntoWS ? intval($tmp_wsid) : 0);
880 $curVersion['t3ver_tstamp'] = $GLOBALS['EXEC_TIME'];
881 $curVersion['t3ver_count'] = $curVersion['t3ver_count']+1; // Increment lifecycle counter
882 $curVersion['t3ver_stage'] = 0;
883 if (!$swapIntoWS) {
884 $curVersion['t3ver_state'] = 0;
885 }
886
887 // Keeping the swapmode state
888 if ($table === 'pages') {
889 $curVersion['t3ver_swapmode'] = $swapVersion['t3ver_swapmode'];
890 }
891
892 // Registering and swapping MM relations in current and swap records:
893 $tcemainObj->version_remapMMForVersionSwap($table, $id, $swapWith);
894
895 // Generating proper history data to prepare logging
896 $tcemainObj->compareFieldArrayWithCurrentAndUnset($table, $id, $swapVersion);
897 $tcemainObj->compareFieldArrayWithCurrentAndUnset($table, $swapWith, $curVersion);
898
899 // Execute swapping:
900 $sqlErrors = array();
901 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($id), $swapVersion);
902 if ($GLOBALS['TYPO3_DB']->sql_error()) {
903 $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
904 } else {
905 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($swapWith), $curVersion);
906 if ($GLOBALS['TYPO3_DB']->sql_error()) {
907 $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
908 } else {
909 unlink($lockFileName);
910 }
911 }
912
913 if (!count($sqlErrors)) {
914 // Register swapped ids for later remapping:
915 $this->remappedIds[$table][$id] =$swapWith;
916 $this->remappedIds[$table][$swapWith] = $id;
917
918 // If a moving operation took place...:
919 if ($movePlhID) {
920 // Remove, if normal publishing:
921 if (!$swapIntoWS) {
922 // For delete + completely delete!
923 $tcemainObj->deleteEl($table, $movePlhID, TRUE, TRUE);
924 } else {
925 // Otherwise update the movePlaceholder:
926 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($movePlhID), $movePlh);
927 $tcemainObj->addRemapStackRefIndex($table, $movePlhID);
928 }
929 }
930
931 // Checking for delete:
932 // Delete only if new/deleted placeholders are there.
933 if (!$swapIntoWS && ((int)$t3ver_state['swapVersion'] === 1 || (int)$t3ver_state['swapVersion'] === 2)) {
934 // Force delete
935 $tcemainObj->deleteEl($table, $id, TRUE);
936 }
937
938 $tcemainObj->newlog2(($swapIntoWS ? 'Swapping' : 'Publishing') . ' successful for table "' . $table . '" uid ' . $id . '=>' . $swapWith, $table, $id, $swapVersion['pid']);
939
940 // Update reference index of the live record:
941 $tcemainObj->addRemapStackRefIndex($table, $id);
942
943 // Set log entry for live record:
944 $propArr = $tcemainObj->getRecordPropertiesFromRow($table, $swapVersion);
945 if ($propArr['_ORIG_pid'] == -1) {
946 $label = $GLOBALS['LANG']->sL ('LLL:EXT:lang/locallang_tcemain.xml:version_swap.offline_record_updated');
947 } else {
948 $label = $GLOBALS['LANG']->sL ('LLL:EXT:lang/locallang_tcemain.xml:version_swap.online_record_updated');
949 }
950 $theLogId = $tcemainObj->log($table, $id, 2, $propArr['pid'], 0, $label, 10, array($propArr['header'], $table . ':' . $id), $propArr['event_pid']);
951 $tcemainObj->setHistory($table, $id, $theLogId);
952
953 // Update reference index of the offline record:
954 $tcemainObj->addRemapStackRefIndex($table, $swapWith);
955 // Set log entry for offline record:
956 $propArr = $tcemainObj->getRecordPropertiesFromRow($table, $curVersion);
957 if ($propArr['_ORIG_pid'] == -1) {
958 $label = $GLOBALS['LANG']->sL ('LLL:EXT:lang/locallang_tcemain.xml:version_swap.offline_record_updated');
959 } else {
960 $label = $GLOBALS['LANG']->sL ('LLL:EXT:lang/locallang_tcemain.xml:version_swap.online_record_updated');
961 }
962 $theLogId = $tcemainObj->log($table, $swapWith, 2, $propArr['pid'], 0, $label, 10, array($propArr['header'], $table . ':' . $swapWith), $propArr['event_pid']);
963 $tcemainObj->setHistory($table, $swapWith, $theLogId);
964
965 // SWAPPING pids for subrecords:
966 if ($table=='pages' && $swapVersion['t3ver_swapmode'] >= 0) {
967
968 // Collect table names that should be copied along with the tables:
969 foreach ($GLOBALS['TCA'] as $tN => $tCfg) {
970 // For "Branch" publishing swap ALL,
971 // otherwise for "page" publishing, swap only "versioning_followPages" tables
972 if ($swapVersion['t3ver_swapmode'] > 0 || $GLOBALS['TCA'][$tN]['ctrl']['versioning_followPages']) {
973 $temporaryPid = -($id+1000000);
974
975 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN, 'pid=' . intval($id), array('pid' => $temporaryPid));
976 if ($GLOBALS['TYPO3_DB']->sql_error()) {
977 $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
978 }
979
980 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN, 'pid=' . intval($swapWith), array('pid' => $id));
981 if ($GLOBALS['TYPO3_DB']->sql_error()) {
982 $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
983 }
984
985 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN, 'pid=' . intval($temporaryPid), array('pid' => $swapWith));
986 if ($GLOBALS['TYPO3_DB']->sql_error()) {
987 $sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
988 }
989
990 if (count($sqlErrors)) {
991 $tcemainObj->newlog('During Swapping: SQL errors happened: ' . implode('; ', $sqlErrors), 2);
992 }
993 }
994 }
995 }
996 // Clear cache:
997 $tcemainObj->clear_cache($table, $id);
998
999 // Checking for "new-placeholder" and if found, delete it (BUT FIRST after swapping!):
1000 if (!$swapIntoWS && $t3ver_state['curVersion']>0) {
1001 // For delete + completely delete!
1002 $tcemainObj->deleteEl($table, $swapWith, TRUE, TRUE);
1003 }
1004 } else $tcemainObj->newlog('During Swapping: SQL errors happened: ' . implode('; ', $sqlErrors), 2);
1005 } else $tcemainObj->newlog('A swapping lock file was present. Either another swap process is already running or a previous swap process failed. Ask your administrator to handle the situation.', 2);
1006 } else $tcemainObj->newlog('In swap version, either pid was not -1 or the t3ver_oid didn\'t match the id of the online version as it must!', 2);
1007 } else $tcemainObj->newlog('Workspace #' . $swapVersion['t3ver_wsid'] . ' does not support swapping.', 1);
1008 } else $tcemainObj->newlog('You cannot publish a record you do not have edit and show permissions for', 1);
1009 } else $tcemainObj->newlog('Records in workspace #' . $swapVersion['t3ver_wsid'] . ' can only be published when in "Publish" stage.', 1);
1010 } else $tcemainObj->newlog('User could not publish records from workspace #' . $swapVersion['t3ver_wsid'], 1);
1011 } else $tcemainObj->newlog('Error: Either online or swap version could not be selected!', 2);
1012 } else $tcemainObj->newlog('Error: You cannot swap versions for a record you do not have access to edit!', 1);
1013 }
1014
1015
1016 /**
1017 * Update relations on version/workspace swapping.
1018 *
1019 * @param string $table: Record Table
1020 * @param string $field: Record field
1021 * @param array $conf: TCA configuration of current field
1022 * @param array $curVersion: Reference to the current (original) record
1023 * @param array $swapVersion: Reference to the record (workspace/versionized) to publish in or swap with
1024 * @param t3lib_TCEmain $tcemainObj TCEmain object
1025 * @return void
1026 */
1027 protected function version_swap_procBasedOnFieldType($table, $field, array $conf, array &$curVersion, array &$swapVersion, t3lib_TCEmain $tcemainObj) {
1028 $inlineType = $tcemainObj->getInlineFieldType($conf);
1029
1030 // Process pointer fields on normalized database:
1031 if ($inlineType == 'field') {
1032 // Read relations that point to the current record (e.g. live record):
1033 /** @var $dbAnalysisCur t3lib_loadDBGroup */
1034 $dbAnalysisCur = t3lib_div::makeInstance('t3lib_loadDBGroup');
1035 $dbAnalysisCur->setUpdateReferenceIndex(FALSE);
1036 $dbAnalysisCur->start('', $conf['foreign_table'], '', $curVersion['uid'], $table, $conf);
1037 // Read relations that point to the record to be swapped with e.g. draft record):
1038 /** @var $dbAnalysisSwap t3lib_loadDBGroup */
1039 $dbAnalysisSwap = t3lib_div::makeInstance('t3lib_loadDBGroup');
1040 $dbAnalysisSwap->setUpdateReferenceIndex(FALSE);
1041 $dbAnalysisSwap->start('', $conf['foreign_table'], '', $swapVersion['uid'], $table, $conf);
1042 // Update relations for both (workspace/versioning) sites:
1043
1044 if (count($dbAnalysisCur->itemArray)) {
1045 $dbAnalysisCur->writeForeignField($conf, $curVersion['uid'], $swapVersion['uid']);
1046 $tcemainObj->addRemapAction(
1047 $table, $curVersion['uid'],
1048 array($this, 'writeRemappedForeignField'),
1049 array($dbAnalysisCur, $conf, $swapVersion['uid'])
1050 );
1051 }
1052
1053 if (count($dbAnalysisSwap->itemArray)) {
1054 $dbAnalysisSwap->writeForeignField($conf, $swapVersion['uid'], $curVersion['uid']);
1055 $tcemainObj->addRemapAction(
1056 $table, $curVersion['uid'],
1057 array($this, 'writeRemappedForeignField'),
1058 array($dbAnalysisSwap, $conf, $curVersion['uid'])
1059 );
1060 }
1061
1062 $items = array_merge($dbAnalysisCur->itemArray, $dbAnalysisSwap->itemArray);
1063 foreach ($items as $item) {
1064 $tcemainObj->addRemapStackRefIndex($item['table'], $item['id']);
1065 }
1066
1067 // Swap field values (CSV):
1068 // BUT: These values will be swapped back in the next steps, when the *CHILD RECORD ITSELF* is swapped!
1069 } elseif ($inlineType == 'list') {
1070 $tempValue = $curVersion[$field];
1071 $curVersion[$field] = $swapVersion[$field];
1072 $swapVersion[$field] = $tempValue;
1073 }
1074 }
1075
1076 /**
1077 * Writes remapped foreign field (IRRE).
1078 *
1079 * @param t3lib_loadDBGroup $dbAnalysis Instance that holds the sorting order of child records
1080 * @param array $configuration The TCA field configuration
1081 * @param integer $parentId The uid of the parent record
1082 * @return void
1083 */
1084 public function writeRemappedForeignField(t3lib_loadDBGroup $dbAnalysis, array $configuration, $parentId) {
1085 foreach ($dbAnalysis->itemArray as &$item) {
1086 if (isset($this->remappedIds[$item['table']][$item['id']])) {
1087 $item['id'] = $this->remappedIds[$item['table']][$item['id']];
1088 }
1089 }
1090
1091 $dbAnalysis->writeForeignField($configuration, $parentId);
1092 }
1093
1094
1095
1096 /**
1097 * Release version from this workspace (and into "Live" workspace but as an offline version).
1098 *
1099 * @param string $table Table name
1100 * @param integer $id Record UID
1101 * @param boolean $flush If set, will completely delete element
1102 * @param t3lib_TCEmain $tcemainObj TCEmain object
1103 * @return void
1104 */
1105 protected function version_clearWSID($table, $id, $flush = FALSE, t3lib_TCEmain $tcemainObj) {
1106 if ($errorCode = $tcemainObj->BE_USER->workspaceCannotEditOfflineVersion($table, $id)) {
1107 $tcemainObj->newlog('Attempt to reset workspace for record failed: ' . $errorCode, 1);
1108 } elseif ($tcemainObj->checkRecordUpdateAccess($table, $id)) {
1109 if ($liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table, $id, 'uid,t3ver_state')) {
1110 // Clear workspace ID:
1111 $updateData = array(
1112 't3ver_wsid' => 0,
1113 't3ver_tstamp' => $GLOBALS['EXEC_TIME'],
1114 );
1115 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($id), $updateData);
1116
1117 // Clear workspace ID for live version AND DELETE IT as well because it is a new record!
1118 if ((int) $liveRec['t3ver_state'] == 1 || (int) $liveRec['t3ver_state'] == 2) {
1119 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid=' . intval($liveRec['uid']), $updateData);
1120 // THIS assumes that the record was placeholder ONLY for ONE record (namely $id)
1121 $tcemainObj->deleteEl($table, $liveRec['uid'], TRUE);
1122 }
1123
1124 // If "deleted" flag is set for the version that got released
1125 // it doesn't make sense to keep that "placeholder" anymore and we delete it completly.
1126 $wsRec = t3lib_BEfunc::getRecord($table, $id);
1127 if ($flush || ((int) $wsRec['t3ver_state'] == 1 || (int) $wsRec['t3ver_state'] == 2)) {
1128 $tcemainObj->deleteEl($table, $id, TRUE, TRUE);
1129 }
1130
1131 // Remove the move-placeholder if found for live record.
1132 if ((int)$GLOBALS['TCA'][$table]['ctrl']['versioningWS'] >= 2) {
1133 if ($plhRec = t3lib_BEfunc::getMovePlaceholder($table, $liveRec['uid'], 'uid')) {
1134 $tcemainObj->deleteEl($table, $plhRec['uid'], TRUE, TRUE);
1135 }
1136 }
1137 }
1138 } else $tcemainObj->newlog('Attempt to reset workspace for record failed because you do not have edit access',1);
1139 }
1140
1141
1142 /*******************************
1143 ***** helper functions ******
1144 *******************************/
1145
1146
1147 /**
1148 * Copies all records from tables in $copyTablesArray from page with $old_pid to page with $new_pid
1149 * Uses raw-copy for the operation (meant for versioning!)
1150 *
1151 * @param integer $oldPageId Current page id.
1152 * @param integer $newPageId New page id
1153 * @param array $copyTablesArray Array of tables from which to copy
1154 * @param t3lib_TCEmain $tcemainObj TCEmain object
1155 * @return void
1156 * @see versionizePages()
1157 */
1158 protected function rawCopyPageContent($oldPageId, $newPageId, array $copyTablesArray, t3lib_TCEmain $tcemainObj) {
1159 if ($newPageId) {
1160 foreach ($copyTablesArray as $table) {
1161 // all records under the page is copied.
1162 if ($table && is_array($GLOBALS['TCA'][$table]) && $table !== 'pages') {
1163 $mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
1164 'uid',
1165 $table,
1166 'pid=' . intval($oldPageId) . $tcemainObj->deleteClause($table)
1167 );
1168 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres)) {
1169 // Check, if this record has already been copied by a parent record as relation:
1170 if (!$tcemainObj->copyMappingArray[$table][$row['uid']]) {
1171 // Copying each of the underlying records (method RAW)
1172 $tcemainObj->copyRecord_raw($table, $row['uid'], $newPageId);
1173 }
1174 }
1175 $GLOBALS['TYPO3_DB']->sql_free_result($mres);
1176 }
1177 }
1178 }
1179 }
1180
1181
1182 /**
1183 * Finds all elements for swapping versions in workspace
1184 *
1185 * @param string $table Table name of the original element to swap
1186 * @param integer $id UID of the original element to swap (online)
1187 * @param integer $offlineId As above but offline
1188 * @return array Element data. Key is table name, values are array with first element as online UID, second - offline UID
1189 */
1190 public function findPageElementsForVersionSwap($table, $id, $offlineId) {
1191 $rec = t3lib_BEfunc::getRecord($table, $offlineId, 't3ver_wsid');
1192 $workspaceId = $rec['t3ver_wsid'];
1193
1194 $elementData = array();
1195 if ($workspaceId != 0) {
1196 // Get page UID for LIVE and workspace
1197 if ($table != 'pages') {
1198 $rec = t3lib_BEfunc::getRecord($table, $id, 'pid');
1199 $pageId = $rec['pid'];
1200 $rec = t3lib_BEfunc::getRecord('pages', $pageId);
1201 t3lib_BEfunc::workspaceOL('pages', $rec, $workspaceId);
1202 $offlinePageId = $rec['_ORIG_uid'];
1203 } else {
1204 $pageId = $id;
1205 $offlinePageId = $offlineId;
1206 }
1207
1208 // Traversing all tables supporting versioning:
1209 foreach ($GLOBALS['TCA'] as $table => $cfg) {
1210 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $table !== 'pages') {
1211 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('A.uid AS offlineUid, B.uid AS uid',
1212 $table . ' A,' . $table . ' B',
1213 'A.pid=-1 AND B.pid=' . $pageId . ' AND A.t3ver_wsid=' . $workspaceId .
1214 ' AND B.uid=A.t3ver_oid' .
1215 t3lib_BEfunc::deleteClause($table, 'A') . t3lib_BEfunc::deleteClause($table, 'B'));
1216 while (FALSE != ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
1217 $elementData[$table][] = array($row[1], $row[0]);
1218 }
1219 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1220 }
1221 }
1222 if ($offlinePageId && $offlinePageId != $pageId) {
1223 $elementData['pages'][] = array($pageId, $offlinePageId);
1224 }
1225 }
1226 return $elementData;
1227 }
1228
1229 /**
1230 * Searches for all elements from all tables on the given pages in the same workspace.
1231 *
1232 * @param array $pageIdList List of PIDs to search
1233 * @param integer $workspaceId Workspace ID
1234 * @param array $elementList List of found elements. Key is table name, value is array of element UIDs
1235 * @return void
1236 */
1237 public function findPageElementsForVersionStageChange(array $pageIdList, $workspaceId, array &$elementList) {
1238 if ($workspaceId != 0) {
1239 // Traversing all tables supporting versioning:
1240 foreach ($GLOBALS['TCA'] as $table => $cfg) {
1241 if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $table !== 'pages') {
1242 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('DISTINCT A.uid',
1243 $table . ' A,' . $table . ' B',
1244 'A.pid=-1' . // Offline version
1245 ' AND A.t3ver_wsid=' . $workspaceId .
1246 ' AND B.pid IN (' . implode(',', $pageIdList) . ') AND A.t3ver_oid=B.uid' .
1247 t3lib_BEfunc::deleteClause($table,'A').
1248 t3lib_BEfunc::deleteClause($table,'B')
1249 );
1250 while (FALSE !== ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
1251 $elementList[$table][] = $row[0];
1252 }
1253 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1254 if (is_array($elementList[$table])) {
1255 // Yes, it is possible to get non-unique array even with DISTINCT above!
1256 // It happens because several UIDs are passed in the array already.
1257 $elementList[$table] = array_unique($elementList[$table]);
1258 }
1259 }
1260 }
1261 }
1262 }
1263
1264
1265 /**
1266 * Finds page UIDs for the element from table <code>$table</code> with UIDs from <code>$idList</code>
1267 *
1268 * @param string $table Table to search
1269 * @param array $idList List of records' UIDs
1270 * @param integer $workspaceId Workspace ID. We need this parameter because user can be in LIVE but he still can publisg DRAFT from ws module!
1271 * @param array $pageIdList List of found page UIDs
1272 * @param array $elementList List of found element UIDs. Key is table name, value is list of UIDs
1273 * @return void
1274 */
1275 public function findPageIdsForVersionStateChange($table, array $idList, $workspaceId, array &$pageIdList, array &$elementList) {
1276 if ($workspaceId != 0) {
1277 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('DISTINCT B.pid',
1278 $table . ' A,' . $table . ' B',
1279 'A.pid=-1' . // Offline version
1280 ' AND A.t3ver_wsid=' . $workspaceId .
1281 ' AND A.uid IN (' . implode(',', $idList) . ') AND A.t3ver_oid=B.uid' .
1282 t3lib_BEfunc::deleteClause($table,'A').
1283 t3lib_BEfunc::deleteClause($table,'B')
1284 );
1285 while (FALSE !== ($row = $GLOBALS['TYPO3_DB']->sql_fetch_row($res))) {
1286 $pageIdList[] = $row[0];
1287 // Find ws version
1288 // Note: cannot use t3lib_BEfunc::getRecordWSOL()
1289 // here because it does not accept workspace id!
1290 $rec = t3lib_BEfunc::getRecord('pages', $row[0]);
1291 t3lib_BEfunc::workspaceOL('pages', $rec, $workspaceId);
1292 if ($rec['_ORIG_uid']) {
1293 $elementList['pages'][$row[0]] = $rec['_ORIG_uid'];
1294 }
1295 }
1296 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1297 // The line below is necessary even with DISTINCT
1298 // because several elements can be passed by caller
1299 $pageIdList = array_unique($pageIdList);
1300 }
1301 }
1302
1303
1304 /**
1305 * Finds real page IDs for state change.
1306 *
1307 * @param array $idList List of page UIDs, possibly versioned
1308 * @return void
1309 */
1310 public function findRealPageIds(array &$idList) {
1311 foreach ($idList as $key => $id) {
1312 $rec = t3lib_BEfunc::getRecord('pages', $id, 't3ver_oid');
1313 if ($rec['t3ver_oid'] > 0) {
1314 $idList[$key] = $rec['t3ver_oid'];
1315 }
1316 }
1317 }
1318
1319
1320 /**
1321 * Creates a move placeholder for workspaces.
1322 * USE ONLY INTERNALLY
1323 * Moving placeholder: Can be done because the system sees it as a placeholder for NEW elements like t3ver_state=1
1324 * Moving original: Will either create the placeholder if it doesn't exist or move existing placeholder in workspace.
1325 *
1326 * @param string $table Table name to move
1327 * @param integer $uid Record uid to move (online record)
1328 * @param integer $destPid Position to move to: $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
1329 * @param integer $wsUid UID of offline version of online record
1330 * @param t3lib_TCEmain $tcemainObj TCEmain object
1331 * @return void
1332 * @see moveRecord()
1333 */
1334 protected function moveRecord_wsPlaceholders($table, $uid, $destPid, $wsUid, t3lib_TCEmain $tcemainObj) {
1335 // If a record gets moved after a record that already has a placeholder record
1336 // then the new placeholder record needs to be after the existing one
1337 $originalRecordDestinationPid = $destPid;
1338 if ($destPid < 0) {
1339 $movePlaceHolder = t3lib_BEfunc::getMovePlaceholder($table, abs($destPid), 'uid');
1340
1341 if ($movePlaceHolder !== FALSE) {
1342 $destPid = -$movePlaceHolder['uid'];
1343 }
1344 }
1345
1346 if ($plh = t3lib_BEfunc::getMovePlaceholder($table, $uid, 'uid')) {
1347 // If already a placeholder exists, move it:
1348 $tcemainObj->moveRecord_raw($table, $plh['uid'], $destPid);
1349 } else {
1350 // First, we create a placeholder record in the Live workspace that
1351 // represents the position to where the record is eventually moved to.
1352 $newVersion_placeholderFieldArray = array();
1353 if ($GLOBALS['TCA'][$table]['ctrl']['crdate']) {
1354 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['crdate']] = $GLOBALS['EXEC_TIME'];
1355 }
1356 if ($GLOBALS['TCA'][$table]['ctrl']['cruser_id']) {
1357 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['cruser_id']] = $tcemainObj->userid;
1358 }
1359 if ($GLOBALS['TCA'][$table]['ctrl']['tstamp']) {
1360 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['tstamp']] = $GLOBALS['EXEC_TIME'];
1361 }
1362
1363 if ($table == 'pages') {
1364 // Copy page access settings from original page to placeholder
1365 $perms_clause = $tcemainObj->BE_USER->getPagePermsClause(1);
1366 $access = t3lib_BEfunc::readPageAccess($uid, $perms_clause);
1367
1368 $newVersion_placeholderFieldArray['perms_userid'] = $access['perms_userid'];
1369 $newVersion_placeholderFieldArray['perms_groupid'] = $access['perms_groupid'];
1370 $newVersion_placeholderFieldArray['perms_user'] = $access['perms_user'];
1371 $newVersion_placeholderFieldArray['perms_group'] = $access['perms_group'];
1372 $newVersion_placeholderFieldArray['perms_everybody'] = $access['perms_everybody'];
1373 }
1374
1375 $newVersion_placeholderFieldArray['t3ver_label'] = 'MOVE-TO PLACEHOLDER for #' . $uid;
1376 $newVersion_placeholderFieldArray['t3ver_move_id'] = $uid;
1377 // Setting placeholder state value for temporary record
1378 $newVersion_placeholderFieldArray['t3ver_state'] = 3;
1379
1380 // Setting workspace - only so display of place holders can filter out those from other workspaces.
1381 $newVersion_placeholderFieldArray['t3ver_wsid'] = $tcemainObj->BE_USER->workspace;
1382 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['label']] = '[MOVE-TO PLACEHOLDER for #' . $uid . ', WS#' . $tcemainObj->BE_USER->workspace . ']';
1383
1384 // moving localized records requires to keep localization-settings for the placeholder too
1385 if (array_key_exists('languageField', $GLOBALS['TCA'][$table]['ctrl']) && array_key_exists('transOrigPointerField', $GLOBALS['TCA'][$table]['ctrl'])) {
1386 $l10nParentRec = t3lib_BEfunc::getRecord($table, $uid);
1387 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['languageField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['languageField']];
1388 $newVersion_placeholderFieldArray[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']] = $l10nParentRec[$GLOBALS['TCA'][$table]['ctrl']['transOrigPointerField']];
1389 unset($l10nParentRec);
1390 }
1391 // Initially, create at root level.
1392 $newVersion_placeholderFieldArray['pid'] = 0;
1393 $id = 'NEW_MOVE_PLH';
1394 // Saving placeholder as 'original'
1395 $tcemainObj->insertDB($table, $id, $newVersion_placeholderFieldArray, FALSE);
1396
1397 // Move the new placeholder from temporary root-level to location:
1398 $tcemainObj->moveRecord_raw($table, $tcemainObj->substNEWwithIDs[$id], $destPid);
1399
1400 // Move the workspace-version of the original to be the version of the move-to-placeholder:
1401 // Setting placeholder state value for version (so it can know it is currently a new version...)
1402 $updateFields = array(
1403 't3ver_state' => 4
1404 );
1405 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid=' . intval($wsUid), $updateFields);
1406 }
1407
1408 // Check for the localizations of that element and move them as well
1409 $tcemainObj->moveL10nOverlayRecords($table, $uid, $destPid, $originalRecordDestinationPid);
1410 }
1411
1412 /**
1413 * Gets all possible child tables that are used on each parent table as field.
1414 *
1415 * @param string $parentTable Name of the parent table
1416 * @param array $possibleInlineChildren Collected possible inline children
1417 * (will be filled automatically during recursive calls)
1418 * @return array
1419 */
1420 protected function getPossibleInlineChildTablesOfParentTable($parentTable, array $possibleInlineChildren = array()) {
1421 t3lib_div::loadTCA($parentTable);
1422
1423 foreach ($GLOBALS['TCA'][$parentTable]['columns'] as $parentField => $parentFieldDefinition) {
1424 if (isset($parentFieldDefinition['config']['type'])) {
1425 $parentFieldConfiguration = $parentFieldDefinition['config'];
1426 if ($parentFieldConfiguration['type'] == 'inline' && isset($parentFieldConfiguration['foreign_table'])) {
1427 if (!in_array($parentFieldConfiguration['foreign_table'], $possibleInlineChildren)) {
1428 $possibleInlineChildren = $this->getPossibleInlineChildTablesOfParentTable(
1429 $parentFieldConfiguration['foreign_table'],
1430 array_merge($possibleInlineChildren, $parentFieldConfiguration['foreign_table'])
1431 );
1432 }
1433 }
1434 }
1435 }
1436
1437 return $possibleInlineChildren;
1438 }
1439
1440 /**
1441 * Gets an instance of the command map helper.
1442 *
1443 * @param t3lib_TCEmain $tceMain TCEmain object
1444 * @param array $commandMap The command map as submitted to t3lib_TCEmain
1445 * @return tx_version_tcemain_CommandMap
1446 */
1447 public function getCommandMap(t3lib_TCEmain $tceMain, array $commandMap) {
1448 return t3lib_div::makeInstance('tx_version_tcemain_CommandMap', $this, $tceMain, $commandMap);
1449 }
1450 }
1451
1452 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/version/class.tx_version_tcemain.php'])) {
1453 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/version/class.tx_version_tcemain.php']);
1454 }
1455 ?>