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