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