[TASK] Remove width/height fields for links in ElementBrowser
[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 ((string)$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 * Rich Text Editor (RTE) link selector (MAIN function)
867 * Generates the link selector for the Rich Text Editor.
868 * Can also be used to select links for the TCEforms (see $wiz)
869 *
870 * @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
871 * @return string Modified content variable.
872 */
873 public function main_rte($wiz = FALSE) {
874 // needs to be executed before doc->startPage()
875 if (in_array($this->act, array('file', 'folder'))) {
876 $this->doc->getDragDropCode('folders', 'Tree.ajaxID = "SC_alt_file_navframe::expandCollapse"');
877 } elseif ($this->act === 'page') {
878 $this->doc->getDragDropCode('pages');
879 }
880 // Starting content:
881 $content = $this->doc->startPage('RTE link');
882 // Add the FlashMessages if any
883 $content .= $this->doc->getFlashMessages();
884
885 $content .= $this->doc->getTabMenuRaw($this->buildMenuArray($wiz, $this->getAllowedItems('page,file,folder,url,mail')));
886 // Adding the menu and header to the top of page:
887 $content .= $this->printCurrentUrl($this->curUrlInfo['info']) . '<br />';
888 // Depending on the current action we will create the actual module content for selecting a link:
889 switch ($this->act) {
890 case 'mail':
891 $content .= $this->getEmailSelectorHtml();
892 break;
893 case 'url':
894 $content .= $this->getExternalUrlSelectorHtml();
895 break;
896 case 'file':
897 case 'folder':
898 $content .= $this->getFileSelectorHtml();
899 break;
900 case 'page':
901 $content .= $this->getPageSelectorHtml();
902 break;
903 default:
904 // Call hook
905 foreach ($this->hookObjects as $hookObject) {
906 $content .= $hookObject->getTab($this->act);
907 }
908 }
909 $lang = $this->getLanguageService();
910
911 // Removing link fields if configured
912 $blindLinkFields = isset($this->RTEProperties['default.']['blindLinkFields'])
913 ? GeneralUtility::trimExplode(',', $this->RTEProperties['default.']['blindLinkFields'], TRUE)
914 : array();
915 $pBlindLinkFields = isset($this->P['params']['blindLinkFields'])
916 ? GeneralUtility::trimExplode(',', $this->P['params']['blindLinkFields'], TRUE)
917 : array();
918 $allowedFields = array_diff(array('target', 'title', 'class', 'params'), $blindLinkFields, $pBlindLinkFields);
919
920 if (in_array('params', $allowedFields, TRUE) && $this->act !== 'url') {
921 $content .= '
922 <!--
923 Selecting params for link:
924 -->
925 <form action="" name="lparamsform" id="lparamsform">
926 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkParams">
927 <tr>
928 <td style="width: 96px;">' . $lang->getLL('params', TRUE) . '</td>
929 <td><input type="text" name="lparams" class="typo3-link-input" onchange="'
930 . 'browse_links_setParams(this.value);" value="' . htmlspecialchars($this->setParams)
931 . '" /></td>
932 </tr>
933 </table>
934 </form>
935 ';
936 }
937 if (in_array('class', $allowedFields, TRUE)) {
938 $content .= '
939 <!--
940 Selecting class for link:
941 -->
942 <form action="" name="lclassform" id="lclassform">
943 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkClass">
944 <tr>
945 <td style="width: 96px;">' . $lang->getLL('class', TRUE) . '</td>
946 <td><input type="text" name="lclass" class="typo3-link-input" onchange="'
947 . 'browse_links_setClass(this.value);" value="' . htmlspecialchars($this->setClass)
948 . '" /></td>
949 </tr>
950 </table>
951 </form>
952 ';
953 }
954 if (in_array('title', $allowedFields, TRUE)) {
955 $content .= '
956 <!--
957 Selecting title for link:
958 -->
959 <form action="" name="ltitleform" id="ltitleform">
960 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkTitle">
961 <tr>
962 <td style="width: 96px;">' . $lang->getLL('title', TRUE) . '</td>
963 <td><input type="text" name="ltitle" class="typo3-link-input" onchange="'
964 . 'browse_links_setTitle(this.value);" value="' . htmlspecialchars($this->setTitle)
965 . '" /></td>
966 </tr>
967 </table>
968 </form>
969 ';
970 }
971 // additional fields for page links
972 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][$this->hookName]['addFields_PageLink'])
973 && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][$this->hookName]['addFields_PageLink'])
974 ) {
975 $conf = array();
976 $_params = array(
977 'conf' => &$conf
978 );
979 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][$this->hookName]['addFields_PageLink'] as $objRef) {
980 $processor =& GeneralUtility::getUserObj($objRef);
981 $content .= $processor->addFields($_params, $this);
982 }
983 }
984 // Target:
985 if ($this->act !== 'mail' && in_array('target', $allowedFields, TRUE)) {
986 $ltarget = '
987
988 <!--
989 Selecting target for link:
990 -->
991 <form action="" name="ltargetform" id="ltargetform">
992 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkTarget">
993 <tr>
994 <td>' . $lang->getLL('target', TRUE) . ':</td>
995 <td><input type="text" name="ltarget" onchange="browse_links_setTarget(this.value);" value="'
996 . htmlspecialchars($this->setTarget) . '"' . $this->doc->formWidth(10) . ' /></td>
997 <td>
998 <select name="ltarget_type" onchange="browse_links_setTarget('
999 . 'this.options[this.selectedIndex].value);document.ltargetform.ltarget.value='
1000 . 'this.options[this.selectedIndex].value;this.selectedIndex=0;">
1001 <option></option>
1002 <option value="_top">' . $lang->getLL('top', TRUE) . '</option>
1003 <option value="_blank">' . $lang->getLL('newWindow', TRUE) . '</option>
1004 </select>
1005 </td>
1006 <td>';
1007 if (($this->curUrlInfo['act'] === 'page' || $this->curUrlInfo['act'] === 'file' || $this->curUrlInfo['act'] === 'folder')
1008 && $this->curUrlArray['href'] && $this->curUrlInfo['act'] === $this->act
1009 ) {
1010 $ltarget .= '
1011 <input class="btn btn-default" type="submit" value="' . $lang->getLL('update', TRUE)
1012 . '" onclick="return link_current();" />';
1013 }
1014 $ltarget .= ' </td>
1015 </tr>
1016 </table>
1017 </form>';
1018 // Add "target selector" box to content:
1019 $content .= $ltarget;
1020 // Add some space
1021 $content .= '<br /><br />';
1022 }
1023 // End page, return content:
1024 $content .= $this->doc->endPage();
1025 $content = $this->doc->insertStylesAndJS($content);
1026 return $content;
1027 }
1028
1029 /**
1030 * Get the allowed items or tabs
1031 *
1032 * @param string $items initial list of possible items
1033 * @return array the allowed items
1034 */
1035 public function getAllowedItems($items) {
1036 $allowedItems = explode(',', $items);
1037 // Call hook for extra options
1038 foreach ($this->hookObjects as $hookObject) {
1039 $allowedItems = $hookObject->addAllowedItems($allowedItems);
1040 }
1041
1042 // Initializing the action value, possibly removing blinded values etc:
1043 $blindLinkOptions = isset($this->RTEProperties['default.']['blindLinkOptions'])
1044 ? GeneralUtility::trimExplode(',', $this->RTEProperties['default.']['blindLinkOptions'], TRUE)
1045 : array();
1046 $pBlindLinkOptions = isset($this->P['params']['blindLinkOptions'])
1047 ? GeneralUtility::trimExplode(',', $this->P['params']['blindLinkOptions'])
1048 : array();
1049 $allowedItems = array_diff($allowedItems, $blindLinkOptions, $pBlindLinkOptions);
1050
1051 reset($allowedItems);
1052 if (!in_array($this->act, $allowedItems)) {
1053 $this->act = current($allowedItems);
1054 }
1055 return $allowedItems;
1056 }
1057
1058 /**
1059 * Returns an array definition of the top menu
1060 *
1061 * @param bool $wiz
1062 * @param array $allowedItems
1063 * @return mixed[][]
1064 */
1065 protected function buildMenuArray($wiz, $allowedItems) {
1066 $lang = $this->getLanguageService();
1067
1068 $menuDef = array();
1069 if (!$wiz && $this->curUrlArray['href']) {
1070 $menuDef['removeLink']['isActive'] = $this->act === 'removeLink';
1071 $menuDef['removeLink']['label'] = $lang->getLL('removeLink', TRUE);
1072 $menuDef['removeLink']['url'] = '#';
1073 $menuDef['removeLink']['addParams'] = 'onclick="plugin.unLink();return false;"';
1074 }
1075 if (in_array('page', $allowedItems, TRUE)) {
1076 $menuDef['page']['isActive'] = $this->act === 'page';
1077 $menuDef['page']['label'] = $lang->getLL('page', TRUE);
1078 $menuDef['page']['url'] = '#';
1079 $menuDef['page']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=page&mode=' . $this->mode . '&bparams=' . $this->bparams) . ');return false;"';
1080 }
1081 if (in_array('file', $allowedItems, TRUE)) {
1082 $menuDef['file']['isActive'] = $this->act === 'file';
1083 $menuDef['file']['label'] = $lang->getLL('file', TRUE);
1084 $menuDef['file']['url'] = '#';
1085 $menuDef['file']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=file&mode=' . $this->mode . '&bparams=' . $this->bparams) . ');return false;"';
1086 }
1087 if (in_array('folder', $allowedItems, TRUE)) {
1088 $menuDef['folder']['isActive'] = $this->act === 'folder';
1089 $menuDef['folder']['label'] = $lang->getLL('folder', TRUE);
1090 $menuDef['folder']['url'] = '#';
1091 $menuDef['folder']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=folder&mode=' . $this->mode . '&bparams=' . $this->bparams) . ');return false;"';
1092 }
1093 if (in_array('url', $allowedItems, TRUE)) {
1094 $menuDef['url']['isActive'] = $this->act === 'url';
1095 $menuDef['url']['label'] = $lang->getLL('extUrl', TRUE);
1096 $menuDef['url']['url'] = '#';
1097 $menuDef['url']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=url&mode=' . $this->mode . '&bparams=' . $this->bparams) . ');return false;"';
1098 }
1099 if (in_array('mail', $allowedItems, TRUE)) {
1100 $menuDef['mail']['isActive'] = $this->act === 'mail';
1101 $menuDef['mail']['label'] = $lang->getLL('email', TRUE);
1102 $menuDef['mail']['url'] = '#';
1103 $menuDef['mail']['addParams'] = 'onclick="jumpToUrl(' . GeneralUtility::quoteJSvalue('?act=mail&mode=' . $this->mode . '&bparams=' . $this->bparams) . ');return false;"';
1104 }
1105 // Call hook for extra options
1106 foreach ($this->hookObjects as $hookObject) {
1107 $menuDef = $hookObject->modifyMenuDefinition($menuDef);
1108 }
1109 return $menuDef;
1110 }
1111
1112 /**
1113 * Returns HTML of the email link from
1114 *
1115 * @return string
1116 */
1117 protected function getEmailSelectorHtml() {
1118 $lang = $this->getLanguageService();
1119 $extUrl = '
1120 <!--
1121 Enter mail address:
1122 -->
1123 <form action="" name="lurlform" id="lurlform">
1124 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkMail">
1125 <tr>
1126 <td style="width: 96px;">
1127 ' . $lang->getLL('emailAddress', TRUE) . ':
1128 </td>
1129 <td>
1130 <input type="text" name="lemail"' . $this->doc->formWidth(20) . ' value="'
1131 . htmlspecialchars(($this->curUrlInfo['act'] === 'mail' ? $this->curUrlInfo['info'] : ''))
1132 . '" />
1133 <input class="btn btn-default" type="submit" value="' . $lang->getLL('setLink', TRUE)
1134 . '" onclick="browse_links_setTarget(\'\');browse_links_setValue(\'mailto:\'+'
1135 . 'document.lurlform.lemail.value); return link_current();" />
1136 </td>
1137 </tr>
1138 </table>
1139 </form>';
1140 return $extUrl;
1141 }
1142
1143 /**
1144 * Returns HTML of the external url link from
1145 *
1146 * @return string
1147 */
1148 protected function getExternalUrlSelectorHtml() {
1149 $extUrl = '
1150
1151 <!--
1152 Enter External URL:
1153 -->
1154 <form action="" name="lurlform" id="lurlform">
1155 <table border="0" cellpadding="2" cellspacing="1" id="typo3-linkURL">
1156 <tr>
1157 <td style="width: 96px;">URL:</td>
1158 <td><input type="text" name="lurl"' . $this->doc->formWidth(30) . ' value="'
1159 . htmlspecialchars(($this->curUrlInfo['act'] === 'url' ? $this->curUrlInfo['info'] : 'http://'))
1160 . '" /> ' . '<input class="btn btn-default" type="submit" value="' . $this->getLanguageService()->getLL('setLink', TRUE)
1161 . '" onclick="browse_links_setValue(document.lurlform.lurl.value); return link_current();" /></td>
1162 </tr>
1163 </table>
1164 </form>';
1165 return $extUrl;
1166 }
1167
1168 /**
1169 * Returns HTML of the file/folder link selector
1170 *
1171 * @param string $treeClassName
1172 * @return string
1173 */
1174 protected function getFileSelectorHtml($treeClassName = ElementBrowserFolderTreeView::class) {
1175 /** @var ElementBrowserFolderTreeView $folderTree */
1176 $folderTree = GeneralUtility::makeInstance($treeClassName);
1177 $folderTree->thisScript = $this->thisScript;
1178 $tree = $folderTree->getBrowsableTree();
1179 $backendUser = $this->getBackendUser();
1180 if ($this->curUrlInfo['value'] && $this->curUrlInfo['act'] === $this->act) {
1181 $cmpPath = $this->curUrlInfo['value'];
1182 if (!isset($this->expandFolder)) {
1183 $this->expandFolder = $cmpPath;
1184 }
1185 }
1186 // Create upload/create folder forms, if a path is given
1187 $selectedFolder = FALSE;
1188 if ($this->expandFolder) {
1189 $fileOrFolderObject = NULL;
1190 try {
1191 $fileOrFolderObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($this->expandFolder);
1192 } catch (\Exception $e) {
1193 // No path is selected
1194 }
1195
1196 if ($fileOrFolderObject instanceof Folder) {
1197 // It's a folder
1198 $selectedFolder = $fileOrFolderObject;
1199 } elseif ($fileOrFolderObject instanceof FileInterface) {
1200 // It's a file
1201 try {
1202 $selectedFolder = $fileOrFolderObject->getParentFolder();
1203 } catch (\Exception $e) {
1204 // Accessing the parent folder failed for some reason. e.g. permissions
1205 }
1206 }
1207 }
1208 // If no folder is selected, get the user's default upload folder
1209 if (!$selectedFolder) {
1210 try {
1211 $selectedFolder = $backendUser->getDefaultUploadFolder();
1212 } catch (\Exception $e) {
1213 // The configured default user folder does not exist
1214 }
1215 }
1216 // Build the file upload and folder creation form
1217 $uploadForm = '';
1218 $createFolder = '';
1219 $content = '';
1220 if ($selectedFolder) {
1221 $uploadForm = ($this->act === 'file') ? $this->uploadForm($selectedFolder) : '';
1222 $createFolder = $this->createFolder($selectedFolder);
1223 }
1224 // Insert the upload form on top, if so configured
1225 if ($backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
1226 $content .= $uploadForm;
1227 }
1228
1229 // Render the filelist if there is a folder selected
1230 $files = '';
1231 if ($selectedFolder) {
1232 $allowedExtensions = isset($this->P['params']['allowedExtensions']) ? $this->P['params']['allowedExtensions'] : '';
1233 $files = $this->expandFolder($selectedFolder, $allowedExtensions);
1234 }
1235 // Create folder tree:
1236 $content .= '
1237 <!--
1238 Wrapper table for folder tree / file/folder list:
1239 -->
1240 <table border="0" cellpadding="0" cellspacing="0" id="typo3-linkFiles">
1241 <tr>
1242 <td class="c-wCell" valign="top">'
1243 . $this->barheader(($this->getLanguageService()->getLL('folderTree') . ':')) . $tree . '</td>
1244 <td class="c-wCell" valign="top">' . $files . '</td>
1245 </tr>
1246 </table>
1247 ';
1248 // Adding create folder + upload form if applicable
1249 if (!$backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
1250 $content .= $uploadForm;
1251 }
1252 $content .= '<br />' . $createFolder . '<br />';
1253 return $content;
1254 }
1255
1256 /**
1257 * Returns HTML of the page link selector
1258 *
1259 * @param string $treeClassName name of the class used for page tree rendering
1260 * @return string
1261 */
1262 protected function getPageSelectorHtml($treeClassName = ElementBrowserPageTreeView::class) {
1263 $backendUser = $this->getBackendUser();
1264
1265 /** @var ElementBrowserPageTreeView $pageTree */
1266 $pageTree = GeneralUtility::makeInstance($treeClassName);
1267 $pageTree->thisScript = $this->thisScript;
1268 $pageTree->ext_showPageId = (bool)$backendUser->getTSConfigVal('options.pageTree.showPageIdWithTitle');
1269 $pageTree->ext_showNavTitle = (bool)$backendUser->getTSConfigVal('options.pageTree.showNavTitle');
1270 $pageTree->addField('nav_title');
1271 $tree = $pageTree->getBrowsableTree();
1272 $cElements = $this->expandPage();
1273 $dbmount = $this->getTemporaryTreeMountCancelNotice();
1274 $content = '
1275
1276 <!--
1277 Wrapper table for page tree / record list:
1278 -->
1279 <table border="0" cellpadding="0" cellspacing="0" id="typo3-linkPages">
1280 <tr>
1281 <td class="c-wCell" valign="top">'
1282 . $this->barheader(($this->getLanguageService()->getLL('pageTree') . ':'))
1283 . $dbmount
1284 . $tree . '</td>
1285 <td class="c-wCell" valign="top">' . $cElements . '</td>
1286 </tr>
1287 </table>
1288 ';
1289 return $content;
1290 }
1291
1292 /**
1293 * TYPO3 Element Browser: Showing a page tree and allows you to browse for records
1294 *
1295 * @return string HTML content for the module
1296 */
1297 public function main_db() {
1298 // Starting content:
1299 $content = $this->doc->startPage('TBE record selector');
1300 // Init variable:
1301 $pArr = explode('|', $this->bparams);
1302 $tables = $pArr[3];
1303 $backendUser = $this->getBackendUser();
1304
1305 // Making the browsable pagetree:
1306 /** @var \TYPO3\CMS\Recordlist\Tree\View\ElementBrowserPageTreeView $pageTree */
1307 $pageTree = GeneralUtility::makeInstance(\TYPO3\CMS\Recordlist\Tree\View\ElementBrowserPageTreeView::class);
1308 $pageTree->thisScript = $this->thisScript;
1309 $pageTree->ext_pArrPages = $tables === 'pages';
1310 $pageTree->ext_showNavTitle = (bool)$backendUser->getTSConfigVal('options.pageTree.showNavTitle');
1311 $pageTree->ext_showPageId = (bool)$backendUser->getTSConfigVal('options.pageTree.showPageIdWithTitle');
1312 $pageTree->addField('nav_title');
1313
1314 $withTree = TRUE;
1315 if (($tables !== '') && ($tables !== '*')) {
1316 $tablesArr = GeneralUtility::trimExplode(',', $tables, TRUE);
1317 $onlyRootLevel = TRUE;
1318 foreach ($tablesArr as $currentTable) {
1319 $tableTca = $GLOBALS['TCA'][$currentTable];
1320 if (isset($tableTca)) {
1321 if (!isset($tableTca['ctrl']['rootLevel']) || ((int)$tableTca['ctrl']['rootLevel']) != 1) {
1322 $onlyRootLevel = FALSE;
1323 }
1324 }
1325 }
1326 if ($onlyRootLevel) {
1327 $withTree = FALSE;
1328 // page to work on will be root
1329 $this->expandPage = 0;
1330 }
1331 }
1332
1333 $tree = $pageTree->getBrowsableTree();
1334 // Making the list of elements, if applicable:
1335 $cElements = $this->TBE_expandPage($tables);
1336 // Putting the things together, side by side:
1337 $content .= '
1338
1339 <!--
1340 Wrapper table for page tree / record list:
1341 -->
1342 <table border="0" cellpadding="0" cellspacing="0" id="typo3-EBrecords">
1343 <tr>';
1344 if ($withTree) {
1345 $content .= '<td class="c-wCell" valign="top">'
1346 . $this->barheader(($this->getLanguageService()->getLL('pageTree') . ':'))
1347 . $this->getTemporaryTreeMountCancelNotice()
1348 . $tree . '</td>';
1349 }
1350 $content .= '<td class="c-wCell" valign="top">' . $cElements . '</td>
1351 </tr>
1352 </table>
1353 ';
1354 // Add some space
1355 $content .= '<br /><br />';
1356 // End page, return content:
1357 $content .= $this->doc->endPage();
1358 $content = $this->doc->insertStylesAndJS($content);
1359 return $content;
1360 }
1361
1362 /**
1363 * TYPO3 Element Browser: Showing a folder tree, allowing you to browse for files.
1364 *
1365 * @return string HTML content for the module
1366 */
1367 public function main_file() {
1368 // include JS files and set prefs for foldertree
1369 $this->doc->getDragDropCode('folders', 'Tree.ajaxID = "SC_alt_file_navframe::expandCollapse"');
1370 // Starting content:
1371 $content = $this->doc->startPage('TBE file selector');
1372 // Add the FlashMessages if any
1373 $content .= $this->doc->getFlashMessages();
1374 // Init variable:
1375 $pArr = explode('|', $this->bparams);
1376 // The key number 3 of the pArr contains the "allowed" string. Disallowed is not passed to
1377 // the element browser at all but only filtered out in TCEMain afterwards
1378 $allowed = $pArr[3];
1379 if ($allowed !== 'sys_file' && $allowed !== '*' && !empty($allowed)) {
1380 $allowedFileExtensions = $allowed;
1381 }
1382 $backendUser = $this->getBackendUser();
1383
1384 if (isset($allowedFileExtensions)) {
1385 // Create new filter object
1386 $filterObject = GeneralUtility::makeInstance(FileExtensionFilter::class);
1387 $filterObject->setAllowedFileExtensions($allowedFileExtensions);
1388 // Set file extension filters on all storages
1389 $storages = $backendUser->getFileStorages();
1390 /** @var $storage \TYPO3\CMS\Core\Resource\ResourceStorage */
1391 foreach ($storages as $storage) {
1392 $storage->addFileAndFolderNameFilter(array($filterObject, 'filterFileList'));
1393 }
1394 }
1395 // Create upload/create folder forms, if a path is given
1396 $this->selectedFolder = FALSE;
1397 if ($this->expandFolder) {
1398 $fileOrFolderObject = NULL;
1399
1400 // Try to fetch the folder the user had open the last time he browsed files
1401 // Fallback to the default folder in case the last used folder is not existing
1402 try {
1403 $fileOrFolderObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($this->expandFolder);
1404 } catch (Exception $accessException) {
1405 // We're just catching the exception here, nothing to be done if folder does not exist or is not accessible.
1406 }
1407
1408 if ($fileOrFolderObject instanceof Folder) {
1409 // It's a folder
1410 $this->selectedFolder = $fileOrFolderObject;
1411 } elseif ($fileOrFolderObject instanceof FileInterface) {
1412 // It's a file
1413 $this->selectedFolder = $fileOrFolderObject->getParentFolder();
1414 }
1415 }
1416 // Or get the user's default upload folder
1417 if (!$this->selectedFolder) {
1418 try {
1419 $this->selectedFolder = $backendUser->getDefaultUploadFolder();
1420 } catch (\Exception $e) {
1421 // The configured default user folder does not exist
1422 }
1423 }
1424 // Build the file upload and folder creation form
1425 $uploadForm = '';
1426 $createFolder = '';
1427 if ($this->selectedFolder) {
1428 $uploadForm = $this->uploadForm($this->selectedFolder);
1429 $createFolder = $this->createFolder($this->selectedFolder);
1430 }
1431 // Insert the upload form on top, if so configured
1432 if ($backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
1433 $content .= $uploadForm;
1434 }
1435 // Getting flag for showing/not showing thumbnails:
1436 $noThumbs = $backendUser->getTSConfigVal('options.noThumbsInEB');
1437 $_MOD_SETTINGS = array();
1438 if (!$noThumbs) {
1439 // MENU-ITEMS, fetching the setting for thumbnails from File>List module:
1440 $_MOD_MENU = array('displayThumbs' => '');
1441 $_MCONF['name'] = 'file_list';
1442 $_MOD_SETTINGS = BackendUtility::getModuleData($_MOD_MENU, GeneralUtility::_GP('SET'), $_MCONF['name']);
1443 }
1444 $noThumbs = $noThumbs ?: !$_MOD_SETTINGS['displayThumbs'];
1445 // Create folder tree:
1446 /** @var ElementBrowserFolderTreeView $folderTree */
1447 $folderTree = GeneralUtility::makeInstance(ElementBrowserFolderTreeView::class);
1448 $folderTree->thisScript = $this->thisScript;
1449 $folderTree->ext_noTempRecyclerDirs = $this->mode === 'filedrag';
1450 $tree = $folderTree->getBrowsableTree();
1451 if ($this->selectedFolder) {
1452 if ($this->mode === 'filedrag') {
1453 $files = $this->TBE_dragNDrop($this->selectedFolder, $pArr[3]);
1454 } else {
1455 $files = $this->TBE_expandFolder($this->selectedFolder, $pArr[3], $noThumbs);
1456 }
1457 } else {
1458 $files = '';
1459 }
1460
1461 // Putting the parts together, side by side:
1462 $content .= '
1463
1464 <!--
1465 Wrapper table for folder tree / filelist:
1466 -->
1467 <table border="0" cellpadding="0" cellspacing="0" id="typo3-EBfiles">
1468 <tr>
1469 <td class="c-wCell" valign="top">' . $this->barheader(($this->getLanguageService()->getLL('folderTree') . ':'))
1470 . $tree . '</td>
1471 <td class="c-wCell" valign="top">' . $files . '</td>
1472 </tr>
1473 </table>
1474 ';
1475 // Adding create folder + upload forms if applicable:
1476 if (!$backendUser->getTSConfigVal('options.uploadFieldsInTopOfEB')) {
1477 $content .= $uploadForm;
1478 }
1479 $content .= $createFolder;
1480 // Add some space
1481 $content .= '<br /><br />';
1482 // Setup indexed elements:
1483 $this->doc->JScode .= $this->doc->wrapScriptTags('
1484 require(["TYPO3/CMS/Backend/BrowseLinks"], function(BrowseLinks) {
1485 BrowseLinks.addElements(' . json_encode($this->elements) . ');
1486 });');
1487 // Ending page, returning content:
1488 $content .= $this->doc->endPage();
1489 $content = $this->doc->insertStylesAndJS($content);
1490 return $content;
1491 }
1492
1493 /**
1494 * TYPO3 Element Browser: Showing a folder tree, allowing you to browse for folders.
1495 *
1496 * @return string HTML content for the module
1497 */
1498 public function main_folder() {
1499 // include JS files
1500 // Setting prefs for foldertree
1501 $this->doc->getDragDropCode('folders', 'Tree.ajaxID = "SC_alt_file_navframe::expandCollapse";');
1502 // Starting content:
1503 $content = $this->doc->startPage('TBE folder selector');
1504 // Add the FlashMessages if any
1505 $content .= $this->doc->getFlashMessages();
1506 // Init variable:
1507 $parameters = explode('|', $this->bparams);
1508 if ($this->expandFolder) {
1509 $this->selectedFolder = ResourceFactory::getInstance()->getFolderObjectFromCombinedIdentifier($this->expandFolder);
1510 }
1511 if ($this->selectedFolder) {
1512 $createFolder = $this->createFolder($this->selectedFolder);
1513 } else {
1514 $createFolder = '';
1515 }
1516 // Create folder tree:
1517 /** @var ElementBrowserFolderTreeView $folderTree */
1518 $folderTree = GeneralUtility::makeInstance(ElementBrowserFolderTreeView::class);
1519 $folderTree->thisScript = $this->thisScript;
1520 $folderTree->ext_noTempRecyclerDirs = $this->mode === 'filedrag';
1521 $tree = $folderTree->getBrowsableTree();
1522 $folders = '';
1523 if ($this->selectedFolder) {
1524 if ($this->mode === 'filedrag') {
1525 $folders = $this->TBE_dragNDrop($this->selectedFolder, $parameters[3]);
1526 } else {
1527 $folders = $this->TBE_expandSubFolders($this->selectedFolder);
1528 }
1529 }
1530 // Putting the parts together, side by side:
1531 $content .= '
1532
1533 <!--
1534 Wrapper table for folder tree / folder list:
1535 -->
1536 <table border="0" cellpadding="0" cellspacing="0" id="typo3-EBfiles">
1537 <tr>
1538 <td class="c-wCell" valign="top">' . $this->barheader(($this->getLanguageService()->getLL('folderTree') . ':'))
1539 . $tree . '</td>
1540 <td class="c-wCell" valign="top">' . $folders . '</td>
1541 </tr>
1542 </table>
1543 ';
1544 // Adding create folder if applicable:
1545 $content .= $createFolder;
1546 // Add some space
1547 $content .= '<br /><br />';
1548 // Ending page, returning content:
1549 $content .= $this->doc->endPage();
1550 $content = $this->doc->insertStylesAndJS($content);
1551 return $content;
1552 }
1553
1554 /******************************************************************
1555 *
1556 * Record listing
1557 *
1558 ******************************************************************/
1559 /**
1560 * For RTE: This displays all content elements on a page and lets you create a link to the element.
1561 *
1562 * @return string HTML output. Returns content only if the ->expandPage value is set (pointing to a page uid to show tt_content records from ...)
1563 */
1564 public function expandPage() {
1565 $out = '';
1566 // Set page id (if any) to expand
1567 $expPageId = $this->expandPage;
1568 // If there is an anchor value (content element reference) in the element reference, then force an ID to expand:
1569 if (!$this->expandPage && $this->curUrlInfo['cElement']) {
1570 // Set to the current link page id.
1571 $expPageId = $this->curUrlInfo['pageid'];
1572 }
1573 // Draw the record list IF there is a page id to expand:
1574 if (
1575 $expPageId
1576 && MathUtility::canBeInterpretedAsInteger($expPageId)
1577 && $this->getBackendUser()->isInWebMount($expPageId)
1578 ) {
1579 // Set header:
1580 $out .= $this->barheader($this->getLanguageService()->getLL('contentElements') . ':');
1581 // Create header for listing, showing the page title/icon:
1582 $mainPageRec = BackendUtility::getRecordWSOL('pages', $expPageId);
1583 $db = $this->getDatabaseConnection();
1584 $out .= '
1585 <ul class="list-tree list-tree-root list-tree-root-clean">
1586 <li class="list-tree-control-open">
1587 <span class="list-tree-group">
1588 <span class="list-tree-icon">' . IconUtility::getSpriteIconForRecord('pages', $mainPageRec) . '</span>
1589 <span class="list-tree-title">' . BackendUtility::getRecordTitle('pages', $mainPageRec, TRUE) . '</span>
1590 </span>
1591 <ul>
1592 ';
1593
1594 // Look up tt_content elements from the expanded page:
1595 $res = $db->exec_SELECTquery(
1596 'uid,header,hidden,starttime,endtime,fe_group,CType,colPos,bodytext',
1597 'tt_content',
1598 'pid=' . (int)$expPageId . BackendUtility::deleteClause('tt_content')
1599 . BackendUtility::versioningPlaceholderClause('tt_content'),
1600 '',
1601 'colPos,sorting'
1602 );
1603 // Traverse list of records:
1604 $c = 0;
1605 while ($row = $db->sql_fetch_assoc($res)) {
1606 $c++;
1607 $icon = IconUtility::getSpriteIconForRecord('tt_content', $row);
1608 $selected = '';
1609 if ($this->curUrlInfo['act'] == 'page' && $this->curUrlInfo['cElement'] == $row['uid']) {
1610 $selected = ' class="active"';
1611 }
1612 // Putting list element HTML together:
1613 $out .= '
1614 <li' . $selected . '>
1615 <span class="list-tree-group">
1616 <span class="list-tree-icon">
1617 ' . $icon . '
1618 </span>
1619 <span class="list-tree-title">
1620 <a href="#" onclick="return link_typo3Page(\'' . $expPageId . '\',\'#' . $row['uid'] . '\');">
1621 ' . BackendUtility::getRecordTitle('tt_content', $row, TRUE) . '
1622 </a>
1623 </span>
1624 </span>
1625 </li>
1626 ';
1627 }
1628 $out .= '
1629 </ul>
1630 </li>
1631 </ul>
1632 ';
1633 }
1634 return $out;
1635 }
1636
1637 /**
1638 * For TYPO3 Element Browser: This lists all content elements from the given list of tables
1639 *
1640 * @param string $tables Comma separated list of tables. Set to "*" if you want all tables.
1641 * @return string HTML output.
1642 */
1643 public function TBE_expandPage($tables) {
1644 $backendUser = $this->getBackendUser();
1645 if (!MathUtility::canBeInterpretedAsInteger($this->expandPage)
1646 || $this->expandPage < 0
1647 || !$backendUser->isInWebMount($this->expandPage)
1648 ) {
1649 return '';
1650 }
1651 // Set array with table names to list:
1652 if (trim($tables) === '*') {
1653 $tablesArr = array_keys($GLOBALS['TCA']);
1654 } else {
1655 $tablesArr = GeneralUtility::trimExplode(',', $tables, TRUE);
1656 }
1657 reset($tablesArr);
1658 // Headline for selecting records:
1659 $out = $this->barheader($this->getLanguageService()->getLL('selectRecords') . ':');
1660 // Create the header, showing the current page for which the listing is.
1661 // Includes link to the page itself, if pages are amount allowed tables.
1662 $titleLen = (int)$backendUser->uc['titleLen'];
1663 $mainPageRec = BackendUtility::getRecordWSOL('pages', $this->expandPage);
1664 $ATag = '';
1665 $ATag_e = '';
1666 $ATag2 = '';
1667 $picon = '';
1668 if (is_array($mainPageRec)) {
1669 $picon = IconUtility::getSpriteIconForRecord('pages', $mainPageRec);
1670 if (in_array('pages', $tablesArr)) {
1671 $ATag = '<a href="#" onclick="return insertElement(\'pages\', \'' . $mainPageRec['uid'] . '\', \'db\', '
1672 . GeneralUtility::quoteJSvalue($mainPageRec['title']) . ', \'\', \'\', \'\',\'\',1);">';
1673 $ATag2 = '<a href="#" onclick="return insertElement(\'pages\', \'' . $mainPageRec['uid'] . '\', \'db\', '
1674 . GeneralUtility::quoteJSvalue($mainPageRec['title']) . ', \'\', \'\', \'\',\'\',0);">';
1675 $ATag_e = '</a>';
1676 }
1677 }
1678 $pBicon = $ATag2 ? IconUtility::getSpriteIcon('actions-edit-add') : '';
1679 $pText = htmlspecialchars(GeneralUtility::fixed_lgd_cs($mainPageRec['title'], $titleLen));
1680 $out .= $picon . $ATag2 . $pBicon . $ATag_e . $ATag . $pText . $ATag_e . '<br />';
1681 // Initialize the record listing:
1682 $id = $this->expandPage;
1683 $pointer = MathUtility::forceIntegerInRange($this->pointer, 0, 100000);
1684 $perms_clause = $backendUser->getPagePermsClause(1);
1685 $pageInfo = BackendUtility::readPageAccess($id, $perms_clause);
1686 // Generate the record list:
1687 /** @var $dbList ElementBrowserRecordList */
1688 if (is_object($this->recordList)) {
1689 $dbList = $this->recordList;
1690 } else {
1691 $dbList = GeneralUtility::makeInstance(ElementBrowserRecordList::class);
1692 }
1693 $dbList->thisScript = $this->thisScript;
1694 $dbList->thumbs = 0;
1695 $dbList->localizationView = 1;
1696 $dbList->setIsEditable(FALSE);
1697 $dbList->calcPerms = $backendUser->calcPerms($pageInfo);
1698 $dbList->noControlPanels = 1;
1699 $dbList->clickMenuEnabled = 0;
1700 $dbList->tableList = implode(',', $tablesArr);
1701 $pArr = explode('|', $this->bparams);
1702 // a string like "data[pages][79][storage_pid]"
1703 $fieldPointerString = $pArr[0];
1704 // parts like: data, pages], 79], storage_pid]
1705 $fieldPointerParts = explode('[', $fieldPointerString);
1706 $relatingTableName = substr($fieldPointerParts[1], 0, -1);
1707 $relatingFieldName = substr($fieldPointerParts[3], 0, -1);
1708 if ($relatingTableName && $relatingFieldName) {
1709 $dbList->setRelatingTableAndField($relatingTableName, $relatingFieldName);
1710 }
1711 $dbList->start($id, GeneralUtility::_GP('table'), $pointer, GeneralUtility::_GP('search_field'),
1712 GeneralUtility::_GP('search_levels'), GeneralUtility::_GP('showLimit')
1713 );
1714 $dbList->setDispFields();
1715 $dbList->generateList();
1716 $out .= $dbList->getSearchBox();
1717 $out .= "<script>document.getElementById('db_list-searchbox-toolbar').style.display = 'block';document.getElementById('db_list-searchbox-toolbar').style.position = 'relative';</script>";
1718
1719 // Add the HTML for the record list to output variable:
1720 $out .= $dbList->HTMLcode;
1721 // Add support for fieldselectbox in singleTableMode
1722 if ($dbList->table) {
1723 $out .= $dbList->fieldSelectBox($dbList->table);
1724 }
1725
1726 // Return accumulated content:
1727 return $out;
1728 }
1729
1730 /**
1731 * Render list of folders inside a folder.
1732 *
1733 * @param Folder $folder Folder
1734 * @return string HTML output
1735 */
1736 public function TBE_expandSubFolders(Folder $folder) {
1737 $content = '';
1738 if ($folder->checkActionPermission('read')) {
1739 $content .= $this->folderList($folder);
1740 }
1741 // Return accumulated content for folderlisting:
1742 return $content;
1743 }
1744
1745 /******************************************************************
1746 *
1747 * Filelisting
1748 *
1749 ******************************************************************/
1750 /**
1751 * For RTE: This displays all files from folder. No thumbnails shown
1752 *
1753 * @param Folder $folder The folder path to expand
1754 * @param string $extensionList List of file extensions to show
1755 * @return string HTML output
1756 */
1757 public function expandFolder(Folder $folder, $extensionList = '') {
1758 if (!$folder->checkActionPermission('read')) {
1759 return '';
1760 }
1761 $lang = $this->getLanguageService();
1762 $renderFolders = $this->act === 'folder';
1763 // Create header for file/folder listing:
1764 if ($renderFolders) {
1765 $out = $this->barheader($lang->getLL('folders') . ':');
1766 } else {
1767 $out = $this->barheader($lang->getLL('files') . ':');
1768 }
1769 // Prepare current path value for comparison (showing red arrow)
1770 $currentIdentifier = '';
1771 if ($this->curUrlInfo['value']) {
1772 $currentIdentifier = $this->curUrlInfo['info'];
1773 }
1774 // Create header element; The folder from which files are listed.
1775 $titleLen = (int)$this->getBackendUser()->uc['titleLen'];
1776 $folderIcon = IconUtility::getSpriteIconForResource($folder);
1777 $folderIcon .= htmlspecialchars(GeneralUtility::fixed_lgd_cs($folder->getIdentifier(), $titleLen));
1778 $selected = '';
1779 if ($this->curUrlInfo['act'] == 'folder' && $currentIdentifier == $folder->getCombinedIdentifier()) {
1780 $selected = ' class="bg-success"';
1781 }
1782 $out .= '
1783 <a href="#"' . $selected . ' title="' . htmlspecialchars($folder->getIdentifier()) . '" onclick="return link_folder(\'file:' . $folder->getCombinedIdentifier() . '\');">
1784 ' . $folderIcon . '
1785 </a>
1786 ';
1787 // Get files from the folder:
1788 if ($renderFolders) {
1789 $items = $folder->getSubfolders();
1790 } else {
1791 $items = $this->getFilesInFolder($folder, $extensionList);
1792 }
1793 $c = 0;
1794
1795 if (!empty($items)) {
1796 $out .= '<ul class="list-tree list-tree-root">';
1797 foreach ($items as $fileOrFolderObject) {
1798 $c++;
1799 if ($renderFolders) {
1800 $fileIdentifier = $fileOrFolderObject->getCombinedIdentifier();
1801 $overlays = array();
1802 if ($fileOrFolderObject instanceof InaccessibleFolder) {
1803 $overlays = array('status-overlay-locked' => array());
1804 }
1805 $icon = IconUtility::getSpriteIcon(
1806 IconUtility::mapFileExtensionToSpriteIconName('folder'),
1807 array('title' => $fileOrFolderObject->getName()),
1808 $overlays);
1809 $itemUid = 'file:' . $fileIdentifier;
1810 } else {
1811 $fileIdentifier = $fileOrFolderObject->getUid();
1812 // Get size and icon:
1813 $size = ' (' . GeneralUtility::formatSize($fileOrFolderObject->getSize()) . 'bytes)';
1814 $icon = IconUtility::getSpriteIconForResource($fileOrFolderObject, array('title' => $fileOrFolderObject->getName() . $size));
1815 $itemUid = 'file:' . $fileIdentifier;
1816 }
1817 $selected = '';
1818 if (($this->curUrlInfo['act'] == 'file' || $this->curUrlInfo['act'] == 'folder')
1819 && $currentIdentifier == $fileIdentifier
1820 ) {
1821 $selected = ' class="active"';
1822 }
1823 // Put it all together for the file element:
1824 $out .=
1825 '<li' . $selected . '>
1826 <a href="#"title="' . htmlspecialchars($fileOrFolderObject->getName()) . '" onclick="return link_folder(\'' . $itemUid . '\');">
1827 ' . $icon . '
1828 ' . htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileOrFolderObject->getName(), $titleLen)) . '
1829 </a>
1830 </li>';
1831 }
1832 $out .= '</ul>';
1833 }
1834 return $out;
1835 }
1836
1837 /**
1838 * For TYPO3 Element Browser: Expand folder of files.
1839 *
1840 * @param Folder $folder The folder path to expand
1841 * @param string $extensionList List of fileextensions to show
1842 * @param bool $noThumbs Whether to show thumbnails or not. If set, no thumbnails are shown.
1843 * @return string HTML output
1844 */
1845 public function TBE_expandFolder(Folder $folder, $extensionList = '', $noThumbs = FALSE) {
1846 if (!$folder->checkActionPermission('read')) {
1847 return '';
1848 }
1849 $extensionList = $extensionList == '*' ? '' : $extensionList;
1850 $files = $this->getFilesInFolder($folder, $extensionList);
1851 return $this->fileList($files, $folder, $noThumbs);
1852 }
1853
1854 /**
1855 * Render list of files.
1856 *
1857 * @param File[] $files List of files
1858 * @param Folder $folder If set a header with a folder icon and folder name are shown
1859 * @param bool $noThumbs Whether to show thumbnails or not. If set, no thumbnails are shown.
1860 * @return string HTML output
1861 */
1862 protected function fileList(array $files, Folder $folder = NULL, $noThumbs = FALSE) {
1863 $out = '';
1864
1865 $lang = $this->getLanguageService();
1866 $lines = array();
1867 // Create headline (showing number of files):
1868 $filesCount = count($files);
1869 $out .= $this->barheader(sprintf($lang->getLL('files') . ' (%s):', $filesCount));
1870 $out .= '<div id="filelist">';
1871 $out .= $this->getBulkSelector($filesCount);
1872 $titleLen = (int)$this->getBackendUser()->uc['titleLen'];
1873 // Create the header of current folder:
1874 if ($folder) {
1875 $folderIcon = IconUtility::getSpriteIconForResource($folder);
1876 $lines[] = '<tr class="t3-row-header">
1877 <td colspan="4">' . $folderIcon
1878 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($folder->getIdentifier(), $titleLen)) . '</td>
1879 </tr>';
1880 }
1881 if ($filesCount == 0) {
1882 $lines[] = '
1883 <tr class="file_list_normal">
1884 <td colspan="4">No files found.</td>
1885 </tr>';
1886 }
1887 // Traverse the filelist:
1888 /** @var $fileObject File */
1889 foreach ($files as $fileObject) {
1890 $fileExtension = $fileObject->getExtension();
1891 // Thumbnail/size generation:
1892 $imgInfo = array();
1893 if (GeneralUtility::inList(strtolower($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext']), strtolower($fileExtension)) && !$noThumbs) {
1894 $processedFile = $fileObject->process(
1895 ProcessedFile::CONTEXT_IMAGEPREVIEW,
1896 array('width' => 64, 'height' => 64)
1897 );
1898 $imageUrl = $processedFile->getPublicUrl(TRUE);
1899 $imgInfo = array(
1900 $fileObject->getProperty('width'),
1901 $fileObject->getProperty('height')
1902 );
1903 $pDim = $imgInfo[0] . 'x' . $imgInfo[1] . ' pixels';
1904 $clickIcon = '<img src="' . $imageUrl . '" ' .
1905 'width="' . $processedFile->getProperty('width') . '" ' .
1906 'height="' . $processedFile->getProperty('height') . '" ' .
1907 'hspace="5" vspace="5" border="1" />';
1908 } else {
1909 $clickIcon = '';
1910 $pDim = '';
1911 }
1912 // Create file icon:
1913 $size = ' (' . GeneralUtility::formatSize($fileObject->getSize()) . 'bytes' . ($pDim ? ', ' . $pDim : '') . ')';
1914 $icon = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileObject->getName() . $size));
1915 // Create links for adding the file:
1916 $filesIndex = count($this->elements);
1917 $this->elements['file_' . $filesIndex] = array(
1918 'type' => 'file',
1919 'table' => 'sys_file',
1920 'uid' => $fileObject->getUid(),
1921 'fileName' => $fileObject->getName(),
1922 'filePath' => $fileObject->getUid(),
1923 'fileExt' => $fileExtension,
1924 'fileIcon' => $icon
1925 );
1926 if ($this->fileIsSelectableInFileList($fileObject, $imgInfo)) {
1927 $ATag = '<a href="#" title="' . htmlspecialchars($fileObject->getName()) . '" onclick="return BrowseLinks.File.insertElement(\'file_' . $filesIndex . '\');">';
1928 $ATag_alt = substr($ATag, 0, -4) . ',1);">';
1929 $bulkCheckBox = '<input type="checkbox" class="typo3-bulk-item" name="file_' . $filesIndex . '" value="0" /> ';
1930 $ATag_e = '</a>';
1931 } else {
1932 $ATag = '';
1933 $ATag_alt = '';
1934 $ATag_e = '';
1935 $bulkCheckBox = '';
1936 }
1937 // Create link to showing details about the file in a window:
1938 $Ahref = BackendUtility::getModuleUrl('show_item', array(
1939 'type' => 'file',
1940 'table' => '_FILE',
1941 'uid' => $fileObject->getCombinedIdentifier(),
1942 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
1943 ));
1944 $ATag2_e = '</a>';
1945 // Combine the stuff:
1946 $filenameAndIcon = $bulkCheckBox . $ATag_alt . $icon
1947 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($fileObject->getName(), $titleLen)) . $ATag_e;
1948 // Show element:
1949 if ($pDim) {
1950 // Image...
1951 $lines[] = '
1952 <tr class="file_list_normal">
1953 <td nowrap="nowrap">' . $filenameAndIcon . '&nbsp;</td>
1954 <td>' . $ATag . IconUtility::getSpriteIcon('actions-edit-add', array('title' => $lang->getLL('addToList', TRUE))) . $ATag_e . '</td>
1955 <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>
1956 <td nowrap="nowrap">&nbsp;' . $pDim . '</td>
1957 </tr>';
1958 $lines[] = '
1959 <tr>
1960 <td class="filelistThumbnail" colspan="4">' . $ATag_alt . $clickIcon . $ATag_e . '</td>
1961 </tr>';
1962 } else {
1963 $lines[] = '
1964 <tr class="file_list_normal">
1965 <td nowrap="nowrap">' . $filenameAndIcon . '&nbsp;</td>
1966 <td>' . $ATag . IconUtility::getSpriteIcon('actions-edit-add', array('title' => $lang->getLL('addToList', TRUE))) . $ATag_e . '</td>
1967 <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>
1968 <td>&nbsp;</td>
1969 </tr>';
1970 }
1971 }
1972 // Wrap all the rows in table tags:
1973 $out .= '
1974
1975 <!--
1976 Filelisting
1977 -->
1978 <table cellpadding="0" cellspacing="0" id="typo3-filelist">
1979 ' . implode('', $lines) . '
1980 </table>';
1981 // Return accumulated content for filelisting:
1982 $out .= '</div>';
1983 return $out;
1984 }
1985
1986 /**
1987 * Checks if the given file is selectable in the filelist.
1988 *
1989 * By default all files are selectable. This method may be overwritten in child classes.
1990 *
1991 * @param FileInterface $file
1992 * @param mixed[] $imgInfo Image dimensions from \TYPO3\CMS\Core\Imaging\GraphicalFunctions::getImageDimensions()
1993 * @return bool TRUE if file is selectable.
1994 */
1995 protected function fileIsSelectableInFileList(FileInterface $file, array $imgInfo) {
1996 return TRUE;
1997 }
1998
1999 /**
2000 * Render list of folders.
2001 *
2002 * @param Folder $baseFolder
2003 * @return string HTML output
2004 */
2005 public function folderList(Folder $baseFolder) {
2006 $content = '';
2007 $lang = $this->getLanguageService();
2008 $folders = $baseFolder->getSubfolders();
2009 $folderIdentifier = $baseFolder->getCombinedIdentifier();
2010 // Create headline (showing number of folders):
2011 $content .= $this->barheader(sprintf($lang->getLL('folders') . ' (%s):', count($folders)));
2012 $titleLength = (int)$this->getBackendUser()->uc['titleLen'];
2013 // Create the header of current folder:
2014 $aTag = '<a href="#" onclick="return insertElement(\'\',' . GeneralUtility::quoteJSvalue($folderIdentifier)
2015 . ', \'folder\', ' . GeneralUtility::quoteJSvalue($folderIdentifier) . ', ' . GeneralUtility::quoteJSvalue($folderIdentifier)
2016 . ', \'\', \'\',\'\',1);">';
2017 // Add the foder icon
2018 $folderIcon = $aTag;
2019 $folderIcon .= IconUtility::getSpriteIcon('apps-filetree-folder-default');
2020 $folderIcon .= htmlspecialchars(GeneralUtility::fixed_lgd_cs($baseFolder->getName(), $titleLength));
2021 $folderIcon .= '</a>';
2022 $content .= $folderIcon . '<br />';
2023
2024 $lines = array();
2025 // Traverse the folder list:
2026 foreach ($folders as $subFolder) {
2027 $subFolderIdentifier = $subFolder->getCombinedIdentifier();
2028 // Create folder icon:
2029 $icon = '<span style="width: 16px; height: 16px; display: inline-block;"></span>';
2030 $icon .= IconUtility::getSpriteIcon('apps-filetree-folder-default', array('title' => htmlspecialchars($subFolder->getName())));
2031 // Create links for adding the folder:
2032 if ($this->P['itemName'] != '' && $this->P['formName'] != '') {
2033 $aTag = '<a href="#" onclick="return set_folderpath(' . GeneralUtility::quoteJSvalue($subFolderIdentifier)
2034 . ');">';
2035 } else {
2036 $aTag = '<a href="#" onclick="return insertElement(\'\',' . GeneralUtility::quoteJSvalue($subFolderIdentifier)
2037 . ', \'folder\', ' . GeneralUtility::quoteJSvalue($subFolderIdentifier) . ', '
2038 . GeneralUtility::quoteJSvalue($subFolderIdentifier) . ', \'\', \'\');">';
2039 }
2040 if (strstr($subFolderIdentifier, ',') || strstr($subFolderIdentifier, '|')) {
2041 // In case an invalid character is in the filepath, display error message:
2042 $errorMessage = GeneralUtility::quoteJSvalue(sprintf($lang->getLL('invalidChar'), ', |'));
2043 $aTag = ($aTag_alt = '<a href="#" onclick="alert(' . $errorMessage . ');return false;">');
2044 } else {
2045 // If foldername is OK, just add it:
2046 $aTag_alt = substr($aTag, 0, -4) . ',\'\',1);">';
2047 }
2048 $aTag_e = '</a>';
2049 // Combine icon and folderpath:
2050 $foldernameAndIcon = $aTag_alt . $icon
2051 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($subFolder->getName(), $titleLength)) . $aTag_e;
2052 if ($this->P['itemName'] != '') {
2053 $lines[] = '
2054 <tr class="bgColor4">
2055 <td nowrap="nowrap">' . $foldernameAndIcon . '&nbsp;</td>
2056 <td>&nbsp;</td>
2057 </tr>';
2058 } else {
2059 $lines[] = '
2060 <tr class="bgColor4">
2061 <td nowrap="nowrap">' . $foldernameAndIcon . '&nbsp;</td>
2062 <td>' . $aTag . IconUtility::getSpriteIcon('actions-edit-add', array('title' => $lang->getLL('addToList', TRUE))) . $aTag_e . ' </td>
2063 <td>&nbsp;</td>
2064 </tr>';
2065 }
2066 $lines[] = '
2067 <tr>
2068 <td colspan="3"><span style="width: 1px; height: 3px; display: inline-block;"></span></td>
2069 </tr>';
2070 }
2071 // Wrap all the rows in table tags:
2072 $content .= '
2073
2074 <!--
2075 Folder listing
2076 -->
2077 <table border="0" cellpadding="0" cellspacing="1" id="typo3-folderList">
2078 ' . implode('', $lines) . '
2079 </table>';
2080 // Return accumulated content for folderlisting:
2081 return $content;
2082 }
2083
2084 /**
2085 * For RTE: This displays all IMAGES (gif,png,jpg) (from extensionList) from folder. Thumbnails are shown for images.
2086 * This listing is of images located in the web-accessible paths ONLY - the listing is for drag-n-drop use in the RTE
2087 *
2088 * @param Folder $folder The folder path to expand
2089 * @param string $extensionList List of file extensions to show
2090 * @return string HTML output
2091 */
2092 public function TBE_dragNDrop(Folder $folder, $extensionList = '') {
2093 if (!$folder) {
2094 return '';
2095 }
2096 $lang = $this->getLanguageService();
2097 if (!$folder->getStorage()->isPublic()) {
2098 // Print this warning if the folder is NOT a web folder
2099 return GeneralUtility::makeInstance(FlashMessage::class, $lang->getLL('noWebFolder'), $lang->getLL('files'), FlashMessage::WARNING)
2100 ->render();
2101 }
2102 $out = '';
2103
2104 // Read files from directory:
2105 $extensionList = $extensionList == '*' ? '' : $extensionList;
2106 $files = $this->getFilesInFolder($folder, $extensionList);
2107
2108 $out .= $this->barheader(sprintf($lang->getLL('files') . ' (%s):', count($files)));
2109 $titleLen = (int)$this->getBackendUser()->uc['titleLen'];
2110 $picon = IconUtility::getSpriteIcon('apps-filetree-folder-default');
2111 $picon .= htmlspecialchars(GeneralUtility::fixed_lgd_cs(basename($folder->getName()), $titleLen));
2112 $out .= $picon . '<br />';
2113 // Init row-array:
2114 $lines = array();
2115 // Add "drag-n-drop" message:
2116 $infoText = GeneralUtility::makeInstance(FlashMessage::class, $lang->getLL('findDragDrop'), '', FlashMessage::INFO)
2117 ->render();
2118 $lines[] = '
2119 <tr>
2120 <td colspan="2">' . $infoText . '</td>
2121 </tr>';
2122 // Traverse files:
2123 foreach ($files as $fileObject) {
2124 // URL of image:
2125 $iUrl = GeneralUtility::rawurlencodeFP($fileObject->getPublicUrl(TRUE));
2126 // Show only web-images
2127 $fileExtension = strtolower($fileObject->getExtension());
2128 if (GeneralUtility::inList('gif,jpeg,jpg,png', $fileExtension)) {
2129 $imgInfo = array(
2130 $fileObject->getProperty('width'),
2131 $fileObject->getProperty('height')
2132 );
2133 $pDim = $imgInfo[0] . 'x' . $imgInfo[1] . ' pixels';
2134 $size = ' (' . GeneralUtility::formatSize($fileObject->getSize()) . 'bytes' . ($pDim ? ', ' . $pDim : '') . ')';
2135 $filenameAndIcon = IconUtility::getSpriteIconForResource($fileObject, array('title' => $fileObject->getName() . $size));
2136 if (GeneralUtility::_GP('noLimit')) {
2137 $maxW = 10000;
2138 $maxH = 10000;
2139 } else {
2140 $maxW = 380;
2141 $maxH = 500;
2142 }
2143 $IW = $imgInfo[0];
2144 $IH = $imgInfo[1];
2145 if ($IW > $maxW) {
2146 $IH = ceil($IH / $IW * $maxW);
2147 $IW = $maxW;
2148 }
2149 if ($IH > $maxH) {
2150 $IW = ceil($IW / $IH * $maxH);
2151 $IH = $maxH;
2152 }
2153 // Make row:
2154 $lines[] = '
2155 <tr class="bgColor4">
2156 <td nowrap="nowrap">' . $filenameAndIcon . '&nbsp;</td>
2157 <td nowrap="nowrap">' . ($imgInfo[0] != $IW
2158 ? '<a href="' . htmlspecialchars(GeneralUtility::linkThisScript(array('noLimit' => '1')))
2159 . '">' . IconUtility::getSpriteIcon('status-dialog-warning', array('title' => $lang->getLL('clickToRedrawFullSize', TRUE)))
2160 . '</a>'
2161 : '')
2162 . $pDim . '&nbsp;</td>
2163 </tr>';
2164 $lines[] = '
2165 <tr>
2166 <td colspan="2"><img src="' . htmlspecialchars($iUrl) . '" data-htmlarea-file-uid="' . $fileObject->getUid()
2167 . '" width="' . htmlspecialchars($IW) . '" height="' . htmlspecialchars($IH) . '" border="1" alt="" /></td>
2168 </tr>';
2169 $lines[] = '
2170 <tr>
2171 <td colspan="2"><span style="width: 1px; height: 3px; display: inline-block;"></span></td>
2172 </tr>';
2173 }
2174 }
2175 // Finally, wrap all rows in a table tag:
2176 $out .= '
2177
2178
2179 <!--
2180 Filelisting / Drag-n-drop
2181 -->
2182 <table border="0" cellpadding="0" cellspacing="1" id="typo3-dragBox">
2183 ' . implode('', $lines) . '
2184 </table>';
2185
2186 return $out;
2187 }
2188
2189 /******************************************************************
2190 *
2191 * Miscellaneous functions
2192 *
2193 ******************************************************************/
2194
2195 /**
2196 * Prints a 'header' where string is in a tablecell
2197 *
2198 * @param string $str The string to print in the header. The value is htmlspecialchars()'ed before output.
2199 * @return string The header HTML (wrapped in a table)
2200 */
2201 public function barheader($str) {
2202 return '
2203 <!-- Bar header: -->
2204 <h3>' . htmlspecialchars($str) . '</h3>
2205 ';
2206 }
2207
2208 /**
2209 * For RTE/link: This prints the 'currentUrl'
2210 *
2211 * @param string $str URL value. The value is htmlspecialchars()'ed before output.
2212 * @return string HTML content, wrapped in a table.
2213 */
2214 public function printCurrentUrl($str) {
2215 // Output the folder or file identifier, when working with files
2216 if (isset($str) && MathUtility::canBeInterpretedAsInteger($str)) {
2217 try {
2218 $fileObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($str);
2219 } catch (Exception\FileDoesNotExistException $e) {
2220 $fileObject = NULL;
2221 }
2222 $str = is_object($fileObject) ? $fileObject->getIdentifier() : '';
2223 }
2224 if ($str !== '') {
2225 return '
2226 <!-- Print current URL -->
2227 <table border="0" cellpadding="0" cellspacing="0" id="typo3-curUrl">
2228 <tr>
2229 <td>' . $this->getLanguageService()->getLL('currentLink', TRUE) . ': '
2230 . htmlspecialchars(rawurldecode($str)) . '</td>
2231 </tr>
2232 </table>';
2233 } else {
2234 return '';
2235 }
2236 }
2237
2238 /**
2239 * For RTE/link: Parses the incoming URL and determines if it's a page, file, external or mail address.
2240 *
2241 * @param string $href HREF value tp analyse
2242 * @param string $siteUrl The URL of the current website (frontend)
2243 * @return array[] Array with URL information stored in assoc. keys: value, act (page, file, mail), pageid, cElement, info
2244 */
2245 public function parseCurUrl($href, $siteUrl) {
2246 $lang = $this->getLanguageService();
2247 $href = trim($href);
2248 if ($href) {
2249 $info = array();
2250 // Default is "url":
2251 $info['value'] = $href;
2252 $info['act'] = 'url';
2253 if (!StringUtility::beginsWith($href, 'file://') && strpos($href, 'file:') !== FALSE) {
2254 $rel = substr($href, strpos($href, 'file:') + 5);
2255 $rel = rawurldecode($rel);
2256 try {
2257 // resolve FAL-api "file:UID-of-sys_file-record" and "file:combined-identifier"
2258 $fileOrFolderObject = ResourceFactory::getInstance()->retrieveFileOrFolderObject($rel);
2259 if ($fileOrFolderObject instanceof Folder) {
2260 $info['act'] = 'folder';
2261 $info['value'] = $fileOrFolderObject->getCombinedIdentifier();
2262 } elseif ($fileOrFolderObject instanceof File) {
2263 $info['act'] = 'file';
2264 $info['value'] = $fileOrFolderObject->getUid();
2265 } else {
2266 $info['value'] = $rel;
2267 }
2268 } catch (Exception\FileDoesNotExistException $e) {
2269 // file was deleted or any other reason, don't select any item
2270 if (MathUtility::canBeInterpretedAsInteger($rel)) {
2271 $info['act'] = 'file';
2272 } else {
2273 $info['act'] = 'folder';
2274 }
2275 $info['value'] = '';
2276 }
2277 } elseif (StringUtility::beginsWith($href, $siteUrl)) {
2278 // If URL is on the current frontend website:
2279 // URL is a file, which exists:
2280 if (file_exists(PATH_site . rawurldecode($href))) {
2281 $info['value'] = rawurldecode($href);
2282 if (@is_dir((PATH_site . $info['value']))) {
2283 $info['act'] = 'folder';
2284 } else {
2285 $info['act'] = 'file';
2286 }
2287 } else {
2288 // URL is a page (id parameter)
2289 $uP = parse_url($href);
2290
2291 $pp = preg_split('/^id=/', $uP['query']);
2292 $pp[1] = preg_replace('/&id=[^&]*/', '', $pp[1]);
2293 $parameters = explode('&', $pp[1]);
2294 $id = array_shift($parameters);
2295 if ($id) {
2296 // Checking if the id-parameter is an alias.
2297 if (!MathUtility::canBeInterpretedAsInteger($id)) {
2298 list($idPartR) = BackendUtility::getRecordsByField('pages', 'alias', $id);
2299 $id = (int)$idPartR['uid'];
2300 }
2301 $pageRow = BackendUtility::getRecordWSOL('pages', $id);
2302 $titleLen = (int)$this->getBackendUser()->uc['titleLen'];
2303 $info['value'] = ((((($lang->getLL('page', TRUE) . ' \'')
2304 . htmlspecialchars(GeneralUtility::fixed_lgd_cs($pageRow['title'], $titleLen)))
2305 . '\' (ID:') . $id) . ($uP['fragment'] ? ', #' . $uP['fragment'] : '')) . ')';
2306 $info['pageid'] = $id;
2307 $info['cElement'] = $uP['fragment'];
2308 $info['act'] = 'page';
2309 $info['query'] = $parameters[0] ? '&' . implode('&', $parameters) : '';
2310 }
2311 }
2312 } else {
2313 // Email link:
2314 if (strtolower(substr($href, 0, 7)) === 'mailto:') {
2315 $info['value'] = trim(substr($href, 7));
2316 $info['act'] = 'mail';
2317 }
2318 }
2319 $info['info'] = $info['value'];
2320 } else {
2321 // NO value input:
2322 $info = array();
2323 $info['info'] = $lang->getLL('none');
2324 $info['value'] = '';
2325 $info['act'] = 'page';
2326 }
2327 // let the hook have a look
2328 foreach ($this->hookObjects as $hookObject) {
2329 $info = $hookObject->parseCurrentUrl($href, $siteUrl, $info);
2330 }
2331 return $info;
2332 }
2333
2334 /**
2335 * Setter for the class that should be used by TBE_expandPage() to generate the record list.
2336 * This method is intended to be used by Extensions that implement their own browsing functionality.
2337 *
2338 * @param ElementBrowserRecordList $recordList
2339 * @throws \InvalidArgumentException
2340 * @return void
2341 * @api
2342 */
2343 public function setRecordList($recordList) {
2344 if (!$recordList instanceof ElementBrowserRecordList) {
2345 throw new \InvalidArgumentException('$recordList needs to be an instance of ' . ElementBrowserRecordList::class, 1370878522);
2346 }
2347 $this->recordList = $recordList;
2348 }
2349
2350 /**
2351 * For TBE: Makes an upload form for uploading files to the filemount the user is browsing.
2352 * The files are uploaded to the tce_file.php script in the core which will handle the upload.
2353 *
2354 * @param Folder $folderObject Absolute filepath on server to which to upload.
2355 * @return string HTML for an upload form.
2356 */
2357 public function uploadForm(Folder $folderObject) {
2358 if (!$folderObject->checkActionPermission('write')) {
2359 return '';
2360 }
2361 // Read configuration of upload field count
2362 $userSetting = $this->getBackendUser()->getTSConfigVal('options.folderTree.uploadFieldsInLinkBrowser');
2363 $count = isset($userSetting) ? $userSetting : 1;
2364 if ($count === '0') {
2365 return '';
2366 }
2367 $count = (int)$count === 0 ? 1 : (int)$count;
2368 // Create header, showing upload path:
2369 $header = $folderObject->getIdentifier();
2370 $lang = $this->getLanguageService();
2371 $code = '
2372 <br />
2373 <!--
2374 Form, for uploading files:
2375 -->
2376 <form action="' . htmlspecialchars(BackendUtility::getModuleUrl('tce_file')) . '" method="post" name="editform"'
2377 . ' id="typo3-uplFilesForm" enctype="multipart/form-data">
2378 <table border="0" cellpadding="0" cellspacing="0" id="typo3-uplFiles">
2379 <tr>
2380 <td>' . $this->barheader($lang->sL(
2381 'LLL:EXT:lang/locallang_core.xlf:file_upload.php.pagetitle', TRUE) . ':') . '</td>
2382 </tr>
2383 <tr>
2384 <td class="c-wCell c-hCell"><strong>' . $lang->getLL('path', TRUE) . ':</strong> '
2385 . htmlspecialchars($header) . '</td>
2386 </tr>
2387 <tr>
2388 <td class="c-wCell c-hCell">';
2389 // Traverse the number of upload fields (default is 3):
2390 for ($a = 1; $a <= $count; $a++) {
2391 $code .= '<input type="file" multiple="multiple" name="upload_' . $a . '[]"' . $this->doc->formWidth(35)
2392 . ' size="50" />
2393 <input type="hidden" name="file[upload][' . $a . '][target]" value="'
2394 . htmlspecialchars($folderObject->getCombinedIdentifier()) . '" />
2395 <input type="hidden" name="file[upload][' . $a . '][data]" value="' . $a . '" /><br />';
2396 }
2397 // Make footer of upload form, including the submit button:
2398 $redirectValue = $this->getThisScript() . 'act=' . $this->act . '&mode=' . $this->mode
2399 . '&expandFolder=' . rawurlencode($folderObject->getCombinedIdentifier())
2400 . '&bparams=' . rawurlencode($this->bparams)
2401 . (is_array($this->P) ? GeneralUtility::implodeArrayForUrl('P', $this->P) : '');
2402 $code .= '<input type="hidden" name="redirect" value="' . htmlspecialchars($redirectValue) . '" />';
2403 $code .= FormEngine::getHiddenTokenField('tceAction');
2404 $code .= '
2405 <div id="c-override">
2406 <label>
2407 <input type="checkbox" name="overwriteExistingFiles" id="overwriteExistingFiles" value="1" /> '
2408 . $lang->sL('LLL:EXT:lang/locallang_misc.xlf:overwriteExistingFiles', TRUE) . '
2409 </label>
2410 </div>
2411 <input class="btn btn-default" type="submit" name="submit" value="'
2412 . $lang->sL('LLL:EXT:lang/locallang_core.xlf:file_upload.php.submit', TRUE) . '" />
2413 ';
2414 $code .= '</td>
2415 </tr>
2416 </table>
2417 </form><br />';
2418 return $code;
2419 }
2420
2421 /**
2422 * For TBE: Makes a form for creating new folders in the filemount the user is browsing.
2423 * The folder creation request is sent to the tce_file.php script in the core which will handle the creation.
2424 *
2425 * @param Folder $folderObject Absolute filepath on server in which to create the new folder.
2426 * @return string HTML for the create folder form.
2427 */
2428 public function createFolder(Folder $folderObject) {
2429 if (!$folderObject->checkActionPermission('write')) {
2430 return '';
2431 }
2432 $backendUser = $this->getBackendUser();
2433 if (!($backendUser->isAdmin() || $backendUser->getTSConfigVal('options.createFoldersInEB'))) {
2434 return '';
2435 }
2436 // Don't show Folder-create form if it's denied
2437 if ($backendUser->getTSConfigVal('options.folderTree.hideCreateFolder')) {
2438 return '';
2439 }
2440 $lang = $this->getLanguageService();
2441 // Create header, showing upload path:
2442 $header = $folderObject->getIdentifier();
2443 $code = '
2444
2445 <!--
2446 Form, for creating new folders:
2447 -->
2448 <form action="' . htmlspecialchars(BackendUtility::getModuleUrl('tce_file')) . '" method="post" name="editform2" id="typo3-crFolderForm">
2449 <table border="0" cellpadding="0" cellspacing="0" id="typo3-crFolder">
2450 <tr>
2451 <td>' . $this->barheader($lang->sL(
2452 'LLL:EXT:lang/locallang_core.xlf:file_newfolder.php.pagetitle') . ':') . '</td>
2453 </tr>
2454 <tr>
2455 <td class="c-wCell c-hCell"><strong>'
2456 . $lang->getLL('path', TRUE) . ':</strong> ' . htmlspecialchars($header) . '</td>
2457 </tr>
2458 <tr>
2459 <td class="c-wCell c-hCell">';
2460 // Create the new-folder name field:
2461 $a = 1;
2462 $code .= '<input' . $this->doc->formWidth(20) . ' type="text" name="file[newfolder][' . $a . '][data]" />'
2463 . '<input type="hidden" name="file[newfolder][' . $a . '][target]" value="'
2464 . htmlspecialchars($folderObject->getCombinedIdentifier()) . '" />';
2465 // Make footer of upload form, including the submit button:
2466 $redirectValue = $this->getThisScript() . 'act=' . $this->act . '&mode=' . $this->mode
2467 . '&expandFolder=' . rawurlencode($folderObject->getCombinedIdentifier())
2468 . '&bparams=' . rawurlencode($this->bparams)
2469 . (is_array($this->P) ? GeneralUtility::implodeArrayForUrl('P', $this->P) : '');
2470 $code .= '<input type="hidden" name="redirect" value="' . htmlspecialchars($redirectValue) . '" />'
2471 . FormEngine::getHiddenTokenField('tceAction')
2472 . '<input class="btn btn-default" type="submit" name="submit" value="'
2473 . $lang->sL('LLL:EXT:lang/locallang_core.xlf:file_newfolder.php.submit', TRUE) . '" />';
2474 $code .= '</td>
2475 </tr>
2476 </table>
2477 </form>';
2478 return $code;
2479 }
2480
2481 /**
2482 * Get the HTML data required for a bulk selection of files of the TYPO3 Element Browser.
2483 *
2484 * @param int $filesCount Number of files currently displayed
2485 * @return string HTML data required for a bulk selection of files - if $filesCount is 0, nothing is returned
2486 */
2487 public function getBulkSelector($filesCount) {
2488 if (!$filesCount) {
2489 return '';
2490 }
2491
2492 $lang = $this->getLanguageService();
2493 $labelToggleSelection = $lang->sL('LLL:EXT:lang/locallang_browse_links.xlf:toggleSelection', TRUE);
2494 $labelImportSelection = $lang->sL('LLL:EXT:lang/locallang_browse_links.xlf:importSelection', TRUE);
2495 // Getting flag for showing/not showing thumbnails:
2496 $noThumbsInEB = $this->getBackendUser()->getTSConfigVal('options.noThumbsInEB');
2497 $out = $this->doc->spacer(10) . '<div>' . '<a href="#" onclick="BrowseLinks.Selector.handle()"'
2498 . 'title="' . $labelImportSelection . '">'
2499 . $this->iconFactory->getIcon('actions-document-import-t3d', Icon::SIZE_SMALL)
2500 . $labelImportSelection . '</a>&nbsp;&nbsp;&nbsp;'
2501 . '<a href="#" onclick="BrowseLinks.Selector.toggle()" title="' . $labelToggleSelection . '">'
2502 . $this->iconFactory->getIcon('actions-document-select', Icon::SIZE_SMALL)
2503 . $labelToggleSelection . '</a>' . '</div>';
2504 if (!$noThumbsInEB && $this->selectedFolder) {
2505 // MENU-ITEMS, fetching the setting for thumbnails from File>List module:
2506 $_MOD_MENU = array('displayThumbs' => '');
2507 $_MCONF['name'] = 'file_list';
2508 $_MOD_SETTINGS = BackendUtility::getModuleData($_MOD_MENU, GeneralUtility::_GP('SET'), $_MCONF['name']);
2509 $addParams = '&act=' . $this->act . '&mode=' . $this->mode
2510 . '&expandFolder=' . rawurlencode($this->selectedFolder->getCombinedIdentifier())
2511 . '&bparams=' . rawurlencode($this->bparams);
2512 $thumbNailCheck = '<div class="checkbox"><label for="checkDisplayThumbs">' . BackendUtility::getFuncCheck('', 'SET[displayThumbs]', $_MOD_SETTINGS['displayThumbs'],
2513 GeneralUtility::_GP('M') ? '' : $this->thisScript, $addParams, 'id="checkDisplayThumbs"')
2514 . $lang->sL('LLL:EXT:lang/locallang_mod_file_list.xlf:displayThumbs', TRUE) . '</label></div>';
2515 $out .= $this->doc->spacer(5) . $thumbNailCheck . $this->doc->spacer(15);
2516 } else {
2517 $out .= $this->doc->spacer(15);
2518 }
2519 return $out;
2520 }
2521
2522 /**
2523 * Determines whether submitted field change functions are valid
2524 * and are coming from the system and not from an external abuse.
2525 *
2526 * @param bool $handleFlexformSections Whether to handle flexform sections differently
2527 * @return bool Whether the submitted field change functions are valid
2528 */
2529 protected function areFieldChangeFunctionsValid($handleFlexformSections = FALSE) {
2530 $result = FALSE;
2531 if (isset($this->P['fieldChangeFunc']) && is_array($this->P['fieldChangeFunc']) && isset($this->P['fieldChangeFuncHash'])) {
2532 $matches = array();
2533 $pattern = '#\\[el\\]\\[(([^]-]+-[^]-]+-)(idx\\d+-)([^]]+))\\]#i';
2534 $fieldChangeFunctions = $this->P['fieldChangeFunc'];
2535 // Special handling of flexform sections:
2536 // Field change functions are modified in JavaScript, thus the hash is always invalid
2537 if ($handleFlexformSections && preg_match($pattern, $this->P['itemName'], $matches)) {
2538 $originalName = $matches[1];
2539 $cleanedName = $matches[2] . $matches[4];
2540 foreach ($fieldChangeFunctions as &$value) {
2541 $value = str_replace($originalName, $cleanedName, $value);
2542 }
2543 unset($value);
2544 }
2545 $result = $this->P['fieldChangeFuncHash'] === GeneralUtility::hmac(serialize($fieldChangeFunctions));
2546 }
2547 return $result;
2548 }
2549
2550 /**
2551 * Check if a temporary tree mount is set and return a cancel button
2552 *
2553 * @return string
2554 */
2555 protected function getTemporaryTreeMountCancelNotice() {
2556 if ((int)$this->getBackendUser()->getSessionData('pageTree_temporaryMountPoint') === 0) {
2557 return '';
2558 }
2559 $link = '<a href="' . htmlspecialchars(GeneralUtility::linkThisScript(array('setTempDBmount' => 0))) . '">'
2560 . $this->getLanguageService()->sl('LLL:EXT:lang/locallang_core.xlf:labels.temporaryDBmount', TRUE) . '</a>';
2561 /** @var FlashMessage $flashMessage */
2562 $flashMessage = GeneralUtility::makeInstance(
2563 FlashMessage::class,
2564 $link,
2565 '',
2566 FlashMessage::INFO
2567 );
2568 return $flashMessage->render();
2569 }
2570
2571 /**
2572 * Get a list of Files in a folder filtered by extension
2573 *
2574 * @param Folder $folder
2575 * @param string $extensionList
2576 * @return File[]
2577 */
2578 protected function getFilesInFolder(Folder $folder, $extensionList) {
2579 if ($extensionList !== '') {
2580 /** @var FileExtensionFilter $filter */
2581 $filter = GeneralUtility::makeInstance(FileExtensionFilter::class);
2582 $filter->setAllowedFileExtensions($extensionList);
2583 $folder->setFileAndFolderNameFilters(array(array($filter, 'filterFileList')));
2584 }
2585 return $folder->getFiles();
2586 }
2587
2588 /**
2589 * @return LanguageService
2590 */
2591 protected function getLanguageService() {
2592 return $GLOBALS['LANG'];
2593 }
2594
2595 /**
2596 * @return BackendUserAuthentication
2597 */
2598 protected function getBackendUser() {
2599 return $GLOBALS['BE_USER'];
2600 }
2601
2602 /**
2603 * @return DatabaseConnection
2604 */
2605 protected function getDatabaseConnection() {
2606 return $GLOBALS['TYPO3_DB'];
2607 }
2608
2609 /**
2610 * @return PageRenderer
2611 */
2612 protected function getPageRenderer() {
2613 if ($this->pageRenderer === NULL) {
2614 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
2615 }
2616 return $this->pageRenderer;
2617 }
2618
2619 }