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