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