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