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