[TASK] Remove extension class for ElementBrowserFolderTreeView
[Packages/TYPO3.CMS.git] / typo3 / sysext / recordlist / Classes / Browser / ElementBrowser.php
1 <?php
2 namespace TYPO3\CMS\Recordlist\Browser;
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\Backend\Form\FormEngine;
18 use TYPO3\CMS\Backend\RecordList\ElementBrowserRecordList;
19 use TYPO3\CMS\Backend\Template\DocumentTemplate;
20 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
21 use TYPO3\CMS\Core\Database\DatabaseConnection;
22 use TYPO3\CMS\Core\ElementBrowser\ElementBrowserHookInterface;
23 use TYPO3\CMS\Core\Messaging\FlashMessage;
24 use TYPO3\CMS\Core\Resource\Exception;
25 use TYPO3\CMS\Core\Resource\File;
26 use TYPO3\CMS\Core\Resource\FileInterface;
27 use TYPO3\CMS\Core\Resource\Filter\FileExtensionFilter;
28 use TYPO3\CMS\Core\Resource\Folder;
29 use TYPO3\CMS\Core\Resource\InaccessibleFolder;
30 use TYPO3\CMS\Core\Resource\ProcessedFile;
31 use TYPO3\CMS\Core\Resource\ResourceFactory;
32 use TYPO3\CMS\Core\Utility\File\BasicFileUtility;
33 use TYPO3\CMS\Core\Utility\GeneralUtility;
34 use TYPO3\CMS\Core\Utility\StringUtility;
35 use TYPO3\CMS\Backend\Utility\BackendUtility;
36 use TYPO3\CMS\Backend\Utility\IconUtility;
37 use TYPO3\CMS\Core\Utility\MathUtility;
38 use TYPO3\CMS\Frontend\Service\TypoLinkCodecService;
39 use TYPO3\CMS\Lang\LanguageService;
40
41 /**
42 * class for the Element Browser window.
43 *
44 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
45 */
46 class ElementBrowser {
47
48 /**
49 * Optional instance of a record list that TBE_expandPage() should
50 * use to render the records in a page
51 *
52 * @var ElementBrowserRecordList
53 */
54 protected $recordList = NULL;
55
56 /**
57 * Current site URL (Frontend)
58 *
59 * @var string
60 * @internal
61 */
62 public $siteURL;
63
64 /**
65 * the script to link to
66 *
67 * @var string
68 */
69 public $thisScript;
70
71 /**
72 * RTE specific TSconfig
73 *
74 * @var array[]
75 */
76 public $thisConfig;
77
78 /**
79 * Target (RTE specific)
80 *
81 * @var string
82 */
83 public $setTarget;
84
85 /**
86 * CSS Class (RTE specific)
87 *
88 * @var string
89 */
90 public $setClass;
91
92 /**
93 * title (RTE specific)
94 *
95 * @var string
96 */
97 public $setTitle;
98
99 /**
100 * @var string
101 */
102 public $setParams;
103
104 /**
105 * Backend template object
106 *
107 * @var DocumentTemplate
108 */
109 public $doc;
110
111 /**
112 * Holds information about files
113 *
114 * @var mixed[][]
115 */
116 public $elements = array();
117
118 /**
119 * The mode determines the main kind of output from the element browser.
120 * There are these options for values: rte, db, file, filedrag, wizard.
121 * "rte" will show the link selector for the Rich Text Editor (see main_rte())
122 * "db" will allow you to browse for pages or records in the page tree (for TCEforms, see main_db())
123 * "file"/"filedrag" will allow you to browse for files or folders in the folder mounts (for TCEforms, main_file())
124 * "wizard" will allow you to browse for links (like "rte") which are passed back to TCEforms (see main_rte(1))
125 *
126 * @see main()
127 * @var string
128 */
129 public $mode;
130
131 /**
132 * Link selector action.
133 * page,file,url,mail,spec are allowed values.
134 * These are only important with the link selector function and in that case they switch
135 * between the various menu options.
136 *
137 * @var string
138 */
139 public $act;
140
141 /**
142 * When you click a page title/expand icon to see the content of a certain page, this
143 * value will contain that value (the ID of the expanded page). If the value is NOT set,
144 * then it will be restored from the module session data (see main(), mode="db")
145 *
146 * @var NULL|int
147 */
148 public $expandPage;
149
150 /**
151 * When you click a folder name/expand icon to see the content of a certain file folder,
152 * this value will contain that value (the path of the expanded file folder). If the
153 * value is NOT set, then it will be restored from the module session data (see main(),
154 * mode="file"/"filedrag"). Example value: "/www/htdocs/typo3/32/3dsplm/fileadmin/css/"
155 *
156 * @var string
157 */
158 public $expandFolder;
159
160 /**
161 * the folder object of a parent folder that was selected
162 *
163 * @var Folder
164 */
165 protected $selectedFolder;
166
167 /**
168 * TYPO3 Element Browser, wizard mode parameters. There is a heap of parameters there,
169 * better debug() them out if you need something... :-)
170 *
171 * @var array[]
172 */
173 public $P;
174
175 /**
176 * Active with TYPO3 Element Browser: Contains the name of the form field for which this window
177 * opens - thus allows us to make references back to the main window in which the form is.
178 * Example value: "data[pages][39][bodytext]|||tt_content|"
179 * or "data[tt_content][NEW3fba56fde763d][image]|||gif,jpg,jpeg,tif,bmp,pcx,tga,png,pdf,ai|"
180 *
181 * Values:
182 * 0: form field name reference, eg. "data[tt_content][123][image]"
183 * 1: htmlArea RTE parameters: editorNo:contentTypo3Language:contentTypo3Charset
184 * 2: RTE config parameters: RTEtsConfigParams
185 * 3: allowed types. Eg. "tt_content" or "gif,jpg,jpeg,tif,bmp,pcx,tga,png,pdf,ai"
186 * 4: IRRE uniqueness: target level object-id to perform actions/checks on, eg. "data[79][tt_address][1][<field>][<foreign_table>]"
187 * 5: IRRE uniqueness: name of function in opener window that checks if element is already used, eg. "inline.checkUniqueElement"
188 * 6: IRRE uniqueness: name of function in opener window that performs some additional(!) action, eg. "inline.setUniqueElement"
189 * 7: IRRE uniqueness: name of function in opener window that performs action instead of using addElement/insertElement, eg. "inline.importElement"
190 *
191 * $pArr = explode('|', $this->bparams);
192 * $formFieldName = $pArr[0];
193 * $allowedTablesOrFileTypes = $pArr[3];
194 *
195 * @var string
196 */
197 public $bparams;
198
199 /**
200 * Used with the Rich Text Editor.
201 * Example value: "tt_content:NEW3fba58c969f5c:bodytext:23:text:23:"
202 *
203 * @var string
204 */
205 public $RTEtsConfigParams;
206
207 /**
208 * Plus/Minus icon value. Used by the tree class to open/close notes on the trees.
209 *
210 * @var string
211 */
212 public $PM;
213
214 /**
215 * Pointer, used when browsing a long list of records etc.
216 *
217 * @var int
218 */
219 public $pointer;
220
221 /**
222 * Used with the link selector: Contains the GET input information about the CURRENT link
223 * in the RTE/TCEform field. This consists of "href", "target" and "title" keys.
224 * This information is passed around in links.
225 *
226 * @var array[]
227 */
228 public $curUrlArray;
229
230 /**
231 * Used with the link selector: Contains a processed version of the input values from curUrlInfo.
232 * This is splitted into pageid, content element id, label value etc.
233 * This is used for the internal processing of that information.
234 *
235 * @var array[]
236 */
237 public $curUrlInfo;
238
239 /**
240 * array which holds hook objects (initialised in init())
241 *
242 * @var ElementBrowserHookInterface[]
243 */
244 protected $hookObjects = array();
245
246 /**
247 * @var BasicFileUtility
248 */
249 public $fileProcessor;
250
251 /**
252 * Sets the script url depending on being a module or script request
253 */
254 protected function determineScriptUrl() {
255 if ($moduleName = GeneralUtility::_GP('M')) {
256 $this->thisScript = BackendUtility::getModuleUrl($moduleName);
257 } else {
258 $this->thisScript = GeneralUtility::getIndpEnv('SCRIPT_NAME');
259 }
260 }
261
262 /**
263 * Calculate path to this script.
264 * This method is public, to be used in hooks of this class only.
265 *
266 * @return string
267 */
268 public function getThisScript() {
269 return strpos($this->thisScript, '?') === FALSE ? $this->thisScript . '?' : $this->thisScript . '&';
270 }
271
272 /**
273 * Constructor:
274 * Initializes a lot of variables, setting JavaScript functions in header etc.
275 *
276 * @return void
277 * @throws \UnexpectedValueException
278 */
279 public function init() {
280 $this->initVariables();
281
282 $this->RTEtsConfigParams = GeneralUtility::_GP('RTEtsConfigParams');
283 $this->initConfiguration();
284 $this->initDocumentTemplate();
285 // init hook objects:
286 $this->initHookObjects('typo3/class.browse_links.php');
287
288 $this->initCurrentUrl();
289
290 // Determine nature of current url:
291 $this->act = GeneralUtility::_GP('act');
292 if (!$this->act) {
293 $this->act = $this->curUrlInfo['act'];
294 }
295
296 // Initializing the target value (RTE)
297 $this->setTarget = $this->curUrlArray['target'] != '-' ? $this->curUrlArray['target'] : '';
298 if ($this->thisConfig['defaultLinkTarget'] && !isset($this->curUrlArray['target'])) {
299 $this->setTarget = $this->thisConfig['defaultLinkTarget'];
300 }
301 // Initializing the class value (RTE)
302 $this->setClass = $this->curUrlArray['class'] != '-' ? $this->curUrlArray['class'] : '';
303 // Initializing the title value (RTE)
304 $this->setTitle = $this->curUrlArray['title'] != '-' ? $this->curUrlArray['title'] : '';
305 // Initializing the params value
306 $this->setParams = $this->curUrlArray['params'] != '-' ? $this->curUrlArray['params'] : '';
307
308 // Finally, add the accumulated JavaScript to the template object:
309 // also unset the default jumpToUrl() function before
310 unset($this->doc->JScodeArray['jumpToUrl']);
311 $this->doc->JScode .= $this->doc->wrapScriptTags($this->getJSCode());
312 }
313
314 /**
315 * Initialize class variables
316 *
317 * @return void
318 */
319 public function initVariables() {
320 // Main GPvars:
321 $this->pointer = GeneralUtility::_GP('pointer');
322 $this->bparams = GeneralUtility::_GP('bparams');
323 $this->P = GeneralUtility::_GP('P');
324 $this->expandPage = GeneralUtility::_GP('expandPage');
325 $this->expandFolder = GeneralUtility::_GP('expandFolder');
326 $this->PM = GeneralUtility::_GP('PM');
327
328 // Site URL
329 // Current site url
330 $this->siteURL = GeneralUtility::getIndpEnv('TYPO3_SITE_URL');
331 $this->determineScriptUrl();
332
333 // Find "mode"
334 $this->mode = GeneralUtility::_GP('mode');
335 if (!$this->mode) {
336 $this->mode = 'rte';
337 }
338
339 // Init fileProcessor
340 $this->fileProcessor = GeneralUtility::makeInstance(BasicFileUtility::class);
341 $this->fileProcessor->init(array(), $GLOBALS['TYPO3_CONF_VARS']['BE']['fileExtensions']);
342 }
343
344 /**
345 * Initializes the configuration variables
346 *
347 * @return void
348 */
349 public function initConfiguration() {
350 // Rich Text Editor specific configuration:
351 if ((string)$this->mode === 'rte') {
352 $this->thisConfig = $this->getRTEConfig();
353 }
354 }
355
356 /**
357 * Initialize document template object
358 *
359 * @return void
360 */
361 protected function initDocumentTemplate() {
362 // Creating backend template object:
363 $this->doc = GeneralUtility::makeInstance(DocumentTemplate::class);
364 $this->doc->bodyTagId = 'typo3-browse-links-php';
365 $this->doc->backPath = $GLOBALS['BACK_PATH'];
366 $this->doc->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/BrowseLinks');
367 $this->doc->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/LegacyTree');
368 }
369
370 /**
371 * Initialize hook objects implementing the interface
372 *
373 * @param string $hookKey the hook key
374 * @throws \UnexpectedValueException
375 * @return void
376 */
377 protected function initHookObjects($hookKey) {
378 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][$hookKey]['browseLinksHook'])) {
379 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][$hookKey]['browseLinksHook'] as $classData) {
380 $processObject = GeneralUtility::getUserObj($classData);
381 if (!$processObject instanceof ElementBrowserHookInterface) {
382 throw new \UnexpectedValueException('$processObject must implement interface ' . ElementBrowserHookInterface::class, 1195039394);
383 }
384 $parameters = array();
385 $processObject->init($this, $parameters);
386 $this->hookObjects[] = $processObject;
387 }
388 }
389 }
390
391 /**
392 * Initialize $this->curUrlArray and $this->curUrlInfo based on script parameters
393 *
394 * @return void
395 */
396 protected function initCurrentUrl() {
397 // CurrentUrl - the current link url must be passed around if it exists
398 if ($this->mode === 'wizard') {
399 $currentValues = GeneralUtility::trimExplode(LF, trim($this->P['currentValue']));
400 if (!empty($currentValues)) {
401 $currentValue = array_pop($currentValues);
402 } else {
403 $currentValue = '';
404 }
405 $currentLinkParts = GeneralUtility::makeInstance(TypoLinkCodecService::class)->decode($currentValue);
406
407 $initialCurUrlArray = array(
408 'href' => $currentLinkParts['url'],
409 'target' => $currentLinkParts['target'],
410 'class' => $currentLinkParts['class'],
411 'title' => $currentLinkParts['title'],
412 'params' => $currentLinkParts['additionalParams']
413 );
414 $this->curUrlArray = is_array(GeneralUtility::_GP('curUrl'))
415 ? array_merge($initialCurUrlArray, GeneralUtility::_GP('curUrl'))
416 : $initialCurUrlArray;
417 // Additional fields for page links
418 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['extendUrlArray'])
419 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['extendUrlArray'])
420 ) {
421 $conf = array();
422 $_params = array(
423 'conf' => &$conf,
424 'linkParts' => [
425 // the hook expects old numerical indexes
426 $currentLinkParts['url'],
427 $currentLinkParts['target'],
428 $currentLinkParts['class'],
429 $currentLinkParts['title'],
430 $currentLinkParts['additionalParams']
431 ]
432 );
433 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['extendUrlArray'] as $objRef) {
434 $processor =& GeneralUtility::getUserObj($objRef);
435 $processor->extendUrlArray($_params, $this);
436 }
437 }
438 $this->curUrlInfo = $this->parseCurUrl($this->siteURL . '?id=' . $this->curUrlArray['href'], $this->siteURL);
439 // pageid == 0 means that this is not an internal (page) link
440 if ($this->curUrlInfo['pageid'] == 0 && $this->curUrlArray['href']) {
441 // Check if there is the FAL API
442 if (GeneralUtility::isFirstPartOfStr($this->curUrlArray['href'], 'file:')) {
443 $this->curUrlInfo = $this->parseCurUrl($this->curUrlArray['href'], $this->siteURL);
444 } elseif (file_exists(PATH_site . rawurldecode($this->curUrlArray['href']))) {
445 $this->curUrlInfo = $this->parseCurUrl($this->siteURL . $this->curUrlArray['href'], $this->siteURL);
446 } elseif (strstr($this->curUrlArray['href'], '@')) {
447 $this->curUrlInfo = $this->parseCurUrl('mailto:' . $this->curUrlArray['href'], $this->siteURL);
448 } else {
449 // nothing of the above. this is an external link
450 if (strpos($this->curUrlArray['href'], '://') === FALSE) {
451 $currentLinkParts['url'] = 'http://' . $this->curUrlArray['href'];
452 }
453 $this->curUrlInfo = $this->parseCurUrl($currentLinkParts['url'], $this->siteURL);
454 }
455 } elseif (!$this->curUrlArray['href']) {
456 $this->curUrlInfo = array();
457 $this->act = 'page';
458 } else {
459 $this->curUrlInfo = $this->parseCurUrl($this->siteURL . '?id=' . $this->curUrlArray['href'], $this->siteURL);
460 }
461 } else {
462 $this->curUrlArray = GeneralUtility::_GP('curUrl');
463 if ($this->curUrlArray['all']) {
464 $this->curUrlArray = GeneralUtility::get_tag_attributes($this->curUrlArray['all']);
465 }
466 $this->curUrlInfo = $this->parseCurUrl($this->curUrlArray['href'], $this->siteURL);
467 }
468 }
469
470 /**
471 * Get the RTE configuration from Page TSConfig
472 *
473 * @return array[] RTE configuration array
474 */
475 protected function getRTEConfig() {
476 $RTEtsConfigParts = explode(':', $this->RTEtsConfigParams);
477 $RTEsetup = $this->getBackendUserAuthentication()->getTSConfig('RTE', BackendUtility::getPagesTSconfig($RTEtsConfigParts[5]));
478 return BackendUtility::RTEsetup($RTEsetup['properties'], $RTEtsConfigParts[0], $RTEtsConfigParts[2], $RTEtsConfigParts[4]);
479 }
480
481 /**
482 * Generate JS code to be used on the link insert/modify dialogue
483 *
484 * @return string the generated JS code
485 */
486 public function getJsCode() {
487 // Rich Text Editor specific configuration:
488 $addPassOnParams = '';
489 if ((string)$this->mode == 'rte') {
490 $addPassOnParams .= '&RTEtsConfigParams=' . rawurlencode($this->RTEtsConfigParams);
491 }
492 // BEGIN accumulation of header JavaScript:
493 $JScode = '
494 // This JavaScript is primarily for RTE/Link. jumpToUrl is used in the other cases as well...
495 var add_href=' . GeneralUtility::quoteJSvalue($this->curUrlArray['href'] ? '&curUrl[href]=' . rawurlencode($this->curUrlArray['href']) : '') . ';
496 var add_target=' . GeneralUtility::quoteJSvalue($this->setTarget ? '&curUrl[target]=' . rawurlencode($this->setTarget) : '') . ';
497 var add_class=' . GeneralUtility::quoteJSvalue($this->setClass ? '&curUrl[class]=' . rawurlencode($this->setClass) : '') . ';
498 var add_title=' . GeneralUtility::quoteJSvalue($this->setTitle ? '&curUrl[title]=' . rawurlencode($this->setTitle) : '') . ';
499 var add_params=' . GeneralUtility::quoteJSvalue($this->bparams ? '&bparams=' . rawurlencode($this->bparams) : '') . ';
500
501 var cur_href=' . GeneralUtility::quoteJSvalue($this->curUrlArray['href'] ?: '') . ';
502 var cur_target=' . GeneralUtility::quoteJSvalue($this->setTarget ?: '') . ';
503 var cur_class=' . GeneralUtility::quoteJSvalue($this->setClass ?: '') . ';
504 var cur_title=' . GeneralUtility::quoteJSvalue($this->setTitle ?: '') . ';
505 var cur_params=' . GeneralUtility::quoteJSvalue($this->setParams ?: '') . ';
506
507 function browse_links_setTarget(target) { //
508 cur_target=target;
509 add_target="&curUrl[target]="+escape(target);
510 }
511 function browse_links_setClass(cssClass) { //
512 cur_class = cssClass;
513 add_class = "&curUrl[class]=" + escape(cssClass);
514 }
515 function browse_links_setTitle(title) { //
516 cur_title=title;
517 add_title="&curUrl[title]="+escape(title);
518 }
519 function browse_links_setValue(value) { //
520 cur_href=value;
521 add_href="&curUrl[href]="+value;
522 }
523 function browse_links_setParams(params) { //
524 cur_params=params;
525 add_params="&curUrl[params]="+escape(params);
526 }
527 ' . $this->doc->redirectUrls();
528 // Functions used, if the link selector is in wizard mode (= TCEforms fields)
529 if ($this->mode == 'wizard') {
530 if (!$this->areFieldChangeFunctionsValid() && !$this->areFieldChangeFunctionsValid(TRUE)) {
531 $this->P['fieldChangeFunc'] = array();
532 }
533 unset($this->P['fieldChangeFunc']['alert']);
534 $update = '';
535 foreach ($this->P['fieldChangeFunc'] as $v) {
536 $update .= '
537 window.opener.' . $v;
538 }
539 $P2 = array();
540 $P2['uid'] = $this->P['uid'];
541 $P2['pid'] = $this->P['pid'];
542 $P2['itemName'] = $this->P['itemName'];
543 $P2['formName'] = $this->P['formName'];
544 $P2['fieldChangeFunc'] = $this->P['fieldChangeFunc'];
545 $P2['fieldChangeFuncHash'] = GeneralUtility::hmac(serialize($this->P['fieldChangeFunc']));
546 $P2['params']['allowedExtensions'] = isset($this->P['params']['allowedExtensions']) ? $this->P['params']['allowedExtensions'] : '';
547 $P2['params']['blindLinkOptions'] = isset($this->P['params']['blindLinkOptions']) ? $this->P['params']['blindLinkOptions'] : '';
548 $P2['params']['blindLinkFields'] = isset($this->P['params']['blindLinkFields']) ? $this->P['params']['blindLinkFields']: '';
549 $addPassOnParams .= GeneralUtility::implodeArrayForUrl('P', $P2);
550 $JScode .= '
551 function link_typo3Page(id,anchor) { //
552 updateValueInMainForm(id + (anchor ? anchor : ""));
553 close();
554 return false;
555 }
556 function link_folder(folder) { //
557 updateValueInMainForm(folder);
558 close();
559 return false;
560 }
561 function link_current() { //
562 if (cur_href!="http://" && cur_href!="mailto:") {
563 returnBeforeCleaned = cur_href;
564 if (returnBeforeCleaned.substr(0, 7) == "http://") {
565 returnToMainFormValue = returnBeforeCleaned.substr(7);
566 } else if (returnBeforeCleaned.substr(0, 7) == "mailto:") {
567 if (returnBeforeCleaned.substr(0, 14) == "mailto:mailto:") {
568 returnToMainFormValue = returnBeforeCleaned.substr(14);
569 } else {
570 returnToMainFormValue = returnBeforeCleaned.substr(7);
571 }
572 } else {
573 returnToMainFormValue = returnBeforeCleaned;
574 }
575 updateValueInMainForm(returnToMainFormValue);
576 close();
577 }
578 return false;
579 }
580 function checkReference() { //
581 if (window.opener && window.opener.document && window.opener.document.' . $this->P['formName']
582 . ' && window.opener.document.' . $this->P['formName'] . '["' . $this->P['itemName'] . '"] ) {
583 return window.opener.document.' . $this->P['formName'] . '["' . $this->P['itemName'] . '"];
584 } else {
585 close();
586 }
587 }
588 function updateValueInMainForm(input) { //
589 var field = checkReference();
590 if (field) {
591 if (cur_target == "" && (cur_class != "" || cur_title != "" || cur_params != "")) {
592 cur_target = "-";
593 }
594 if (cur_class == "" && (cur_title != "" || cur_params != "")) {
595 cur_class = "-";
596 }
597 cur_class = cur_class.replace(/[\'\\"]/g, "");
598 if (cur_class.indexOf(" ") != -1) {
599 cur_class = "\\"" + cur_class + "\\"";
600 }
601 if (cur_title == "" && cur_params != "") {
602 cur_title = "-";
603 }
604 // replace each \ with \\
605 cur_title = cur_title.replace(/\\\\/g, "\\\\\\\\");
606 // replace each " with \"
607 cur_title = cur_title.replace(/\\"/g, "\\\\\\"");
608 if (cur_title.indexOf(" ") != -1) {
609 cur_title = "\\"" + cur_title + "\\"";
610 }
611 if (cur_params) {
612 cur_params = cur_params.replace(/\\bid\\=.*?(\\&|$)/, "");
613 }
614 input = input + " " + cur_target + " " + cur_class + " " + cur_title + " " + cur_params;
615 input = input.replace(/^\s+|\s+$/g, "");
616 if(field.value && field.className.search(/textarea/) != -1) {
617 field.value += "\\n" + input;
618 } else {
619 field.value = input;
620 }
621 field.onchange();
622 ' . $update . '
623 }
624 }
625 ';
626 } else {
627 // Functions used, if the link selector is in RTE mode:
628 $JScode .= '
629 function link_typo3Page(id,anchor) { //
630 var theLink = \'' . $this->siteURL . '?id=\'+id+(anchor?anchor:"");
631 self.parent.parent.renderPopup_addLink(theLink, cur_target, cur_class, cur_title);
632 return false;
633 }
634 function link_folder(folder) { //
635 var theLink = \'' . $this->siteURL . '\'+folder;
636 self.parent.parent.renderPopup_addLink(theLink, cur_target, cur_class, cur_title);
637 return false;
638 }
639 function link_spec(theLink) { //
640 self.parent.parent.renderPopup_addLink(theLink, cur_target, cur_class, cur_title);
641 return false;
642 }
643 function link_current() { //
644 if (cur_href!="http://" && cur_href!="mailto:") {
645 self.parent.parent.renderPopup_addLink(cur_href, cur_target, cur_class, cur_title);
646 }
647 return false;
648 }
649 ';
650 }
651 // General "jumpToUrl" function:
652 $JScode .= '
653 function jumpToUrl(URL,anchor) { //
654 if (URL.charAt(0) === \'?\') {
655 URL = ' . GeneralUtility::quoteJSvalue($this->getThisScript()) . ' + URL.substring(1);
656 }
657 var add_act = URL.indexOf("act=")==-1 ? "&act=' . $this->act . '" : "";
658 var add_mode = URL.indexOf("mode=")==-1 ? "&mode=' . $this->mode . '" : "";
659 var theLocation = URL + add_act + add_mode + add_href + add_target + add_class + add_title + add_params'
660 . ($addPassOnParams ? '+' . GeneralUtility::quoteJSvalue($addPassOnParams) : '')
661 . '+(typeof(anchor)=="string"?anchor:"");
662 window.location.href = theLocation;
663 return false;
664 }
665 ';
666 /**
667 * Splits parts of $this->bparams
668 *
669 * @see $bparams
670 */
671 $pArr = explode('|', $this->bparams);
672 // This is JavaScript especially for the TBE Element Browser!
673 $formFieldName = 'data[' . $pArr[0] . '][' . $pArr[1] . '][' . $pArr[2] . ']';
674 // insertElement - Call check function (e.g. for uniqueness handling):
675 $JScodeCheck = '';
676 if ($pArr[4] && $pArr[5]) {
677 $JScodeCheck = '
678 // Call a check function in the opener window (e.g. for uniqueness handling):
679 if (parent.window.opener) {
680 var res = parent.window.opener.' . $pArr[5] . '("' . addslashes($pArr[4]) . '",table,uid,type);
681 if (!res.passed) {
682 if (res.message) alert(res.message);
683 performAction = false;
684 }
685 } else {
686 alert("Error - reference to main window is not set properly!");
687 parent.close();
688 }
689 ';
690 }
691 // insertElement - Call helper function:
692 $JScodeHelper = '';
693 if ($pArr[4] && $pArr[6]) {
694 $JScodeHelper = '
695 // Call helper function to manage data in the opener window:
696 if (parent.window.opener) {
697 parent.window.opener.' . $pArr[6] . '("' . addslashes($pArr[4]) . '",table,uid,type,"' . addslashes($pArr[0]) . '");
698 } else {
699 alert("Error - reference to main window is not set properly!");
700 parent.close();
701 }
702 ';
703 }
704 // insertElement - perform action commands:
705 $JScodeActionMultiple = '';
706 if ($pArr[4] && $pArr[7]) {
707 // Call user defined action function:
708 $JScodeAction = '
709 if (parent.window.opener) {
710 parent.window.opener.' . $pArr[7] . '("' . addslashes($pArr[4]) . '",table,uid,type);
711 if (close) { focusOpenerAndClose(close); }
712 } else {
713 alert("Error - reference to main window is not set properly!");
714 if (close) { parent.close(); }
715 }
716 ';
717 $JScodeActionMultiple = '
718 // Call helper function to manage data in the opener window:
719 if (parent.window.opener) {
720 parent.window.opener.' . $pArr[7] . 'Multiple("' . addslashes($pArr[4]) . '",table,uid,type,"'
721 . addslashes($pArr[0]) . '");
722 } else {
723 alert("Error - reference to main window is not set properly!");
724 parent.close();
725 }
726 ';
727 } elseif ($pArr[0] && !$pArr[1] && !$pArr[2]) {
728 $JScodeAction = '
729 addElement(filename,table+"_"+uid,fp,close);
730 ';
731 } else {
732 $JScodeAction = '
733 if (setReferences()) {
734 parent.window.opener.group_change("add","' . $pArr[0] . '","' . $pArr[1] . '","' . $pArr[2]
735 . '",elRef,targetDoc);
736 } else {
737 alert("Error - reference to main window is not set properly!");
738 }
739 focusOpenerAndClose(close);
740 ';
741 }
742 $JScode .= '
743 var elRef="";
744 var targetDoc="";
745
746 function launchView(url) { //
747 var thePreviewWindow="";
748 thePreviewWindow = window.open(' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('show_item') . '&table=') . '+url,"ShowItem",'
749 . '"height=300,width=410,status=0,menubar=0,resizable=0,location=0,directories=0,scrollbars=1,toolbar=0");
750 if (thePreviewWindow && thePreviewWindow.focus) {
751 thePreviewWindow.focus();
752 }
753 }
754 function setReferences() { //
755 if (parent.window.opener && parent.window.opener.content && parent.window.opener.content.document.editform'
756 . '&& parent.window.opener.content.document.editform["' . $formFieldName . '"]) {
757 targetDoc = parent.window.opener.content.document;
758 elRef = targetDoc.editform["' . $formFieldName . '"];
759 return true;
760 } else {
761 return false;
762 }
763 }
764 function insertElement(table, uid, type, filename, fp, filetype, imagefile, action, close) { //
765 var performAction = true;
766 ' . $JScodeCheck . '
767 // Call performing function and finish this action:
768 if (performAction) {
769 ' . $JScodeHelper . $JScodeAction . '
770 }
771 return false;
772 }
773 var _hasActionMultipleCode = ' . (!empty($JScodeActionMultiple) ? 'true' : 'false') . ';
774 function insertMultiple(table, uid) {
775 var type = "";
776 ' . $JScodeActionMultiple . '
777 return false;
778 }
779 function addElement(elName, elValue, altElValue, close) { //
780 if (parent.window.opener && parent.window.opener.setFormValueFromBrowseWin) {
781 parent.window.opener.setFormValueFromBrowseWin("' . $pArr[0] . '",altElValue?altElValue:elValue,elName);
782 focusOpenerAndClose(close);
783 } else {
784 alert("Error - reference to main window is not set properly!");
785 parent.close();
786 }
787 }
788 function focusOpenerAndClose(close) { //
789 BrowseLinks.focusOpenerAndClose(close);
790 }
791 ';
792 // extends JavaScript code
793 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['extendJScode'])
794 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['extendJScode'])
795 ) {
796 $conf = array();
797 $update = '';
798 $_params = array(
799 'conf' => &$conf,
800 'wizardUpdate' => $update,
801 'addPassOnParams' => $addPassOnParams
802 );
803 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['extendJScode'] as $objRef) {
804 $processor =& GeneralUtility::getUserObj($objRef);
805 $JScode .= $processor->extendJScode($_params, $this);
806 }
807 }
808 return $JScode;
809 }
810
811 /**
812 * Session data for this class can be set from outside with this method.
813 * Call after init()
814 *
815 * @param mixed[] $data Session data array
816 * @return array[] Session data and boolean which indicates that data needs to be stored in session because it's changed
817 */
818 public function processSessionData($data) {
819 $store = FALSE;
820 switch ((string)$this->mode) {
821 case 'db':
822 if (isset($this->expandPage)) {
823 $data['expandPage'] = $this->expandPage;
824 $store = TRUE;
825 } else {
826 $this->expandPage = $data['expandPage'];
827 }
828 break;
829 case 'file':
830
831 case 'filedrag':
832
833 case 'folder':
834 if (isset($this->expandFolder)) {
835 $data['expandFolder'] = $this->expandFolder;
836 $store = TRUE;
837 } else {
838 $this->expandFolder = $data['expandFolder'];
839 }
840 break;
841 }
842 return array($data, $store);
843 }
844
845 /******************************************************************
846 *
847 * Main functions
848 *
849 ******************************************************************/
850 /**
851 * Rich Text Editor (RTE) link selector (MAIN function)
852 * Generates the link selector for the Rich Text Editor.
853 * Can also be used to select links for the TCEforms (see $wiz)
854 *
855 * @param bool $wiz If set, the "remove link" is not shown in the menu: Used for the "Select link" wizard which is used by the TCEforms
856 * @return string Modified content variable.
857 */
858 public function main_rte($wiz = FALSE) {
859 // Starting content:
860 $content = $this->doc->startPage('RTE link');
861 // Add the FlashMessages if any
862 $content .= $this->doc->getFlashMessages();
863
864 $allowedItems = $this->getAllowedItems('page,file,folder,url,mail,spec');
865
866 // Removing link fields if configured
867 $blindLinkFields = isset($this->thisConfig['blindLinkFields'])
868 ? GeneralUtility::trimExplode(',', $this->thisConfig['blindLinkFields'], TRUE)
869 : array();
870 $pBlindLinkFields = isset($this->P['params']['blindLinkFields'])
871 ? GeneralUtility::trimExplode(',', $this->P['params']['blindLinkFields'], TRUE)
872 : array();
873 $allowedFields = array_diff(array('target', 'title', 'class', 'params'), $blindLinkFields, $pBlindLinkFields);
874
875 $content .= $this->doc->getTabMenuRaw($this->buildMenuArray($wiz, $allowedItems));
876 // Adding the menu and header to the top of page:
877 $content .= $this->printCurrentUrl($this->curUrlInfo['info']) . '<br />';
878 // Depending on the current action we will create the actual module content for selecting a link:
879 switch ($this->act) {
880 case 'mail':
881 $content .= $this->getEmailSelectorHtml();
882 break;
883 case 'url':
884 $content .= $this->getExternalUrlSelectorHtml();
885 break;
886 case 'file':
887 case 'folder':
888 $content .= $this->getFileSelectorHtml();
889 break;
890 case 'spec':
891 $content .= $this->getUserLinkSelectorHtml();
892 break;
893 case 'page':
894 $content .= $this->getPageSelectorHtml();
895 break;
896 default:
897 // Call hook
898 foreach ($this->hookObjects as $hookObject) {
899 $content .= $hookObject->getTab($this->act);
900 }
901 }
902 $lang = $this->getLanguageService();
903 if (in_array('params', $allowedFields, TRUE)) {
904 $content .= '
905 <!--
906 Selecting params for link:
907 -->
908 <form action="" name="lparamsform" id="lparamsform">
909 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkParams">
910 <tr>
911 <td style="width: 96px;">' . $lang->getLL('params', TRUE) . '</td>
912 <td><input type="text" name="lparams" class="typo3-link-input" onchange="'
913 . 'browse_links_setParams(this.value);" value="' . htmlspecialchars($this->setParams)
914 . '" /></td>
915 </tr>
916 </table>
917 </form>
918 ';
919 }
920 if (in_array('class', $allowedFields, TRUE)) {
921 $content .= '
922 <!--
923 Selecting class for link:
924 -->
925 <form action="" name="lclassform" id="lclassform">
926 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkClass">
927 <tr>
928 <td style="width: 96px;">' . $lang->getLL('class', TRUE) . '</td>
929 <td><input type="text" name="lclass" class="typo3-link-input" onchange="'
930 . 'browse_links_setClass(this.value);" value="' . htmlspecialchars($this->setClass)
931 . '" /></td>
932 </tr>
933 </table>
934 </form>
935 ';
936 }
937 if (in_array('title', $allowedFields, TRUE)) {
938 $content .= '
939 <!--
940 Selecting title for link:
941 -->
942 <form action="" name="ltitleform" id="ltitleform">
943 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkTitle">
944 <tr>
945 <td style="width: 96px;">' . $lang->getLL('title', TRUE) . '</td>
946 <td><input type="text" name="ltitle" class="typo3-link-input" onchange="'
947 . 'browse_links_setTitle(this.value);" value="' . htmlspecialchars($this->setTitle)
948 . '" /></td>
949 </tr>
950 </table>
951 </form>
952 ';
953 }
954 // additional fields for page links
955 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['addFields_PageLink'])
956 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['addFields_PageLink'])
957 ) {
958 $conf = array();
959 $_params = array(
960 'conf' => &$conf
961 );
962 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/class.browse_links.php']['addFields_PageLink'] as $objRef) {
963 $processor =& GeneralUtility::getUserObj($objRef);
964 $content .= $processor->addFields($_params, $this);
965 }
966 }
967 // Target:
968 if ($this->act != 'mail' && in_array('target', $allowedFields, TRUE)) {
969 $ltarget = '
970
971 <!--
972 Selecting target for link:
973 -->
974 <form action="" name="ltargetform" id="ltargetform">
975 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkTarget">
976 <tr>
977 <td>' . $lang->getLL('target', TRUE) . ':</td>
978 <td><input type="text" name="ltarget" onchange="browse_links_setTarget(this.value);" value="'
979 . htmlspecialchars($this->setTarget) . '"' . $this->doc->formWidth(10) . ' /></td>
980 <td>
981 <select name="ltarget_type" onchange="browse_links_setTarget('
982 . 'this.options[this.selectedIndex].value);document.ltargetform.ltarget.value='
983 . 'this.options[this.selectedIndex].value;this.selectedIndex=0;">
984 <option></option>
985 <option value="_top">' . $lang->getLL('top', TRUE) . '</option>
986 <option value="_blank">' . $lang->getLL('newWindow', TRUE) . '</option>
987 </select>
988 </td>
989 <td>';
990 if (($this->curUrlInfo['act'] == 'page' || $this->curUrlInfo['act'] == 'file' || $this->curUrlInfo['act'] == 'folder')
991 && $this->curUrlArray['href'] && $this->curUrlInfo['act'] == $this->act
992 ) {
993 $ltarget .= '
994 <input class="btn btn-default" type="submit" value="' . $lang->getLL('update', TRUE)
995 . '" onclick="return link_current();" />';
996 }
997 $selectJS = '
998 if (document.ltargetform.popup_width.options[document.ltargetform.popup_width.selectedIndex].value>0'
999 . ' && document.ltargetform.popup_height.options[document.ltargetform.popup_height.selectedIndex].value>0) {
1000 document.ltargetform.ltarget.value = document.ltargetform.popup_width.options['
1001 . 'document.ltargetform.popup_width.selectedIndex].value+"x"'
1002 . '+document.ltargetformbrowse_links_setTarget.popup_height.options['
1003 . 'document.ltargetform.popup_height.selectedIndex].value;
1004 browse_links_setTarget(document.ltargetform.ltarget.value);
1005 browse_links_setClass(document.lclassform.lclass.value);
1006 browse_links_setTitle(document.ltitleform.ltitle.value);
1007 browse_links_setParams(document.lparamsform.lparams.value);
1008 document.ltargetform.popup_width.selectedIndex=0;
1009 document.ltargetform.popup_height.selectedIndex=0;
1010 }
1011 ';
1012 $ltarget .= ' </td>
1013 </tr>
1014 <tr>
1015 <td>' . $lang->getLL('target_popUpWindow', TRUE) . ':</td>
1016 <td colspan="3">
1017 <select name="popup_width" onchange="' . htmlspecialchars($selectJS) . '">
1018 <option value="0">' . $lang->getLL('target_popUpWindow_width', TRUE) . '</option>
1019 <option value="300">300</option>
1020 <option value="400">400</option>
1021 <option value="500">500</option>
1022 <option value="600">600</option>
1023 <option value="700">700</option>
1024 <option value="800">800</option>
1025 </select>
1026 x
1027 <select name="popup_height" onchange="' . htmlspecialchars($selectJS) . '">
1028 <option value="0">' . $lang->getLL('target_popUpWindow_height', TRUE) . '</option>
1029 <option value="200">200</option>
1030 <option value="300">300</option>
1031 <option value="400">400</option>
1032 <option value="500">500</option>
1033 <option value="600">600</option>
1034 </select>
1035 </td>
1036 </tr>
1037 </table>
1038 </form>';
1039 // Add "target selector" box to content:
1040 $content .= $ltarget;
1041 // Add some space
1042 $content .= '<br /><br />';
1043 }
1044 // End page, return content:
1045 $content .= $this->doc->endPage();
1046 $content = $this->doc->insertStylesAndJS($content);
1047 return $content;
1048 }
1049
1050 /**
1051 * Get the allowed items or tabs
1052 *
1053 * @param string $items initial list of possible items
1054 * @return array the allowed items
1055 */
1056 public function getAllowedItems($items) {
1057 // Initializing the action value, possibly removing blinded values etc:
1058 $blindLinkOptions = isset($this->thisConfig['blindLinkOptions'])
1059 ? GeneralUtility::trimExplode(',', $this->thisConfig['blindLinkOptions'], TRUE)
1060 : array();
1061 $pBlindLinkOptions = isset($this->P['params']['blindLinkOptions'])
1062 ? GeneralUtility::trimExplode(',', $this->P['params']['blindLinkOptions'])
1063 : array();
1064 $allowedItems = array_diff(explode(',', $items), $blindLinkOptions, $pBlindLinkOptions);
1065
1066 // Call hook for extra options
1067 foreach ($this->hookObjects as $hookObject) {
1068 $allowedItems = $hookObject->addAllowedItems($allowedItems);
1069 }
1070 return $allowedItems;
1071 }
1072
1073 /**
1074 * Returns an array definition of the top menu
1075 *
1076 * @param $wiz
1077 * @param $allowedItems
1078 * @return mixed[][]
1079 */
1080 protected function buildMenuArray($wiz, $allowedItems) {
1081 // Making menu in top:
1082 $menuDef = array();
1083 $lang = $this->getLanguageService();
1084 if (!$wiz) {
1085 $menuDef['removeLink']['isActive'] = $this->act === 'removeLink';
1086 $menuDef['removeLink']['label'] = $lang->getLL('removeLink', TRUE);
1087 $menuDef['removeLink']['url'] = '#';
1088 $menuDef['removeLink']['addParams'] = 'onclick="self.parent.parent.renderPopup_unLink();return false;"';
1089 }
1090 if (in_array('page', $allowedItems)) {
1091 $menuDef['page']['isActive'] = $this->act === 'page';
1092 $menuDef['page']['label'] = $lang->getLL('page', TRUE);
1093 $menuDef['page']['url'] = '#';
1094 $menuDef['page']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=page') . ');return false;"';
1095 }
1096 if (in_array('file', $allowedItems)) {
1097 $menuDef['file']['isActive'] = $this->act === 'file';
1098 $menuDef['file']['label'] = $lang->getLL('file', TRUE);
1099 $menuDef['file']['url'] = '#';
1100 $menuDef['file']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=file') . ');return false;"';
1101 }
1102 if (in_array('folder', $allowedItems)) {
1103 $menuDef['folder']['isActive'] = $this->act === 'folder';
1104 $menuDef['folder']['label'] = $lang->getLL('folder', TRUE);
1105 $menuDef['folder']['url'] = '#';
1106 $menuDef['folder']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=folder') . ');return false;"';
1107 }
1108 if (in_array('url', $allowedItems)) {
1109 $menuDef['url']['isActive'] = $this->act === 'url';
1110 $menuDef['url']['label'] = $lang->getLL('extUrl', TRUE);
1111 $menuDef['url']['url'] = '#';
1112 $menuDef['url']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=url') . ');return false;"';
1113 }
1114 if (in_array('mail', $allowedItems)) {
1115 $menuDef['mail']['isActive'] = $this->act === 'mail';
1116 $menuDef['mail']['label'] = $lang->getLL('email', TRUE);
1117 $menuDef['mail']['url'] = '#';
1118 $menuDef['mail']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=mail') . ');return false;"';
1119 }
1120 if (is_array($this->thisConfig['userLinks.']) && in_array('spec', $allowedItems)) {
1121 $menuDef['spec']['isActive'] = $this->act === 'spec';
1122 $menuDef['spec']['label'] = $lang->getLL('special', TRUE);
1123 $menuDef['spec']['url'] = '#';
1124 $menuDef['spec']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=spec') . ');return false;"';
1125 }
1126 // Call hook for extra options
1127 foreach ($this->hookObjects as $hookObject) {
1128 $menuDef = $hookObject->modifyMenuDefinition($menuDef);
1129 }
1130 return $menuDef;
1131 }
1132
1133 /**
1134 * Returns HTML of the email link from
1135 *
1136 * @return string
1137 */
1138 protected function getEmailSelectorHtml() {
1139 $lang = $this->getLanguageService();
1140 $extUrl = '
1141 <!--
1142 Enter mail address:
1143 -->
1144 <form action="" name="lurlform" id="lurlform">
1145 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkMail">
1146 <tr>
1147 <td style="width: 96px;">
1148 ' . $lang->getLL('emailAddress', TRUE) . ':
1149 </td>
1150 <td>
1151 <input type="text" name="lemail"' . $this->doc->formWidth(20) . ' value="'
1152 . htmlspecialchars(($this->curUrlInfo['act'] === 'mail' ? $this->curUrlInfo['info'] : ''))
1153 . '" />
1154 <input class="btn btn-default" type="submit" value="' . $lang->getLL('setLink', TRUE)
1155 . '" onclick="browse_links_setTarget(\'\');browse_links_setValue(\'mailto:\'+'
1156 . 'document.lurlform.lemail.value); return link_current();" />
1157 </td>
1158 </tr>
1159 </table>
1160 </form>';
1161 return $extUrl;
1162 }
1163
1164 /**
1165 * Returns HTML of the external url link from
1166 *
1167 * @return string
1168 */
1169 protected function getExternalUrlSelectorHtml() {
1170 $extUrl = '
1171
1172 <!--
1173 Enter External URL:
1174 -->
1175 <form action="" name="lurlform" id="lurlform">
1176 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkURL">
1177 <tr>
1178 <td style="width: 96px;">URL:</td>
1179 <td><input type="text" name="lurl"' . $this->doc->formWidth(30) . ' value="'
1180 . htmlspecialchars(($this->curUrlInfo['act'] === 'url' ? $this->curUrlInfo['info'] : 'http://'))
1181 . '" /> ' . '<input class="btn btn-default" type="submit" value="' . $this->getLanguageService()->getLL('setLink', TRUE)
1182 . '" onclick="browse_links_setValue(document.lurlform.lurl.value); return link_current();" /></td>
1183 </tr>
1184 </table>
1185 </form>';
1186 return $extUrl;
1187 }
1188
1189 /**
1190 * Returns HTML of the file/folder link selector
1191 *
1192 * @param string $treeClassName
1193 * @return string
1194 */
1195 protected function getFileSelectorHtml($treeClassName = \TYPO3\CMS\Backend\Tree\View\ElementBrowserFolderTreeView::class) {
1196 $folderTree = GeneralUtility::makeInstance($treeClassName);
1197 $folderTree->thisScript = $this->thisScript;
1198 $tree = $folderTree->getBrowsableTree();
1199 $backendUser = $this->getBackendUserAuthentication();
1200 if (!$this->curUrlInfo['value'] || $this->curUrlInfo['act'] != $this->act) {
1201 $cmpPath = '';
1202 } else {
1203 $cmpPath = $this->curUrlInfo['value'];
1204 if (!isset($this->expandFolder)) {
1205 $this->expandFolder = $cmpPath;
1206 }
1207 }
1208 // Create upload/create folder forms, if a path is given
1209 $selectedFolder = FALSE;
1210 if ($this->expandFolder) {
1211 $fileOrFolderObject = NULL;
1212 try {
1213 $fileOrFolderObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($this->expandFolder);
1214 } catch (\Exception $e) {
1215 // No path is selected
1216 }
1217
1218 if ($fileOrFolderObject instanceof Folder) {
1219 // It's a folder
1220 $selectedFolder = $fileOrFolderObject;
1221 } elseif ($fileOrFolderObject instanceof FileInterface) {
1222 // It's a file
1223 try {
1224 $selectedFolder = $fileOrFolderObject->getParentFolder();
1225 } catch (\Exception $e) {
1226 // Accessing the parent folder failed for some reason. e.g. permissions
1227 }
1228 }
1229 }
1230 // If no folder is selected, get the user's default upload folder
1231 if (!$selectedFolder) {
1232 try {
1233 $selectedFolder = $backendUser->getDefaultUploadFolder();
1234 } catch (\Exception $e) {
1235 // The configured default user folder does not exist
1236 }
1237 }
1238 // Build the file upload and folder creation form
1239 $uploadForm = '';
1240 $createFolder = '';
1241 $content = '';
1242 if ($selectedFolder) {
1243 $uploadForm = ($this->act === 'file') ? $this->uploadForm($selectedFolder) : '';
1244 $createFolder = $this->createFolder($selectedFolder);
1245 }
1246 // Insert the upload form on top, if so configured
1247 if ($backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
1248 $content .= $uploadForm;
1249 }
1250
1251 // Render the filelist if there is a folder selected
1252 $files = '';
1253 if ($selectedFolder) {
1254 $allowedExtensions = isset($this->P['params']['allowedExtensions']) ? $this->P['params']['allowedExtensions'] : '';
1255 $files = $this->expandFolder($selectedFolder, $allowedExtensions);
1256 }
1257 // Create folder tree:
1258 $this->doc->getPageRenderer()->loadRequireJsModule('TYPO3/CMS/Backend/LegacyTree', 'function(Tree) {
1259 Tree.ajaxID = "SC_alt_file_navframe::expandCollapse";
1260 }');
1261 $content .= '
1262 <!--
1263 Wrapper table for folder tree / file/folder list:
1264 -->
1265 <table border="0" cellpadding="0" cellspacing="0" id="typo3-linkFiles">
1266 <tr>
1267 <td class="c-wCell" valign="top">'
1268 . $this->barheader(($this->getLanguageService()->getLL('folderTree') . ':')) . $tree . '</td>
1269 <td class="c-wCell" valign="top">' . $files . '</td>
1270 </tr>
1271 </table>
1272 ';
1273 // Adding create folder + upload form if applicable
1274 if (!$backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
1275 $content .= $uploadForm;
1276 }
1277 $content .= '<br />' . $createFolder . '<br />';
1278 return $content;
1279 }
1280
1281 /**
1282 * Returns HTML of the user defined link selector
1283 *
1284 * @return string
1285 */
1286 protected function getUserLinkSelectorHtml() {
1287 if (!is_array($this->thisConfig['userLinks.'])) {
1288 return '';
1289 }
1290 $lang = $this->getLanguageService();
1291 $subcats = array();
1292 $v = $this->thisConfig['userLinks.'];
1293 foreach ($v as $k2 => $value) {
1294 $k2i = (int)$k2;
1295 if (substr($k2, -1) === '.' && is_array($v[$k2i . '.'])) {
1296 // Title:
1297 $title = trim($v[$k2i]);
1298 if (!$title) {
1299 $title = $v[$k2i . '.']['url'];
1300 } else {
1301 $title = $lang->sL($title);
1302 }
1303 // Description:
1304 $description = $v[$k2i . '.']['description']
1305 ? $lang->sL($v[($k2i . '.')]['description'], TRUE) . '<br />'
1306 : '';
1307 // URL + onclick event:
1308 $onClickEvent = '';
1309 if (isset($v[$k2i . '.']['target'])) {
1310 $onClickEvent .= 'browse_links_setTarget(' . GeneralUtility::quoteJSvalue($v[($k2i . '.')]['target']) . ');';
1311 }
1312 $v[$k2i . '.']['url'] = str_replace('###_URL###', $this->siteURL, $v[$k2i . '.']['url']);
1313 if (substr($v[$k2i . '.']['url'], 0, 7) === 'http://' || substr($v[$k2i . '.']['url'], 0, 7) === 'mailto:') {
1314 $onClickEvent .= 'cur_href=' . GeneralUtility::quoteJSvalue($v[($k2i . '.')]['url']) . ';link_current();';
1315 } else {
1316 $onClickEvent .= 'link_spec(' . GeneralUtility::quoteJSvalue($this->siteURL . $v[($k2i . '.')]['url']) . ');';
1317 }
1318 // Link:
1319 $A = array('<a href="#" onclick="' . htmlspecialchars($onClickEvent) . 'return false;">', '</a>');
1320 // Adding link to menu of user defined links:
1321 $subcats[$k2i] = '
1322 <tr>
1323 <td class="bgColor4">' . $A[0] . '<strong>' . htmlspecialchars($title)
1324 . ($this->curUrlInfo['info'] == $v[$k2i . '.']['url']
1325 ? '<img' . IconUtility::skinImg(
1326 $GLOBALS['BACK_PATH'],
1327 'gfx/blinkarrow_right.gif',
1328 'width="5" height="9"'
1329 ) . ' class="c-blinkArrowR" alt="" />'
1330 : '')
1331 . '</strong><br />' . $description . $A[1] . '</td>
1332 </tr>';
1333 }
1334 }
1335 // Sort by keys:
1336 ksort($subcats);
1337 // Add menu to content:
1338 $content = '
1339
1340 <!--
1341 Special userdefined menu:
1342 -->
1343 <table border="0" cellpadding="1" cellspacing="1" id="typo3-linkSpecial">
1344 <tr>
1345 <td class="bgColor5" class="c-wCell" valign="top"><strong>'
1346 . $lang->getLL('special', TRUE) . '</strong></td>
1347 </tr>
1348 ' . implode('', $subcats) . '
1349 </table>
1350 ';
1351 return $content;
1352 }
1353
1354 /**
1355 * Returns HTML of the page link selector
1356 *
1357 * @param string $treeClassName name of the class used for page tree rendering
1358 * @return string
1359 */
1360 protected function getPageSelectorHtml($treeClassName = \TYPO3\CMS\Backend\Tree\View\ElementBrowserPageTreeView::class) {
1361 $backendUser = $this->getBackendUserAuthentication();
1362 $pageTree = GeneralUtility::makeInstance($treeClassName);
1363 $pageTree->thisScript = $this->thisScript;
1364 $pageTree->ext_showPageId = $backendUser->getTSConfigVal('options.pageTree.showPageIdWithTitle');
1365 $pageTree->ext_showNavTitle = $backendUser->getTSConfigVal('options.pageTree.showNavTitle');
1366 $pageTree->addField('nav_title');
1367 $tree = $pageTree->getBrowsableTree();
1368 $cElements = $this->expandPage();
1369 $dbmount = $this->getTemporaryTreeMountCancelNotice();
1370 $content = '
1371
1372 <!--
1373 Wrapper table for page tree / record list:
1374 -->
1375 <table border="0" cellpadding="0" cellspacing="0" id="typo3-linkPages">
1376 <tr>
1377 <td class="c-wCell" valign="top">'
1378 . $this->barheader(($this->getLanguageService()->getLL('pageTree') . ':'))
1379 . $dbmount
1380 . $tree . '</td>
1381 <td class="c-wCell" valign="top">' . $cElements . '</td>
1382 </tr>
1383 </table>
1384 ';
1385 return $content;
1386 }
1387
1388 /**
1389 * TYPO3 Element Browser: Showing a page tree and allows you to browse for records
1390 *
1391 * @return string HTML content for the module
1392 */
1393 public function main_db() {
1394 // Starting content:
1395 $content = $this->doc->startPage('TBE record selector');
1396 // Init variable:
1397 $pArr = explode('|', $this->bparams);
1398 $tables = $pArr[3];
1399 $backendUser = $this->getBackendUserAuthentication();
1400
1401 // Making the browsable pagetree:
1402 /** @var \TYPO3\CMS\Recordlist\Tree\View\ElementBrowserPageTreeView $pageTree */
1403 $pageTree = GeneralUtility::makeInstance(\TYPO3\CMS\Recordlist\Tree\View\ElementBrowserPageTreeView::class);
1404 $pageTree->thisScript = $this->thisScript;
1405 $pageTree->ext_pArrPages = $tables === 'pages' ? 1 : 0;
1406 $pageTree->ext_showNavTitle = $backendUser->getTSConfigVal('options.pageTree.showNavTitle');
1407 $pageTree->ext_showPageId = $backendUser->getTSConfigVal('options.pageTree.showPageIdWithTitle');
1408 $pageTree->addField('nav_title');
1409
1410 $withTree = TRUE;
1411 if (($tables !== '') && ($tables !== '*')) {
1412 $tablesArr = GeneralUtility::trimExplode(',', $tables, TRUE);
1413 $onlyRootLevel = TRUE;
1414 foreach ($tablesArr as $currentTable) {
1415 $tableTca = $GLOBALS['TCA'][$currentTable];
1416 if (isset($tableTca)) {
1417 if (!isset($tableTca['ctrl']['rootLevel']) || ((int)$tableTca['ctrl']['rootLevel']) != 1) {
1418 $onlyRootLevel = FALSE;
1419 }
1420 }
1421 }
1422 if ($onlyRootLevel) {
1423 $withTree = FALSE;
1424 // page to work on will be root
1425 $this->expandPage = 0;
1426 }
1427 }
1428
1429 $tree = $pageTree->getBrowsableTree();
1430 // Making the list of elements, if applicable:
1431 $cElements = $this->TBE_expandPage($tables);
1432 // Putting the things together, side by side:
1433 $content .= '
1434
1435 <!--
1436 Wrapper table for page tree / record list:
1437 -->
1438 <table border="0" cellpadding="0" cellspacing="0" id="typo3-EBrecords">
1439 <tr>';
1440 if ($withTree) {
1441 $content .= '<td class="c-wCell" valign="top">'
1442 . $this->barheader(($this->getLanguageService()->getLL('pageTree') . ':'))
1443 . $this->getTemporaryTreeMountCancelNotice()
1444 . $tree . '</td>';
1445 }
1446 $content .= '<td class="c-wCell" valign="top">' . $cElements . '</td>
1447 </tr>
1448 </table>
1449 ';
1450 // Add some space
1451 $content .= '<br /><br />';
1452 // End page, return content:
1453 $content .= $this->doc->endPage();
1454 $content = $this->doc->insertStylesAndJS($content);
1455 return $content;
1456 }
1457
1458 /**
1459 * TYPO3 Element Browser: Showing a folder tree, allowing you to browse for files.
1460 *
1461 * @return string HTML content for the module
1462 */
1463 public function main_file() {
1464 // include JS files and set prefs for foldertree
1465 $this->doc->getDragDropCode('folders', 'Tree.ajaxID = "SC_alt_file_navframe::expandCollapse"');
1466 // Starting content:
1467 $content = $this->doc->startPage('TBE file selector');
1468 // Add the FlashMessages if any
1469 $content .= $this->doc->getFlashMessages();
1470 // Init variable:
1471 $pArr = explode('|', $this->bparams);
1472 // The key number 3 of the pArr contains the "allowed" string. Disallowed is not passed to
1473 // the element browser at all but only filtered out in TCEMain afterwards
1474 $allowed = $pArr[3];
1475 if ($allowed !== 'sys_file' && $allowed !== '*' && !empty($allowed)) {
1476 $allowedFileExtensions = $allowed;
1477 }
1478 $backendUser = $this->getBackendUserAuthentication();
1479
1480 if (isset($allowedFileExtensions)) {
1481 // Create new filter object
1482 $filterObject = GeneralUtility::makeInstance(FileExtensionFilter::class);
1483 $filterObject->setAllowedFileExtensions($allowedFileExtensions);
1484 // Set file extension filters on all storages
1485 $storages = $backendUser->getFileStorages();
1486 /** @var $storage \TYPO3\CMS\Core\Resource\ResourceStorage */
1487 foreach ($storages as $storage) {
1488 $storage->addFileAndFolderNameFilter(array($filterObject, 'filterFileList'));
1489 }
1490 }
1491 // Create upload/create folder forms, if a path is given
1492 $this->selectedFolder = FALSE;
1493 if ($this->expandFolder) {
1494 $fileOrFolderObject = NULL;
1495
1496 // Try to fetch the folder the user had open the last time he browsed files
1497 // Fallback to the default folder in case the last used folder is not existing
1498 try {
1499 $fileOrFolderObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($this->expandFolder);
1500 } catch (Exception $accessException) {
1501 // We're just catching the exception here, nothing to be done if folder does not exist or is not accessible.
1502 }
1503
1504 if ($fileOrFolderObject instanceof Folder) {
1505 // It's a folder
1506 $this->selectedFolder = $fileOrFolderObject;
1507 } elseif ($fileOrFolderObject instanceof FileInterface) {
1508 // It's a file
1509 $this->selectedFolder = $fileOrFolderObject->getParentFolder();
1510 }
1511 }
1512 // Or get the user's default upload folder
1513 if (!$this->selectedFolder) {
1514 try {
1515 $this->selectedFolder = $backendUser->getDefaultUploadFolder();
1516 } catch (\Exception $e) {
1517 // The configured default user folder does not exist
1518 }
1519 }
1520 // Build the file upload and folder creation form
1521 $uploadForm = '';
1522 $createFolder = '';
1523 if ($this->selectedFolder) {
1524 $uploadForm = $this->uploadForm($this->selectedFolder);
1525 $createFolder = $this->createFolder($this->selectedFolder);
1526 }
1527 // Insert the upload form on top, if so configured
1528 if ($backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
1529 $content .= $uploadForm;
1530 }
1531 // Getting flag for showing/not showing thumbnails:
1532 $noThumbs = $backendUser->getTSConfigVal('options.noThumbsInEB');
1533 $_MOD_SETTINGS = array();
1534 if (!$noThumbs) {
1535 // MENU-ITEMS, fetching the setting for thumbnails from File>List module:
1536 $_MOD_MENU = array('displayThumbs' => '');
1537 $_MCONF['name'] = 'file_list';
1538 $_MOD_SETTINGS = BackendUtility::getModuleData($_MOD_MENU, GeneralUtility::_GP('SET'), $_MCONF['name']);
1539 }
1540 $noThumbs = $noThumbs ?: !$_MOD_SETTINGS['displayThumbs'];
1541 // Create folder tree:
1542 /** @var \TYPO3\CMS\Backend\Tree\View\ElementBrowserFolderTreeView $folderTree */
1543 $folderTree = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Tree\View\ElementBrowserFolderTreeView::class);
1544 $folderTree->thisScript = $this->thisScript;
1545 $folderTree->ext_noTempRecyclerDirs = $this->mode == 'filedrag';
1546 $tree = $folderTree->getBrowsableTree();
1547 if ($this->selectedFolder) {
1548 if ($this->mode == 'filedrag') {
1549 $files = $this->TBE_dragNDrop($this->selectedFolder, $pArr[3]);
1550 } else {
1551 $files = $this->TBE_expandFolder($this->selectedFolder, $pArr[3], $noThumbs);
1552 }
1553 } else {
1554 $files = '';
1555 }
1556
1557 // Putting the parts together, side by side:
1558 $content .= '
1559
1560 <!--
1561 Wrapper table for folder tree / file list:
1562 -->
1563 <table border="0" cellpadding="0" cellspacing="0" id="typo3-EBfiles">
1564 <tr>
1565 <td class="c-wCell" valign="top">' . $this->barheader(($this->getLanguageService()->getLL('folderTree') . ':'))
1566 . $tree . '</td>
1567 <td class="c-wCell" valign="top">' . $files . '</td>
1568 </tr>
1569 </table>
1570 ';
1571 // Adding create folder + upload forms if applicable:
1572 if (!$backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
1573 $content .= $uploadForm;
1574 }
1575 $content .= $createFolder;
1576 // Add some space
1577 $content .= '<br /><br />';
1578 // Setup indexed elements:
1579 $this->doc->JScode .= $this->doc->wrapScriptTags('
1580 require(["TYPO3/CMS/Backend/BrowseLinks"], function(BrowseLinks) {
1581 BrowseLinks.addElements(' . json_encode($this->elements) . ');
1582 });');
1583 // Ending page, returning content:
1584 $content .= $this->doc->endPage();
1585 $content = $this->doc->insertStylesAndJS($content);
1586 return $content;
1587 }
1588
1589 /**
1590 * TYPO3 Element Browser: Showing a folder tree, allowing you to browse for folders.
1591 *
1592 * @return string HTML content for the module
1593 */
1594 public function main_folder() {
1595 // include JS files
1596 // Setting prefs for foldertree
1597 $this->doc->getDragDropCode('folders', 'Tree.ajaxID = "SC_alt_file_navframe::expandCollapse";');
1598 // Starting content:
1599 $content = $this->doc->startPage('TBE folder selector');
1600 // Add the FlashMessages if any
1601 $content .= $this->doc->getFlashMessages();
1602 // Init variable:
1603 $parameters = explode('|', $this->bparams);
1604 if ($this->expandFolder) {
1605 $this->selectedFolder = ResourceFactory::getInstance()->getFolderObjectFromCombinedIdentifier($this->expandFolder);
1606 }
1607 if ($this->selectedFolder) {
1608 $createFolder = $this->createFolder($this->selectedFolder);
1609 } else {
1610 $createFolder = '';
1611 }
1612 // Create folder tree:
1613 /** @var \TYPO3\CMS\Backend\Tree\View\ElementBrowserFolderTreeView $folderTree */
1614 $folderTree = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Tree\View\ElementBrowserFolderTreeView::class);
1615 $folderTree->thisScript = $this->thisScript;
1616 $folderTree->ext_noTempRecyclerDirs = $this->mode == 'filedrag';
1617 $tree = $folderTree->getBrowsableTree(FALSE);
1618 $folders = '';
1619 if ($this->selectedFolder) {
1620 if ($this->mode == 'filedrag') {
1621 $folders = $this->TBE_dragNDrop($this->selectedFolder, $parameters[3]);
1622 } else {
1623 $folders = $this->TBE_expandSubFolders($this->selectedFolder);
1624 }
1625 }
1626 // Putting the parts together, side by side:
1627 $content .= '
1628
1629 <!--
1630 Wrapper table for folder tree / folder list:
1631 -->
1632 <table border="0" cellpadding="0" cellspacing="0" id="typo3-EBfiles">
1633 <tr>
1634 <td class="c-wCell" valign="top">' . $this->barheader(($this->getLanguageService()->getLL('folderTree') . ':'))
1635 . $tree . '</td>
1636 <td class="c-wCell" valign="top">' . $folders . '</td>
1637 </tr>
1638 </table>
1639 ';
1640 // Adding create folder if applicable:
1641 $content .= $createFolder;
1642 // Add some space
1643 $content .= '<br /><br />';
1644 // Ending page, returning content:
1645 $content .= $this->doc->endPage();
1646 $content = $this->doc->insertStylesAndJS($content);
1647 return $content;
1648 }
1649
1650 /******************************************************************
1651 *
1652 * Record listing
1653 *
1654 ******************************************************************/
1655 /**
1656 * For RTE: This displays all content elements on a page and lets you create a link to the element.
1657 *
1658 * @return string HTML output. Returns content only if the ->expandPage value is set (pointing to a page uid to show tt_content records from ...)
1659 */
1660 public function expandPage() {
1661 $out = '';
1662 // Set page id (if any) to expand
1663 $expPageId = $this->expandPage;
1664 // If there is an anchor value (content element reference) in the element reference, then force an ID to expand:
1665 if (!$this->expandPage && $this->curUrlInfo['cElement']) {
1666 // Set to the current link page id.
1667 $expPageId = $this->curUrlInfo['pageid'];
1668 }
1669 // Draw the record list IF there is a page id to expand:
1670 if ($expPageId
1671 && MathUtility::canBeInterpretedAsInteger($expPageId)
1672 && $this->getBackendUserAuthentication()->isInWebMount($expPageId)
1673 ) {
1674 // Set header:
1675 $out .= $this->barheader($this->getLanguageService()->getLL('contentElements') . ':');
1676 // Create header for listing, showing the page title/icon:
1677 $mainPageRec = BackendUtility::getRecordWSOL('pages', $expPageId);
1678 $db = $this->getDatabaseConnection();
1679 $picon = IconUtility::getSpriteIconForRecord('pages', $mainPageRec);
1680 $picon .= BackendUtility::getRecordTitle('pages', $mainPageRec, TRUE);
1681 $out .= $picon . '<br />';
1682 // Look up tt_content elements from the expanded page:
1683 $res = $db->exec_SELECTquery(
1684 'uid,header,hidden,starttime,endtime,fe_group,CType,colPos,bodytext',
1685 'tt_content',
1686 'pid=' . (int)$expPageId . BackendUtility::deleteClause('tt_content')
1687 . BackendUtility::versioningPlaceholderClause('tt_content'),
1688 '',
1689 'colPos,sorting'
1690 );
1691 $cc = $db->sql_num_rows($res);
1692 // Traverse list of records:
1693 $c = 0;
1694 while ($row = $db->sql_fetch_assoc($res)) {
1695 $c++;
1696 $icon = IconUtility::getSpriteIconForRecord('tt_content', $row);
1697 if ($this->curUrlInfo['act'] == 'page' && $this->curUrlInfo['cElement'] == $row['uid']) {
1698 $arrCol = '<img' . IconUtility::skinImg($GLOBALS['BACK_PATH'], 'gfx/blinkarrow_left.gif', 'width="5" height="9"')
1699 . ' class="c-blinkArrowL" alt="" />';
1700 } else {
1701 $arrCol = '';
1702 }
1703 // Putting list element HTML together:
1704 $out .= '<img' . IconUtility::skinImg($GLOBALS['BACK_PATH'], ('gfx/ol/join' . ($c == $cc ? 'bottom' : '')
1705 . '.gif'), 'width="18" height="16"') . ' alt="" />' . $arrCol
1706 . '<a href="#" onclick="return link_typo3Page(\'' . $expPageId . '\',\'#' . $row['uid'] . '\');">'
1707 . $icon . BackendUtility::getRecordTitle('tt_content', $row, TRUE) . '</a><br />';
1708 // Finding internal anchor points:
1709 if (GeneralUtility::inList('text,textpic', $row['CType'])) {
1710 $split = preg_split('/(<a[^>]+name=[\'"]?([^"\'>[:space:]]+)[\'"]?[^>]*>)/i', $row['bodytext'], -1, PREG_SPLIT_DELIM_CAPTURE);
1711 foreach ($split as $skey => $sval) {
1712 if ($skey % 3 == 2) {
1713 // Putting list element HTML together:
1714 $sval = substr($sval, 0, 100);
1715 $out .= '<img' . IconUtility::skinImg($GLOBALS['BACK_PATH'], 'gfx/ol/line.gif',
1716 'width="18" height="16"') . ' alt="" />'
1717 . '<img' . IconUtility::skinImg($GLOBALS['BACK_PATH'], ('gfx/ol/join'
1718 . ($skey + 3 > count($split) ? 'bottom' : '') . '.gif'), 'width="18" height="16"')
1719 . ' alt="" />' . '<a href="#" onclick="return link_typo3Page(' . GeneralUtility::quoteJSvalue($expPageId)
1720 . ',' . GeneralUtility::quoteJSvalue('#' . $sval) . ');">' . htmlspecialchars((' <A> ' . $sval))
1721 . '</a><br />';
1722 }
1723 }
1724 }
1725 }
1726 }
1727 return $out;
1728 }
1729
1730 /**
1731 * For TYPO3 Element Browser: This lists all content elements from the given list of tables
1732 *
1733 * @param string $tables Comma separated list of tables. Set to "*" if you want all tables.
1734 * @return string HTML output.
1735 */
1736 public function TBE_expandPage($tables) {
1737 $backendUser = $this->getBackendUserAuthentication();
1738 if (!MathUtility::canBeInterpretedAsInteger($this->expandPage)
1739 || $this->expandPage < 0
1740 || !$backendUser->isInWebMount($this->expandPage)
1741 ) {
1742 return '';
1743 }
1744 // Set array with table names to list:
1745 if (trim($tables) === '*') {
1746 $tablesArr = array_keys($GLOBALS['TCA']);
1747 } else {
1748 $tablesArr = GeneralUtility::trimExplode(',', $tables, TRUE);
1749 }
1750 reset($tablesArr);
1751 // Headline for selecting records:
1752 $out = $this->barheader($this->getLanguageService()->getLL('selectRecords') . ':');
1753 // Create the header, showing the current page for which the listing is.
1754 // Includes link to the page itself, if pages are amount allowed tables.
1755 $titleLen = (int)$backendUser->uc['titleLen'];
1756 $mainPageRec = BackendUtility::getRecordWSOL('pages', $this->expandPage);
1757 $ATag = '';
1758 $ATag_e = '';
1759 $ATag2 = '';
1760 $picon = '';
1761 if (is_array($mainPageRec)) {
1762 $picon = IconUtility::getSpriteIconForRecord('pages', $mainPageRec);
1763 if (in_array('pages', $tablesArr)) {
1764 $ATag = '<a href="#" onclick="return insertElement(\'pages\', \'' . $mainPageRec['uid'] . '\', \'db\', '
1765 . GeneralUtility::quoteJSvalue($mainPageRec['title']) . ', \'\', \'\', \'\',\'\',1);">';
1766 $ATag2 = '<a href="#" onclick="return insertElement(\'pages\', \'' . $mainPageRec['uid'] . '\', \'db\', '
1767 . GeneralUtility::quoteJSvalue($mainPageRec['title']) . ', \'\', \'\', \'\',\'\',0);">';
1768 $ATag_e = '</a>';
1769 }
1770 }
1771 $pBicon = $ATag2 ? IconUtility::getSpriteIcon('actions-edit-add') : '';
1772 $pText = htmlspecialchars(GeneralUtility::fixed_lgd_cs($mainPageRec['title'], $titleLen));
1773 $out .= $picon . $ATag2 . $pBicon . $ATag_e . $ATag . $pText . $ATag_e . '<br />';
1774 // Initialize the record listing:
1775 $id = $this->expandPage;
1776 $pointer = MathUtility::forceIntegerInRange($this->pointer, 0, 100000);
1777 $perms_clause = $backendUser->getPagePermsClause(1);
1778 $pageInfo = BackendUtility::readPageAccess($id, $perms_clause);
1779 // Generate the record list:
1780 /** @var $dbList ElementBrowserRecordList */
1781 if (is_object($this->recordList)) {
1782 $dbList = $this->recordList;
1783 } else {
1784 $dbList = GeneralUtility::makeInstance(ElementBrowserRecordList::class);
1785 }
1786 $dbList->thisScript = $this->thisScript;
1787 $dbList->backPath = $GLOBALS['BACK_PATH'];
1788 $dbList->thumbs = 0;
1789 $dbList->calcPerms = $backendUser->calcPerms($pageInfo);
1790 $dbList->noControlPanels = 1;
1791 $dbList->clickMenuEnabled = 0;
1792 $dbList->tableList = implode(',', $tablesArr);
1793 $pArr = explode('|', $this->bparams);
1794 // a string like "data[pages][79][storage_pid]"
1795 $fieldPointerString = $pArr[0];
1796 // parts like: data, pages], 79], storage_pid]
1797 $fieldPointerParts = explode('[', $fieldPointerString);
1798 $relatingTableName = substr($fieldPointerParts[1], 0, -1);
1799 $relatingFieldName = substr($fieldPointerParts[3], 0, -1);
1800 if ($relatingTableName && $relatingFieldName) {
1801 $dbList->setRelatingTableAndField($relatingTableName, $relatingFieldName);
1802 }
1803 $dbList->start($id, GeneralUtility::_GP('table'), $pointer, GeneralUtility::_GP('search_field'),
1804 GeneralUtility::_GP('search_levels'), GeneralUtility::_GP('showLimit')
1805 );
1806 $dbList->setDispFields();
1807 $dbList->generateList();
1808 $out .= $dbList->getSearchBox();
1809 $out .= "<script>document.getElementById('db_list-searchbox-toolbar').style.display = 'block';document.getElementById('db_list-searchbox-toolbar').style.position = 'relative';</script>";
1810
1811 // Add the HTML for the record list to output variable:
1812 $out .= $dbList->HTMLcode;
1813 // Add support for fieldselectbox in singleTableMode
1814 if ($dbList->table) {
1815 $out .= $dbList->fieldSelectBox($dbList->table);
1816 }
1817
1818 // Return accumulated content:
1819 return $out;
1820 }
1821
1822 /**
1823 * Render list of folders inside a folder.
1824 *
1825 * @param Folder $folder Folder
1826 * @return string HTML output
1827 */
1828 public function TBE_expandSubFolders(Folder $folder) {
1829 $content = '';
1830 if ($folder->checkActionPermission('read')) {
1831 $content .= $this->folderList($folder);
1832 }
1833 // Return accumulated content for folderlisting:
1834 return $content;
1835 }
1836
1837 /******************************************************************
1838 *
1839 * File listing
1840 *
1841 ******************************************************************/
1842 /**
1843 * For RTE: This displays all files from folder. No thumbnails shown
1844 *
1845 * @param Folder $folder The folder path to expand
1846 * @param string $extensionList List of file extensions to show
1847 * @return string HTML output
1848 */
1849 public function expandFolder(Folder $folder, $extensionList = '') {
1850 if (!$folder->checkActionPermission('read')) {
1851 return '';
1852 }
1853 $lang = $this->getLanguageService();
1854 $renderFolders = $this->act === 'folder';
1855 // Create header for file/folder listing:
1856 if ($renderFolders) {
1857 $out = $this->barheader($lang->getLL('folders') . ':');
1858 } else {
1859 $out = $this->barheader($lang->getLL('files') . ':');
1860 }
1861 // Prepare current path value for comparison (showing red arrow)
1862 $currentIdentifier = '';
1863 if ($this->curUrlInfo['value']) {
1864 $currentIdentifier = $this->curUrlInfo['info'];
1865 }
1866 // Create header element; The folder from which files are listed.
1867 $titleLen = (int)$this->getBackendUserAuthentication()->uc['titleLen'];
1868 $folderIcon = IconUtility::getSpriteIconForResource($folder);
1869 $folderIcon .= htmlspecialchars(GeneralUtility::fixed_lgd_cs($folder->getIdentifier(), $titleLen));
1870 $picon = '<a href="#" title="' . htmlspecialchars($folder->getIdentifier()) . '" onclick="return link_folder(\'file:' . $folder->getCombinedIdentifier() . '\');">'
1871 . $folderIcon . '</a>';
1872 if ($this->curUrlInfo['act'] == 'folder' && $currentIdentifier == $folder->getCombinedIdentifier()) {
1873 $out .= '<img'
1874 . IconUtility::skinImg($GLOBALS['BACK_PATH'], 'gfx/blinkarrow_left.gif', 'width="5" height="9"')
1875 . ' class="c-blinkArrowL" alt="" />';
1876 }
1877 $out .= $picon . '<br />';
1878 // Get files from the folder:
1879 if ($renderFolders) {
1880 $items = $folder->getSubfolders();
1881 } else {
1882 $items = $this->getFilesInFolder($folder, $extensionList);
1883 }
1884 $c = 0;
1885 $totalItems = count($items);
1886 foreach ($items as $fileOrFolderObject) {
1887 $c++;
1888 if ($renderFolders) {
1889 $fileIdentifier = $fileOrFolderObject->getCombinedIdentifier();
1890 $overlays = array();
1891 if ($fileOrFolderObject instanceof InaccessibleFolder) {
1892 $overlays = array('status-overlay-locked' => array());
1893 }
1894 $icon = IconUtility::getSpriteIcon(
1895 IconUtility::mapFileExtensionToSpriteIconName('folder'),
1896 array('title' => $fileOrFolderObject->getName()),
1897 $overlays);
1898 $itemUid = 'file:' . $fileIdentifier;
1899 } else {
1900 $fileIdentifier = $fileOrFolderObject->getUid();
1901 // Get size and icon:
1902 $size = ' (' . GeneralUtility::formatSize($fileOrFolderObject->getSize()) . 'bytes)';
1903 $icon = IconUtility::getSpriteIconForResource($fileOrFolderObject, array('title' => $fileOrFolderObject->getName() . $size));
1904 $itemUid = 'file:' . $fileIdentifier;
1905 }
1906 // If the listed file turns out to be the CURRENT file, then show blinking arrow:
1907 if (($this->curUrlInfo['act'] == 'file' || $this->curUrlInfo['act'] == 'folder')
1908 && $currentIdentifier == $fileIdentifier
1909 ) {
1910 $arrCol = '<img' . IconUtility::skinImg($GLOBALS['BACK_PATH'], 'gfx/blinkarrow_left.gif',
1911 'width="5" height="9"') . ' class="c-blinkArrowL" alt="" />';
1912 } else {
1913 $arrCol = '';
1914 }
1915 // Put it all together for the file element:
1916 $out .=
1917 '<img' .
1918 IconUtility::skinImg(
1919 $GLOBALS['BACK_PATH'],
1920 ('gfx/ol/join' . ($c == $totalItems ? 'bottom' : '') . '.gif'),
1921 'width="18" height="16"'
1922 ) . ' alt="" />' . $arrCol .
1923 '<a href="#" title="' . htmlspecialchars($fileOrFolderObject->getName()) . '" onclick="return link_folder(\'' . $itemUid . '\');">' .
1924 $icon .
1925 htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileOrFolderObject->getName(), $titleLen)) .
1926 '</a><br />';
1927 }
1928 return $out;
1929 }
1930
1931 /**
1932 * For TYPO3 Element Browser: Expand folder of files.
1933 *
1934 * @param Folder $folder The folder path to expand
1935 * @param string $extensionList List of fileextensions to show
1936 * @param bool $noThumbs Whether to show thumbnails or not. If set, no thumbnails are shown.
1937 * @return string HTML output
1938 */
1939 public function TBE_expandFolder(Folder $folder, $extensionList = '', $noThumbs = FALSE) {
1940 if (!$folder->checkActionPermission('read')) {
1941 return '';
1942 }
1943 $extensionList = $extensionList == '*' ? '' : $extensionList;
1944 $files = $this->getFilesInFolder($folder, $extensionList);
1945 return $this->fileList($files, $folder, $noThumbs);
1946 }
1947
1948 /**
1949 * Render list of files.
1950 *
1951 * @param File[] $files List of files
1952 * @param Folder $folder If set a header with a folder icon and folder name are shown
1953 * @param bool $noThumbs Whether to show thumbnails or not. If set, no thumbnails are shown.
1954 * @return string HTML output
1955 */
1956 protected function fileList(array $files, Folder $folder = NULL, $noThumbs = FALSE) {
1957 $out = '';
1958
1959 $lang = $this->getLanguageService();
1960 $lines = array();
1961 // Create headline (showing number of files):
1962 $filesCount = count($files);
1963 $out .= $this->barheader(sprintf($lang->getLL('files') . ' (%s):', $filesCount));
1964 $out .= '<div id="filelist">';
1965 $out .= $this->getBulkSelector($filesCount);
1966 $titleLen = (int)$this->getBackendUserAuthentication()->uc['titleLen'];
1967 // Create the header of current folder:
1968 if ($folder) {
1969 $folderIcon = IconUtility::getSpriteIconForResource($folder);
1970 $lines[] = '<tr class="t3-row-header">
1971 <td colspan="4">' . $folderIcon
1972 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($folder->getIdentifier(), $titleLen)) . '</td>
1973 </tr>';
1974 }
1975 if ($filesCount == 0) {
1976 $lines[] = '
1977 <tr class="file_list_normal">
1978 <td colspan="4">No files found.</td>
1979 </tr>';
1980 }
1981 // Traverse the file list:
1982 /** @var $fileObject \TYPO3\CMS\Core\Resource\File */
1983 foreach ($files as $fileObject) {
1984 $fileExtension = $fileObject->getExtension();
1985 // Thumbnail/size generation:
1986 $imgInfo = array();
1987 if (GeneralUtility::inList(strtolower($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']), strtolower($fileExtension)) && !$noThumbs) {
1988 $processedFile = $fileObject->process(
1989 ProcessedFile::CONTEXT_IMAGEPREVIEW,
1990 array('width' => 64, 'height' => 64)
1991 );
1992 $imageUrl = $processedFile->getPublicUrl(TRUE);
1993 $imgInfo = array(
1994 $fileObject->getProperty('width'),
1995 $fileObject->getProperty('height')
1996 );
1997 $pDim = $imgInfo[0] . 'x' . $imgInfo[1] . ' pixels';
1998 $clickIcon = '<img src="' . $imageUrl . '" ' .
1999 'width="' . $processedFile->getProperty('width') . '" ' .
2000 'height="' . $processedFile->getProperty('height') . '" ' .
2001 'hspace="5" vspace="5" border="1" />';
2002 } else {
2003 $clickIcon = '';
2004 $pDim = '';
2005 }
2006 // Create file icon:
2007 $size = ' (' . GeneralUtility::formatSize($fileObject->getSize()) . 'bytes' . ($pDim ? ', ' . $pDim : '') . ')';
2008 $icon = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileObject->getName() . $size));
2009 // Create links for adding the file:
2010 $filesIndex = count($this->elements);
2011 $this->elements['file_' . $filesIndex] = array(
2012 'type' => 'file',
2013 'table' => 'sys_file',
2014 'uid' => $fileObject->getUid(),
2015 'fileName' => $fileObject->getName(),
2016 'filePath' => $fileObject->getUid(),
2017 'fileExt' => $fileExtension,
2018 'fileIcon' => $icon
2019 );
2020 if ($this->fileIsSelectableInFileList($fileObject, $imgInfo)) {
2021 $ATag = '<a href="#" title="' . htmlspecialchars($fileObject->getName()) . '" onclick="return BrowseLinks.File.insertElement(\'file_' . $filesIndex . '\');">';
2022 $ATag_alt = substr($ATag, 0, -4) . ',1);">';
2023 $bulkCheckBox = '<input type="checkbox" class="typo3-bulk-item" name="file_' . $filesIndex . '" value="0" /> ';
2024 $ATag_e = '</a>';
2025 } else {
2026 $ATag = '';
2027 $ATag_alt = '';
2028 $ATag_e = '';
2029 $bulkCheckBox = '';
2030 }
2031 // Create link to showing details about the file in a window:
2032 $Ahref = $GLOBALS['BACK_PATH'] . 'show_item.php?type=file&table=_FILE&uid='
2033 . rawurlencode($fileObject->getCombinedIdentifier())
2034 . '&returnUrl=' . rawurlencode(GeneralUtility::getIndpEnv('REQUEST_URI'));
2035 $ATag2 = '<a href="' . htmlspecialchars($Ahref) . '">';
2036 $ATag2_e = '</a>';
2037 // Combine the stuff:
2038 $filenameAndIcon = $bulkCheckBox . $ATag_alt . $icon
2039 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileObject->getName(), $titleLen)) . $ATag_e;
2040 // Show element:
2041 if ($pDim) {
2042 // Image...
2043 $lines[] = '
2044 <tr class="file_list_normal">
2045 <td nowrap="nowrap">' . $filenameAndIcon . '&nbsp;</td>
2046 <td>' . $ATag . IconUtility::getSpriteIcon('actions-edit-add', array('title' => $lang->getLL('addToList', TRUE))) . $ATag_e . '</td>
2047 <td nowrap="nowrap">' . $ATag2 . IconUtility::getSpriteIcon('actions-document-info', array('title' => $lang->getLL('info', TRUE))) . $lang->getLL('info', TRUE) . $ATag2_e . '</td>
2048 <td nowrap="nowrap">&nbsp;' . $pDim . '</td>
2049 </tr>';
2050 $lines[] = '
2051 <tr>
2052 <td class="filelistThumbnail" colspan="4">' . $ATag_alt . $clickIcon . $ATag_e . '</td>
2053 </tr>';
2054 } else {
2055 $lines[] = '
2056 <tr class="file_list_normal">
2057 <td nowrap="nowrap">' . $filenameAndIcon . '&nbsp;</td>
2058 <td>' . $ATag . IconUtility::getSpriteIcon('actions-edit-add', array('title' => $lang->getLL('addToList', TRUE))) . $ATag_e . '</td>
2059 <td nowrap="nowrap">' . $ATag2 . IconUtility::getSpriteIcon('actions-document-info', array('title' => $lang->getLL('info', TRUE))) . $lang->getLL('info', TRUE) . $ATag2_e . '</td>
2060 <td>&nbsp;</td>
2061 </tr>';
2062 }
2063 }
2064 // Wrap all the rows in table tags:
2065 $out .= '
2066
2067 <!--
2068 File listing
2069 -->
2070 <table cellpadding="0" cellspacing="0" id="typo3-filelist">
2071 ' . implode('', $lines) . '
2072 </table>';
2073 // Return accumulated content for file listing:
2074 $out .= '</div>';
2075 return $out;
2076 }
2077
2078 /**
2079 * Checks if the given file is selectable in the file list.
2080 *
2081 * By default all files are selectable. This method may be overwritten in child classes.
2082 *
2083 * @param FileInterface $file
2084 * @param mixed[] $imgInfo Image dimensions from \TYPO3\CMS\Core\Imaging\GraphicalFunctions::getImageDimensions()
2085 * @return bool TRUE if file is selectable.
2086 */
2087 protected function fileIsSelectableInFileList(FileInterface $file, array $imgInfo) {
2088 return TRUE;
2089 }
2090
2091 /**
2092 * Render list of folders.
2093 *
2094 * @param Folder $baseFolder
2095 * @return string HTML output
2096 */
2097 public function folderList(Folder $baseFolder) {
2098 $content = '';
2099 $lang = $this->getLanguageService();
2100 $folders = $baseFolder->getSubfolders();
2101 $folderIdentifier = $baseFolder->getCombinedIdentifier();
2102 // Create headline (showing number of folders):
2103 $content .= $this->barheader(sprintf($lang->getLL('folders') . ' (%s):', count($folders)));
2104 $titleLength = (int)$this->getBackendUserAuthentication()->uc['titleLen'];
2105 // Create the header of current folder:
2106 $aTag = '<a href="#" onclick="return insertElement(\'\',' . GeneralUtility::quoteJSvalue($folderIdentifier)
2107 . ', \'folder\', ' . GeneralUtility::quoteJSvalue($folderIdentifier) . ', ' . GeneralUtility::quoteJSvalue($folderIdentifier)
2108 . ', \'\', \'\',\'\',1);">';
2109 // Add the foder icon
2110 $folderIcon = $aTag;
2111 $folderIcon .= IconUtility::getSpriteIcon('apps-filetree-folder-default');
2112 $folderIcon .= htmlspecialchars(GeneralUtility::fixed_lgd_cs($baseFolder->getName(), $titleLength));
2113 $folderIcon .= '</a>';
2114 $content .= $folderIcon . '<br />';
2115
2116 $lines = array();
2117 // Traverse the folder list:
2118 foreach ($folders as $subFolder) {
2119 $subFolderIdentifier = $subFolder->getCombinedIdentifier();
2120 // Create folder icon:
2121 $icon = '<img src="clear.gif" width="16" height="16" alt="" />';
2122 $icon .= IconUtility::getSpriteIcon('apps-filetree-folder-default', array('title' => htmlspecialchars($subFolder->getName())));
2123 // Create links for adding the folder:
2124 if ($this->P['itemName'] != '' && $this->P['formName'] != '') {
2125 $aTag = '<a href="#" onclick="return set_folderpath(' . GeneralUtility::quoteJSvalue($subFolderIdentifier)
2126 . ');">';
2127 } else {
2128 $aTag = '<a href="#" onclick="return insertElement(\'\',' . GeneralUtility::quoteJSvalue($subFolderIdentifier)
2129 . ', \'folder\', ' . GeneralUtility::quoteJSvalue($subFolderIdentifier) . ', '
2130 . GeneralUtility::quoteJSvalue($subFolderIdentifier) . ', \'\', \'\');">';
2131 }
2132 if (strstr($subFolderIdentifier, ',') || strstr($subFolderIdentifier, '|')) {
2133 // In case an invalid character is in the filepath, display error message:
2134 $errorMessage = GeneralUtility::quoteJSvalue(sprintf($lang->getLL('invalidChar'), ', |'));
2135 $aTag = ($aTag_alt = '<a href="#" onclick="alert(' . $errorMessage . ');return false;">');
2136 } else {
2137 // If foldername is OK, just add it:
2138 $aTag_alt = substr($aTag, 0, -4) . ',\'\',1);">';
2139 }
2140 $aTag_e = '</a>';
2141 // Combine icon and folderpath:
2142 $foldernameAndIcon = $aTag_alt . $icon
2143 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($subFolder->getName(), $titleLength)) . $aTag_e;
2144 if ($this->P['itemName'] != '') {
2145 $lines[] = '
2146 <tr class="bgColor4">
2147 <td nowrap="nowrap">' . $foldernameAndIcon . '&nbsp;</td>
2148 <td>&nbsp;</td>
2149 </tr>';
2150 } else {
2151 $lines[] = '
2152 <tr class="bgColor4">
2153 <td nowrap="nowrap">' . $foldernameAndIcon . '&nbsp;</td>
2154 <td>' . $aTag . IconUtility::getSpriteIcon('actions-edit-add', array('title' => $lang->getLL('addToList', TRUE))) . $aTag_e . ' </td>
2155 <td>&nbsp;</td>
2156 </tr>';
2157 }
2158 $lines[] = '
2159 <tr>
2160 <td colspan="3"><img src="clear.gif" width="1" height="3" alt="" /></td>
2161 </tr>';
2162 }
2163 // Wrap all the rows in table tags:
2164 $content .= '
2165
2166 <!--
2167 Folder listing
2168 -->
2169 <table border="0" cellpadding="0" cellspacing="1" id="typo3-folderList">
2170 ' . implode('', $lines) . '
2171 </table>';
2172 // Return accumulated content for folderlisting:
2173 return $content;
2174 }
2175
2176 /**
2177 * For RTE: This displays all IMAGES (gif,png,jpg) (from extensionList) from folder. Thumbnails are shown for images.
2178 * This listing is of images located in the web-accessible paths ONLY - the listing is for drag-n-drop use in the RTE
2179 *
2180 * @param Folder $folder The folder path to expand
2181 * @param string $extensionList List of file extensions to show
2182 * @return string HTML output
2183 */
2184 public function TBE_dragNDrop(Folder $folder, $extensionList = '') {
2185 if (!$folder) {
2186 return '';
2187 }
2188 $lang = $this->getLanguageService();
2189 if (!$folder->getStorage()->isPublic()) {
2190 // Print this warning if the folder is NOT a web folder
2191 return $this->barheader($lang->getLL('files'))
2192 . $this->getMsgBox($lang->getLL('noWebFolder'), 'status-dialog-warning');
2193 }
2194 $out = '';
2195
2196 // Read files from directory:
2197 $extensionList = $extensionList == '*' ? '' : $extensionList;
2198 $files = $this->getFilesInFolder($folder, $extensionList);
2199
2200 $out .= $this->barheader(sprintf($lang->getLL('files') . ' (%s):', count($files)));
2201 $titleLen = (int)$this->getBackendUserAuthentication()->uc['titleLen'];
2202 $picon = IconUtility::getSpriteIcon('apps-filetree-folder-default');
2203 $picon .= htmlspecialchars(GeneralUtility::fixed_lgd_cs(basename($folder->getName()), $titleLen));
2204 $out .= $picon . '<br />';
2205 // Init row-array:
2206 $lines = array();
2207 // Add "drag-n-drop" message:
2208 $lines[] = '
2209 <tr>
2210 <td colspan="2">' . $this->getMsgBox($lang->getLL('findDragDrop')) . '</td>
2211 </tr>';
2212 // Traverse files:
2213 foreach ($files as $fileObject) {
2214 // URL of image:
2215 $iUrl = GeneralUtility::rawurlencodeFP($fileObject->getPublicUrl(TRUE));
2216 // Show only web-images
2217 $fileExtension = strtolower($fileObject->getExtension());
2218 if (GeneralUtility::inList('gif,jpeg,jpg,png', $fileExtension)) {
2219 $imgInfo = array(
2220 $fileObject->getProperty('width'),
2221 $fileObject->getProperty('height')
2222 );
2223 $pDim = $imgInfo[0] . 'x' . $imgInfo[1] . ' pixels';
2224 $size = ' (' . GeneralUtility::formatSize($fileObject->getSize()) . 'bytes' . ($pDim ? ', ' . $pDim : '') . ')';
2225 $filenameAndIcon = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileObject->getName() . $size));
2226 if (GeneralUtility::_GP('noLimit')) {
2227 $maxW = 10000;
2228 $maxH = 10000;
2229 } else {
2230 $maxW = 380;
2231 $maxH = 500;
2232 }
2233 $IW = $imgInfo[0];
2234 $IH = $imgInfo[1];
2235 if ($IW > $maxW) {
2236 $IH = ceil($IH / $IW * $maxW);
2237 $IW = $maxW;
2238 }
2239 if ($IH > $maxH) {
2240 $IW = ceil($IW / $IH * $maxH);
2241 $IH = $maxH;
2242 }
2243 // Make row:
2244 $lines[] = '
2245 <tr class="bgColor4">
2246 <td nowrap="nowrap">' . $filenameAndIcon . '&nbsp;</td>
2247 <td nowrap="nowrap">' . ($imgInfo[0] != $IW
2248 ? '<a href="' . htmlspecialchars(GeneralUtility::linkThisScript(array('noLimit' => '1')))
2249 . '">' . IconUtility::getSpriteIcon('status-dialog-warning', array('title' => $lang->getLL('clickToRedrawFullSize', TRUE)))
2250 . '</a>'
2251 : '')
2252 . $pDim . '&nbsp;</td>
2253 </tr>';
2254 $lines[] = '
2255 <tr>
2256 <td colspan="2"><img src="' . htmlspecialchars($iUrl) . '" data-htmlarea-file-uid="' . $fileObject->getUid()
2257 . '" width="' . htmlspecialchars($IW) . '" height="' . htmlspecialchars($IH) . '" border="1" alt="" /></td>
2258 </tr>';
2259 $lines[] = '
2260 <tr>
2261 <td colspan="2"><img src="clear.gif" width="1" height="3" alt="" /></td>
2262 </tr>';
2263 }
2264 }
2265 // Finally, wrap all rows in a table tag:
2266 $out .= '
2267
2268
2269 <!--
2270 File listing / Drag-n-drop
2271 -->
2272 <table border="0" cellpadding="0" cellspacing="1" id="typo3-dragBox">
2273 ' . implode('', $lines) . '
2274 </table>';
2275
2276 return $out;
2277 }
2278
2279 /******************************************************************
2280 *
2281 * Miscellaneous functions
2282 *
2283 ******************************************************************/
2284
2285 /**
2286 * Prints a 'header' where string is in a tablecell
2287 *
2288 * @param string $str The string to print in the header. The value is htmlspecialchars()'ed before output.
2289 * @return string The header HTML (wrapped in a table)
2290 */
2291 public function barheader($str) {
2292 return '
2293 <!-- Bar header: -->
2294 <h3>' . htmlspecialchars($str) . '</h3>
2295 ';
2296 }
2297
2298 /**
2299 * Displays a message box with the input message
2300 *
2301 * @param string $inputMessage Input message to show (will be htmlspecialchars()'ed inside of this function)
2302 * @param string $icon Sprite sprite name. Default is 'actions-document-info'.
2303 * @return string HTML for the message (wrapped in a table).
2304 */
2305 public function getMsgBox($inputMessage, $icon = 'actions-document-info') {
2306 return '
2307 <!-- Message box -->
2308 <table cellspacing="0" class="bgColor4" id="typo3-msgBox">
2309 <tr>
2310 <td>' . IconUtility::getSpriteIcon($icon) . htmlspecialchars($inputMessage) . '</td>
2311 </tr>
2312 </table>
2313 ';
2314 }
2315
2316 /**
2317 * For RTE/link: This prints the 'currentUrl'
2318 *
2319 * @param string $str URL value. The value is htmlspecialchars()'ed before output.
2320 * @return string HTML content, wrapped in a table.
2321 */
2322 public function printCurrentUrl($str) {
2323 // Output the folder or file identifier, when working with files
2324 if (isset($str) && MathUtility::canBeInterpretedAsInteger($str)) {
2325 try {
2326 $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($str);
2327 } catch (Exception\FileDoesNotExistException $e) {
2328 $fileObject = NULL;
2329 }
2330 $str = is_object($fileObject) ? $fileObject->getIdentifier() : '';
2331 }
2332 if ($str !== '') {
2333 return '
2334 <!-- Print current URL -->
2335 <table border="0" cellpadding="0" cellspacing="0" id="typo3-curUrl">
2336 <tr>
2337 <td>' . $this->getLanguageService()->getLL('currentLink', TRUE) . ': '
2338 . htmlspecialchars(rawurldecode($str)) . '</td>
2339 </tr>
2340 </table>';
2341 } else {
2342 return '';
2343 }
2344 }
2345
2346 /**
2347 * For RTE/link: Parses the incoming URL and determines if it's a page, file, external or mail address.
2348 *
2349 * @param string $href HREF value tp analyse
2350 * @param string $siteUrl The URL of the current website (frontend)
2351 * @return array[] Array with URL information stored in assoc. keys: value, act (page, file, spec, mail), pageid, cElement, info
2352 */
2353 public function parseCurUrl($href, $siteUrl) {
2354 $href = trim($href);
2355 $lang = $this->getLanguageService();
2356 if ($href) {
2357 $info = array();
2358 // Default is "url":
2359 $info['value'] = $href;
2360 $info['act'] = 'url';
2361 $specialParts = explode('#_SPECIAL', $href);
2362 // Special kind (Something RTE specific: User configurable links through: "userLinks." from ->thisConfig)
2363 if (count($specialParts) == 2) {
2364 $info['value'] = '#_SPECIAL' . $specialParts[1];
2365 $info['act'] = 'spec';
2366 } elseif (!StringUtility::beginsWith($href, 'file://') && strpos($href, 'file:') !== FALSE) {
2367 $rel = substr($href, strpos($href, 'file:') + 5);
2368 $rel = rawurldecode($rel);
2369 // resolve FAL-api "file:UID-of-sys_file-record" and "file:combined-identifier"
2370 $fileOrFolderObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($rel);
2371 if ($fileOrFolderObject instanceof Folder) {
2372 $info['act'] = 'folder';
2373 $info['value'] = $fileOrFolderObject->getCombinedIdentifier();
2374 } elseif ($fileOrFolderObject instanceof File) {
2375 $info['act'] = 'file';
2376 $info['value'] = $fileOrFolderObject->getUid();
2377 } else {
2378 $info['value'] = $rel;
2379 }
2380 } elseif (StringUtility::beginsWith($href, $siteUrl)) {
2381 // If URL is on the current frontend website:
2382 // URL is a file, which exists:
2383 if (file_exists(PATH_site . rawurldecode($href))) {
2384 $info['value'] = rawurldecode($href);
2385 if (@is_dir((PATH_site . $info['value']))) {
2386 $info['act'] = 'folder';
2387 } else {
2388 $info['act'] = 'file';
2389 }
2390 } else {
2391 // URL is a page (id parameter)
2392 $uP = parse_url($href);
2393
2394 $pp = preg_split('/^id=/', $uP['query']);
2395 $pp[1] = preg_replace('/&id=[^&]*/', '', $pp[1]);
2396 $parameters = explode('&', $pp[1]);
2397 $id = array_shift($parameters);
2398 if ($id) {
2399 // Checking if the id-parameter is an alias.
2400 if (!MathUtility::canBeInterpretedAsInteger($id)) {
2401 list($idPartR) = BackendUtility::getRecordsByField('pages', 'alias', $id);
2402 $id = (int)$idPartR['uid'];
2403 }
2404 $pageRow = BackendUtility::getRecordWSOL('pages', $id);
2405 $titleLen = (int)$this->getBackendUserAuthentication()->uc['titleLen'];
2406 $info['value'] = ((((($lang->getLL('page', TRUE) . ' \'')
2407 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($pageRow['title'], $titleLen)))
2408 . '\' (ID:') . $id) . ($uP['fragment'] ? ', #' . $uP['fragment'] : '')) . ')';
2409 $info['pageid'] = $id;
2410 $info['cElement'] = $uP['fragment'];
2411 $info['act'] = 'page';
2412 $info['query'] = $parameters[0] ? '&' . implode('&', $parameters) : '';
2413 }
2414 }
2415 } else {
2416 // Email link:
2417 if (strtolower(substr($href, 0, 7)) === 'mailto:') {
2418 $info['value'] = trim(substr($href, 7));
2419 $info['act'] = 'mail';
2420 }
2421 }
2422 $info['info'] = $info['value'];
2423 } else {
2424 // NO value input:
2425 $info = array();
2426 $info['info'] = $lang->getLL('none');
2427 $info['value'] = '';
2428 $info['act'] = 'page';
2429 }
2430 // let the hook have a look
2431 foreach ($this->hookObjects as $hookObject) {
2432 $info = $hookObject->parseCurrentUrl($href, $siteUrl, $info);
2433 }
2434 return $info;
2435 }
2436
2437 /**
2438 * Setter for the class that should be used by TBE_expandPage() to generate the record list.
2439 * This method is intended to be used by Extensions that implement their own browsing functionality.
2440 *
2441 * @param ElementBrowserRecordList $recordList
2442 * @throws \InvalidArgumentException
2443 * @return void
2444 * @api
2445 */
2446 public function setRecordList($recordList) {
2447 if (!$recordList instanceof ElementBrowserRecordList) {
2448 throw new \InvalidArgumentException('$recordList needs to be an instance of ' . ElementBrowserRecordList::class, 1370878522);
2449 }
2450 $this->recordList = $recordList;
2451 }
2452
2453 /**
2454 * For TBE: Makes an upload form for uploading files to the filemount the user is browsing.
2455 * The files are uploaded to the tce_file.php script in the core which will handle the upload.
2456 *
2457 * @param Folder $folderObject Absolute filepath on server to which to upload.
2458 * @return string HTML for an upload form.
2459 */
2460 public function uploadForm(Folder $folderObject) {
2461 if (!$folderObject->checkActionPermission('write')) {
2462 return '';
2463 }
2464 // Read configuration of upload field count
2465 $userSetting = $this->getBackendUserAuthentication()->getTSConfigVal('options.folderTree.uploadFieldsInLinkBrowser');
2466 $count = isset($userSetting) ? $userSetting : 1;
2467 if ($count === '0') {
2468 return '';
2469 }
2470 $count = (int)$count === 0 ? 1 : (int)$count;
2471 // Create header, showing upload path:
2472 $header = $folderObject->getIdentifier();
2473 $lang = $this->getLanguageService();
2474 $code = '
2475 <br />
2476 <!--
2477 Form, for uploading files:
2478 -->
2479 <form action="' . htmlspecialchars(BackendUtility::getModuleUrl('tce_file')) . '" method="post" name="editform"'
2480 . ' id="typo3-uplFilesForm" enctype="' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['form_enctype'] . '">
2481 <table border="0" cellpadding="0" cellspacing="0" id="typo3-uplFiles">
2482 <tr>
2483 <td>' . $this->barheader($lang->sL(
2484 'LLL:EXT:lang/locallang_core.xlf:file_upload.php.pagetitle', TRUE) . ':') . '</td>
2485 </tr>
2486 <tr>
2487 <td class="c-wCell c-hCell"><strong>' . $lang->getLL('path', TRUE) . ':</strong> '
2488 . htmlspecialchars($header) . '</td>
2489 </tr>
2490 <tr>
2491 <td class="c-wCell c-hCell">';
2492 // Traverse the number of upload fields (default is 3):
2493 for ($a = 1; $a <= $count; $a++) {
2494 $code .= '<input type="file" multiple="multiple" name="upload_' . $a . '[]"' . $this->doc->formWidth(35)
2495 . ' size="50" />
2496 <input type="hidden" name="file[upload][' . $a . '][target]" value="'
2497 . htmlspecialchars($folderObject->getCombinedIdentifier()) . '" />
2498 <input type="hidden" name="file[upload][' . $a . '][data]" value="' . $a . '" /><br />';
2499 }
2500 // Make footer of upload form, including the submit button:
2501 $redirectValue = $this->getThisScript() . 'act=' . $this->act . '&mode=' . $this->mode
2502 . '&expandFolder=' . rawurlencode($folderObject->getCombinedIdentifier())
2503 . '&bparams=' . rawurlencode($this->bparams)
2504 . (is_array($this->P) ? GeneralUtility::implodeArrayForUrl('P', $this->P) : '');
2505 $code .= '<input type="hidden" name="redirect" value="' . htmlspecialchars($redirectValue) . '" />';
2506 $code .= FormEngine::getHiddenTokenField('tceAction');
2507 $code .= '
2508 <div id="c-override">
2509 <label>
2510 <input type="checkbox" name="overwriteExistingFiles" id="overwriteExistingFiles" value="1" /> '
2511 . $lang->sL('LLL:EXT:lang/locallang_misc.xlf:overwriteExistingFiles', TRUE) . '
2512 </label>
2513 </div>
2514 <input class="btn btn-default" type="submit" name="submit" value="'
2515 . $lang->sL('LLL:EXT:lang/locallang_core.xlf:file_upload.php.submit', TRUE) . '" />
2516 ';
2517 $code .= '</td>
2518 </tr>
2519 </table>
2520 </form><br />';
2521 return $code;
2522 }
2523
2524 /**
2525 * For TBE: Makes a form for creating new folders in the filemount the user is browsing.
2526 * The folder creation request is sent to the tce_file.php script in the core which will handle the creation.
2527 *
2528 * @param Folder $folderObject Absolute filepath on server in which to create the new folder.
2529 * @return string HTML for the create folder form.
2530 */
2531 public function createFolder(Folder $folderObject) {
2532 if (!$folderObject->checkActionPermission('write')) {
2533 return '';
2534 }
2535 $backendUser = $this->getBackendUserAuthentication();
2536 if (!($backendUser->isAdmin() || $backendUser->getTSConfigVal('options.createFoldersInEB'))) {
2537 return '';
2538 }
2539 // Don't show Folder-create form if it's denied
2540 if ($backendUser->getTSConfigVal('options.folderTree.hideCreateFolder')) {
2541 return '';
2542 }
2543 $lang = $this->getLanguageService();
2544 // Create header, showing upload path:
2545 $header = $folderObject->getIdentifier();
2546 $code = '
2547
2548 <!--
2549 Form, for creating new folders:
2550 -->
2551 <form action="' . htmlspecialchars(BackendUtility::getModuleUrl('tce_file')) . '" method="post" name="editform2" id="typo3-crFolderForm">
2552 <table border="0" cellpadding="0" cellspacing="0" id="typo3-crFolder">
2553 <tr>
2554 <td>' . $this->barheader($lang->sL(
2555 'LLL:EXT:lang/locallang_core.xlf:file_newfolder.php.pagetitle') . ':') . '</td>
2556 </tr>
2557 <tr>
2558 <td class="c-wCell c-hCell"><strong>'
2559 . $lang->getLL('path', TRUE) . ':</strong> ' . htmlspecialchars($header) . '</td>
2560 </tr>
2561 <tr>
2562 <td class="c-wCell c-hCell">';
2563 // Create the new-folder name field:
2564 $a = 1;
2565 $code .= '<input' . $this->doc->formWidth(20) . ' type="text" name="file[newfolder][' . $a . '][data]" />'
2566 . '<input type="hidden" name="file[newfolder][' . $a . '][target]" value="'
2567 . htmlspecialchars($folderObject->getCombinedIdentifier()) . '" />';
2568 // Make footer of upload form, including the submit button:
2569 $redirectValue = $this->getThisScript() . 'act=' . $this->act . '&mode=' . $this->mode
2570 . '&expandFolder=' . rawurlencode($folderObject->getCombinedIdentifier())
2571 . '&bparams=' . rawurlencode($this->bparams)
2572 . (is_array($this->P) ? GeneralUtility::implodeArrayForUrl('P', $this->P) : '');
2573 $code .= '<input type="hidden" name="redirect" value="' . htmlspecialchars($redirectValue) . '" />'
2574 . FormEngine::getHiddenTokenField('tceAction')
2575 . '<input class="btn btn-default" type="submit" name="submit" value="'
2576 . $lang->sL('LLL:EXT:lang/locallang_core.xlf:file_newfolder.php.submit', TRUE) . '" />';
2577 $code .= '</td>
2578 </tr>
2579 </table>
2580 </form>';
2581 return $code;
2582 }
2583
2584 /**
2585 * Get the HTML data required for a bulk selection of files of the TYPO3 Element Browser.
2586 *
2587 * @param int $filesCount Number of files currently displayed
2588 * @return string HTML data required for a bulk selection of files - if $filesCount is 0, nothing is returned
2589 */
2590 public function getBulkSelector($filesCount) {
2591 if (!$filesCount) {
2592 return '';
2593 }
2594
2595 $lang = $this->getLanguageService();
2596 $labelToggleSelection = $lang->sL('LLL:EXT:lang/locallang_browse_links.xlf:toggleSelection', TRUE);
2597 $labelImportSelection = $lang->sL('LLL:EXT:lang/locallang_browse_links.xlf:importSelection', TRUE);
2598 // Getting flag for showing/not showing thumbnails:
2599 $noThumbsInEB = $this->getBackendUserAuthentication()->getTSConfigVal('options.noThumbsInEB');
2600 $out = $this->doc->spacer(10) . '<div>' . '<a href="#" onclick="BrowseLinks.Selector.handle()">'
2601 . IconUtility::getSpriteIcon('actions-document-import-t3d', array('title' => $labelImportSelection))
2602 . $labelImportSelection . '</a>&nbsp;&nbsp;&nbsp;'
2603 . '<a href="#" onclick="BrowseLinks.Selector.toggle()">'
2604 . IconUtility::getSpriteIcon('actions-document-select', array('title' => $labelToggleSelection))
2605 . $labelToggleSelection . '</a>' . '</div>';
2606 if (!$noThumbsInEB && $this->selectedFolder) {
2607 // MENU-ITEMS, fetching the setting for thumbnails from File>List module:
2608 $_MOD_MENU = array('displayThumbs' => '');
2609 $_MCONF['name'] = 'file_list';
2610 $_MOD_SETTINGS = BackendUtility::getModuleData($_MOD_MENU, GeneralUtility::_GP('SET'), $_MCONF['name']);
2611 $addParams = '&act=' . $this->act . '&mode=' . $this->mode
2612 . '&expandFolder=' . rawurlencode($this->selectedFolder->getCombinedIdentifier())
2613 . '&bparams=' . rawurlencode($this->bparams);
2614 $thumbNailCheck = BackendUtility::getFuncCheck('', 'SET[displayThumbs]', $_MOD_SETTINGS['displayThumbs'],
2615 GeneralUtility::_GP('M') ? '' : $this->thisScript, $addParams, 'id="checkDisplayThumbs"')
2616 . ' <label for="checkDisplayThumbs">'
2617 . $lang->sL('LLL:EXT:lang/locallang_mod_file_list.xlf:displayThumbs', TRUE) . '</label>';
2618 $out .= $this->doc->spacer(5) . $thumbNailCheck . $this->doc->spacer(15);
2619 } else {
2620 $out .= $this->doc->spacer(15);
2621 }
2622 return $out;
2623 }
2624
2625 /**
2626 * Determines whether submitted field change functions are valid
2627 * and are coming from the system and not from an external abuse.
2628 *
2629 * @param bool $handleFlexformSections Whether to handle flexform sections differently
2630 * @return bool Whether the submitted field change functions are valid
2631 */
2632 protected function areFieldChangeFunctionsValid($handleFlexformSections = FALSE) {
2633 $result = FALSE;
2634 if (isset($this->P['fieldChangeFunc']) && is_array($this->P['fieldChangeFunc']) && isset($this->P['fieldChangeFuncHash'])) {
2635 $matches = array();
2636 $pattern = '#\\[el\\]\\[(([^]-]+-[^]-]+-)(idx\\d+-)([^]]+))\\]#i';
2637 $fieldChangeFunctions = $this->P['fieldChangeFunc'];
2638 // Special handling of flexform sections:
2639 // Field change functions are modified in JavaScript, thus the hash is always invalid
2640 if ($handleFlexformSections && preg_match($pattern, $this->P['itemName'], $matches)) {
2641 $originalName = $matches[1];
2642 $cleanedName = $matches[2] . $matches[4];
2643 foreach ($fieldChangeFunctions as &$value) {
2644 $value = str_replace($originalName, $cleanedName, $value);
2645 }
2646 unset($value);
2647 }
2648 $result = $this->P['fieldChangeFuncHash'] === GeneralUtility::hmac(serialize($fieldChangeFunctions));
2649 }
2650 return $result;
2651 }
2652
2653 /**
2654 * Check if a temporary tree mount is set and return a cancel button
2655 *
2656 * @return string
2657 */
2658 protected function getTemporaryTreeMountCancelNotice() {
2659 if ((int)$this->getBackendUserAuthentication()->getSessionData('pageTree_temporaryMountPoint') === 0) {
2660 return '';
2661 }
2662 $link = '<a href="' . htmlspecialchars(GeneralUtility::linkThisScript(array('setTempDBmount' => 0))) . '">'
2663 . $this->getLanguageService()->sl('LLL:EXT:lang/locallang_core.xlf:labels.temporaryDBmount', TRUE) . '</a>';
2664 /** @var FlashMessage $flashMessage */
2665 $flashMessage = GeneralUtility::makeInstance(
2666 FlashMessage::class,
2667 $link,
2668 '',
2669 FlashMessage::INFO
2670 );
2671 return $flashMessage->render();
2672 }
2673
2674 /**
2675 * Get a list of Files in a folder filtered by extension
2676 *
2677 * @param Folder $folder
2678 * @param string $extensionList
2679 * @return \TYPO3\CMS\Core\Resource\File[]
2680 */
2681 protected function getFilesInFolder(Folder $folder, $extensionList) {
2682 if ($extensionList !== '') {
2683 /** @var FileExtensionFilter $filter */
2684 $filter = GeneralUtility::makeInstance(FileExtensionFilter::class);
2685 $filter->setAllowedFileExtensions($extensionList);
2686 $folder->setFileAndFolderNameFilters(array(array($filter, 'filterFileList')));
2687 }
2688 return $folder->getFiles();
2689 }
2690
2691 /**
2692 * @return LanguageService
2693 */
2694 protected function getLanguageService() {
2695 return $GLOBALS['LANG'];
2696 }
2697
2698 /**
2699 * @return BackendUserAuthentication
2700 */
2701 protected function getBackendUserAuthentication() {
2702 return $GLOBALS['BE_USER'];
2703 }
2704
2705 /**
2706 * @return DatabaseConnection
2707 */
2708 protected function getDatabaseConnection() {
2709 return $GLOBALS['TYPO3_DB'];
2710 }
2711
2712 }