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