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