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