03abf8dc629775d0e2a622522f2be1bb0e25b833
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Plugin / AbstractPlugin.php
1 <?php
2 namespace TYPO3\CMS\Frontend\Plugin;
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 Doctrine\DBAL\Driver\Statement;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Core\Database\Connection;
20 use TYPO3\CMS\Core\Database\ConnectionPool;
21 use TYPO3\CMS\Core\Database\Query\QueryHelper;
22 use TYPO3\CMS\Core\Database\Query\Restriction\FrontendRestrictionContainer;
23 use TYPO3\CMS\Core\Localization\Locales;
24 use TYPO3\CMS\Core\Localization\LocalizationFactory;
25 use TYPO3\CMS\Core\Service\MarkerBasedTemplateService;
26 use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
27 use TYPO3\CMS\Core\Utility\ArrayUtility;
28 use TYPO3\CMS\Core\Utility\GeneralUtility;
29 use TYPO3\CMS\Core\Utility\HttpUtility;
30 use TYPO3\CMS\Core\Utility\MathUtility;
31 use TYPO3\CMS\Core\Utility\PathUtility;
32 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
33 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
34
35 /**
36 * Base class for frontend plugins
37 * Most legacy frontend plugins are extension classes of this one.
38 * This class contains functions which assists these plugins in creating lists, searching, displaying menus, page-browsing (next/previous/1/2/3) and handling links.
39 * Functions are all prefixed "pi_" which is reserved for this class. Those functions can of course be overridden in the extension classes (that is the point...)
40 */
41 class AbstractPlugin
42 {
43 /**
44 * The backReference to the mother cObj object set at call time
45 *
46 * @var ContentObjectRenderer
47 */
48 public $cObj;
49
50 /**
51 * Should be same as classname of the plugin, used for CSS classes, variables
52 *
53 * @var string
54 */
55 public $prefixId;
56
57 /**
58 * Path to the plugin class script relative to extension directory, eg. 'pi1/class.tx_newfaq_pi1.php'
59 *
60 * @var string
61 */
62 public $scriptRelPath;
63
64 /**
65 * Extension key.
66 *
67 * @var string
68 */
69 public $extKey;
70
71 /**
72 * This is the incoming array by name $this->prefixId merged between POST and GET, POST taking precedence.
73 * Eg. if the class name is 'tx_myext'
74 * then the content of this array will be whatever comes into &tx_myext[...]=...
75 *
76 * @var array
77 */
78 public $piVars = [
79 'pointer' => '',
80 // Used as a pointer for lists
81 'mode' => '',
82 // List mode
83 'sword' => '',
84 // Search word
85 'sort' => ''
86 ];
87
88 /**
89 * Local pointer variabe array.
90 * Holds pointer information for the MVC like approach Kasper
91 * initially proposed
92 *
93 * @var array
94 */
95 public $internal = ['res_count' => 0, 'results_at_a_time' => 20, 'maxPages' => 10, 'currentRow' => [], 'currentTable' => ''];
96
97 /**
98 * Local Language content
99 *
100 * @var array
101 */
102 public $LOCAL_LANG = [];
103
104 /**
105 * Contains those LL keys, which have been set to (empty) in TypoScript.
106 * This is necessary, as we cannot distinguish between a nonexisting
107 * translation and a label that has been cleared by TS.
108 * In both cases ['key'][0]['target'] is "".
109 *
110 * @var array
111 */
112 protected $LOCAL_LANG_UNSET = [];
113
114 /**
115 * Flag that tells if the locallang file has been fetch (or tried to
116 * be fetched) already.
117 *
118 * @var bool
119 */
120 public $LOCAL_LANG_loaded = false;
121
122 /**
123 * Pointer to the language to use.
124 *
125 * @var string
126 */
127 public $LLkey = 'default';
128
129 /**
130 * Pointer to alternative fall-back language to use.
131 *
132 * @var string
133 */
134 public $altLLkey = '';
135
136 /**
137 * You can set this during development to some value that makes it
138 * easy for you to spot all labels that ARe delivered by the getLL function.
139 *
140 * @var string
141 */
142 public $LLtestPrefix = '';
143
144 /**
145 * Save as LLtestPrefix, but additional prefix for the alternative value
146 * in getLL() function calls
147 *
148 * @var string
149 */
150 public $LLtestPrefixAlt = '';
151
152 /**
153 * @var string
154 */
155 public $pi_isOnlyFields = 'mode,pointer';
156
157 /**
158 * @var int
159 */
160 public $pi_alwaysPrev = 0;
161
162 /**
163 * @var int
164 */
165 public $pi_lowerThan = 5;
166
167 /**
168 * @var string
169 */
170 public $pi_moreParams = '';
171
172 /**
173 * @var string
174 */
175 public $pi_listFields = '*';
176
177 /**
178 * @var array
179 */
180 public $pi_autoCacheFields = [];
181
182 /**
183 * @var bool
184 */
185 public $pi_autoCacheEn = false;
186
187 /**
188 * If set, then links are
189 * 1) not using cHash and
190 * 2) not allowing pages to be cached. (Set this for all USER_INT plugins!)
191 *
192 * @var bool
193 */
194 public $pi_USER_INT_obj = false;
195
196 /**
197 * If set, then caching is disabled if piVars are incoming while
198 * no cHash was set (Set this for all USER plugins!)
199 *
200 * @var bool
201 */
202 public $pi_checkCHash = false;
203
204 /**
205 * Should normally be set in the main function with the TypoScript content passed to the method.
206 *
207 * $conf[LOCAL_LANG][_key_] is reserved for Local Language overrides.
208 * $conf[userFunc] reserved for setting up the USER / USER_INT object. See TSref
209 *
210 * @var array
211 */
212 public $conf = [];
213
214 /**
215 * internal, don't mess with...
216 *
217 * @var ContentObjectRenderer
218 */
219 public $pi_EPtemp_cObj;
220
221 /**
222 * @var int
223 */
224 public $pi_tmpPageId = 0;
225
226 /**
227 * Property for accessing TypoScriptFrontendController centrally
228 *
229 * @var TypoScriptFrontendController
230 */
231 protected $frontendController;
232
233 /**
234 * @var MarkerBasedTemplateService
235 */
236 protected $templateService;
237
238 /**
239 * Class Constructor (true constructor)
240 * Initializes $this->piVars if $this->prefixId is set to any value
241 * Will also set $this->LLkey based on the config.language setting.
242 *
243 * @param null $_ unused,
244 * @param TypoScriptFrontendController $frontendController
245 */
246 public function __construct($_ = null, TypoScriptFrontendController $frontendController = null)
247 {
248 $this->frontendController = $frontendController ?: $GLOBALS['TSFE'];
249 $this->templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
250 // Setting piVars:
251 if ($this->prefixId) {
252 $this->piVars = GeneralUtility::_GPmerged($this->prefixId);
253 // cHash mode check
254 // IMPORTANT FOR CACHED PLUGINS (USER cObject): As soon as you generate cached plugin output which
255 // depends on parameters (eg. seeing the details of a news item) you MUST check if a cHash value is set.
256 // Background: The function call will check if a cHash parameter was sent with the URL because only if
257 // it was the page may be cached. If no cHash was found the function will simply disable caching to
258 // avoid unpredictable caching behaviour. In any case your plugin can generate the expected output and
259 // the only risk is that the content may not be cached. A missing cHash value is considered a mistake
260 // in the URL resulting from either URL manipulation, "realurl" "grayzones" etc. The problem is rare
261 // (more frequent with "realurl") but when it occurs it is very puzzling!
262 if ($this->pi_checkCHash && !empty($this->piVars)) {
263 $this->frontendController->reqCHash();
264 }
265 }
266 $siteLanguage = $this->getCurrentSiteLanguage();
267 if ($siteLanguage) {
268 $this->LLkey = $siteLanguage->getTypo3Language();
269 } elseif (!empty($this->frontendController->config['config']['language'])) {
270 $this->LLkey = $this->frontendController->config['config']['language'];
271 }
272
273 if (empty($this->frontendController->config['config']['language_alt'])) {
274 /** @var Locales $locales */
275 $locales = GeneralUtility::makeInstance(Locales::class);
276 if (in_array($this->LLkey, $locales->getLocales())) {
277 $this->altLLkey = '';
278 foreach ($locales->getLocaleDependencies($this->LLkey) as $language) {
279 $this->altLLkey .= $language . ',';
280 }
281 $this->altLLkey = rtrim($this->altLLkey, ',');
282 }
283 } else {
284 $this->altLLkey = $this->frontendController->config['config']['language_alt'];
285 }
286 }
287
288 /**
289 * Recursively looks for stdWrap and executes it
290 *
291 * @param array $conf Current section of configuration to work on
292 * @param int $level Current level being processed (currently just for tracking; no limit enforced)
293 * @return array Current section of configuration after stdWrap applied
294 */
295 protected function applyStdWrapRecursive(array $conf, $level = 0)
296 {
297 foreach ($conf as $key => $confNextLevel) {
298 if (strpos($key, '.') !== false) {
299 $key = substr($key, 0, -1);
300
301 // descend into all non-stdWrap-subelements first
302 foreach ($confNextLevel as $subKey => $subConfNextLevel) {
303 if (is_array($subConfNextLevel) && strpos($subKey, '.') !== false && $subKey !== 'stdWrap.') {
304 $conf[$key . '.'] = $this->applyStdWrapRecursive($confNextLevel, $level + 1);
305 }
306 }
307
308 // now for stdWrap
309 foreach ($confNextLevel as $subKey => $subConfNextLevel) {
310 if (is_array($subConfNextLevel) && $subKey === 'stdWrap.') {
311 $conf[$key] = $this->cObj->stdWrap($conf[$key] ?? '', $conf[$key . '.']['stdWrap.'] ?? []);
312 unset($conf[$key . '.']['stdWrap.']);
313 if (empty($conf[$key . '.'])) {
314 unset($conf[$key . '.']);
315 }
316 }
317 }
318 }
319 }
320 return $conf;
321 }
322
323 /**
324 * If internal TypoScript property "_DEFAULT_PI_VARS." is set then it will merge the current $this->piVars array onto these default values.
325 */
326 public function pi_setPiVarDefaults()
327 {
328 if (isset($this->conf['_DEFAULT_PI_VARS.']) && is_array($this->conf['_DEFAULT_PI_VARS.'])) {
329 $this->conf['_DEFAULT_PI_VARS.'] = $this->applyStdWrapRecursive($this->conf['_DEFAULT_PI_VARS.']);
330 $tmp = $this->conf['_DEFAULT_PI_VARS.'];
331 ArrayUtility::mergeRecursiveWithOverrule($tmp, is_array($this->piVars) ? $this->piVars : []);
332 $this->piVars = $tmp;
333 }
334 }
335
336 /***************************
337 *
338 * Link functions
339 *
340 **************************/
341 /**
342 * Get URL to some page.
343 * Returns the URL to page $id with $target and an array of additional url-parameters, $urlParameters
344 * Simple example: $this->pi_getPageLink(123) to get the URL for page-id 123.
345 *
346 * The function basically calls $this->cObj->getTypoLink_URL()
347 *
348 * @param int $id Page id
349 * @param string $target Target value to use. Affects the &type-value of the URL, defaults to current.
350 * @param array|string $urlParameters As an array key/value pairs represent URL parameters to set. Values NOT URL-encoded yet, keys should be URL-encoded if needed. As a string the parameter is expected to be URL-encoded already.
351 * @return string The resulting URL
352 * @see pi_linkToPage()
353 * @see ContentObjectRenderer->getTypoLink()
354 */
355 public function pi_getPageLink($id, $target = '', $urlParameters = [])
356 {
357 return $this->cObj->getTypoLink_URL($id, $urlParameters, $target);
358 }
359
360 /**
361 * Link a string to some page.
362 * Like pi_getPageLink() but takes a string as first parameter which will in turn be wrapped with the URL including target attribute
363 * Simple example: $this->pi_linkToPage('My link', 123) to get something like <a href="index.php?id=123&type=1">My link</a>
364 *
365 * @param string $str The content string to wrap in <a> tags
366 * @param int $id Page id
367 * @param string $target Target value to use. Affects the &type-value of the URL, defaults to current.
368 * @param array|string $urlParameters As an array key/value pairs represent URL parameters to set. Values NOT URL-encoded yet, keys should be URL-encoded if needed. As a string the parameter is expected to be URL-encoded already.
369 * @return string The input string wrapped in <a> tags with the URL and target set.
370 * @see pi_getPageLink(), ContentObjectRenderer::getTypoLink()
371 */
372 public function pi_linkToPage($str, $id, $target = '', $urlParameters = [])
373 {
374 return $this->cObj->getTypoLink($str, $id, $urlParameters, $target);
375 }
376
377 /**
378 * Link string to the current page.
379 * Returns the $str wrapped in <a>-tags with a link to the CURRENT page, but with $urlParameters set as extra parameters for the page.
380 *
381 * @param string $str The content string to wrap in <a> tags
382 * @param array $urlParameters Array with URL parameters as key/value pairs. They will be "imploded" and added to the list of parameters defined in the plugins TypoScript property "parent.addParams" plus $this->pi_moreParams.
383 * @param bool $cache If $cache is set (0/1), the page is asked to be cached by a &cHash value (unless the current plugin using this class is a USER_INT). Otherwise the no_cache-parameter will be a part of the link.
384 * @param int $altPageId Alternative page ID for the link. (By default this function links to the SAME page!)
385 * @return string The input string wrapped in <a> tags
386 * @see pi_linkTP_keepPIvars(), ContentObjectRenderer::typoLink()
387 */
388 public function pi_linkTP($str, $urlParameters = [], $cache = false, $altPageId = 0)
389 {
390 $conf = [];
391 $conf['no_cache'] = $this->pi_USER_INT_obj ? 0 : !$cache;
392 $conf['parameter'] = $altPageId ? $altPageId : ($this->pi_tmpPageId ? $this->pi_tmpPageId : $this->frontendController->id);
393 $conf['additionalParams'] = $this->conf['parent.']['addParams'] . HttpUtility::buildQueryString($urlParameters, '&', true) . $this->pi_moreParams;
394 return $this->cObj->typoLink($str, $conf);
395 }
396
397 /**
398 * Link a string to the current page while keeping currently set values in piVars.
399 * Like pi_linkTP, but $urlParameters is by default set to $this->piVars with $overrulePIvars overlaid.
400 * This means any current entries from this->piVars are passed on (except the key "DATA" which will be unset before!) and entries in $overrulePIvars will OVERRULE the current in the link.
401 *
402 * @param string $str The content string to wrap in <a> tags
403 * @param array $overrulePIvars Array of values to override in the current piVars. Contrary to pi_linkTP the keys in this array must correspond to the real piVars array and therefore NOT be prefixed with the $this->prefixId string. Further, if a value is a blank string it means the piVar key will not be a part of the link (unset)
404 * @param bool $cache If $cache is set, the page is asked to be cached by a &cHash value (unless the current plugin using this class is a USER_INT). Otherwise the no_cache-parameter will be a part of the link.
405 * @param bool $clearAnyway If set, then the current values of piVars will NOT be preserved anyways... Practical if you want an easy way to set piVars without having to worry about the prefix, "tx_xxxxx[]
406 * @param int $altPageId Alternative page ID for the link. (By default this function links to the SAME page!)
407 * @return string The input string wrapped in <a> tags
408 * @see pi_linkTP()
409 */
410 public function pi_linkTP_keepPIvars($str, $overrulePIvars = [], $cache = false, $clearAnyway = false, $altPageId = 0)
411 {
412 if (is_array($this->piVars) && is_array($overrulePIvars) && !$clearAnyway) {
413 $piVars = $this->piVars;
414 unset($piVars['DATA']);
415 ArrayUtility::mergeRecursiveWithOverrule($piVars, $overrulePIvars);
416 $overrulePIvars = $piVars;
417 if ($this->pi_autoCacheEn) {
418 $cache = $this->pi_autoCache($overrulePIvars);
419 }
420 }
421 return $this->pi_linkTP($str, [$this->prefixId => $overrulePIvars], $cache, $altPageId);
422 }
423
424 /**
425 * Get URL to the current page while keeping currently set values in piVars.
426 * Same as pi_linkTP_keepPIvars but returns only the URL from the link.
427 *
428 * @param array $overrulePIvars See pi_linkTP_keepPIvars
429 * @param bool $cache See pi_linkTP_keepPIvars
430 * @param bool $clearAnyway See pi_linkTP_keepPIvars
431 * @param int $altPageId See pi_linkTP_keepPIvars
432 * @return string The URL ($this->cObj->lastTypoLinkUrl)
433 * @see pi_linkTP_keepPIvars()
434 */
435 public function pi_linkTP_keepPIvars_url($overrulePIvars = [], $cache = false, $clearAnyway = false, $altPageId = 0)
436 {
437 $this->pi_linkTP_keepPIvars('|', $overrulePIvars, $cache, $clearAnyway, $altPageId);
438 return $this->cObj->lastTypoLinkUrl;
439 }
440
441 /**
442 * Wraps the $str in a link to a single display of the record (using piVars[showUid])
443 * Uses pi_linkTP for the linking
444 *
445 * @param string $str The content string to wrap in <a> tags
446 * @param int $uid UID of the record for which to display details (basically this will become the value of [showUid]
447 * @param bool $cache See pi_linkTP_keepPIvars
448 * @param array $mergeArr Array of values to override in the current piVars. Same as $overrulePIvars in pi_linkTP_keepPIvars
449 * @param bool $urlOnly If TRUE, only the URL is returned, not a full link
450 * @param int $altPageId Alternative page ID for the link. (By default this function links to the SAME page!)
451 * @return string The input string wrapped in <a> tags
452 * @see pi_linkTP(), pi_linkTP_keepPIvars()
453 */
454 public function pi_list_linkSingle($str, $uid, $cache = false, $mergeArr = [], $urlOnly = false, $altPageId = 0)
455 {
456 if ($this->prefixId) {
457 if ($cache) {
458 $overrulePIvars = $uid ? ['showUid' => $uid] : [];
459 $overrulePIvars = array_merge($overrulePIvars, (array)$mergeArr);
460 $str = $this->pi_linkTP($str, [$this->prefixId => $overrulePIvars], $cache, $altPageId);
461 } else {
462 $overrulePIvars = ['showUid' => $uid ?: ''];
463 $overrulePIvars = array_merge($overrulePIvars, (array)$mergeArr);
464 $str = $this->pi_linkTP_keepPIvars($str, $overrulePIvars, $cache, 0, $altPageId);
465 }
466 // If urlOnly flag, return only URL as it has recently be generated.
467 if ($urlOnly) {
468 $str = $this->cObj->lastTypoLinkUrl;
469 }
470 }
471 return $str;
472 }
473
474 /**
475 * Will change the href value from <a> in the input string and turn it into an onclick event that will open a new window with the URL
476 *
477 * @param string $str The string to process. This should be a string already wrapped/including a <a> tag which will be modified to contain an onclick handler. Only the attributes "href" and "onclick" will be left.
478 * @param string $winName Window name for the pop-up window
479 * @param string $winParams Window parameters, see the default list for inspiration
480 * @return string The processed input string, modified IF a <a> tag was found
481 */
482 public function pi_openAtagHrefInJSwindow($str, $winName = '', $winParams = 'width=670,height=500,status=0,menubar=0,scrollbars=1,resizable=1')
483 {
484 if (preg_match('/(.*)(<a[^>]*>)(.*)/i', $str, $match)) {
485 $aTagContent = GeneralUtility::get_tag_attributes($match[2]);
486 $onClick = 'vHWin=window.open('
487 . GeneralUtility::quoteJSvalue($this->frontendController->baseUrlWrap($aTagContent['href'])) . ','
488 . GeneralUtility::quoteJSvalue($winName ?: md5($aTagContent['href'])) . ','
489 . GeneralUtility::quoteJSvalue($winParams) . ');vHWin.focus();return false;';
490 $match[2] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">';
491 $str = $match[1] . $match[2] . $match[3];
492 }
493 return $str;
494 }
495
496 /***************************
497 *
498 * Functions for listing, browsing, searching etc.
499 *
500 **************************/
501 /**
502 * Returns a results browser. This means a bar of page numbers plus a "previous" and "next" link. For each entry in the bar the piVars "pointer" will be pointing to the "result page" to show.
503 * Using $this->piVars['pointer'] as pointer to the page to display. Can be overwritten with another string ($pointerName) to make it possible to have more than one pagebrowser on a page)
504 * Using $this->internal['res_count'], $this->internal['results_at_a_time'] and $this->internal['maxPages'] for count number, how many results to show and the max number of pages to include in the browse bar.
505 * Using $this->internal['dontLinkActivePage'] as switch if the active (current) page should be displayed as pure text or as a link to itself
506 * Using $this->internal['showFirstLast'] as switch if the two links named "<< First" and "LAST >>" will be shown and point to the first or last page.
507 * Using $this->internal['pagefloat']: this defines were the current page is shown in the list of pages in the Pagebrowser. If this var is an integer it will be interpreted as position in the list of pages. If its value is the keyword "center" the current page will be shown in the middle of the pagelist.
508 * Using $this->internal['showRange']: this var switches the display of the pagelinks from pagenumbers to ranges f.e.: 1-5 6-10 11-15... instead of 1 2 3...
509 * Using $this->pi_isOnlyFields: this holds a comma-separated list of fieldnames which - if they are among the GETvars - will not disable caching for the page with pagebrowser.
510 *
511 * The third parameter is an array with several wraps for the parts of the pagebrowser. The following elements will be recognized:
512 * disabledLinkWrap, inactiveLinkWrap, activeLinkWrap, browseLinksWrap, showResultsWrap, showResultsNumbersWrap, browseBoxWrap.
513 *
514 * If $wrapArr['showResultsNumbersWrap'] is set, the formatting string is expected to hold template markers (###FROM###, ###TO###, ###OUT_OF###, ###FROM_TO###, ###CURRENT_PAGE###, ###TOTAL_PAGES###)
515 * otherwise the formatting string is expected to hold sprintf-markers (%s) for from, to, outof (in that sequence)
516 *
517 * @param int $showResultCount Determines how the results of the page browser will be shown. See description below
518 * @param string $tableParams Attributes for the table tag which is wrapped around the table cells containing the browse links
519 * @param array $wrapArr Array with elements to overwrite the default $wrapper-array.
520 * @param string $pointerName varname for the pointer.
521 * @param bool $hscText Enable htmlspecialchars() on language labels
522 * @param bool $forceOutput Forces the output of the page browser if you set this option to "TRUE" (otherwise it's only drawn if enough entries are available)
523 * @return string Output HTML-Table, wrapped in <div>-tags with a class attribute (if $wrapArr is not passed,
524 */
525 public function pi_list_browseresults($showResultCount = 1, $tableParams = '', $wrapArr = [], $pointerName = 'pointer', $hscText = true, $forceOutput = false)
526 {
527 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['pi_list_browseresults'] ?? [] as $classRef) {
528 $hookObj = GeneralUtility::makeInstance($classRef);
529 if (method_exists($hookObj, 'pi_list_browseresults')) {
530 $pageBrowser = $hookObj->pi_list_browseresults($showResultCount, $tableParams, $wrapArr, $pointerName, $hscText, $forceOutput, $this);
531 if (is_string($pageBrowser) && trim($pageBrowser) !== '') {
532 return $pageBrowser;
533 }
534 }
535 }
536 // example $wrapArr-array how it could be traversed from an extension
537 /* $wrapArr = array(
538 'browseBoxWrap' => '<div class="browseBoxWrap">|</div>',
539 'showResultsWrap' => '<div class="showResultsWrap">|</div>',
540 'browseLinksWrap' => '<div class="browseLinksWrap">|</div>',
541 'showResultsNumbersWrap' => '<span class="showResultsNumbersWrap">|</span>',
542 'disabledLinkWrap' => '<span class="disabledLinkWrap">|</span>',
543 'inactiveLinkWrap' => '<span class="inactiveLinkWrap">|</span>',
544 'activeLinkWrap' => '<span class="activeLinkWrap">|</span>'
545 );*/
546 // Initializing variables:
547 $pointer = (int)$this->piVars[$pointerName];
548 $count = (int)$this->internal['res_count'];
549 $results_at_a_time = MathUtility::forceIntegerInRange($this->internal['results_at_a_time'], 1, 1000);
550 $totalPages = ceil($count / $results_at_a_time);
551 $maxPages = MathUtility::forceIntegerInRange($this->internal['maxPages'], 1, 100);
552 $pi_isOnlyFields = $this->pi_isOnlyFields($this->pi_isOnlyFields);
553 if (!$forceOutput && $count <= $results_at_a_time) {
554 return '';
555 }
556 // $showResultCount determines how the results of the pagerowser will be shown.
557 // If set to 0: only the result-browser will be shown
558 // 1: (default) the text "Displaying results..." and the result-browser will be shown.
559 // 2: only the text "Displaying results..." will be shown
560 $showResultCount = (int)$showResultCount;
561 // If this is set, two links named "<< First" and "LAST >>" will be shown and point to the very first or last page.
562 $showFirstLast = !empty($this->internal['showFirstLast']);
563 // If this has a value the "previous" button is always visible (will be forced if "showFirstLast" is set)
564 $alwaysPrev = $showFirstLast ? 1 : $this->pi_alwaysPrev;
565 if (isset($this->internal['pagefloat'])) {
566 if (strtoupper($this->internal['pagefloat']) === 'CENTER') {
567 $pagefloat = ceil(($maxPages - 1) / 2);
568 } else {
569 // pagefloat set as integer. 0 = left, value >= $this->internal['maxPages'] = right
570 $pagefloat = MathUtility::forceIntegerInRange($this->internal['pagefloat'], -1, $maxPages - 1);
571 }
572 } else {
573 // pagefloat disabled
574 $pagefloat = -1;
575 }
576 // Default values for "traditional" wrapping with a table. Can be overwritten by vars from $wrapArr
577 $wrapper['disabledLinkWrap'] = '<td class="nowrap"><p>|</p></td>';
578 $wrapper['inactiveLinkWrap'] = '<td class="nowrap"><p>|</p></td>';
579 $wrapper['activeLinkWrap'] = '<td' . $this->pi_classParam('browsebox-SCell') . ' class="nowrap"><p>|</p></td>';
580 $wrapper['browseLinksWrap'] = rtrim('<table ' . $tableParams) . '><tr>|</tr></table>';
581 $wrapper['showResultsWrap'] = '<p>|</p>';
582 $wrapper['browseBoxWrap'] = '
583 <!--
584 List browsing box:
585 -->
586 <div ' . $this->pi_classParam('browsebox') . '>
587 |
588 </div>';
589 // Now overwrite all entries in $wrapper which are also in $wrapArr
590 $wrapper = array_merge($wrapper, $wrapArr);
591 // Show pagebrowser
592 if ($showResultCount != 2) {
593 if ($pagefloat > -1) {
594 $lastPage = min($totalPages, max($pointer + 1 + $pagefloat, $maxPages));
595 $firstPage = max(0, $lastPage - $maxPages);
596 } else {
597 $firstPage = 0;
598 $lastPage = MathUtility::forceIntegerInRange($totalPages, 1, $maxPages);
599 }
600 $links = [];
601 // Make browse-table/links:
602 // Link to first page
603 if ($showFirstLast) {
604 if ($pointer > 0) {
605 $label = $this->pi_getLL('pi_list_browseresults_first', '<< First');
606 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($hscText ? htmlspecialchars($label) : $label, [$pointerName => null], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
607 } else {
608 $label = $this->pi_getLL('pi_list_browseresults_first', '<< First');
609 $links[] = $this->cObj->wrap($hscText ? htmlspecialchars($label) : $label, $wrapper['disabledLinkWrap']);
610 }
611 }
612 // Link to previous page
613 if ($alwaysPrev >= 0) {
614 if ($pointer > 0) {
615 $label = $this->pi_getLL('pi_list_browseresults_prev', '< Previous');
616 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($hscText ? htmlspecialchars($label) : $label, [$pointerName => ($pointer - 1) ?: ''], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
617 } elseif ($alwaysPrev) {
618 $label = $this->pi_getLL('pi_list_browseresults_prev', '< Previous');
619 $links[] = $this->cObj->wrap($hscText ? htmlspecialchars($label) : $label, $wrapper['disabledLinkWrap']);
620 }
621 }
622 // Links to pages
623 for ($a = $firstPage; $a < $lastPage; $a++) {
624 if ($this->internal['showRange']) {
625 $pageText = ($a * $results_at_a_time + 1) . '-' . min($count, ($a + 1) * $results_at_a_time);
626 } else {
627 $label = $this->pi_getLL('pi_list_browseresults_page', 'Page');
628 $pageText = trim(($hscText ? htmlspecialchars($label) : $label) . ' ' . ($a + 1));
629 }
630 // Current page
631 if ($pointer == $a) {
632 if ($this->internal['dontLinkActivePage']) {
633 $links[] = $this->cObj->wrap($pageText, $wrapper['activeLinkWrap']);
634 } else {
635 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($pageText, [$pointerName => $a ?: ''], $pi_isOnlyFields), $wrapper['activeLinkWrap']);
636 }
637 } else {
638 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($pageText, [$pointerName => $a ?: ''], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
639 }
640 }
641 if ($pointer < $totalPages - 1 || $showFirstLast) {
642 // Link to next page
643 if ($pointer >= $totalPages - 1) {
644 $label = $this->pi_getLL('pi_list_browseresults_next', 'Next >');
645 $links[] = $this->cObj->wrap($hscText ? htmlspecialchars($label) : $label, $wrapper['disabledLinkWrap']);
646 } else {
647 $label = $this->pi_getLL('pi_list_browseresults_next', 'Next >');
648 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($hscText ? htmlspecialchars($label) : $label, [$pointerName => $pointer + 1], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
649 }
650 }
651 // Link to last page
652 if ($showFirstLast) {
653 if ($pointer < $totalPages - 1) {
654 $label = $this->pi_getLL('pi_list_browseresults_last', 'Last >>');
655 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($hscText ? htmlspecialchars($label) : $label, [$pointerName => $totalPages - 1], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
656 } else {
657 $label = $this->pi_getLL('pi_list_browseresults_last', 'Last >>');
658 $links[] = $this->cObj->wrap($hscText ? htmlspecialchars($label) : $label, $wrapper['disabledLinkWrap']);
659 }
660 }
661 $theLinks = $this->cObj->wrap(implode(LF, $links), $wrapper['browseLinksWrap']);
662 } else {
663 $theLinks = '';
664 }
665 $pR1 = $pointer * $results_at_a_time + 1;
666 $pR2 = $pointer * $results_at_a_time + $results_at_a_time;
667 if ($showResultCount) {
668 if ($wrapper['showResultsNumbersWrap']) {
669 // This will render the resultcount in a more flexible way using markers (new in TYPO3 3.8.0).
670 // The formatting string is expected to hold template markers (see function header). Example: 'Displaying results ###FROM### to ###TO### out of ###OUT_OF###'
671 $markerArray['###FROM###'] = $this->cObj->wrap($this->internal['res_count'] > 0 ? $pR1 : 0, $wrapper['showResultsNumbersWrap']);
672 $markerArray['###TO###'] = $this->cObj->wrap(min($this->internal['res_count'], $pR2), $wrapper['showResultsNumbersWrap']);
673 $markerArray['###OUT_OF###'] = $this->cObj->wrap($this->internal['res_count'], $wrapper['showResultsNumbersWrap']);
674 $markerArray['###FROM_TO###'] = $this->cObj->wrap(($this->internal['res_count'] > 0 ? $pR1 : 0) . ' ' . $this->pi_getLL('pi_list_browseresults_to', 'to') . ' ' . min($this->internal['res_count'], $pR2), $wrapper['showResultsNumbersWrap']);
675 $markerArray['###CURRENT_PAGE###'] = $this->cObj->wrap($pointer + 1, $wrapper['showResultsNumbersWrap']);
676 $markerArray['###TOTAL_PAGES###'] = $this->cObj->wrap($totalPages, $wrapper['showResultsNumbersWrap']);
677 // Substitute markers
678 $resultCountMsg = $this->templateService->substituteMarkerArray($this->pi_getLL('pi_list_browseresults_displays', 'Displaying results ###FROM### to ###TO### out of ###OUT_OF###'), $markerArray);
679 } else {
680 // Render the resultcount in the "traditional" way using sprintf
681 $resultCountMsg = sprintf(str_replace('###SPAN_BEGIN###', '<span' . $this->pi_classParam('browsebox-strong') . '>', $this->pi_getLL('pi_list_browseresults_displays', 'Displaying results ###SPAN_BEGIN###%s to %s</span> out of ###SPAN_BEGIN###%s</span>')), $count > 0 ? $pR1 : 0, min($count, $pR2), $count);
682 }
683 $resultCountMsg = $this->cObj->wrap($resultCountMsg, $wrapper['showResultsWrap']);
684 } else {
685 $resultCountMsg = '';
686 }
687 $sTables = $this->cObj->wrap($resultCountMsg . $theLinks, $wrapper['browseBoxWrap']);
688 return $sTables;
689 }
690
691 /**
692 * Returns a mode selector; a little menu in a table normally put in the top of the page/list.
693 *
694 * @param array $items Key/Value pairs for the menu; keys are the piVars[mode] values and the "values" are the labels for them.
695 * @param string $tableParams Attributes for the table tag which is wrapped around the table cells containing the menu
696 * @return string Output HTML, wrapped in <div>-tags with a class attribute
697 */
698 public function pi_list_modeSelector($items = [], $tableParams = '')
699 {
700 $cells = [];
701 foreach ($items as $k => $v) {
702 $cells[] = '
703 <td' . ($this->piVars['mode'] == $k ? $this->pi_classParam('modeSelector-SCell') : '') . '><p>' . $this->pi_linkTP_keepPIvars(htmlspecialchars($v), ['mode' => $k], $this->pi_isOnlyFields($this->pi_isOnlyFields)) . '</p></td>';
704 }
705 $sTables = '
706
707 <!--
708 Mode selector (menu for list):
709 -->
710 <div' . $this->pi_classParam('modeSelector') . '>
711 <' . rtrim('table ' . $tableParams) . '>
712 <tr>
713 ' . implode('', $cells) . '
714 </tr>
715 </table>
716 </div>';
717 return $sTables;
718 }
719
720 /**
721 * Returns the list of items based on the input SQL result pointer
722 * For each result row the internal var, $this->internal['currentRow'], is set with the row returned.
723 * $this->pi_list_header() makes the header row for the list
724 * $this->pi_list_row() is used for rendering each row
725 * Notice that these two functions are typically ALWAYS defined in the extension class of the plugin since they are directly concerned with the specific layout for that plugins purpose.
726 *
727 * @param Statement $statement Result pointer to a SQL result which can be traversed.
728 * @param string $tableParams Attributes for the table tag which is wrapped around the table rows containing the list
729 * @return string Output HTML, wrapped in <div>-tags with a class attribute
730 * @see pi_list_row(), pi_list_header()
731 */
732 public function pi_list_makelist($statement, $tableParams = '')
733 {
734 // Make list table header:
735 $tRows = [];
736 $this->internal['currentRow'] = '';
737 $tRows[] = $this->pi_list_header();
738 // Make list table rows
739 $c = 0;
740 while ($this->internal['currentRow'] = $statement->fetch()) {
741 $tRows[] = $this->pi_list_row($c);
742 $c++;
743 }
744 $out = '
745
746 <!--
747 Record list:
748 -->
749 <div' . $this->pi_classParam('listrow') . '>
750 <' . rtrim('table ' . $tableParams) . '>
751 ' . implode('', $tRows) . '
752 </table>
753 </div>';
754 return $out;
755 }
756
757 /**
758 * Returns a list row. Get data from $this->internal['currentRow'];
759 * (Dummy)
760 * Notice: This function should ALWAYS be defined in the extension class of the plugin since it is directly concerned with the specific layout of the listing for your plugins purpose.
761 *
762 * @param int $c Row counting. Starts at 0 (zero). Used for alternating class values in the output rows.
763 * @return string HTML output, a table row with a class attribute set (alternative based on odd/even rows)
764 */
765 public function pi_list_row($c)
766 {
767 // Dummy
768 return '<tr' . ($c % 2 ? $this->pi_classParam('listrow-odd') : '') . '><td><p>[dummy row]</p></td></tr>';
769 }
770
771 /**
772 * Returns a list header row.
773 * (Dummy)
774 * Notice: This function should ALWAYS be defined in the extension class of the plugin since it is directly concerned with the specific layout of the listing for your plugins purpose.
775 *
776 * @return string HTML output, a table row with a class attribute set
777 */
778 public function pi_list_header()
779 {
780 return '<tr' . $this->pi_classParam('listrow-header') . '><td><p>[dummy header row]</p></td></tr>';
781 }
782
783 /***************************
784 *
785 * Stylesheet, CSS
786 *
787 **************************/
788 /**
789 * Returns a class-name prefixed with $this->prefixId and with all underscores substituted to dashes (-)
790 *
791 * @param string $class The class name (or the END of it since it will be prefixed by $this->prefixId.'-')
792 * @return string The combined class name (with the correct prefix)
793 */
794 public function pi_getClassName($class)
795 {
796 return str_replace('_', '-', $this->prefixId) . ($this->prefixId ? '-' : '') . $class;
797 }
798
799 /**
800 * Returns the class-attribute with the correctly prefixed classname
801 * Using pi_getClassName()
802 *
803 * @param string $class The class name(s) (suffix) - separate multiple classes with commas
804 * @param string $addClasses Additional class names which should not be prefixed - separate multiple classes with commas
805 * @return string A "class" attribute with value and a single space char before it.
806 * @see pi_getClassName()
807 */
808 public function pi_classParam($class, $addClasses = '')
809 {
810 $output = '';
811 $classNames = GeneralUtility::trimExplode(',', $class);
812 foreach ($classNames as $className) {
813 $output .= ' ' . $this->pi_getClassName($className);
814 }
815 $additionalClassNames = GeneralUtility::trimExplode(',', $addClasses);
816 foreach ($additionalClassNames as $additionalClassName) {
817 $output .= ' ' . $additionalClassName;
818 }
819 return ' class="' . trim($output) . '"';
820 }
821
822 /**
823 * Wraps the input string in a <div> tag with the class attribute set to the prefixId.
824 * All content returned from your plugins should be returned through this function so all content from your plugin is encapsulated in a <div>-tag nicely identifying the content of your plugin.
825 *
826 * @param string $str HTML content to wrap in the div-tags with the "main class" of the plugin
827 * @return string HTML content wrapped, ready to return to the parent object.
828 */
829 public function pi_wrapInBaseClass($str)
830 {
831 $content = '<div class="' . str_replace('_', '-', $this->prefixId) . '">
832 ' . $str . '
833 </div>
834 ';
835 if (!$this->frontendController->config['config']['disablePrefixComment']) {
836 $content = '
837
838
839 <!--
840
841 BEGIN: Content of extension "' . $this->extKey . '", plugin "' . $this->prefixId . '"
842
843 -->
844 ' . $content . '
845 <!-- END: Content of extension "' . $this->extKey . '", plugin "' . $this->prefixId . '" -->
846
847 ';
848 }
849 return $content;
850 }
851
852 /***************************
853 *
854 * Frontend editing: Edit panel, edit icons
855 *
856 **************************/
857 /**
858 * Returns the Backend User edit panel for the $row from $tablename
859 *
860 * @param array $row Record array.
861 * @param string $tablename Table name
862 * @param string $label A label to show with the panel.
863 * @param array $conf TypoScript parameters to pass along to the EDITPANEL content Object that gets rendered. The property "allow" WILL get overridden/set though.
864 * @return string Returns FALSE/blank if no BE User login and of course if the panel is not shown for other reasons. Otherwise the HTML for the panel (a table).
865 * @see ContentObjectRenderer::EDITPANEL()
866 */
867 public function pi_getEditPanel($row = [], $tablename = '', $label = '', $conf = [])
868 {
869 $panel = '';
870 if (!$row || !$tablename) {
871 $row = $this->internal['currentRow'];
872 $tablename = $this->internal['currentTable'];
873 }
874 if ($this->frontendController->isBackendUserLoggedIn()) {
875 // Create local cObj if not set:
876 if (!is_object($this->pi_EPtemp_cObj)) {
877 $this->pi_EPtemp_cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
878 $this->pi_EPtemp_cObj->setParent($this->cObj->data, $this->cObj->currentRecord);
879 }
880 // Initialize the cObj object with current row
881 $this->pi_EPtemp_cObj->start($row, $tablename);
882 // Setting TypoScript values in the $conf array. See documentation in TSref for the EDITPANEL cObject.
883 $conf['allow'] = 'edit,new,delete,move,hide';
884 $panel = $this->pi_EPtemp_cObj->cObjGetSingle('EDITPANEL', $conf, 'editpanel');
885 }
886 if ($panel) {
887 if ($label) {
888 return '<!-- BEGIN: EDIT PANEL --><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr><td valign="top">' . $label . '</td><td valign="top" align="right">' . $panel . '</td></tr></table><!-- END: EDIT PANEL -->';
889 }
890 return '<!-- BEGIN: EDIT PANEL -->' . $panel . '<!-- END: EDIT PANEL -->';
891 }
892 return $label;
893 }
894
895 /**
896 * Adds edit-icons to the input content.
897 * ContentObjectRenderer::editIcons used for rendering
898 *
899 * @param string $content HTML content to add icons to. The icons will be put right after the last content part in the string (that means before the ending series of HTML tags)
900 * @param string $fields The list of fields to edit when the icon is clicked.
901 * @param string $title Title for the edit icon.
902 * @param array $row Table record row
903 * @param string $tablename Table name
904 * @param array $oConf Conf array
905 * @return string The processed content
906 * @see ContentObjectRenderer::editIcons()
907 */
908 public function pi_getEditIcon($content, $fields, $title = '', $row = [], $tablename = '', $oConf = [])
909 {
910 if ($this->frontendController->isBackendUserLoggedIn()) {
911 if (!$row || !$tablename) {
912 $row = $this->internal['currentRow'];
913 $tablename = $this->internal['currentTable'];
914 }
915 $conf = array_merge([
916 'beforeLastTag' => 1,
917 'iconTitle' => $title
918 ], $oConf);
919 $content = $this->cObj->editIcons($content, $tablename . ':' . $fields, $conf, $tablename . ':' . $row['uid'], $row, '&viewUrl=' . rawurlencode(GeneralUtility::getIndpEnv('REQUEST_URI')));
920 }
921 return $content;
922 }
923
924 /***************************
925 *
926 * Localization, locallang functions
927 *
928 **************************/
929 /**
930 * Returns the localized label of the LOCAL_LANG key, $key
931 * Notice that for debugging purposes prefixes for the output values can be set with the internal vars ->LLtestPrefixAlt and ->LLtestPrefix
932 *
933 * @param string $key The key from the LOCAL_LANG array for which to return the value.
934 * @param string $alternativeLabel Alternative string to return IF no value is found set for the key, neither for the local language nor the default.
935 * @return string The value from LOCAL_LANG.
936 */
937 public function pi_getLL($key, $alternativeLabel = '')
938 {
939 $word = null;
940 if (!empty($this->LOCAL_LANG[$this->LLkey][$key][0]['target'])
941 || isset($this->LOCAL_LANG_UNSET[$this->LLkey][$key])
942 ) {
943 $word = $this->LOCAL_LANG[$this->LLkey][$key][0]['target'];
944 } elseif ($this->altLLkey) {
945 $alternativeLanguageKeys = GeneralUtility::trimExplode(',', $this->altLLkey, true);
946 $alternativeLanguageKeys = array_reverse($alternativeLanguageKeys);
947 foreach ($alternativeLanguageKeys as $languageKey) {
948 if (!empty($this->LOCAL_LANG[$languageKey][$key][0]['target'])
949 || isset($this->LOCAL_LANG_UNSET[$languageKey][$key])
950 ) {
951 // Alternative language translation for key exists
952 $word = $this->LOCAL_LANG[$languageKey][$key][0]['target'];
953 break;
954 }
955 }
956 }
957 if ($word === null) {
958 if (!empty($this->LOCAL_LANG['default'][$key][0]['target'])
959 || isset($this->LOCAL_LANG_UNSET['default'][$key])
960 ) {
961 // Get default translation (without charset conversion, english)
962 $word = $this->LOCAL_LANG['default'][$key][0]['target'];
963 } else {
964 // Return alternative string or empty
965 $word = isset($this->LLtestPrefixAlt) ? $this->LLtestPrefixAlt . $alternativeLabel : $alternativeLabel;
966 }
967 }
968 return isset($this->LLtestPrefix) ? $this->LLtestPrefix . $word : $word;
969 }
970
971 /**
972 * Loads local-language values from the file passed as a parameter or
973 * by looking for a "locallang" file in the
974 * plugin class directory ($this->scriptRelPath).
975 * Also locallang values set in the TypoScript property "_LOCAL_LANG" are
976 * merged onto the values found in the "locallang" file.
977 * Supported file extensions xlf, xml
978 *
979 * @param string $languageFilePath path to the plugin language file in format EXT:....
980 */
981 public function pi_loadLL($languageFilePath = '')
982 {
983 if ($this->LOCAL_LANG_loaded) {
984 return;
985 }
986
987 if ($languageFilePath === '' && $this->scriptRelPath) {
988 $languageFilePath = 'EXT:' . $this->extKey . '/' . PathUtility::dirname($this->scriptRelPath) . '/locallang.xlf';
989 }
990 if ($languageFilePath !== '') {
991 /** @var LocalizationFactory $languageFactory */
992 $languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
993 $this->LOCAL_LANG = $languageFactory->getParsedData($languageFilePath, $this->LLkey);
994 $alternativeLanguageKeys = GeneralUtility::trimExplode(',', $this->altLLkey, true);
995 foreach ($alternativeLanguageKeys as $languageKey) {
996 $tempLL = $languageFactory->getParsedData($languageFilePath, $languageKey);
997 if ($this->LLkey !== 'default' && isset($tempLL[$languageKey])) {
998 $this->LOCAL_LANG[$languageKey] = $tempLL[$languageKey];
999 }
1000 }
1001 // Overlaying labels from TypoScript (including fictitious language keys for non-system languages!):
1002 if (isset($this->conf['_LOCAL_LANG.'])) {
1003 // Clear the "unset memory"
1004 $this->LOCAL_LANG_UNSET = [];
1005 foreach ($this->conf['_LOCAL_LANG.'] as $languageKey => $languageArray) {
1006 // Remove the dot after the language key
1007 $languageKey = substr($languageKey, 0, -1);
1008 // Don't process label if the language is not loaded
1009 if (is_array($languageArray) && isset($this->LOCAL_LANG[$languageKey])) {
1010 foreach ($languageArray as $labelKey => $labelValue) {
1011 if (!is_array($labelValue)) {
1012 $this->LOCAL_LANG[$languageKey][$labelKey][0]['target'] = $labelValue;
1013 if ($labelValue === '') {
1014 $this->LOCAL_LANG_UNSET[$languageKey][$labelKey] = '';
1015 }
1016 }
1017 }
1018 }
1019 }
1020 }
1021 }
1022 $this->LOCAL_LANG_loaded = true;
1023 }
1024
1025 /***************************
1026 *
1027 * Database, queries
1028 *
1029 **************************/
1030 /**
1031 * Executes a standard SELECT query for listing of records based on standard input vars from the 'browser' ($this->internal['results_at_a_time'] and $this->piVars['pointer']) and 'searchbox' ($this->piVars['sword'] and $this->internal['searchFieldList'])
1032 * Set $count to 1 if you wish to get a count(*) query for selecting the number of results.
1033 * Notice that the query will use $this->conf['pidList'] and $this->conf['recursive'] to generate a PID list within which to search for records.
1034 *
1035 * @param string $table The table name to make the query for.
1036 * @param bool $count If set, you will get a "count(*)" query back instead of field selecting
1037 * @param string $addWhere Additional WHERE clauses (should be starting with " AND ....")
1038 * @param mixed $mm_cat If an array, then it must contain the keys "table", "mmtable" and (optionally) "catUidList" defining a table to make a MM-relation to in the query (based on fields uid_local and uid_foreign). If not array, the query will be a plain query looking up data in only one table.
1039 * @param string $groupBy If set, this is added as a " GROUP BY ...." part of the query.
1040 * @param string $orderBy If set, this is added as a " ORDER BY ...." part of the query. The default is that an ORDER BY clause is made based on $this->internal['orderBy'] and $this->internal['descFlag'] where the orderBy field must be found in $this->internal['orderByList']
1041 * @param string $query If set, this is taken as the first part of the query instead of what is created internally. Basically this should be a query starting with "FROM [table] WHERE ... AND ...". The $addWhere clauses and all the other stuff is still added. Only the tables and PID selecting clauses are bypassed. May be deprecated in the future!
1042 * @return Statement
1043 */
1044 public function pi_exec_query($table, $count = false, $addWhere = '', $mm_cat = '', $groupBy = '', $orderBy = '', $query = '')
1045 {
1046 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1047 $queryBuilder->from($table);
1048
1049 // Begin Query:
1050 if (!$query) {
1051 // This adds WHERE-clauses that ensures deleted, hidden, starttime/endtime/access records are NOT
1052 // selected, if they should not! Almost ALWAYS add this to your queries!
1053 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1054
1055 // Fetches the list of PIDs to select from.
1056 // TypoScript property .pidList is a comma list of pids. If blank, current page id is used.
1057 // TypoScript property .recursive is an int+ which determines how many levels down from the pids in the pid-list subpages should be included in the select.
1058 $pidList = GeneralUtility::intExplode(',', $this->pi_getPidList($this->conf['pidList'], $this->conf['recursive']), true);
1059 if (is_array($mm_cat)) {
1060 $queryBuilder->from($mm_cat['table'])
1061 ->from($mm_cat['mmtable'])
1062 ->where(
1063 $queryBuilder->expr()->eq($table . '.uid', $queryBuilder->quoteIdentifier($mm_cat['mmtable'] . '.uid_local')),
1064 $queryBuilder->expr()->eq($mm_cat['table'] . '.uid', $queryBuilder->quoteIdentifier($mm_cat['mmtable'] . '.uid_foreign')),
1065 $queryBuilder->expr()->in(
1066 $table . '.pid',
1067 $queryBuilder->createNamedParameter($pidList, Connection::PARAM_INT_ARRAY)
1068 )
1069 );
1070 if (strcmp($mm_cat['catUidList'], '')) {
1071 $queryBuilder->andWhere(
1072 $queryBuilder->expr()->in(
1073 $mm_cat['table'] . '.uid',
1074 $queryBuilder->createNamedParameter(
1075 GeneralUtility::intExplode(',', $mm_cat['catUidList'], true),
1076 Connection::PARAM_INT_ARRAY
1077 )
1078 )
1079 );
1080 }
1081 } else {
1082 $queryBuilder->where(
1083 $queryBuilder->expr()->in(
1084 'pid',
1085 $queryBuilder->createNamedParameter($pidList, Connection::PARAM_INT_ARRAY)
1086 )
1087 );
1088 }
1089 } else {
1090 // Restrictions need to be handled by the $query parameter!
1091 $queryBuilder->getRestrictions()->removeAll();
1092
1093 // Split the "FROM ... WHERE" string so we get the WHERE part and TABLE names separated...:
1094 list($tableListFragment, $whereFragment) = preg_split('/WHERE/i', trim($query), 2);
1095 foreach (QueryHelper::parseTableList($tableListFragment) as $tableNameAndAlias) {
1096 list($tableName, $tableAlias) = $tableNameAndAlias;
1097 $queryBuilder->from($tableName, $tableAlias);
1098 }
1099 $queryBuilder->where(QueryHelper::stripLogicalOperatorPrefix($whereFragment));
1100 }
1101
1102 // Add '$addWhere'
1103 if ($addWhere) {
1104 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($addWhere));
1105 }
1106 // Search word:
1107 if ($this->piVars['sword'] && $this->internal['searchFieldList']) {
1108 $queryBuilder->andWhere(
1109 QueryHelper::stripLogicalOperatorPrefix(
1110 $this->cObj->searchWhere($this->piVars['sword'], $this->internal['searchFieldList'], $table)
1111 )
1112 );
1113 }
1114
1115 if ($count) {
1116 $queryBuilder->count('*');
1117 } else {
1118 // Add 'SELECT'
1119 $fields = $this->pi_prependFieldsWithTable($table, $this->pi_listFields);
1120 $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true));
1121
1122 // Order by data:
1123 if (!$orderBy && $this->internal['orderBy']) {
1124 if (GeneralUtility::inList($this->internal['orderByList'], $this->internal['orderBy'])) {
1125 $sorting = $this->internal['descFlag'] ? ' DESC' : 'ASC';
1126 $queryBuilder->orderBy($table . '.' . $this->internal['orderBy'], $sorting);
1127 }
1128 } elseif ($orderBy) {
1129 foreach (QueryHelper::parseOrderBy($orderBy) as $fieldNameAndSorting) {
1130 list($fieldName, $sorting) = $fieldNameAndSorting;
1131 $queryBuilder->addOrderBy($fieldName, $sorting);
1132 }
1133 }
1134
1135 // Limit data:
1136 $pointer = (int)$this->piVars['pointer'];
1137 $results_at_a_time = MathUtility::forceIntegerInRange($this->internal['results_at_a_time'], 1, 1000);
1138 $queryBuilder->setFirstResult($pointer * $results_at_a_time)
1139 ->setMaxResults($results_at_a_time);
1140
1141 // Grouping
1142 if (!empty($groupBy)) {
1143 $queryBuilder->groupBy(...QueryHelper::parseGroupBy($groupBy));
1144 }
1145 }
1146
1147 return $queryBuilder->execute();
1148 }
1149
1150 /**
1151 * Returns the row $uid from $table
1152 * (Simply calling $this->frontendEngine->sys_page->checkRecord())
1153 *
1154 * @param string $table The table name
1155 * @param int $uid The uid of the record from the table
1156 * @param bool $checkPage If $checkPage is set, it's required that the page on which the record resides is accessible
1157 * @return array If record is found, an array. Otherwise FALSE.
1158 */
1159 public function pi_getRecord($table, $uid, $checkPage = false)
1160 {
1161 return $this->frontendController->sys_page->checkRecord($table, $uid, $checkPage);
1162 }
1163
1164 /**
1165 * Returns a commalist of page ids for a query (eg. 'WHERE pid IN (...)')
1166 *
1167 * @param string $pid_list A comma list of page ids (if empty current page is used)
1168 * @param int $recursive An integer >=0 telling how deep to dig for pids under each entry in $pid_list
1169 * @return string List of PID values (comma separated)
1170 */
1171 public function pi_getPidList($pid_list, $recursive = 0)
1172 {
1173 if (!strcmp($pid_list, '')) {
1174 $pid_list = $this->frontendController->id;
1175 }
1176 $recursive = MathUtility::forceIntegerInRange($recursive, 0);
1177 $pid_list_arr = array_unique(GeneralUtility::trimExplode(',', $pid_list, true));
1178 $pid_list = [];
1179 foreach ($pid_list_arr as $val) {
1180 $val = MathUtility::forceIntegerInRange($val, 0);
1181 if ($val) {
1182 $_list = $this->cObj->getTreeList(-1 * $val, $recursive);
1183 if ($_list) {
1184 $pid_list[] = $_list;
1185 }
1186 }
1187 }
1188 return implode(',', $pid_list);
1189 }
1190
1191 /**
1192 * Having a comma list of fields ($fieldList) this is prepended with the $table.'.' name
1193 *
1194 * @param string $table Table name to prepend
1195 * @param string $fieldList List of fields where each element will be prepended with the table name given.
1196 * @return string List of fields processed.
1197 */
1198 public function pi_prependFieldsWithTable($table, $fieldList)
1199 {
1200 $list = GeneralUtility::trimExplode(',', $fieldList, true);
1201 $return = [];
1202 foreach ($list as $listItem) {
1203 $return[] = $table . '.' . $listItem;
1204 }
1205 return implode(',', $return);
1206 }
1207
1208 /**
1209 * Will select all records from the "category table", $table, and return them in an array.
1210 *
1211 * @param string $table The name of the category table to select from.
1212 * @param int $pid The page from where to select the category records.
1213 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
1214 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
1215 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
1216 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
1217 * @return array The array with the category records in.
1218 */
1219 public function pi_getCategoryTableContents($table, $pid, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
1220 {
1221 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1222 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1223 $queryBuilder->select('*')
1224 ->from($table)
1225 ->where(
1226 $queryBuilder->expr()->eq(
1227 'pid',
1228 $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
1229 ),
1230 QueryHelper::stripLogicalOperatorPrefix($whereClause)
1231 );
1232
1233 if (!empty($orderBy)) {
1234 foreach (QueryHelper::parseOrderBy($orderBy) as $fieldNameAndSorting) {
1235 list($fieldName, $sorting) = $fieldNameAndSorting;
1236 $queryBuilder->addOrderBy($fieldName, $sorting);
1237 }
1238 }
1239
1240 if (!empty($groupBy)) {
1241 $queryBuilder->groupBy(...QueryHelper::parseGroupBy($groupBy));
1242 }
1243
1244 if (!empty($limit)) {
1245 $limitValues = GeneralUtility::intExplode(',', $limit, true);
1246 if (count($limitValues) === 1) {
1247 $queryBuilder->setMaxResults($limitValues[0]);
1248 } else {
1249 $queryBuilder->setFirstResult($limitValues[0])
1250 ->setMaxResults($limitValues[1]);
1251 }
1252 }
1253
1254 $result = $queryBuilder->execute();
1255 $outArr = [];
1256 while ($row = $result->fetch()) {
1257 $outArr[$row['uid']] = $row;
1258 }
1259 return $outArr;
1260 }
1261
1262 /***************************
1263 *
1264 * Various
1265 *
1266 **************************/
1267 /**
1268 * Returns TRUE if the piVars array has ONLY those fields entered that is set in the $fList (commalist) AND if none of those fields value is greater than $lowerThan field if they are integers.
1269 * Notice that this function will only work as long as values are integers.
1270 *
1271 * @param string $fList List of fields (keys from piVars) to evaluate on
1272 * @param int $lowerThan Limit for the values.
1273 * @return bool|null Returns TRUE (1) if conditions are met.
1274 */
1275 public function pi_isOnlyFields($fList, $lowerThan = -1)
1276 {
1277 $lowerThan = $lowerThan == -1 ? $this->pi_lowerThan : $lowerThan;
1278 $fList = GeneralUtility::trimExplode(',', $fList, true);
1279 $tempPiVars = $this->piVars;
1280 foreach ($fList as $k) {
1281 if (!MathUtility::canBeInterpretedAsInteger($tempPiVars[$k]) || $tempPiVars[$k] < $lowerThan) {
1282 unset($tempPiVars[$k]);
1283 }
1284 }
1285 if (empty($tempPiVars)) {
1286 //@TODO: How do we deal with this? return TRUE would be the right thing to do here but that might be breaking
1287 return 1;
1288 }
1289 return null;
1290 }
1291
1292 /**
1293 * Returns TRUE if the array $inArray contains only values allowed to be cached based on the configuration in $this->pi_autoCacheFields
1294 * Used by ->pi_linkTP_keepPIvars
1295 * This is an advanced form of evaluation of whether a URL should be cached or not.
1296 *
1297 * @param array $inArray An array with piVars values to evaluate
1298 * @return bool|null Returns TRUE (1) if conditions are met.
1299 * @see pi_linkTP_keepPIvars()
1300 */
1301 public function pi_autoCache($inArray)
1302 {
1303 if (is_array($inArray)) {
1304 foreach ($inArray as $fN => $fV) {
1305 if (!strcmp($inArray[$fN], '')) {
1306 unset($inArray[$fN]);
1307 } elseif (is_array($this->pi_autoCacheFields[$fN])) {
1308 if (is_array($this->pi_autoCacheFields[$fN]['range']) && (int)$inArray[$fN] >= (int)$this->pi_autoCacheFields[$fN]['range'][0] && (int)$inArray[$fN] <= (int)$this->pi_autoCacheFields[$fN]['range'][1]) {
1309 unset($inArray[$fN]);
1310 }
1311 if (is_array($this->pi_autoCacheFields[$fN]['list']) && in_array($inArray[$fN], $this->pi_autoCacheFields[$fN]['list'])) {
1312 unset($inArray[$fN]);
1313 }
1314 }
1315 }
1316 }
1317 if (empty($inArray)) {
1318 //@TODO: How do we deal with this? return TRUE would be the right thing to do here but that might be breaking
1319 return 1;
1320 }
1321 return null;
1322 }
1323
1324 /**
1325 * Will process the input string with the parseFunc function from ContentObjectRenderer based on configuration
1326 * set in "lib.parseFunc_RTE" in the current TypoScript template.
1327 *
1328 * @param string $str The input text string to process
1329 * @return string The processed string
1330 * @see ContentObjectRenderer::parseFunc()
1331 */
1332 public function pi_RTEcssText($str)
1333 {
1334 $parseFunc = $this->frontendController->tmpl->setup['lib.']['parseFunc_RTE.'];
1335 if (is_array($parseFunc)) {
1336 $str = $this->cObj->parseFunc($str, $parseFunc);
1337 }
1338 return $str;
1339 }
1340
1341 /*******************************
1342 *
1343 * FlexForms related functions
1344 *
1345 *******************************/
1346 /**
1347 * Converts $this->cObj->data['pi_flexform'] from XML string to flexForm array.
1348 *
1349 * @param string $field Field name to convert
1350 */
1351 public function pi_initPIflexForm($field = 'pi_flexform')
1352 {
1353 // Converting flexform data into array:
1354 if (!is_array($this->cObj->data[$field]) && $this->cObj->data[$field]) {
1355 $this->cObj->data[$field] = GeneralUtility::xml2array($this->cObj->data[$field]);
1356 if (!is_array($this->cObj->data[$field])) {
1357 $this->cObj->data[$field] = [];
1358 }
1359 }
1360 }
1361
1362 /**
1363 * Return value from somewhere inside a FlexForm structure
1364 *
1365 * @param array $T3FlexForm_array FlexForm data
1366 * @param string $fieldName Field name to extract. Can be given like "test/el/2/test/el/field_templateObject" where each part will dig a level deeper in the FlexForm data.
1367 * @param string $sheet Sheet pointer, eg. "sDEF
1368 * @param string $lang Language pointer, eg. "lDEF
1369 * @param string $value Value pointer, eg. "vDEF
1370 * @return string|null The content.
1371 */
1372 public function pi_getFFvalue($T3FlexForm_array, $fieldName, $sheet = 'sDEF', $lang = 'lDEF', $value = 'vDEF')
1373 {
1374 $sheetArray = is_array($T3FlexForm_array) ? $T3FlexForm_array['data'][$sheet][$lang] : '';
1375 if (is_array($sheetArray)) {
1376 return $this->pi_getFFvalueFromSheetArray($sheetArray, explode('/', $fieldName), $value);
1377 }
1378 return null;
1379 }
1380
1381 /**
1382 * Returns part of $sheetArray pointed to by the keys in $fieldNameArray
1383 *
1384 * @param array $sheetArray Multidimensiona array, typically FlexForm contents
1385 * @param array $fieldNameArr Array where each value points to a key in the FlexForms content - the input array will have the value returned pointed to by these keys. All integer keys will not take their integer counterparts, but rather traverse the current position in the array an return element number X (whether this is right behavior is not settled yet...)
1386 * @param string $value Value for outermost key, typ. "vDEF" depending on language.
1387 * @return mixed The value, typ. string.
1388 * @internal
1389 * @see pi_getFFvalue()
1390 */
1391 public function pi_getFFvalueFromSheetArray($sheetArray, $fieldNameArr, $value)
1392 {
1393 $tempArr = $sheetArray;
1394 foreach ($fieldNameArr as $k => $v) {
1395 if (MathUtility::canBeInterpretedAsInteger($v)) {
1396 if (is_array($tempArr)) {
1397 $c = 0;
1398 foreach ($tempArr as $values) {
1399 if ($c == $v) {
1400 $tempArr = $values;
1401 break;
1402 }
1403 $c++;
1404 }
1405 }
1406 } else {
1407 $tempArr = $tempArr[$v];
1408 }
1409 }
1410 return $tempArr[$value];
1411 }
1412
1413 /**
1414 * Returns the currently configured "site language" if a site is configured (= resolved) in the current request.
1415 *
1416 * @internal
1417 */
1418 protected function getCurrentSiteLanguage(): ?SiteLanguage
1419 {
1420 $request = $GLOBALS['TYPO3_REQUEST'] ?? null;
1421 return $request
1422 && $request instanceof ServerRequestInterface
1423 && $request->getAttribute('language') instanceof SiteLanguage
1424 ? $request->getAttribute('language')
1425 : null;
1426 }
1427 }