[BUGFIX] fe_adminLib.inc uses undefined function
[Packages/TYPO3.CMS.git] / typo3 / sysext / cms / tslib / media / scripts / fe_adminLib.inc
1 <?php
2 /***************************************************************
3 *  Copyright notice
4 *
5 *  (c) 1999-2009 Kasper Skårhøj (kasperYYYY@typo3.com)
6 *  All rights reserved
7 *
8 *  This script is part of the TYPO3 project. The TYPO3 project is
9 *  free software; you can redistribute it and/or modify
10 *  it under the terms of the GNU General Public License as published by
11 *  the Free Software Foundation; either version 2 of the License, or
12 *  (at your option) any later version.
13 *
14 *  The GNU General Public License can be found at
15 *  http://www.gnu.org/copyleft/gpl.html.
16 *  A copy is found in the textfile GPL.txt and important notices to the license
17 *  from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 *  This script is distributed in the hope that it will be useful,
21 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
22 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 *  GNU General Public License for more details.
24 *
25 *  This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27 /**
28  * FE admin lib
29  *
30  * $Id$
31  * Revised for TYPO3 3.6 June/2003 by Kasper Skårhøj
32  *
33  * @author      Kasper Skårhøj <kasperYYYY@typo3.com>
34  */
35 /**
36  * [CLASS/FUNCTION INDEX of SCRIPT]
37  *
38  *
39  *
40  *  132: class user_feAdmin
41  *  179:     function init($content,$conf)
42  *
43  *              SECTION: Data processing
44  *  423:     function parseValues()
45  *  518:     function processFiles($cmdParts,$theField)
46  *  624:     function overrideValues()
47  *  640:     function defaultValues()
48  *  659:     function evalValues()
49  *  781:     function userProcess($mConfKey,$passVar)
50  *  799:     function userProcess_alt($confVal,$confArr,$passVar)
51  *
52  *              SECTION: Database manipulation functions
53  *  841:     function save()
54  *  899:     function deleteRecord()
55  *  929:     function deleteFilesFromRecord($uid)
56  *
57  *              SECTION: Command "display" functions
58  *  986:     function displayDeleteScreen()
59  * 1014:     function displayCreateScreen()
60  * 1037:     function displayEditScreen()
61  * 1088:     function displayEditForm($origArr)
62  * 1116:     function procesSetFixed()
63  *
64  *              SECTION: Template processing functions
65  * 1205:     function removeRequired($templateCode,$failure)
66  * 1223:     function getPlainTemplate($key,$r='')
67  * 1240:     function modifyDataArrForFormUpdate($inputArr)
68  * 1309:     function setCObjects($templateCode,$currentArr=array(),$markerArray='',$specialPrefix='')
69  *
70  *              SECTION: Emailing
71  * 1371:     function sendInfoMail()
72  * 1419:     function compileMail($key, $DBrows, $recipient, $setFixedConfig=array())
73  * 1465:     function sendMail($recipient, $admin, $content='', $adminContent='')
74  * 1510:     function isHTMLContent($c)
75  * 1531:     function sendHTMLMail($content,$recipient,$dummy,$fromEmail,$fromName,$replyTo='')
76  *
77  *              SECTION: Various helper functions
78  * 1615:     function aCAuth($r)
79  * 1629:     function authCode($r,$extra='')
80  * 1655:     function setfixed($markerArray, $setfixed, $r)
81  * 1693:     function setfixedHash($recCopy,$fields='')
82  * 1714:     function isPreview()
83  * 1723:     function createFileFuncObj()
84  * 1734:     function clearCacheIfSet()
85  * 1749:     function getFailure($theField, $theCmd, $label)
86  *
87  * TOTAL FUNCTIONS: 33
88  * (This index is automatically created/updated by the extension "extdeveval")
89  *
90  */
91 /**
92  * This library provides a HTML-template file based framework for Front End creating/editing/deleting records authenticated by email or fe_user login.
93  * It is used in the extensions "direct_mail_subscription" and "feuser_admin" (and the deprecated(!) static template "plugin.feadmin.dmailsubscription" and "plugin.feadmin.fe_users" which are the old versions of these two extensions)
94  * Further the extensions "t3consultancies" and "t3references" also uses this library but contrary to the "direct_mail_subscription" and "feuser_admin" extensions which relies on external HTML templates which must be adapted these two extensions delivers the HTML template code from inside.
95  * Generally the fe_adminLib appears to be hard to use. Personally I feel turned off by all the template-file work involved and since it is very feature rich (and for that sake pretty stable!) there are lots of things that can go wrong - you feel. Therefore I like the concept used by "t3consultancies"/"t3references" since those extensions uses the library by supplying the HTML-template code automatically.
96  * Suggestions for improvement and streamlining is welcome so this powerful class could be used more and effectively.
97  *
98  * @author      Kasper Skårhøj <kasperYYYY@typo3.com>
99  * @package TYPO3
100  * @subpackage tslib
101  */
102 class user_feAdmin      {
103
104                 // External, static:
105         var $recInMarkersHSC = TRUE;            // If true, values from the record put into markers going out into HTML will be passed through htmlspecialchars()!
106
107         var $dataArr = array();
108         var $failureMsg = array();
109         var $theTable = '';
110         var $thePid = 0;
111         var $markerArray = array();
112         var $templateCode='';
113         var $cObj;
114
115         var $cmd;
116         var $preview;
117         var $backURL;
118         var $recUid;
119         var $failure=0;         // is set if data did not have the required fields set.
120         var $error='';
121         var $saved=0;           // is set if data is saved
122         var $requiredArr;
123         var $currentArr = array();
124         var $previewLabel='';
125         var $nc = '';           // '&no_cache=1' if you want that parameter sent.
126         var $additionalUpdateFields='';
127         var $emailMarkPrefix = 'EMAIL_TEMPLATE_';
128         var $codeLength;
129         var $cmdKey;
130         var $fileFunc='';       // Set to a basic_filefunc object
131         var $filesStoredInUploadFolders=array();                // This array will hold the names of files transferred to the uploads/* folder if any. If the records are NOT saved, these files should be deleted!! Currently this is not working!
132
133                 // Internal vars, dynamic:
134         var $unlinkTempFiles = array();                 // Is loaded with all temporary filenames used for upload which should be deleted before exit...
135
136         /**
137          * Main function. Called from TypoScript.
138          * This
139          * - initializes internal variables,
140          * - fills in the markerArray with default substitution string
141          * - saves/emails if such commands are sent
142          * - calls functions for display of the screen for editing/creation/deletion etc.
143          *
144          * @param       string          Empty string, ignore.
145          * @param       array           TypoScript properties following the USER_INT object which uses this library
146          * @return      string          HTML content
147          */
148         function init($content,$conf)   {
149                 $this->conf = $conf;
150
151                         // template file is fetched.
152                 $this->templateCode = $this->conf['templateContent'] ? $this->conf['templateContent'] : $this->cObj->fileResource($this->conf['templateFile']);
153
154                         // Getting the cmd var
155                 $this->cmd = (string)t3lib_div::_GP('cmd');
156                         // Getting the preview var
157                 $this->preview = (string)t3lib_div::_GP('preview');
158                         // backURL is a given URL to return to when login is performed
159                 $this->backURL = t3lib_div::_GP('backURL');
160                 if (strstr($this->backURL, '"') || strstr($this->backURL, "'") || preg_match('/(javascript|vbscript):/i', $this->backURL)  || stristr($this->backURL, "fromcharcode") || strstr($this->backURL, "<") || strstr($this->backURL, ">"))    {
161                         $this->backURL = '';    // Clear backURL if it seems to contain XSS code - only URLs are allowed
162                 }
163                         // Remove host from URL: Make sure that $this->backURL maps to the current site
164                 $this->backURL = preg_replace('|[A-Za-z]+://[^/]+|', '', $this->backURL);
165                         // Uid to edit:
166                 $this->recUid = t3lib_div::_GP('rU');
167                         // Authentication code:
168                 $this->authCode = t3lib_div::_GP('aC');
169                         // get table
170                 $this->theTable = $this->conf['table'];
171                         // link configuration
172                 $linkConf = is_array($this->conf['formurl.']) ? $this->conf['formurl.'] : array();
173                         // pid
174                 $this->thePid = intval($this->conf['pid']) ? intval($this->conf['pid']) : $GLOBALS['TSFE']->id;
175                         //
176                 $this->codeLength = intval($this->conf['authcodeFields.']['codeLength']) ? intval($this->conf['authcodeFields.']['codeLength']) : 8;
177
178                         // Setting the hardcoded lists of fields allowed for editing and creation.
179                 $this->fieldList=implode(',',t3lib_div::trimExplode(',',$GLOBALS['TCA'][$this->theTable]['feInterface']['fe_admin_fieldList'],1));
180
181                         // globally substituted markers, fonts and colors.
182                 $splitMark = md5(microtime());
183                 list($this->markerArray['###GW1B###'],$this->markerArray['###GW1E###']) = explode($splitMark,$this->cObj->stdWrap($splitMark,$this->conf['wrap1.']));
184                 list($this->markerArray['###GW2B###'],$this->markerArray['###GW2E###']) = explode($splitMark,$this->cObj->stdWrap($splitMark,$this->conf['wrap2.']));
185                 $this->markerArray['###GC1###'] = $this->cObj->stdWrap($this->conf['color1'],$this->conf['color1.']);
186                 $this->markerArray['###GC2###'] = $this->cObj->stdWrap($this->conf['color2'],$this->conf['color2.']);
187                 $this->markerArray['###GC3###'] = $this->cObj->stdWrap($this->conf['color3'],$this->conf['color3.']);
188
189                 if (intval($this->conf['no_cache']) && !isset($linkConf['no_cache']))   {       // needed for backwards compatibility
190                         $linkConf['no_cache'] = 1;
191                 }
192                 if(!$linkConf['parameter'])     {
193                         $linkConf['parameter'] = $GLOBALS['TSFE']->id;
194                 }
195                 if(!$linkConf['additionalParams'])      {       // needed for backwards compatibility
196                         $linkConf['additionalParams'] = $this->conf['addParams'];
197                 }
198
199                 $formURL = $this->cObj->typoLink_URL($linkConf);
200                 if(!strstr($formURL,'?')) {
201                         $formURL .= '?';
202                 }
203
204                         // Initialize markerArray, setting FORM_URL and HIDDENFIELDS
205                 $this->markerArray['###FORM_URL###'] = $formURL;
206                 $this->markerArray['###FORM_URL_ENC###'] = rawurlencode($this->markerArray['###FORM_URL###']);
207                 $this->markerArray['###FORM_URL_HSC###'] = htmlspecialchars($this->markerArray['###FORM_URL###']);
208
209                 $this->markerArray['###BACK_URL###'] = $this->backURL;
210                 $this->markerArray['###BACK_URL_ENC###'] = rawurlencode($this->markerArray['###BACK_URL###']);
211                 $this->markerArray['###BACK_URL_HSC###'] = htmlspecialchars($this->markerArray['###BACK_URL###']);
212
213                 $this->markerArray['###THE_PID###'] = $this->thePid;
214                 $this->markerArray['###REC_UID###'] = $this->recUid;
215                 $this->markerArray['###AUTH_CODE###'] = $this->authCode;
216                 $this->markerArray['###THIS_ID###'] = $GLOBALS['TSFE']->id;
217                 $this->markerArray['###THIS_URL###'] = htmlspecialchars(t3lib_div::getIndpEnv('TYPO3_REQUEST_DIR'));
218                 $this->markerArray['###HIDDENFIELDS###'] =
219                         ($this->cmd?'<input type="hidden" name="cmd" value="'.htmlspecialchars($this->cmd).'" />':'').
220                         ($this->authCode?'<input type="hidden" name="aC" value="'.htmlspecialchars($this->authCode).'" />':'').
221                         ($this->backURL?'<input type="hidden" name="backURL" value="'.htmlspecialchars($this->backURL).'" />':'');
222
223
224                         // Setting cmdKey which is either 'edit' or 'create'
225                 switch($this->cmd)      {
226                         case 'edit':
227                                 $this->cmdKey='edit';
228                         break;
229                         default:
230                                 $this->cmdKey='create';
231                         break;
232                 }
233                         // Setting requiredArr to the fields in 'required' intersected field the total field list in order to remove invalid fields.
234                 $this->requiredArr = array_intersect(
235                         t3lib_div::trimExplode(',',$this->conf[$this->cmdKey.'.']['required'],1),
236                         t3lib_div::trimExplode(',',$this->conf[$this->cmdKey.'.']['fields'],1)
237                 );
238
239                         // Setting incoming data. Non-stripped
240                 $fe=t3lib_div::_GP('FE');
241                 $this->dataArr = $fe[$this->theTable];  // Incoming data.
242
243                         // Checking template file and table value
244                 if (!$this->templateCode)       {
245                         $content = 'No template file found: '.$this->conf['templateFile'];
246                         return $content;
247                 }
248
249                 if (!$this->theTable || !$this->fieldList)      {
250                         $content = 'Wrong table: '.$this->theTable;
251                         return $content;                // Not listed or editable table!
252                 }
253
254                 // *****************
255                 // If data is submitted, we take care of it here.
256                 // *******************
257                 if ($this->cmd=='delete' && !$this->preview && !t3lib_div::_GP('doNotSave'))    {       // Delete record if delete command is sent + the preview flag is NOT set.
258                         $this->deleteRecord();
259                 }
260                         // If incoming data is seen...
261                 if (is_array($this->dataArr))   {
262                                 // Evaluation of data:
263                         $this->parseValues();
264                         $this->overrideValues();
265                         $this->evalValues();
266                         if ($this->conf['evalFunc'])    {
267                                 $this->dataArr = $this->userProcess('evalFunc',$this->dataArr);
268                         }
269
270                 /*
271                 debug($this->dataArr);
272                 debug($this->failure);
273                 debug($this->preview);
274                 */
275                                 // if not preview and no failures, then set data...
276                         if (!$this->failure && !$this->preview && !t3lib_div::_GP('doNotSave')) {       // doNotSave is a global var (eg a 'Cancel' submit button) that prevents the data from being processed
277                                 $this->save();
278                         } else {
279                                 if ($this->conf['debug'])               debug($this->failure);
280                         }
281                 } else {
282                         $this->defaultValues(); // If no incoming data, this will set the default values.
283                         $this->preview = 0;     // No preview if data is not received
284                 }
285                 if ($this->failure)     {$this->preview=0;}     // No preview flag if a evaluation failure has occured
286                 $this->previewLabel = $this->preview ? '_PREVIEW' : ''; // Setting preview label prefix.
287
288
289                         // *********************
290                         // DISPLAY FORMS:
291                         // ***********************
292                 if ($this->saved) {
293                                 // Clear page cache
294                         $this->clearCacheIfSet();
295
296                                 // Displaying the page here that says, the record has been saved. You're able to include the saved values by markers.
297                         switch($this->cmd)      {
298                                 case 'delete':
299                                         $key='DELETE';
300                                 break;
301                                 case 'edit':
302                                         $key='EDIT';
303                                 break;
304                                 default:
305                                         $key='CREATE';
306                                 break;
307                         }
308                                 // Output message
309                         $templateCode = $this->cObj->getSubpart($this->templateCode, '###TEMPLATE_'.$key.'_SAVED###');
310                         $this->setCObjects($templateCode,$this->currentArr);
311                         $markerArray = $this->cObj->fillInMarkerArray($this->markerArray, $this->currentArr, '', TRUE, 'FIELD_', $this->recInMarkersHSC);
312                         $content = $this->cObj->substituteMarkerArray($templateCode, $markerArray);
313
314                                 // email message:
315                         $this->compileMail(
316                                 $key.'_SAVED',
317                                 array($this->currentArr),
318                                 $this->currentArr[$this->conf['email.']['field']],
319                                 $this->conf['setfixed.']
320                         );
321
322                 } elseif ($this->error) {       // If there was an error, we return the template-subpart with the error message
323                         $templateCode = $this->cObj->getSubpart($this->templateCode, $this->error);
324                         $this->setCObjects($templateCode);
325                         $content = $this->cObj->substituteMarkerArray($templateCode, $this->markerArray);
326                 } else {
327                                 // Finally, if there has been no attempt to save. That is either preview or just displaying and empty or not correctly filled form:
328                         if (!$this->cmd)        {
329                                 $this->cmd=$this->conf['defaultCmd'];
330                         }
331                         if ($this->conf['debug'])               debug('Display form: '.$this->cmd,1);
332                         switch($this->cmd)      {
333                                 case 'setfixed':
334                                         $content = $this->procesSetFixed();
335                                 break;
336                                 case 'infomail':
337                                         $content = $this->sendInfoMail();
338                                 break;
339                                 case 'delete':
340                                         $content = $this->displayDeleteScreen();
341                                 break;
342                                 case 'edit':
343                                         $content = $this->displayEditScreen();
344                                 break;
345                                 case 'create':
346                                         $content = $this->displayCreateScreen();
347                                 break;
348                         }
349                 }
350
351                         // Delete temp files:
352                 foreach($this->unlinkTempFiles as $tempFileName)        {
353                         t3lib_div::unlink_tempfile($tempFileName);
354                 }
355
356                         // Return content:
357                 return $content;
358         }
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382         /*****************************************
383          *
384          * Data processing
385          *
386          *****************************************/
387
388         /**
389          * Performs processing on the values found in the input data array, $this->dataArr.
390          * The processing is done according to configuration found in TypoScript
391          * Examples of this could be to force a value to an integer, remove all non-alphanumeric characters, trimming a value, upper/lowercase it, or process it due to special types like files submitted etc.
392          * Called from init() if the $this->dataArr is found to be an array
393          *
394          * @return      void
395          * @see init()
396          */
397         function parseValues()  {
398                 if (is_array($this->conf['parseValues.']))      {
399                         foreach ($this->conf['parseValues.'] as $theField => $theValue) {
400                                 $listOfCommands = t3lib_div::trimExplode(',',$theValue,1);
401                                 foreach ($listOfCommands as $cmd) {
402                                         $cmdParts = preg_split('/\[|\]/', $cmd);        // Point is to enable parameters after each command enclosed in brackets [..]. These will be in position 1 in the array.
403                                         $theCmd=trim($cmdParts[0]);
404                                         switch($theCmd) {
405                                                 case 'int':
406                                                         $this->dataArr[$theField]=intval($this->dataArr[$theField]);
407                                                 break;
408                                                 case 'lower':
409                                                 case 'upper':
410                                                         $this->dataArr[$theField] = $this->cObj->caseshift($this->dataArr[$theField],$theCmd);
411                                                 break;
412                                                 case 'nospace':
413                                                         $this->dataArr[$theField] = str_replace(' ', '', $this->dataArr[$theField]);
414                                                 break;
415                                                 case 'alpha':
416                                                         $this->dataArr[$theField] = preg_replace('/[^a-zA-Z]/','',$this->dataArr[$theField]);
417                                                 break;
418                                                 case 'num':
419                                                         $this->dataArr[$theField] = preg_replace('/[^0-9]/','',$this->dataArr[$theField]);
420                                                 break;
421                                                 case 'alphanum':
422                                                         $this->dataArr[$theField] = preg_replace('/[^a-zA-Z0-9]/','',$this->dataArr[$theField]);
423                                                 break;
424                                                 case 'alphanum_x':
425                                                         $this->dataArr[$theField] = preg_replace('/[^a-zA-Z0-9_-]/','',$this->dataArr[$theField]);
426                                                 break;
427                                                 case 'trim':
428                                                         $this->dataArr[$theField] = trim($this->dataArr[$theField]);
429                                                 break;
430                                                 case 'random':
431                                                         $this->dataArr[$theField] = substr(md5(uniqid(microtime(),1)),0,intval($cmdParts[1]));
432                                                 break;
433                                                 case 'files':
434                                                         if ($this->cmdKey=='create' && !t3lib_div::_GP('doNotSave'))    {
435                                                                 $this->processFiles($cmdParts,$theField);
436                                                         } else unset($this->dataArr[$theField]);        // Fields with files cannot be edited - only created.
437                                                 break;
438                                                 case 'setEmptyIfAbsent':
439                                                         if (!isset($this->dataArr[$theField]))  {
440                                                                 $this->dataArr[$theField]='';
441                                                         }
442                                                 break;
443                                                 case 'multiple':
444                                                         if (is_array($this->dataArr[$theField]))        {
445                                                                 $this->dataArr[$theField] = implode(',',$this->dataArr[$theField]);
446                                                         }
447                                                 break;
448                                                 case 'checkArray':
449                                                         if (is_array($this->dataArr[$theField]))        {
450                                                                 $val = 0;
451                                                                 foreach ($this->dataArr[$theField] as $kk => $vv) {
452                                                                         $kk = t3lib_div::intInRange($kk,0);
453                                                                         if ($kk<=30)    {
454                                                                                 if ($vv)        {
455                                                                                         $val|=pow(2,$kk);
456                                                                                 }
457                                                                         }
458                                                                 }
459                                                                 $this->dataArr[$theField] = $val;
460                                                         } else {$this->dataArr[$theField]=0;}
461                                                 break;
462                                                 case 'uniqueHashInt':
463                                                         $otherFields = t3lib_div::trimExplode(';',$cmdParts[1],1);
464                                                         $hashArray=array();
465                                                         foreach ($otherFields as $fN) {
466                                                                 $vv = $this->dataArr[$fN];
467                                                                 $vv = preg_replace('/[[:space:]]/','',$vv);
468                                                                 $vv = preg_replace('/[^[:alnum:]]/','',$vv);
469                                                                 $vv = strtolower($vv);
470                                                                 $hashArray[]=$vv;
471                                                         }
472                                                         $this->dataArr[$theField]=hexdec(substr(md5(serialize($hashArray)),0,8));
473                                                 break;
474                                         }
475                                 }
476                         }
477                 }
478         }
479
480         /**
481          * Processing of files.
482          * NOTICE: for now files can be handled only on creation of records. But a more advanced feature is that PREVIEW of files is handled.
483          *
484          * @param       array           Array with cmd-parts (from parseValues()). This will for example contain information about allowed file extensions and max size of uploaded files.
485          * @param       string          The fieldname with the files.
486          * @return      void
487          * @access private
488          * @see parseValues()
489          */
490         function processFiles($cmdParts,$theField)      {
491 //debug($_FILES);
492                         // First, make an array with the filename and file reference, whether the file is just uploaded or a preview
493                 $filesArr = array();
494
495                 if (is_string($this->dataArr[$theField]))       {               // files from preview.
496                         $tmpArr = explode(',',$this->dataArr[$theField]);
497                         foreach ($tmpArr as $val) {
498                                 $valParts = explode('|',$val);
499                                 $filesArr[] = array (
500                                         'name'=>$valParts[1],
501                                         'tmp_name'=>PATH_site.'typo3temp/'.$valParts[0]
502                                 );
503                         }
504                 } elseif (is_array($_FILES['FE'][$this->theTable][$theField]['name']))  {       // Files from upload
505                         foreach ($_FILES['FE'][$this->theTable][$theField]['name'] as $kk => $vv) {
506                                 if ($vv)        {
507                                         $tmpFile = t3lib_div::upload_to_tempfile($_FILES['FE'][$this->theTable][$theField]['tmp_name'][$kk]);
508                                         if ($tmpFile)   {
509                                                 $this->unlinkTempFiles[]=$tmpFile;
510                                                 $filesArr[] = array (
511                                                         'name'=>$vv,
512                                                         'tmp_name'=>$tmpFile
513                                                 );
514                                         }
515                                 }
516                         }
517                 } elseif (is_array($_FILES['FE']['name'][$this->theTable][$theField]))  {       // Files from upload
518                         foreach ($_FILES['FE']['name'][$this->theTable][$theField] as $kk => $vv) {
519                                 if ($vv)        {
520                                         $tmpFile = t3lib_div::upload_to_tempfile($_FILES['FE']['tmp_name'][$this->theTable][$theField][$kk]);
521                                         if ($tmpFile)   {
522                                                 $this->unlinkTempFiles[]=$tmpFile;
523                                                 $filesArr[] = array (
524                                                         'name'=>$vv,
525                                                         'tmp_name'=>$tmpFile
526                                                 );
527                                         }
528                                 }
529                         }
530                 }
531
532                         // Then verify the files in that array; check existence, extension and size
533                 $this->dataArr[$theField]='';
534                 $finalFilesArr=array();
535                 if (count($filesArr))   {
536                         $extArray = t3lib_div::trimExplode(';',strtolower($cmdParts[1]),1);
537                         $maxSize = intval($cmdParts[3]);
538                         foreach ($filesArr as $infoArr) {
539                                 $fI = pathinfo($infoArr['name']);
540                                 if (t3lib_div::verifyFilenameAgainstDenyPattern($fI['name']))   {
541                                         if (!count($extArray) || in_array(strtolower($fI['extension']), $extArray))     {
542                                                 $tmpFile = $infoArr['tmp_name'];
543                                                 if (@is_file($tmpFile)) {
544                                                         if (!$maxSize || filesize($tmpFile)<$maxSize*1024)      {
545                                                                 $finalFilesArr[]=$infoArr;
546                                                         } elseif ($this->conf['debug']) {debug('Size is beyond '.$maxSize.' kb ('.filesize($tmpFile).' bytes) and the file cannot be saved.');}
547                                                 } elseif ($this->conf['debug']) {debug('Surprisingly there was no file for '.$vv.' in '.$tmpFile);}
548                                         } elseif ($this->conf['debug']) {debug('Extension "'.$fI['extension'].'" not allowed');}
549                                 } elseif ($this->conf['debug']) {debug('Filename matched illegal pattern.');}
550                         }
551                 }
552                         // Copy the files in the resulting array to the proper positions based on preview/non-preview.
553                 $fileNameList=array();
554                 foreach ($finalFilesArr as $infoArr) {
555                         if ($this->isPreview()) {               // If the form is a preview form (and data is therefore not going into the database...) do this.
556                                 $this->createFileFuncObj();
557                                 $fI = pathinfo($infoArr['name']);
558                                 $tmpFilename = $this->theTable.'_'.t3lib_div::shortmd5(uniqid($infoArr['name'])).'.'.$fI['extension'];
559                                 $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($tmpFilename), PATH_site.'typo3temp/');
560                                 t3lib_div::upload_copy_move($infoArr['tmp_name'],$theDestFile);
561                                         // Setting the filename in the list
562                                 $fI2 = pathinfo($theDestFile);
563                                 $fileNameList[] = $fI2['basename'].'|'.$infoArr['name'];
564                         } else {
565                                 $this->createFileFuncObj();
566                                 $GLOBALS['TSFE']->includeTCA();
567                                 t3lib_div::loadTCA($this->theTable);
568                                 if (is_array($GLOBALS['TCA'][$this->theTable]['columns'][$theField]))   {
569                                         $uploadPath = $GLOBALS['TCA'][$this->theTable]['columns'][$theField]['config']['uploadfolder'];
570                                 }
571                                 if ($uploadPath)        {
572                                         $theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($infoArr['name']), PATH_site.$uploadPath);
573                                         t3lib_div::upload_copy_move($infoArr['tmp_name'],$theDestFile);
574                                                 // Setting the filename in the list
575                                         $fI2 = pathinfo($theDestFile);
576                                         $fileNameList[] = $fI2['basename'];
577                                         $this->filesStoredInUploadFolders[]=$theDestFile;
578                                 }
579                         }
580                                 // Implode the list of filenames
581                         $this->dataArr[$theField] = implode(',',$fileNameList);
582                 }
583         }
584
585         /**
586          * Overriding values in $this->dataArr if configured for that in TypoScript ([edit/create].overrideValues)
587          *
588          * @return      void
589          * @see init()
590          */
591         function overrideValues()       {
592                 // Addition of overriding values
593                 if (is_array($this->conf[$this->cmdKey.'.']['overrideValues.']))        {
594                         foreach ($this->conf[$this->cmdKey.'.']['overrideValues.'] as $theField => $theValue) {
595                                 $this->dataArr[$theField] = $theValue;
596                         }
597                 }
598         }
599
600         /**
601          * Called if there is no input array in $this->dataArr. Then this function sets the default values configured in TypoScript
602          *
603          * @return      void
604          * @see init()
605          */
606         function defaultValues()        {
607                         // Addition of default values
608                 if (is_array($this->conf[$this->cmdKey.'.']['defaultValues.'])) {
609                         foreach ($this->conf[$this->cmdKey.'.']['defaultValues.'] as $theField => $theValue) {
610                                 $this->dataArr[$theField] = $theValue;
611                         }
612                 }
613         }
614
615         /**
616          * This will evaluate the input values from $this->dataArr to see if they conforms with the requirements configured in TypoScript per field.
617          * For example this could be checking if a field contains a valid email address, a unique value, a value within a certain range etc.
618          * It will populate arrays like $this->failure and $this->failureMsg with error messages (which can later be displayed in the template). Mostly it does NOT alter $this->dataArr (such parsing of values was done by parseValues())
619          * Works based on configuration in TypoScript key [create/edit].evalValues
620          *
621          * @return      void
622          * @see init(), parseValues()
623          */
624         function evalValues()   {
625                 // Check required, set failure if not ok.
626                 $tempArr=array();
627                 foreach ($this->requiredArr as $theField) {
628                         if (!trim($this->dataArr[$theField]))   {
629                                 $tempArr[]=$theField;
630                         }
631                 }
632
633                 // Evaluate: This evaluates for more advanced things than 'required' does. But it returns the same error code, so you must let the required-message tell, if further evaluation has failed!
634                 $recExist=0;
635                 if (is_array($this->conf[$this->cmdKey.'.']['evalValues.']))    {
636                         switch($this->cmd)      {
637                                 case 'edit':
638                                         if (isset($this->dataArr['pid']))       {                       // This may be tricked if the input has the pid-field set but the edit-field list does NOT allow the pid to be edited. Then the pid may be false.
639                                                 $recordTestPid = intval($this->dataArr['pid']);
640                                         } else {
641                                                 $tempRecArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,$this->dataArr['uid']);
642                                                 $recordTestPid = intval($tempRecArr['pid']);
643                                         }
644                                         $recExist=1;
645                                 break;
646                                 default:
647                                         $recordTestPid = $this->thePid ? $this->thePid : t3lib_div::intval_positive($this->dataArr['pid']);
648                                 break;
649                         }
650
651                         foreach ($this->conf[$this->cmdKey.'.']['evalValues.'] as $theField => $theValue) {
652                                 $listOfCommands = t3lib_div::trimExplode(',',$theValue,1);
653                                 foreach ($listOfCommands as $cmd) {
654                                         $cmdParts = preg_split('/\[|\]/', $cmd);        // Point is to enable parameters after each command enclosed in brackets [..]. These will be in position 1 in the array.
655                                         $theCmd = trim($cmdParts[0]);
656                                         switch($theCmd) {
657                                                 case 'uniqueGlobal':
658                                                         if ($DBrows = $GLOBALS['TSFE']->sys_page->getRecordsByField($this->theTable,$theField,$this->dataArr[$theField],'','','','1'))  {
659                                                                 if (!$recExist || $DBrows[0]['uid']!=$this->dataArr['uid'])     {       // Only issue an error if the record is not existing (if new...) and if the record with the false value selected was not our self.
660                                                                         $tempArr[]=$theField;
661                                                                         $this->failureMsg[$theField][] = $this->getFailure($theField, $theCmd, 'The value existed already. Enter a new value.');
662                                                                 }
663                                                         }
664                                                 break;
665                                                 case 'uniqueLocal':
666                                                         if ($DBrows = $GLOBALS['TSFE']->sys_page->getRecordsByField($this->theTable,$theField,$this->dataArr[$theField], 'AND pid IN ('.$recordTestPid.')','','','1'))  {
667                                                                 if (!$recExist || $DBrows[0]['uid']!=$this->dataArr['uid'])     {       // Only issue an error if the record is not existing (if new...) and if the record with the false value selected was not our self.
668                                                                         $tempArr[]=$theField;
669                                                                         $this->failureMsg[$theField][] = $this->getFailure($theField, $theCmd, 'The value existed already. Enter a new value.');
670                                                                 }
671                                                         }
672                                                 break;
673                                                 case 'twice':
674                                                         if (strcmp($this->dataArr[$theField], $this->dataArr[$theField.'_again']))      {
675                                                                 $tempArr[]=$theField;
676                                                                 $this->failureMsg[$theField][] = $this->getFailure($theField, $theCmd, 'You must enter the same value twice');
677                                                         }
678                                                 break;
679                                                 case 'email':
680                                                         if (!$this->cObj->checkEmail($this->dataArr[$theField]))        {
681                                                                 $tempArr[]=$theField;
682                                                                 $this->failureMsg[$theField][] = $this->getFailure($theField, $theCmd, 'You must enter a valid email address');
683                                                         }
684                                                 break;
685                                                 case 'required':
686                                                         if (!trim($this->dataArr[$theField]))   {
687                                                                 $tempArr[]=$theField;
688                                                                 $this->failureMsg[$theField][] = $this->getFailure($theField, $theCmd, 'You must enter a value!');
689                                                         }
690                                                 break;
691                                                 case 'atLeast':
692                                                         $chars=intval($cmdParts[1]);
693                                                         if (strlen($this->dataArr[$theField])<$chars)   {
694                                                                 $tempArr[]=$theField;
695                                                                 $this->failureMsg[$theField][] = sprintf($this->getFailure($theField, $theCmd, 'You must enter at least %s characters!'), $chars);
696                                                         }
697                                                 break;
698                                                 case 'atMost':
699                                                         $chars=intval($cmdParts[1]);
700                                                         if (strlen($this->dataArr[$theField])>$chars)   {
701                                                                 $tempArr[]=$theField;
702                                                                 $this->failureMsg[$theField][] = sprintf($this->getFailure($theField, $theCmd, 'You must enter at most %s characters!'), $chars);
703                                                         }
704                                                 break;
705                                                 case 'inBranch':
706                                                         $pars = explode(';',$cmdParts[1]);
707                                                         if (intval($pars[0]))   {
708                                                                 $pid_list = $this->cObj->getTreeList(
709                                                                         intval($pars[0]),
710                                                                         intval($pars[1]) ? intval($pars[1]) : 999,
711                                                                         intval($pars[2])
712                                                                 );
713                                                                 if (!$pid_list || !t3lib_div::inList($pid_list,$this->dataArr[$theField]))      {
714                                                                         $tempArr[]=$theField;
715                                                                         $this->failureMsg[$theField][] = sprintf($this->getFailure($theField, $theCmd, 'The value was not a valid valud from this list: %s'), $pid_list);
716                                                                 }
717                                                         }
718                                                 break;
719                                                 case 'unsetEmpty':
720                                                         if (!$this->dataArr[$theField]) {
721                                                                 $hash = array_flip($tempArr);
722                                                                 unset($hash[$theField]);
723                                                                 $tempArr = array_keys($hash);
724                                                                 unset($this->failureMsg[$theField]);
725                                                                 unset($this->dataArr[$theField]);       // This should prevent the field from entering the database.
726                                                         }
727                                                 break;
728                                         }
729                                 }
730                                 $this->markerArray['###EVAL_ERROR_FIELD_'.$theField.'###'] = is_array($this->failureMsg[$theField]) ? implode('<br />',$this->failureMsg[$theField]) : '';
731                         }
732                 }
733                 $this->failure=implode(',',$tempArr);    //$failure will show which fields were not OK
734         }
735
736         /**
737          * Preforms user processing of input array - triggered right after the function call to evalValues() IF TypoScript property "evalFunc" was set.
738          *
739          * @param       string          Key pointing to the property in TypoScript holding the configuration for this processing (here: "evalFunc.*"). Well: at least its safe to say that "parentObj" in this array passed to the function is a reference back to this object.
740          * @param       array           The $this->dataArr passed for processing
741          * @return      array           The processed $passVar ($this->dataArr)
742          * @see init(), evalValues()
743          */
744         function userProcess($mConfKey,$passVar)        {
745                 if ($this->conf[$mConfKey])     {
746                         $funcConf = $this->conf[$mConfKey.'.'];
747                         $funcConf['parentObj'] = $this;
748                         $passVar = $GLOBALS['TSFE']->cObj->callUserFunction($this->conf[$mConfKey], $funcConf, $passVar);
749                 }
750                 return $passVar;
751         }
752
753         /**
754          * User processing of contnet
755          *
756          * @param       string          Value of the TypoScript object triggering the processing.
757          * @param       array           Properties of the TypoScript object triggering the processing. The key "parentObj" in this array is passed to the function as a reference back to this object.
758          * @param       mixed           Input variable to process
759          * @return      mixed           Processed input variable, $passVar
760          * @see userProcess(), save(), modifyDataArrForFormUpdate()
761          */
762         function userProcess_alt($confVal,$confArr,$passVar)    {
763                 if ($confVal)   {
764                         $funcConf = $confArr;
765                         $funcConf['parentObj'] = $this;
766                         $passVar = $GLOBALS['TSFE']->cObj->callUserFunction($confVal, $funcConf, $passVar);
767                 }
768                 return $passVar;
769         }
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792         /*****************************************
793          *
794          * Database manipulation functions
795          *
796          *****************************************/
797
798         /**
799          * Performs the saving of records, either edited or created.
800          *
801          * @return      void
802          * @see init()
803          */
804         function save() {
805                 switch($this->cmd)      {
806                         case 'edit':
807                                 $theUid = $this->dataArr['uid'];
808                                 $origArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,$theUid);           // Fetches the original record to check permissions
809                                 if ($this->conf['edit'] && ($GLOBALS['TSFE']->loginUser || $this->aCAuth($origArr)))    {       // Must be logged in in order to edit  (OR be validated by email)
810                                         $newFieldList = implode(',',array_intersect(explode(',',$this->fieldList),t3lib_div::trimExplode(',',$this->conf['edit.']['fields'],1)));
811                                         if ($this->aCAuth($origArr) || $this->cObj->DBmayFEUserEdit($this->theTable,$origArr,$GLOBALS['TSFE']->fe_user->user,$this->conf['allowedGroups'],$this->conf['fe_userEditSelf']))      {
812                                                 $this->cObj->DBgetUpdate($this->theTable, $theUid, $this->dataArr, $newFieldList, TRUE);
813                                                 $this->currentArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,$theUid);
814                                                 $this->userProcess_alt($this->conf['edit.']['userFunc_afterSave'],$this->conf['edit.']['userFunc_afterSave.'],array('rec'=>$this->currentArr, 'origRec'=>$origArr));
815                                                 $this->saved=1;
816                                         } else {
817                                                 $this->error='###TEMPLATE_NO_PERMISSIONS###';
818                                         }
819                                 }
820                         break;
821                         default:
822                                 if ($this->conf['create'])      {
823                                         $newFieldList = implode(',',array_intersect(explode(',',$this->fieldList),t3lib_div::trimExplode(',',$this->conf['create.']['fields'],1)));
824                                         $this->cObj->DBgetInsert($this->theTable, $this->thePid, $this->dataArr, $newFieldList, TRUE);
825                                         $newId = $GLOBALS['TYPO3_DB']->sql_insert_id();
826
827                                         if ($this->theTable=='fe_users' && $this->conf['fe_userOwnSelf'])       {               // enables users, creating logins, to own them self.
828                                                 $extraList='';
829                                                 $dataArr = array();
830                                                 if ($GLOBALS['TCA'][$this->theTable]['ctrl']['fe_cruser_id'])           {
831                                                         $field=$GLOBALS['TCA'][$this->theTable]['ctrl']['fe_cruser_id'];
832                                                         $dataArr[$field]=$newId;
833                                                         $extraList.=','.$field;
834                                                 }
835                                                 if ($GLOBALS['TCA'][$this->theTable]['ctrl']['fe_crgroup_id'])  {
836                                                         $field=$GLOBALS['TCA'][$this->theTable]['ctrl']['fe_crgroup_id'];
837                                                         list($dataArr[$field])=explode(',',$this->dataArr['usergroup']);
838                                                         $dataArr[$field]=intval($dataArr[$field]);
839                                                         $extraList.=','.$field;
840                                                 }
841                                                 if (count($dataArr))    {
842                                                         $this->cObj->DBgetUpdate($this->theTable, $newId, $dataArr, $extraList, TRUE);
843                                                 }
844                                         }
845
846                                         $this->currentArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,$newId);
847                                         $this->userProcess_alt($this->conf['create.']['userFunc_afterSave'],$this->conf['create.']['userFunc_afterSave.'],array('rec'=>$this->currentArr));
848                                         $this->saved=1;
849                                 }
850                         break;
851                 }
852         }
853
854         /**
855          * Deletes the record from table/uid, $this->theTable/$this->recUid, IF the fe-user has permission to do so.
856          * If the deleted flag should just be set, then it is done so. Otherwise the record truely is deleted along with any attached files.
857          * Called from init() if "cmd" was set to "delete" (and some other conditions)
858          *
859          * @return      string          void
860          * @see init()
861          */
862         function deleteRecord() {
863                 if ($this->conf['delete'])      {       // If deleting is enabled
864                         $origArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,  $this->recUid);
865                         if ($GLOBALS['TSFE']->loginUser || $this->aCAuth($origArr))     {       // Must be logged in OR be authenticated by the aC code in order to delete
866                                         // If the recUid selects a record.... (no check here)
867                                 if (is_array($origArr)) {
868                                         if ($this->aCAuth($origArr) || $this->cObj->DBmayFEUserEdit($this->theTable,$origArr, $GLOBALS['TSFE']->fe_user->user,$this->conf['allowedGroups'],$this->conf['fe_userEditSelf']))     {       // Display the form, if access granted.
869                                                 if (!$GLOBALS['TCA'][$this->theTable]['ctrl']['delete'])        {       // If the record is fully deleted... then remove the image (or any file) attached.
870                                                         $this->deleteFilesFromRecord($this->recUid);
871                                                 }
872                                                 $this->cObj->DBgetDelete($this->theTable, $this->recUid, TRUE);
873                                                 $this->currentArr = $origArr;
874                                                 $this->saved = 1;
875                                         } else {
876                                                 $this->error = '###TEMPLATE_NO_PERMISSIONS###';
877                                         }
878                                 }
879                         }
880                 }
881         }
882
883         /**
884          * Deletes the files attached to a record and updates the record.
885          * Table/uid is $this->theTable/$uid
886          *
887          * @param       integer         Uid number of the record to delete from $this->theTable
888          * @return      void
889          * @access private
890          * @see deleteRecord()
891          */
892         function deleteFilesFromRecord($uid)    {
893                 $table = $this->theTable;
894                 $rec = $GLOBALS['TSFE']->sys_page->getRawRecord($table,$uid);
895
896                 $GLOBALS['TSFE']->includeTCA();
897                 t3lib_div::loadTCA($table);
898                 $iFields=array();
899                 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $conf) {
900                         if ($conf['config']['type']=='group' && $conf['config']['internal_type']=='file')       {
901
902                                 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), array($field => ''));
903
904                                 $delFileArr = explode(',',$rec[$field]);
905                                 foreach ($delFileArr as $n) {
906                                         if ($n) {
907                                                 $fpath = $conf['config']['uploadfolder'].'/'.$n;
908                                                 unlink($fpath);
909                                         }
910                                 }
911                         }
912                 }
913         }
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935         /*****************************************
936          *
937          * Command "display" functions
938          *
939          *****************************************/
940
941         /**
942          * Creates the preview display of delete actions
943          *
944          * @return      string          HTML content
945          * @see init()
946          */
947         function displayDeleteScreen()  {
948                 if ($this->conf['delete'])      {       // If deleting is enabled
949                         $origArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,  $this->recUid);
950                         if ($GLOBALS['TSFE']->loginUser || $this->aCAuth($origArr))     {       // Must be logged in OR be authenticated by the aC code in order to delete
951                                         // If the recUid selects a record.... (no check here)
952                                 if (is_array($origArr)) {
953                                         if ($this->aCAuth($origArr) || $this->cObj->DBmayFEUserEdit($this->theTable,$origArr, $GLOBALS['TSFE']->fe_user->user,$this->conf['allowedGroups'],$this->conf['fe_userEditSelf']))     {       // Display the form, if access granted.
954                                                 $this->markerArray['###HIDDENFIELDS###'].= '<input type="hidden" name="rU" value="'.$this->recUid.'" />';
955                                                 $content = $this->getPlainTemplate('###TEMPLATE_DELETE_PREVIEW###', $origArr);
956                                         } else {        // Else display error, that you could not edit that particular record...
957                                                 $content = $this->getPlainTemplate('###TEMPLATE_NO_PERMISSIONS###');
958                                         }
959                                 }
960                         } else {        // Finally this is if there is no login user. This must tell that you must login. Perhaps link to a page with create-user or login information.
961                                 $content = $this->getPlainTemplate('###TEMPLATE_AUTH###');
962                         }
963                 } else {
964                         $content.='Delete-option is not set in TypoScript';
965                 }
966                 return $content;
967         }
968
969         /**
970          * Creates the "create" screen for records
971          *
972          * @return      string          HTML content
973          * @see init()
974          */
975         function displayCreateScreen()  {
976                 if ($this->conf['create'])      {
977                         $templateCode = $this->cObj->getSubpart($this->templateCode, ((!$GLOBALS['TSFE']->loginUser||$this->conf['create.']['noSpecialLoginForm'])?'###TEMPLATE_CREATE'.$this->previewLabel.'###':'###TEMPLATE_CREATE_LOGIN'.$this->previewLabel.'###'));
978                         $failure = t3lib_div::_GP('noWarnings')?'':$this->failure;
979                         if (!$failure)  $templateCode = $this->cObj->substituteSubpart($templateCode, '###SUB_REQUIRED_FIELDS_WARNING###', '');
980
981                         $templateCode = $this->removeRequired($templateCode,$failure);
982                         $this->setCObjects($templateCode);
983
984                         if (!is_array($this->dataArr)) {
985                                 $this->dataArr = array();
986                         }
987
988                         $markerArray = $this->cObj->fillInMarkerArray($this->markerArray, $this->dataArr, '', TRUE, 'FIELD_', $this->recInMarkersHSC);
989                         if ($this->conf['create.']['preview'] && !$this->previewLabel)  {$markerArray['###HIDDENFIELDS###'].= '<input type="hidden" name="preview" value="1" />';}
990                         $content = $this->cObj->substituteMarkerArray($templateCode, $markerArray);
991                         $content.=$this->cObj->getUpdateJS($this->modifyDataArrForFormUpdate($this->dataArr), $this->theTable.'_form', 'FE['.$this->theTable.']', $this->fieldList.$this->additionalUpdateFields);
992                 }
993                 return $content;
994         }
995
996         /**
997          * Creates the edit-screen for records
998          *
999          * @return      string          HTML content
1000          * @see init()
1001          */
1002         function displayEditScreen()    {
1003                 if ($this->conf['edit'])        {       // If editing is enabled
1004                         $origArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,  $this->dataArr['uid']?$this->dataArr['uid']:$this->recUid);
1005
1006                         if ($GLOBALS['TSFE']->loginUser || $this->aCAuth($origArr))     {       // Must be logged in OR be authenticated by the aC code in order to edit
1007                                         // If the recUid selects a record.... (no check here)
1008                                 if (is_array($origArr)) {
1009                                         if ($this->aCAuth($origArr) || $this->cObj->DBmayFEUserEdit($this->theTable,$origArr, $GLOBALS['TSFE']->fe_user->user,$this->conf['allowedGroups'],$this->conf['fe_userEditSelf']))     {       // Display the form, if access granted.
1010                                                 $content=$this->displayEditForm($origArr);
1011                                         } else {        // Else display error, that you could not edit that particular record...
1012                                                 $content = $this->getPlainTemplate('###TEMPLATE_NO_PERMISSIONS###');
1013                                         }
1014                                 } elseif ($GLOBALS['TSFE']->loginUser) {        // If the recUid did not select a record, we display a menu of records. (eg. if no recUid)
1015                                         $lockPid = $this->conf['edit.']['menuLockPid'] ? ' AND pid='.intval($this->thePid) : '';
1016
1017                                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->theTable, '1 '.$lockPid.$this->cObj->DBmayFEUserEditSelect($this->theTable,$GLOBALS['TSFE']->fe_user->user, $this->conf['allowedGroups'],$this->conf['fe_userEditSelf']).$GLOBALS['TSFE']->sys_page->deleteClause($this->theTable));
1018
1019                                         if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))   {       // If there are menu-items ...
1020                                                 $templateCode = $this->getPlainTemplate('###TEMPLATE_EDITMENU###');
1021                                                 $out='';
1022                                                 $itemCode = $this->cObj->getSubpart($templateCode, '###ITEM###');
1023                                                 while($menuRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))   {
1024                                                         $markerArray = $this->cObj->fillInMarkerArray(array(), $menuRow, '', TRUE, 'FIELD_', $this->recInMarkersHSC);
1025                                                         $markerArray = $this->setCObjects($itemCode,$menuRow,$markerArray,'ITEM_');
1026                                                         $out.= $this->cObj->substituteMarkerArray($itemCode, $markerArray);
1027                                                 }
1028                                                 $content=$this->cObj->substituteSubpart($templateCode, '###ALLITEMS###', $out);
1029                                         } else {        // If there are not menu items....
1030                                                 $content = $this->getPlainTemplate('###TEMPLATE_EDITMENU_NOITEMS###');
1031                                         }
1032                                 } else {
1033                                         $content = $this->getPlainTemplate('###TEMPLATE_AUTH###');
1034                                 }
1035                         } else {        // Finally this is if there is no login user. This must tell that you must login. Perhaps link to a page with create-user or login information.
1036                                 $content = $this->getPlainTemplate('###TEMPLATE_AUTH###');
1037                         }
1038                 } else {
1039                         $content.='Edit-option is not set in TypoScript';
1040                 }
1041                 return $content;
1042         }
1043
1044         /**
1045          * Subfunction for displayEditScreen(); Takes a record and creates an edit form based on the template code for it.
1046          * This function is called if the user is editing a record and permitted to do so. Checked in displayEditScreen()
1047          *
1048          * @param       array           The array with the record to edit
1049          * @return      string          HTML content
1050          * @access private
1051          * @see displayEditScreen()
1052          */
1053         function displayEditForm($origArr)      {
1054                 $currentArr = is_array($this->dataArr) ? $this->dataArr+$origArr : $origArr;
1055
1056                 if ($this->conf['debug'])       debug('displayEditForm(): '.'###TEMPLATE_EDIT'.$this->previewLabel.'###',1);
1057                 $templateCode = $this->cObj->getSubpart($this->templateCode, '###TEMPLATE_EDIT'.$this->previewLabel.'###');
1058                 $failure = t3lib_div::_GP('noWarnings')?'':$this->failure;
1059                 if (!$failure)  {$templateCode = $this->cObj->substituteSubpart($templateCode, '###SUB_REQUIRED_FIELDS_WARNING###', '');}
1060
1061                 $templateCode = $this->removeRequired($templateCode,$failure);
1062
1063                 $this->setCObjects($templateCode,$currentArr);
1064
1065                 $markerArray = $this->cObj->fillInMarkerArray($this->markerArray, $currentArr, '', TRUE, 'FIELD_', $this->recInMarkersHSC);
1066
1067                 $markerArray['###HIDDENFIELDS###'].= '<input type="hidden" name="FE['.$this->theTable.'][uid]" value="'.$currentArr['uid'].'" />';
1068                 if ($this->conf['edit.']['preview'] && !$this->previewLabel)    {$markerArray['###HIDDENFIELDS###'].= '<input type="hidden" name="preview" value="1" />';}
1069                 $content = $this->cObj->substituteMarkerArray($templateCode, $markerArray);
1070                 $content.=$this->cObj->getUpdateJS($this->modifyDataArrForFormUpdate($currentArr), $this->theTable.'_form',  'FE['.$this->theTable.']', $this->fieldList.$this->additionalUpdateFields);
1071
1072                 return $content;
1073         }
1074
1075         /**
1076          * Processes socalled "setfixed" commands. These are commands setting a certain field in a certain record to a certain value. Like a link you can click in an email which will unhide a record to enable something. Or likewise a link which can delete a record by a single click.
1077          * The idea is that only some allowed actions like this is allowed depending on the configured TypoScript.
1078          *
1079          * @return      string          HTML content displaying the status of the action
1080          */
1081         function procesSetFixed()       {
1082                 if ($this->conf['setfixed'])    {
1083                         $theUid = intval($this->recUid);
1084                         $origArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,  $theUid);
1085                         $fD = t3lib_div::_GP('fD');
1086                         $sFK = t3lib_div::_GP('sFK');
1087
1088                         $fieldArr=array();
1089                         if (is_array($fD) || $sFK=='DELETE')    {
1090                                 if (is_array($fD))      {
1091                                         foreach ($fD as $field => $value) {
1092                                                 $origArr[$field]=$value;
1093                                                 $fieldArr[]=$field;
1094                                         }
1095                                 }
1096                                 $theCode = $this->setfixedHash($origArr,$origArr['_FIELDLIST']);
1097                                 if (!strcmp($this->authCode,$theCode))  {
1098                                         if ($sFK=='DELETE')     {
1099                                                 $this->cObj->DBgetDelete($this->theTable, $theUid, TRUE);
1100                                         } else {
1101                                                 $newFieldList = implode(',',array_intersect(t3lib_div::trimExplode(',',$this->fieldList),t3lib_div::trimExplode(',',implode($fieldArr,','),1)));
1102                                                 $this->cObj->DBgetUpdate($this->theTable, $theUid, $fD, $newFieldList, TRUE);
1103                                                 $this->currentArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->theTable,$theUid);
1104                                                 $this->userProcess_alt($this->conf['setfixed.']['userFunc_afterSave'],$this->conf['setfixed.']['userFunc_afterSave.'],array('rec'=>$this->currentArr, 'origRec'=>$origArr));
1105                                         }
1106
1107                                                 // Outputting template
1108                                         $this->markerArray = $this->cObj->fillInMarkerArray($this->markerArray, $origArr, '', TRUE, 'FIELD_', $this->recInMarkersHSC);
1109                                         $content = $this->getPlainTemplate('###TEMPLATE_SETFIXED_OK_'.$sFK.'###');
1110                                         if (!$content)  {$content = $this->getPlainTemplate('###TEMPLATE_SETFIXED_OK###');}
1111
1112                                                 // Compiling email
1113                                         $this->compileMail(
1114                                                 'SETFIXED_'.$sFK,
1115                                                 array($origArr),
1116                                                 $origArr[$this->conf['email.']['field']],
1117                                                 $this->conf['setfixed.']
1118                                         );
1119                                                 // Clearing cache if set:
1120                                         $this->clearCacheIfSet();
1121                                 } else $content = $this->getPlainTemplate('###TEMPLATE_SETFIXED_FAILED###');
1122                         } else $content = $this->getPlainTemplate('###TEMPLATE_SETFIXED_FAILED###');
1123                 }
1124                 return $content;
1125         }
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149         /*****************************************
1150          *
1151          * Template processing functions
1152          *
1153          *****************************************/
1154
1155
1156
1157         /**
1158          * Remove required parts from template code string
1159          *       Works like this:
1160          *               - You insert subparts like this ###SUB_REQUIRED_FIELD_'.$theField.'### in the template that tells what is required for the field, if it's not correct filled in.
1161          *               - These subparts are all removed, except if the field is listed in $failure string!
1162          *
1163          *              Only fields that are found in $this->requiredArr is processed.
1164          *
1165          * @param       string          The template HTML code
1166          * @param       string          Comma list of fields which has errors (and therefore should not be removed)
1167          * @return      string          The processed template HTML code
1168          */
1169         function removeRequired($templateCode,$failure) {
1170                 foreach ($this->requiredArr as $theField) {
1171                         if (!t3lib_div::inList($failure,$theField))     {
1172                                 $templateCode = $this->cObj->substituteSubpart($templateCode, '###SUB_REQUIRED_FIELD_'.$theField.'###', '');
1173                         }
1174                 }
1175                 return $templateCode;
1176         }
1177
1178         /**
1179          * Returns template subpart HTML code for the key given
1180          *
1181          * @param       string          Subpart marker to return subpart for.
1182          * @param       array           Optional data record array. If set, then all fields herein will also be substituted if found as markers in the template
1183          * @return      string          The subpart with all markers found in current $this->markerArray substituted.
1184          * @see tslib_cObj::fillInMarkerArray()
1185          */
1186         function getPlainTemplate($key,$r='')   {
1187                 if ($this->conf['debug'])       debug('getPlainTemplate(): '.$key,1);
1188                 $templateCode = $this->cObj->getSubpart($this->templateCode, $key);
1189                 $this->setCObjects($templateCode,is_array($r)?$r:array());
1190                 return  $this->cObj->substituteMarkerArray(
1191                                 $templateCode,
1192                                 is_array($r) ? $this->cObj->fillInMarkerArray($this->markerArray, $r, '', TRUE, 'FIELD_', $this->recInMarkersHSC) : $this->markerArray
1193                         );
1194         }
1195
1196         /**
1197          * Modifies input array for passing on to tslib_cObj::getUpdateJS() which produces some JavaScript for form evaluation or the like.
1198          *
1199          * @param       array           The data array
1200          * @return      array           The processed input array
1201          * @see displayCreateScreen(), displayEditForm(), tslib_cObj::getUpdateJS()
1202          */
1203         function modifyDataArrForFormUpdate($inputArr)  {
1204                 if (is_array($this->conf[$this->cmdKey.'.']['evalValues.']))    {
1205                         foreach ($this->conf[$this->cmdKey.'.']['evalValues.'] as $theField => $theValue) {
1206                                 $listOfCommands = t3lib_div::trimExplode(',',$theValue,1);
1207                                 foreach ($listOfCommands as $cmd) {
1208                                         $cmdParts = preg_split('/\[|\]/', $cmd);        // Point is to enable parameters after each command enclosed in brackets [..]. These will be in position 1 in the array.
1209                                         $theCmd = trim($cmdParts[0]);
1210                                         switch($theCmd) {
1211                                                 case 'twice':
1212                                                         if (isset($inputArr[$theField]))        {
1213                                                                 if (!isset($inputArr[$theField.'_again']))      {
1214                                                                         $inputArr[$theField.'_again'] = $inputArr[$theField];
1215                                                                 }
1216                                                                 $this->additionalUpdateFields.=','.$theField.'_again';
1217                                                         }
1218                                                 break;
1219                                         }
1220                                 }
1221                         }
1222                 }
1223                 if (is_array($this->conf['parseValues.']))      {
1224                         foreach ($this->conf['parseValues.'] as $theField => $theValue) {
1225                                 $listOfCommands = t3lib_div::trimExplode(',',$theValue,1);
1226                                 foreach ($listOfCommands as $cmd) {
1227                                         $cmdParts = preg_split('/\[|\]/', $cmd);        // Point is to enable parameters after each command enclosed in brackets [..]. These will be in position 1 in the array.
1228                                         $theCmd = trim($cmdParts[0]);
1229                                         switch($theCmd) {
1230                                                 case 'multiple':
1231                                                         if (isset($inputArr[$theField]) && !$this->isPreview()) {
1232                                                                 $inputArr[$theField] = explode(',',$inputArr[$theField]);
1233                                                         }
1234                                                 break;
1235                                                 case 'checkArray':
1236                                                         if ($inputArr[$theField] && !$this->isPreview())        {
1237                                                                 for($a=0;$a<=30;$a++)   {
1238                                                                         if ($inputArr[$theField] & pow(2,$a))   {
1239                                                                                 $alt_theField = $theField.']['.$a;
1240                                                                                 $inputArr[$alt_theField] = 1;
1241                                                                                 $this->additionalUpdateFields.=','.$alt_theField;
1242                                                                         }
1243                                                                 }
1244                                                         }
1245                                                 break;
1246                                         }
1247                                 }
1248                         }
1249                 }
1250
1251
1252                 $inputArr = $this->userProcess_alt(
1253                         $this->conf['userFunc_updateArray'],
1254                         $this->conf['userFunc_updateArray.'],
1255                         $inputArr
1256                 );
1257
1258                 return $this->escapeHTML($inputArr);
1259         }
1260
1261         /**
1262          * Will render TypoScript cObjects (configured in $this->conf['cObjects.']) and add their content to keys in a markerArray, either the array passed to the function or the internal one ($this->markerArray) if the input $markerArray is not set.
1263          *
1264          * @param       string          The current template code string. Is used to check if the marker string is found and if not, the content object is not rendered!
1265          * @param       array           An alternative data record array (if empty then $this->dataArr is used)
1266          * @param       mixed           An alternative markerArray to fill in (instead of $this->markerArray). If you want to set the cobjects in the internal $this->markerArray, then just set this to non-array value.
1267          * @param       string          Optional prefix to set for the marker strings.
1268          * @return      array           The processed $markerArray (if given).
1269          */
1270         function setCObjects($templateCode,$currentArr=array(),$markerArray='',$specialPrefix='')       {
1271                 if (is_array($this->conf['cObjects.'])) {
1272
1273                         foreach ($this->conf['cObjects.'] as $theKey => $theConf) {
1274                                 if (!strstr($theKey,'.'))       {
1275                                         if (strstr($templateCode,'###'.$specialPrefix.'CE_'.$theKey.'###'))     {
1276                                                 $cObjCode = $this->cObj->cObjGetSingle($this->conf['cObjects.'][$theKey], $this->conf['cObjects.'][$theKey.'.'], 'cObjects.'.$theKey);
1277
1278                                                 if (!is_array($markerArray))    {
1279                                                         $this->markerArray['###'.$specialPrefix.'CE_'.$theKey.'###'] = $cObjCode;
1280                                                 } else {
1281                                                         $markerArray['###'.$specialPrefix.'CE_'.$theKey.'###'] = $cObjCode;
1282                                                 }
1283                                         }
1284                                         if (strstr($templateCode,'###'.$specialPrefix.'PCE_'.$theKey.'###'))    {
1285                                                 $local_cObj =t3lib_div::makeInstance('tslib_cObj');
1286                                                 $local_cObj->start(count($currentArr)?$currentArr:$this->dataArr,$this->theTable);
1287                                                 $cObjCode = $local_cObj->cObjGetSingle($this->conf['cObjects.'][$theKey], $this->conf['cObjects.'][$theKey.'.'], 'cObjects.'.$theKey);
1288
1289                                                 if (!is_array($markerArray))    {
1290                                                         $this->markerArray['###'.$specialPrefix.'PCE_'.$theKey.'###'] = $cObjCode;
1291                                                 } else {
1292                                                         $markerArray['###'.$specialPrefix.'PCE_'.$theKey.'###'] = $cObjCode;
1293                                                 }
1294                                         }
1295                                 }
1296                         }
1297                 }
1298                 return $markerArray;
1299         }
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319         /*****************************************
1320          *
1321          * Emailing
1322          *
1323          *****************************************/
1324
1325         /**
1326          * Sends info mail to user
1327          *
1328          * @return      string          HTML content message
1329          * @see init(),compileMail(), sendMail()
1330          */
1331         function sendInfoMail() {
1332                 if ($this->conf['infomail'] && $this->conf['email.']['field'])  {
1333                         $fetch = t3lib_div::_GP('fetch');
1334                         if ($fetch)     {
1335                                         // Getting infomail config.
1336                                 $key= trim(t3lib_div::_GP('key'));
1337                                 if (is_array($this->conf['infomail.'][$key.'.']))               {
1338                                         $config = $this->conf['infomail.'][$key.'.'];
1339                                 } else {
1340                                         $config = $this->conf['infomail.']['default.'];
1341                                 }
1342                                 $pidLock='';
1343                                 if (!$config['dontLockPid'])    {
1344                                         $pidLock='AND pid IN ('.$this->thePid.') ';
1345                                 }
1346
1347                                         // Getting records
1348                                 if (t3lib_div::testInt($fetch)) {
1349                                         $DBrows = $GLOBALS['TSFE']->sys_page->getRecordsByField($this->theTable,'uid',$fetch,$pidLock,'','','1');
1350                                 } elseif ($fetch) {     // $this->conf['email.']['field'] must be a valid field in the table!
1351                                         $DBrows = $GLOBALS['TSFE']->sys_page->getRecordsByField($this->theTable,$this->conf['email.']['field'],$fetch,$pidLock,'','','100');
1352                                 }
1353
1354                                         // Processing records
1355                                 if (is_array($DBrows))  {
1356                                         $recipient = $DBrows[0][$this->conf['email.']['field']];
1357                                         $this->compileMail($config['label'], $DBrows, $recipient, $this->conf['setfixed.']);
1358                                 } elseif ($this->cObj->checkEmail($fetch)) {
1359                                         $this->sendMail($fetch, '', trim($this->cObj->getSubpart($this->templateCode, '###'.$this->emailMarkPrefix.'NORECORD###')));
1360                                 }
1361
1362                                 $content = $this->getPlainTemplate('###TEMPLATE_INFOMAIL_SENT###');
1363                         } else {
1364                                 $content = $this->getPlainTemplate('###TEMPLATE_INFOMAIL###');
1365                         }
1366                 } else $content='Error: infomail option is not available or emailField is not setup in TypoScript';
1367                 return $content;
1368         }
1369
1370         /**
1371          * Compiles and sends a mail based on input values + template parts. Looks for a normal and an "-admin" template and may send both kinds of emails. See documentation in TSref.
1372          *
1373          * @param       string          A key which together with $this->emailMarkPrefix will identify the part from the template code to use for the email.
1374          * @param       array           An array of records which fields are substituted in the templates
1375          * @param       mixed           Mail recipient. If string then its supposed to be an email address. If integer then its a uid of a fe_users record which is looked up and the email address from here is used for sending the mail.
1376          * @param       array           Additional fields to set in the markerArray used in the substitution process
1377          * @return      void
1378          */
1379         function compileMail($key, $DBrows, $recipient, $setFixedConfig=array())        {
1380                 $GLOBALS['TT']->push('compileMail');
1381                 $mailContent='';
1382                 $key = $this->emailMarkPrefix.$key;
1383
1384                 $userContent['all'] = trim($this->cObj->getSubpart($this->templateCode, '###'.$key.'###'));
1385                 $adminContent['all'] = trim($this->cObj->getSubpart($this->templateCode, '###'.$key.'-ADMIN###'));
1386                 $userContent['rec'] = $this->cObj->getSubpart($userContent['all'], '###SUB_RECORD###');
1387                 $adminContent['rec'] = $this->cObj->getSubpart($adminContent['all'], '###SUB_RECORD###');
1388
1389                 foreach ($DBrows as $r) {
1390                         $markerArray = $this->cObj->fillInMarkerArray($this->markerArray, $r,'',0);
1391                         $markerArray = $this->setCObjects($userContent['rec'].$adminContent['rec'],$r,$markerArray,'ITEM_');
1392                         $markerArray['###SYS_AUTHCODE###'] = $this->authCode($r);
1393                         $markerArray = $this->setfixed($markerArray, $setFixedConfig, $r);
1394
1395                         if ($userContent['rec'])        $userContent['accum'] .=$this->cObj->substituteMarkerArray($userContent['rec'], $markerArray);
1396                         if ($adminContent['rec'])       $adminContent['accum'].=$this->cObj->substituteMarkerArray($adminContent['rec'], $markerArray);
1397                 }
1398
1399                 if ($userContent['all'])        $userContent['final'] .=$this->cObj->substituteSubpart($userContent['all'], '###SUB_RECORD###', $userContent['accum']);
1400                 if ($adminContent['all'])       $adminContent['final'].=$this->cObj->substituteSubpart($adminContent['all'], '###SUB_RECORD###', $adminContent['accum']);
1401
1402                 if (t3lib_div::testInt($recipient))     {
1403                         $fe_userRec = $GLOBALS['TSFE']->sys_page->getRawRecord('fe_users',$recipient);
1404                         $recipient=$fe_userRec['email'];
1405                 }
1406
1407                 $GLOBALS['TT']->setTSlogMessage('Template key: ###'.$key.'###, userContentLength: '.strlen($userContent['final']).', adminContentLength: '.strlen($adminContent['final']));
1408
1409                 $this->sendMail($recipient, $this->conf['email.']['admin'], $userContent['final'], $adminContent['final']);
1410                 $GLOBALS['TT']->pull();
1411         }
1412
1413         /**
1414          * Actually sends the requested mails (through $this->cObj->sendNotifyEmail or through $this->sendHTMLMail).
1415          * As of TYPO3 v4.3 with autoloader, a check for $GLOBALS['TSFE']->config['config']['incT3Lib_htmlmail'] has been included for backwards compatibility.
1416          *
1417          * @param       string          Recipient email address (or list)
1418          * @param       string          Possible "admin" email address. Will enable sending of admin emails if also $adminContent is provided
1419          * @param       string          Content for the regular email to user
1420          * @param       string          Content for the admin email to administrator
1421          * @return      void
1422          * @access private
1423          * @see compileMail(), sendInfoMail()
1424          */
1425         function sendMail($recipient, $admin, $content='', $adminContent='')    {
1426                         // Admin mail:
1427                 if ($admin && $adminContent)    {
1428                         if (!$this->isHTMLContent($adminContent) || !$GLOBALS['TSFE']->config['config']['incT3Lib_htmlmail']) {
1429                                 $admMail = $this->cObj->sendNotifyEmail(
1430                                                                         strip_tags($adminContent),
1431                                                                         $admin,
1432                                                                         '',
1433                                                                         $this->conf['email.']['from'],
1434                                                                         $this->conf['email.']['fromName'],
1435                                                                         $recipient
1436                                                         );
1437                         } else {
1438                                 $this->sendHTMLMail($adminContent,
1439                                                                         $admin,
1440                                                                         '',
1441                                                                         $this->conf['email.']['from'],
1442                                                                         $this->conf['email.']['fromName'],
1443                                                                         $recipient
1444                                                         );
1445                         }
1446                 }
1447                         // user mail:
1448                 if (!$this->isHTMLContent($content) || !$GLOBALS['TSFE']->config['config']['incT3Lib_htmlmail']) {
1449                         $this->cObj->sendNotifyEmail(
1450                                                                 strip_tags($content),
1451                                                                 $recipient,
1452                                                                 '',                     // ($admMail ? '' : $admin),            // If the special administration mail was not found and send, the regular is...
1453                                                                 $this->conf['email.']['from'],
1454                                                                 $this->conf['email.']['fromName']
1455                                                 );
1456                 } else {
1457                         $this->sendHTMLMail($content,
1458                                                                 $recipient,
1459                                                                 '',                     // ($admMail ? '' : $admin),            // If the special administration mail was not found and send, the regular is...
1460                                                                 $this->conf['email.']['from'],
1461                                                                 $this->conf['email.']['fromName']
1462                                                 );
1463                 }
1464         }
1465
1466         /**
1467          * Detects if content is HTML (looking for <html> tag as first and last in string)
1468          *
1469          * @param       string          Content string to test
1470          * @return      boolean         Returns true if the content begins and ends with <html></html>-tags
1471          */
1472         function isHTMLContent($c)      {
1473                 $c = trim($c);
1474                 $first = strtolower(substr($c,0,6));
1475                 $last = strtolower(substr($c,-7));
1476                 if ($first.$last=='<html></html>')      return 1;
1477         }
1478
1479         /**
1480          * Sending HTML email, using same parameters as tslib_cObj::sendNotifyEmail()
1481          *
1482          * @param       string          The message content. If blank, no email is sent.
1483          * @param       string          Comma list of recipient email addresses
1484          * @param       string          IGNORE this parameter
1485          * @param       string          "From" email address
1486          * @param       string          Optional "From" name
1487          * @param       string          Optional "Reply-To" header email address.
1488          * @return      void
1489          * @access private
1490          * @see sendMail(), tslib_cObj::sendNotifyEmail()
1491          */
1492         function sendHTMLMail($content,$recipient,$dummy,$fromEmail,$fromName,$replyTo='')      {
1493                 if (trim($recipient) && trim($content)) {
1494                         $parts = preg_split('/<title>|<\/title>/i', $content, 3);
1495                         $subject = trim($parts[1]) ? trim($parts[1]) : 'TYPO3 FE Admin message';
1496
1497                         $Typo3_htmlmail = t3lib_div::makeInstance('t3lib_htmlmail');
1498                         $Typo3_htmlmail->start();
1499                         $Typo3_htmlmail->useBase64();
1500
1501                         $Typo3_htmlmail->subject = $subject;
1502                         $Typo3_htmlmail->from_email = $fromEmail;
1503                         $Typo3_htmlmail->from_name = $fromName;
1504                         $Typo3_htmlmail->replyto_email = $replyTo ? $replyTo : $fromEmail;
1505                         $Typo3_htmlmail->replyto_name = $replyTo ? '' : $fromName;
1506                         $Typo3_htmlmail->organisation = '';
1507                         $Typo3_htmlmail->priority = 3;
1508
1509                                 // HTML
1510                         $Typo3_htmlmail->theParts['html']['content'] = $content;        // Fetches the content of the page
1511                         $Typo3_htmlmail->theParts['html']['path'] = '';
1512                         $Typo3_htmlmail->extractMediaLinks();
1513                         $Typo3_htmlmail->extractHyperLinks();
1514                         $Typo3_htmlmail->fetchHTMLMedia();
1515                         $Typo3_htmlmail->substMediaNamesInHTML(0);      // 0 = relative
1516                         $Typo3_htmlmail->substHREFsInHTML();
1517                         $Typo3_htmlmail->setHTML($Typo3_htmlmail->encodeMsg($Typo3_htmlmail->theParts['html']['content']));
1518
1519                                 // PLAIN
1520                         $Typo3_htmlmail->addPlain('');
1521
1522                                 // SET Headers and Content
1523                         $Typo3_htmlmail->setHeaders();
1524                         $Typo3_htmlmail->setContent();
1525                         $Typo3_htmlmail->setRecipient($recipient);
1526
1527                         $Typo3_htmlmail->sendtheMail();
1528                 }
1529         }
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554         /*****************************************
1555          *
1556          * Various helper functions
1557          *
1558          *****************************************/
1559
1560
1561         /**
1562          * Returns true if authentication is OK based on the "aC" code which is a GET parameter set from outside with a hash string which must match some internal hash string.
1563          * This allows to authenticate editing without having a fe_users login
1564          * Uses $this->authCode which is set in init() by "t3lib_div::_GP('aC');"
1565          *
1566          * @param       array           The data array for which to evaluate authentication
1567          * @return      boolean         True if authenticated OK
1568          * @see authCode(), init()
1569          */
1570         function aCAuth($r)     {
1571                 if ($this->authCode && !strcmp($this->authCode,$this->authCode($r)))    {
1572                         return true;
1573                 }
1574         }
1575
1576         /**
1577          * Creating authentication hash string based on input record and the fields listed in TypoScript property "authcodeFields"
1578          *
1579          * @param       array           The data record
1580          * @param       string          Additional string to include in the hash
1581          * @return      string          Hash string of $this->codeLength (if TypoScript "authcodeFields" was set)
1582          * @see aCAuth()
1583          */
1584         function authCode($r,$extra='') {
1585                 $l=$this->codeLength;
1586                 if ($this->conf['authcodeFields'])      {
1587                         $fieldArr = t3lib_div::trimExplode(',', $this->conf['authcodeFields'], 1);
1588                         $value='';
1589                         foreach ($fieldArr as $field) {
1590                                 $value.=$r[$field].'|';
1591                         }
1592                         $value.=$extra.'|'.$this->conf['authcodeFields.']['addKey'];
1593                         if ($this->conf['authcodeFields.']['addDate'])  {
1594                                 $value.='|'.date($this->conf['authcodeFields.']['addDate']);
1595                         }
1596                         $value.=$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1597                         return substr(md5($value), 0,$l);
1598                 }
1599         }
1600
1601         /**
1602          * Adding keys to the marker array with "setfixed" GET parameters
1603          *
1604          * @param       array           Marker-array to modify/add a key to.
1605          * @param       array           TypoScript properties configuring "setfixed" for the plugin. Basically this is $this->conf['setfixed.'] passed along.
1606          * @param       array           The data record
1607          * @return      array           Processed $markerArray
1608          * @see compileMail()
1609          */
1610         function setfixed($markerArray, $setfixed, $r)  {
1611                 if (is_array($setfixed))        {
1612                         foreach ($setfixed as $theKey => $data) {
1613                                 if (!strcmp($theKey,'DELETE'))  {
1614                                         $recCopy = $r;
1615                                         $string='&cmd=setfixed&sFK='.rawurlencode($theKey).'&rU='.$r['uid'];
1616                                         $string.='&aC='.$this->setfixedHash($recCopy,$data['_FIELDLIST']);
1617                                         $markerArray['###SYS_SETFIXED_DELETE###'] = $string;
1618                                         $markerArray['###SYS_SETFIXED_HSC_DELETE###'] = htmlspecialchars($string);
1619                                 } elseif (strstr($theKey,'.'))  {
1620                                         $theKey = substr($theKey,0,-1);
1621                                         if (is_array($data))    {
1622                                                 $recCopy = $r;
1623                                                 $string='&cmd=setfixed&sFK='.rawurlencode($theKey).'&rU='.$r['uid'];
1624                                                 foreach ($data as $fieldName => $fieldValue) {
1625                                                         $string.='&fD%5B'.$fieldName.'%5D='.rawurlencode($fieldValue);
1626                                                         $recCopy[$fieldName]=$fieldValue;
1627                                                 }
1628                                                 $string.='&aC='.$this->setfixedHash($recCopy,$data['_FIELDLIST']);
1629                                                 $markerArray['###SYS_SETFIXED_'.$theKey.'###'] = $string;
1630                                                 $markerArray['###SYS_SETFIXED_HSC_'.$theKey.'###'] = htmlspecialchars($string);
1631                                         }
1632                                 }
1633                         }
1634                 }
1635                 return $markerArray;
1636         }
1637
1638         /**
1639          * Creating hash string for setFixed. Much similar to authCode()
1640          *
1641          * @param       array           The data record
1642          * @param       string          List of fields to use
1643          * @return      string          Hash string of $this->codeLength (if TypoScript "authcodeFields" was set)
1644          * @see setfixed(),authCode()
1645          */
1646         function setfixedHash($recCopy,$fields='')      {
1647                 if ($fields)    {
1648                         $fieldArr = t3lib_div::trimExplode(',',$fields,1);
1649                         foreach ($fieldArr as $k => $v) {
1650                                 $recCopy_temp[$k]=$recCopy[$v];
1651                         }
1652                 } else {
1653                         $recCopy_temp=$recCopy;
1654                 }
1655                 $encStr = implode('|',$recCopy_temp).'|'.$this->conf['authcodeFields.']['addKey'].'|'.$GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'];
1656                 $hash = substr(md5($encStr),0,$this->codeLength);
1657                 return $hash;
1658         }
1659
1660
1661         /**
1662          * Returns true if preview display is on.
1663          *
1664          * @return      boolean
1665          */
1666         function isPreview()    {
1667                 return ($this->conf[$this->cmdKey.'.']['preview'] && $this->preview);
1668         }
1669
1670         /**
1671          * Creates an instance of class "t3lib_basicFileFunctions" in $this->fileFunc (if not already done)
1672          *
1673          * @return      void
1674          */
1675         function createFileFuncObj()    {
1676                 if (!$this->fileFunc)   {
1677                         $this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
1678                 }
1679         }
1680
1681         /**
1682          * If TypoScript property clearCacheOfPages is set then all page ids in this value will have their cache cleared
1683          *
1684          * @return      void
1685          */
1686         function clearCacheIfSet()      {
1687                 if ($this->conf['clearCacheOfPages'])   {
1688                         $cc_pidList = $GLOBALS['TYPO3_DB']->cleanIntList($this->conf['clearCacheOfPages']);
1689                         $GLOBALS['TSFE']->clearPageCacheContent_pidList($cc_pidList);
1690                 }
1691         }
1692
1693         /**
1694          * Returns an error message for the field/command combination inputted. The error message is looked up in the TypoScript properties (evalErrors.[fieldname].[command]) and if empty then the $label value is returned
1695          *
1696          * @param       string          Field name
1697          * @param       string          Command identifier string
1698          * @param       string          Alternative label, shown if no other error string was found
1699          * @return      string          The error message string
1700          */
1701         function getFailure($theField, $theCmd, $label) {
1702                 return isset($this->conf['evalErrors.'][$theField.'.'][$theCmd]) ? $this->conf['evalErrors.'][$theField.'.'][$theCmd] : $label;
1703         }
1704
1705         /**
1706          * Will escape HTML-tags
1707          *
1708          * @param       mixed           The unescaped data
1709          * @return      mixed           The processed input data
1710          */
1711         function escapeHTML($var)       {
1712                 if (is_array($var)) {
1713                         foreach ($var as $k => $value) {
1714                                 $var[$k] = $this->escapeHTML($var[$k]);
1715                         }
1716                 } else {
1717                         $var = htmlspecialchars($var, ENT_NOQUOTES);
1718                 }
1719                 return $var;
1720         }
1721 }
1722
1723
1724 if (defined('TYPO3_MODE') && isset($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['media/scripts/fe_adminLib.inc'])) {
1725         include_once($GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['XCLASS']['media/scripts/fe_adminLib.inc']);
1726 }
1727 ?>