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