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