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