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