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