[!!!][TASK] Remove config.language_alt and config.language
[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 $this->LLkey = $this->getCurrentSiteLanguage()->getTypo3Language();
267
268 /** @var Locales $locales */
269 $locales = GeneralUtility::makeInstance(Locales::class);
270 if (in_array($this->LLkey, $locales->getLocales())) {
271 foreach ($locales->getLocaleDependencies($this->LLkey) as $language) {
272 $this->altLLkey .= $language . ',';
273 }
274 $this->altLLkey = rtrim($this->altLLkey, ',');
275 }
276 }
277
278 /**
279 * Recursively looks for stdWrap and executes it
280 *
281 * @param array $conf Current section of configuration to work on
282 * @param int $level Current level being processed (currently just for tracking; no limit enforced)
283 * @return array Current section of configuration after stdWrap applied
284 */
285 protected function applyStdWrapRecursive(array $conf, $level = 0)
286 {
287 foreach ($conf as $key => $confNextLevel) {
288 if (strpos($key, '.') !== false) {
289 $key = substr($key, 0, -1);
290
291 // descend into all non-stdWrap-subelements first
292 foreach ($confNextLevel as $subKey => $subConfNextLevel) {
293 if (is_array($subConfNextLevel) && strpos($subKey, '.') !== false && $subKey !== 'stdWrap.') {
294 $conf[$key . '.'] = $this->applyStdWrapRecursive($confNextLevel, $level + 1);
295 }
296 }
297
298 // now for stdWrap
299 foreach ($confNextLevel as $subKey => $subConfNextLevel) {
300 if (is_array($subConfNextLevel) && $subKey === 'stdWrap.') {
301 $conf[$key] = $this->cObj->stdWrap($conf[$key] ?? '', $conf[$key . '.']['stdWrap.'] ?? []);
302 unset($conf[$key . '.']['stdWrap.']);
303 if (empty($conf[$key . '.'])) {
304 unset($conf[$key . '.']);
305 }
306 }
307 }
308 }
309 }
310 return $conf;
311 }
312
313 /**
314 * If internal TypoScript property "_DEFAULT_PI_VARS." is set then it will merge the current $this->piVars array onto these default values.
315 */
316 public function pi_setPiVarDefaults()
317 {
318 if (isset($this->conf['_DEFAULT_PI_VARS.']) && is_array($this->conf['_DEFAULT_PI_VARS.'])) {
319 $this->conf['_DEFAULT_PI_VARS.'] = $this->applyStdWrapRecursive($this->conf['_DEFAULT_PI_VARS.']);
320 $tmp = $this->conf['_DEFAULT_PI_VARS.'];
321 ArrayUtility::mergeRecursiveWithOverrule($tmp, is_array($this->piVars) ? $this->piVars : []);
322 $this->piVars = $tmp;
323 }
324 }
325
326 /***************************
327 *
328 * Link functions
329 *
330 **************************/
331 /**
332 * Get URL to some page.
333 * Returns the URL to page $id with $target and an array of additional url-parameters, $urlParameters
334 * Simple example: $this->pi_getPageLink(123) to get the URL for page-id 123.
335 *
336 * The function basically calls $this->cObj->getTypoLink_URL()
337 *
338 * @param int $id Page id
339 * @param string $target Target value to use. Affects the &type-value of the URL, defaults to current.
340 * @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.
341 * @return string The resulting URL
342 * @see pi_linkToPage()
343 * @see ContentObjectRenderer->getTypoLink()
344 */
345 public function pi_getPageLink($id, $target = '', $urlParameters = [])
346 {
347 return $this->cObj->getTypoLink_URL($id, $urlParameters, $target);
348 }
349
350 /**
351 * Link a string to some page.
352 * Like pi_getPageLink() but takes a string as first parameter which will in turn be wrapped with the URL including target attribute
353 * Simple example: $this->pi_linkToPage('My link', 123) to get something like <a href="index.php?id=123&type=1">My link</a>
354 *
355 * @param string $str The content string to wrap in <a> tags
356 * @param int $id Page id
357 * @param string $target Target value to use. Affects the &type-value of the URL, defaults to current.
358 * @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.
359 * @return string The input string wrapped in <a> tags with the URL and target set.
360 * @see pi_getPageLink(), ContentObjectRenderer::getTypoLink()
361 */
362 public function pi_linkToPage($str, $id, $target = '', $urlParameters = [])
363 {
364 return $this->cObj->getTypoLink($str, $id, $urlParameters, $target);
365 }
366
367 /**
368 * Link string to the current page.
369 * Returns the $str wrapped in <a>-tags with a link to the CURRENT page, but with $urlParameters set as extra parameters for the page.
370 *
371 * @param string $str The content string to wrap in <a> tags
372 * @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.
373 * @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.
374 * @param int $altPageId Alternative page ID for the link. (By default this function links to the SAME page!)
375 * @return string The input string wrapped in <a> tags
376 * @see pi_linkTP_keepPIvars(), ContentObjectRenderer::typoLink()
377 */
378 public function pi_linkTP($str, $urlParameters = [], $cache = false, $altPageId = 0)
379 {
380 $conf = [];
381 $conf['no_cache'] = $this->pi_USER_INT_obj ? 0 : !$cache;
382 $conf['parameter'] = $altPageId ? $altPageId : ($this->pi_tmpPageId ? $this->pi_tmpPageId : $this->frontendController->id);
383 $conf['additionalParams'] = $this->conf['parent.']['addParams'] . HttpUtility::buildQueryString($urlParameters, '&', true) . $this->pi_moreParams;
384 return $this->cObj->typoLink($str, $conf);
385 }
386
387 /**
388 * Link a string to the current page while keeping currently set values in piVars.
389 * Like pi_linkTP, but $urlParameters is by default set to $this->piVars with $overrulePIvars overlaid.
390 * 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.
391 *
392 * @param string $str The content string to wrap in <a> tags
393 * @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)
394 * @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.
395 * @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[]
396 * @param int $altPageId Alternative page ID for the link. (By default this function links to the SAME page!)
397 * @return string The input string wrapped in <a> tags
398 * @see pi_linkTP()
399 */
400 public function pi_linkTP_keepPIvars($str, $overrulePIvars = [], $cache = false, $clearAnyway = false, $altPageId = 0)
401 {
402 if (is_array($this->piVars) && is_array($overrulePIvars) && !$clearAnyway) {
403 $piVars = $this->piVars;
404 unset($piVars['DATA']);
405 ArrayUtility::mergeRecursiveWithOverrule($piVars, $overrulePIvars);
406 $overrulePIvars = $piVars;
407 if ($this->pi_autoCacheEn) {
408 $cache = $this->pi_autoCache($overrulePIvars);
409 }
410 }
411 return $this->pi_linkTP($str, [$this->prefixId => $overrulePIvars], $cache, $altPageId);
412 }
413
414 /**
415 * Get URL to the current page while keeping currently set values in piVars.
416 * Same as pi_linkTP_keepPIvars but returns only the URL from the link.
417 *
418 * @param array $overrulePIvars See pi_linkTP_keepPIvars
419 * @param bool $cache See pi_linkTP_keepPIvars
420 * @param bool $clearAnyway See pi_linkTP_keepPIvars
421 * @param int $altPageId See pi_linkTP_keepPIvars
422 * @return string The URL ($this->cObj->lastTypoLinkUrl)
423 * @see pi_linkTP_keepPIvars()
424 */
425 public function pi_linkTP_keepPIvars_url($overrulePIvars = [], $cache = false, $clearAnyway = false, $altPageId = 0)
426 {
427 $this->pi_linkTP_keepPIvars('|', $overrulePIvars, $cache, $clearAnyway, $altPageId);
428 return $this->cObj->lastTypoLinkUrl;
429 }
430
431 /**
432 * Wraps the $str in a link to a single display of the record (using piVars[showUid])
433 * Uses pi_linkTP for the linking
434 *
435 * @param string $str The content string to wrap in <a> tags
436 * @param int $uid UID of the record for which to display details (basically this will become the value of [showUid]
437 * @param bool $cache See pi_linkTP_keepPIvars
438 * @param array $mergeArr Array of values to override in the current piVars. Same as $overrulePIvars in pi_linkTP_keepPIvars
439 * @param bool $urlOnly If TRUE, only the URL is returned, not a full link
440 * @param int $altPageId Alternative page ID for the link. (By default this function links to the SAME page!)
441 * @return string The input string wrapped in <a> tags
442 * @see pi_linkTP(), pi_linkTP_keepPIvars()
443 */
444 public function pi_list_linkSingle($str, $uid, $cache = false, $mergeArr = [], $urlOnly = false, $altPageId = 0)
445 {
446 if ($this->prefixId) {
447 if ($cache) {
448 $overrulePIvars = $uid ? ['showUid' => $uid] : [];
449 $overrulePIvars = array_merge($overrulePIvars, (array)$mergeArr);
450 $str = $this->pi_linkTP($str, [$this->prefixId => $overrulePIvars], $cache, $altPageId);
451 } else {
452 $overrulePIvars = ['showUid' => $uid ?: ''];
453 $overrulePIvars = array_merge($overrulePIvars, (array)$mergeArr);
454 $str = $this->pi_linkTP_keepPIvars($str, $overrulePIvars, $cache, 0, $altPageId);
455 }
456 // If urlOnly flag, return only URL as it has recently be generated.
457 if ($urlOnly) {
458 $str = $this->cObj->lastTypoLinkUrl;
459 }
460 }
461 return $str;
462 }
463
464 /**
465 * 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
466 *
467 * @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.
468 * @param string $winName Window name for the pop-up window
469 * @param string $winParams Window parameters, see the default list for inspiration
470 * @return string The processed input string, modified IF a <a> tag was found
471 */
472 public function pi_openAtagHrefInJSwindow($str, $winName = '', $winParams = 'width=670,height=500,status=0,menubar=0,scrollbars=1,resizable=1')
473 {
474 if (preg_match('/(.*)(<a[^>]*>)(.*)/i', $str, $match)) {
475 $aTagContent = GeneralUtility::get_tag_attributes($match[2]);
476 $onClick = 'vHWin=window.open('
477 . GeneralUtility::quoteJSvalue($this->frontendController->baseUrlWrap($aTagContent['href'])) . ','
478 . GeneralUtility::quoteJSvalue($winName ?: md5($aTagContent['href'])) . ','
479 . GeneralUtility::quoteJSvalue($winParams) . ');vHWin.focus();return false;';
480 $match[2] = '<a href="#" onclick="' . htmlspecialchars($onClick) . '">';
481 $str = $match[1] . $match[2] . $match[3];
482 }
483 return $str;
484 }
485
486 /***************************
487 *
488 * Functions for listing, browsing, searching etc.
489 *
490 **************************/
491 /**
492 * 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.
493 * 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)
494 * 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.
495 * Using $this->internal['dontLinkActivePage'] as switch if the active (current) page should be displayed as pure text or as a link to itself
496 * 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.
497 * 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.
498 * 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...
499 * 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.
500 *
501 * The third parameter is an array with several wraps for the parts of the pagebrowser. The following elements will be recognized:
502 * disabledLinkWrap, inactiveLinkWrap, activeLinkWrap, browseLinksWrap, showResultsWrap, showResultsNumbersWrap, browseBoxWrap.
503 *
504 * If $wrapArr['showResultsNumbersWrap'] is set, the formatting string is expected to hold template markers (###FROM###, ###TO###, ###OUT_OF###, ###FROM_TO###, ###CURRENT_PAGE###, ###TOTAL_PAGES###)
505 * otherwise the formatting string is expected to hold sprintf-markers (%s) for from, to, outof (in that sequence)
506 *
507 * @param int $showResultCount Determines how the results of the page browser will be shown. See description below
508 * @param string $tableParams Attributes for the table tag which is wrapped around the table cells containing the browse links
509 * @param array $wrapArr Array with elements to overwrite the default $wrapper-array.
510 * @param string $pointerName varname for the pointer.
511 * @param bool $hscText Enable htmlspecialchars() on language labels
512 * @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)
513 * @return string Output HTML-Table, wrapped in <div>-tags with a class attribute (if $wrapArr is not passed,
514 */
515 public function pi_list_browseresults($showResultCount = 1, $tableParams = '', $wrapArr = [], $pointerName = 'pointer', $hscText = true, $forceOutput = false)
516 {
517 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][self::class]['pi_list_browseresults'] ?? [] as $classRef) {
518 $hookObj = GeneralUtility::makeInstance($classRef);
519 if (method_exists($hookObj, 'pi_list_browseresults')) {
520 $pageBrowser = $hookObj->pi_list_browseresults($showResultCount, $tableParams, $wrapArr, $pointerName, $hscText, $forceOutput, $this);
521 if (is_string($pageBrowser) && trim($pageBrowser) !== '') {
522 return $pageBrowser;
523 }
524 }
525 }
526 // example $wrapArr-array how it could be traversed from an extension
527 /* $wrapArr = array(
528 'browseBoxWrap' => '<div class="browseBoxWrap">|</div>',
529 'showResultsWrap' => '<div class="showResultsWrap">|</div>',
530 'browseLinksWrap' => '<div class="browseLinksWrap">|</div>',
531 'showResultsNumbersWrap' => '<span class="showResultsNumbersWrap">|</span>',
532 'disabledLinkWrap' => '<span class="disabledLinkWrap">|</span>',
533 'inactiveLinkWrap' => '<span class="inactiveLinkWrap">|</span>',
534 'activeLinkWrap' => '<span class="activeLinkWrap">|</span>'
535 );*/
536 // Initializing variables:
537 $pointer = (int)$this->piVars[$pointerName];
538 $count = (int)$this->internal['res_count'];
539 $results_at_a_time = MathUtility::forceIntegerInRange($this->internal['results_at_a_time'], 1, 1000);
540 $totalPages = ceil($count / $results_at_a_time);
541 $maxPages = MathUtility::forceIntegerInRange($this->internal['maxPages'], 1, 100);
542 $pi_isOnlyFields = $this->pi_isOnlyFields($this->pi_isOnlyFields);
543 if (!$forceOutput && $count <= $results_at_a_time) {
544 return '';
545 }
546 // $showResultCount determines how the results of the pagerowser will be shown.
547 // If set to 0: only the result-browser will be shown
548 // 1: (default) the text "Displaying results..." and the result-browser will be shown.
549 // 2: only the text "Displaying results..." will be shown
550 $showResultCount = (int)$showResultCount;
551 // If this is set, two links named "<< First" and "LAST >>" will be shown and point to the very first or last page.
552 $showFirstLast = !empty($this->internal['showFirstLast']);
553 // If this has a value the "previous" button is always visible (will be forced if "showFirstLast" is set)
554 $alwaysPrev = $showFirstLast ? 1 : $this->pi_alwaysPrev;
555 if (isset($this->internal['pagefloat'])) {
556 if (strtoupper($this->internal['pagefloat']) === 'CENTER') {
557 $pagefloat = ceil(($maxPages - 1) / 2);
558 } else {
559 // pagefloat set as integer. 0 = left, value >= $this->internal['maxPages'] = right
560 $pagefloat = MathUtility::forceIntegerInRange($this->internal['pagefloat'], -1, $maxPages - 1);
561 }
562 } else {
563 // pagefloat disabled
564 $pagefloat = -1;
565 }
566 // Default values for "traditional" wrapping with a table. Can be overwritten by vars from $wrapArr
567 $wrapper['disabledLinkWrap'] = '<td class="nowrap"><p>|</p></td>';
568 $wrapper['inactiveLinkWrap'] = '<td class="nowrap"><p>|</p></td>';
569 $wrapper['activeLinkWrap'] = '<td' . $this->pi_classParam('browsebox-SCell') . ' class="nowrap"><p>|</p></td>';
570 $wrapper['browseLinksWrap'] = rtrim('<table ' . $tableParams) . '><tr>|</tr></table>';
571 $wrapper['showResultsWrap'] = '<p>|</p>';
572 $wrapper['browseBoxWrap'] = '
573 <!--
574 List browsing box:
575 -->
576 <div ' . $this->pi_classParam('browsebox') . '>
577 |
578 </div>';
579 // Now overwrite all entries in $wrapper which are also in $wrapArr
580 $wrapper = array_merge($wrapper, $wrapArr);
581 // Show pagebrowser
582 if ($showResultCount != 2) {
583 if ($pagefloat > -1) {
584 $lastPage = min($totalPages, max($pointer + 1 + $pagefloat, $maxPages));
585 $firstPage = max(0, $lastPage - $maxPages);
586 } else {
587 $firstPage = 0;
588 $lastPage = MathUtility::forceIntegerInRange($totalPages, 1, $maxPages);
589 }
590 $links = [];
591 // Make browse-table/links:
592 // Link to first page
593 if ($showFirstLast) {
594 if ($pointer > 0) {
595 $label = $this->pi_getLL('pi_list_browseresults_first', '<< First');
596 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($hscText ? htmlspecialchars($label) : $label, [$pointerName => null], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
597 } else {
598 $label = $this->pi_getLL('pi_list_browseresults_first', '<< First');
599 $links[] = $this->cObj->wrap($hscText ? htmlspecialchars($label) : $label, $wrapper['disabledLinkWrap']);
600 }
601 }
602 // Link to previous page
603 if ($alwaysPrev >= 0) {
604 if ($pointer > 0) {
605 $label = $this->pi_getLL('pi_list_browseresults_prev', '< Previous');
606 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($hscText ? htmlspecialchars($label) : $label, [$pointerName => ($pointer - 1) ?: ''], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
607 } elseif ($alwaysPrev) {
608 $label = $this->pi_getLL('pi_list_browseresults_prev', '< Previous');
609 $links[] = $this->cObj->wrap($hscText ? htmlspecialchars($label) : $label, $wrapper['disabledLinkWrap']);
610 }
611 }
612 // Links to pages
613 for ($a = $firstPage; $a < $lastPage; $a++) {
614 if ($this->internal['showRange']) {
615 $pageText = ($a * $results_at_a_time + 1) . '-' . min($count, ($a + 1) * $results_at_a_time);
616 } else {
617 $label = $this->pi_getLL('pi_list_browseresults_page', 'Page');
618 $pageText = trim(($hscText ? htmlspecialchars($label) : $label) . ' ' . ($a + 1));
619 }
620 // Current page
621 if ($pointer == $a) {
622 if ($this->internal['dontLinkActivePage']) {
623 $links[] = $this->cObj->wrap($pageText, $wrapper['activeLinkWrap']);
624 } else {
625 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($pageText, [$pointerName => $a ?: ''], $pi_isOnlyFields), $wrapper['activeLinkWrap']);
626 }
627 } else {
628 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($pageText, [$pointerName => $a ?: ''], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
629 }
630 }
631 if ($pointer < $totalPages - 1 || $showFirstLast) {
632 // Link to next page
633 if ($pointer >= $totalPages - 1) {
634 $label = $this->pi_getLL('pi_list_browseresults_next', 'Next >');
635 $links[] = $this->cObj->wrap($hscText ? htmlspecialchars($label) : $label, $wrapper['disabledLinkWrap']);
636 } else {
637 $label = $this->pi_getLL('pi_list_browseresults_next', 'Next >');
638 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($hscText ? htmlspecialchars($label) : $label, [$pointerName => $pointer + 1], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
639 }
640 }
641 // Link to last page
642 if ($showFirstLast) {
643 if ($pointer < $totalPages - 1) {
644 $label = $this->pi_getLL('pi_list_browseresults_last', 'Last >>');
645 $links[] = $this->cObj->wrap($this->pi_linkTP_keepPIvars($hscText ? htmlspecialchars($label) : $label, [$pointerName => $totalPages - 1], $pi_isOnlyFields), $wrapper['inactiveLinkWrap']);
646 } else {
647 $label = $this->pi_getLL('pi_list_browseresults_last', 'Last >>');
648 $links[] = $this->cObj->wrap($hscText ? htmlspecialchars($label) : $label, $wrapper['disabledLinkWrap']);
649 }
650 }
651 $theLinks = $this->cObj->wrap(implode(LF, $links), $wrapper['browseLinksWrap']);
652 } else {
653 $theLinks = '';
654 }
655 $pR1 = $pointer * $results_at_a_time + 1;
656 $pR2 = $pointer * $results_at_a_time + $results_at_a_time;
657 if ($showResultCount) {
658 if ($wrapper['showResultsNumbersWrap']) {
659 // This will render the resultcount in a more flexible way using markers (new in TYPO3 3.8.0).
660 // The formatting string is expected to hold template markers (see function header). Example: 'Displaying results ###FROM### to ###TO### out of ###OUT_OF###'
661 $markerArray['###FROM###'] = $this->cObj->wrap($this->internal['res_count'] > 0 ? $pR1 : 0, $wrapper['showResultsNumbersWrap']);
662 $markerArray['###TO###'] = $this->cObj->wrap(min($this->internal['res_count'], $pR2), $wrapper['showResultsNumbersWrap']);
663 $markerArray['###OUT_OF###'] = $this->cObj->wrap($this->internal['res_count'], $wrapper['showResultsNumbersWrap']);
664 $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']);
665 $markerArray['###CURRENT_PAGE###'] = $this->cObj->wrap($pointer + 1, $wrapper['showResultsNumbersWrap']);
666 $markerArray['###TOTAL_PAGES###'] = $this->cObj->wrap($totalPages, $wrapper['showResultsNumbersWrap']);
667 // Substitute markers
668 $resultCountMsg = $this->templateService->substituteMarkerArray($this->pi_getLL('pi_list_browseresults_displays', 'Displaying results ###FROM### to ###TO### out of ###OUT_OF###'), $markerArray);
669 } else {
670 // Render the resultcount in the "traditional" way using sprintf
671 $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);
672 }
673 $resultCountMsg = $this->cObj->wrap($resultCountMsg, $wrapper['showResultsWrap']);
674 } else {
675 $resultCountMsg = '';
676 }
677 $sTables = $this->cObj->wrap($resultCountMsg . $theLinks, $wrapper['browseBoxWrap']);
678 return $sTables;
679 }
680
681 /**
682 * Returns a mode selector; a little menu in a table normally put in the top of the page/list.
683 *
684 * @param array $items Key/Value pairs for the menu; keys are the piVars[mode] values and the "values" are the labels for them.
685 * @param string $tableParams Attributes for the table tag which is wrapped around the table cells containing the menu
686 * @return string Output HTML, wrapped in <div>-tags with a class attribute
687 */
688 public function pi_list_modeSelector($items = [], $tableParams = '')
689 {
690 $cells = [];
691 foreach ($items as $k => $v) {
692 $cells[] = '
693 <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>';
694 }
695 $sTables = '
696
697 <!--
698 Mode selector (menu for list):
699 -->
700 <div' . $this->pi_classParam('modeSelector') . '>
701 <' . rtrim('table ' . $tableParams) . '>
702 <tr>
703 ' . implode('', $cells) . '
704 </tr>
705 </table>
706 </div>';
707 return $sTables;
708 }
709
710 /**
711 * Returns the list of items based on the input SQL result pointer
712 * For each result row the internal var, $this->internal['currentRow'], is set with the row returned.
713 * $this->pi_list_header() makes the header row for the list
714 * $this->pi_list_row() is used for rendering each row
715 * 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.
716 *
717 * @param Statement $statement Result pointer to a SQL result which can be traversed.
718 * @param string $tableParams Attributes for the table tag which is wrapped around the table rows containing the list
719 * @return string Output HTML, wrapped in <div>-tags with a class attribute
720 * @see pi_list_row(), pi_list_header()
721 */
722 public function pi_list_makelist($statement, $tableParams = '')
723 {
724 // Make list table header:
725 $tRows = [];
726 $this->internal['currentRow'] = '';
727 $tRows[] = $this->pi_list_header();
728 // Make list table rows
729 $c = 0;
730 while ($this->internal['currentRow'] = $statement->fetch()) {
731 $tRows[] = $this->pi_list_row($c);
732 $c++;
733 }
734 $out = '
735
736 <!--
737 Record list:
738 -->
739 <div' . $this->pi_classParam('listrow') . '>
740 <' . rtrim('table ' . $tableParams) . '>
741 ' . implode('', $tRows) . '
742 </table>
743 </div>';
744 return $out;
745 }
746
747 /**
748 * Returns a list row. Get data from $this->internal['currentRow'];
749 * (Dummy)
750 * 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.
751 *
752 * @param int $c Row counting. Starts at 0 (zero). Used for alternating class values in the output rows.
753 * @return string HTML output, a table row with a class attribute set (alternative based on odd/even rows)
754 */
755 public function pi_list_row($c)
756 {
757 // Dummy
758 return '<tr' . ($c % 2 ? $this->pi_classParam('listrow-odd') : '') . '><td><p>[dummy row]</p></td></tr>';
759 }
760
761 /**
762 * Returns a list header row.
763 * (Dummy)
764 * 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.
765 *
766 * @return string HTML output, a table row with a class attribute set
767 */
768 public function pi_list_header()
769 {
770 return '<tr' . $this->pi_classParam('listrow-header') . '><td><p>[dummy header row]</p></td></tr>';
771 }
772
773 /***************************
774 *
775 * Stylesheet, CSS
776 *
777 **************************/
778 /**
779 * Returns a class-name prefixed with $this->prefixId and with all underscores substituted to dashes (-)
780 *
781 * @param string $class The class name (or the END of it since it will be prefixed by $this->prefixId.'-')
782 * @return string The combined class name (with the correct prefix)
783 */
784 public function pi_getClassName($class)
785 {
786 return str_replace('_', '-', $this->prefixId) . ($this->prefixId ? '-' : '') . $class;
787 }
788
789 /**
790 * Returns the class-attribute with the correctly prefixed classname
791 * Using pi_getClassName()
792 *
793 * @param string $class The class name(s) (suffix) - separate multiple classes with commas
794 * @param string $addClasses Additional class names which should not be prefixed - separate multiple classes with commas
795 * @return string A "class" attribute with value and a single space char before it.
796 * @see pi_getClassName()
797 */
798 public function pi_classParam($class, $addClasses = '')
799 {
800 $output = '';
801 $classNames = GeneralUtility::trimExplode(',', $class);
802 foreach ($classNames as $className) {
803 $output .= ' ' . $this->pi_getClassName($className);
804 }
805 $additionalClassNames = GeneralUtility::trimExplode(',', $addClasses);
806 foreach ($additionalClassNames as $additionalClassName) {
807 $output .= ' ' . $additionalClassName;
808 }
809 return ' class="' . trim($output) . '"';
810 }
811
812 /**
813 * Wraps the input string in a <div> tag with the class attribute set to the prefixId.
814 * 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.
815 *
816 * @param string $str HTML content to wrap in the div-tags with the "main class" of the plugin
817 * @return string HTML content wrapped, ready to return to the parent object.
818 */
819 public function pi_wrapInBaseClass($str)
820 {
821 $content = '<div class="' . str_replace('_', '-', $this->prefixId) . '">
822 ' . $str . '
823 </div>
824 ';
825 if (!$this->frontendController->config['config']['disablePrefixComment']) {
826 $content = '
827
828
829 <!--
830
831 BEGIN: Content of extension "' . $this->extKey . '", plugin "' . $this->prefixId . '"
832
833 -->
834 ' . $content . '
835 <!-- END: Content of extension "' . $this->extKey . '", plugin "' . $this->prefixId . '" -->
836
837 ';
838 }
839 return $content;
840 }
841
842 /***************************
843 *
844 * Frontend editing: Edit panel, edit icons
845 *
846 **************************/
847 /**
848 * Returns the Backend User edit panel for the $row from $tablename
849 *
850 * @param array $row Record array.
851 * @param string $tablename Table name
852 * @param string $label A label to show with the panel.
853 * @param array $conf TypoScript parameters to pass along to the EDITPANEL content Object that gets rendered. The property "allow" WILL get overridden/set though.
854 * @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).
855 * @see ContentObjectRenderer::EDITPANEL()
856 */
857 public function pi_getEditPanel($row = [], $tablename = '', $label = '', $conf = [])
858 {
859 $panel = '';
860 if (!$row || !$tablename) {
861 $row = $this->internal['currentRow'];
862 $tablename = $this->internal['currentTable'];
863 }
864 if ($this->frontendController->isBackendUserLoggedIn()) {
865 // Create local cObj if not set:
866 if (!is_object($this->pi_EPtemp_cObj)) {
867 $this->pi_EPtemp_cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
868 $this->pi_EPtemp_cObj->setParent($this->cObj->data, $this->cObj->currentRecord);
869 }
870 // Initialize the cObj object with current row
871 $this->pi_EPtemp_cObj->start($row, $tablename);
872 // Setting TypoScript values in the $conf array. See documentation in TSref for the EDITPANEL cObject.
873 $conf['allow'] = 'edit,new,delete,move,hide';
874 $panel = $this->pi_EPtemp_cObj->cObjGetSingle('EDITPANEL', $conf, 'editpanel');
875 }
876 if ($panel) {
877 if ($label) {
878 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 -->';
879 }
880 return '<!-- BEGIN: EDIT PANEL -->' . $panel . '<!-- END: EDIT PANEL -->';
881 }
882 return $label;
883 }
884
885 /**
886 * Adds edit-icons to the input content.
887 * ContentObjectRenderer::editIcons used for rendering
888 *
889 * @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)
890 * @param string $fields The list of fields to edit when the icon is clicked.
891 * @param string $title Title for the edit icon.
892 * @param array $row Table record row
893 * @param string $tablename Table name
894 * @param array $oConf Conf array
895 * @return string The processed content
896 * @see ContentObjectRenderer::editIcons()
897 */
898 public function pi_getEditIcon($content, $fields, $title = '', $row = [], $tablename = '', $oConf = [])
899 {
900 if ($this->frontendController->isBackendUserLoggedIn()) {
901 if (!$row || !$tablename) {
902 $row = $this->internal['currentRow'];
903 $tablename = $this->internal['currentTable'];
904 }
905 $conf = array_merge([
906 'beforeLastTag' => 1,
907 'iconTitle' => $title
908 ], $oConf);
909 $content = $this->cObj->editIcons($content, $tablename . ':' . $fields, $conf, $tablename . ':' . $row['uid'], $row, '&viewUrl=' . rawurlencode(GeneralUtility::getIndpEnv('REQUEST_URI')));
910 }
911 return $content;
912 }
913
914 /***************************
915 *
916 * Localization, locallang functions
917 *
918 **************************/
919 /**
920 * Returns the localized label of the LOCAL_LANG key, $key
921 * Notice that for debugging purposes prefixes for the output values can be set with the internal vars ->LLtestPrefixAlt and ->LLtestPrefix
922 *
923 * @param string $key The key from the LOCAL_LANG array for which to return the value.
924 * @param string $alternativeLabel Alternative string to return IF no value is found set for the key, neither for the local language nor the default.
925 * @return string The value from LOCAL_LANG.
926 */
927 public function pi_getLL($key, $alternativeLabel = '')
928 {
929 $word = null;
930 if (!empty($this->LOCAL_LANG[$this->LLkey][$key][0]['target'])
931 || isset($this->LOCAL_LANG_UNSET[$this->LLkey][$key])
932 ) {
933 $word = $this->LOCAL_LANG[$this->LLkey][$key][0]['target'];
934 } elseif ($this->altLLkey) {
935 $alternativeLanguageKeys = GeneralUtility::trimExplode(',', $this->altLLkey, true);
936 $alternativeLanguageKeys = array_reverse($alternativeLanguageKeys);
937 foreach ($alternativeLanguageKeys as $languageKey) {
938 if (!empty($this->LOCAL_LANG[$languageKey][$key][0]['target'])
939 || isset($this->LOCAL_LANG_UNSET[$languageKey][$key])
940 ) {
941 // Alternative language translation for key exists
942 $word = $this->LOCAL_LANG[$languageKey][$key][0]['target'];
943 break;
944 }
945 }
946 }
947 if ($word === null) {
948 if (!empty($this->LOCAL_LANG['default'][$key][0]['target'])
949 || isset($this->LOCAL_LANG_UNSET['default'][$key])
950 ) {
951 // Get default translation (without charset conversion, english)
952 $word = $this->LOCAL_LANG['default'][$key][0]['target'];
953 } else {
954 // Return alternative string or empty
955 $word = isset($this->LLtestPrefixAlt) ? $this->LLtestPrefixAlt . $alternativeLabel : $alternativeLabel;
956 }
957 }
958 return isset($this->LLtestPrefix) ? $this->LLtestPrefix . $word : $word;
959 }
960
961 /**
962 * Loads local-language values from the file passed as a parameter or
963 * by looking for a "locallang" file in the
964 * plugin class directory ($this->scriptRelPath).
965 * Also locallang values set in the TypoScript property "_LOCAL_LANG" are
966 * merged onto the values found in the "locallang" file.
967 * Supported file extensions xlf, xml
968 *
969 * @param string $languageFilePath path to the plugin language file in format EXT:....
970 */
971 public function pi_loadLL($languageFilePath = '')
972 {
973 if ($this->LOCAL_LANG_loaded) {
974 return;
975 }
976
977 if ($languageFilePath === '' && $this->scriptRelPath) {
978 $languageFilePath = 'EXT:' . $this->extKey . '/' . PathUtility::dirname($this->scriptRelPath) . '/locallang.xlf';
979 }
980 if ($languageFilePath !== '') {
981 /** @var LocalizationFactory $languageFactory */
982 $languageFactory = GeneralUtility::makeInstance(LocalizationFactory::class);
983 $this->LOCAL_LANG = $languageFactory->getParsedData($languageFilePath, $this->LLkey);
984 $alternativeLanguageKeys = GeneralUtility::trimExplode(',', $this->altLLkey, true);
985 foreach ($alternativeLanguageKeys as $languageKey) {
986 $tempLL = $languageFactory->getParsedData($languageFilePath, $languageKey);
987 if ($this->LLkey !== 'default' && isset($tempLL[$languageKey])) {
988 $this->LOCAL_LANG[$languageKey] = $tempLL[$languageKey];
989 }
990 }
991 // Overlaying labels from TypoScript (including fictitious language keys for non-system languages!):
992 if (isset($this->conf['_LOCAL_LANG.'])) {
993 // Clear the "unset memory"
994 $this->LOCAL_LANG_UNSET = [];
995 foreach ($this->conf['_LOCAL_LANG.'] as $languageKey => $languageArray) {
996 // Remove the dot after the language key
997 $languageKey = substr($languageKey, 0, -1);
998 // Don't process label if the language is not loaded
999 if (is_array($languageArray) && isset($this->LOCAL_LANG[$languageKey])) {
1000 foreach ($languageArray as $labelKey => $labelValue) {
1001 if (!is_array($labelValue)) {
1002 $this->LOCAL_LANG[$languageKey][$labelKey][0]['target'] = $labelValue;
1003 if ($labelValue === '') {
1004 $this->LOCAL_LANG_UNSET[$languageKey][$labelKey] = '';
1005 }
1006 }
1007 }
1008 }
1009 }
1010 }
1011 }
1012 $this->LOCAL_LANG_loaded = true;
1013 }
1014
1015 /***************************
1016 *
1017 * Database, queries
1018 *
1019 **************************/
1020 /**
1021 * 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'])
1022 * Set $count to 1 if you wish to get a count(*) query for selecting the number of results.
1023 * Notice that the query will use $this->conf['pidList'] and $this->conf['recursive'] to generate a PID list within which to search for records.
1024 *
1025 * @param string $table The table name to make the query for.
1026 * @param bool $count If set, you will get a "count(*)" query back instead of field selecting
1027 * @param string $addWhere Additional WHERE clauses (should be starting with " AND ....")
1028 * @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.
1029 * @param string $groupBy If set, this is added as a " GROUP BY ...." part of the query.
1030 * @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']
1031 * @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!
1032 * @return Statement
1033 */
1034 public function pi_exec_query($table, $count = false, $addWhere = '', $mm_cat = '', $groupBy = '', $orderBy = '', $query = '')
1035 {
1036 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1037 $queryBuilder->from($table);
1038
1039 // Begin Query:
1040 if (!$query) {
1041 // This adds WHERE-clauses that ensures deleted, hidden, starttime/endtime/access records are NOT
1042 // selected, if they should not! Almost ALWAYS add this to your queries!
1043 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1044
1045 // Fetches the list of PIDs to select from.
1046 // TypoScript property .pidList is a comma list of pids. If blank, current page id is used.
1047 // 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.
1048 $pidList = GeneralUtility::intExplode(',', $this->pi_getPidList($this->conf['pidList'], $this->conf['recursive']), true);
1049 if (is_array($mm_cat)) {
1050 $queryBuilder->from($mm_cat['table'])
1051 ->from($mm_cat['mmtable'])
1052 ->where(
1053 $queryBuilder->expr()->eq($table . '.uid', $queryBuilder->quoteIdentifier($mm_cat['mmtable'] . '.uid_local')),
1054 $queryBuilder->expr()->eq($mm_cat['table'] . '.uid', $queryBuilder->quoteIdentifier($mm_cat['mmtable'] . '.uid_foreign')),
1055 $queryBuilder->expr()->in(
1056 $table . '.pid',
1057 $queryBuilder->createNamedParameter($pidList, Connection::PARAM_INT_ARRAY)
1058 )
1059 );
1060 if (strcmp($mm_cat['catUidList'], '')) {
1061 $queryBuilder->andWhere(
1062 $queryBuilder->expr()->in(
1063 $mm_cat['table'] . '.uid',
1064 $queryBuilder->createNamedParameter(
1065 GeneralUtility::intExplode(',', $mm_cat['catUidList'], true),
1066 Connection::PARAM_INT_ARRAY
1067 )
1068 )
1069 );
1070 }
1071 } else {
1072 $queryBuilder->where(
1073 $queryBuilder->expr()->in(
1074 'pid',
1075 $queryBuilder->createNamedParameter($pidList, Connection::PARAM_INT_ARRAY)
1076 )
1077 );
1078 }
1079 } else {
1080 // Restrictions need to be handled by the $query parameter!
1081 $queryBuilder->getRestrictions()->removeAll();
1082
1083 // Split the "FROM ... WHERE" string so we get the WHERE part and TABLE names separated...:
1084 list($tableListFragment, $whereFragment) = preg_split('/WHERE/i', trim($query), 2);
1085 foreach (QueryHelper::parseTableList($tableListFragment) as $tableNameAndAlias) {
1086 list($tableName, $tableAlias) = $tableNameAndAlias;
1087 $queryBuilder->from($tableName, $tableAlias);
1088 }
1089 $queryBuilder->where(QueryHelper::stripLogicalOperatorPrefix($whereFragment));
1090 }
1091
1092 // Add '$addWhere'
1093 if ($addWhere) {
1094 $queryBuilder->andWhere(QueryHelper::stripLogicalOperatorPrefix($addWhere));
1095 }
1096 // Search word:
1097 if ($this->piVars['sword'] && $this->internal['searchFieldList']) {
1098 $queryBuilder->andWhere(
1099 QueryHelper::stripLogicalOperatorPrefix(
1100 $this->cObj->searchWhere($this->piVars['sword'], $this->internal['searchFieldList'], $table)
1101 )
1102 );
1103 }
1104
1105 if ($count) {
1106 $queryBuilder->count('*');
1107 } else {
1108 // Add 'SELECT'
1109 $fields = $this->pi_prependFieldsWithTable($table, $this->pi_listFields);
1110 $queryBuilder->select(...GeneralUtility::trimExplode(',', $fields, true));
1111
1112 // Order by data:
1113 if (!$orderBy && $this->internal['orderBy']) {
1114 if (GeneralUtility::inList($this->internal['orderByList'], $this->internal['orderBy'])) {
1115 $sorting = $this->internal['descFlag'] ? ' DESC' : 'ASC';
1116 $queryBuilder->orderBy($table . '.' . $this->internal['orderBy'], $sorting);
1117 }
1118 } elseif ($orderBy) {
1119 foreach (QueryHelper::parseOrderBy($orderBy) as $fieldNameAndSorting) {
1120 list($fieldName, $sorting) = $fieldNameAndSorting;
1121 $queryBuilder->addOrderBy($fieldName, $sorting);
1122 }
1123 }
1124
1125 // Limit data:
1126 $pointer = (int)$this->piVars['pointer'];
1127 $results_at_a_time = MathUtility::forceIntegerInRange($this->internal['results_at_a_time'], 1, 1000);
1128 $queryBuilder->setFirstResult($pointer * $results_at_a_time)
1129 ->setMaxResults($results_at_a_time);
1130
1131 // Grouping
1132 if (!empty($groupBy)) {
1133 $queryBuilder->groupBy(...QueryHelper::parseGroupBy($groupBy));
1134 }
1135 }
1136
1137 return $queryBuilder->execute();
1138 }
1139
1140 /**
1141 * Returns the row $uid from $table
1142 * (Simply calling $this->frontendEngine->sys_page->checkRecord())
1143 *
1144 * @param string $table The table name
1145 * @param int $uid The uid of the record from the table
1146 * @param bool $checkPage If $checkPage is set, it's required that the page on which the record resides is accessible
1147 * @return array If record is found, an array. Otherwise FALSE.
1148 */
1149 public function pi_getRecord($table, $uid, $checkPage = false)
1150 {
1151 return $this->frontendController->sys_page->checkRecord($table, $uid, $checkPage);
1152 }
1153
1154 /**
1155 * Returns a commalist of page ids for a query (eg. 'WHERE pid IN (...)')
1156 *
1157 * @param string $pid_list A comma list of page ids (if empty current page is used)
1158 * @param int $recursive An integer >=0 telling how deep to dig for pids under each entry in $pid_list
1159 * @return string List of PID values (comma separated)
1160 */
1161 public function pi_getPidList($pid_list, $recursive = 0)
1162 {
1163 if (!strcmp($pid_list, '')) {
1164 $pid_list = $this->frontendController->id;
1165 }
1166 $recursive = MathUtility::forceIntegerInRange($recursive, 0);
1167 $pid_list_arr = array_unique(GeneralUtility::trimExplode(',', $pid_list, true));
1168 $pid_list = [];
1169 foreach ($pid_list_arr as $val) {
1170 $val = MathUtility::forceIntegerInRange($val, 0);
1171 if ($val) {
1172 $_list = $this->cObj->getTreeList(-1 * $val, $recursive);
1173 if ($_list) {
1174 $pid_list[] = $_list;
1175 }
1176 }
1177 }
1178 return implode(',', $pid_list);
1179 }
1180
1181 /**
1182 * Having a comma list of fields ($fieldList) this is prepended with the $table.'.' name
1183 *
1184 * @param string $table Table name to prepend
1185 * @param string $fieldList List of fields where each element will be prepended with the table name given.
1186 * @return string List of fields processed.
1187 */
1188 public function pi_prependFieldsWithTable($table, $fieldList)
1189 {
1190 $list = GeneralUtility::trimExplode(',', $fieldList, true);
1191 $return = [];
1192 foreach ($list as $listItem) {
1193 $return[] = $table . '.' . $listItem;
1194 }
1195 return implode(',', $return);
1196 }
1197
1198 /**
1199 * Will select all records from the "category table", $table, and return them in an array.
1200 *
1201 * @param string $table The name of the category table to select from.
1202 * @param int $pid The page from where to select the category records.
1203 * @param string $whereClause Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
1204 * @param string $groupBy Optional GROUP BY field(s), if none, supply blank string.
1205 * @param string $orderBy Optional ORDER BY field(s), if none, supply blank string.
1206 * @param string $limit Optional LIMIT value ([begin,]max), if none, supply blank string.
1207 * @return array The array with the category records in.
1208 */
1209 public function pi_getCategoryTableContents($table, $pid, $whereClause = '', $groupBy = '', $orderBy = '', $limit = '')
1210 {
1211 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable($table);
1212 $queryBuilder->setRestrictions(GeneralUtility::makeInstance(FrontendRestrictionContainer::class));
1213 $queryBuilder->select('*')
1214 ->from($table)
1215 ->where(
1216 $queryBuilder->expr()->eq(
1217 'pid',
1218 $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
1219 ),
1220 QueryHelper::stripLogicalOperatorPrefix($whereClause)
1221 );
1222
1223 if (!empty($orderBy)) {
1224 foreach (QueryHelper::parseOrderBy($orderBy) as $fieldNameAndSorting) {
1225 list($fieldName, $sorting) = $fieldNameAndSorting;
1226 $queryBuilder->addOrderBy($fieldName, $sorting);
1227 }
1228 }
1229
1230 if (!empty($groupBy)) {
1231 $queryBuilder->groupBy(...QueryHelper::parseGroupBy($groupBy));
1232 }
1233
1234 if (!empty($limit)) {
1235 $limitValues = GeneralUtility::intExplode(',', $limit, true);
1236 if (count($limitValues) === 1) {
1237 $queryBuilder->setMaxResults($limitValues[0]);
1238 } else {
1239 $queryBuilder->setFirstResult($limitValues[0])
1240 ->setMaxResults($limitValues[1]);
1241 }
1242 }
1243
1244 $result = $queryBuilder->execute();
1245 $outArr = [];
1246 while ($row = $result->fetch()) {
1247 $outArr[$row['uid']] = $row;
1248 }
1249 return $outArr;
1250 }
1251
1252 /***************************
1253 *
1254 * Various
1255 *
1256 **************************/
1257 /**
1258 * 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.
1259 * Notice that this function will only work as long as values are integers.
1260 *
1261 * @param string $fList List of fields (keys from piVars) to evaluate on
1262 * @param int $lowerThan Limit for the values.
1263 * @return bool|null Returns TRUE (1) if conditions are met.
1264 */
1265 public function pi_isOnlyFields($fList, $lowerThan = -1)
1266 {
1267 $lowerThan = $lowerThan == -1 ? $this->pi_lowerThan : $lowerThan;
1268 $fList = GeneralUtility::trimExplode(',', $fList, true);
1269 $tempPiVars = $this->piVars;
1270 foreach ($fList as $k) {
1271 if (!MathUtility::canBeInterpretedAsInteger($tempPiVars[$k]) || $tempPiVars[$k] < $lowerThan) {
1272 unset($tempPiVars[$k]);
1273 }
1274 }
1275 if (empty($tempPiVars)) {
1276 //@TODO: How do we deal with this? return TRUE would be the right thing to do here but that might be breaking
1277 return 1;
1278 }
1279 return null;
1280 }
1281
1282 /**
1283 * Returns TRUE if the array $inArray contains only values allowed to be cached based on the configuration in $this->pi_autoCacheFields
1284 * Used by ->pi_linkTP_keepPIvars
1285 * This is an advanced form of evaluation of whether a URL should be cached or not.
1286 *
1287 * @param array $inArray An array with piVars values to evaluate
1288 * @return bool|null Returns TRUE (1) if conditions are met.
1289 * @see pi_linkTP_keepPIvars()
1290 */
1291 public function pi_autoCache($inArray)
1292 {
1293 if (is_array($inArray)) {
1294 foreach ($inArray as $fN => $fV) {
1295 if (!strcmp($inArray[$fN], '')) {
1296 unset($inArray[$fN]);
1297 } elseif (is_array($this->pi_autoCacheFields[$fN])) {
1298 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]) {
1299 unset($inArray[$fN]);
1300 }
1301 if (is_array($this->pi_autoCacheFields[$fN]['list']) && in_array($inArray[$fN], $this->pi_autoCacheFields[$fN]['list'])) {
1302 unset($inArray[$fN]);
1303 }
1304 }
1305 }
1306 }
1307 if (empty($inArray)) {
1308 //@TODO: How do we deal with this? return TRUE would be the right thing to do here but that might be breaking
1309 return 1;
1310 }
1311 return null;
1312 }
1313
1314 /**
1315 * Will process the input string with the parseFunc function from ContentObjectRenderer based on configuration
1316 * set in "lib.parseFunc_RTE" in the current TypoScript template.
1317 *
1318 * @param string $str The input text string to process
1319 * @return string The processed string
1320 * @see ContentObjectRenderer::parseFunc()
1321 */
1322 public function pi_RTEcssText($str)
1323 {
1324 $parseFunc = $this->frontendController->tmpl->setup['lib.']['parseFunc_RTE.'];
1325 if (is_array($parseFunc)) {
1326 $str = $this->cObj->parseFunc($str, $parseFunc);
1327 }
1328 return $str;
1329 }
1330
1331 /*******************************
1332 *
1333 * FlexForms related functions
1334 *
1335 *******************************/
1336 /**
1337 * Converts $this->cObj->data['pi_flexform'] from XML string to flexForm array.
1338 *
1339 * @param string $field Field name to convert
1340 */
1341 public function pi_initPIflexForm($field = 'pi_flexform')
1342 {
1343 // Converting flexform data into array:
1344 if (!is_array($this->cObj->data[$field]) && $this->cObj->data[$field]) {
1345 $this->cObj->data[$field] = GeneralUtility::xml2array($this->cObj->data[$field]);
1346 if (!is_array($this->cObj->data[$field])) {
1347 $this->cObj->data[$field] = [];
1348 }
1349 }
1350 }
1351
1352 /**
1353 * Return value from somewhere inside a FlexForm structure
1354 *
1355 * @param array $T3FlexForm_array FlexForm data
1356 * @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.
1357 * @param string $sheet Sheet pointer, eg. "sDEF
1358 * @param string $lang Language pointer, eg. "lDEF
1359 * @param string $value Value pointer, eg. "vDEF
1360 * @return string|null The content.
1361 */
1362 public function pi_getFFvalue($T3FlexForm_array, $fieldName, $sheet = 'sDEF', $lang = 'lDEF', $value = 'vDEF')
1363 {
1364 $sheetArray = is_array($T3FlexForm_array) ? $T3FlexForm_array['data'][$sheet][$lang] : '';
1365 if (is_array($sheetArray)) {
1366 return $this->pi_getFFvalueFromSheetArray($sheetArray, explode('/', $fieldName), $value);
1367 }
1368 return null;
1369 }
1370
1371 /**
1372 * Returns part of $sheetArray pointed to by the keys in $fieldNameArray
1373 *
1374 * @param array $sheetArray Multidimensiona array, typically FlexForm contents
1375 * @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...)
1376 * @param string $value Value for outermost key, typ. "vDEF" depending on language.
1377 * @return mixed The value, typ. string.
1378 * @internal
1379 * @see pi_getFFvalue()
1380 */
1381 public function pi_getFFvalueFromSheetArray($sheetArray, $fieldNameArr, $value)
1382 {
1383 $tempArr = $sheetArray;
1384 foreach ($fieldNameArr as $k => $v) {
1385 if (MathUtility::canBeInterpretedAsInteger($v)) {
1386 if (is_array($tempArr)) {
1387 $c = 0;
1388 foreach ($tempArr as $values) {
1389 if ($c == $v) {
1390 $tempArr = $values;
1391 break;
1392 }
1393 $c++;
1394 }
1395 }
1396 } else {
1397 $tempArr = $tempArr[$v];
1398 }
1399 }
1400 return $tempArr[$value];
1401 }
1402
1403 /**
1404 * Returns the currently configured "site language" if a site is configured (= resolved) in the current request.
1405 *
1406 * @internal
1407 */
1408 protected function getCurrentSiteLanguage(): ?SiteLanguage
1409 {
1410 $request = $GLOBALS['TYPO3_REQUEST'] ?? null;
1411 return $request
1412 && $request instanceof ServerRequestInterface
1413 && $request->getAttribute('language') instanceof SiteLanguage
1414 ? $request->getAttribute('language')
1415 : null;
1416 }
1417 }