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