[TASK] update the comments regarding ajax.php
[Packages/TYPO3.CMS.git] / typo3 / sysext / belog / Classes / Controller / AbstractController.php
1 <?php
2 namespace TYPO3\CMS\Belog\Controller;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Page\PageRenderer;
18
19 /**
20 * Abstract class to show log entries from sys_log
21 */
22 abstract class AbstractController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {
23
24 /**
25 * @var int
26 */
27 const TIMEFRAME_THISWEEK = 0;
28
29 /**
30 * @var int
31 */
32 const TIMEFRAME_LASTWEEK = 1;
33
34 /**
35 * @var int
36 */
37 const TIMEFRAME_LASTSEVENDAYS = 2;
38
39 /**
40 * @var int
41 */
42 const TIMEFRAME_THISMONTH = 10;
43
44 /**
45 * @var int
46 */
47 const TIMEFRAME_LASTMONTH = 11;
48
49 /**
50 * @var int
51 */
52 const TIMEFRAME_LAST31DAYS = 12;
53
54 /**
55 * @var int
56 */
57 const TIMEFRAME_CUSTOM = 30;
58
59 /**
60 * Whether plugin is running in page context (sub module of Web > Info)
61 *
62 * @var bool
63 */
64 protected $isInPageContext = FALSE;
65
66 /**
67 * Page ID in page context
68 *
69 * @var int
70 */
71 protected $pageId = 0;
72
73 /**
74 * @var \TYPO3\CMS\Belog\Domain\Repository\LogEntryRepository
75 */
76 protected $logEntryRepository = NULL;
77
78 /**
79 * @var PageRenderer
80 */
81 protected $pageRenderer;
82
83 /**
84 * @param \TYPO3\CMS\Belog\Domain\Repository\LogEntryRepository $logEntryRepository
85 */
86 public function injectLogEntryRepository(\TYPO3\CMS\Belog\Domain\Repository\LogEntryRepository $logEntryRepository) {
87 $this->logEntryRepository = $logEntryRepository;
88 }
89
90 /**
91 * init all actions
92 * @return void
93 */
94 public function initializeAction() {
95 $this->pageRenderer = $this->objectManager->get(PageRenderer::class);
96 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DateTimePicker');
97 }
98
99 /**
100 * Initialize index action
101 *
102 * @return void
103 * @throws \RuntimeException
104 */
105 public function initializeIndexAction() {
106 // @TODO: Extbase backend modules rely on frontend TypoScript for view, persistence
107 // and settings. Thus, we need a TypoScript root template, that then loads the
108 // ext_typoscript_setup.txt file of this module. This is nasty, but can not be
109 // circumvented until there is a better solution in extbase.
110 // For now we throw an exception if no settings are detected.
111 if (empty($this->settings)) {
112 throw new \RuntimeException(
113 'No settings detected. This usually happens if there is no frontend TypoScript template with root flag set. Please create one.',
114 1333650506
115 );
116 }
117 if (!isset($this->settings['dateFormat'])) {
118 $this->settings['dateFormat'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ? 'm-d-Y' : 'd-m-Y';
119 }
120 if (!isset($this->settings['timeFormat'])) {
121 $this->settings['timeFormat'] = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
122 }
123 }
124
125 /**
126 * Show general information and the installed modules
127 *
128 * @param \TYPO3\CMS\Belog\Domain\Model\Constraint $constraint
129 * @return void
130 */
131 public function indexAction(\TYPO3\CMS\Belog\Domain\Model\Constraint $constraint = NULL) {
132 // Constraint object handling:
133 // If there is none from GET, try to get it from BE user data, else create new
134 if ($constraint === NULL) {
135 $constraint = $this->getConstraintFromBeUserData();
136 if ($constraint === NULL) {
137 $constraint = $this->objectManager->get(\TYPO3\CMS\Belog\Domain\Model\Constraint::class);
138 }
139 } else {
140 $this->persistConstraintInBeUserData($constraint);
141 }
142 $constraint->setIsInPageContext($this->isInPageContext);
143 $constraint->setPageId($this->pageId);
144 $this->setStartAndEndTimeFromTimeSelector($constraint);
145 $this->forceWorkspaceSelectionIfInWorkspace($constraint);
146 $logEntries = $this->logEntryRepository->findByConstraint($constraint);
147 $groupedLogEntries = $this->groupLogEntriesByPageAndDay($logEntries, $constraint->getGroupByPage());
148 $this->view->assign('groupedLogEntries', $groupedLogEntries)->assign('constraint', $constraint)->assign('userGroups', $this->createUserAndGroupListForSelectOptions())->assign('workspaces', $this->createWorkspaceListForSelectOptions())->assign('pageDepths', $this->createPageDepthOptions());
149 }
150
151 /**
152 * Get module states (the constraint object) from user data
153 *
154 * @return \TYPO3\CMS\Belog\Domain\Model\Constraint|NULL
155 */
156 protected function getConstraintFromBeUserData() {
157 $serializedConstraint = $GLOBALS['BE_USER']->getModuleData(get_class($this));
158 if (!is_string($serializedConstraint) || empty($serializedConstraint)) {
159 return NULL;
160 }
161 return @unserialize($serializedConstraint);
162 }
163
164 /**
165 * Save current constraint object in be user settings (uC)
166 *
167 * @param \TYPO3\CMS\Belog\Domain\Model\Constraint $constraint
168 * @return void
169 */
170 protected function persistConstraintInBeUserData(\TYPO3\CMS\Belog\Domain\Model\Constraint $constraint) {
171 $GLOBALS['BE_USER']->pushModuleData(get_class($this), serialize($constraint));
172 }
173
174 /**
175 * Create a sorted array for day and page view from
176 * the query result of the sys log repository.
177 *
178 * If group by page is FALSE, pid is always -1 (will render a flat list),
179 * otherwise the output is splitted by pages.
180 * '12345' is a sub array to split entries by day, number is first second of day
181 *
182 * [pid][dayTimestamp][items]
183 *
184 * @param \TYPO3\CMS\Extbase\Persistence\QueryResultInterface<\TYPO3\CMS\Belog\Domain\Model\LogEntry> $logEntries
185 * @param bool $groupByPage Whether or not log entries should be grouped by page
186 * @return array
187 */
188 protected function groupLogEntriesByPageAndDay(\TYPO3\CMS\Extbase\Persistence\QueryResultInterface $logEntries, $groupByPage = FALSE) {
189 $targetStructure = array();
190 /** @var $entry \TYPO3\CMS\Belog\Domain\Model\LogEntry */
191 foreach ($logEntries as $entry) {
192 // Create page split list or flat list
193 if ($groupByPage) {
194 $pid = $entry->getEventPid();
195 } else {
196 $pid = -1;
197 }
198 // Create array if it is not defined yet
199 if (!is_array($targetStructure[$pid])) {
200 $targetStructure[$pid] = array();
201 }
202 // Get day timestamp of log entry and create sub array if needed
203 $timestampDay = strtotime(strftime('%d.%m.%Y', $entry->getTstamp()));
204 if (!is_array($targetStructure[$pid][$timestampDay])) {
205 $targetStructure[$pid][$timestampDay] = array();
206 }
207 // Add row
208 $targetStructure[$pid][$timestampDay][] = $entry;
209 }
210 ksort($targetStructure);
211 return $targetStructure;
212 }
213
214 /**
215 * Create options for the user / group drop down.
216 * This is not moved to a repository by intention to not mix up this 'meta' data
217 * with real repository work
218 *
219 * @return array Key is the option name, value its label
220 */
221 protected function createUserAndGroupListForSelectOptions() {
222 $userGroupArray = array();
223 // Two meta entries: 'all' and 'self'
224 $userGroupArray[0] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('allUsers', 'Belog');
225 $userGroupArray[-1] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('self', 'Belog');
226 // List of groups, key is gr-'uid'
227 $groups = \TYPO3\CMS\Backend\Utility\BackendUtility::getGroupNames();
228 foreach ($groups as $group) {
229 $userGroupArray['gr-' . $group['uid']] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('group', 'Belog') . ' ' . $group['title'];
230 }
231 // List of users, key is us-'uid'
232 $users = \TYPO3\CMS\Backend\Utility\BackendUtility::getUserNames();
233 foreach ($users as $user) {
234 $userGroupArray['us-' . $user['uid']] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('user', 'Belog') . ' ' . $user['username'];
235 }
236 return $userGroupArray;
237 }
238
239 /**
240 * Create options for the workspace selector
241 *
242 * @return array Key is uid of workspace, value its label
243 */
244 protected function createWorkspaceListForSelectOptions() {
245 if (!\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded('workspaces')) {
246 return array();
247 }
248 $workspaceArray = array();
249 // Two meta entries: 'all' and 'live'
250 $workspaceArray[-99] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('any', 'Belog');
251 $workspaceArray[0] = \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('live', 'Belog');
252 $workspaces = $this->objectManager->get(\TYPO3\CMS\Belog\Domain\Repository\WorkspaceRepository::class)->findAll();
253 /** @var $workspace \TYPO3\CMS\Belog\Domain\Model\Workspace */
254 foreach ($workspaces as $workspace) {
255 $workspaceArray[$workspace->getUid()] = $workspace->getUid() . ': ' . $workspace->getTitle();
256 }
257 return $workspaceArray;
258 }
259
260 /**
261 * If the user is in a workspace different than LIVE,
262 * we force to show only log entries from the selected workspace,
263 * and the workspace selector is not shown.
264 *
265 * @param \TYPO3\CMS\Belog\Domain\Model\Constraint $constraint
266 * @return void
267 */
268 protected function forceWorkspaceSelectionIfInWorkspace(\TYPO3\CMS\Belog\Domain\Model\Constraint $constraint) {
269 if ($GLOBALS['BE_USER']->workspace !== 0) {
270 $constraint->setWorkspaceUid($GLOBALS['BE_USER']->workspace);
271 $this->view->assign('showWorkspaceSelector', FALSE);
272 } else {
273 $this->view->assign('showWorkspaceSelector', TRUE);
274 }
275 }
276
277 /**
278 * Create options for the 'depth of page levels' selector.
279 * This is shown if the module is displayed in page -> info
280 *
281 * @return array Key is depth identifier (1 = One level), value the localized select option label
282 */
283 protected function createPageDepthOptions() {
284 $options = array(
285 0 => \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('LLL:EXT:lang/locallang_core.xlf:labels.depth_0', 'lang'),
286 1 => \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('LLL:EXT:lang/locallang_core.xlf:labels.depth_1', 'lang'),
287 2 => \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('LLL:EXT:lang/locallang_core.xlf:labels.depth_2', 'lang'),
288 3 => \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('LLL:EXT:lang/locallang_core.xlf:labels.depth_3', 'lang'),
289 4 => \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('LLL:EXT:lang/locallang_core.xlf:labels.depth_4', 'lang'),
290 999 => \TYPO3\CMS\Extbase\Utility\LocalizationUtility::translate('LLL:EXT:lang/locallang_core.xlf:labels.depth_infi', 'lang')
291 );
292 return $options;
293 }
294
295 /**
296 * Calculate the start- and end timestamp from the different time selector options
297 *
298 * @param \TYPO3\CMS\Belog\Domain\Model\Constraint $constraint
299 * @return void
300 */
301 protected function setStartAndEndTimeFromTimeSelector(\TYPO3\CMS\Belog\Domain\Model\Constraint $constraint) {
302 $startTime = 0;
303 $endTime = $GLOBALS['EXEC_TIME'];
304 // @TODO: Refactor this construct
305 switch ($constraint->getTimeFrame()) {
306 case self::TIMEFRAME_THISWEEK:
307 // This week
308 $week = (date('w') ?: 7) - 1;
309 $startTime = mktime(0, 0, 0) - $week * 3600 * 24;
310 break;
311 case self::TIMEFRAME_LASTWEEK:
312 // Last week
313 $week = (date('w') ?: 7) - 1;
314 $startTime = mktime(0, 0, 0) - ($week + 7) * 3600 * 24;
315 $endTime = mktime(0, 0, 0) - $week * 3600 * 24;
316 break;
317 case self::TIMEFRAME_LASTSEVENDAYS:
318 // Last 7 days
319 $startTime = mktime(0, 0, 0) - 7 * 3600 * 24;
320 break;
321 case self::TIMEFRAME_THISMONTH:
322 // This month
323 $startTime = mktime(0, 0, 0, date('m'), 1);
324 break;
325 case self::TIMEFRAME_LASTMONTH:
326 // Last month
327 $startTime = mktime(0, 0, 0, date('m') - 1, 1);
328 $endTime = mktime(0, 0, 0, date('m'), 1);
329 break;
330 case self::TIMEFRAME_LAST31DAYS:
331 // Last 31 days
332 $startTime = mktime(0, 0, 0) - 31 * 3600 * 24;
333 break;
334 case self::TIMEFRAME_CUSTOM:
335 $startTime = $constraint->getStartTimestamp();
336 if ($constraint->getEndTimestamp() > $constraint->getStartTimestamp()) {
337 $endTime = $constraint->getEndTimestamp();
338 } else {
339 $endTime = $GLOBALS['EXEC_TIME'];
340 }
341 break;
342 default:
343 }
344 $constraint->setStartTimestamp($startTime);
345 $constraint->setEndTimestamp($endTime);
346 }
347
348 }