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