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