8e8e16fea33b0528308d3b71f7a3cd878bfaa4cb
[Packages/TYPO3.CMS.git] / typo3 / sysext / workspaces / Classes / Service / GridData.php
1 <?php
2 /***************************************************************
3 * Copyright notice
4 *
5 * (c) 2010-2011 Workspaces Team (http://forge.typo3.org/projects/show/typo3v4-workspaces)
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27
28 /**
29 * @author Workspaces Team (http://forge.typo3.org/projects/show/typo3v4-workspaces)
30 * @package Workspaces
31 * @subpackage Service
32 */
33 class Tx_Workspaces_Service_GridData {
34 protected $currentWorkspace = NULL;
35 protected $dataArray = array();
36 protected $sort = '';
37 protected $sortDir = '';
38 protected $workspacesCache = NULL;
39
40 /**
41 * Generates grid list array from given versions.
42 *
43 * @param array $versions All records uids etc. First key is table name, second key incremental integer. Records are associative arrays with uid, t3ver_oid and t3ver_swapmode fields. The pid of the online record is found as "livepid" the pid of the offline record is found in "wspid"
44 * @param object $parameter
45 * @param integer $currentWorkspace
46 * @return array
47 * @throws InvalidArgumentException
48 */
49 public function generateGridListFromVersions($versions, $parameter, $currentWorkspace) {
50
51 // Read the given parameters from grid. If the parameter is not set use default values.
52 $filterTxt = isset($parameter->filterTxt) ? $parameter->filterTxt : '';
53 $start = isset($parameter->start) ? intval($parameter->start) : 0;
54 $limit = isset($parameter->limit) ? intval($parameter->limit) : 30;
55 $this->sort = isset($parameter->sort) ? $parameter->sort : 't3ver_oid';
56 $this->sortDir = isset($parameter->dir) ? $parameter->dir : 'ASC';
57
58 if (is_int($currentWorkspace)) {
59 $this->currentWorkspace = $currentWorkspace;
60 } else {
61 throw new InvalidArgumentException('No such workspace defined');
62 }
63
64 $data = array();
65 $data['data'] = array();
66
67 $this->generateDataArray($versions, $filterTxt);
68
69 $data['total'] = count($this->dataArray);
70 $data['data'] = $this->getDataArray($start, $limit);
71
72 return $data;
73 }
74
75 /**
76 * Generates grid list array from given versions.
77 *
78 * @param array $versions
79 * @param string $filterTxt
80 * @return void
81 */
82 protected function generateDataArray(array $versions, $filterTxt) {
83 /** @var $stagesObj Tx_Workspaces_Service_Stages */
84 $stagesObj = t3lib_div::makeInstance('Tx_Workspaces_Service_Stages');
85
86 /** @var $workspacesObj Tx_Workspaces_Service_Workspaces */
87 $workspacesObj = t3lib_div::makeInstance('Tx_Workspaces_Service_Workspaces');
88 $availableWorkspaces = $workspacesObj->getAvailableWorkspaces();
89
90 $workspaceAccess = $GLOBALS['BE_USER']->checkWorkspace($GLOBALS['BE_USER']->workspace);
91 $swapStage = ($workspaceAccess['publish_access'] & 1) ? Tx_Workspaces_Service_Stages::STAGE_PUBLISH_ID : 0;
92 $swapAccess = $GLOBALS['BE_USER']->workspacePublishAccess($GLOBALS['BE_USER']->workspace) &&
93 $GLOBALS['BE_USER']->workspaceSwapAccess();
94
95 $this->initializeWorkspacesCachingFramework();
96
97 // check for dataArray in cache
98 if ($this->getDataArrayFromCache($versions, $filterTxt) == FALSE) {
99 $stagesObj = t3lib_div::makeInstance('Tx_Workspaces_Service_Stages');
100
101 foreach ($versions as $table => $records) {
102 $versionArray = array('table' => $table);
103 $isRecordTypeAllowedToModify = $GLOBALS['BE_USER']->check('tables_modify', $table);
104
105 foreach ($records as $record) {
106
107 $origRecord = t3lib_BEFunc::getRecord($table, $record['t3ver_oid']);
108 $versionRecord = t3lib_BEFunc::getRecord($table, $record['uid']);
109
110 if (isset($GLOBALS['TCA'][$table]['columns']['hidden'])) {
111 $recordState = $this->workspaceState($versionRecord['t3ver_state'], $origRecord['hidden'], $versionRecord['hidden']);
112 } else {
113 $recordState = $this->workspaceState($versionRecord['t3ver_state']);
114 }
115 $isDeletedPage = ($table == 'pages' && $recordState == 'deleted');
116 $viewUrl = Tx_Workspaces_Service_Workspaces::viewSingleRecord($table, $record['t3ver_oid'], $origRecord);
117
118 $pctChange = $this->calculateChangePercentage($table, $origRecord, $versionRecord);
119 $versionArray['uid'] = $record['uid'];
120 $versionArray['workspace'] = $versionRecord['t3ver_id'];
121 $versionArray['label_Workspace'] = htmlspecialchars(t3lib_befunc::getRecordTitle($table, $versionRecord));
122 $versionArray['label_Live'] = htmlspecialchars(t3lib_befunc::getRecordTitle($table, $origRecord));
123 $versionArray['label_Stage'] = htmlspecialchars($stagesObj->getStageTitle($versionRecord['t3ver_stage']));
124 $versionArray['change'] = $pctChange;
125 $versionArray['path_Live'] = htmlspecialchars(t3lib_BEfunc::getRecordPath($record['livepid'], '', 999));
126 $versionArray['path_Workspace'] = htmlspecialchars(t3lib_BEfunc::getRecordPath($record['wspid'], '', 999));
127 $versionArray['workspace_Title'] = htmlspecialchars(Tx_Workspaces_Service_Workspaces::getWorkspaceTitle($versionRecord['t3ver_wsid']));
128
129 $versionArray['workspace_Tstamp'] = $versionRecord['tstamp'];
130 $versionArray['workspace_Formated_Tstamp'] = t3lib_BEfunc::datetime($versionRecord['tstamp']);
131 $versionArray['t3ver_oid'] = $record['t3ver_oid'];
132 $versionArray['livepid'] = $record['livepid'];
133 $versionArray['stage'] = $versionRecord['t3ver_stage'];
134 $versionArray['icon_Live'] = t3lib_iconWorks::mapRecordTypeToSpriteIconClass($table, $origRecord);
135 $versionArray['icon_Workspace'] = t3lib_iconWorks::mapRecordTypeToSpriteIconClass($table, $versionRecord);
136
137 $versionArray['allowedAction_nextStage'] = $isRecordTypeAllowedToModify && $stagesObj->isNextStageAllowedForUser($versionRecord['t3ver_stage']);
138 $versionArray['allowedAction_prevStage'] = $isRecordTypeAllowedToModify && $stagesObj->isPrevStageAllowedForUser($versionRecord['t3ver_stage']);
139
140 if ($swapAccess && $swapStage != 0 && $versionRecord['t3ver_stage'] == $swapStage) {
141 $versionArray['allowedAction_swap'] = $isRecordTypeAllowedToModify && $stagesObj->isNextStageAllowedForUser($swapStage);
142 } elseif ($swapAccess && $swapStage == 0) {
143 $versionArray['allowedAction_swap'] = $isRecordTypeAllowedToModify;
144 } else {
145 $versionArray['allowedAction_swap'] = FALSE;
146 }
147 $versionArray['allowedAction_delete'] = $isRecordTypeAllowedToModify;
148 // preview and editing of a deleted page won't work ;)
149 $versionArray['allowedAction_view'] = !$isDeletedPage && $viewUrl;
150 $versionArray['allowedAction_edit'] = $isRecordTypeAllowedToModify && !$isDeletedPage;
151 $versionArray['allowedAction_editVersionedPage'] = $isRecordTypeAllowedToModify && !$isDeletedPage;
152
153 $versionArray['state_Workspace'] = $recordState;
154
155 if ($filterTxt == '' || $this->isFilterTextInVisibleColumns($filterTxt, $versionArray)) {
156 $this->dataArray[] = $versionArray;
157 }
158 }
159 }
160 $this->sortDataArray();
161
162 $this->setDataArrayIntoCache($versions, $filterTxt);
163 }
164 $this->sortDataArray();
165 }
166
167 /**
168 * Gets the data array by considering the page to be shown in the grid view.
169 *
170 * @param integer $start
171 * @param integer $limit
172 * @return array
173 */
174 protected function getDataArray($start, $limit) {
175 $dataArrayPart = array();
176 $end = $start + $limit < count($this->dataArray) ? $start + $limit : count($this->dataArray);
177
178 for ($i = $start; $i < $end; $i++) {
179 $dataArrayPart[] = $this->dataArray[$i];
180 }
181
182 return $dataArrayPart;
183 }
184
185
186 /**
187 * Initialize the workspace cache
188 *
189 * @return void
190 */
191 protected function initializeWorkspacesCachingFramework() {
192 $this->workspacesCache = $GLOBALS['typo3CacheManager']->getCache('workspaces_cache');
193 }
194
195
196 /**
197 * Put the generated dataArray into the workspace cache.
198 *
199 * @param array $versions All records uids etc. First key is table name, second key incremental integer. Records are associative arrays with uid, t3ver_oid and t3ver_swapmode fields. The pid of the online record is found as "livepid" the pid of the offline record is found in "wspid"
200 * @param string $filterTxt The given filter text from the grid.
201 */
202 protected function setDataArrayIntoCache (array $versions, $filterTxt) {
203 if (TYPO3_UseCachingFramework === TRUE) {
204 $hash = $this->calculateHash($versions, $filterTxt);
205 $this->workspacesCache->set($hash, $this->dataArray, array($this->currentWorkspace));
206 }
207 }
208
209
210 /**
211 * Checks if a cache entry is given for given versions and filter text and tries to load the data array from cache.
212 *
213 * @param array $versions All records uids etc. First key is table name, second key incremental integer. Records are associative arrays with uid, t3ver_oid and t3ver_swapmode fields. The pid of the online record is found as "livepid" the pid of the offline record is found in "wspid"
214 * @param string $filterTxt The given filter text from the grid.
215 * @return boolean TRUE if cache entry was successfully fetched from cache and content put to $this->dataArray
216 */
217 protected function getDataArrayFromCache (array $versions, $filterTxt) {
218 $cacheEntry = FALSE;
219
220 if (TYPO3_UseCachingFramework === TRUE) {
221 $hash = $this->calculateHash($versions, $filterTxt);
222
223 $content = $this->workspacesCache->get($hash);
224
225 if ($content !== FALSE) {
226 $this->dataArray = $content;
227 $cacheEntry = TRUE;
228 }
229 }
230
231 return $cacheEntry;
232 }
233
234 /**
235 * Calculate the hash value of the used workspace, the user id, the versions array, the filter text, the sorting attribute, the workspace selected in grid and the sorting direction.
236 *
237 * @param array $versions All records uids etc. First key is table name, second key incremental integer. Records are associative arrays with uid, t3ver_oid and t3ver_swapmode fields. The pid of the online record is found as "livepid" the pid of the offline record is found in "wspid"
238 * @param string $filterTxt The given filter text from the grid.
239 * @return string
240 */
241 protected function calculateHash (array $versions, $filterTxt) {
242 $hashArray = array(
243 $GLOBALS['BE_USER']->workspace,
244 $GLOBALS['BE_USER']->user['uid'],
245 $versions,
246 $filterTxt,
247 $this->sort,
248 $this->sortDir,
249 $this->currentWorkspace);
250 $hash = md5(serialize($hashArray));
251
252 return $hash;
253 }
254
255
256 /**
257 * Performs sorting on the data array accordant to the
258 * selected column in the grid view to be used for sorting.
259 *
260 * @return void
261 */
262 protected function sortDataArray() {
263 if (is_array($this->dataArray)) {
264 switch ($this->sort) {
265 case 'uid';
266 case 'change';
267 case 'workspace_Tstamp';
268 case 't3ver_oid';
269 case 'liveid';
270 case 'livepid':
271 usort($this->dataArray, array($this, 'intSort'));
272 break;
273 case 'label_Workspace';
274 case 'label_Live';
275 case 'label_Stage';
276 case 'workspace_Title';
277 case 'path_Live':
278 // case 'path_Workspace': This is the first sorting attribute
279 usort($this->dataArray, array($this, 'stringSort'));
280 break;
281 }
282 } else {
283 t3lib_div::sysLog('Try to sort "' . $this->sort . '" in "Tx_Workspaces_Service_GridData::sortDataArray" but $this->dataArray is empty! This might be the Bug #26422 which could not reproduced yet.', 3);
284 }
285 }
286
287 /**
288 * Implements individual sorting for columns based on integer comparison.
289 *
290 * @param array $a
291 * @param array $b
292 * @return integer
293 */
294 protected function intSort(array $a, array $b) {
295 // Als erstes nach dem Pfad sortieren
296 $path_cmp = strcasecmp($a['path_Workspace'], $b['path_Workspace']);
297
298 if ($path_cmp < 0) {
299 return $path_cmp;
300 } elseif ($path_cmp == 0) {
301 if ($a[$this->sort] == $b[$this->sort]) {
302 return 0;
303 }
304 if ($this->sortDir == 'ASC') {
305 return ($a[$this->sort] < $b[$this->sort]) ? -1 : 1;
306 } elseif ($this->sortDir == 'DESC') {
307 return ($a[$this->sort] > $b[$this->sort]) ? -1 : 1;
308 }
309 } elseif ($path_cmp > 0) {
310 return $path_cmp;
311 }
312 return 0; //ToDo: Throw Exception
313 }
314
315 /**
316 * Implements individual sorting for columns based on string comparison.
317 *
318 * @param $a
319 * @param $b
320 * @return int
321 */
322 protected function stringSort($a, $b) {
323 $path_cmp = strcasecmp($a['path_Workspace'], $b['path_Workspace']);
324
325 if ($path_cmp < 0) {
326 return $path_cmp;
327 } elseif ($path_cmp == 0) {
328 if ($a[$this->sort] == $b[$this->sort]) {
329 return 0;
330 }
331 if ($this->sortDir == 'ASC') {
332 return (strcasecmp($a[$this->sort], $b[$this->sort]));
333 } elseif ($this->sortDir == 'DESC') {
334 return (strcasecmp($a[$this->sort], $b[$this->sort]) * (-1));
335 }
336 } elseif ($path_cmp > 0) {
337 return $path_cmp;
338 }
339 return 0; //ToDo: Throw Exception
340 }
341
342 /**
343 * Determines whether the text used to filter the results is part of
344 * a column that is visible in the grid view.
345 *
346 * @param string $filterText
347 * @param array $versionArray
348 * @return boolean
349 */
350 protected function isFilterTextInVisibleColumns($filterText, array $versionArray) {
351 if (is_array($GLOBALS['BE_USER']->uc['moduleData']['Workspaces'][$GLOBALS['BE_USER']->workspace]['columns'])) {
352 foreach ($GLOBALS['BE_USER']->uc['moduleData']['Workspaces'][$GLOBALS['BE_USER']->workspace]['columns'] as $column => $value) {
353 if (isset($value['hidden']) && isset($column) && isset($versionArray[$column])) {
354 if ($value['hidden'] == 0) {
355 switch ($column) {
356 case 'workspace_Tstamp':
357 if (stripos($versionArray['workspace_Formated_Tstamp'], $filterText) !== FALSE) {
358 return TRUE;
359 }
360 break;
361 case 'change':
362 if (stripos(strval($versionArray[$column]), str_replace('%', '', $filterText)) !== FALSE) {
363 return TRUE;
364 }
365 break;
366 default:
367 if (stripos(strval($versionArray[$column]), $filterText) !== FALSE) {
368 return TRUE;
369 }
370 }
371 }
372 }
373 }
374 }
375 return FALSE;
376 }
377
378 /**
379 * Calculates the percentage of changes between two records.
380 *
381 * @param string $table
382 * @param array $diffRecordOne
383 * @param array $diffRecordTwo
384 * @return integer
385 */
386 public function calculateChangePercentage($table, array $diffRecordOne, array $diffRecordTwo) {
387
388 // Initialize:
389 $changePercentage = 0;
390 $changePercentageArray = array();
391
392 // Check that records are arrays:
393 if (is_array($diffRecordOne) && is_array($diffRecordTwo)) {
394
395 // Load full table description
396 t3lib_div::loadTCA($table);
397
398 $similarityPercentage = 0;
399
400 // Traversing the first record and process all fields which are editable:
401 foreach ($diffRecordOne as $fieldName => $fieldValue) {
402 if ($GLOBALS['TCA'][$table]['columns'][$fieldName] && $GLOBALS['TCA'][$table]['columns'][$fieldName]['config']['type'] != 'passthrough' && !t3lib_div::inList('t3ver_label', $fieldName)) {
403
404 if (strcmp(trim($diffRecordOne[$fieldName]), trim($diffRecordTwo[$fieldName]))
405 && $GLOBALS['TCA'][$table]['columns'][$fieldName]['config']['type'] == 'group'
406 && $GLOBALS['TCA'][$table]['columns'][$fieldName]['config']['internal_type'] == 'file'
407 ) {
408
409 // Initialize:
410 $uploadFolder = $GLOBALS['TCA'][$table]['columns'][$fieldName]['config']['uploadfolder'];
411 $files1 = array_flip(t3lib_div::trimExplode(',', $diffRecordOne[$fieldName], 1));
412 $files2 = array_flip(t3lib_div::trimExplode(',', $diffRecordTwo[$fieldName], 1));
413
414 // Traverse filenames and read their md5 sum:
415 foreach ($files1 as $filename => $tmp) {
416 $files1[$filename] = @is_file(PATH_site . $uploadFolder . '/' . $filename) ? md5(t3lib_div::getUrl(PATH_site . $uploadFolder . '/' . $filename)) : $filename;
417 }
418 foreach ($files2 as $filename => $tmp) {
419 $files2[$filename] = @is_file(PATH_site . $uploadFolder . '/' . $filename) ? md5(t3lib_div::getUrl(PATH_site . $uploadFolder . '/' . $filename)) : $filename;
420 }
421
422 // Implode MD5 sums and set flag:
423 $diffRecordOne[$fieldName] = implode(' ', $files1);
424 $diffRecordTwo[$fieldName] = implode(' ', $files2);
425 }
426
427 // If there is a change of value:
428 if (strcmp(trim($diffRecordOne[$fieldName]), trim($diffRecordTwo[$fieldName]))) {
429 // Get the best visual presentation of the value to calculate differences:
430 $val1 = t3lib_BEfunc::getProcessedValue($table, $fieldName, $diffRecordOne[$fieldName], 0, 1);
431 $val2 = t3lib_BEfunc::getProcessedValue($table, $fieldName, $diffRecordTwo[$fieldName], 0, 1);
432
433 similar_text($val1, $val2, $similarityPercentage);
434 $changePercentageArray[] = $similarityPercentage > 0 ? abs($similarityPercentage - 100) : 0;
435 }
436 }
437 }
438
439 // Calculate final change percentage:
440 if (is_array($changePercentageArray)) {
441 $sumPctChange = 0;
442 foreach ($changePercentageArray as $singlePctChange) {
443 $sumPctChange += $singlePctChange;
444 }
445 count($changePercentageArray) > 0 ? $changePercentage = round($sumPctChange / count($changePercentageArray)) : $changePercentage = 0;
446 }
447
448 }
449 return $changePercentage;
450 }
451
452 /**
453 * Gets the state of a given state value.
454 *
455 * @param integer stateId of offline record
456 * @param boolean hidden flag of online record
457 * @param boolean hidden flag of offline record
458 * @return string
459 */
460 protected function workspaceState($stateId, $hiddenOnline = FALSE, $hiddenOffline = FALSE) {
461 switch ($stateId) {
462 case -1:
463 $state = 'new';
464 break;
465 case 1:
466 case 2:
467 $state = 'deleted';
468 break;
469 case 4:
470 $state = 'moved';
471 break;
472 default:
473 $state = 'modified';
474 }
475
476 if ($hiddenOnline == 0 && $hiddenOffline == 1) {
477 $state = 'hidden';
478 } elseif ($hiddenOnline == 1 && $hiddenOffline == 0) {
479 $state = 'unhidden';
480 }
481
482 return $state;
483 }
484 }
485
486
487 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/workspaces/Classes/Service/GridData.php'])) {
488 include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['ext/workspaces/Classes/Service/GridData.php']);
489 }
490 ?>