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