/**
	 * Spam-Validation of given Params
	 * 		see powermail/doc/SpamDetection for formula
	 *
	 * @param array $params
	 * @return bool
	 */
	public function isValid($params) {
		if (!$this->settings['spamshield.']['_enable']) {
			return true;
		}
		$this->div = t3lib_div::makeInstance('Tx_Powermail_Utility_Div');
		$spamFactor = $this->settings['spamshield.']['factor'] / 100;

		// Different checks to increase spam indicator
		$this->honeypodCheck($params, $this->settings['spamshield.']['indicator.']['honeypod']);
		$this->linkCheck($params, $this->settings['spamshield.']['indicator.']['link'], $this->settings['spamshield.']['indicator.']['linkLimit']);
		$this->nameCheck($params, $this->settings['spamshield.']['indicator.']['name']);
		$this->sessionCheck($this->settings['spamshield.']['indicator.']['session']);
		$this->uniqueCheck($params, $this->settings['spamshield.']['indicator.']['unique']);
		$this->blacklistStringCheck($params, $this->settings['spamshield.']['indicator.']['blacklistString']);
		$this->blacklistIpCheck($this->settings['spamshield.']['indicator.']['blacklistIp']);

		// spam formula with asymptote 1 (100%)
		if ($this->spamIndicator > 0) {
			$thisSpamFactor = -1 / $this->spamIndicator + 1;
		} else {
			$thisSpamFactor = 0;
		}

		// Save Spam Factor in session for db storage
		$GLOBALS['TSFE']->fe_user->setKey('ses', 'powermail_spamfactor', $this->formatSpamFactor($thisSpamFactor));
		$GLOBALS['TSFE']->storeSessionData();

		// Spam debugging
		if ($this->settings['debug.']['spamshield']) {
			t3lib_utility_Debug::debug($this->msg, 'powermail debug: Show Spamchecks - Spamfactor ' . $this->formatSpamFactor($thisSpamFactor));
		}

		// if spam
		if ($thisSpamFactor >= $spamFactor) {
			$this->addError('spam_details', $this->formatSpamFactor($thisSpamFactor));

			// Send notification email to admin
			if (t3lib_div::validEmail($this->settings['spamshield.']['email'])) {
				$subject = 'Spam in powermail form recognized';
				$message = 'Possible spam in powermail form on page with PID ' . $GLOBALS['TSFE']->id;
				$message .= "\n\n";
				$message .= 'Spamfactor of this mail: ' . $this->formatSpamFactor($thisSpamFactor) . "\n";
				$message .= "\n\n";
				$message .= 'Failed Spamchecks:' . "\n";
				$message .= Tx_Powermail_Utility_Div::viewPlainArray($this->msg);
				$message .= "\n\n";
				$message .= 'Given Form variables:' . "\n";
				$message .= Tx_Powermail_Utility_Div::viewPlainArray($params);
				$header  = 'MIME-Version: 1.0' . "\r\n";
				$header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
				$header .= 'From: powermail@' . t3lib_div::getIndpEnv('TYPO3_HOST_ONLY') . "\r\n";
				t3lib_div::plainMailEncoded($this->settings['spamshield.']['email'], $subject, $message, $header);
			}

			return false;
		}

		return true;
	}
	/**
	 * Server valuation
	 *
	 * @param 	$value		The field value to be evaluated.
	 * @param 	$is_in		The "is_in" value of the field configuration from TCA
	 * @param 	$set		Boolean defining if the value is written to the database or not. Must be passed by reference and changed if needed.
	 * @return 	string		Value
	 */
	public function evaluateFieldValue($value, $is_in, &$set) {
		if (t3lib_div::validEmail($value)) {
			$set = 1;
		} else {
			$set = 0;
			$value = '*****@*****.**';
		}
		return $value;
	}
 /**
  * Validates that a specified field has valid email syntax.
  *
  * @param array &$check The TypoScript settings for this error check
  * @param string $name The field name
  * @param array &$gp The current GET/POST parameters
  * @return string The error string
  */
 public function check(&$check, $name, &$gp)
 {
     $checkFailed = '';
     if (isset($gp[$name]) && strlen(trim($gp[$name])) > 0) {
         $valid = t3lib_div::validEmail($gp[$name]);
         if (!$valid) {
             $checkFailed = $this->getCheckFailed($check);
         }
     }
     return $checkFailed;
 }
示例#4
0
 /**
  * Validation of given Params
  *
  * @param Tx_WoehrlSeminare_Domain_Model_Subscriber $newSubscriber
  * @return bool
  */
 public function isValid($newSubscriber)
 {
     if (strlen($newSubscriber->getName()) < 3) {
         $error = $this->objectManager->get('Tx_Extbase_Error_Error', 'val_name', 1000);
         $this->result->forProperty('name')->addError($error);
         // usually $this->addError is enough but this doesn't set the CSS errorClass in the form-viewhelper :-(
         //			$this->addError('val_name', 1000);
         $this->isValid = FALSE;
     }
     if (!t3lib_div::validEmail($newSubscriber->getEmail())) {
         $error = $this->objectManager->get('Tx_Extbase_Error_Error', 'val_email', 1100);
         $this->result->forProperty('email')->addError($error);
         //			$this->addError('val_email', 1100);
         $this->isValid = FALSE;
     }
     if (strlen($newSubscriber->getCustomerid()) > 0 && filter_var($newSubscriber->getCustomerid(), FILTER_VALIDATE_INT) === FALSE) {
         $error = $this->objectManager->get('Tx_Extbase_Error_Error', 'val_customerid', 1110);
         $this->result->forProperty('customerid')->addError($error);
         //			$this->addError('val_customerid', 1110);
         $this->isValid = FALSE;
     }
     if (strlen($newSubscriber->getNumber()) == 0 || filter_var($newSubscriber->getNumber(), FILTER_VALIDATE_INT) === FALSE || $newSubscriber->getNumber() < 1) {
         $error = $this->objectManager->get('Tx_Extbase_Error_Error', 'val_number', 1120);
         $this->result->forProperty('number')->addError($error);
         //			$this->addError('val_number', 1120);
         $this->isValid = FALSE;
     } else {
         $event = $newSubscriber->getEvent();
         // limit reached already --> overbooked
         if ($this->subscriberRepository->countAllByEvent($event) + $newSubscriber->getNumber() > $event->getMaxSubscriber()) {
             $error = $this->objectManager->get('Tx_Extbase_Error_Error', 'val_number', 1130);
             $this->result->forProperty('number')->addError($error);
             //			    $this->addError('val_number', 1130);
             $this->isValid = FALSE;
         }
     }
     if ($newSubscriber->getEditcode() != $this->getSessionData('editcode')) {
         $error = $this->objectManager->get('Tx_Extbase_Error_Error', 'val_editcode', 1140);
         $this->result->forProperty('editcode')->addError($error);
         //			$this->addError('val_editcode', 1140);
         $this->isValid = FALSE;
     }
     return $this->isValid;
 }
	/**
	 * Check View Backend
	 *
	 * @param string $email email address
	 * @return void
	 */
	public function checkBeAction($email = NULL) {
		$this->view->assign('pid', t3lib_div::_GP('id'));

		if ($email) {
			if (t3lib_div::validEmail($email)) {
				$body = 'New <b>Test Email</b> from User ' . $GLOBALS['BE_USER']->user['username'] . ' (' . t3lib_div::getIndpEnv('HTTP_HOST') . ')';

				$message = t3lib_div::makeInstance('t3lib_mail_Message');
				$message
					->setTo(array($email => 'Receiver'))
					->setFrom(array('*****@*****.**' => 'powermail'))
					->setSubject('New Powermail Test Email')
					->setBody($body, 'text/html')
					->send();

				$this->view->assign('issent', $message->isSent());
				$this->view->assign('email', $email);
			}
		}
	}
 function startIndexing($verbose = true, $extConf, $mode = '')
 {
     // write starting timestamp into registry
     // this is a helper to delete all records which are older than starting timestamp in registry
     // this also prevents starting the indexer twice
     if ($this->registry->get('tx_kesearch', 'startTimeOfIndexer') === null) {
         $this->registry->set('tx_kesearch', 'startTimeOfIndexer', time());
     } else {
         // check lock time
         $lockTime = $this->registry->get('tx_kesearch', 'startTimeOfIndexer');
         $compareTime = time() - 60 * 60 * 12;
         if ($lockTime < $compareTime) {
             // lock is older than 12 hours - remove
             $this->registry->removeAllByNamespace('tx_kesearch');
             $this->registry->set('tx_kesearch', 'startTimeOfIndexer', time());
         } else {
             return 'You can\'t start the indexer twice. Please wait while first indexer process is currently running';
         }
     }
     // set indexing start time
     $this->startTime = time();
     // get configurations
     $configurations = $this->getConfigurations();
     // number of records that should be written to the database in one action
     $this->amountOfRecordsToSaveInMem = 500;
     // register additional fields which should be written to DB
     if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['registerAdditionalFields'])) {
         foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['registerAdditionalFields'] as $_classRef) {
             if (TYPO3_VERSION_INTEGER >= 7000000) {
                 $_procObj =& TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($_classRef);
             } else {
                 $_procObj =& t3lib_div::getUserObj($_classRef);
             }
             $_procObj->registerAdditionalFields($this->additionalFields);
         }
     }
     // set some prepare statements
     $this->prepareStatements();
     foreach ($configurations as $indexerConfig) {
         $this->indexerConfig = $indexerConfig;
         // run default indexers shipped with ke_search
         if (in_array($this->indexerConfig['type'], $this->defaultIndexerTypes)) {
             if (TYPO3_VERSION_INTEGER < 6002000) {
                 $path = t3lib_extMgm::extPath('ke_search') . 'Classes/indexer/types/class.tx_kesearch_indexer_types_' . $this->indexerConfig['type'] . '.php';
             } else {
                 $path = TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('ke_search') . 'Classes/indexer/types/class.tx_kesearch_indexer_types_' . $this->indexerConfig['type'] . '.php';
             }
             if (is_file($path)) {
                 require_once $path;
                 if (TYPO3_VERSION_INTEGER >= 6002000) {
                     $searchObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('tx_kesearch_indexer_types_' . $this->indexerConfig['type'], $this);
                 } else {
                     $searchObj = t3lib_div::makeInstance('tx_kesearch_indexer_types_' . $this->indexerConfig['type'], $this);
                 }
                 $content .= $searchObj->startIndexing();
             } else {
                 $content = '<div class="error"> Could not find file ' . $path . '</div>' . "\n";
             }
         }
         // hook for custom indexer
         if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['customIndexer'])) {
             foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['ke_search']['customIndexer'] as $_classRef) {
                 if (TYPO3_VERSION_INTEGER >= 7000000) {
                     $_procObj =& TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($_classRef);
                 } else {
                     $_procObj =& t3lib_div::getUserObj($_classRef);
                 }
                 $content .= $_procObj->customIndexer($indexerConfig, $this);
             }
         }
         // In most cases there are some records waiting in ram to be written to db
         $this->storeTempRecordsToIndex('both');
     }
     // process index cleanup
     $content .= $this->cleanUpIndex();
     // count index records
     $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', 'tx_kesearch_index');
     $content .= '<p><b>Index contains ' . $count . ' entries.</b></p>';
     // clean up process after indezing to free memory
     $this->cleanUpProcessAfterIndexing();
     // print indexing errors
     if (sizeof($this->indexingErrors)) {
         $content .= "\n\n" . '<br /><br /><br /><b>INDEXING ERRORS (' . sizeof($this->indexingErrors) . ')<br /><br />' . CHR(10);
         foreach ($this->indexingErrors as $error) {
             $content .= $error . '<br />' . CHR(10);
         }
     }
     // create plaintext report
     $plaintextReport = $this->createPlaintextReport($content);
     // send notification in CLI mode
     if ($mode == 'CLI') {
         // send finishNotification
         if (TYPO3_VERSION_INTEGER >= 7000000) {
             $isValidEmail = TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($extConf['notificationRecipient']);
         } else {
             $isValidEmail = t3lib_div::validEmail($extConf['notificationRecipient']);
         }
         if ($extConf['finishNotification'] && $isValidEmail) {
             // send the notification message
             // use swiftmailer in 4.5 and above
             if (TYPO3_VERSION_INTEGER >= 4005000) {
                 if (TYPO3_VERSION_INTEGER >= 7000000) {
                     $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Mail\\MailMessage');
                 } else {
                     if (TYPO3_VERSION_INTEGER >= 6002000) {
                         $mail = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('t3lib_mail_Message');
                     } else {
                         $mail = t3lib_div::makeInstance('t3lib_mail_Message');
                     }
                 }
                 $mail->setFrom(array($extConf['notificationSender']));
                 $mail->setTo(array($extConf['notificationRecipient']));
                 $mail->setSubject($extConf['notificationSubject']);
                 $mail->setBody($plaintextReport);
                 $mail->send();
             } else {
                 mail($extConf['notificationRecipient'], $subject, $plaintextReport);
             }
         }
     }
     // log report to sys_log
     $GLOBALS['BE_USER']->simplelog($plaintextReport, 'ke_search');
     // verbose or quiet output? as set in function call!
     if ($verbose) {
         return $content;
     }
 }
 /**
  * Sends info mail to subscriber or displays a screen to update or delete the membership
  *
  * @param array $cObj: the cObject
  * @param array $langObj: the language object
  * @param array $controlData: the object of the control data
  * @param array $controlData: the object of the control data
  * @param string $theTable: the table in use
  * @param string $prefixId: the extension prefix id
  * @param array  Array with key/values being marker-strings/substitution values.
  * @return	string		HTML content message
  * @see init(),compile(), send()
  */
 public function sendInfo($conf, $cObj, $langObj, $controlData, $tcaObj, $markerObj, $dataObj, $displayObj, $setfixedObj, $theTable, $prefixId, $origArr, $securedArray, $markerArray, $cmd, $cmdKey, $templateCode, $failure, &$errorCode)
 {
     $content = FALSE;
     if ($conf['infomail'] && $conf['email.']['field']) {
         $fetch = $controlData->getFeUserData('fetch');
         if (isset($fetch) && !empty($fetch) && !$failure) {
             $pidLock = 'AND pid IN (' . ($cObj->data['pages'] ? $cObj->data['pages'] . ',' : '') . $controlData->getPid() . ')';
             $enable = $GLOBALS['TSFE']->sys_page->enableFields($theTable);
             // Getting records
             // $conf['email.']['field'] must be a valid field in the table!
             $DBrows = $GLOBALS['TSFE']->sys_page->getRecordsByField($theTable, $conf['email.']['field'], $fetch, $pidLock . $enable, '', '', '100');
             $errorContent = '';
             // Processing records
             if (is_array($DBrows)) {
                 $recipient = $DBrows[0][$conf['email.']['field']];
                 $dataObj->setDataArray($DBrows[0]);
                 $errorContent = $this->compile('INFOMAIL', $conf, $cObj, $langObj, $controlData, $tcaObj, $markerObj, $dataObj, $displayObj, $setfixedObj, $theTable, $prefixId, $DBrows, $DBrows, $securedArray, trim($recipient), $markerArray, $cmd, $cmdKey, $templateCode, $dataObj->getInError(), $conf['setfixed.'], $errorCode);
             } elseif (t3lib_div::validEmail($fetch)) {
                 $fetchArray = array('0' => array('email' => $fetch));
                 $errorContent = $this->compile('INFOMAIL_NORECORD', $conf, $cObj, $langObj, $controlData, $tcaObj, $markerObj, $dataObj, $displayObj, $setfixedObj, $theTable, $prefixId, $fetchArray, $fetchArray, $securedArray, $fetch, $markerArray, $cmd, $cmdKey, $templateCode, $dataObj->getInError(), array(), $errorCode);
             }
             if ($errorContent || is_array($errorCode)) {
                 $content = $errorContent;
             } else {
                 $subpartkey = '###TEMPLATE_' . $this->infomailPrefix . 'SENT###';
                 $content = $displayObj->getPlainTemplate($conf, $cObj, $langObj, $controlData, $tcaObj, $markerObj, $dataObj, $templateCode, $subpartkey, $markerArray, $origArr, $theTable, $prefixId, is_array($DBrows) ? $DBrows[0] : (is_array($fetchArray) ? $fetchArray[0] : ''), $securedArray, FALSE);
                 if (!$content) {
                     // compatibility until 1.1.2010
                     $subpartkey = '###' . $this->emailMarkPrefix . $this->infomailPrefix . 'SENT###';
                     $content = $displayObj->getPlainTemplate($conf, $cObj, $langObj, $controlData, $tcaObj, $markerObj, $dataObj, $templateCode, $subpartkey, $markerArray, $origArr, $theTable, $prefixId, is_array($DBrows) ? $DBrows[0] : (is_array($fetchArray) ? $fetchArray[0] : ''), $securedArray);
                 }
             }
         } else {
             $subpartkey = '###TEMPLATE_INFOMAIL###';
             if (isset($fetch) && !empty($fetch)) {
                 $markerArray['###FIELD_email###'] = htmlspecialchars($fetch);
             } else {
                 $markerArray['###FIELD_email###'] = '';
             }
             $content = $displayObj->getPlainTemplate($conf, $cObj, $langObj, $controlData, $tcaObj, $markerObj, $dataObj, $templateCode, $subpartkey, $markerArray, $origArr, $theTable, $prefixId, '', $securedArray, TRUE, $failure);
         }
     } else {
         $errorCode = array();
         $errorCode['0'] = 'internal_infomail_configuration';
     }
     return $content;
 }
示例#8
0
 /**
  * Gets all assigned recipients of a particular stage.
  *
  * @param integer $stage
  * @return array
  */
 protected function getReceipientsOfStage($stage)
 {
     $result = array();
     $recipients = $this->getStageService()->getResponsibleBeUser($stage);
     foreach ($recipients as $id => $user) {
         if (t3lib_div::validEmail($user['email'])) {
             $name = $user['realName'] ? $user['realName'] : $user['username'];
             $result[] = array('boxLabel' => sprintf('%s (%s)', $name, $user['email']), 'name' => 'receipients-' . $id, 'checked' => TRUE);
         }
     }
     return $result;
 }
示例#9
0
 /**
  * Validates that $emailAddress is non-empty and valid. If it is not, this method throws an exception.
  *
  * @param string $emailAddress the supposed e-mail address to check
  * @param string $roleDescription e.g., "To:" or "From:", must not be empty
  *
  * @return void
  *
  * @throws InvalidArgumentException
  */
 protected function validateEmailAddress($emailAddress, $roleDescription)
 {
     if ($emailAddress === '') {
         throw new InvalidArgumentException('The ' . $roleDescription . ' e-mail address "' . $emailAddress . '" was empty.', 1409601561);
     }
     if (!$this->isLocalhostAddress($emailAddress) && !t3lib_div::validEmail($emailAddress)) {
         throw new InvalidArgumentException('The ' . $roleDescription . ' e-mail address "' . $emailAddress . '" was not valid.', 1409601561);
     }
 }
 /**
  * This method checks any additional data that is relevant to the specific task
  * If the task class is not relevant, the method is expected to return true
  *
  * @param	array					$submittedData: reference to the array containing the data submitted by the user
  * @param	tx_scheduler_Module		$parentObject: reference to the calling object (Scheduler's BE module)
  * @return	boolean					True if validation was ok (or selected class is not relevant), false otherwise
  */
 public function validateAdditionalFields(array &$submittedData, tx_scheduler_Module $parentObject)
 {
     $bError = false;
     foreach ($this->getAdditionalFieldConfig() as $sKey => $aOptions) {
         $mValue =& $submittedData[$sKey];
         // bei einer checkbox ist der value immer 'on'!
         if ($aOptions['type'] && $mValue === 'on') {
             $mValue = 1;
         }
         $bMessage = false;
         // Die Einzelnen validatoren anwenden.
         if (!$bMessage) {
             foreach (t3lib_div::trimExplode(',', $aOptions['eval']) as $sEval) {
                 $sLabelKey = ($aOptions['label'] ? $aOptions['label'] : $sKey) . '_eval_' . $sEval;
                 switch ($sEval) {
                     case 'required':
                         $bMessage = empty($mValue);
                         break;
                     case 'trim':
                         $mValue = trim($mValue);
                         break;
                     case 'int':
                         $bMessage = !is_numeric($mValue);
                         if (!$bMessage) {
                             $mValue = intval($mValue);
                         }
                         break;
                     case 'date':
                         $mValue = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $mValue);
                         break;
                     case 'email':
                         //wir unterstützen kommaseparierte listen von email andressen
                         if (!empty($mValue)) {
                             $aEmails = explode(',', $mValue);
                             $bMessage = false;
                             foreach ($aEmails as $sEmail) {
                                 if (!t3lib_div::validEmail($sEmail)) {
                                     $bMessage = true;
                                 }
                             }
                         }
                         break;
                     case 'folder':
                         tx_rnbase::load('tx_mklib_util_File');
                         $sPath = tx_mklib_util_File::getServerPath($mValue);
                         $bMessage = !@is_dir($sPath);
                         if (!$bMessage) {
                             $mValue = $sPath;
                         }
                         break;
                     case 'file':
                         tx_rnbase::load('tx_mklib_util_File');
                         $sPath = tx_mklib_util_File::getServerPath($mValue);
                         $bMessage = !@file_exists($sPath);
                         if (!$bMessage) {
                             $mValue = $sPath;
                         }
                         break;
                     case 'url':
                         $bMessage = !t3lib_div::isValidUrl($mValue);
                         break;
                     default:
                         // wir prüfen auf eine eigene validator methode in der Kindklasse.
                         // in eval muss validateLifetime stehen, damit folgende methode aufgerufen wird.
                         // protected function validateLifetime($mValue){ return true; }
                         // @TODO: clasname::method prüfen!?
                         if (method_exists($this, $sEval)) {
                             $ret = $this->{$sEval}($mValue, $submittedData);
                             if (is_string($ret)) {
                                 $bMessage = $sMessage = $ret;
                             }
                         }
                 }
                 // wir generieren nur eine meldung pro feld!
                 if ($bMessage) {
                     break;
                 }
             }
         }
         // wurde eine fehlermeldung erzeugt?
         if ($bMessage) {
             $sMessage = $sMessage ? $sMessage : $GLOBALS['LANG']->sL($sLabelKey);
             $sMessage = $sMessage ? $sMessage : ucfirst($sKey) . ' has to eval ' . $sEval . '.';
             $parentObject->addMessage($sMessage, t3lib_FlashMessage::ERROR);
             $bError = true;
             continue;
         }
     }
     return !$bError;
 }
示例#11
0
 /**
  * Logs message to the system log.
  * This should be implemented around the source code, including the Core and both frontend and backend, logging serious errors.
  * If you want to implement the sysLog in your applications, simply add lines like:
  *		 t3lib_div::sysLog('[write message in English here]', 'extension_key', 'severity');
  *
  * @param	string		Message (in English).
  * @param	string		Extension key (from which extension you are calling the log) or "Core"
  * @param	integer		Severity: 0 is info, 1 is notice, 2 is warning, 3 is error, 4 is fatal error
  * @return	void
  */
 public static function sysLog($msg, $extKey, $severity = 0)
 {
     global $TYPO3_CONF_VARS;
     $severity = self::intInRange($severity, 0, 4);
     // is message worth logging?
     if (intval($TYPO3_CONF_VARS['SYS']['systemLogLevel']) > $severity) {
         return;
     }
     // initialize logging
     if (!$TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogInit']) {
         self::initSysLog();
     }
     // do custom logging
     if (isset($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog']) && is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'])) {
         $params = array('msg' => $msg, 'extKey' => $extKey, 'backTrace' => debug_backtrace(), 'severity' => $severity);
         $fakeThis = FALSE;
         foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLog'] as $hookMethod) {
             self::callUserFunction($hookMethod, $params, $fakeThis);
         }
     }
     // TYPO3 logging enabled?
     if (!$TYPO3_CONF_VARS['SYS']['systemLog']) {
         return;
     }
     $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
     $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
     // use all configured logging options
     foreach (explode(';', $TYPO3_CONF_VARS['SYS']['systemLog'], 2) as $log) {
         list($type, $destination, $level) = explode(',', $log, 4);
         // is message worth logging for this log type?
         if (intval($level) > $severity) {
             continue;
         }
         $msgLine = ' - ' . $extKey . ': ' . $msg;
         // write message to a file
         if ($type == 'file') {
             $file = fopen($destination, 'a');
             if ($file) {
                 flock($file, LOCK_EX);
                 // try locking, but ignore if not available (eg. on NFS and FAT)
                 fwrite($file, date($dateFormat . ' ' . $timeFormat) . $msgLine . LF);
                 flock($file, LOCK_UN);
                 // release the lock
                 fclose($file);
                 self::fixPermissions($destination);
             }
         } elseif ($type == 'mail') {
             list($to, $from) = explode('/', $destination);
             if (!t3lib_div::validEmail($from)) {
                 $from = t3lib_utility_Mail::getSystemFrom();
             }
             /** @var $mail t3lib_mail_Message */
             $mail = t3lib_div::makeInstance('t3lib_mail_Message');
             $mail->setTo($to)->setFrom($from)->setSubject('Warning - error in TYPO3 installation')->setBody('Host: ' . $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . LF . 'Extension: ' . $extKey . LF . 'Severity: ' . $severity . LF . LF . $msg);
             $mail->send();
         } elseif ($type == 'error_log') {
             error_log($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_div.php']['systemLogHost'] . $msgLine, 0);
         } elseif ($type == 'syslog') {
             $priority = array(LOG_INFO, LOG_NOTICE, LOG_WARNING, LOG_ERR, LOG_CRIT);
             syslog($priority[(int) $severity], $msgLine);
         }
     }
 }
 /**
  * Creates a valid email address for the sender of mail messages.
  *
  * Uses a fallback chain:
  *     $TYPO3_CONF_VARS['MAIL']['defaultMailFromAddress'] ->
  *     no-reply@FirstDomainRecordFound ->
  *     no-reply@php_uname('n') ->
  *     no-reply@example.com
  *
  * Ready to be passed to $mail->setFrom() (t3lib_mail)
  *
  * @return	string	An email address
  */
 public static function getSystemFromAddress()
 {
     // default, first check the localconf setting
     $address = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'];
     if (!t3lib_div::validEmail($address)) {
         // just get us a domain record we can use as the host
         $host = '';
         $domainRecord = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('domainName', 'sys_domain', 'hidden = 0', '', 'pid ASC, sorting ASC');
         if (!empty($domainRecord['domainName'])) {
             $tempUrl = $domainRecord['domainName'];
             if (!t3lib_div::isFirstPartOfStr($tempUrl, 'http')) {
                 // shouldn't be the case anyways, but you never know
                 // ... there're crazy people out there
                 $tempUrl = 'http://' . $tempUrl;
             }
             $host = parse_url($tempUrl, PHP_URL_HOST);
         }
         $address = 'no-reply@' . $host;
         if (!t3lib_div::validEmail($address)) {
             // still nothing, get host name from server
             $address = 'no-reply@' . php_uname('n');
             if (!t3lib_div::validEmail($address)) {
                 // if everything fails use a dummy address
                 $address = '*****@*****.**';
             }
         }
     }
     return $address;
 }
 /**
  * This method checks any additional data that is relevant to the specific task.
  * If the task class is not relevant, the method is expected to return TRUE.
  *
  * @param	array		$submittedData: reference to the array containing the data submitted by the user
  * @param	tx_scheduler_module1		$parentObject: reference to the calling object (BE module of the Scheduler)
  * @return	boolean		True if validation was ok (or selected class is not relevant), FALSE otherwise
  */
 public function validateAdditionalFields(array &$submittedData, tx_scheduler_Module $schedulerModule)
 {
     $isValid = TRUE;
     //!TODO add validation to validate the $submittedData['configuration'] wich is normally a comma seperated string
     if (!empty($submittedData['linkvalidator']['email'])) {
         $emailList = t3lib_div::trimExplode(',', $submittedData['linkvalidator']['email']);
         foreach ($emailList as $emailAdd) {
             if (!t3lib_div::validEmail($emailAdd)) {
                 $isValid = FALSE;
                 $schedulerModule->addMessage($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/locallang.xml:tasks.validate.invalidEmail'), t3lib_FlashMessage::ERROR);
             }
         }
     }
     if ($res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid = ' . $submittedData['linkvalidator']['page'])) {
         if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) == 0 && $submittedData['linkvalidator']['page'] > 0) {
             $isValid = FALSE;
             $schedulerModule->addMessage($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/locallang.xml:tasks.validate.invalidPage'), t3lib_FlashMessage::ERROR);
         }
     } else {
         $isValid = FALSE;
         $schedulerModule->addMessage($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/locallang.xml:tasks.validate.invalidPage'), t3lib_FlashMessage::ERROR);
     }
     if ($submittedData['linkvalidator']['depth'] < 0) {
         $isValid = FALSE;
         $schedulerModule->addMessage($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/locallang.xml:tasks.validate.invalidDepth'), t3lib_FlashMessage::ERROR);
     }
     return $isValid;
 }
 /**
  * Displays an alternative, more advanced / user friendly login form (than the default)
  *
  * @param	string		Default content string, ignore
  * @param	array		TypoScript configuration for the plugin
  * @return	string		HTML for the plugin
  */
 function main($content, $conf)
 {
     // Loading TypoScript array into object variable:
     $this->conf = $conf;
     // Loading language-labels
     $this->pi_loadLL();
     // Init FlexForm configuration for plugin:
     $this->pi_initPIflexForm();
     // Get storage PIDs:
     if ($this->conf['storagePid']) {
         $spid['_STORAGE_PID'] = $this->conf['storagePid'];
     } else {
         $spid = $GLOBALS['TSFE']->getStorageSiterootPids();
     }
     // GPvars:
     $logintype = t3lib_div::GPvar('logintype');
     $redirect_url = t3lib_div::GPvar('redirect_url');
     // Auto redirect.
     // Feature to redirect to the page where the user came from (HTTP_REFERER).
     // Allowed domains to redirect to, can be configured with plugin.tx_newloginbox_pi1.domains
     // Thanks to plan2.net / Martin Kutschker for implementing this feature.
     if (!$redirect_url && $this->conf['domains']) {
         $redirect_url = t3lib_div::getIndpEnv('HTTP_REFERER');
         // is referring url allowed to redirect?
         $match = array();
         if (ereg('^http://([[:alnum:]._-]+)/', $redirect_url, $match)) {
             $redirect_domain = $match[1];
             $found = false;
             foreach (split(',', $this->conf['domains']) as $d) {
                 if (ereg('(^|\\.)' . $d . '$', $redirect_domain)) {
                     $found = true;
                     break;
                 }
             }
             if (!$found) {
                 $redirect_url = '';
             }
         }
         // avoid forced logout, when trying to login immediatly after a logout
         $redirect_url = ereg_replace("[&?]logintype=[a-z]+", "", $redirect_url);
     }
     // Store the entries we will use in the template
     $markerArray = array();
     $subPartArray = array();
     $wrapArray = array();
     // Store entries retrieved by post / get queries
     $workingData = array('forgot_email' => $this->piVars['DATA']['forgot_email'] ? trim($this->piVars['DATA']['forgot_email']) : '');
     if ($this->piVars['forgot']) {
         $markerArray['###STATUS_HEADER###'] = $this->pi_getLL('forgot_password', '', 1);
         if ($workingData['forgot_email'] && t3lib_div::validEmail($workingData['forgot_email'])) {
             $templateMarker = '###TEMPLATE_FORGOT_SENT###';
             $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('username, password', 'fe_users', sprintf('email=\'%s\' and pid=\'%d\' %s', addslashes($workingData['forgot_email']), intval($spid['_STORAGE_PID']), $this->cObj->enableFields('fe_users')));
             if ($GLOBALS['TYPO3_DB']->sql_num_rows($res)) {
                 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                 $msg = sprintf($this->pi_getLL('forgot_password_pswmsg', '', 0), $workingData['forgot_email'], $row['username'], $row['password']);
             } else {
                 $msg = sprintf($this->pi_getLL('forgot_password_no_pswmsg', '', 0), $workingData['forgot_email']);
             }
             // Hook (used by kb_md5fepw extension by Kraft Bernhard <*****@*****.**>)
             if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newloginbox']['forgotEmail'])) {
                 $_params = array('msg' => &$msg);
                 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newloginbox']['forgotEmail'] as $funcRef) {
                     t3lib_div::callUserFunction($funcRef, $_params, $this);
                 }
             }
             $this->cObj->sendNotifyEmail($msg, $workingData['forgot_email'], '', $this->conf['email_from'], $this->conf['email_fromName'], $this->conf['replyTo']);
             $markerArray['###STATUS_MESSAGE###'] = sprintf($this->pi_getLL('forgot_password_emailSent', '', 1), '<em>' . htmlspecialchars($workingData['forgot_email']) . '</em>');
             $markerArray['###FORGOT_PASSWORD_BACKTOLOGIN###'] = $this->pi_linkTP_keepPIvars($this->pi_getLL('forgot_password_backToLogin', '', 1), array('forgot' => ''));
         } else {
             $templateMarker = '###TEMPLATE_FORGOT###';
             $markerArray['###ACTION_URI###'] = htmlspecialchars(t3lib_div::getIndpEnv('REQUEST_URI'));
             $markerArray['###EMAIL_LABEL###'] = $this->pi_getLL('your_email', '', 1);
             $markerArray['###FORGOT_PASSWORD_ENTEREMAIL###'] = $this->pi_getLL('forgot_password_enterEmail', '', 1);
             $markerArray['###PREFIXID###'] = $this->prefixId;
             $markerArray['###SEND_PASSWORD###'] = $this->pi_getLL('send_password', '', 1);
         }
     } else {
         if ($GLOBALS['TSFE']->loginUser) {
             if ($logintype == 'login') {
                 $templateMarker = '###TEMPLATE_SUCCESS###';
                 $outH = $this->getOutputLabel('header_success', 's_success', 'header');
                 $outC = str_replace('###USER###', $GLOBALS['TSFE']->fe_user->user['username'], $this->getOutputLabel('msg_success', 's_success', 'message'));
                 if ($outH) {
                     $markerArray['###STATUS_HEADER###'] = $outH;
                 }
                 if ($outC) {
                     $markerArray['###STATUS_MESSAGE###'] = $outC;
                 }
                 // Hook for general actions after after login has been confirmed (by Thomas Danzl <*****@*****.**>)
                 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newloginbox']['login_confirmed']) {
                     $_params = array();
                     foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newloginbox']['login_confirmed'] as $_funcRef) {
                         if ($_funcRef) {
                             t3lib_div::callUserFunction($_funcRef, $_params, $this);
                         }
                     }
                 }
                 // Hook for dkd_redirect_at_login extension (by Ingmar Schlecht <*****@*****.**>)
                 if ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newloginbox']['dkd_redirect_at_login']) {
                     $_params = array('redirect_url' => $redirect_url);
                     $redirect_url = t3lib_div::callUserFunction($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newloginbox']['dkd_redirect_at_login'], $_params, $this);
                 }
                 if (!$GLOBALS['TSFE']->fe_user->cookieId) {
                     $content .= '<p style="color:red; font-weight:bold;">' . $this->pi_getLL('cookie_warning', '', 1) . '</p>';
                 } elseif ($redirect_url) {
                     header('Location: ' . t3lib_div::locationHeaderUrl($redirect_url));
                     exit;
                 }
             } else {
                 $templateMarker = '###TEMPLATE_LOGOUT###';
                 $outH = $this->getOutputLabel('header_status', 's_status', 'header');
                 $outC = str_replace('###USER###', $GLOBALS['TSFE']->fe_user->user['username'], $this->getOutputLabel('msg_status', 's_status', 'message'));
                 if ($outH) {
                     $markerArray['###STATUS_HEADER###'] = $outH;
                 }
                 if ($outC) {
                     $markerArray['###STATUS_MESSAGE###'] = $outC;
                 }
             }
             if ($this->conf['detailsPage']) {
                 $usernameInfo = $this->pi_linkToPage($usernameInfo, $this->conf['detailsPage'], '', array('tx_newloginbox_pi3[showUid]' => $GLOBALS['TSFE']->fe_user->user['uid'], 'tx_newloginbox_pi3[returnUrl]' => t3lib_div::getIndpEnv('REQUEST_URI')));
                 $wrapArray['###DETAILS_LINK###'] = '<a href="' . $this->pi_linkToPage($this->conf['detailsPage'], '', array('tx_newloginbox_pi3[showUid]' => $GLOBALS['TSFE']->fe_user->user['uid'], 'tx_newloginbox_pi3[returnUrl]' => t3lib_div::getIndpEnv('REQUEST_URI'))) . '">|</a>';
             } else {
                 $wrapArray['###DETAILS_LINK###'] = '|';
             }
             $markerArray['###ACTION_URI###'] = htmlspecialchars($this->pi_getPageLink($GLOBALS['TSFE']->id, '_top'));
             $markerArray['###LOGOUT_LABEL###'] = $this->pi_getLL('logout', '', 1);
             $markerArray['###NAME###'] = $GLOBALS['TSFE']->fe_user->user['name'];
             $markerArray['###STORAGE_PID###'] = intval($spid['_STORAGE_PID']);
             $markerArray['###USERNAME###'] = $GLOBALS['TSFE']->fe_user->user['username'];
             $markerArray['###USERNAME_LABEL###'] = $this->pi_getLL('username', '', 1);
         } else {
             $templateMarker = '###TEMPLATE_LOGIN###';
             if ($logintype == 'login') {
                 $outH = $this->getOutputLabel('header_error', 's_error', 'header');
                 $outC = $this->getOutputLabel('msg_error', 's_error', 'message');
             } elseif ($logintype == 'logout') {
                 $outH = $this->getOutputLabel('header_logout', 's_logout', 'header');
                 $outC = $this->getOutputLabel('msg_logout', 's_logout', 'message');
             } else {
                 // No user currently logged in:
                 $outH = $this->getOutputLabel('header_welcome', 's_welcome', 'header');
                 $outC = $this->getOutputLabel('msg_welcome', 's_welcome', 'message');
             }
             if ($outH) {
                 $markerArray['###STATUS_HEADER###'] = $outH;
             }
             if ($outC) {
                 $markerArray['###STATUS_MESSAGE###'] = $outC;
             }
             // Hook (used by kb_md5fepw extension by Kraft Bernhard <*****@*****.**>)
             // This hook allows to call User JS functions.
             // The methods should also set the required JS functions to get included
             $onSubmit = '';
             $extraHidden = '';
             if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newloginbox']['loginFormOnSubmitFuncs'])) {
                 $_params = array();
                 $onSubmitAr = array();
                 $extraHiddenAr = array();
                 foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['newloginbox']['loginFormOnSubmitFuncs'] as $funcRef) {
                     list($onSub, $hid) = t3lib_div::callUserFunction($funcRef, $_params, $this);
                     $onSubmitAr[] = $onSub;
                     $extraHiddenAr[] = $hid;
                 }
             }
             if (count($onSubmitAr)) {
                 $onSubmit = implode('; ', $onSubmitAr) . '; return true;';
                 $extraHidden = implode(chr(10), $extraHiddenAr);
             }
             // Login form
             $markerArray['###ACTION_URI###'] = htmlspecialchars($this->pi_getPageLink($GLOBALS['TSFE']->id, '_top'));
             $markerArray['###EXTRA_HIDDEN###'] = $extraHidden;
             // used by kb_md5fepw extension...
             $markerArray['###LOGIN_LABEL###'] = $this->pi_getLL('login', '', 1);
             $markerArray['###ON_SUBMIT###'] = $onSubmit;
             // used by kb_md5fepw extension...
             $markerArray['###PASSWORD_LABEL###'] = $this->pi_getLL('password', '', 1);
             $markerArray['###REDIRECT_URL###'] = htmlspecialchars($redirect_url);
             $markerArray['###STORAGE_PID###'] = intval($spid['_STORAGE_PID']);
             $markerArray['###USERNAME_LABEL###'] = $this->pi_getLL('username', '', 1);
             if ($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'show_forgot_password', 'sDEF') || $this->conf['showForgotPassword']) {
                 // $wrapArray['###FORGOTP_LINK###'] = '<a href="' . $this->pi_linkTP_keepPIvars_url(array('forgot'=>1)) . '">|</a>';
                 $markerArray['###FORGOT_PASSWORD###'] = $this->pi_getLL('forgot_password', '', 1);
             }
             if (($this->pi_getFFvalue($this->cObj->data['pi_flexform'], 'show_permalogin', 'sDEF') || $this->conf['showPermaLogin']) && ($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 0 || $GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 1) && $GLOBALS['TYPO3_CONF_VARS']['FE']['lifetime'] > 0) {
                 $markerArray['###PERMALOGIN###'] = $this->pi_getLL('permalogin', '', 1);
                 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['permalogin'] == 1) {
                     $markerArray['###PERMALOGIN_HIDDENFIELD_ATTRIBUTES###'] = 'disabled="disabled"';
                     $markerArray['###PERMALOGIN_CHECKBOX_ATTRIBUTES###'] = 'checked="checked"';
                 } else {
                     $markerArray['###PERMALOGIN_HIDDENFIELD_ATTRIBUTES###'] = '';
                     $markerArray['###PERMALOGIN_CHECKBOX_ATTRIBUTES###'] = '';
                 }
             }
         }
     }
     // Retrieve the template file
     $templateFile = $this->conf['templateFile'];
     if (!$templateFile) {
         $templateFile = 'EXT:newloginbox/res/newloginbox_00.html';
     }
     $templateCode = $this->cObj->fileResource($templateFile);
     $template = $this->cObj->getSubpart($templateCode, $templateMarker);
     // Strip items that aren't needed for this output
     $template = $this->cObj->substituteSubpart($template, '###FORGOTP_VALID###', array_key_exists('###FORGOT_PASSWORD###', $markerArray) ? array('', '') : '', 0);
     $template = $this->cObj->substituteSubpart($template, '###FORGOTP_LINK###', array('<a href="' . htmlspecialchars($this->pi_linkTP_keepPIvars_url(array('forgot' => 1))) . '">', '</a>'), 0);
     $template = $this->cObj->substituteSubpart($template, '###HEADER_VALID###', array_key_exists('###STATUS_HEADER###', $markerArray) ? array('', '') : '', 0);
     $template = $this->cObj->substituteSubpart($template, '###MESSAGE_VALID###', array_key_exists('###STATUS_MESSAGE###', $markerArray) ? array('', '') : '', 0);
     $template = $this->cObj->substituteSubpart($template, '###PERMALOGIN_VALID###', array_key_exists('###PERMALOGIN###', $markerArray) ? array('', '') : '', 0);
     // Replace the remaining markers
     $content = $this->cObj->substituteMarkerArrayCached($template, $markerArray, $subPartArray, array());
     return $this->pi_wrapInBaseClass($content);
 }
    /**
     * Action to create a new BE user
     *
     * @param	array		$record: sys_action record
     * @return	string form to create a new user
     */
    protected function viewNewBackendUser($record)
    {
        $content = '';
        $beRec = t3lib_BEfunc::getRecord('be_users', intval($record['t1_copy_of_user']));
        // a record is neeed which is used as copy for the new user
        if (!is_array($beRec)) {
            $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage', $GLOBALS['LANG']->getLL('action_notReady', TRUE), $GLOBALS['LANG']->getLL('action_error'), t3lib_FlashMessage::ERROR);
            $content .= $flashMessage->render();
            return $content;
        }
        $vars = t3lib_div::_POST('data');
        $key = 'NEW';
        if ($vars['sent'] == 1) {
            $errors = array();
            // basic error checks
            if (!empty($vars['email']) && !t3lib_div::validEmail($vars['email'])) {
                $errors[] = $GLOBALS['LANG']->getLL('error-wrong-email');
            }
            if (empty($vars['username'])) {
                $errors[] = $GLOBALS['LANG']->getLL('error-username-empty');
            }
            if (empty($vars['password'])) {
                $errors[] = $GLOBALS['LANG']->getLL('error-password-empty');
            }
            if ($vars['key'] !== 'NEW' && !$this->isCreatedByUser($vars['key'], $record)) {
                $errors[] = $GLOBALS['LANG']->getLL('error-wrong-user');
            }
            // show errors if there are any
            if (count($errors) > 0) {
                $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage', implode('<br />', $errors), $GLOBALS['LANG']->getLL('action_error'), t3lib_FlashMessage::ERROR);
                $content .= $flashMessage->render() . '<br />';
            } else {
                // save user
                $key = $this->saveNewBackendUser($record, $vars);
                // success messsage
                $flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage', $vars['key'] === 'NEW' ? $GLOBALS['LANG']->getLL('success-user-created') : $GLOBALS['LANG']->getLL('success-user-updated'), $GLOBALS['LANG']->getLL('success'), t3lib_FlashMessage::OK);
                $content .= $flashMessage->render() . '<br />';
            }
        }
        // load BE user to edit
        if (intval(t3lib_div::_GP('be_users_uid')) > 0) {
            $tmpUserId = intval(t3lib_div::_GP('be_users_uid'));
            // check if the selected user is created by the current user
            $rawRecord = $this->isCreatedByUser($tmpUserId, $record);
            if ($rawRecord) {
                // delete user
                if (t3lib_div::_GP('delete') == 1) {
                    $this->deleteUser($tmpUserId, $record['uid']);
                }
                $key = $tmpUserId;
                $vars = $rawRecord;
            }
        }
        $this->JScode();
        $loadDB = t3lib_div::makeInstance('t3lib_loadDBGroup');
        $loadDB->start($vars['db_mountpoints'], 'pages');
        $content .= '<form action="" method="post" enctype="multipart/form-data">
						<fieldset class="fields">
							<legend>General fields</legend>
							<div class="row">
								<label for="field_disable">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_general.xml:LGL.disable') . '</label>
								<input type="checkbox" id="field_disable" name="data[disable]" value="1" class="checkbox" ' . ($vars['disable'] == 1 ? ' checked="checked" ' : '') . ' />
							</div>
							<div class="row">
								<label for="field_realname">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_general.xml:LGL.name') . '</label>
								<input type="text" id="field_realname" name="data[realName]" value="' . htmlspecialchars($vars['realName']) . '" />
							</div>
							<div class="row">
								<label for="field_username">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tca.xml:be_users.username') . '</label>
								<input type="text" id="field_username" name="data[username]" value="' . htmlspecialchars($vars['username']) . '" />
							</div>
							<div class="row">
								<label for="field_password">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tca.xml:be_users.password') . '</label>
								<input type="password" id="field_password" name="data[password]" value="" />
							</div>
							<div class="row">
								<label for="field_email">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_general.xml:LGL.email') . '</label>
								<input type="text" id="field_email" name="data[email]" value="' . htmlspecialchars($vars['email']) . '" />
							</div>
						</fieldset>
						<fieldset class="fields">
							<legend>Configuration</legend>

							<div class="row">
								<label for="field_usergroup">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tca.xml:be_users.usergroup') . '</label>
								<select id="field_usergroup" name="data[usergroup][]" multiple="multiple">
									' . $this->getUsergroups($record, $vars) . '
								</select>
							</div>
							<div class="row">
								<label for="field_db_mountpoints">' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_tca.xml:be_users.options_db_mounts') . '</label>
								' . $this->t3lib_TCEforms->dbFileIcons('data[db_mountpoints]', 'db', 'pages', $loadDB->itemArray, '', array('size' => 3)) . '
							</div>
							<div class="row">
								<input type="hidden" name="data[key]" value="' . $key . '" />
								<input type="hidden" name="data[sent]" value="1" />
								<input type="submit" value="' . ($key === 'NEW' ? $GLOBALS['LANG']->getLL('action_Create') : $GLOBALS['LANG']->getLL('action_Update')) . '" />
							</div>
						</fieldset>
					</form>';
        $content .= $this->getCreatedUsers($record, $key);
        return $content;
    }
 function _isEmail($mValue)
 {
     return trim($mValue) == "" || t3lib_div::validEmail($mValue);
 }
示例#17
0
 /**
  * Search for the given address in one of the geocoding services and update
  * its data.
  *
  * Data lat, lon, zip and city may get updated.
  *
  * @param array   &$address Address record from database
  * @param integer $service  Geocoding service to use
  *						  - 0: internal caching database table
  *						  - 1: geonames.org
  *						  - 2: nominatim.openstreetmap.org
  *
  * @return boolean True if the address got updated, false if not.
  */
 function searchAddress(&$address, $service = 0)
 {
     $config = tx_odsosm_div::getConfig(array('default_country', 'geo_service_email', 'geo_service_user'));
     $ll = false;
     $country = strtoupper(strlen($address['country']) == 2 ? $address['country'] : $config['default_country']);
     $email = t3lib_div::validEmail($config['geo_service_email']) ? $config['geo_service_email'] : $_SERVER['SERVER_ADMIN'];
     if (TYPO3_DLOG) {
         $service_names = array(0 => 'cache', 1 => 'geonames', 2 => 'nominatim');
         t3lib_div::devLog('Search address using ' . $service_names[$service], 'ods_osm', 0, $address);
     }
     switch ($service) {
         case 0:
             // cache
             $where = array();
             if ($country) {
                 $where[] = 'country=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($country, 'tx_odsosm_geocache');
             }
             if ($address['city']) {
                 $where[] = '(city=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($address['city'], 'tx_odsosm_geocache') . ' OR search_city=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($address['city'], 'tx_odsosm_geocache') . ')';
             }
             if ($address['zip']) {
                 $where[] = 'zip=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($address['zip'], 'tx_odsosm_geocache');
             }
             if ($address['street']) {
                 $where[] = 'street=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($address['street'], 'tx_odsosm_geocache');
             }
             if ($address['housenumber']) {
                 $where[] = 'housenumber=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($address['housenumber'], 'tx_odsosm_geocache');
             }
             if ($where) {
                 $where[] = 'deleted=0';
                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'tx_odsosm_geocache', implode(' AND ', $where));
                 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
                 if ($row) {
                     $ll = true;
                     $set = array('tstamp' => time(), 'cache_hit' => $row['cache_hit'] + 1);
                     $GLOBALS['TYPO3_DB']->exec_UPDATEquery('tx_odsosm_geocache', 'uid=' . $row['uid'], $set);
                     $address['lat'] = $row['lat'];
                     $address['lon'] = $row['lon'];
                     if ($row['zip']) {
                         $address['zip'] = $row['zip'];
                     }
                     if ($row['city']) {
                         $address['city'] = $row['city'];
                     }
                     if ($row['state']) {
                         $address['state'] = $row['state'];
                     }
                     if (empty($address['country'])) {
                         $address['country'] = $row['country'];
                     }
                 }
             }
             break;
         case 1:
             // http://www.geonames.org/
             if ($country) {
                 $query['country'] = $country;
             }
             if ($address['city']) {
                 $query['placename'] = $address['city'];
             }
             if ($address['zip']) {
                 $query['postalcode'] = $address['zip'];
             }
             if ($query) {
                 $query['maxRows'] = 1;
                 $query['username'] = $config['geo_service_user'];
                 $xml = t3lib_div::getURL('http://api.geonames.org/postalCodeSearch?' . http_build_query($query, '', '&'), false, 'User-Agent: TYPO3 extension ods_osm/' . t3lib_extMgm::getExtensionVersion('ods_osm'));
                 if (TYPO3_DLOG && $xml === false) {
                     t3lib_div::devLog('t3lib_div::getURL failed', "ods_osm", 3);
                 }
                 if ($xml) {
                     $xmlobj = new SimpleXMLElement($xml);
                     if ($xmlobj->status) {
                         if (TYPO3_DLOG) {
                             t3lib_div::devLog('GeoNames message', 'ods_osm', 2, (array) $xmlobj->status->attributes());
                         }
                         $o_flashMessage = t3lib_div::makeInstance('t3lib_FlashMessage', (string) $xmlobj->status->attributes()->message, 'GeoNames message', t3lib_FlashMessage::WARNING);
                         t3lib_FlashMessageQueue::addMessage($o_flashMessage);
                     }
                     if ($xmlobj->code) {
                         $ll = true;
                         $address['lat'] = (string) $xmlobj->code->lat;
                         $address['lon'] = (string) $xmlobj->code->lng;
                         if ($xmlobj->code->postalcode) {
                             $address['zip'] = (string) $xmlobj->code->postalcode;
                         }
                         if ($xmlobj->code->name) {
                             $address['city'] = (string) $xmlobj->code->name;
                         }
                         if (empty($address['country'])) {
                             $address['country'] = (string) $xmlobj->code->countryCode;
                         }
                     }
                 }
             }
             break;
         case 2:
             // http://nominatim.openstreetmap.org/
             $query['country'] = $country;
             $query['email'] = $email;
             $query['addressdetails'] = 1;
             $query['format'] = 'xml';
             if ($this->address_type == 'structured') {
                 if ($address['city']) {
                     $query['city'] = $address['city'];
                 }
                 if ($address['zip']) {
                     $query['postalcode'] = $address['zip'];
                 }
                 if ($address['street']) {
                     $query['street'] = $address['street'];
                 }
                 if ($address['housenumber']) {
                     $query['street'] = $address['housenumber'] . ' ' . $query['street'];
                 }
                 if (TYPO3_DLOG) {
                     t3lib_div::devLog('Nominatim structured', 'ods_osm', -1, $query);
                 }
                 $ll = tx_odsosm_div::searchAddressNominatim($query, $address);
                 if (!$ll && $query['postalcode']) {
                     unset($query['postalcode']);
                     if (TYPO3_DLOG) {
                         t3lib_div::devLog('Nominatim retrying without zip', 'ods_osm', -1, $query);
                     }
                     $ll = tx_odsosm_div::searchAddressNominatim($query, $address);
                 }
             }
             if ($this->address_type == 'unstructured') {
                 $query['q'] = $address['address'];
                 if (TYPO3_DLOG) {
                     t3lib_div::devLog('Nominatim unstructured', 'ods_osm', -1, $query);
                 }
                 $ll = tx_odsosm_div::searchAddressNominatim($query, $address);
             }
             break;
     }
     if (TYPO3_DLOG) {
         if ($ll) {
             t3lib_div::devLog('Return address', 'ods_osm', 0, $address);
         } else {
             t3lib_div::devLog('No address found', 'ods_osm', 0);
         }
     }
     return $ll;
 }
示例#18
0
 /**
  * Validates the e-mail addresses of additional persons for non-emptiness and validity.
  *
  * If the entering of additional persons as FE user records is disabled, this function will always return TRUE.
  *
  * @return bool
  *         TRUE if either additional persons as FE users are disabled or all entered e-mail addresses are non-empty and valid,
  *         FALSE otherwise
  */
 public function validateAdditionalPersonsEMailAddresses()
 {
     if (!$this->isFormFieldEnabled('attendees_names')) {
         return TRUE;
     }
     if (!$this->getConfValueBoolean('createAdditionalAttendeesAsFrontEndUsers', 's_registration')) {
         return TRUE;
     }
     $isValid = TRUE;
     $allPersonsData = $this->getAdditionalRegisteredPersonsData();
     foreach ($allPersonsData as $onePersonData) {
         if (!isset($onePersonData[3]) || !t3lib_div::validEmail($onePersonData[3])) {
             $isValid = FALSE;
             break;
         }
     }
     return $isValid;
 }
 /**
  * Extracts name/email parts from a header field (like 'To:' or 'From:' with name/email mixed up.
  *
  * @param	string		Value from a header field containing name/email values.
  * @return	array		Array with the name and email in. Email is validated, otherwise not set.
  */
 function extractNameEmail($str)
 {
     $outArr = array();
     // Email:
     $reg = '';
     preg_match('/<([^>]*)>/', $str, $reg);
     if (t3lib_div::validEmail($str)) {
         $outArr['email'] = $str;
     } elseif ($reg[1] && t3lib_div::validEmail($reg[1])) {
         $outArr['email'] = $reg[1];
         // Find name:
         list($namePart) = explode($reg[0], $str);
         if (trim($namePart)) {
             $reg = '';
             preg_match('/"([^"]*)"/', $str, $reg);
             if (trim($reg[1])) {
                 $outArr['name'] = trim($reg[1]);
             } else {
                 $outArr['name'] = trim($namePart);
             }
         }
     }
     return $outArr;
 }
 /**
  * Creates the URL, target and onclick values for the menu item link. Returns them in an array as key/value pairs for <A>-tag attributes
  * This function doesn't care about the url, because if we let the url be redirected, it will be logged in the stat!!!
  *
  * @param	integer		Pointer to a key in the $this->menuArr array where the value for that key represents the menu item we are linking to (page record)
  * @param	string		Alternative target
  * @param	integer		Alternative type
  * @return	array		Returns an array with A-tag attributes as key/value pairs (HREF, TARGET and onClick)
  * @access private
  */
 function link($key, $altTarget = '', $typeOverride = '')
 {
     // Mount points:
     $MP_var = $this->getMPvar($key);
     $MP_params = $MP_var ? '&MP=' . rawurlencode($MP_var) : '';
     // Setting override ID
     if ($this->mconf['overrideId'] || $this->menuArr[$key]['overrideId']) {
         $overrideArray = array();
         // If a user script returned the value overrideId in the menu array we use that as page id
         $overrideArray['uid'] = $this->mconf['overrideId'] ? $this->mconf['overrideId'] : $this->menuArr[$key]['overrideId'];
         $overrideArray['alias'] = '';
         $MP_params = '';
         // clear MP parameters since ID was changed.
     } else {
         $overrideArray = '';
     }
     // Setting main target:
     $mainTarget = $altTarget ? $altTarget : $this->mconf['target'];
     // Creating link:
     if ($this->mconf['collapse'] && $this->isActive($this->menuArr[$key]['uid'], $this->getMPvar($key))) {
         $thePage = $this->sys_page->getPage($this->menuArr[$key]['pid']);
         $LD = $this->menuTypoLink($thePage, $mainTarget, '', '', $overrideArray, $this->mconf['addParams'] . $MP_params . $this->menuArr[$key]['_ADD_GETVARS'], $typeOverride);
     } else {
         $LD = $this->menuTypoLink($this->menuArr[$key], $mainTarget, '', '', $overrideArray, $this->mconf['addParams'] . $MP_params . $this->I['val']['additionalParams'] . $this->menuArr[$key]['_ADD_GETVARS'], $typeOverride);
     }
     // Override URL if using "External URL" as doktype with a valid e-mail address:
     if ($this->menuArr[$key]['doktype'] == 3 && $this->menuArr[$key]['urltype'] == 3 && t3lib_div::validEmail($this->menuArr[$key]['url'])) {
         // Create mailto-link using tslib_cObj::typolink (concerning spamProtectEmailAddresses):
         $LD['totalURL'] = $this->parent_cObj->typoLink_URL(array('parameter' => $this->menuArr[$key]['url']));
         $LD['target'] = '';
     }
     // Manipulation in case of access restricted pages:
     $this->changeLinksForAccessRestrictedPages($LD, $this->menuArr[$key], $mainTarget, $typeOverride);
     // Overriding URL / Target if set to do so:
     if ($this->menuArr[$key]['_OVERRIDE_HREF']) {
         $LD['totalURL'] = $this->menuArr[$key]['_OVERRIDE_HREF'];
         if ($this->menuArr[$key]['_OVERRIDE_TARGET']) {
             $LD['target'] = $this->menuArr[$key]['_OVERRIDE_TARGET'];
         }
     }
     // OnClick open in windows.
     $onClick = '';
     if ($this->mconf['JSWindow']) {
         $conf = $this->mconf['JSWindow.'];
         $url = $LD['totalURL'];
         $LD['totalURL'] = '#';
         $onClick = 'openPic(\'' . $GLOBALS['TSFE']->baseUrlWrap($url) . '\',\'' . ($conf['newWindow'] ? md5($url) : 'theNewPage') . '\',\'' . $conf['params'] . '\'); return false;';
         $GLOBALS['TSFE']->setJS('openPic');
     }
     // look for type and popup
     // following settings are valid in field target:
     // 230								will add type=230 to the link
     // 230 500x600						will add type=230 to the link and open in popup window with 500x600 pixels
     // 230 _blank						will add type=230 to the link and open with target "_blank"
     // 230x450:resizable=0,location=1	will open in popup window with 500x600 pixels with settings "resizable=0,location=1"
     $matches = array();
     $targetIsType = $LD['target'] && (string) intval($LD['target']) == trim($LD['target']) ? intval($LD['target']) : FALSE;
     if (preg_match('/([0-9]+[\\s])?(([0-9]+)x([0-9]+))?(:.+)?/s', $LD['target'], $matches) || $targetIsType) {
         // has type?
         if (intval($matches[1]) || $targetIsType) {
             $LD['totalURL'] .= '&type=' . ($targetIsType ? $targetIsType : intval($matches[1]));
             $LD['target'] = $targetIsType ? '' : trim(substr($LD['target'], strlen($matches[1]) + 1));
         }
         // open in popup window?
         if ($matches[3] && $matches[4]) {
             $JSparamWH = 'width=' . $matches[3] . ',height=' . $matches[4] . ($matches[5] ? ',' . substr($matches[5], 1) : '');
             $onClick = 'vHWin=window.open(\'' . $LD['totalURL'] . '\',\'FEopenLink\',\'' . $JSparamWH . '\');vHWin.focus();return false;';
             $LD['target'] = '';
         }
     }
     // out:
     $list = array();
     $list['HREF'] = strlen($LD['totalURL']) ? $LD['totalURL'] : $GLOBALS['TSFE']->baseUrl;
     // Added this check: What it does is to enter the baseUrl (if set, which it should for "realurl" based sites) as URL if the calculated value is empty. The problem is that no link is generated with a blank URL and blank URLs might appear when the realurl encoding is used and a link to the frontpage is generated.
     $list['TARGET'] = $LD['target'];
     $list['onClick'] = $onClick;
     return $list;
 }
 /**
  * Create HTML for info box from template and tt_address item
  *
  * @param	array	Array containing a tt_address item
  * @return	string	Processed template for sidebar
  */
 function createInfoBox($lRow)
 {
     $sContent = '';
     // Fill marker array
     $lMarkerArray = array();
     // Field: name
     $lMarkerArray['###INFOBOX_NAME###'] = $lRow['name'];
     // Field: title
     $lMarkerArray['###INFOBOX_TITLE###'] = $lRow['title'];
     // Field: company
     $lMarkerArray['###INFOBOX_COMPANY###'] = $lRow['company'];
     // Field: address
     $sAddress = $lRow['address'];
     $sAddress = str_replace("\r", '', $sAddress);
     $sAddress = str_replace("\n", '<br />', $sAddress);
     $lMarkerArray['###INFOBOX_ADDRESS###'] = $sAddress;
     // Field: zip
     $lMarkerArray['###INFOBOX_ZIP###'] = $lRow['zip'];
     // Field: city
     $lMarkerArray['###INFOBOX_CITY###'] = $lRow['city'];
     // Field: country
     $lMarkerArray['###INFOBOX_COUNTRY###'] = $lRow['country'];
     // Field: email
     $sEmail = $lRow['email'];
     if (t3lib_div::validEmail($sEmail)) {
         $sEmail = $this->cObj->getTypoLink($sEmail, $sEmail);
     }
     $lMarkerArray['###INFOBOX_EMAIL###'] = $sEmail;
     // Field: www
     $sWWW = $this->cObj->getTypoLink($lRow['www'], $lRow['www'], array(), '_blank');
     $lMarkerArray['###INFOBOX_WWW###'] = $sWWW;
     // Field: phone
     $lMarkerArray['###INFOBOX_PHONE###'] = $lRow['phone'];
     // Field: mobile
     $lMarkerArray['###INFOBOX_MOBILE###'] = $lRow['mobile'];
     // Field: fax
     $lMarkerArray['###INFOBOX_FAX###'] = $lRow['fax'];
     // Field: image
     $lMarkerArray['###INFOBOX_IMAGE###'] = $this->createImage('uploads/pics/' . $lRow['image']);
     // Field: description
     $lMarkerArray['###INFOBOX_DESCRIPTION###'] = $this->cObj->parseFunc($lRow['description'], $GLOBALS['TSFE']->tmpl->setup['lib.']['parseFunc_RTE.']);
     // Field: tx_lumogooglemaps_longitude
     $lMarkerArray['###INFOBOX_LONGITUDE###'] = $lRow['tx_lumogooglemaps_longitude'];
     // Field: tx_lumogooglemaps_latitude
     $lMarkerArray['###INFOBOX_LATITUDE###'] = $lRow['tx_lumogooglemaps_latitude'];
     // Replace marker in template
     $sContent = $this->cObj->substituteMarkerArrayCached($this->lTemplateParts['infobox'], $lMarkerArray, array(), array());
     // Remove newlines (as infobox HTML is used in JavaScript)
     $sContent = str_replace("\r", '', $sContent);
     $sContent = str_replace("\n", '', $sContent);
     return $sContent;
 }
   /**
    * Main method of your PlugIn
    *
    * @param    string    $content: The content of the PlugIn
    * @param    array    $conf: The PlugIn Configuration
    * @return    string    The content that should be displayed on the website
    */
   function main($content, $conf)
   {
       $this->conf = $conf;
       $this->pi_setPiVarDefaults();
       $this->pi_initPIflexForm();
       // Init FlexForm configuration for plugin
       $this->pi_loadLL();
       $this->pi_USER_INT_obj = 1;
       // Configuring so caching is not expected. This value means that no cHash params are ever set. We do this, because it's a USER_INT object!
       $thePID = 0;
       // PID of the sysfolder with questions
       $resPID = 0;
       // PID of the sysfolder with results
       $nextPID = 0;
       // PID for forms
       $finalPID = 0;
       // PID for the final page
       $listPID = 0;
       // PID for highscore or poll result
       $startPID = 0;
       // PID of the startpage
       $uid = 0;
       // quiz taker UID?!
       //$firsttime = 0;            // start time of the quiz
       $elapseTime = 0;
       // intval($this->conf['quizTimeMinutes'])*60;            // Verflossene Zeit in Sekunden
       $joker1 = 0;
       // Joker used?
       $joker2 = 0;
       $joker3 = 0;
       $startPage = false;
       // start page which asks only for user data?
       $questionPage = false;
       // question page?
       $answerPage = false;
       // answer page?
       $finalPage = false;
       // final page reached?
       $noQuestions = false;
       // no more questions?
       $secondVisit = false;
       // quiz already solved?
       $sendMail = false;
       // email should be send?
       $error = false;
       // was there an error?
       $nextCat = '';
       // global next category
       $catArray = array();
       // array with category names
       $oldLoaded = false;
       // old data loaded
       // global $TSFE;
       $this->lang = intval($GLOBALS['TSFE']->config['config']['sys_language_uid']);
       $this->copyFlex();
       // copy Felxform-Variables to this->conf
       $this->tableAnswers = $this->conf['tableAnswers'] == 'tx_myquizpoll_voting' ? 'tx_myquizpoll_voting' : 'tx_myquizpoll_result';
       if ($this->conf['enableCaptcha'] && t3lib_extMgm::isLoaded('sr_freecap')) {
           // load Captcha: Anti-Spam-Tool ??? only if enabled (16.10.2009)
           require_once t3lib_extMgm::extPath('sr_freecap') . 'pi2/class.tx_srfreecap_pi2.php';
           $this->freeCap = t3lib_div::makeInstance('tx_srfreecap_pi2');
       }
       // TODO: Rekursiv-Flag berücksichtigen!
       if (!($this->cObj->data['pages'] == '')) {
           // PID (eine oder mehrere)
           $thePID = $this->cObj->data['pages'];
       } elseif (!($this->conf['sysPID'] == '')) {
           $thePID = preg_replace('/[^0-9,]/', '', $this->conf['sysPID']);
       } else {
           $thePID = $GLOBALS["TSFE"]->id;
       }
       $resPID = $this->conf['resultsPID'] ? intval($this->conf['resultsPID']) : $thePID;
       $resPIDs = preg_replace('/[^0-9,]/', '', $resPID);
       // für den Highscore werden ggf. alle PIDs gebraucht
       if (strstr($resPID, ',')) {
           // wenn mehrere Ordner ausgewählt, nimm den ersten
           $tmp = explode(",", $resPID);
           $resPID = intval(trim($tmp[0]));
       }
       $nextPID = $this->conf['nextPID'] ? intval($this->conf['nextPID']) : $GLOBALS['TSFE']->id;
       $finalPID = $this->conf['finalPID'] ? intval($this->conf['finalPID']) : $GLOBALS['TSFE']->id;
       // oder $nextPID;
       $listPID = $this->conf['listPID'] ? intval($this->conf['listPID']) : $GLOBALS['TSFE']->id;
       // oder $finalPID;
       $startPID = intval($this->conf['startPID']);
       if ($this->conf['answerChoiceMax']) {
           // antworten pro fragen
           $this->answerChoiceMax = intval($this->conf['answerChoiceMax']);
       }
       if (!$this->conf['myVars.']['separator']) {
           // separator bei den myVars
           $this->conf['myVars.']['separator'] = ',';
       }
       mt_srand(hexdec(substr(md5(microtime()), -8)) & 0x7fffffff);
       // Seed random number generator
       //$this->local_cObj = t3lib_div::makeInstance("tslib_cObj");    // Local cObj
       // Get post parameters: Submited Quiz-data
       if ($this->conf['CMD'] == 'archive') {
           $this->conf['ignoreSubmit'] = true;
       }
       // submits in diesen Fällen igonieren
       $quizData = array();
       if (is_array(t3lib_div::_GP($this->prefixId)) && !$this->conf['ignoreSubmit']) {
           if (is_array(t3lib_div::_POST($this->prefixId))) {
               $quizData = t3lib_div::_POST($this->prefixId);
           } else {
               $quizData = t3lib_div::_GET($this->prefixId);
           }
           //$quizData = t3lib_div::slashArray(t3lib_div::GPvar($this->prefixId),"strip"); // deprecated
           if ($quizData['cmd'] == '') {
               $quizData['cmd'] = $this->conf['CMD'];
           } elseif ($quizData['cmd'] == 'allanswers') {
               // or $quizData['cmd']=='score' or $quizData['cmd']=='list'
               $quizData['cmd'] = '';
               // for security reasons we want that users can´t see everything
           }
       } else {
           $quizData['cmd'] = $this->conf['CMD'];
           // get the CMD from the backend
       }
       if ($quizData["name"]) {
           $quizData["name"] = htmlspecialchars($quizData["name"]);
       }
       if ($quizData["email"]) {
           $quizData["email"] = htmlspecialchars($quizData["email"]);
       }
       if ($quizData["homepage"]) {
           $quizData["homepage"] = htmlspecialchars($quizData["homepage"]);
       }
       // Zurück navigieren?
       $back = intval($quizData["back"]);
       $back_hit = intval($quizData["back-hit"]);
       if ($back_hit) {
           $quizData['cmd'] = '';
       }
       $seite = 0;
       if ($this->tableAnswers == 'tx_myquizpoll_voting') {
           $this->conf['allowBack'] = 0;
       }
       // Load template
       $tempPath = $this->initTemplate();
       // Marker values
       $statisticsArray = array();
       $markerArray = array();
       $subpartArray = array();
       $wrappedSubpartArray = array();
       $markerArrayP = array();
       $markerArrayQ = array();
       $markerArrayP["###REF_HIGHSCORE###"] = '';
       $markerArrayP["###REF_HIGHSCORE_URL###"] = '';
       $markerArrayP["###REF_POLLRESULT_URL###"] = '';
       $markerArrayP["###REF_QUIZ_ANALYSIS###"] = '';
       $markerArrayP["###REF_NO_MORE###"] = '';
       $markerArrayP["###REF_ERRORS###"] = '';
       $markerArrayP["###REF_RES_ERRORS###"] = '';
       $markerArrayP["###REF_JOKERS###"] = '';
       $markerArrayP["###REF_QUESTIONS###"] = '';
       $markerArrayP["###REF_QRESULT###"] = '';
       $markerArrayP["###REF_INTRODUCTION###"] = '';
       $markerArrayP["###REF_QPOINTS###"] = '';
       $markerArrayP["###REF_SKIPPED###"] = '';
       $markerArrayP["###REF_NEXT###"] = '';
       $markerArrayP["###REF_POLLRESULT###"] = '';
       $markerArrayP["###SUBMIT_JSC###"] = '';
       $markerArrayP["###PREFIX###"] = $this->prefixId;
       $markerArrayP["###FORM_URL###"] = $this->pi_getPageLink($nextPID);
       $markerArrayP["###NO_NEGATIVE###"] = intval($this->conf['noNegativePoints']);
       $markerArrayP["###REMOTE_IP###"] = intval($this->conf['remoteIP']);
       $markerArrayP["###BLOCK_IP###"] = $this->conf['blockIP'];
       $markerArrayQ["###PREFIX###"] = $this->prefixId;
       $markerArray["###PREFIX###"] = $this->prefixId;
       $markerArray["###FORM_URL###"] = $markerArrayP["###FORM_URL###"];
       $markerArrayP["###VAR_RESPID###"] = $resPID;
       $markerArrayP["###VAR_LANG###"] = $this->lang;
       $markerArrayP["###VAR_NOW###"] = $markerArray["###VAR_NOW###"] = time() + 1;
       // kleiner Zeitvorsprung (Seite muss ja geladen werden)
       $markerArray["###NAME###"] = $this->pi_getLL('name', 'name');
       $markerArray["###EMAIL###"] = $this->pi_getLL('email', 'email');
       $markerArray["###HOMEPAGE###"] = $this->pi_getLL('homepage', 'homepage');
       $markerArray["###GO_ON###"] = $this->pi_getLL('go_on', 'go_on');
       $markerArray["###SUBMIT###"] = $this->pi_getLL('submit', 'submit');
       $markerArray["###RESET###"] = $this->pi_getLL('reset', 'reset');
       $markerArray["###GO_BACK###"] = $this->pi_getLL('back', 'back');
       $markerArray["###CORRECT_ANSWERS###"] = $this->pi_getLL('correct_answers', 'correct_answers');
       $markerArray["###EXPLANATION###"] = $this->pi_getLL('listFieldHeader_explanation', 'listFieldHeader_explanation');
       //$markerArray["###VAR_ADDRESS_UID###"] = $quizData["address_uid"] = 0;
       $markerArray["###VAR_CATEGORY###"] = '';
       $markerArray["###VAR_NEXT_CATEGORY###"] = '';
       $markerArray["###VAR_TOTAL_POINTS###"] = '';
       $markerArray["###VAR_QUESTIONS_CORRECT###"] = '';
       $markerArray["###VAR_QUESTIONS_FALSE###"] = '';
       $markerArray["###VAR_QUESTIONS_ANSWERED###"] = 0;
       //if ($this->conf['enforceSelection']) {
       $markerArrayP["###QUESTION###"] = $this->pi_getLL('listFieldHeader_name', 'listFieldHeader_name');
       $markerArrayP["###MISSING_ANSWER###"] = $this->pi_getLL('missing_answer', 'missing_answer');
       //}
       if ($this->conf['pageTimeSeconds'] || $this->conf['quizTimeMinutes']) {
           $markerArray["###TIME_UP1###"] = $this->pi_getLL('time_up1', 'time_up1');
           $markerArray["###LIMIT1A###"] = $this->pi_getLL('limit1a', 'limit1a');
           $markerArray["###LIMIT1B###"] = $this->pi_getLL('limit1b', 'limit1b');
           $markerArray["###TIME_UP2###"] = $this->pi_getLL('time_up2', 'time_up2');
           $markerArray["###LIMIT2A###"] = $this->pi_getLL('limit2a', 'limit2a');
           $markerArray["###LIMIT2B###"] = $this->pi_getLL('limit2b', 'limit2b');
           $markerArray["###SECONDS###"] = $this->pi_getLL('seconds', 'seconds');
           $markerArray["###MINUTES###"] = $this->pi_getLL('minutes', 'minutes');
       }
       // Link to the Highscore list
       $urlParameters = array("tx_myquizpoll_pi1[cmd]" => "score", "tx_myquizpoll_pi1[qtuid]" => intval($quizData['qtuid']), "no_cache" => "1");
       $markerArray["###HIGHSCORE_URL###"] = $this->pi_linkToPage($this->pi_getLL('highscore_url', 'highscore_url'), $listPID, $target = '', $urlParameters);
       // Jokers and Details
       if ($this->conf['useJokers'] && $this->conf['pageQuestions'] == 1 || $this->conf['showDetailAnswers']) {
           /*
            *  Instantiate the xajax object and configure it
            */
           require_once t3lib_extMgm::extPath('xajax') . 'class.tx_xajax.php';
           // Include xaJax
           $this->xajax = t3lib_div::makeInstance('tx_xajax');
           // Make the instance
           # $this->xajax->setRequestURI('xxx');         // nothing to set, we send to the same URI
           # $this->xajax->decodeUTF8InputOn(); // Decode form vars from utf8 ???
           # $this->xajax->setCharEncoding('utf-8'); // Encode of the response to utf-8 ???
           $this->xajax->setWrapperPrefix($this->prefixId);
           // To prevent conflicts, prepend the extension prefix
           $this->xajax->statusMessagesOff();
           // messages in the status bar?
           $this->xajax->debugOff();
           // Turn only on during testing
           if ($this->conf['useJokers']) {
               $this->xajax->registerFunction(array('getAjaxData', &$this, 'getAjaxData'));
           }
           // Register the names of the PHP functions you want to be able to call through xajax - $xajax->registerFunction(array('functionNameInJavascript', &$object, 'methodName'));
           if ($this->conf['showDetailAnswers']) {
               $this->xajax->registerFunction(array('getAjaxDetails', &$this, 'getAjaxDetails'));
           }
           $this->xajax->processRequests();
           // If this is an xajax request, call our registered function, send output and exit
           $GLOBALS['TSFE']->additionalHeaderData[$this->prefixId . '_2'] = $this->xajax->getJavascript(t3lib_extMgm::siteRelPath('xajax'));
           // Else create javascript and add it to the header output
           $markerArrayJ = array();
           $markerArrayJ["###PREFIX###"] = $this->prefixId;
           $markerArrayJ["###USE_JOKERS###"] = $this->pi_getLL('use_jokers', 'use_jokers');
           $markerArrayJ["###ANSWER_JOKER###"] = $this->pi_getLL('answer_joker', 'answer_joker');
       }
       // Init
       $no_rights = 0;
       // second entry of the quiz taker or not logged in if requiered?
       $captchaError = false;
       // wrong Captcha?
       //        $leftQuestions = 0;        // no. of questions to be shown
       $whereAnswered = '';
       // questions that have been allready answered (UIDs)
       $whereSkipped = '';
       // questions that have been skipped (UIDs)
       $content = '';
       // content to be shown
       $this->helperObj = t3lib_div::makeInstance('tx_myquizpoll_helper', $thePID, $this->lang, $this->answerChoiceMax, $this->tableQuestions, $this->tableAnswers, $this->tableRelation, $this->conf);
       // enable dev logging if set
       if (TYPO3_DLOG || $this->conf['debug']) {
           $this->helperObj->writeDevLog = TRUE;
           t3lib_div::devLog('UID: ' . $this->cObj->data['uid'] . '; language: ' . $this->lang . '; use cookies: ' . $this->conf['useCookiesInDays'] . '; use ip-check: ' . $this->conf['doubleEntryCheck'] . '; path to template: ' . $tempPath, $this->extKey, 0);
       }
       // set some session-variables
       if (!$this->conf['isPoll'] && $quizData['cmd'] == '' && !$quizData['qtuid']) {
           $this->helperObj->setQuestionsVars();
       }
       // what to display?
       switch ($quizData['cmd']) {
           case 'archive':
               if ($this->conf['isPoll']) {
                   /* Display only a list of old polls	*/
                   return $this->pi_wrapInBaseClass($this->showPollArchive($listPID, $thePID, $resPID));
               }
           case 'list':
               if (is_numeric($quizData['qid'])) {
                   /* Display an old poll	*/
                   return $this->pi_wrapInBaseClass($this->showPollResult('', $quizData, $thePID, $resPID));
               }
               // Andere Fälle später entscheiden
       }
       // get the startPID of a solved quiz
       if (!$startPID) {
           $startPID = $this->helperObj->getStartUid($quizData['qtuid']);
       }
       $quiz_name = $this->conf['quizName'];
       if (!$quiz_name) {
           $quiz_name = $this->helperObj->getPageTitle($startPID);
       }
       $markerArrayP["###QUIZ_NAME###"] = $markerArray["###QUIZ_NAME###"] = $quiz_name;
       //if ($this->conf['startCategory']) {        // Kategorie-Namen zwischenspeichern
       $res6 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,name,celement,pagetime', $this->tableCategory, 'pid IN (' . $thePID . ')');
       $catCount = $GLOBALS['TYPO3_DB']->sql_num_rows($res6);
       if ($catCount > 0) {
           while ($row6 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res6)) {
               $catUID = $row6['uid'];
               $this->catArray[$catUID] = array();
               $this->catArray[$catUID]['name'] = $row6['name'];
               $this->catArray[$catUID]['celement'] = $row6['celement'];
               $this->catArray[$catUID]['pagetime'] = $row6['pagetime'];
           }
           if ($this->helperObj->writeDevLog) {
               t3lib_div::devLog($catCount . ' categories found.', $this->extKey, 0);
           }
       }
       $GLOBALS['TYPO3_DB']->sql_free_result($res6);
       //}
       // check, if logged in
       if ($this->conf['loggedInCheck'] && ($quizData['cmd'] != 'score' && $quizData['cmd'] != 'list') && !$GLOBALS['TSFE']->loginUser) {
           $no_rights = 1;
           // noname user is (b)locked now
           $markerArray["###NOT_LOGGEDIN###"] = $this->pi_getLL('not_loggedin', 'not_loggedin');
           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_NOT_LOGGEDIN###");
           $content .= $this->cObj->substituteMarkerArray($template, $markerArray);
           // Sonderfall !!!
           if ($this->helperObj->writeDevLog) {
               t3lib_div::devLog('Loggin check failes!', $this->extKey, 0);
           }
       }
       $quiz_taker_ip_address = preg_replace('/[^0-9\\.]/', '', $this->helperObj->getRealIpAddr());
       // Ignore all sumbits and old data?
       if (!$this->conf['ignoreSubmit']) {
           // check for second entry ( based on the ip-address )
           if ($this->conf['doubleEntryCheck'] && ($quizData['cmd'] != 'score' && $quizData['cmd'] != 'list') && !$quizData['qtuid'] && $no_rights == 0) {
               $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('tstamp, uid', $this->tableAnswers, 'pid=' . $resPID . " AND ip='" . $quiz_taker_ip_address . "' AND sys_language_uid=" . $this->lang, '', 'tstamp DESC', '1');
               $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
               if ($rows > 0) {
                   // DB entry found for current user?
                   $fetchedRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5);
                   $dateOld = $fetchedRow['tstamp'];
                   if ($this->helperObj->writeDevLog) {
                       t3lib_div::devLog('Entry found for IP ' . $quiz_taker_ip_address . ': ' . $fetchedRow['uid'], $this->extKey, 0);
                   }
                   $period = intval($this->conf['doubleEntryCheck']);
                   // seconds
                   if ($period < 10000) {
                       $period *= 60 * 60 * 24;
                   }
                   // days
                   //if ($period==1) $period = 50000;        // approx. a half day is the quiz blocked for the same ip-address
                   if (time() - $dateOld < $period) {
                       if ($this->conf['doubleCheckMode'] || $this->conf['secondPollMode']) {
                           $quizData['qtuid'] = intval($fetchedRow['uid']);
                           $quizData['cmd'] = 'next';
                           $quizData['secondVisit'] = 1;
                           $secondVisit = true;
                           if ($this->helperObj->writeDevLog) {
                               t3lib_div::devLog('IP-check: cmd to next changed, because doubleCheckMode=' . $this->conf['doubleCheckMode'] . ', secondPollMode=' . $this->conf['secondPollMode'], $this->extKey, 0);
                           }
                       } else {
                           $no_rights = 1;
                           // user is (b)locked now
                           $markerArray["###DOUBLE_ENTRY###"] = $this->pi_getLL('double_entry', 'double_entry');
                           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_DOUBLE_ENTRY###");
                           $content .= $this->cObj->substituteMarkerArray($template, $markerArray);
                           // Sonderfall !!!
                           if ($this->helperObj->writeDevLog) {
                               t3lib_div::devLog('User is blocked (ip-check), because doubleCheckMode=' . $this->conf['doubleCheckMode'] . ', secondPollMode=' . $this->conf['secondPollMode'], $this->extKey, 0);
                           }
                       }
                   }
                   $GLOBALS['TYPO3_DB']->sql_free_result($res5);
                   //$oldLoaded = true;
               }
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('IP check for qtuid=' . $quizData['qtuid'], $this->extKey, 0);
               }
           }
           // check for second entry ( based on the fe_users-id )
           if ($this->conf['loggedInMode'] && ($quizData['cmd'] != 'score' && $quizData['cmd'] != 'list') && !$quizData['qtuid'] && $GLOBALS['TSFE']->loginUser && $this->tableAnswers == 'tx_myquizpoll_result' && $no_rights == 0) {
               $fe_uid = intval($GLOBALS['TSFE']->fe_user->user['uid']);
               $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, tstamp', $this->tableAnswers, 'pid=' . $resPID . " AND fe_uid={$fe_uid} AND sys_language_uid=" . $this->lang, '', 'tstamp DESC', '1');
               $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
               if ($rows > 0) {
                   // DB entry found for current user?
                   $fetchedRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5);
                   if ($this->conf['doubleCheckMode'] || $this->conf['secondPollMode']) {
                       $quizData['qtuid'] = intval($fetchedRow['uid']);
                       $quizData['cmd'] = 'next';
                       $secondVisit = true;
                   } else {
                       $no_rights = 1;
                       // user is (b)locked now
                       $markerArray["###DOUBLE_ENTRY###"] = $this->pi_getLL('double_entry', 'double_entry');
                       $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_DOUBLE_ENTRY###");
                       $content .= $this->cObj->substituteMarkerArray($template, $markerArray);
                       // Sonderfall !!!
                   }
                   $GLOBALS['TYPO3_DB']->sql_free_result($res5);
                   //$oldLoaded = true;
               }
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('fe_users check for qtuid=' . $quizData['qtuid'], $this->extKey, 0);
               }
           }
           // check if the captcha is OK
           if (($quizData['cmd'] == 'submit' && $this->helperObj->getAskAtQ($quizData['qtuid']) || $quizData["fromStart"] && $this->conf['userData.']['askAtStart'] || $quizData["fromFinal"] && $this->conf['userData.']['askAtFinal']) && is_object($this->freeCap) && $this->conf['enableCaptcha'] && !$this->freeCap->checkWord($quizData['captcha_response']) && $no_rights == 0) {
               if ($quizData["fromStart"] && $startPID != $GLOBALS["TSFE"]->id) {
                   // Weiterleitung zurueck zur Extra-Startseite
                   $this->redirectUrl($startPID, array($this->prefixId . '[name]' => $quizData["name"], $this->prefixId . '[email]' => $quizData["email"], $this->prefixId . '[homepage]' => $quizData["homepage"], $this->prefixId . '[captchaError]' => '1'));
                   break;
                   // hier kommt man eh nie hin...
               }
               if ($quizData["fromFinal"] && $finalPID != $GLOBALS["TSFE"]->id) {
                   // Weiterleitung zurueck zur Extra-Endseite
                   $this->redirectUrl($finalPID, array($this->prefixId . '[qtuid]' => intval($quizData["qtuid"]), $this->prefixId . '[cmd]' => 'next', $this->prefixId . '[name]' => $quizData["name"], $this->prefixId . '[email]' => $quizData["email"], $this->prefixId . '[homepage]' => $quizData["homepage"], $this->prefixId . '[captchaError]' => '1'));
                   break;
                   // hier kommt man eh nie hin...
               }
               $quizData['cmd'] = $quizData["fromStart"] ? '' : 'next';
               // "nochmal" simulieren
               //$quizData['qtuid'] = '';        // wieso wohl???
               $markerArray["###CAPTCHA_NOT_OK###"] = $this->pi_getLL('captcha_not_ok', 'captcha_not_ok');
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_CAPTCHA_NOT_OK###");
               $markerArrayP["###REF_ERRORS###"] .= $this->cObj->substituteMarkerArray($template, $markerArray);
               // instead of $content
               //if ($quizData["fromStart"])
               $quizData["fromStart"] = 0;
               // nichts wurde getan simulieren
               $quizData["fromFinal"] = 0;
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('captcha check 1 not ok.', $this->extKey, 0);
               }
               $error = true;
               $captchaError = true;
           } else {
               if ($quizData["captchaError"]) {
                   $markerArray["###CAPTCHA_NOT_OK###"] = $this->pi_getLL('captcha_not_ok', 'captcha_not_ok');
                   $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_CAPTCHA_NOT_OK###");
                   $markerArrayP["###REF_ERRORS###"] .= $this->cObj->substituteMarkerArray($template, $markerArray);
                   // instead of $content
                   if ($this->helperObj->writeDevLog) {
                       t3lib_div::devLog('captcha check 2 not ok.', $this->extKey, 0);
                   }
                   $error = true;
                   $captchaError = true;
               }
           }
           // check if used IP is blocked
           if ($quizData['cmd'] == 'submit' && $this->conf['blockIP']) {
               $ips = explode(',', $this->conf['blockIP']);
               foreach ($ips as $aip) {
                   $len = strlen(trim($aip));
                   if (substr($quiz_taker_ip_address, 0, $len) == trim($aip)) {
                       //$markerArray["###IP_BLOCKED###"] = $this->pi_getLL('ip_blocked','ip_blocked');
                       //$template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_IP_BLOCKED###");
                       $markerArrayP["###REF_ERRORS###"] .= 'Your IP is blocked!';
                       //$this->cObj->substituteMarkerArray($template, $markerArray);
                       if ($this->helperObj->writeDevLog) {
                           t3lib_div::devLog('IP ' . $quiz_taker_ip_address . ' blocked!', $this->extKey, 0);
                       }
                       $error = true;
                       $no_rights = 1;
                   }
               }
           }
           // read quiz takers old data
           $answeredQuestions = '';
           // prev. answered Question(s)
           $skipped = '';
           $cids = '';
           $fids = '';
           if (($this->conf['useCookiesInDays'] && !$quizData['qtuid'] || $quizData['cmd'] == 'next' || $quizData['cmd'] == 'submit' && !$this->conf['isPoll'] && ($this->conf['dontShowPoints'] != 1 || $this->conf['quizTimeMinutes'])) && $no_rights == 0) {
               $cookieRead = false;
               if (!$quizData['qtuid'] && $this->conf['useCookiesInDays']) {
                   // !($quizData['cmd']  == 'next' || $quizData['cmd']  == 'submit')) warum das nur? auskommentiert am 27.12.2009
                   $cookieName = $this->getCookieMode($resPID, $thePID);
                   if ($this->conf['allowCookieReset'] && $quizData["resetcookie"]) {
                       setcookie($cookieName, "", time() - 3600);
                       if ($this->helperObj->writeDevLog) {
                           t3lib_div::devLog('Cookie reseted: ' . $cookieName, $this->extKey, 0);
                       }
                   } else {
                       if ($this->conf['useCookiesInDays']) {
                           $quizData['qtuid'] = intval($_COOKIE[$cookieName]);
                           // read quiz taker UID from a cookie
                           if ($quizData['qtuid']) {
                               $cookieRead = true;
                           }
                           if ($this->helperObj->writeDevLog) {
                               t3lib_div::devLog('Cookie read: ' . $cookieName . '=' . $quizData['qtuid'], $this->extKey, 0);
                           }
                           // oder? $HTTP_COOKIE_VARS["myquizpoll".$resPID];    oder?  $GLOBALS["TSFE"]->fe_user->getKey("ses","myquizpoll".$resPID);
                       }
                   }
               }
               if ($quizData['qtuid'] && $this->tableAnswers == 'tx_myquizpoll_result') {
                   // load solved questions and quiz takers name, email, homepage, old points and last time
                   $uid = intval($quizData['qtuid']);
                   $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('name, email, homepage, qids,sids,cids,fids, p_or_a, p_max, percent, o_max, o_percent, firsttime, joker1,joker2,joker3, lastcat,nextcat', $this->tableAnswers, 'uid=' . $uid . ' AND sys_language_uid=' . $this->lang);
                   //.' '.$this->cObj->enableFields($this->tableAnswers), auskommentiert am 7.11.10
                   $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
                   if ($rows > 0) {
                       // DB entry found for current user?
                       $fetchedRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5);
                       $answeredQuestions = $fetchedRow['qids'];
                       if (!$this->conf["isPoll"]) {
                           $skipped = $fetchedRow['sids'];
                           $joker1 = $fetchedRow['joker1'];
                           $joker2 = $fetchedRow['joker2'];
                           $joker3 = $fetchedRow['joker3'];
                           $firsttime = intval($fetchedRow['firsttime']);
                           $this->helperObj->setFirstTime($uid, $firsttime);
                           if ($answeredQuestions) {
                               // 2.9.10: beantwortete poll-frage muss man auch speichern???
                               if ($fetchedRow['nextcat']) {
                                   $nextCat = $fetchedRow['nextcat'];
                                   if ($this->conf['startCategory']) {
                                       $this->conf['startCategory'] = $nextCat;
                                   }
                                   // kategorie der naechsten frage...
                               }
                               if ($quizData['cmd'] != 'submit') {
                                   // namen nicht ueberschreiben
                                   $whereAnswered = ' AND uid NOT IN (' . preg_replace('/[^0-9,]/', '', $answeredQuestions) . ')';
                                   // exclude answered questions next time
                                   if (!($quizData["name"] || $quizData["email"] || $quizData["homepage"])) {
                                       $quizData["name"] = $fetchedRow['name'];
                                       // abgesendete daten nicht mit default-werten ueberschreiben!
                                       $quizData["email"] = $fetchedRow['email'];
                                       $quizData["homepage"] = $fetchedRow['homepage'];
                                   }
                                   //$markerArray["###VAR_ADDRESS_UID###"] = $quizData["address_uid"] = $fetchedRow['address_uid'];
                               }
                               $markerArray["###VAR_TOTAL_POINTS###"] = intval($fetchedRow['p_or_a']);
                               // save total points for the case there are no more questions
                               $markerArray["###VAR_TMAX_POINTS###"] = intval($fetchedRow['p_max']);
                               $markerArray["###VAR_TMISSING_POINTS###"] = intval($fetchedRow['p_max']) - intval($fetchedRow['p_or_a']);
                               $markerArray["###VAR_PERCENT###"] = intval($fetchedRow['percent']);
                               $markerArray["###VAR_OMAX_POINTS###"] = intval($fetchedRow['o_max']);
                               $markerArray["###VAR_OVERALL_PERCENT###"] = intval($fetchedRow['o_percent']);
                               $markerArray["###VAR_QUESTIONS_ANSWERED###"] = $fetchedRow['qids'] ? substr_count($fetchedRow['qids'], ',') + 1 : 0;
                               if ($fetchedRow['cids'] || $fetchedRow['fids']) {
                                   // if weglassen?
                                   $markerArray["###VAR_QUESTIONS_CORRECT###"] = $fetchedRow['cids'] ? substr_count($fetchedRow['cids'], ',') + 1 : 0;
                                   $markerArray["###VAR_QUESTIONS_FALSE###"] = $fetchedRow['fids'] ? substr_count($fetchedRow['fids'], ',') + 1 : 0;
                               }
                               $markerArray["###VAR_CATEGORY###"] = $this->catArray[$row['lastcat']]['name'];
                               $markerArray["###VAR_NEXT_CATEGORY###"] = $this->catArray[$row['nextcat']]['name'];
                               $elapseTime = time() - $firsttime;
                           }
                           if ($skipped && $quizData['cmd'] != 'submit') {
                               $whereSkipped = ' AND uid NOT IN (' . preg_replace('/[^0-9,]/', '', $skipped) . ')';
                               // exclude skipped questions next time
                           }
                       }
                       if ($cookieRead) {
                           $secondVisit = true;
                       }
                       // es wurde erfolgreich ein cookie gelesen
                   }
                   $GLOBALS['TYPO3_DB']->sql_free_result($res5);
               } else {
                   if ($quizData['qtuid']) {
                       // load solved poll question from voting-table
                       $uid = intval($quizData['qtuid']);
                       $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('question_id', $this->tableAnswers, 'uid=' . $uid . ' AND sys_language_uid=' . $this->lang);
                       if ($GLOBALS['TYPO3_DB']->sql_num_rows($res5) > 0) {
                           $fetchedRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5);
                           $answeredQuestions = $fetchedRow['question_id'];
                           if ($cookieRead) {
                               $secondVisit = true;
                           }
                       }
                       $GLOBALS['TYPO3_DB']->sql_free_result($res5);
                   } else {
                       if ($this->conf['quizTimeMinutes'] && $quizData["time"]) {
                           $elapseTime = time() - intval($quizData["time"]);
                           // before saving data
                       }
                   }
               }
               if ($quizData['qtuid'] && $this->conf["isPoll"] && $this->conf["secondPollMode"] == 1) {
                   $quizData['cmd'] = 'list';
                   if ($this->helperObj->writeDevLog) {
                       t3lib_div::devLog("changing to list mode", $this->extKey, 0);
                   }
               }
               if ($quizData['qtuid']) {
                   $oldLoaded = true;
               }
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog("Old data loaded with uid {$uid}: {$answeredQuestions} / {$whereAnswered} / {$whereSkipped}", $this->extKey, 0);
               }
           }
       }
       $markerArrayP["###QTUID###"] = intval($quizData['qtuid']);
       // check, if quiz is cancled
       if ($this->conf['quizTimeMinutes'] && intval($this->conf['quizTimeMinutes']) * 60 - $elapseTime <= 0) {
           // oder $quizData['cancel'] == 1 ) {
           $markerArray["###REACHED1###"] = $this->pi_getLL('reached1', 'reached1');
           $markerArray["###REACHED2###"] = $this->pi_getLL('reached2', 'reached2');
           $markerArray["###SO_FAR_REACHED1###"] = $this->pi_getLL('so_far_reached1', 'so_far_reached1');
           $markerArray["###SO_FAR_REACHED2###"] = $this->pi_getLL('so_far_reached2', 'so_far_reached2');
           $markerArray["###QUIZ_END###"] = $this->pi_getLL('quiz_end', 'quiz_end');
           $markerArray["###RESTART_QUIZ###"] = $this->pi_linkToPage($this->pi_getLL('restart_quiz', 'restart_quiz'), $startPID, $target = '', array());
           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_END###");
           $content .= $this->cObj->substituteMarkerArray($template, $markerArray);
           // sonderfall !!!
           if ($this->conf['finalWhenCancel']) {
               $noQuestions = true;
           } else {
               if ($this->conf['highscore.']['showAtFinal']) {
                   $quizData['cmd'] = 'score';
                   // show highscore
               } else {
                   $quizData['cmd'] = 'exit';
                   // display no more questions
               }
               $no_rights = 1;
               // cancel all
           }
           if ($this->helperObj->writeDevLog) {
               t3lib_div::devLog("cancel check: {$no_rights}/" . $quizData['cmd'], $this->extKey, 0);
           }
       }
       // show only a start page?
       if ($this->conf['userData.']['askAtStart'] && !$quizData['qtuid'] && !$quizData['cmd'] && !$quizData["fromStart"]) {
           // show only "ask for user data"?
           $startPage = true;
           $quizData['cmd'] = 'start';
       }
       // next page is a page with questions...
       if ($quizData['cmd'] == 'next') {
           $quizData['cmd'] = '';
       }
       if ($quizData['cmd'] == 'submit' && !$this->conf['ignoreSubmit'] && $no_rights == 0) {
           /* ***************************************************** */
           /*
            * Display result page: answers and points
            */
           if (!$this->conf["isPoll"]) {
               // neu seit 20.2.2011
               // Check quiz taker name and email
               if (trim($quizData["name"]) == "") {
                   $quizData["name"] = $this->pi_getLL('no_name', 'no_name');
               }
               if (!t3lib_div::validEmail(trim($quizData["email"]))) {
                   $quizData["email"] = $this->pi_getLL('no_email', 'no_email');
               }
               // Avoid bad characters in database request
               $quiz_taker_name = $GLOBALS['TYPO3_DB']->quoteStr($quizData['name'], $this->tableAnswers);
               $quiz_taker_email = $GLOBALS['TYPO3_DB']->quoteStr($quizData['email'], $this->tableAnswers);
               $quiz_taker_homepage = $GLOBALS['TYPO3_DB']->quoteStr($quizData['homepage'], $this->tableAnswers);
               $markerArray["###REAL_NAME###"] = $quiz_taker_name;
               $markerArray["###REAL_EMAIL###"] = $quiz_taker_email;
               $markerArray["###REAL_HOMEPAGE###"] = $quiz_taker_homepage;
               $markerArray["###RESULT_FOR###"] = $this->pi_getLL('result_for', 'result_for');
               if ($quiz_taker_email == $this->pi_getLL('no_email', 'no_email')) {
                   $quiz_taker_email = '';
               }
               if ($quiz_taker_homepage == $this->pi_getLL('no_homepage', 'no_homepage')) {
                   $quiz_taker_homepage = '';
               }
           }
           $markerArray["###THANK_YOU###"] = $this->pi_getLL('thank_you', 'thank_you');
           if (!$this->conf['isPoll']) {
               $markerArray["###RES_QUESTION_POINTS###"] = $this->pi_getLL('result_question_points', 'result_question_points');
               $markerArray["###VAR_QUESTIONS###"] = $this->helperObj->getQuestionsNo();
               if ($whereAnswered) {
                   $markerArray["###VAR_QUESTION###"] = $this->helperObj->getQuestionNo($whereAnswered);
               } else {
                   $markerArray["###VAR_QUESTION###"] = $this->helperObj->getQuestionNo('-');
               }
           }
           // Begin HTML output
           $template_qr = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QRESULT###");
           // full template
           if (!$this->conf["isPoll"]) {
               // neu seit 20.2.2011
               $template_answer = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QR_CORR###");
               $template_okok = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QR_CORR_ANSW###");
               $template_oknot = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QR_CORR_NOTANSW###");
               $template_notok = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QR_NOTCORR_ANSW###");
               $template_notnot = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QR_NOTCORR_NOTANSW###");
               $template_qr_points = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QR_POINTS###");
               $template_expl = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_EXPLANATION###");
           }
           $template_delimiter = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_DELIMITER###");
           $template_image_begin = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUESTION_IMAGE_BEGIN###");
           $template_image_end = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUESTION_IMAGE_END###");
           // Get the answers from the user
           $answerArray = array();
           $questionNumber = 1;
           $lastUIDs = '';
           $whereUIDs = '';
           $whereCat = '';
           if ($this->conf['onlyCategories']) {
               $whereCat = " AND category IN (" . preg_replace('/[^0-9,]/', '', $this->conf['onlyCategories']) . ")";
           }
           while ($quizData['uid' . $questionNumber]) {
               $answerArray[$questionNumber] = $quizData['uid' . $questionNumber];
               $lastUIDs .= ',' . intval($quizData['uid' . $questionNumber]);
               $questionNumber++;
           }
           $maxQuestions = $questionNumber - 1;
           if ($lastUIDs) {
               $whereUIDs = ' AND uid IN (' . substr($lastUIDs, 1) . ')';
               //}    // kgb: geaendert am 6.9.2010
               // Get questions from the database
               $questionsArray = array();
               $tempNumber = 0;
               $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->tableQuestions, 'pid IN (' . $thePID . ')' . $whereUIDs . $whereCat . ' AND sys_language_uid=' . $this->lang . ' ' . $this->cObj->enableFields($this->tableQuestions));
               $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
               if ($rows > 0) {
                   while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5)) {
                       $tempNumber = $row['uid'];
                       // save the uid for each question
                       $questionsArray[$tempNumber] = $row;
                       // save each question
                   }
               }
               $GLOBALS['TYPO3_DB']->sql_free_result($res5);
           }
           $points = 0;
           // points from the user (quiz taker)
           $maxPoints = 0;
           // maximum points reachable per page
           $maxTotal = 0;
           // maximum total points reachable
           $percent = 0;
           // 100 * reached points / total points
           $overallMaximum = 0;
           // overall points of all questions
           $overallPercent = 0;
           // overall percent
           $questionUID = 0;
           // uid of a question
           $answered = '';
           // uids of answered questions
           $skipped = '';
           // uids of skipped questions
           $correctAnsw = '';
           // uids of correct answered question
           $falseAnsw = '';
           // uids of false answered question
           $skippedCount = 0;
           // no. of skipped questions at this page
           $imgTSConfig = array();
           // image values
           if (is_array($this->conf['jokers.'])) {
               $halvePoints = $this->conf['jokers.']['halvePoints'];
           } else {
               $halvePoints = 0;
           }
           // Old questions and answers
           for ($questionNumber = 1; $questionNumber < $maxQuestions + 1; $questionNumber++) {
               $questionUID = intval($answerArray[$questionNumber]);
               $row = $questionsArray[$questionUID];
               $markerArray["###VAR_QUESTION_NUMBER###"] = $questionNumber;
               if ($this->conf['isPoll']) {
                   // link to the result page
                   $urlParameters = array("tx_myquizpoll_pi1[cmd]" => "list", "tx_myquizpoll_pi1[qid]" => $questionUID, "no_cache" => "1");
                   $markerArray["###POLLRESULT_URL###"] = $this->pi_linkToPage($this->pi_getLL('poll_url', 'poll_url'), $listPID, $target = '', $urlParameters);
               } else {
                   if ($quizData['answer' . $questionNumber] == -1) {
                       $skipped .= ',' . $questionUID;
                       $skippedCount++;
                       continue;
                   }
               }
               //$answerPointsBool = false;
               $answered .= ',' . $questionUID;
               // nach unten geschoben...
               $questionPoints = 0;
               $maxQuestionPoints = 0;
               $markerArray["###VAR_QUESTION###"]++;
               $nextCat = '';
               $lastCat = $row['category'];
               if ($this->catArray[$lastCat]) {
                   $markerArray["###VAR_CATEGORY###"] = $this->catArray[$lastCat]['name'];
               }
               // Output the result/explanations
               if (!($this->conf['dontShowCorrectAnswers'] && $this->conf['dontShowPoints'] == 1) || $this->conf['startCategory'] || $this->conf['advancedStatistics'] || $this->conf['showAllCorrectAnswers'] || $this->conf['isPoll']) {
                   if ($row['image']) {
                       // && (substr_count($template_qr, 'REF_QUESTION_IMAGE_BEGIN')>0)) {
                       $markerArray["###VAR_QUESTION_IMAGE###"] = $this->helperObj->getImage($row['image'], $row["alt_text"]);
                       $markerArray["###REF_QUESTION_IMAGE_BEGIN###"] = $this->cObj->substituteMarkerArray($template_image_begin, $markerArray);
                       $markerArray["###REF_QUESTION_IMAGE_END###"] = $template_image_end;
                   } else {
                       $markerArray["###REF_QUESTION_IMAGE_BEGIN###"] = '';
                       $markerArray["###REF_QUESTION_IMAGE_END###"] = '';
                   }
                   $markerArray["###TITLE_HIDE###"] = $row['title_hide'] ? '-hide' : '';
                   $markerArray["###VAR_QUESTION_TITLE###"] = $row['title'];
                   $markerArray["###VAR_QUESTION_NAME###"] = $this->formatStr($row['name']);
                   // $this->pi_RTEcssText($row['name']);
                   $markerArray["###VAR_ANSWER_POINTS###"] = '';
                   $markerArray["###REF_QR_ANSWER_ALL###"] = '';
                   $markerArray["###REF_QR_ANSWER_CORR###"] = '';
                   $markerArray["###REF_QR_ANSWER_CORR_ANSW###"] = '';
                   $markerArray["###REF_QR_ANSWER_CORR_NOTANSW###"] = '';
                   $markerArray["###REF_QR_ANSWER_NOTCORR_ANSW###"] = '';
                   $markerArray["###REF_QR_ANSWER_NOTCORR_NOTANSW###"] = '';
                   $markerArray["###REF_QR_POINTS###"] = '';
                   $markerArray["###VAR_QUESTION_ANSWER###"] = '';
                   $markerArray["###REF_QR_EXPLANATION###"] = '';
                   $markerArray["###REF_DELIMITER###"] = '';
                   $markerArray["###P1###"] = '';
                   $markerArray["###P2###"] = '';
                   if ($this->conf['dontShowPoints']) {
                       $markerArray["###NO_POINTS###"] = '';
                   } else {
                       $markerArray["###NO_POINTS###"] = '0';
                   }
                   if (!$this->conf['isPoll']) {
                       if (!$this->conf['dontShowPoints'] && $row['qtype'] < 5) {
                           $markerArray["###P1###"] = $this->pi_getLL('p1', 'p1');
                           $markerArray["###P2###"] = $this->pi_getLL('p2', 'p2');
                       }
                       /*    if ($this->conf['noNegativePoints']<3) {        // 20.01.10: wenn alle antworten richtig sein muessen, antwort-punkte ignorieren!
                                 for ($currentValue=1; $currentValue <= $this->answerChoiceMax; $currentValue++) {
                                     if (intval($row['points'.$currentValue])>0 ) {
                                         $answerPointsBool = true;
                                         break;        // Punkte bei Antworten gefunden...
                                     }
                                 }
                             }  am 21.01.10 auskommentiert! */
                   } else {
                       $points = $quizData['answer' . $questionNumber];
                       // points = SELECTED ANSWER !!!
                       $markerArray["###VAR_USER_ANSWER###"] = $row['answer' . $points];
                       if ($points > 0 && $row['category' . $points]) {
                           // NEU && $this->conf['startCategory']
                           $nextCat = $row['category' . $points];
                           // next category from an answer
                       }
                       break;
                       // mehr braucht man nicht bei Umfragen !!!
                   }
                   // myVars for questions
                   $markerArray = array_merge($markerArray, $this->helperObj->setQuestionVars($questionNumber));
                   $allAnswersOK = true;
                   // alle Antworten richtig beantwortet?
                   //$correctBool = false;    // gibt es ueberhaupt korrekte antworten?
                   $realCorrectBool = false;
                   // wurden ueberhaupt korrekte Antworten markiert?
                   $withAnswer = $this->conf['noAnswer'];
                   // gab es eine Antwort vom Benutzer?
                   $lastSelected = 0;
                   for ($answerNumber = 1; $answerNumber < $this->answerChoiceMax + 1; $answerNumber++) {
                       if ($row['answer' . $answerNumber] || $row['answer' . $answerNumber] === '0' || in_array($row['qtype'], $this->textType)) {
                           // was a answer set in the backend?
                           $selected = 0;
                           // was the answer selected by the quiz taker?
                           $tempAnswer = '';
                           // text for answer $answerNumber
                           // myVars for answers
                           $markerArray = array_merge($markerArray, $this->helperObj->setAnswerVars($answerNumber, $row['qtype']));
                           //if ( !$this->conf['isPoll'] ) {    // show correct answers. Bug fixed: dontShowCorrectAnswers doesnt matter here
                           if (!$this->conf['dontShowCorrectAnswers']) {
                               $markerArray["###VAR_QUESTION_ANSWER###"] = $row['answer' . $answerNumber];
                           }
                           $thisCat = $row['category' . $answerNumber];
                           if ($this->catArray[$thisCat]) {
                               $markerArray['###VAR_QA_CATEGORY###'] = $this->catArray[$thisCat]['name'];
                           }
                           if ($row['correct' . $answerNumber]) {
                               // es gibt richtige Antworten
                               $realCorrectBool = true;
                           }
                           $answerPoints = 0;
                           // answer points from the DB
                           if (!$this->conf['dontShowPoints']) {
                               //if ($answerPointsBool) {         // hier interessiert es nicht, ob eine Antwort als korrekt markiert wurde!
                               if ($this->conf['noNegativePoints'] < 3) {
                                   // das ganze Verhalten am 21.01.10 geaendert...
                                   $answerPoints = intval($row['points' . $answerNumber]);
                               }
                               if ($answerPoints > 0) {
                                   $row['correct' . $answerNumber] = true;
                                   // ACHTUNG: falls Punkte zu einer Antwort gesetzt sind, dann wird die Antwort als RICHTIG bewertet!
                               } else {
                                   $answerPoints = intval($row['points']);
                               }
                               if ($row['correct' . $answerNumber] || $row['qtype'] == 3) {
                                   if (($row['qtype'] == 0 || $row['qtype'] == 4) && $this->conf['noNegativePoints'] < 3) {
                                       // KGB, 20.01.10: weg: !$answerPointsBool || $row['qtype'] >= 3, neu: $this->conf['noNegativePoints']<3
                                       $maxQuestionPoints += $answerPoints;
                                   } else {
                                       if ($answerPoints > $maxQuestionPoints) {
                                           $maxQuestionPoints = $answerPoints;
                                       }
                                   }
                                   // bei punkten pro antwort ODER wenn nicht addiert werden soll
                               }
                               if ($row['qtype'] < 5) {
                                   $markerArray["###VAR_ANSWER_POINTS###"] = $answerPoints;
                               }
                           }
                           if ($quizData['answer' . $questionNumber . '_' . $answerNumber]) {
                               // !='') {    // type 0 und 4
                               $selected = $answerNumber;
                           } else {
                               if (($row['qtype'] > 0 && $row['qtype'] < 3 || $row['qtype'] == 7) && $quizData['answer' . $questionNumber] == $answerNumber) {
                                   $selected = $answerNumber;
                               } else {
                                   if ($row['qtype'] == 3 && $quizData['answer' . $questionNumber] != '' || $row['qtype'] == 5) {
                                       // type 3 und 5
                                       $selected = $answerNumber;
                                       // sollte 1 sein
                                   }
                               }
                           }
                           //}
                           $wrongText = 0;
                           // wrong text input?
                           /*                            if ($this->conf['isPoll']) {    // wurde aus der Schleife genommen!
                                                           $points=$quizData['answer'.$questionNumber];                        // points = SELECTED ANSWER !!!
                                                           $markerArray["###VAR_USER_ANSWER###"] .= $row['answer'.$points];
                                                       } else */
                           if ($row['qtype'] == 5 && !$this->conf['dontShowCorrectAnswers']) {
                               $markerArray["###VAR_QUESTION_ANSWER###"] = nl2br(htmlspecialchars($quizData['answer' . $questionNumber]));
                               $tempAnswer = $this->cObj->substituteMarkerArray($template_okok, $markerArray);
                               $markerArray["###REF_QR_ANSWER_CORR_ANSW###"] .= $tempAnswer;
                               // welches template soll man hier wohl nehmen?
                               if ($quizData['answer' . $questionNumber] || $quizData['answer' . $questionNumber] === 0) {
                                   $withAnswer = true;
                               }
                               if ($this->helperObj->writeDevLog) {
                                   t3lib_div::devLog($questionUID . '-' . $answerNumber . '=CORR_ANSW5->', $this->extKey, 0);
                               }
                           } else {
                               if ($selected > 0 && ($row['qtype'] == 3 && strtolower($row['answer' . $answerNumber]) == strtolower($quizData['answer' . $questionNumber]) || $row['qtype'] != 3 && $row['correct' . $answerNumber])) {
                                   // korrekte Antwort
                                   $questionPoints = $questionPoints + $answerPoints;
                                   // $row['points']; geaendert am 16.9.2009
                                   if (!$this->conf['dontShowCorrectAnswers']) {
                                       $tempAnswer = $this->cObj->substituteMarkerArray($template_okok, $markerArray);
                                       $markerArray["###REF_QR_ANSWER_CORR_ANSW###"] .= $tempAnswer;
                                   }
                                   //$correctBool = true;
                                   $withAnswer = true;
                                   if ($this->helperObj->writeDevLog) {
                                       t3lib_div::devLog($questionUID . '-' . $answerNumber . '=CORR_ANSW->' . $questionPoints, $this->extKey, 0);
                                   }
                               } else {
                                   if ($selected > 0) {
                                       // falsche Antwort
                                       $allAnswersOK = false;
                                       if ($this->conf['noNegativePoints'] != 2) {
                                           $questionPoints = $questionPoints - $answerPoints;
                                       }
                                       // $row['points']; geaendert am 16.9.2009
                                       if (!$this->conf['dontShowCorrectAnswers']) {
                                           // { added 8.8.09
                                           if ($row['qtype'] == 3) {
                                               // since 0.1.8: falsche und richtige antwort ausgeben
                                               $tempAnswer = $this->cObj->substituteMarkerArray($template_oknot, $markerArray);
                                               $markerArray["###REF_QR_ANSWER_CORR_NOTANSW###"] .= $tempAnswer;
                                               $markerArray["###VAR_QUESTION_ANSWER###"] = htmlspecialchars($quizData['answer' . $questionNumber]);
                                           }
                                           $tempAnswer2 = $this->cObj->substituteMarkerArray($template_notok, $markerArray);
                                           $markerArray["###REF_QR_ANSWER_NOTCORR_ANSW###"] .= $tempAnswer2;
                                           $tempAnswer .= $tempAnswer2;
                                           // hier gibt es 2 antworten !!!
                                       }
                                       if ($row['qtype'] == 3 && ($row['answer1'] || $row['answer1'] === '0')) {
                                           $wrongText = 1;
                                       }
                                       // for statistics: a2 statt a1 bei falscher antwort
                                       $withAnswer = true;
                                       if ($this->helperObj->writeDevLog) {
                                           t3lib_div::devLog($questionUID . '-' . $answerNumber . '=NOTCORR_ANSW->' . $questionPoints, $this->extKey, 0);
                                       }
                                   } else {
                                       if ($row['correct' . $answerNumber]) {
                                           // nicht beantwortet, waere aber richtig gewesen
                                           $allAnswersOK = false;
                                           if (!$this->conf['dontShowCorrectAnswers']) {
                                               // hierhin verschoben am 24.1.10
                                               $tempAnswer = $this->cObj->substituteMarkerArray($template_oknot, $markerArray);
                                               $markerArray["###REF_QR_ANSWER_CORR_NOTANSW###"] .= $tempAnswer;
                                           }
                                           if ($row['qtype'] == 3 && ($row['answer1'] || $row['answer1'] === '0')) {
                                               $wrongText = 1;
                                               // for statistics: a2 statt a1 bei falscher antwort
                                               $selected = 2;
                                               // statistics: no answer = false answer !
                                           }
                                           //$correctBool = true;
                                           if ($this->helperObj->writeDevLog) {
                                               t3lib_div::devLog($questionUID . '-' . $answerNumber . '=CORR_NOTANSW->', $this->extKey, 0);
                                           }
                                       } else {
                                           if (!$this->conf['dontShowCorrectAnswers']) {
                                               $tempAnswer = $this->cObj->substituteMarkerArray($template_notnot, $markerArray);
                                               $markerArray["###REF_QR_ANSWER_NOTCORR_NOTANSW###"] .= $tempAnswer;
                                               if ($this->helperObj->writeDevLog) {
                                                   t3lib_div::devLog($questionUID . '-' . $answerNumber . '=NOTCORR_NOTANSW->', $this->extKey, 0);
                                               }
                                           }
                                       }
                                   }
                               }
                           }
                           if (!$this->conf['dontShowCorrectAnswers']) {
                               // !$this->conf['isPoll'] &&
                               $markerArray["###REF_QR_ANSWER_ALL###"] .= $tempAnswer;
                               // all answers in correct order
                               if ($row['correct' . $answerNumber] || $row['qtype'] == 3 || $row['qtype'] == 5) {
                                   // all correct answers
                                   $markerArray["###REF_QR_ANSWER_CORR###"] .= $this->cObj->substituteMarkerArray($template_answer, $markerArray);
                               }
                           }
                           if ($this->conf['advancedStatistics'] && $withAnswer) {
                               // for more statistics  && !$this->conf['isPoll']
                               $statisticsArray[$questionUID]['a' . ($answerNumber + $wrongText)] = $selected > 0 ? 1 : 0;
                               if (($row['qtype'] == 3 || $row['qtype'] == 5) && ($quizData['answer' . $questionNumber] || $quizData['answer' . $questionNumber] === '0')) {
                                   $statisticsArray[$questionUID]['text'] = $GLOBALS['TYPO3_DB']->quoteStr($quizData['answer' . $questionNumber], $this->tableRelation);
                               } else {
                                   $statisticsArray[$questionUID]['text'] = '';
                               }
                           }
                           if ($selected > 0 && $row['category' . $selected]) {
                               // && $this->conf['startCategory']
                               $nextCat = $row['category' . $selected];
                               // next category from an answer
                           }
                           if ($selected > 0) {
                               $lastSelected = $selected;
                           }
                       }
                       if (in_array($row['qtype'], $this->textType)) {
                           break 1;
                       }
                       // nur erste Antwort ist hier moeglich
                   }
                   if ($catCount > 0) {
                       // $this->conf['startCategory']
                       if (!$nextCat) {
                           $nextCat = $row['category_next'];
                       }
                       // next category of this question
                       if ($this->conf['advancedStatistics'] && $withAnswer) {
                           $statisticsArray[$questionUID]['nextCat'] = $nextCat;
                       }
                   }
                   if (!$this->conf['dontShowPoints']) {
                       // Bug fixed: dontShowCorrectAnswers doesnt matter here  && !$this->conf['isPoll']
                       if ($questionPoints < 0 && $this->conf['noNegativePoints']) {
                           $questionPoints = 0;
                       }
                       // keine neg. Punkte
                       if ($questionPoints > 0 && $this->conf['noNegativePoints'] == 3) {
                           if (!$allAnswersOK) {
                               $questionPoints = 0;
                           } else {
                               $questionPoints = $answerPoints;
                           }
                           // KGB, 19.01.10: nur maximale Punkte vergeben, nicht pro Antwort
                       }
                       if ($this->conf['noNegativePoints'] == 4) {
                           // Punkte nur, wenn alles OK war
                           if ($allAnswersOK) {
                               $questionPoints = 0;
                           } else {
                               $questionPoints = $answerPoints;
                           }
                       }
                       if ($questionPoints > 0 && $halvePoints && ($quizData["joker1"] || $quizData["joker2"] || $quizData["joker3"])) {
                           $questionPoints = intval($questionPoints / 2);
                       }
                       // halbe Punkte nach Joker-Benutzung
                       $points += $questionPoints;
                       $maxPoints += $maxQuestionPoints;
                       if ($this->conf['advancedStatistics'] && $withAnswer) {
                           $statisticsArray[$questionUID]['points'] = $questionPoints;
                       }
                   } else {
                       if ($this->conf['advancedStatistics'] && $withAnswer) {
                           $statisticsArray[$questionUID]['points'] = 0;
                       }
                       /*    if ($this->conf['dontShowPoints']==2){    // TODO: eine unausgereifte Idee
                                 $cat = ($allAnswersOK) ? $nextCat : $row['category'];
                                 $points=intval('/,|\./', '', $this->catArray[$cat]['name']);    // katgorie in punkte umwandeln
                             } */
                   }
                   // 20.4.10: $correctBool ersetzt durch:
                   if ($realCorrectBool && $withAnswer) {
                       // falls es richtige antworten gibt, merken welche man richtig/falsch beantwortet hat
                       if ($allAnswersOK) {
                           $correctAnsw .= ',' . $questionUID;
                           if ($this->helperObj->writeDevLog) {
                               t3lib_div::devLog($questionUID . ' correct.', $this->extKey, 0);
                           }
                       } else {
                           $falseAnsw .= ',' . $questionUID;
                           if ($this->helperObj->writeDevLog) {
                               t3lib_div::devLog($questionUID . ' not correct.', $this->extKey, 0);
                           }
                       }
                   } else {
                       if ($this->helperObj->writeDevLog) {
                           t3lib_div::devLog($questionUID . ' not counted.', $this->extKey, 0);
                       }
                   }
                   if (!$this->conf['dontShowCorrectAnswers']) {
                       //  && !$this->conf['isPoll']
                       if (!$this->conf['dontShowPoints'] && $row['qtype'] < 5) {
                           $markerArray["###VAR_QUESTION_POINTS###"] = $questionPoints;
                           $markerArray["###VAR_MAX_QUESTION_POINTS###"] = $maxQuestionPoints;
                           $markerArray["###REF_QR_POINTS###"] = $this->cObj->substituteMarkerArray($template_qr_points, $markerArray);
                       } else {
                           $markerArray["###VAR_QUESTION_POINTS###"] = '';
                           $markerArray["###VAR_MAX_QUESTION_POINTS###"] = '';
                       }
                       if ($row['explanation'] != '' || $row['explanation1'] != '' || $row['explanation2'] != '') {
                           // Explanation
                           $markerArray["###VAR_EXPLANATION###"] = '';
                           if ($row['explanation1'] != '') {
                               // Nur wenn das addon myquizpoll_expl2 installiert ist
                               $markerArray["###VAR_EXPLANATION###"] = $lastSelected && $row['explanation' . $lastSelected] ? $this->formatStr($row['explanation' . $lastSelected]) : $this->formatStr($row['explanation']);
                           } else {
                               if ($row['explanation2'] != '') {
                                   // Nur wenn das addon myquizpoll_expl installiert ist
                                   $markerArray["###VAR_EXPLANATION###"] = $allAnswersOK ? $this->formatStr($row['explanation']) : $this->formatStr($row['explanation2']);
                               } else {
                                   $markerArray["###VAR_EXPLANATION###"] = $this->formatStr($row['explanation']);
                               }
                           }
                           if ($markerArray["###VAR_EXPLANATION###"]) {
                               $markerArray["###REF_QR_EXPLANATION###"] = $this->cObj->substituteMarkerArray($template_expl, $markerArray);
                           } else {
                               $markerArray["###REF_QR_EXPLANATION###"] = '';
                           }
                       }
                       $markerArray["###REF_DELIMITER###"] = $this->cObj->substituteMarkerArray($template_delimiter, $markerArray);
                   }
               }
               if (!$this->conf['dontShowCorrectAnswers']) {
                   // bug fixed: points dont even matter  && !$this->conf['isPoll']
                   $markerArrayP["###REF_QRESULT###"] .= $this->cObj->substituteMarkerArray($template_qr, $markerArray);
               }
           }
           // hier wurde mal REF_INTRODUCTION befüllt
           if ($answered) {
               $answered = substr($answered, 1);
           }
           // now answered questions (UIDs)
           if ($skipped) {
               $skipped = substr($skipped, 1);
           }
           // now skipped questions (UIDs)
           if ($correctAnsw) {
               $correctAnsw = substr($correctAnsw, 1);
           }
           if ($falseAnsw) {
               $falseAnsw = substr($falseAnsw, 1);
           }
           $doUpdate = 0;
           // insert or update?
           $pointsTotal = $points;
           // total points, reached
           $maxTotal = $maxPoints;
           // total points, maximum
           $markerArray["###VAR_NEXT_CATEGORY###"] = $this->catArray[$nextCat]['name'];
           //if ($this->conf['pageQuestions'] > 0 && !$this->conf['isPoll']) {    // more questions aviable? // auskommentiert am 27.12.2009, denn der Cheat-Test muss immer kommen!
           if (!$this->conf['showAnswersSeparate']) {
               $quizData['cmd'] = '';
           }
           // show more/next questions!
           // Seek for old answered questions
           if ($quizData['qtuid'] && !$this->conf['isPoll']) {
               $uid = intval($quizData['qtuid']);
               $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('qids,cids,fids,sids, p_or_a, p_max, joker1,joker2,joker3', $this->tableAnswers, 'uid=' . $uid . ' AND sys_language_uid=' . $this->lang);
               //.' '.$this->cObj->enableFields($this->tableAnswers), auskommentiert am 7.11.10
               $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
               if ($rows > 0) {
                   // DB entry found for current user?
                   $fetchedRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5);
                   $answeredOld = $fetchedRow['qids'];
                   $correctOld = $fetchedRow['cids'];
                   $falseOld = $fetchedRow['fids'];
                   $skippedOld = $fetchedRow['sids'];
                   $pointsOld = $fetchedRow['p_or_a'];
                   $maxPointsOld = $fetchedRow['p_max'];
                   $joker1 = $fetchedRow['joker1'];
                   $joker2 = $fetchedRow['joker2'];
                   $joker3 = $fetchedRow['joker3'];
                   if ($correctOld && $correctAnsw) {
                       $correctAnsw = $correctOld . ',' . $correctAnsw;
                   } else {
                       if ($correctOld) {
                           $correctAnsw = $correctOld;
                       }
                   }
                   if ($falseOld && $falseAnsw) {
                       $falseAnsw = $falseOld . ',' . $falseAnsw;
                   } else {
                       if ($falseOld) {
                           $falseAnsw = $falseOld;
                       }
                   }
                   if (!$answered) {
                       // all questions skipped  # Fall 1: bisher nur geskipped
                       $answered = $answeredOld;
                       // all answered questions
                       if ($skippedOld && $skipped) {
                           $skipped = $skippedOld . ',' . $skipped;
                       } else {
                           if ($skippedOld) {
                               $skipped = $skippedOld;
                           }
                       }
                       $pointsTotal = $pointsOld;
                       // total points
                       $maxTotal = $maxPointsOld;
                       //if ($answeredOld) $doUpdate=1;
                       $doUpdate = 3;
                       if ($this->helperObj->writeDevLog) {
                           t3lib_div::devLog("do=3, points={$pointsTotal}, max={$maxTotal}", $this->extKey, 0);
                       }
                   } else {
                       if (stristr(',' . $answeredOld . ',', ',' . $answered . ',')) {
                           // Fall 2: somebody tries to cheat!
                           $answered = $answeredOld;
                           // all answered questions
                           $skipped = $skippedOld;
                           // all skipped questions
                           $pointsTotal = $pointsOld;
                           // total points
                           $maxTotal = $maxPointsOld;
                           if ($back > 0) {
                               $doUpdate = 1;
                               // back-seite: update mit alten daten
                           } else {
                               $doUpdate = 2;
                               $error = true;
                               $markerArray["###CHEATING###"] = $this->pi_getLL('cheating', 'cheating');
                               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_CHEATING###");
                               $markerArrayP["###REF_RES_ERRORS###"] .= $this->cObj->substituteMarkerArray($template, $markerArray);
                               if ($this->helperObj->writeDevLog) {
                                   t3lib_div::devLog("Cheating error!", $this->extKey, 0);
                               }
                               /*$tempTime = $this->helperObj->getPageTime($quizData['qtuid']);
                                 if ($tempTime) {
                                     $markerArrayP["###VAR_NOW###"] = $markerArray["###VAR_NOW###"] = $tempTime;
                                 }*/
                           }
                           if ($this->helperObj->writeDevLog) {
                               t3lib_div::devLog("do=2, points={$pointsTotal}, max={$maxTotal}", $this->extKey, 0);
                           }
                       } else {
                           if ($answeredOld) {
                               // Fall 3: man hat schon was beantwortet
                               $answered = $answeredOld . ',' . $answered;
                               // all answered questions
                               if ($skippedOld && $skipped) {
                                   $skipped = $skippedOld . ',' . $skipped;
                               } else {
                                   if ($skippedOld) {
                                       $skipped = $skippedOld;
                                   }
                               }
                               $pointsTotal = $points + $pointsOld;
                               // total points
                               //$maxTotal = $maxPoints;
                               if ($maxPointsOld > 0) {
                                   $maxTotal += $maxPointsOld;
                               }
                               $doUpdate = 1;
                               if ($this->helperObj->writeDevLog) {
                                   t3lib_div::devLog("do=1, points={$pointsTotal}, max={$maxTotal}", $this->extKey, 0);
                               }
                           } else {
                               if ($skippedOld) {
                                   // Fall 4: skipped, dann beantwortet
                                   if ($skippedOld && $skipped) {
                                       $skipped = $skippedOld . ',' . $skipped;
                                   } else {
                                       $skipped = $skippedOld;
                                   }
                                   $pointsTotal = $points;
                                   // total points
                                   $doUpdate = 1;
                               }
                           }
                       }
                   }
               }
           }
           $whereAnswered = '';
           if ($answered) {
               $whereAnswered = ' AND uid NOT IN (' . preg_replace('/[^0-9,]/', '', $answered) . ')';
           }
           // exclude answered questions next time
           $whereSkipped = '';
           if ($skipped) {
               $whereSkipped = ' AND uid NOT IN (' . preg_replace('/[^0-9,]/', '', $skipped) . ')';
           }
           // exclude skipped questions next time
           if ($skippedCount > 0) {
               $markerArray["###VAR_NO###"] = $skippedCount;
               $markerArray["###SKIPPED###"] = $this->pi_getLL('skipped', 'skipped');
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_SKIPPED###");
               $markerArrayP["###REF_SKIPPED###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
               // instead $content
           }
           //} else
           if (!$this->conf['pageQuestions']) {
               if ($this->conf['highscore.']['showAtFinal']) {
                   $quizData['cmd'] = 'score';
               } else {
                   $quizData['cmd'] = 'nix';
               }
               // keine neuen Fragen...
           } else {
               if ($this->conf['isPoll'] && !$nextCat) {
                   $quizData['cmd'] = 'list';
               }
           }
           $markerArray["###VAR_QUESTIONS_ANSWERED###"] = $answered ? substr_count($answered, ',') + 1 : 0;
           if ($falseAnsw || $correctAnsw) {
               $markerArray["###VAR_QUESTIONS_CORRECT###"] = $correctAnsw ? substr_count($correctAnsw, ',') + 1 : 0;
               $markerArray["###VAR_QUESTIONS_FALSE###"] = $falseAnsw ? substr_count($falseAnsw, ',') + 1 : 0;
           }
           if ($this->conf['dontShowPoints'] != 1 && !$this->conf['isPoll']) {
               // Total points yet. && !$this->conf['dontShowCorrectAnswers'] ??
               $markerArray["###RESULT_POINTS###"] = $this->pi_getLL('result_points', 'result_points');
               $markerArray["###TOTAL_POINTS###"] = $this->pi_getLL('total_points', 'total_points');
               $markerArray["###SO_FAR_REACHED1###"] = $this->pi_getLL('so_far_reached1', 'so_far_reached1');
               $markerArray["###SO_FAR_REACHED2###"] = $this->pi_getLL('so_far_reached2', 'so_far_reached2');
               $markerArray["###VAR_RESULT_POINTS###"] = $points;
               $markerArray["###VAR_MAX_POINTS###"] = $maxPoints;
               $markerArray["###VAR_MISSING_POINTS###"] = $maxPoints - $points;
               $markerArray["###VAR_TOTAL_POINTS###"] = $pointsTotal;
               $markerArray["###VAR_TMAX_POINTS###"] = $maxTotal;
               $markerArray["###VAR_TMISSING_POINTS###"] = $maxTotal - $pointsTotal;
               if ($maxTotal > 0) {
                   $percent = intval(round(100 * $pointsTotal / $maxTotal));
               }
               $markerArray["###VAR_PERCENT###"] = $percent;
               $overallMaximum = $markerArray["###VAR_OMAX_POINTS###"];
               if ($overallMaximum) {
                   $overallPercent = 100 * $pointsTotal / $overallMaximum;
                   $markerArray["###VAR_OVERALL_PERCENT###"] = intval(round($overallPercent));
                   //$markerArray["###VAR_OMAX_POINTS###"] = $overallMaximum;
               }
               if ($doUpdate == 0) {
                   $overallMaximum = $this->helperObj->getQuestionsMaxPoints();
                   // maximum points of all questions
                   if ($overallMaximum > 0) {
                       $overallPercent = 100 * $markerArray["###VAR_TOTAL_POINTS###"] / $overallMaximum;
                   }
                   $markerArray["###VAR_OVERALL_PERCENT###"] = intval(round($overallPercent));
                   $markerArray["###VAR_OMAX_POINTS###"] = $overallMaximum;
                   $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_RESULT_POINTS###");
               } else {
                   $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_RESULT_POINTS_TOTAL###");
               }
               $markerArrayP["###REF_QPOINTS###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
               // instead $content
           }
           if ($this->conf['startCategory'] && $nextCat) {
               //  && $this->conf['pageQuestions']==1
               $this->conf['startCategory'] = $nextCat;
               // kategorie der naechsten frage
           }
           // myVars for page
           $markerArrayP = array_merge($markerArrayP, $this->helperObj->setPageVars());
           if ($points == '') {
               $points = 0;
           }
           if ($pointsTotal == '') {
               $pointsTotal = 0;
           }
           $hidden = intval($quizData["hidden"]);
           if ($doUpdate == 0 && ($points > 0 || !$this->conf['isPoll'])) {
               // Insert new results into database
               $timestamp = time();
               $firsttime = intval($quizData["time"]);
               $insert = array('pid' => $resPID, 'tstamp' => $timestamp, 'crdate' => $timestamp, 'hidden' => $hidden, 'ip' => $quiz_taker_ip_address, 'sys_language_uid' => $this->lang);
               if (!$this->conf['isPoll']) {
                   $insert['joker1'] = $joker1 = intval($quizData["joker1"]);
                   $insert['joker2'] = $joker2 = intval($quizData["joker2"]);
                   $insert['joker3'] = $joker3 = intval($quizData["joker3"]);
                   $insert['name'] = $quiz_taker_name;
                   $insert['email'] = $quiz_taker_email;
                   $insert['homepage'] = $quiz_taker_homepage;
                   $insert['p_max'] = $maxPoints;
                   $insert['percent'] = $percent;
                   $insert['o_max'] = $overallMaximum;
                   $insert['o_percent'] = $overallPercent;
                   $insert['cids'] = $correctAnsw;
                   $insert['fids'] = $falseAnsw;
                   $insert['sids'] = $skipped;
                   // Hook for tt_address
                   if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey]['setAdrHook']) && $this->conf['userData.']['tt_address_pid']) {
                       foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey]['setAdrHook'] as $_classRef) {
                           $_procObj =& t3lib_div::getUserObj($_classRef);
                           $markerArray["###VAR_ADDRESS_UID###"] = $quizData["address_uid"] = intval($_procObj->setAdr($quizData, $this->conf['userData.']['tt_address_pid'], $this->conf['userData.']['tt_address_groups']));
                       }
                       $insert['address_uid'] = $quizData["address_uid"];
                   }
               }
               if ($this->tableAnswers == 'tx_myquizpoll_result') {
                   $insert['p_or_a'] = $points;
                   $insert['qids'] = $answered;
                   $insert['firsttime'] = $firsttime;
                   $insert['lasttime'] = $timestamp;
                   $insert['lastcat'] = $lastCat;
                   $insert['nextcat'] = $nextCat;
                   $insert['fe_uid'] = intval($GLOBALS['TSFE']->fe_user->user['uid']);
                   $insert['start_uid'] = intval($quizData["start_uid"]);
               } else {
                   $insert['answer_no'] = $points;
                   $insert['question_id'] = $answered;
               }
               $success = $GLOBALS['TYPO3_DB']->exec_INSERTquery($this->tableAnswers, $insert);
               if ($success) {
                   $quizData['qtuid'] = $GLOBALS['TYPO3_DB']->sql_insert_id();
                   if ($this->tableAnswers == 'tx_myquizpoll_result') {
                       $this->helperObj->setStartUid($quizData['qtuid'], intval($quizData["start_uid"]));
                   }
                   if ($this->conf['useCookiesInDays']) {
                       // save quiz takers UID as cookie?
                       $cookieName = $this->getCookieMode($resPID, $thePID);
                       //if (!($this->conf['isPoll'] && $_COOKIE[$cookieName])) {    // bein Umfragen Cookie nicht ueberschreiben...
                       if (intval($this->conf['useCookiesInDays']) == -1) {
                           $periode = 0;
                       } else {
                           $periode = time() + 3600 * 24 * intval($this->conf['useCookiesInDays']);
                       }
                       setcookie($cookieName, $quizData['qtuid'], $periode);
                       /* cookie for x days */
                       if ($this->helperObj->writeDevLog) {
                           t3lib_div::devLog('Storing Cookie: ' . $cookieName . '=' . $quizData['qtuid'] . ', period=' . $periode, $this->extKey, 0);
                       }
                       //}
                   }
                   $this->helperObj->setFirstTime($quizData['qtuid'], $firsttime);
               } else {
                   $content .= "<p>MySQL Insert-Error for table " . $this->tableAnswers . " :-(</p>";
               }
           } else {
               if ($doUpdate == 1) {
                   // update current user entry
                   $uid = intval($quizData['qtuid']);
                   $timestamp = time();
                   $update = array('tstamp' => $timestamp, 'hidden' => $hidden, 'name' => $quiz_taker_name, 'email' => $quiz_taker_email, 'homepage' => $quiz_taker_homepage, 'p_or_a' => $pointsTotal, 'p_max' => $maxTotal, 'percent' => $percent, 'o_percent' => $overallPercent, 'qids' => $answered, 'cids' => $correctAnsw, 'fids' => $falseAnsw, 'sids' => $skipped, 'lastcat' => $lastCat, 'nextcat' => $nextCat, 'lasttime' => $timestamp);
                   $success = $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->tableAnswers, 'uid=' . $uid . ' AND sys_language_uid=' . $this->lang, $update);
                   if (!$success) {
                       $content .= "<p>MySQL Update-Error :-(</p>";
                   }
               } else {
                   if ($doUpdate == 3) {
                       // update current skipped entry (only skipped questions?!?!)
                       $uid = intval($quizData['qtuid']);
                       $timestamp = time();
                       $update = array('tstamp' => $timestamp, 'hidden' => $hidden, 'sids' => $skipped, 'lasttime' => $timestamp);
                       $success = $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->tableAnswers, 'uid=' . $uid . ' AND sys_language_uid=' . $this->lang, $update);
                       if (!$success) {
                           $content .= "<p>MySQL Update-Error :-(</p>";
                       }
                   }
               }
           }
           $markerArray["###QTUID###"] = intval($quizData["qtuid"]);
           if ($this->conf['isPoll']) {
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_POLL_SUBMITED###");
               // Output thank you
               $markerArray['###QUESTION_NAME###'] = $this->pi_getLL('poll_question', 'poll_question');
               $markerArray['###USER_ANSWER###'] = $this->pi_getLL('poll_answer', 'poll_answer');
               $markerArrayP["###REF_INTRODUCTION###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
               // instead $content
           } else {
               if ($this->conf['userData.']['showAtAnswer']) {
                   $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_USER_SUBMITED###");
                   // Output the user name
                   $markerArrayP["###REF_INTRODUCTION###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
                   // instead $content
               }
           }
           if ($this->conf['advancedStatistics'] && $doUpdate < 2) {
               // write advanced Statistics to database
               $uid = intval($quizData['qtuid']);
               $timestamp = time();
               $firsttime = $this->helperObj->getFirstTime($uid);
               if ($this->conf['requireSession']) {
                   $where_time = ' AND crdate=' . $firsttime;
               } else {
                   $where_time = '';
               }
               if (is_array($statisticsArray)) {
                   foreach ($statisticsArray as $type => $element) {
                       // delete old entry in back-mode
                       if ($back > 0) {
                           $GLOBALS['TYPO3_DB']->exec_DELETEquery($this->tableRelation, "pid={$resPID} AND user_id={$uid} AND question_id={$type} {$where_time} AND sys_language_uid=" . $this->lang);
                       }
                       $insert = array('pid' => $resPID, 'tstamp' => $timestamp, 'crdate' => $firsttime, 'hidden' => $hidden, 'user_id' => $uid, 'question_id' => $type, 'textinput' => $element['text'], 'points' => $element['points'] ? $element['points'] : 0, 'nextcat' => $element['nextCat'] ? $element['nextCat'] : 0, 'sys_language_uid' => $this->lang);
                       //$array2=array();
                       for ($answerNumber = 1; $answerNumber < $this->answerChoiceMax + 1; $answerNumber++) {
                           $insert['checked' . $answerNumber] = $element['a' . $answerNumber] ? 1 : 0;
                       }
                       //$insert = array_merge($array1, $array2);
                       $GLOBALS['TYPO3_DB']->exec_INSERTquery($this->tableRelation, $insert);
                   }
               }
           }
           if (!$this->conf['pageQuestions'] && !$this->conf['isPoll']) {
               $finalPage = true;
           }
           $answerPage = true;
           if ($back) {
               $back--;
           }
       }
       if ($this->conf['finishedMinPercent'] && $this->conf['pageQuestions'] > 0 && $markerArray["###VAR_TOTAL_POINTS###"] !== '' && (!$this->conf['showAnswersSeparate'] || !$quizData['cmd']) && $no_rights == 0) {
           /* ***************************************************** */
           /*
            * Display positive cancel page: quiz taker has reached finishedMinPercent percent???
            */
           if ($markerArray["###VAR_OMAX_POINTS###"]) {
               $myPercent = 100 * $markerArray["###VAR_TOTAL_POINTS###"] / $markerArray["###VAR_OMAX_POINTS###"];
           } else {
               $myPercent = 0;
           }
           $uidP = 0;
           $finishedMinPercent = $this->conf['finishedMinPercent'];
           if (strpos($finishedMinPercent, ':') !== false) {
               list($finishedMinPercent, $uidP) = explode(":", $finishedMinPercent);
           }
           if (intval($finishedMinPercent) <= $myPercent) {
               // do we have enough points???
               if ($uidP) {
                   // redirect to a URL with that UID?
                   $this->redirectUrl($uidP, array());
               }
               $markerArray["###REACHED1###"] = $this->pi_getLL('reached1', 'reached1');
               $markerArray["###REACHED2###"] = $this->pi_getLL('reached2', 'reached2');
               $markerArray["###SO_FAR_REACHED1###"] = $this->pi_getLL('so_far_reached1', 'so_far_reached1');
               $markerArray["###SO_FAR_REACHED2###"] = $this->pi_getLL('so_far_reached2', 'so_far_reached2');
               //$markerArray["###VAR_OVERALL_PERCENT###"] = intval($myPercent);
               //$markerArray["###VAR_OMAX_POINTS###"] = $overallMaximum;
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_FINISHEDMINPERCENT###");
               if ($template == '') {
                   // if it is not in the template
                   $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_QUIZ_FINISHEDMINPERCENT###");
               }
               $content .= $this->cObj->substituteMarkerArray($template, $markerArray);
               // sonderfall !!!!!!!!!
               $answerPage = false;
               if ($this->conf['highscore.']['showAtFinal']) {
                   $quizData['cmd'] = 'score';
                   // show highscore
               } else {
                   $quizData['cmd'] = 'exit';
                   // display no more questions
               }
           }
       }
       if ($this->conf['cancelWhenWrong'] && $this->conf['pageQuestions'] > 0 && $markerArray["###VAR_TOTAL_POINTS###"] !== '' && (!$this->conf['showAnswersSeparate'] || !$quizData['cmd']) && $no_rights == 0) {
           /* ***************************************************** */
           /*
            * Display negative cancel page: quiz taker has given a wrong answer???
            */
           if ($markerArray["###VAR_TOTAL_POINTS###"] < $markerArray["###VAR_TMAX_POINTS###"]) {
               $markerArray["###REACHED1###"] = $this->pi_getLL('reached1', 'reached1');
               $markerArray["###REACHED2###"] = $this->pi_getLL('reached2', 'reached2');
               $markerArray["###SO_FAR_REACHED1###"] = $this->pi_getLL('so_far_reached1', 'so_far_reached1');
               $markerArray["###SO_FAR_REACHED2###"] = $this->pi_getLL('so_far_reached2', 'so_far_reached2');
               $markerArray["###QUIZ_END###"] = $this->pi_getLL('quiz_end', 'quiz_end');
               $markerArray["###RESTART_QUIZ###"] = $this->pi_linkToPage($this->pi_getLL('restart_quiz', 'restart_quiz'), $startPID, $target = '', array());
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_END###");
               if ($template == '') {
                   // if it is not in the template
                   $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_QUIZ_END###");
               }
               $content .= $this->cObj->substituteMarkerArray($template, $markerArray);
               // sonderfall !!!
               $answerPage = false;
               // show no answers
               if ($this->conf['finalWhenCancel']) {
                   $noQuestions = true;
               } else {
                   if ($this->conf['highscore.']['showAtFinal']) {
                       $quizData['cmd'] = 'score';
                       // show highscore
                   } else {
                       $quizData['cmd'] = 'exit';
                       // display no more questions
                   }
                   $no_rights = 1;
                   // cancel all
               }
           }
       }
       // Pre-fill quiz taker name and email if FE user logged in
       if ($GLOBALS['TSFE']->loginUser) {
           if (!$quizData["name"]) {
               $field = $this->conf['fe_usersName'];
               if (!$field) {
                   $field = 'name';
               }
               $quizData["name"] = $GLOBALS['TSFE']->fe_user->user[$field];
           }
           if (!$quizData["email"]) {
               $quizData["email"] = $GLOBALS['TSFE']->fe_user->user['email'];
           }
           if (!$quizData["homepage"]) {
               $quizData["homepage"] = $GLOBALS['TSFE']->fe_user->user['www'];
           }
       }
       if ($quizData["name"]) {
           $markerArray["###DEFAULT_NAME###"] = htmlspecialchars($quizData["name"]);
       } else {
           $markerArray["###DEFAULT_NAME###"] = $this->pi_getLL('no_name', 'no_name');
       }
       if ($quizData["email"]) {
           $markerArray["###DEFAULT_EMAIL###"] = htmlspecialchars($quizData["email"]);
       } else {
           $markerArray["###DEFAULT_EMAIL###"] = $this->pi_getLL('no_email', 'no_email');
       }
       if ($quizData["homepage"]) {
           $markerArray["###DEFAULT_HOMEPAGE###"] = htmlspecialchars($quizData["homepage"]);
       } else {
           $markerArray["###DEFAULT_HOMEPAGE###"] = $this->pi_getLL('no_homepage', 'no_homepage');
       }
       $markerArray["###HIDE_ME###"] = $this->pi_getLL('hide_me', 'hide_me');
       $markerArray["###VISIBILITY###"] = $this->pi_getLL('visibility', 'visibility');
       // TODO: warum nur?
       // UID loeschen bei Umfragen
       if ($this->conf['isPoll']) {
           $quizData['qtuid'] = '';
       }
       if ($this->helperObj->writeDevLog) {
           t3lib_div::devLog('Next cmd: ' . $quizData['cmd'] . ', answer-page: ' . $answerPage . ', final-page: ' . $finalPage, $this->extKey, 0);
       }
       if ($quizData['cmd'] == '' && $no_rights == 0) {
           /* ***************************************************** */
           /*
            * Display initial page: questions and quiz taker name fields
            */
           $oldRelData = array();
           if ($this->conf['allowBack'] && $this->conf['pageQuestions'] && $quizData['qtuid'] && $back > 0) {
               $where = '';
               $where_rel = '';
               $where_time = '';
               $uid = intval($quizData['qtuid']);
               if ($this->conf['requireSession']) {
                   $where_time = ' AND firsttime=' . $this->helperObj->getFirstTime($uid);
               }
               $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('name,email,homepage,qids', $this->tableAnswers, "uid={$uid} {$where_time} AND sys_language_uid=" . $this->lang);
               //.' '.$this->cObj->enableFields($this->tableAnswers));
               $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
               if ($rows > 0) {
                   $fetchedRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5);
                   $qids = explode(',', $fetchedRow['qids']);
                   $bisher = count($qids);
                   $seiten = round($bisher / $this->conf['pageQuestions']);
                   $seite = $seiten - $back + 1;
                   for ($k = 0; $k < $bisher; $k++) {
                       if (ceil(($k + 1) / $this->conf['pageQuestions']) == $seite) {
                           $where .= $qids[$k] . ',';
                       }
                   }
                   if ($where) {
                       $where = ' AND uid IN (' . preg_replace('/[^0-9,]/', '', rtrim($where, ',')) . ')';
                       $where_rel = ' AND user_id IN (' . preg_replace('/[^0-9,]/', '', rtrim($where, ',')) . ')';
                   }
                   $quizData["name"] = $fetchedRow['name'];
                   $quizData["email"] = $fetchedRow['email'];
                   $quizData["homepage"] = $fetchedRow['homepage'];
                   if ($quizData["name"]) {
                       $markerArray["###DEFAULT_NAME###"] = htmlspecialchars($quizData["name"]);
                   } else {
                       $markerArray["###DEFAULT_NAME###"] = $this->pi_getLL('no_name', 'no_name');
                   }
                   if ($quizData["email"]) {
                       $markerArray["###DEFAULT_EMAIL###"] = htmlspecialchars($quizData["email"]);
                   } else {
                       $markerArray["###DEFAULT_EMAIL###"] = $this->pi_getLL('no_email', 'no_email');
                   }
                   if ($quizData["homepage"]) {
                       $markerArray["###DEFAULT_HOMEPAGE###"] = htmlspecialchars($quizData["homepage"]);
                   } else {
                       $markerArray["###DEFAULT_HOMEPAGE###"] = $this->pi_getLL('no_homepage', 'no_homepage');
                   }
               }
               $GLOBALS['TYPO3_DB']->sql_free_result($res5);
               $sortBy = $this->getSortBy();
               $questionsArray = array();
               $questionNumber = 0;
               if ($where) {
                   $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->tableQuestions, 'pid IN (' . $thePID . ')' . $where . ' AND sys_language_uid=' . $this->lang . ' ' . $this->cObj->enableFields($this->tableQuestions), '', $sortBy);
                   $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
                   if ($this->helperObj->writeDevLog) {
                       t3lib_div::devLog($rows . ' rows selected with: pid IN (' . $thePID . ')' . $where . ' AND sys_language_uid=' . $this->lang, $this->extKey, 0);
                   }
                   if ($rows > 0) {
                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5)) {
                           $questionNumber++;
                           $questionsArray[$questionNumber] = $row;
                       }
                   }
                   $GLOBALS['TYPO3_DB']->sql_free_result($res5);
               }
               $numOfQuestions = $questionNumber;
               $maxQuestions = $numOfQuestions;
               // bisherige Antworten noch holen
               if ($where_rel) {
                   if ($this->conf['requireSession']) {
                       $where_time = ' AND crdate=' . $this->helperObj->getFirstTime($uid);
                   }
                   $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->tableRelation, "pid={$resPID} AND user_id={$uid} {$where_time} AND sys_language_uid=" . $this->lang);
                   $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
                   if ($rows > 0) {
                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5)) {
                           $temp_qid = $row['question_id'];
                           $oldRelData[$temp_qid] = array();
                           $oldRelData[$temp_qid]['textinput'] = $row['textinput'];
                           for ($j = 1; $j <= $this->answerChoiceMax; $j++) {
                               $oldRelData[$temp_qid]['checked' . $j] = $row['checked' . $j];
                           }
                       }
                   }
                   $GLOBALS['TYPO3_DB']->sql_free_result($res5);
               }
               //print_r($oldRelData);
           } elseif (!$noQuestions) {
               // Order questions by & and limit to
               $limitTo = '';
               $whereCat = '';
               $sortBy = $this->getSortBy();
               // Limit questions?
               if ($this->conf['pageQuestions'] > 0 && $this->conf['sortBy'] != 'random') {
                   $limitTo = preg_replace('/[^0-9,]/', '', $this->conf['pageQuestions']);
               }
               // category
               if ($this->conf['startCategory']) {
                   $whereCat = " AND category=" . intval($this->conf['startCategory']);
               } else {
                   if ($this->conf['onlyCategories']) {
                       $whereCat = " AND category IN (" . preg_replace('/[^0-9,]/', '', $this->conf['onlyCategories']) . ")";
                   }
               }
               // Get questions from the database
               $questionsArray = array();
               $questionNumber = 0;
               $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->tableQuestions, 'pid IN (' . $thePID . ')' . $whereCat . $whereAnswered . $whereSkipped . ' AND sys_language_uid=' . $this->lang . ' ' . $this->cObj->enableFields($this->tableQuestions), '', $sortBy, $limitTo);
               $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
               if (!$rows && $whereSkipped) {
                   // now ignore the skipped questions
                   $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->tableQuestions, 'pid IN (' . $thePID . ')' . $whereCat . $whereAnswered . ' AND sys_language_uid=' . $this->lang . ' ' . $this->cObj->enableFields($this->tableQuestions), '', $sortBy, $limitTo);
                   $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
               }
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog($rows . ' rows selected with: pid IN (' . $thePID . ')' . $whereCat . $whereAnswered . ' AND sys_language_uid=' . $this->lang, $this->extKey, 0);
               }
               if ($rows > 0) {
                   while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5)) {
                       $questionNumber++;
                       $questionsArray[$questionNumber] = $row;
                   }
               }
               $numOfQuestions = $questionNumber;
               // real questions
               $maxQuestions = $this->conf['pageQuestions'];
               // should be questions
               if ($this->conf['isPoll']) {
                   $maxQuestions = 1;
                   // only max. 1 poll-question
               } else {
                   if (!$maxQuestions) {
                       $maxQuestions = $numOfQuestions;
                   } else {
                       if ($numOfQuestions < $maxQuestions) {
                           $maxQuestions = $numOfQuestions;
                           // no. of maximum question = no. of questions in the DB
                       }
                   }
               }
               if ($numOfQuestions > 0 and $this->conf['sortBy'] == 'random') {
                   // any questions out there???    Random questions???
                   $randomQuestionsArray = array();
                   $questionNumber = 0;
                   $versuche = 0;
                   // Not very fast random method
                   while ($questionNumber < $maxQuestions) {
                       // alle Fragen durchgehen
                       $random = mt_rand(1, $numOfQuestions);
                       $randomQuestionsArray[$questionNumber + 1] = $questionsArray[$random];
                       // eine Frage uebernehmen
                       $duplicate = 0;
                       for ($i = 1; $i < $questionNumber + 1; $i++) {
                           if ($randomQuestionsArray[$questionNumber + 1]['uid'] == $randomQuestionsArray[$i]['uid']) {
                               $duplicate = 1;
                               // doch nicht uebernehmen
                           }
                           if (!$duplicate && $this->conf['randomCategories'] && $versuche < 5 * $maxQuestions && $randomQuestionsArray[$questionNumber + 1]['category'] == $randomQuestionsArray[$i]['category']) {
                               $duplicate = 1;
                               // doch nicht uebernehmen
                           }
                       }
                       if (!$duplicate) {
                           $questionNumber++;
                       }
                       $versuche++;
                   }
                   // rearange questions Array
                   for ($questionNumber = 1; $questionNumber < $maxQuestions + 1; $questionNumber++) {
                       $questionsArray[$questionNumber] = $randomQuestionsArray[$questionNumber];
                   }
               }
               if ($this->conf['finishAfterQuestions']) {
                   // finish after X questions?
                   $numOfQuestions = intval($this->conf['finishAfterQuestions']) - $this->helperObj->getQuestionNo($whereAnswered);
                   if ($numOfQuestions < $maxQuestions) {
                       $maxQuestions = $numOfQuestions;
                       // no. of maximum question = no. of questions in the DB
                   }
               }
           } else {
               $numOfQuestions = 0;
           }
           if ($numOfQuestions > 0) {
               // any questions out there???
               // Start des Output
               $lastUID = 0;
               // remember the last question ID
               $pageTimeCat = 0;
               // time per page from a category
               $questTillNow = 0;
               // no. of questions answered till now
               $imgTSConfig = array();
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUESTION###");
               $template_image_begin = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUESTION_IMAGE_BEGIN###");
               $template_image_end = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUESTION_IMAGE_END###");
               $template_answer = $this->cObj->getSubpart($template, "###TEMPLATE_QUESTION_ANSWER###");
               $template_delimiter = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_DELIMITER###");
               if (!$this->conf['isPoll']) {
                   $markerArray["###VAR_QUESTIONS###"] = $this->helperObj->getQuestionsNo();
                   if ($back && $seite) {
                       $markerArray["###VAR_QUESTION###"] = $questTillNow = ($seite - 1) * $this->conf['pageQuestions'];
                   } else {
                       $markerArray["###VAR_QUESTION###"] = $questTillNow = $this->helperObj->getQuestionNo($whereAnswered);
                   }
               }
               // Questions and answers
               for ($questionNumber = 1; $questionNumber < $maxQuestions + 1; $questionNumber++) {
                   $row = $questionsArray[$questionNumber];
                   $quid = $row['uid'];
                   $markerArray["###VAR_QUESTION_NUMBER###"] = $questionNumber;
                   $answerPointsBool = false;
                   // gibt es punkte bei einzelnen antworten?
                   $markerArray["###VAR_QUESTION###"]++;
                   if ($row['image']) {
                       $markerArray["###VAR_QUESTION_IMAGE###"] = $this->helperObj->getImage($row['image'], $row["alt_text"]);
                       $markerArray["###REF_QUESTION_IMAGE_BEGIN###"] = $this->cObj->substituteMarkerArray($template_image_begin, $markerArray);
                       $markerArray["###REF_QUESTION_IMAGE_END###"] = $template_image_end;
                   } else {
                       $markerArray["###REF_QUESTION_IMAGE_BEGIN###"] = '';
                       $markerArray["###REF_QUESTION_IMAGE_END###"] = '';
                   }
                   $markerArray["###VAR_QUESTION_TYPE###"] = $row['qtype'];
                   $markerArray["###TITLE_HIDE###"] = $row['title_hide'] ? '-hide' : '';
                   $markerArray["###VAR_QUESTION_TITLE###"] = $row['title'];
                   $markerArray["###VAR_QUESTION_NAME###"] = $this->formatStr($row['name']);
                   //$this->formatStr($this->local_cObj->stdWrap($row['name'],$this->conf["general_stdWrap."])); //$this->pi_RTEcssText($row['name']);
                   if (!$this->conf['dontShowPoints'] && !$this->conf['isPoll'] && $row['qtype'] < 5) {
                       $markerArray["###VAR_QUESTION_POINTS###"] = 0;
                       if ($markerArray["###VAR_TOTAL_POINTS###"]) {
                           $markerArray["###VAR_NEXT_POINTS###"] = $markerArray["###VAR_TOTAL_POINTS###"];
                       } else {
                           $markerArray["###VAR_NEXT_POINTS###"] = 0;
                       }
                       for ($currentValue = 1; $currentValue <= $this->answerChoiceMax; $currentValue++) {
                           if (intval($row['points' . $currentValue]) > 0) {
                               $answerPointsBool = true;
                               break;
                           }
                       }
                       if ($answerPointsBool) {
                           $markerArray["###VAR_ANSWER_POINTS###"] = $this->pi_getLL('different_number_of', 'different_number_of');
                       } else {
                           if (($row['qtype'] == 0 || $row['qtype'] == 4) && $this->conf['noNegativePoints'] < 3) {
                               $markerArray["###VAR_ANSWER_POINTS###"] = $this->pi_getLL('each', 'each') . ' ' . $row['points'];
                           } else {
                               $markerArray["###VAR_ANSWER_POINTS###"] = $row['points'];
                           }
                       }
                       $markerArray["###P1###"] = $this->pi_getLL('p1', 'p1');
                       $markerArray["###P2###"] = $this->pi_getLL('p2', 'p2');
                   } else {
                       $markerArray["###VAR_ANSWER_POINTS###"] = '';
                       $markerArray["###VAR_QUESTION_POINTS###"] = '';
                       $markerArray["###VAR_NEXT_POINTS###"] = '';
                       $markerArray["###P1###"] = '';
                       $markerArray["###P2###"] = '';
                   }
                   $markerArray["###REF_QUESTION_ANSWER###"] = '';
                   if ($row['qtype'] == 2) {
                       $input_id = $this->conf['myVars.']['answers.']['input_id'] ? ' id="answer' . $questionNumber . '"' : '';
                       if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                           $input_id .= ' class="form-control"';
                       }
                       $markerArrayQ["###VAR_QUESTION_ANSWER###"] = '<select name="tx_myquizpoll_pi1[answer' . $questionNumber . ']" ###MY_SELECT###' . $input_id . '>' . "\n";
                       //  class="'.$this->prefixId.'-answer"
                   }
                   // my Variables of questions
                   $markerArray["###MY_SELECT###"] = '';
                   $markerArray = array_merge($markerArray, $this->helperObj->setQuestionVars($questionNumber));
                   // Jokers
                   if ($this->conf['useJokers'] && $this->conf['pageQuestions'] == 1) {
                       $temp_uid = intval($quizData['qtuid']);
                       $markerArrayJ["###JAVASCRIPT###"] = '';
                       $markerArrayJ["###JOKER_50###"] = $this->pi_getLL('joker_50', 'joker_50');
                       $markerArrayJ["###JOKER_AUDIENCE###"] = $this->pi_getLL('joker_audience', 'joker_audience');
                       $markerArrayJ["###JOKER_PHONE###"] = $this->pi_getLL('joker_phone', 'joker_phone');
                       if (is_array($this->conf['jokers.'])) {
                           $unlimited = $this->conf['jokers.']['unlimited'];
                       } else {
                           $unlimited = 0;
                       }
                       if ($joker1 && !$unlimited) {
                           $markerArrayJ["###JOKER_50_LINK###"] = '';
                           $markerArrayJ["###JAVASCRIPT###"] .= "document.getElementById('" . $this->prefixId . "-joker_50').style.display = 'none';\n";
                       } else {
                           $markerArrayJ["###JOKER_50_LINK###"] = $this->prefixId . 'getAjaxData(' . $quid . ',' . $temp_uid . ',1,\'joker_50\');';
                       }
                       if ($joker2 && !$unlimited) {
                           $markerArrayJ["###JOKER_AUDIENCE_LINK###"] = '';
                           $markerArrayJ["###JAVASCRIPT###"] .= "document.getElementById('" . $this->prefixId . "-joker_audience').style.display = 'none';\n";
                       } else {
                           $markerArrayJ["###JOKER_AUDIENCE_LINK###"] = $this->prefixId . 'getAjaxData(' . $quid . ',' . $temp_uid . ',2,\'joker_audience\');';
                       }
                       if ($joker3 && !$unlimited) {
                           $markerArrayJ["###JOKER_PHONE_LINK###"] = '';
                           $markerArrayJ["###JAVASCRIPT###"] .= "document.getElementById('" . $this->prefixId . "-joker_phone').style.display = 'none';\n";
                       } else {
                           $markerArrayJ["###JOKER_PHONE_LINK###"] = $this->prefixId . 'getAjaxData(' . $quid . ',' . $temp_uid . ',3,\'joker_phone\');';
                       }
                       $template_jokers = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_JOKERS###");
                       $markerArrayP["###REF_JOKERS###"] = $this->cObj->substituteMarkerArray($template_jokers, $markerArrayJ);
                   }
                   // Daten zur aktuellen und nächsten Kategorie
                   $thisCat = $row['category'];
                   if ($this->catArray[$thisCat]) {
                       $markerArray["###VAR_CATEGORY###"] = $this->catArray[$thisCat]['name'];
                       $pageTimeCat = $this->catArray[$thisCat]['pagetime'];
                   }
                   $thisCat = $row['category_next'];
                   if ($this->catArray[$thisCat]) {
                       $markerArray["###VAR_NEXT_CATEGORY###"] = $this->catArray[$thisCat]['name'];
                   }
                   // Display answers
                   $answers = 0;
                   $radmonArray = array();
                   for ($answerNumber = 1; $answerNumber <= $this->answerChoiceMax; $answerNumber++) {
                       $text_type = in_array($row['qtype'], $this->textType);
                       // Answers in random order?
                       if ($this->conf['mixAnswers'] && !$text_type) {
                           $currentValue = 0;
                           $leer = 0;
                           while ($currentValue == 0 && $leer < 33) {
                               $random = mt_rand(1, $this->answerChoiceMax);
                               if (($row['answer' . $random] || $row['answer' . $random] === '0') && !in_array($random, $radmonArray)) {
                                   $radmonArray[] = $random;
                                   $currentValue = $random;
                               } else {
                                   $leer++;
                               }
                           }
                       } else {
                           $currentValue = $answerNumber;
                       }
                       if (!$text_type && ($row['answer' . $currentValue] || $row['answer' . $currentValue] === '0') || $text_type && $answerNumber == 1) {
                           $answers++;
                           $input_id = '';
                           $input_label1 = '';
                           $input_label2 = '';
                           // my Variables for answers
                           $markerArrayQ["###MY_OPTION###"] = '';
                           $markerArrayQ["###MY_INPUT_RADIO###"] = '';
                           $markerArrayQ["###MY_INPUT_CHECKBOX###"] = '';
                           $markerArrayQ["###MY_INPUT_TEXT###"] = '';
                           $markerArrayQ["###MY_INPUT_AREA###"] = '';
                           $markerArrayQ["###MY_INPUT_WRAP###"] = '';
                           $markerArrayQ = array_merge($markerArrayQ, $this->helperObj->setAnswerVars($answerNumber, $row['qtype']));
                           $markerArrayQ["###VAR_QA_NR###"] = $currentValue;
                           if ($row['qtype'] < 3 || $row['qtype'] == 4 || $row['qtype'] == 7) {
                               //$answer_choice = $this->formatStr($row['answer'.$currentValue]);    // Problem: <tt> geht hier verloren!
                               $answer_choice = $this->conf['general_stdWrap.']['notForAnswers'] ? $row['answer' . $currentValue] : $this->formatStr($row['answer' . $currentValue]);
                               if ($row['qtype'] != 2 && !(strpos($markerArrayQ["###MY_INPUT_WRAP###"], '|') === false)) {
                                   $answer_choice = str_replace('|', $answer_choice, $markerArrayQ["###MY_INPUT_WRAP###"]);
                               }
                           }
                           // Questtion type
                           if ($row['qtype'] == 1) {
                               // radio-button
                               if ($markerArrayQ["###MY_INPUT_ID###"]) {
                                   $input_id = 'id="answer' . $questionNumber . '_' . $answerNumber . '"';
                               }
                               if ($markerArrayQ["###MY_INPUT_LABEL###"]) {
                                   if ($markerArrayQ["###MY_INPUT_LABEL###"] == 3) {
                                       $class_label = ' class="radio"';
                                   } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 4) {
                                       $class_label = ' class="radio inline"';
                                   } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 6) {
                                       $class_label = ' class="radio-inline"';
                                   } else {
                                       $class_label = '';
                                   }
                                   if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                                       $label_wrap1 = '<div class="radio">';
                                       $label_wrap2 = '</div>';
                                   } else {
                                       $label_wrap1 = '';
                                       $label_wrap2 = '';
                                   }
                                   $input_label1 = $label_wrap1 . '<label for="answer' . $questionNumber . '_' . $answerNumber . '"' . $class_label . '>';
                                   $input_label2 = '</label>' . $label_wrap2;
                               }
                               $answer_content = '<input type="radio" name="tx_myquizpoll_pi1[answer' . $questionNumber . ']" value="' . $currentValue . '" ' . $input_id . ' ###MY_INPUT_RADIO###';
                               if (is_array($oldRelData[$quid]) && $oldRelData[$quid]['checked' . $currentValue]) {
                                   $answer_content .= ' checked="checked"';
                               } elseif ($captchaError && $quizData['answer' . $questionNumber] == $currentValue) {
                                   $answer_content .= ' checked="checked"';
                               }
                               $answer_content .= ' /> ';
                           } else {
                               if ($row['qtype'] == 2) {
                                   // select-box
                                   $answer_content = '<option value="' . $currentValue . '" ###MY_OPTION###';
                                   if (is_array($oldRelData[$quid]) && $oldRelData[$quid]['checked' . $currentValue]) {
                                       $answer_content .= ' selected="selected"';
                                   } elseif ($captchaError && $quizData['answer' . $questionNumber] == $currentValue) {
                                       $answer_content .= ' selected="selected"';
                                   }
                                   $answer_content .= '> ';
                               } else {
                                   if ($row['qtype'] == 3) {
                                       // input-text
                                       if ($markerArrayQ["###MY_INPUT_ID###"]) {
                                           $input_id = 'id="answer' . $questionNumber . '"';
                                       }
                                       if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                                           $input_id .= ' class="form-control"';
                                       }
                                       if (is_array($oldRelData[$quid])) {
                                           $value = $oldRelData[$quid]['textinput'];
                                       } else {
                                           if ($captchaError) {
                                               $value = $quizData['answer' . $questionNumber];
                                           } else {
                                               if ($row['answer2'] || $row['answer2'] === '0') {
                                                   $value = $row['answer2'];
                                               } else {
                                                   $value = '';
                                               }
                                           }
                                       }
                                       $answer_content = '<input type="text" name="tx_myquizpoll_pi1[answer' . $questionNumber . ']" value="' . $value . '" ' . $input_id . ' ###MY_INPUT_TEXT### /> ';
                                   } else {
                                       if ($row['qtype'] == 4) {
                                           // ja/nein
                                           $answer_content = $answer_choice;
                                           if ($markerArrayQ["###MY_INPUT_ID###"]) {
                                               $input_id = 'id="answer' . $questionNumber . '_' . $answerNumber . '_1"';
                                           }
                                           if ($markerArrayQ["###MY_INPUT_LABEL###"]) {
                                               if ($markerArrayQ["###MY_INPUT_LABEL###"] == 3) {
                                                   $class_label = ' class="radio"';
                                               } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 4) {
                                                   $class_label = ' class="radio inline"';
                                               } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 6) {
                                                   $class_label = ' class="radio-inline"';
                                               } else {
                                                   $class_label = '';
                                               }
                                               if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                                                   $label_wrap1 = '<div class="radio">';
                                                   $label_wrap2 = '</div>';
                                               } else {
                                                   $label_wrap1 = '';
                                                   $label_wrap2 = '';
                                               }
                                               $input_label1 = $label_wrap1 . '<label for="answer' . $questionNumber . '_' . $answerNumber . '_1"' . $class_label . '>';
                                               $input_label2 = '</label>' . $label_wrap2;
                                           }
                                           $answer_content .= ' <span class="' . $this->prefixId . '-yesno"><span class="' . $this->prefixId . '-yes">';
                                           if ($markerArrayQ["###MY_INPUT_LABEL###"] > 1) {
                                               $answer_content .= $input_label1;
                                           }
                                           $answer_content .= '<input type="radio" name="tx_myquizpoll_pi1[answer' . $questionNumber . '_' . $currentValue . ']" ' . $input_id . ' value="' . $currentValue . '" ###MY_INPUT_RADIO###';
                                           if (is_array($oldRelData[$quid]) && $oldRelData[$quid]['checked' . $currentValue]) {
                                               $answer_content .= ' checked="checked"';
                                           } elseif ($captchaError && $quizData['answer' . $questionNumber . '_' . $currentValue] == $currentValue) {
                                               $answer_content .= ' checked="checked"';
                                           }
                                           $answer_content .= ' /> ';
                                           if ($markerArrayQ["###MY_INPUT_LABEL###"] == 1) {
                                               $answer_content .= $input_label1;
                                           }
                                           $answer_content .= $this->pi_getLL('yes', 'yes') . $input_label2 . '</span>';
                                           if ($markerArrayQ["###MY_INPUT_ID###"]) {
                                               $input_id = 'id="answer' . $questionNumber . '_' . $answerNumber . '_0"';
                                           }
                                           if ($markerArrayQ["###MY_INPUT_LABEL###"]) {
                                               if ($markerArrayQ["###MY_INPUT_LABEL###"] == 3) {
                                                   $class_label = ' class="radio"';
                                               } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 4) {
                                                   $class_label = ' class="radio inline"';
                                               } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 6) {
                                                   $class_label = ' class="radio-inline"';
                                               } else {
                                                   $class_label = '';
                                               }
                                               if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                                                   $label_wrap1 = '<div class="radio">';
                                                   $label_wrap2 = '</div>';
                                               } else {
                                                   $label_wrap1 = '';
                                                   $label_wrap2 = '';
                                               }
                                               $input_label1 = $label_wrap1 . '<label for="answer' . $questionNumber . '_' . $answerNumber . '_0"' . $class_label . '>';
                                               $input_label2 = '</label>' . $label_wrap2;
                                           }
                                           $answer_content .= ' <span class="' . $this->prefixId . '-no">';
                                           if ($markerArrayQ["###MY_INPUT_LABEL###"] > 1) {
                                               $answer_content .= $input_label1;
                                           }
                                           $answer_content .= '<input type="radio" name="tx_myquizpoll_pi1[answer' . $questionNumber . '_' . $currentValue . ']" ' . $input_id . ' value="0" ###MY_INPUT_RADIO###';
                                           if (is_array($oldRelData[$quid]) && !$oldRelData[$quid]['checked' . $currentValue]) {
                                               $answer_content .= ' checked="checked"';
                                           } elseif ($captchaError && $quizData['answer' . $questionNumber . '_' . $currentValue] == 0) {
                                               $answer_content .= ' checked="checked"';
                                           }
                                           $answer_content .= ' /> ';
                                           if ($markerArrayQ["###MY_INPUT_LABEL###"] == 1) {
                                               $answer_content .= $input_label1;
                                           }
                                           $answer_content .= $this->pi_getLL('no', 'no') . $input_label2 . '</span></span>';
                                       } else {
                                           if ($row['qtype'] == 5) {
                                               // textarea
                                               if ($markerArrayQ["###MY_INPUT_ID###"]) {
                                                   $input_id = 'id="answer' . $questionNumber . '"';
                                               }
                                               if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                                                   $input_id .= ' class="form-control"';
                                               }
                                               if (is_array($oldRelData[$quid])) {
                                                   $value = str_replace('\\r\\n', "\r\n", $oldRelData[$quid]['textinput']);
                                               } else {
                                                   if ($captchaError) {
                                                       $value = $quizData['answer' . $questionNumber];
                                                   } else {
                                                       if ($row['answer2'] || $row['answer2'] === '0') {
                                                           $value = $row['answer2'];
                                                       } else {
                                                           $value = '';
                                                       }
                                                   }
                                               }
                                               $answer_content = '<textarea name="tx_myquizpoll_pi1[answer' . $questionNumber . ']" ' . $input_id . ' ###MY_INPUT_AREA###>' . $value . '</textarea> ';
                                           } else {
                                               if ($row['qtype'] == 7) {
                                                   // star-rating
                                                   if ($markerArrayQ["###MY_INPUT_ID###"]) {
                                                       $input_id = 'id="answer' . $questionNumber . '_' . $answerNumber . '"';
                                                   }
                                                   if ($markerArrayQ["###MY_INPUT_LABEL###"]) {
                                                       $input_label1 = '<label for="answer' . $questionNumber . '_' . $answerNumber . '">';
                                                       $input_label2 = '</label>';
                                                   }
                                                   $answer_content = '<input type="radio" class="star" name="tx_myquizpoll_pi1[answer' . $questionNumber . ']" value="' . $currentValue . '" ' . $input_id;
                                                   if (is_array($oldRelData[$quid]) && $oldRelData[$quid]['checked' . $currentValue]) {
                                                       $answer_content .= ' checked="checked"';
                                                   } elseif ($captchaError && $quizData['answer' . $questionNumber] == $currentValue) {
                                                       $answer_content .= ' checked="checked"';
                                                   }
                                                   $answer_content .= ' title="' . $answer_choice . '" /> ';
                                               } else {
                                                   // checkbox
                                                   if ($markerArrayQ["###MY_INPUT_ID###"]) {
                                                       $input_id = 'id="answer' . $questionNumber . '_' . $answerNumber . '"';
                                                   }
                                                   if ($markerArrayQ["###MY_INPUT_LABEL###"]) {
                                                       if ($markerArrayQ["###MY_INPUT_LABEL###"] == 3) {
                                                           $class_label = ' class="checkbox"';
                                                       } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 4) {
                                                           $class_label = ' class="checkbox inline"';
                                                       } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 6) {
                                                           $class_label = ' class="checkbox-inline"';
                                                       } else {
                                                           $class_label = '';
                                                       }
                                                       if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                                                           $label_wrap1 = '<div class="checkbox">';
                                                           $label_wrap2 = '</div>';
                                                       } else {
                                                           $label_wrap1 = '';
                                                           $label_wrap2 = '';
                                                       }
                                                       $input_label1 = $label_wrap1 . '<label for="answer' . $questionNumber . '_' . $answerNumber . '"' . $class_label . '>';
                                                       $input_label2 = '</label>' . $label_wrap2;
                                                   }
                                                   $answer_content = '<input type="checkbox" name="tx_myquizpoll_pi1[answer' . $questionNumber . '_' . $currentValue . ']" value="' . $currentValue . '" ' . $input_id . ' ###MY_INPUT_CHECKBOX###';
                                                   if (is_array($oldRelData[$quid]) && $oldRelData[$quid]['checked' . $currentValue]) {
                                                       $answer_content .= ' checked="checked"';
                                                   } elseif ($captchaError && $quizData['answer' . $questionNumber . '_' . $currentValue] == $currentValue) {
                                                       $answer_content .= ' checked="checked"';
                                                   }
                                                   $answer_content .= ' /> ';
                                               }
                                           }
                                       }
                                   }
                               }
                           }
                           if (!$this->conf['dontShowPoints'] && !$this->conf['isPoll'] && $row['qtype'] < 5) {
                               $tmpPoints = 0;
                               if ($this->conf['noNegativePoints'] < 3 && $answerPointsBool) {
                                   $tmpPoints = intval($row['points' . $currentValue]);
                               }
                               if ($tmpPoints > 0) {
                                   $row['correct' . $currentValue] = true;
                               } else {
                                   $tmpPoints = intval($row['points']);
                               }
                               if ($row['correct' . $currentValue] || $row['qtype'] == 3) {
                                   if (($row['qtype'] == 0 || $row['qtype'] == 4) && $this->conf['noNegativePoints'] < 3) {
                                       $markerArray["###VAR_QUESTION_POINTS###"] += $tmpPoints;
                                       // points for each answer
                                   } else {
                                       if ($tmpPoints > $markerArray["###VAR_QUESTION_POINTS###"]) {
                                           $markerArray["###VAR_QUESTION_POINTS###"] = $tmpPoints;
                                           // points for each answer
                                       }
                                   }
                               }
                           }
                           $thisCat = $row['category' . $currentValue];
                           if ($this->catArray[$thisCat]) {
                               $markerArrayQ['###VAR_QA_CATEGORY###'] = $this->catArray[$thisCat]['name'];
                           }
                           if ($row['qtype'] < 3) {
                               if ($markerArrayQ["###MY_INPUT_LABEL###"] > 1) {
                                   $answer_content = $input_label1 . $answer_content . $answer_choice . $input_label2;
                               } else {
                                   $answer_content .= $input_label1 . $answer_choice . $input_label2;
                               }
                           }
                           if ($row['qtype'] == 2) {
                               $answer_content .= "</option>\n";
                               $markerArrayQ["###VAR_QUESTION_ANSWER###"] .= $this->cObj->substituteMarkerArray($answer_content, $markerArrayQ);
                           } else {
                               $markerArrayQ['###VAR_QUESTION_ANSWER###'] = $this->cObj->substituteMarkerArray($answer_content, $markerArrayQ);
                               $markerArray["###REF_QUESTION_ANSWER###"] .= $this->cObj->substituteMarkerArray($template_answer, $markerArrayQ);
                           }
                       }
                   }
                   if (!$this->conf['dontShowPoints'] && !$this->conf['isPoll'] && $row['qtype'] < 5) {
                       $markerArray["###VAR_NEXT_POINTS###"] += $markerArray["###VAR_QUESTION_POINTS###"];
                   }
                   $markerArray["###VAR_QUESTION_ANSWERS###"] = $answers;
                   if ($this->conf['allowSkipping']) {
                       // skip answers
                       $markerArrayQ["###VAR_QA_NR###"] = -1;
                       // Questtion type
                       if ($row['qtype'] == 1) {
                           if ($markerArrayQ["###MY_INPUT_ID###"]) {
                               $input_id = ' id="answer' . $questionNumber . '_x"';
                           }
                           if ($markerArrayQ["###MY_INPUT_LABEL###"]) {
                               if ($markerArrayQ["###MY_INPUT_LABEL###"] == 3) {
                                   $class_label = ' class="radio"';
                               } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 4) {
                                   $class_label = ' class="radio inline"';
                               } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 6) {
                                   $class_label = ' class="radio-inline"';
                               } else {
                                   $class_label = '';
                               }
                               if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                                   $label_wrap1 = '<div class="radio">';
                                   $label_wrap2 = '</div>';
                               } else {
                                   $label_wrap1 = '';
                                   $label_wrap2 = '';
                               }
                               $input_label1 = $label_wrap1 . '<label for="answer' . $questionNumber . '_x"' . $class_label . '>';
                               $input_label2 = '</label>' . $label_wrap2;
                           }
                           $answer_content = '<input type="radio" name="tx_myquizpoll_pi1[answer' . $questionNumber . ']" value="-1"' . $input_id . ' /> ';
                           if ($markerArrayQ["###MY_INPUT_LABEL###"] > 1) {
                               $answer_content = $input_label1 . $answer_content . $this->pi_getLL('skip', 'skip') . $input_label2;
                           } else {
                               $answer_content .= $input_label1 . $this->pi_getLL('skip', 'skip') . $input_label2;
                           }
                       } else {
                           if ($row['qtype'] == 2) {
                               $answer_content = '<option value="-1"> ' . $this->pi_getLL('skip', 'skip') . '</option>';
                           } else {
                               if ($row['qtype'] < 6) {
                                   if ($markerArrayQ["###MY_INPUT_ID###"]) {
                                       $input_id = ' id="answer' . $questionNumber . '_x"';
                                   }
                                   if ($markerArrayQ["###MY_INPUT_LABEL###"]) {
                                       if ($markerArrayQ["###MY_INPUT_LABEL###"] == 3) {
                                           $class_label = ' class="checkbox"';
                                       } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 4) {
                                           $class_label = ' class="checkbox inline"';
                                       } elseif ($markerArrayQ["###MY_INPUT_LABEL###"] == 6) {
                                           $class_label = ' class="checkbox-inline"';
                                       } else {
                                           $class_label = '';
                                       }
                                       if ($markerArrayQ["###MY_INPUT_LABEL###"] == 5) {
                                           $label_wrap1 = '<div class="checkbox">';
                                           $label_wrap2 = '</div>';
                                       } else {
                                           $label_wrap1 = '';
                                           $label_wrap2 = '';
                                       }
                                       $input_label1 = $label_wrap1 . '<label for="answer' . $questionNumber . '_x"' . $class_label . '>';
                                       $input_label2 = '</label>' . $label_wrap2;
                                   }
                                   $answer_content = '<input type="checkbox" name="tx_myquizpoll_pi1[answer' . $questionNumber . ']" value="-1"' . $input_id . ' /> ';
                                   if ($markerArrayQ["###MY_INPUT_LABEL###"] > 1) {
                                       $answer_content = $input_label1 . $answer_content . $this->pi_getLL('skip', 'skip') . $input_label2;
                                   } else {
                                       $answer_content .= $input_label1 . $this->pi_getLL('skip', 'skip') . $input_label2;
                                   }
                               }
                           }
                       }
                       $markerArrayQ['###VAR_QA_CATEGORY###'] = '';
                       if ($row['qtype'] == 2) {
                           $markerArrayQ['###VAR_QUESTION_ANSWER###'] .= $answer_content;
                       } else {
                           $markerArrayQ['###VAR_QUESTION_ANSWER###'] = $answer_content;
                           $markerArray["###REF_QUESTION_ANSWER###"] .= $this->cObj->substituteMarkerArray($template_answer, $markerArrayQ);
                       }
                   }
                   if ($row['qtype'] == 2) {
                       $markerArrayQ["###VAR_QUESTION_ANSWER###"] .= "</select>\n";
                       $markerArray["###REF_QUESTION_ANSWER###"] .= $this->cObj->substituteMarkerArray($template_answer, $markerArrayQ);
                   }
                   if (($this->helperObj->getAskAtQ($quizData['qtuid']) || $questionNumber < $maxQuestions) && !$this->conf['isPoll']) {
                       $markerArray["###REF_DELIMITER###"] = $this->cObj->substituteMarkerArray($template_delimiter, $markerArray);
                   } else {
                       $markerArray["###REF_DELIMITER###"] = '';
                   }
                   if ($this->conf['enforceSelection']) {
                       // 25.1.10: antwort erzwingen?
                       $this->helperObj->addEnforceJsc($questionNumber, $answers, $row['qtype']);
                   }
                   //$this->subpart = $template;
                   $template2 = $this->cObj->substituteSubpart($template, '###TEMPLATE_QUESTION_ANSWER###', $markerArray["###REF_QUESTION_ANSWER###"], 0);
                   $markerArrayP["###REF_QUESTIONS###"] .= $this->cObj->substituteMarkerArray($template2, $markerArray);
                   // statt $content .= since 0.1.8
                   $markerArrayP["###REF_QUESTIONS###"] .= '<input type="hidden" name="tx_myquizpoll_pi1[uid' . $questionNumber . ']" value="' . $quid . '" class="input_hidden" />';
                   if ($this->conf['isPoll']) {
                       // link to the result page
                       $urlParameters = array("tx_myquizpoll_pi1[cmd]" => "list", "tx_myquizpoll_pi1[qid]" => $quid, "no_cache" => "1");
                       $markerArray["###POLLRESULT_URL###"] = $this->pi_linkToPage($this->pi_getLL('poll_url', 'poll_url'), $listPID, $target = '', $urlParameters);
                   }
                   $lastUID = $quid;
               }
               $markerArrayP["###REF_SUBMIT_FIELDS###"] = '';
               $markerArrayP["###HIDDENFIELDS###"] = '';
               $markerArrayP["###VAR_QID###"] = $lastUID;
               // last question uid, added on 23.1.2011
               if ($this->conf['isPoll']) {
                   $markerArrayP["###VAR_FID###"] = '';
                   $markerArrayP["###POLLRESULT###"] = $this->pi_getLL('poll_url', 'poll_url');
                   $markerArrayP["###NUM_VOTES###"] = $this->pi_getLL('num_votes', 'num_votes');
                   if ($this->conf['rating.']['parameter']) {
                       // rating
                       $markerArrayP["###VAR_FID###"] = $this->helperObj->getForeignId();
                       // a foreign uid, added on 23.1.2011
                   }
               }
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('last question: ' . $lastUID, $this->extKey, 0);
               }
               // back-button
               if ($this->conf['allowBack'] && $this->conf['pageQuestions'] && $quizData['qtuid']) {
                   $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[back]" value="' . $back . '" />';
                   $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[back-hit]" value="0" />';
                   $markerArray['###BACK_STYLE###'] = $seite == 1 ? ' style="display:none;"' : '';
               } else {
                   $markerArray['###BACK_STYLE###'] = ' style="display:none;"';
               }
               // Submit/User-Data Template
               if ($this->helperObj->getAskAtQ($quizData['qtuid']) && !$this->conf['isPoll']) {
                   $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_USER_TO_SUBMIT###");
                   if (is_object($this->freeCap) && $this->conf['enableCaptcha']) {
                       $markerArray = array_merge($markerArray, $this->freeCap->makeCaptcha());
                   } else {
                       $subpartArray['###CAPTCHA_INSERT###'] = '';
                   }
                   $markerArrayP["###REF_SUBMIT_FIELDS###"] = $this->cObj->substituteMarkerArrayCached($template, $markerArray, $subpartArray, $wrappedSubpartArray);
               } else {
                   if (!($answeredQuestions == $lastUID && $this->conf["isPoll"])) {
                       $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_SUBMIT###");
                       $markerArrayP["###REF_SUBMIT_FIELDS###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
                       $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="name" value="' . $markerArray["###DEFAULT_NAME###"] . '" /> ';
                       // fürs Template?
                       $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[name]" value="' . htmlspecialchars($quizData["name"]) . '" />';
                       $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[email]" value="' . htmlspecialchars($quizData["email"]) . '" />';
                       $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[homepage]" value="' . htmlspecialchars($quizData["homepage"]) . '" />';
                   } else {
                       $markerArray["###NO_SUBMIT###"] = $this->pi_getLL('no_submit', 'no_submit');
                       $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_NO_SUBMIT###");
                       $markerArrayP["###REF_SUBMIT_FIELDS###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
                       // new in 0.1.8
                   }
               }
               if (!$this->conf['isPoll']) {
                   // when is Poll, do not update result-table
                   $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[qtuid]" value="' . intval($quizData["qtuid"]) . '" />';
               }
               if ($this->conf['hideByDefault']) {
                   $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[hidden]" value="1" />';
               }
               if (!$quizData['qtuid']) {
                   $markerArrayP["###HIDDENFIELDS###"] .= '
 <input type="hidden" name="' . $this->prefixId . '[start_uid]" value="' . $GLOBALS['TSFE']->id . '" />
 <input type="hidden" name="' . $this->prefixId . '[time]" value="' . time() . '" />';
               }
               $markerArrayP["###HIDDENFIELDS###"] .= '
 <input type="hidden" name="' . $this->prefixId . '[cmd]" value="submit" />';
               //  <input type="hidden" name="no_cache" value="1" />		KGB: auskommentiert am 30.5.2015
               if ($this->conf['useJokers'] && $this->conf['pageQuestions'] == 1) {
                   $markerArrayP["###HIDDENFIELDS###"] .= '
 <input type="hidden" name="' . $this->prefixId . '[joker1]" value="0" />
 <input type="hidden" name="' . $this->prefixId . '[joker2]" value="0" />
 <input type="hidden" name="' . $this->prefixId . '[joker3]" value="0" />';
               }
               $markerArrayP["###MAX_PAGES###"] = $this->helperObj->getMaxPages();
               $markerArrayP["###PAGE###"] = $this->helperObj->getPage($questTillNow);
               $markerArrayP["###FE_USER_UID###"] = intval($GLOBALS['TSFE']->fe_user->user['uid']);
               $markerArrayP["###SUBMIT_JSC###"] = $this->helperObj->getSubmitJsc();
               $questionPage = true;
           } else {
               // final page: no more questions left, if pageQuestions > 0
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('0 questions found. Entering final page...', $this->extKey, 0);
               }
               // if ($oldLoaded) $secondVisit = true;	// Keine Email schicken, wenn alle Fragen schon beantwortet wurden: NE, so einfach ist das nicht :-(
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_NO_MORE###");
               $markerArray["###NO_MORE###"] = $this->pi_getLL('no_more', 'no_more');
               $markerArray['###YOUR_EVALUATION###'] = $this->pi_getLL('your_evaluation', 'your_evaluation');
               $markerArray['###REACHED1###'] = $this->pi_getLL('reached1', 'reached1');
               $markerArray['###REACHED2###'] = $this->pi_getLL('reached2', 'reached2');
               $markerArray['###POINTS###'] = $this->pi_getLL('points', 'points');
               /*    if ($this->conf['startPID'])        // wir sind nicht auf der Startseite, also parent holen...
                         $restart_id = $this->conf['startPID']; // $GLOBALS['TSFE']->page['pid'];
                     else 
                         $restart_id = $GLOBALS['TSFE']->id;    */
               $markerArray["###RESTART_QUIZ###"] = $this->pi_linkToPage($this->pi_getLL('restart_quiz', 'restart_quiz'), $startPID, $target = '', array());
               if ($this->conf['allowCookieReset']) {
                   $markerArray["###RESET_COOKIE###"] = $this->pi_linkToPage($this->pi_getLL('reset_cookie', 'reset_cookie'), $startPID, $target = '', array($this->prefixId . '[resetcookie]' => 1));
               } else {
                   $markerArray["###RESET_COOKIE###"] = '';
               }
               $questions = '';
               if ($this->conf['showAllCorrectAnswers'] && !$this->conf['isPoll']) {
                   // show all answers...
                   /*if ($this->conf['finishAfterQuestions'])
                         $fragen = intval($this->conf['finishAfterQuestions']);
                     else
                         $fragen = $this->helperObj->getQuestionsNo();*/
                   $questions = $this->showAllAnswers($quizData, $thePID, $resPID, false, 0);
                   // 24.01.10: 0 statt $fragen
               }
               $subpart = $template;
               $template = $this->cObj->substituteSubpart($subpart, '###QUIZ_ANSWERS###', $questions);
               $markerArrayP["###REF_NO_MORE###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
               $markerArrayP["###RESTART_QUIZ###"] = $markerArray["###RESTART_QUIZ###"];
               $markerArrayP["###RESET_COOKIE###"] = $markerArray["###RESET_COOKIE###"];
               if ($this->conf['highscore.']['showAtFinal']) {
                   $quizData['cmd'] = 'score';
               }
               $finalPage = true;
           }
           // myVars for page
           $markerArrayP = array_merge($markerArrayP, $this->helperObj->setPageVars());
       } else {
           if ($this->conf['showAnswersSeparate'] && $quizData['cmd'] == 'submit' && !$this->conf['isPoll'] && $no_rights == 0) {
               /* ***************************************************** */
               /*
                * Display only a next button
                */
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_NEXT###");
               $markerArray["###HIDDENFIELDS###"] = '';
               // back-button
               if ($this->conf['allowBack'] && $this->conf['pageQuestions'] && $quizData['qtuid']) {
                   $markerArray['###BACK_STYLE###'] = '';
                   $markerArray["###HIDDENFIELDS###"] .= '<input type="hidden" name="' . $this->prefixId . '[back]" value="' . $back . '" />
   <input type="hidden" name="' . $this->prefixId . '[back-hit]" value="0" />';
               } else {
                   $markerArray['###BACK_STYLE###'] = ' style="display:none;"';
               }
               if ($template == '') {
                   // if it is not in the template
                   $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_NEXT###");
               }
               $markerArrayP["###REF_NEXT###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
               // instead $content
           }
       }
       /** Redirect to the final page? **/
       if ($finalPage && $quizData['cmd'] != 'exit' && $this->conf['finalPID'] && $finalPID != intval($GLOBALS["TSFE"]->id)) {
           $this->redirectUrl($finalPID, array($this->prefixId . '[qtuid]' => intval($quizData["qtuid"]), $this->prefixId . '[cmd]' => 'next'));
           break;
           // unnoetig...
       }
       /** Poll result? **/
       if ($answerPage && $this->conf['isPoll']) {
           $quizData['cmd'] = 'list';
       }
       // Make a page-layout
       if ($quizData['cmd'] == 'allanswers' && !$this->conf['isPoll']) {
           /* ***************************************************** */
           /*
            * Display all questions and correct answers
            */
           if ($this->helperObj->writeDevLog) {
               t3lib_div::devLog("show answers of: {$thePID},{$resPID}", $this->extKey, 0);
           }
           $content .= $this->showAllAnswers($quizData, $thePID, $resPID, false, 0);
           // 24.01.10: 0 statt $this->helperObj->getQuestionsNo()
       }
       if ($quizData['cmd'] == 'score' && !$this->conf['isPoll']) {
           /* ***************************************************** */
           /*
            * Display highscore page: top 10 table
            */
           if ($quizData["setUserData"] && $quizData['qtuid'] && $quizData["name"]) {
               // ggf. erst Benutzerdaten in der DB setzen...
               $uid = intval($quizData['qtuid']);
               $firsttime = $this->helperObj->getFirstTime($uid);
               if ($firsttime == intval($quizData["setUserData"])) {
                   // Security test bestanden?
                   // update current user entry
                   $timestamp = time();
                   // Avoid bad characters in database request
                   $quiz_taker_name = $GLOBALS['TYPO3_DB']->quoteStr($quizData["name"], $this->tableAnswers);
                   $quiz_taker_email = $GLOBALS['TYPO3_DB']->quoteStr($quizData["email"], $this->tableAnswers);
                   $quiz_taker_homepage = $GLOBALS['TYPO3_DB']->quoteStr($quizData["homepage"], $this->tableAnswers);
                   $hidden = intval($quizData["hidden"]);
                   $update = array('tstamp' => $timestamp, 'name' => $quiz_taker_name, 'email' => $quiz_taker_email, 'homepage' => $quiz_taker_homepage, 'hidden' => $hidden);
                   // Hook for tt_address
                   if (is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey]['setAdrHook']) && $this->conf['userData.']['tt_address_pid']) {
                       foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$this->extKey]['setAdrHook'] as $_classRef) {
                           $_procObj =& t3lib_div::getUserObj($_classRef);
                           $update['address_uid'] = intval($_procObj->setAdr($quizData, $this->conf['userData.']['tt_address_pid'], $this->conf['userData.']['tt_address_groups']));
                       }
                   }
                   $success = $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->tableAnswers, 'uid=' . $uid . ' AND sys_language_uid=' . $this->lang, $update);
                   if (!$success) {
                       $content .= "<p>MySQL Update-Error :-(</p>";
                   }
               }
               if ($this->conf['email.']['send_admin'] == 2 || $this->conf['email.']['send_user'] == 2) {
                   $sendMail = true;
               }
           }
           if ($finalPage) {
               $markerArrayP["###REF_HIGHSCORE###"] = $this->showHighscoreList($quizData, $resPIDs, $listPID);
           } else {
               $content .= $this->showHighscoreList($quizData, $resPIDs, $listPID);
           }
       } else {
           if ($quizData['cmd'] == 'list' && $this->conf['isPoll']) {
               /* ***************************************************** */
               /*
                * Display poll result
                */
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('Poll result: searching question in ' . $thePID . ' and results in ' . $resPID, $this->extKey, 0);
               }
               if ($answerPage) {
                   $markerArrayP["###REF_POLLRESULT###"] = $this->showPollResult($answered, $quizData, $thePID, $resPID);
               } else {
                   $content .= $this->showPollResult($answered, $quizData, $thePID, $resPID);
               }
           }
       }
       if (!$this->conf['isPoll'] && $quizData['cmd'] != 'score') {
           // show highscore link?
           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_HIGHSCORE_URL###");
           $markerArrayP["###REF_HIGHSCORE_URL###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
       }
       if ($this->conf['isPoll'] && $quizData['cmd'] != 'list') {
           // show poll result link?
           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_POLLRESULT_URL###");
           $markerArrayP["###REF_POLLRESULT_URL###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
       }
       /** Layout for the start page **/
       if ($startPage) {
           $markerArrayP["###REF_PAGE_LIMIT###"] = '';
           $markerArrayP["###REF_QUIZ_LIMIT###"] = '';
           $markerArrayP["###HIDDENFIELDS###"] = '<input type="hidden" name="' . $this->prefixId . '[fromStart]" value="1" />';
           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_USER_TO_SUBMIT###");
           $markerArray['###BACK_STYLE###'] = ' style="display:none;"';
           if (is_object($this->freeCap) && $this->conf['enableCaptcha']) {
               $markerArray = array_merge($markerArray, $this->freeCap->makeCaptcha());
           } else {
               $subpartArray['###CAPTCHA_INSERT###'] = '';
           }
           $markerArrayP["###REF_SUBMIT_FIELDS###"] = $this->cObj->substituteMarkerArrayCached($template, $markerArray, $subpartArray, $wrappedSubpartArray);
           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUESTION_PAGE###");
           if ($template == '') {
               // if it is not in the template
               $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_QUESTION_PAGE###");
           }
           $content .= $this->cObj->substituteMarkerArray($template, $markerArrayP);
       }
       /** Layout for a result page **/
       if ($answerPage && $quizData['cmd'] != 'exit') {
           if ($this->conf['quizTimeMinutes']) {
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_TIME_LIMIT###");
               if (!$quizData['qtuid']) {
                   $markerArray["###VAR_SECS###"] = intval($this->conf['quizTimeMinutes']) * 60;
                   $markerArray["###VAR_MIN###"] = $this->conf['quizTimeMinutes'];
               } else {
                   $markerArray["###VAR_SECS###"] = intval($this->conf['quizTimeMinutes']) * 60 - $elapseTime;
                   $markerArray["###VAR_MIN###"] = round($markerArray["###VAR_SECS###"] / 60);
               }
               $markerArrayP["###REF_QUIZ_LIMIT###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
           } else {
               $markerArrayP["###REF_QUIZ_LIMIT###"] = '';
           }
           if ($this->helperObj->writeDevLog) {
               t3lib_div::devLog('Displaying result-page...', $this->extKey, 0);
           }
           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_RESULT_PAGE###");
           if ($template == '') {
               // if it is not in the (old custom) template
               $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_RESULT_PAGE###");
           }
           $content .= $this->cObj->substituteMarkerArray($template, $markerArrayP);
           if ($this->conf['isPoll'] && $this->conf['email.']['send_admin']) {
               $sendMail = true;
           }
       }
       /** Layout for a questions page **/
       if ($questionPage && $quizData['cmd'] != 'exit') {
           if ($this->conf['pageTimeSeconds']) {
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_PAGE_TIME_LIMIT###");
               $markerArray["###VAR_SECS###"] = $pageTimeCat ? $pageTimeCat : $this->conf['pageTimeSeconds'];
               $markerArrayP["###REF_PAGE_LIMIT###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
           } else {
               $markerArrayP["###REF_PAGE_LIMIT###"] = '';
           }
           if ($this->conf['quizTimeMinutes']) {
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_TIME_LIMIT###");
               if (!$quizData['qtuid']) {
                   $markerArray["###VAR_SECS###"] = intval($this->conf['quizTimeMinutes']) * 60;
                   $markerArray["###VAR_MIN###"] = $this->conf['quizTimeMinutes'];
               } else {
                   $markerArray["###VAR_SECS###"] = intval($this->conf['quizTimeMinutes']) * 60 - $elapseTime;
                   $markerArray["###VAR_MIN###"] = round($markerArray["###VAR_SECS###"] / 60);
               }
               $markerArrayP["###REF_QUIZ_LIMIT###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
           } else {
               $markerArrayP["###REF_QUIZ_LIMIT###"] = '';
           }
           $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUESTION_PAGE###");
           if ($template == '') {
               // if it is not in the template
               $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_QUESTION_PAGE###");
           }
           $content .= $this->cObj->substituteMarkerArray($template, $markerArrayP);
       }
       /** Layout for the last/final page **/
       $uidP = 0;
       // page UID
       $uidC = 0;
       // content UID
       if ($finalPage && $quizData['cmd'] != 'exit') {
           // nicht noetig: && !$this->conf['isPoll']) {
           if (($this->conf['showAnalysis'] || $this->conf['showEvaluation']) && !$this->conf['dontShowPoints']) {
               // Analysis depends on points
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('Displaying Analysis: ' . $this->conf['showAnalysis'] . ' or Evaluation: ' . $this->conf['showEvaluation'], $this->extKey, 0);
               }
               if (!$markerArray["###VAR_TMAX_POINTS###"]) {
                   $this->helperObj->setQuestionsVars();
                   $markerArray["###VAR_TMAX_POINTS###"] = $this->helperObj->getQuestionsMaxPoints();
                   // omax und tmax sollten hier gleich sein
                   if (!$markerArray["###VAR_TMAX_POINTS###"]) {
                       $markerArray["###VAR_TMAX_POINTS###"] = 100000;
                   }
                   // notfalls halt irgendein wert
               }
               $points = $markerArray["###VAR_TOTAL_POINTS###"];
               $percent = 100 * $points / $markerArray["###VAR_TMAX_POINTS###"];
               // genauerer wert...
               $markerArray["###VAR_PERCENT###"] = intval($percent);
               $markerArray["###REACHED1###"] = $this->pi_getLL('reached1', 'reached1');
               $markerArray["###REACHED2###"] = $this->pi_getLL('reached2', 'reached2');
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('Total points=' . $markerArray["###VAR_TOTAL_POINTS###"] . ' tmax points=' . $markerArray["###VAR_TMAX_POINTS###"] . ' percent=' . $markerArray["###VAR_PERCENT###"], $this->extKey, 0);
               }
               if ($this->conf['showAnalysis']) {
                   $dataArray = explode(',', $this->conf['showAnalysis']);
               } else {
                   $dataArray = explode(',', $this->conf['showEvaluation']);
               }
               $templateNo = '';
               $p = 0;
               while ($p < count($dataArray)) {
                   $templateNo = $dataArray[$p];
                   if (strpos($templateNo, ':') !== false) {
                       if ($this->conf['showAnalysis']) {
                           list($templateNo, $uidP) = explode(":", $templateNo);
                       } else {
                           list($templateNo, $uidC) = explode(":", $templateNo);
                       }
                   }
                   if ($this->conf['showAnalysis']) {
                       if ($percent <= floatval($templateNo)) {
                           // wann abbrechen?
                           //    if ($uidP) ...    // redirect to a URL with that UID  -> weiter nach unten verschoben (nach email Versendung!!)
                           break;
                       }
                   } else {
                       if ($points <= floatval($templateNo)) {
                           // wann abbrechen?
                           break;
                       }
                   }
                   $p++;
               }
               if (!($uidP || $uidC)) {
                   $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_ANALYSIS_{$templateNo}###");
                   $markerArrayP["###REF_QUIZ_ANALYSIS###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
               } else {
                   if ($uidC) {
                       $confC = array('tables' => 'tt_content', 'source' => $uidC, 'dontCheckPid' => 1);
                       $markerArrayP["###REF_QUIZ_ANALYSIS###"] = $this->cObj->RECORDS($confC);
                   }
               }
           } else {
               if ($this->conf['showCategoryElement']) {
                   $showCategoryElement = intval($this->conf['showCategoryElement']);
                   if ($this->helperObj->writeDevLog) {
                       t3lib_div::devLog('Displaying category element: ' . $showCategoryElement . ' nextcat: ' . $nextCat, $this->extKey, 0);
                   }
                   if ($showCategoryElement == 1 && $nextCat > 0 && $this->catArray[$nextCat]['celement']) {
                       $uidC = $this->catArray[$nextCat]['celement'];
                       $confC = array('tables' => 'tt_content', 'source' => $uidC, 'dontCheckPid' => 1);
                       $markerArrayP["###REF_QUIZ_ANALYSIS###"] = $this->cObj->RECORDS($confC);
                       // last category element
                   } else {
                       if ($showCategoryElement > 1 && $this->conf['advancedStatistics']) {
                           $tmpCat = '';
                           $usedCatArray = array();
                           $catCount = 0;
                           $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('DISTINCT nextcat, COUNT(nextcat) anzahl', $this->tableRelation, 'nextcat>0 AND user_id=' . intval($quizData['qtuid']) . ' AND sys_language_uid=' . $this->lang, 'nextcat', 'anzahl DESC', '');
                           $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
                           if ($rows > 0) {
                               while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5)) {
                                   $tmpCat = $row['nextcat'];
                                   if ($catCount == 0) {
                                       $firstCount = $row['anzahl'];
                                   }
                                   if ($tmpCat && $this->catArray[$tmpCat]['celement'] && ($showCategoryElement == 4 || $showCategoryElement == 3 && $firstCount == $row['anzahl'] || $catCount == 0)) {
                                       $usedCatArray[$tmpCat] = $row['anzahl'];
                                   }
                                   $catCount += $row['anzahl'];
                               }
                           }
                           if (count($usedCatArray) > 0) {
                               $markerArrayC = array();
                               $markerArrayC['###PREFIX###'] = $markerArrayP['###PREFIX###'];
                               $markerArrayC['###ANSWERS###'] = $this->pi_getLL('answers', 'answers');
                               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_CATEGORY_ELEMENT###");
                               foreach ($usedCatArray as $key => $value) {
                                   $uidC = $this->catArray[$key]['celement'];
                                   $confC = array('tables' => 'tt_content', 'source' => $uidC, 'dontCheckPid' => 1);
                                   $markerArrayC['###CATEGORY###'] = $this->catArray[$key]['name'];
                                   $markerArrayC['###CONTENT###'] = $this->cObj->RECORDS($confC);
                                   // most category element
                                   $markerArrayC['###VAR_COUNT###'] = $value;
                                   $markerArrayC['###VAR_PERCENT###'] = round(100 * $value / $catCount);
                                   $markerArrayP["###REF_QUIZ_ANALYSIS###"] .= $this->cObj->substituteMarkerArray($template, $markerArrayC);
                               }
                           }
                           $GLOBALS['TYPO3_DB']->sql_free_result($res5);
                       }
                   }
               }
           }
           if (!$uidP) {
               // no redirect
               $markerArrayP["###FORM_URL###"] = $this->pi_getPageLink($listPID);
               // zur endgueltig letzten seite wechseln
               $markerArrayP["###REF_SUBMIT_FIELDS###"] = '';
               $markerArrayP["###HIDDENFIELDS###"] = '';
               $markerArrayP["###FE_USER_UID###"] = intval($GLOBALS['TSFE']->fe_user->user['uid']);
               if ($this->conf['userData.']['showAtFinal']) {
                   $quiz_taker_name = $GLOBALS['TYPO3_DB']->quoteStr($quizData["name"], $this->tableAnswers);
                   $quiz_taker_email = $GLOBALS['TYPO3_DB']->quoteStr($quizData["email"], $this->tableAnswers);
                   $quiz_taker_homepage = $GLOBALS['TYPO3_DB']->quoteStr($quizData["homepage"], $this->tableAnswers);
                   $markerArray["###REAL_NAME###"] = $quiz_taker_name;
                   $markerArray["###REAL_EMAIL###"] = $quiz_taker_email;
                   $markerArray["###REAL_HOMEPAGE###"] = $quiz_taker_homepage;
                   $markerArray["###RESULT_FOR###"] = $this->pi_getLL('result_for', 'result_for');
                   $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_USER_SUBMITED###");
                   // Output the user name
                   $markerArrayP["###REF_INTRODUCTION###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
               }
               // User-Data Template
               if ($this->conf['userData.']['askAtFinal'] && $quizData['qtuid']) {
                   $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_USER_TO_SUBMIT###");
                   $markerArray['###BACK_STYLE###'] = ' style="display:none;"';
                   if (is_object($this->freeCap) && $this->conf['enableCaptcha']) {
                       $markerArray = array_merge($markerArray, $this->freeCap->makeCaptcha());
                   } else {
                       $subpartArray['###CAPTCHA_INSERT###'] = '';
                   }
                   $firsttime = $this->helperObj->getFirstTime($quizData['qtuid']);
                   $markerArrayP["###REF_SUBMIT_FIELDS###"] = $this->cObj->substituteMarkerArrayCached($template, $markerArray, $subpartArray, $wrappedSubpartArray);
                   $markerArrayP["###HIDDENFIELDS###"] = "\n" . '  <input type="hidden" name="' . $this->prefixId . '[qtuid]" value="' . intval($quizData["qtuid"]) . '" />' . "\n";
                   $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[setUserData]" value="' . $firsttime . '" />' . "\n";
                   $markerArrayP["###HIDDENFIELDS###"] .= '  <input type="hidden" name="' . $this->prefixId . '[fromFinal]" value="1" />';
               }
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_FINAL_PAGE###");
               if ($template == '') {
                   // if it is not in the template
                   $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_QUIZ_FINAL_PAGE###");
               }
               $content .= $this->cObj->substituteMarkerArray($template, $markerArrayP);
           }
           if ($this->conf['email.']['send_admin'] == 1 || $this->conf['email.']['send_user'] == 1) {
               $sendMail = true;
           }
       }
       /** Send an/two email(s)? **/
       if ($sendMail && !$error && !$secondVisit) {
           if ($this->helperObj->writeDevLog) {
               t3lib_div::devLog('Entering "send emails"...', $this->extKey, 0);
           }
           $markerArrayP["###EMAIL_TAKEN###"] = $this->pi_getLL('email_taken', 'email_taken');
           if (!$markerArrayP["###REF_INTRODUCTION###"] && !$this->conf['isPoll']) {
               if (!$markerArray["###RESULT_FOR###"]) {
                   $markerArray["###REAL_NAME###"] = htmlspecialchars($quizData['name']);
                   $markerArray["###REAL_EMAIL###"] = htmlspecialchars($quizData['email']);
                   $markerArray["###REAL_HOMEPAGE###"] = htmlspecialchars($quizData['homepage']);
                   $markerArray["###RESULT_FOR###"] = $this->pi_getLL('result_for', 'result_for');
               }
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_QUIZ_USER_SUBMITED###");
               // Output the user name
               $markerArrayP["###REF_INTRODUCTION###"] = $this->cObj->substituteMarkerArray($template, $markerArray);
           }
           if ($this->conf['showAllCorrectAnswers'] && !$this->conf['isPoll']) {
               // show all answers...
               $quizData['sendEmailNow'] = true;
               // noetig um zu wissen, welches Template genommen werden soll
               $markerArrayP["###REF_EMAIL_ALLANSWERS###"] = $this->showAllAnswers($quizData, $thePID, $resPID, true, 0);
           } else {
               $markerArrayP["###REF_EMAIL_ALLANSWERS###"] = '';
           }
           if ($this->conf['email.']['send_admin'] && t3lib_div::validEmail($this->conf['email.']['admin_mail']) && $this->conf['email.']['admin_subject']) {
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('Sending email to admin: ' . $this->conf['email.']['admin_mail'], $this->extKey, 0);
               }
               $markerArrayP["###SUBJECT###"] = $this->conf['email.']['admin_subject'];
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_ADMIN_EMAIL###");
               if ($template == '') {
                   // if it is not in the template
                   $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_ADMIN_EMAIL###");
               }
               $mailcontent = $this->cObj->substituteMarkerArray($template, $markerArrayP);
               $this->helperObj->sendEmail($mailcontent, '', $this->conf['email.']['admin_mail'], $this->conf['email.']['admin_name'], $this->conf['email.']['admin_subject']);
           }
           if ($this->conf['email.']['send_user'] && t3lib_div::validEmail($quizData["email"]) && $this->conf['email.']['user_subject']) {
               if ($this->helperObj->writeDevLog) {
                   t3lib_div::devLog('Sending email to user: '******'email.']['user_subject'];
               $template = $this->cObj->getSubpart($this->templateCode, "###TEMPLATE_USER_EMAIL###");
               if ($template == '') {
                   // if it is not in the template
                   $template = $this->cObj->getSubpart($this->origTemplateCode, "###TEMPLATE_USER_EMAIL###");
               }
               $mailcontent = $this->cObj->substituteMarkerArray($template, $markerArrayP);
               $this->helperObj->sendEmail($mailcontent, '', $quizData["email"], $quizData["name"], $this->conf['email.']['user_subject']);
           }
       }
       /** Delete user result at the end of the quiz? **/
       if ($finalPage && $this->conf['deleteResults']) {
           // 60*60*24 = 86400 = 1 tag
           $loesche = '';
           $counter = 0;
           $where = 'pid=' . $resPID;
           $where .= ' AND (crdate<' . (time() - 86400) . ' OR uid=' . intval($quizData['qtuid']) . ')';
           if ($this->conf['deleteResults'] == 2) {
               $where .= ' AND fe_uid=0';
           }
           if ($this->conf['deleteResults'] == 3) {
               $where .= " AND name='" . $GLOBALS['TYPO3_DB']->quoteStr($this->pi_getLL('no_name', 'no_name'), $this->tableAnswers) . "'";
           }
           $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $this->tableAnswers, $where, '', 'crdate DESC', '255');
           if ($GLOBALS['TYPO3_DB']->sql_num_rows($res5) > 0) {
               while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5)) {
                   $loesche .= ', ' . $row['uid'];
                   $counter++;
               }
               $loesche = substr($loesche, 1);
           }
           $GLOBALS['TYPO3_DB']->sql_free_result($res5);
           if ($this->conf['deleteDouble'] && $counter < 250) {
               // mehrfache eintraege eines users zu einem quiz loeschen
               $where2 = '';
               $fe_uid = intval($GLOBALS['TSFE']->fe_user->user['uid']);
               if ($this->conf['deleteResults'] == 2 && $fe_uid > 0) {
                   $where2 = ' AND fe_uid=' . $fe_uid;
               } else {
                   if ($this->conf['deleteResults'] == 3 && $quizData["name"] != $this->pi_getLL('no_name', 'no_name') && $quizData["name"]) {
                       $where2 = " AND name='" . $GLOBALS['TYPO3_DB']->quoteStr($quizData["name"], $this->tableAnswers) . "'";
                   }
               }
               if ($where2) {
                   $start_uid = $this->helperObj->getStartUid($quizData['qtuid']);
                   $res5 = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, o_percent, crdate', $this->tableAnswers, 'pid=' . $resPID . ' AND sys_language_uid=' . $this->lang . ' AND start_uid=' . $start_uid . $where2, '', 'o_percent DESC, crdate DESC', '200');
                   $rows = $GLOBALS['TYPO3_DB']->sql_num_rows($res5);
                   if ($rows > 0) {
                       $counter = 0;
                       while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res5)) {
                           $counter++;
                           if ($counter > 1) {
                               $loesche .= $loesche ? ',' . $row['uid'] : $row['uid'];
                           }
                       }
                   }
                   $GLOBALS['TYPO3_DB']->sql_free_result($res5);
               }
           }
           if ($this->helperObj->writeDevLog) {
               t3lib_div::devLog('Deleting result data with: ' . $where . $where2 . ' => ' . $loesche, $this->extKey, 0);
           }
           if ($loesche) {
               $res = $GLOBALS['TYPO3_DB']->exec_DELETEquery($this->tableRelation, 'user_id IN (' . preg_replace('/[^0-9,]/', '', $loesche) . ')');
               $res = $GLOBALS['TYPO3_DB']->exec_DELETEquery($this->tableAnswers, 'uid IN (' . preg_replace('/[^0-9,]/', '', $loesche) . ')');
           }
       }
       /** Redirect at the end of the quiz? **/
       if ($finalPage && $uidP) {
           // redirect to a URL with that UID
           $this->redirectUrl($uidP, array($this->prefixId . '[name]' => $quizData["name"], $this->prefixId . '[email]' => $quizData["email"], $this->prefixId . '[homepage]' => $quizData["homepage"]));
       }
       if ($this->helperObj->writeDevLog) {
           t3lib_div::devLog('return the content to the Typo3 core', $this->extKey, 0);
       }
       return $this->pi_wrapInBaseClass($content);
   }
 /**
  * Start function
  * This class is able to generate a mail in formmail-style from the data in $V
  * Fields:
  *
  * [recipient]:			email-adress of the one to receive the mail. If array, then all values are expected to be recipients
  * [attachment]:		....
  *
  * [subject]:			The subject of the mail
  * [from_email]:		Sender email. If not set, [email] is used
  * [from_name]:			Sender name. If not set, [name] is used
  * [replyto_email]:		Reply-to email. If not set [from_email] is used
  * [replyto_name]:		Reply-to name. If not set [from_name] is used
  * [organisation]:		Organization (header)
  * [priority]:			Priority, 1-5, default 3
  * [html_enabled]:		If mail is sent as html
  * [use_base64]:		If set, base64 encoding will be used instead of quoted-printable
  *
  * @param	array		Contains values for the field names listed above (with slashes removed if from POST input)
  * @param	boolean		Whether to base64 encode the mail content
  * @return	void
  */
 function start($V, $base64 = false)
 {
     $convCharset = FALSE;
     // do we need to convert form data?
     if ($GLOBALS['TSFE']->config['config']['formMailCharset']) {
         // Respect formMailCharset if it was set
         $this->charset = $GLOBALS['TSFE']->csConvObj->parse_charset($GLOBALS['TSFE']->config['config']['formMailCharset']);
         $convCharset = TRUE;
     } elseif ($GLOBALS['TSFE']->metaCharset != $GLOBALS['TSFE']->renderCharset) {
         // Use metaCharset for mail if different from renderCharset
         $this->charset = $GLOBALS['TSFE']->metaCharset;
         $convCharset = TRUE;
     }
     parent::start();
     if ($base64 || $V['use_base64']) {
         $this->useBase64();
     }
     if (isset($V['recipient'])) {
         // convert form data from renderCharset to mail charset
         $val = $V['subject'] ? $V['subject'] : 'Formmail on ' . t3lib_div::getIndpEnv('HTTP_HOST');
         $this->subject = $convCharset && strlen($val) ? $GLOBALS['TSFE']->csConvObj->conv($val, $GLOBALS['TSFE']->renderCharset, $this->charset) : $val;
         $this->subject = $this->sanitizeHeaderString($this->subject);
         $val = $V['from_name'] ? $V['from_name'] : ($V['name'] ? $V['name'] : '');
         // Be careful when changing $val! It is used again as the fallback value for replyto_name
         $this->from_name = $convCharset && strlen($val) ? $GLOBALS['TSFE']->csConvObj->conv($val, $GLOBALS['TSFE']->renderCharset, $this->charset) : $val;
         $this->from_name = $this->sanitizeHeaderString($this->from_name);
         $this->from_name = preg_match('/\\s|,/', $this->from_name) >= 1 ? '"' . $this->from_name . '"' : $this->from_name;
         $val = $V['replyto_name'] ? $V['replyto_name'] : $val;
         $this->replyto_name = $convCharset && strlen($val) ? $GLOBALS['TSFE']->csConvObj->conv($val, $GLOBALS['TSFE']->renderCharset, $this->charset) : $val;
         $this->replyto_name = $this->sanitizeHeaderString($this->replyto_name);
         $this->replyto_name = preg_match('/\\s|,/', $this->replyto_name) >= 1 ? '"' . $this->replyto_name . '"' : $this->replyto_name;
         $val = $V['organisation'] ? $V['organisation'] : '';
         $this->organisation = $convCharset && strlen($val) ? $GLOBALS['TSFE']->csConvObj->conv($val, $GLOBALS['TSFE']->renderCharset, $this->charset) : $val;
         $this->organisation = $this->sanitizeHeaderString($this->organisation);
         $this->from_email = $V['from_email'] ? $V['from_email'] : ($V['email'] ? $V['email'] : '');
         $this->from_email = t3lib_div::validEmail($this->from_email) ? $this->from_email : '';
         $this->replyto_email = $V['replyto_email'] ? $V['replyto_email'] : $this->from_email;
         $this->replyto_email = t3lib_div::validEmail($this->replyto_email) ? $this->replyto_email : '';
         $this->priority = $V['priority'] ? t3lib_div::intInRange($V['priority'], 1, 5) : 3;
         // Auto responder.
         $this->auto_respond_msg = trim($V['auto_respond_msg']) && $this->from_email ? trim($V['auto_respond_msg']) : '';
         $this->auto_respond_msg = $this->sanitizeHeaderString($this->auto_respond_msg);
         $Plain_content = '';
         $HTML_content = '<table border="0" cellpadding="2" cellspacing="2">';
         // Runs through $V and generates the mail
         if (is_array($V)) {
             foreach ($V as $key => $val) {
                 if (!t3lib_div::inList($this->reserved_names, $key)) {
                     $space = strlen($val) > 60 ? LF : '';
                     $val = is_array($val) ? implode($val, LF) : $val;
                     // convert form data from renderCharset to mail charset (HTML may use entities)
                     $Plain_val = $convCharset && strlen($val) ? $GLOBALS['TSFE']->csConvObj->conv($val, $GLOBALS['TSFE']->renderCharset, $this->charset, 0) : $val;
                     $HTML_val = $convCharset && strlen($val) ? $GLOBALS['TSFE']->csConvObj->conv(htmlspecialchars($val), $GLOBALS['TSFE']->renderCharset, $this->charset, 1) : htmlspecialchars($val);
                     $Plain_content .= strtoupper($key) . ':  ' . $space . $Plain_val . LF . $space;
                     $HTML_content .= '<tr><td bgcolor="#eeeeee"><font face="Verdana" size="1"><strong>' . strtoupper($key) . '</strong></font></td><td bgcolor="#eeeeee"><font face="Verdana" size="1">' . nl2br($HTML_val) . '&nbsp;</font></td></tr>';
                 }
             }
         }
         $HTML_content .= '</table>';
         if ($V['html_enabled']) {
             $this->setHTML($this->encodeMsg($HTML_content));
         }
         $this->addPlain($Plain_content);
         for ($a = 0; $a < 10; $a++) {
             $varname = 'attachment' . ($a ? $a : '');
             if (!isset($_FILES[$varname])) {
                 continue;
             }
             if (!is_uploaded_file($_FILES[$varname]['tmp_name'])) {
                 t3lib_div::sysLog('Possible abuse of t3lib_formmail: temporary file "' . $_FILES[$varname]['tmp_name'] . '" ("' . $_FILES[$varname]['name'] . '") was not an uploaded file.', 'Core', 3);
             }
             if ($_FILES[$varname]['tmp_name']['error'] !== UPLOAD_ERR_OK) {
                 t3lib_div::sysLog('Error in uploaded file in t3lib_formmail: temporary file "' . $_FILES[$varname]['tmp_name'] . '" ("' . $_FILES[$varname]['name'] . '") Error code: ' . $_FILES[$varname]['tmp_name']['error'], 'Core', 3);
             }
             $theFile = t3lib_div::upload_to_tempfile($_FILES[$varname]['tmp_name']);
             $theName = $_FILES[$varname]['name'];
             if ($theFile && file_exists($theFile)) {
                 if (filesize($theFile) < $GLOBALS['TYPO3_CONF_VARS']['FE']['formmailMaxAttachmentSize']) {
                     $this->addAttachment($theFile, $theName);
                 }
             }
             t3lib_div::unlink_tempfile($theFile);
         }
         $this->setHeaders();
         $this->setContent();
         $this->setRecipient($V['recipient']);
         if ($V['recipient_copy']) {
             $this->recipient_copy = trim($V['recipient_copy']);
         }
         // log dirty header lines
         if ($this->dirtyHeaders) {
             t3lib_div::sysLog('Possible misuse of t3lib_formmail: see TYPO3 devLog', 'Core', 3);
             if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']) {
                 t3lib_div::devLog('t3lib_formmail: ' . t3lib_div::arrayToLogString($this->dirtyHeaders, '', 200), 'Core', 3);
             }
         }
     }
 }
 /**
  * Method for checking the user input in the form mode
  *
  * @return	string		$error Error-Code (HTML)
  */
 function checkForm()
 {
     if (is_array($this->config['obligationfields']) && count($this->config['obligationfields']) > 0) {
         foreach ($this->config['obligationfields'] as $obl_field) {
             if (empty($this->postvars[$obl_field])) {
                 $error .= '<li>' . ucfirst($this->pi_getLL('form_' . $obl_field)) . "</li>\n";
                 $this->errorFields['obligationfields'] = $obl_field;
             }
         }
     }
     if ($this->config['email_validation'] && !empty($this->postvars['email'])) {
         if (t3lib_div::validEmail($this->postvars['email']) == false) {
             $error .= '<li>' . $this->pi_getLL('form_email') . " (" . $this->pi_getLL('form_invalid_field') . ")</li>\n";
             $this->errorFields['email_validation'] = false;
         }
     }
     if ($this->config['website_validation'] && !empty($this->postvars['homepage']) && $this->postvars['homepage'] != 'http://') {
         if ($this->isURL($this->postvars['homepage']) == false) {
             $error .= '<li>' . ucfirst($this->pi_getLL('form_homepage')) . " (" . $this->pi_getLL('form_invalid_field') . ")</li>\n";
             $this->errorFields['website_validation'] = false;
         }
     }
     // blacklist validation
     if ($this->config['blacklist_mail'] && !empty($this->postvars['email'])) {
         $emails_blacklisted = split(",", $this->config['blacklist_mail']);
         if (is_array($emails_blacklisted)) {
             foreach ($emails_blacklisted as $single_email) {
                 if (!(strpos($this->postvars['email'], trim($single_email)) === false)) {
                     $errorBlacklist = '<li>' . $this->pi_getLL('form_email') . " (" . $this->pi_getLL('form_blacklisted') . ")</li>\n";
                     $this->errorFields['blacklist_mail'] = false;
                     break;
                 }
             }
         }
     }
     // whitelist validation
     if ($this->config['whitelist_mail'] && !empty($this->postvars['email'])) {
         $emails_whitelisted = split(",", $this->config['whitelist_mail']);
         if (is_array($emails_whitelisted)) {
             foreach ($emails_whitelisted as $single_email) {
                 if (!(strpos($this->postvars['email'], trim($single_email)) === false)) {
                     $errorBlacklist = '';
                     $this->errorFields['blacklist_mail'] = true;
                     break;
                 }
             }
         }
     }
     if (!$GLOBALS['TSFE']->loginUser) {
         if (is_object($this->freeCap) && $this->config['captcha'] == 'sr_freecap' && !$this->freeCap->checkWord($this->postvars['captcha_response'])) {
             $error .= '<li>' . ucfirst($this->pi_getLL('form_captcha_response')) . " (" . $this->pi_getLL('form_invalid_field') . ")</li>\n";
             $this->errorFields['captcha'] = false;
         }
     }
     if (t3lib_extMgm::isLoaded('captcha') && $this->config['captcha'] == 'captcha') {
         session_start();
         if (isset($_SESSION['tx_captcha_string'])) {
             $captchaStr = $_SESSION['tx_captcha_string'];
             $_SESSION['tx_captcha_string'] = '';
             if ($captchaStr != $this->postvars['captcha_response'] && !empty($captchaStr)) {
                 $error .= '<li>' . ucfirst($this->pi_getLL('form_captcha_response')) . " (" . $this->pi_getLL('form_invalid_field') . ")</li>\n";
                 $this->errorFields['captcha'] = false;
             }
         } else {
             $error .= '<li>' . ucfirst($this->pi_getLL('form_error_cookie')) . '</li>';
             $this->errorFields['captcha'] = false;
         }
     }
     $error .= $errorBlacklist;
     if (!empty($error)) {
         return "<ul>\n" . $error . "</ul>\n";
     }
 }
 /**
  * Checking syntax of input email address
  *
  * @param	string		Input string to evaluate
  * @return	boolean		Returns TRUE if the $email address (input string) is valid; Has a "@", domain name with at least one period and only allowed a-z characters.
  * @see t3lib_div::validEmail()
  * @deprecated since TYPO3 3.6, will be removed in TYPO3 4.6 - Use t3lib_div::validEmail() instead
  */
 function checkEmail($email)
 {
     t3lib_div::logDeprecatedFunction();
     return t3lib_div::validEmail($email);
 }
 /**
  * Start function
  * This class is able to generate a mail in formmail-style from the data in $V
  * Fields:
  *
  * [recipient]:			email-adress of the one to receive the mail. If array, then all values are expected to be recipients
  * [attachment]:		....
  *
  * [subject]:			The subject of the mail
  * [from_email]:		Sender email. If not set, [email] is used
  * [from_name]:			Sender name. If not set, [name] is used
  * [replyto_email]:		Reply-to email. If not set [from_email] is used
  * [replyto_name]:		Reply-to name. If not set [from_name] is used
  * [organisation]:		Organization (header)
  * [priority]:			Priority, 1-5, default 3
  * [html_enabled]:		If mail is sent as html
  * [use_base64]:		If set, base64 encoding will be used instead of quoted-printable
  *
  * @param	array		Contains values for the field names listed above (with slashes removed if from POST input)
  * @param	boolean		Whether to base64 encode the mail content
  * @return	void
  */
 function start($valueList, $base64 = false)
 {
     $this->mailMessage = t3lib_div::makeInstance('t3lib_mail_Message');
     if ($GLOBALS['TSFE']->config['config']['formMailCharset']) {
         // Respect formMailCharset if it was set
         $this->characterSet = $GLOBALS['TSFE']->csConvObj->parse_charset($GLOBALS['TSFE']->config['config']['formMailCharset']);
     } elseif ($GLOBALS['TSFE']->metaCharset != $GLOBALS['TSFE']->renderCharset) {
         // Use metaCharset for mail if different from renderCharset
         $this->characterSet = $GLOBALS['TSFE']->metaCharset;
     }
     if ($base64 || $valueList['use_base64']) {
         $this->encoding = 'base64';
     }
     if (isset($valueList['recipient'])) {
         // convert form data from renderCharset to mail charset
         $this->subject = $valueList['subject'] ? $valueList['subject'] : 'Formmail on ' . t3lib_div::getIndpEnv('HTTP_HOST');
         $this->subject = $this->sanitizeHeaderString($this->subject);
         $this->fromName = $valueList['from_name'] ? $valueList['from_name'] : ($valueList['name'] ? $valueList['name'] : '');
         $this->fromName = $this->sanitizeHeaderString($this->fromName);
         $this->replyToName = $valueList['replyto_name'] ? $valueList['replyto_name'] : $this->fromName;
         $this->replyToName = $this->sanitizeHeaderString($this->replyToName);
         $this->organisation = $valueList['organisation'] ? $valueList['organisation'] : '';
         $this->organisation = $this->sanitizeHeaderString($this->organisation);
         $this->fromAddress = $valueList['from_email'] ? $valueList['from_email'] : ($valueList['email'] ? $valueList['email'] : '');
         if (!t3lib_div::validEmail($this->fromAddress)) {
             $this->fromAddress = t3lib_utility_Mail::getSystemFromAddress();
             $this->fromName = t3lib_utility_Mail::getSystemFromName();
         }
         $this->replyToAddress = $valueList['replyto_email'] ? $valueList['replyto_email'] : $this->fromAddress;
         $this->priority = $valueList['priority'] ? t3lib_div::intInRange($valueList['priority'], 1, 5) : 3;
         // auto responder
         $this->autoRespondMessage = trim($valueList['auto_respond_msg']) && $this->fromAddress ? trim($valueList['auto_respond_msg']) : '';
         if ($this->autoRespondMessage !== '') {
             // Check if the value of the auto responder message has been modified with evil intentions
             $autoRespondChecksum = $valueList['auto_respond_checksum'];
             $correctHmacChecksum = t3lib_div::hmac($this->autoRespondMessage);
             if ($autoRespondChecksum !== $correctHmacChecksum) {
                 t3lib_div::sysLog('Possible misuse of t3lib_formmail auto respond method. Subject: ' . $valueList['subject'], 'Core', 3);
                 return;
             } else {
                 $this->autoRespondMessage = $this->sanitizeHeaderString($this->autoRespondMessage);
             }
         }
         $plainTextContent = '';
         $htmlContent = '<table border="0" cellpadding="2" cellspacing="2">';
         // Runs through $V and generates the mail
         if (is_array($valueList)) {
             foreach ($valueList as $key => $val) {
                 if (!t3lib_div::inList($this->reserved_names, $key)) {
                     $space = strlen($val) > 60 ? LF : '';
                     $val = is_array($val) ? implode($val, LF) : $val;
                     // convert form data from renderCharset to mail charset (HTML may use entities)
                     $plainTextValue = $val;
                     $HtmlValue = htmlspecialchars($val);
                     $plainTextContent .= strtoupper($key) . ':  ' . $space . $plainTextValue . LF . $space;
                     $htmlContent .= '<tr><td bgcolor="#eeeeee"><font face="Verdana" size="1"><strong>' . strtoupper($key) . '</strong></font></td><td bgcolor="#eeeeee"><font face="Verdana" size="1">' . nl2br($HtmlValue) . '&nbsp;</font></td></tr>';
                 }
             }
         }
         $htmlContent .= '</table>';
         $this->plainContent = $plainTextContent;
         if ($valueList['html_enabled']) {
             $this->mailMessage->setBody($htmlContent, 'text/html');
             $this->mailMessage->addPart($plainTextContent, 'text/plain');
         } else {
             $this->mailMessage->setBody($plainTextContent, 'text/plain');
         }
         for ($a = 0; $a < 10; $a++) {
             $variableName = 'attachment' . ($a ? $a : '');
             if (!isset($_FILES[$variableName])) {
                 continue;
             }
             if (!is_uploaded_file($_FILES[$variableName]['tmp_name'])) {
                 t3lib_div::sysLog('Possible abuse of t3lib_formmail: temporary file "' . $_FILES[$variableName]['tmp_name'] . '" ("' . $_FILES[$variableName]['name'] . '") was not an uploaded file.', 'Core', 3);
             }
             if ($_FILES[$variableName]['tmp_name']['error'] !== UPLOAD_ERR_OK) {
                 t3lib_div::sysLog('Error in uploaded file in t3lib_formmail: temporary file "' . $_FILES[$variableName]['tmp_name'] . '" ("' . $_FILES[$variableName]['name'] . '") Error code: ' . $_FILES[$variableName]['tmp_name']['error'], 'Core', 3);
             }
             $theFile = t3lib_div::upload_to_tempfile($_FILES[$variableName]['tmp_name']);
             $theName = $_FILES[$variableName]['name'];
             if ($theFile && file_exists($theFile)) {
                 if (filesize($theFile) < $GLOBALS['TYPO3_CONF_VARS']['FE']['formmailMaxAttachmentSize']) {
                     $this->mailMessage->attach(Swift_Attachment::fromPath($theFile)->setFilename($theName));
                 }
             }
             $this->temporaryFiles[] = $theFile;
         }
         $from = $this->fromName ? array($this->fromAddress => $this->fromName) : array($this->fromAddress);
         $this->recipient = $this->parseAddresses($valueList['recipient']);
         $this->mailMessage->setSubject($this->subject)->setFrom($from)->setTo($this->recipient)->setPriority($this->priority);
         $replyTo = $this->replyToName ? array($this->replyToAddress => $this->replyToName) : array($this->replyToAddress);
         $this->mailMessage->addReplyTo($replyTo);
         $this->mailMessage->getHeaders()->addTextHeader('Organization', $this->organisation);
         if ($valueList['recipient_copy']) {
             $this->mailMessage->addCc($this->parseAddresses($valueList['recipient_copy']));
         }
         if ($this->characterSet) {
             $this->mailMessage->setCharset($this->characterSet);
         }
         // Ignore target encoding. This is handled automatically by Swift Mailer and overriding the defaults
         // is not worth the trouble
         // log dirty header lines
         if ($this->dirtyHeaders) {
             t3lib_div::sysLog('Possible misuse of t3lib_formmail: see TYPO3 devLog', 'Core', 3);
             if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['enable_DLOG']) {
                 t3lib_div::devLog('t3lib_formmail: ' . t3lib_div::arrayToLogString($this->dirtyHeaders, '', 200), 'Core', 3);
             }
         }
     }
 }
 /**
  * Build and send warning email when new broken links were found.
  *
  * @param	string		$pageSections: Content of page section
  * @param	string		$modTS: TSconfig array
  * @return	bool		TRUE if mail was sent, FALSE if or not
  */
 protected function reportEmail($pageSections, $modTS)
 {
     $content = t3lib_parsehtml::substituteSubpart($this->templateMail, '###PAGE_SECTION###', $pageSections);
     /** @var array $markerArray */
     $markerArray = array();
     /** @var array $validEmailList */
     $validEmailList = array();
     /** @var boolean $sendEmail */
     $sendEmail = TRUE;
     $markerArray['totalBrokenLink'] = $this->totalBrokenLink;
     $markerArray['totalBrokenLink_old'] = $this->oldTotalBrokenLink;
     $content = t3lib_parsehtml::substituteMarkerArray($content, $markerArray, '###|###', TRUE, TRUE);
     /** @var t3lib_mail_Message $mail */
     $mail = t3lib_div::makeInstance('t3lib_mail_Message');
     if (empty($modTS['mail.']['fromemail'])) {
         $modTS['mail.']['fromemail'] = t3lib_utility_Mail::getSystemFromAddress();
     }
     if (empty($modTS['mail.']['fromname'])) {
         $modTS['mail.']['fromname'] = t3lib_utility_Mail::getSystemFromName();
     }
     if (t3lib_div::validEmail($modTS['mail.']['fromemail'])) {
         $mail->setFrom(array($modTS['mail.']['fromemail'] => $modTS['mail.']['fromname']));
     } else {
         throw new Exception($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/locallang.xml:tasks.error.invalidFromEmail'), '1295476760');
     }
     if (t3lib_div::validEmail($modTS['mail.']['replytoemail'])) {
         $mail->setReplyTo(array($modTS['mail.']['replytoemail'] => $modTS['mail.']['replytoname']));
     }
     if (!empty($modTS['mail.']['subject'])) {
         $mail->setSubject($modTS['mail.']['subject']);
     } else {
         throw new Exception($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/locallang.xml:tasks.error.noSubject'), '1295476808');
     }
     if (!empty($this->email)) {
         $emailList = t3lib_div::trimExplode(',', $this->email);
         foreach ($emailList as $emailAdd) {
             if (!t3lib_div::validEmail($emailAdd)) {
                 throw new Exception($GLOBALS['LANG']->sL('LLL:EXT:linkvalidator/locallang.xml:tasks.error.invalidToEmail'), '1295476821');
             } else {
                 $validEmailList[] = $emailAdd;
             }
         }
     }
     if (is_array($validEmailList) && !empty($validEmailList)) {
         $mail->setTo($this->email);
     } else {
         $sendEmail = FALSE;
     }
     if ($sendEmail) {
         $mail->setBody($content, 'text/html');
         $mail->send();
     }
     return $sendEmail;
 }
 /**
  * Applies validation rules specified in TS setup
  *
  * @param array  Array with key/values being marker-strings/substitution values.
  * @return void  on return, the ControlData failure will contain the list of fields which were not ok
  */
 public function evalValues($theTable, array &$dataArray, array &$origArray, array &$markContentArray, $cmdKey, array $requiredArray)
 {
     $failureMsg = array();
     $displayFieldArray = t3lib_div::trimExplode(',', $this->conf[$cmdKey . '.']['fields'], 1);
     if ($this->controlData->useCaptcha($this->conf, $cmdKey)) {
         $displayFieldArray = array_merge($displayFieldArray, array('captcha_response'));
     }
     // Check required, set failure if not ok.
     $failureArray = array();
     foreach ($requiredArray as $k => $theField) {
         $bIsMissing = FALSE;
         if (isset($dataArray[$theField])) {
             if (empty($dataArray[$theField]) && $dataArray[$theField] != '0') {
                 $bIsMissing = TRUE;
             }
         } else {
             $bIsMissing = TRUE;
         }
         if ($bIsMissing) {
             $failureArray[] = $theField;
             $this->missing[$theField] = TRUE;
         }
     }
     $pid = intval($dataArray['pid']);
     // 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!
     $bRecordExists = FALSE;
     if (is_array($this->conf[$cmdKey . '.']['evalValues.'])) {
         $cmd = $this->controlData->getCmd();
         if ($cmd == 'edit' || $cmdKey == 'edit') {
             if ($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.
                 $recordTestPid = $pid;
             } else {
                 $tempRecArr = $GLOBALS['TSFE']->sys_page->getRawRecord($this->controlData->getTable(), $dataArray['uid']);
                 $recordTestPid = intval($tempRecArr['pid']);
             }
             $bRecordExists = $recordTestPid != 0;
         } else {
             $thePid = $this->controlData->getPid();
             $recordTestPid = $thePid ? $thePid : (method_exists('TYPO3\\CMS\\Core\\Utility\\MathUtility', 'convertToPositiveInteger') ? \TYPO3\CMS\Core\Utility\MathUtility::convertToPositiveInteger($pid) : t3lib_div::intval_positive($pid));
         }
         // TODO: Fix scope issue: unsetting $conf entry in tx_srfeuserregister_control->init2 has no effect
         // Do not evaluate any password when inviting
         if ($cmdKey == 'invite') {
             unset($this->conf[$cmdKey . '.']['evalValues.']['password']);
         }
         // Do not evaluate the username if it is generated or if email is used
         if ($this->conf[$cmdKey . '.']['useEmailAsUsername'] || $this->conf[$cmdKey . '.']['generateUsername'] && $cmdKey != 'edit' && $cmdKey != 'password') {
             unset($this->conf[$cmdKey . '.']['evalValues.']['username']);
         }
         $countArray = array();
         $countArray['hook'] = array();
         $countArray['preg'] = array();
         foreach ($this->conf[$cmdKey . '.']['evalValues.'] as $theField => $theValue) {
             $this->evalErrors[$theField] = array();
             $failureMsg[$theField] = array();
             $listOfCommands = t3lib_div::trimExplode(',', $theValue, 1);
             // Unset the incoming value is empty and unsetEmpty is specified
             if (array_search('unsetEmpty', $listOfCommands) !== FALSE) {
                 if (isset($dataArray[$theField]) && empty($dataArray[$theField]) && trim($dataArray[$theField]) !== '0') {
                     unset($dataArray[$theField]);
                 }
                 if (isset($dataArray[$theField . '_again']) && empty($dataArray[$theField . '_again']) && trim($dataArray[$theField . '_again']) !== '0') {
                     unset($dataArray[$theField . '_again']);
                 }
             }
             if (isset($dataArray[$theField]) || isset($dataArray[$theField . '_again']) || !count($origArray) || !isset($origArray[$theField])) {
                 foreach ($listOfCommands as $k => $cmd) {
                     $cmdParts = preg_split('/\\[|\\]/', $cmd);
                     // Point is to enable parameters after each command enclosed in brackets [..]. These will be in position 1 in the array.
                     $theCmd = trim($cmdParts[0]);
                     switch ($theCmd) {
                         case 'uniqueGlobal':
                         case 'uniqueDeletedGlobal':
                         case 'uniqueLocal':
                         case 'uniqueDeletedLocal':
                             $where = $theField . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($dataArray[$theField], $theTable);
                             if ($theCmd == 'uniqueLocal' || $theCmd == 'uniqueGlobal') {
                                 $where .= $GLOBALS['TSFE']->sys_page->deleteClause($theTable);
                             }
                             if ($theCmd == 'uniqueLocal' || $theCmd == 'uniqueDeletedLocal') {
                                 $where .= ' AND pid IN (' . $recordTestPid . ')';
                             }
                             $DBrows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid,' . $theField, $theTable, $where, '', '', '1');
                             if (!is_array($dataArray[$theField]) && trim($dataArray[$theField]) != '' && isset($DBrows) && is_array($DBrows) && isset($DBrows[0]) && is_array($DBrows[0])) {
                                 if (!$bRecordExists || $DBrows[0]['uid'] != $dataArray['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.
                                     $failureArray[] = $theField;
                                     $this->inError[$theField] = TRUE;
                                     $this->evalErrors[$theField][] = $theCmd;
                                     $failureMsg[$theField][] = $this->getFailureText($theField, 'uniqueLocal', 'evalErrors_existed_already');
                                 }
                             }
                             break;
                         case 'twice':
                             $fieldValue = strval($dataArray[$theField]);
                             $fieldAgainValue = strval($dataArray[$theField . '_again']);
                             if (strcmp($fieldValue, $fieldAgainValue)) {
                                 $failureArray[] = $theField;
                                 $this->inError[$theField] = TRUE;
                                 $this->evalErrors[$theField][] = $theCmd;
                                 $failureMsg[$theField][] = $this->getFailureText($theField, $theCmd, 'evalErrors_same_twice');
                             }
                             break;
                         case 'email':
                             if (!is_array($dataArray[$theField]) && trim($dataArray[$theField]) && !t3lib_div::validEmail($dataArray[$theField])) {
                                 $failureArray[] = $theField;
                                 $this->inError[$theField] = TRUE;
                                 $this->evalErrors[$theField][] = $theCmd;
                                 $failureMsg[$theField][] = $this->getFailureText($theField, $theCmd, 'evalErrors_valid_email');
                             }
                             break;
                         case 'required':
                             if (empty($dataArray[$theField]) && $dataArray[$theField] !== '0') {
                                 $failureArray[] = $theField;
                                 $this->inError[$theField] = TRUE;
                                 $this->evalErrors[$theField][] = $theCmd;
                                 $failureMsg[$theField][] = $this->getFailureText($theField, $theCmd, 'evalErrors_required');
                             }
                             break;
                         case 'atLeast':
                             $chars = intval($cmdParts[1]);
                             if (!is_array($dataArray[$theField]) && strlen($dataArray[$theField]) < $chars) {
                                 $failureArray[] = $theField;
                                 $this->inError[$theField] = TRUE;
                                 $this->evalErrors[$theField][] = $theCmd;
                                 $failureMsg[$theField][] = sprintf($this->getFailureText($theField, $theCmd, 'evalErrors_atleast_characters'), $chars);
                             }
                             break;
                         case 'atMost':
                             $chars = intval($cmdParts[1]);
                             if (!is_array($dataArray[$theField]) && strlen($dataArray[$theField]) > $chars) {
                                 $failureArray[] = $theField;
                                 $this->inError[$theField] = TRUE;
                                 $this->evalErrors[$theField][] = $theCmd;
                                 $failureMsg[$theField][] = sprintf($this->getFailureText($theField, $theCmd, 'evalErrors_atmost_characters'), $chars);
                             }
                             break;
                         case 'inBranch':
                             $pars = explode(';', $cmdParts[1]);
                             if (intval($pars[0])) {
                                 $pid_list = $this->cObj->getTreeList(intval($pars[0]), intval($pars[1]) ? intval($pars[1]) : 999, intval($pars[2]));
                                 if (!$pid_list || !t3lib_div::inList($pid_list, $dataArray[$theField])) {
                                     $failureArray[] = $theField;
                                     $this->inError[$theField] = TRUE;
                                     $this->evalErrors[$theField][] = $theCmd;
                                     $failureMsg[$theField][] = sprintf($this->getFailureText($theField, $theCmd, 'evalErrors_unvalid_list'), $pid_list);
                                 }
                             }
                             break;
                         case 'upload':
                             if ($dataArray[$theField] && is_array($GLOBALS['TCA'][$theTable]['columns'][$theField]['config'])) {
                                 $colSettings = $GLOBALS['TCA'][$theTable]['columns'][$theField];
                                 $colConfig = $colSettings['config'];
                                 if ($colConfig['type'] == 'group' && $colConfig['internal_type'] == 'file') {
                                     $uploadPath = $colConfig['uploadfolder'];
                                     $allowedExtArray = t3lib_div::trimExplode(',', $colConfig['allowed'], 1);
                                     $maxSize = $colConfig['max_size'];
                                     $fileNameArray = $dataArray[$theField];
                                     $newFileNameArray = array();
                                     if (is_array($fileNameArray) && $fileNameArray[0] != '') {
                                         foreach ($fileNameArray as $k => $filename) {
                                             if (is_array($filename)) {
                                                 $filename = $filename['name'];
                                             }
                                             $bAllowedFilename = $this->checkFilename($filename);
                                             $fI = pathinfo($filename);
                                             $fileExtension = strtolower($fI['extension']);
                                             $fullfilename = PATH_site . $uploadPath . '/' . $filename;
                                             if ($bAllowedFilename && (!count($allowedExtArray) || in_array($fileExtension, $allowedExtArray))) {
                                                 if (@is_file($fullfilename)) {
                                                     if (!$maxSize || filesize(PATH_site . $uploadPath . '/' . $filename) < $maxSize * 1024) {
                                                         $newFileNameArray[] = $filename;
                                                     } else {
                                                         $this->evalErrors[$theField][] = $theCmd;
                                                         $failureMsg[$theField][] = sprintf($this->getFailureText($theField, 'max_size', 'evalErrors_size_too_large'), $maxSize);
                                                         $failureArray[] = $theField;
                                                         $this->inError[$theField] = TRUE;
                                                         if (@is_file(PATH_site . $uploadPath . '/' . $filename)) {
                                                             @unlink(PATH_site . $uploadPath . '/' . $filename);
                                                         }
                                                     }
                                                 } else {
                                                     if (isset($_FILES) && is_array($_FILES) && isset($_FILES['FE']) && is_array($_FILES['FE']) && isset($_FILES['FE']['tmp_name']) && is_array($_FILES['FE']['tmp_name']) && isset($_FILES['FE']['tmp_name'][$theTable]) && is_array($_FILES['FE']['tmp_name'][$theTable]) && isset($_FILES['FE']['tmp_name'][$theTable][$theField]) && is_array($_FILES['FE']['tmp_name'][$theTable][$theField]) && isset($_FILES['FE']['tmp_name'][$theTable][$theField][$k])) {
                                                         $bWritePermissionError = TRUE;
                                                     } else {
                                                         $bWritePermissionError = FALSE;
                                                     }
                                                     $this->evalErrors[$theField][] = $theCmd;
                                                     $failureMsg[$theField][] = sprintf($this->getFailureText($theField, 'isfile', $bWritePermissionError ? 'evalErrors_write_permission' : 'evalErrors_file_upload'), $filename);
                                                     $failureArray[] = $theField;
                                                 }
                                             } else {
                                                 $this->evalErrors[$theField][] = $theCmd;
                                                 $failureMsg[$theField][] = sprintf($this->getFailureText($theField, 'allowed', 'evalErrors_file_extension'), $fileExtension);
                                                 $failureArray[] = $theField;
                                                 $this->inError[$theField] = TRUE;
                                                 if ($bAllowedFilename && @is_file($fullfilename)) {
                                                     @unlink($fullfilename);
                                                 }
                                             }
                                         }
                                         $dataValue = $newFileNameArray;
                                         $dataArray[$theField] = $dataValue;
                                     }
                                 }
                             }
                             break;
                         case 'wwwURL':
                             if ($dataArray[$theField]) {
                                 $urlParts = parse_url($dataArray[$theField]);
                                 if ($urlParts === FALSE || !t3lib_div::isValidUrl($dataArray[$theField]) || $urlParts['scheme'] != 'http' && $urlParts['scheme'] != 'https' || $urlParts['user'] || $urlParts['pass']) {
                                     $failureArray[] = $theField;
                                     $this->inError[$theField] = TRUE;
                                     $this->evalErrors[$theField][] = $theCmd;
                                     $failureMsg[$theField][] = $this->getFailureText($theField, $theCmd, 'evalErrors_unvalid_url');
                                 }
                             }
                             break;
                         case 'date':
                             if (!is_array($dataArray[$theField]) && $dataArray[$theField] && !$this->evalDate($dataArray[$theField], $this->conf['dateFormat'])) {
                                 $failureArray[] = $theField;
                                 $this->inError[$theField] = TRUE;
                                 $this->evalErrors[$theField][] = $theCmd;
                                 $failureMsg[$theField][] = $this->getFailureText($theField, $theCmd, 'evalErrors_unvalid_date');
                             }
                             break;
                         case 'preg':
                             if (!is_array($dataArray[$theField]) && !(empty($dataArray[$theField]) && $dataArray[$theField] !== '0')) {
                                 if (isset($countArray['preg'][$theCmd])) {
                                     $countArray['preg'][$theCmd]++;
                                 } else {
                                     $countArray['preg'][$theCmd] = 1;
                                 }
                                 $pattern = str_replace('preg[', '', $cmd);
                                 $pattern = substr($pattern, 0, strlen($pattern) - 1);
                                 $matches = array();
                                 $test = preg_match($pattern, $dataArray[$theField], $matches);
                                 if ($test === FALSE || $test == 0) {
                                     $failureArray[] = $theField;
                                     $this->inError[$theField] = TRUE;
                                     $this->evalErrors[$theField][] = $theCmd;
                                     $failureMsg[$theField][] = $this->getFailureText($theField, $theCmd, 'evalErrors_' . $theCmd, $countArray['preg'][$theCmd], $cmd, $test === FALSE);
                                 }
                             }
                             break;
                         case 'hook':
                         default:
                             if (isset($countArray['hook'][$theCmd])) {
                                 $countArray['hook'][$theCmd]++;
                             } else {
                                 $countArray['hook'][$theCmd] = 1;
                             }
                             $extKey = $this->controlData->getExtKey();
                             $prefixId = $this->controlData->getPrefixId();
                             $hookClassArray = $GLOBALS['TYPO3_CONF_VARS']['EXTCONF'][$extKey][$prefixId]['model'];
                             if (is_array($hookClassArray)) {
                                 foreach ($hookClassArray as $classRef) {
                                     $hookObj = t3lib_div::getUserObj($classRef);
                                     if (is_object($hookObj) && method_exists($hookObj, 'evalValues')) {
                                         $test = FALSE;
                                         // set it to TRUE when you test the hooks
                                         $bInternal = FALSE;
                                         $errorField = $hookObj->evalValues($theTable, $dataArray, $origArray, $markContentArray, $cmdKey, $requiredArray, $theField, $cmdParts, $bInternal, $test, $this);
                                         if ($errorField != '') {
                                             $failureArray[] = $errorField;
                                             $this->evalErrors[$theField][] = $theCmd;
                                             if (!$test) {
                                                 $this->inError[$theField] = TRUE;
                                                 $failureMsg[$theField][] = $this->getFailureText($theField, $theCmd, 'evalErrors_' . $theCmd, $countArray['hook'][$theCmd], $cmd, $bInternal);
                                             }
                                             break;
                                         }
                                     } else {
                                         debug($classRef, 'error in the class name for the hook "model"');
                                         // keep debug
                                     }
                                 }
                             }
                             break;
                     }
                 }
             }
             if (in_array($theField, $displayFieldArray) || in_array($theField, $failureArray)) {
                 if (!empty($failureMsg[$theField])) {
                     if ($markContentArray['###EVAL_ERROR_saved###']) {
                         $markContentArray['###EVAL_ERROR_saved###'] .= '<br />';
                     }
                     $errorMsg = implode($failureMsg[$theField], '<br />');
                     $markContentArray['###EVAL_ERROR_saved###'] .= $errorMsg;
                 } else {
                     $errorMsg = '';
                 }
                 $markContentArray['###EVAL_ERROR_FIELD_' . $theField . '###'] = $errorMsg != '' ? $errorMsg : '<!--no error-->';
             }
         }
     }
     if (empty($markContentArray['###EVAL_ERROR_saved###'])) {
         $markContentArray['###EVAL_ERROR_saved###'] = '';
     }
     if ($this->missing['zone'] && t3lib_extMgm::isLoaded(STATIC_INFO_TABLES_EXT)) {
         $staticInfoObj = t3lib_div::getUserObj('&tx_staticinfotables_pi1');
         // empty zone if there is not zone for the provided country
         $zoneArray = $staticInfoObj->initCountrySubdivisions($dataArray['static_info_country']);
         if (!isset($zoneArray) || is_array($zoneArray) && !count($zoneArray)) {
             unset($this->missing['zone']);
             $k = array_search('zone', $failureArray);
             unset($failureArray[$k]);
         }
     }
     $failure = implode($failureArray, ',');
     $this->controlData->setFailure($failure);
     return $this->evalErrors;
 }
 public function PM_SubmitEmailHook(&$subpart, &$maildata, &$sessiondata, &$markerArray, &$powermail)
 {
     if ($powermail->cObj->cObjGetSingle($powermail->conf['allow.']['sender_overwrite'], $powermail->conf['allow.']['sender_overwrite.'])) {
         if ($subpart == 'sender_mail') {
             $email = $powermail->cObj->cObjGetSingle($powermail->conf['email.']['sender_mail.']['receiver.']['email'], $powermail->conf['email.']['sender_mail.']['receiver.']['email.']);
             if (t3lib_div::validEmail($email)) {
                 $maildata['receiver'] = $email;
             }
         }
         $senderName = $powermail->cObj->cObjGetSingle($powermail->conf['email.']['sender_mail.']['sender.']['name'], $powermail->conf['email.']['sender_mail.']['sender.']['name.']);
         if (!empty($senderName)) {
             if ($senderName == 'empty') {
                 $maildata['sendername'] = $maildata['sender'];
             } else {
                 $maildata['sendername'] = $senderName;
             }
         }
     }
     $conf = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_hetools_pi1.']['powermail.'];
     if (!empty($conf['receiverlist_replace.'])) {
         $replaceConf = $conf['receiverlist_replace.'];
     } else {
         if (!empty($conf['field_replace.'])) {
             $replaceConf = $conf['field_replace.'];
         }
     }
     if (!empty($replaceConf)) {
         $uid = $selectCondition[$selectVal];
         $thema = $powermail->sessiondata['uid' . $uid];
         $maildata['subject'] = str_replace('###THEMA###', $thema, $maildata['subject']);
     }
     if (!empty($conf['receiverlist_replace.'])) {
         $selectFieldUid = $conf['receiverlist_replace.']['selectFieldUid'];
         $selectVal = $powermail->sessionfields['uid' . $selectFieldUid];
         $selectCondition = $conf['receiverlist_replace.']['uid_condition.'];
         $uid = $selectCondition[$selectVal];
         $mailId = $powermail->sessionfields['uid' . $uid];
         $thema = $powermail->sessiondata['uid' . $uid];
         $senderName = $powermail->sessiondata['uid' . $conf['receiverlist_replace.']['senderName']];
         $senderEmail = $powermail->sessiondata['uid' . $conf['receiverlist_replace.']['senderEmail']];
         if (empty($senderName)) {
             $senderName = $maildata['sendername'];
         }
         if (empty($senderEmail)) {
             $senderEmail = $maildata['sender'];
         }
         $where = 'deleted=0 AND uid=' . $mailId;
         $data = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('email', ' tx_he_personen', $where);
         $GLOBALS['TYPO3_DB']->sql_free_result($result);
         if ($subpart == 'sender_mail') {
             $maildata['receiver'] = $senderEmail;
             $maildata['receivername'] = $senderName;
             $maildata['sender'] = $data['email'];
             $maildata['sendername'] = 'Hochschule Esslingen';
         } else {
             $maildata['receiver'] = $data['email'];
             $maildata['sender'] = $senderEmail;
             $maildata['sendername'] = $senderName;
         }
     }
     /*		
     if ($GLOBALS['TSFE']->fe_user->user['username']=='mmirsch' || $GLOBALS['TSFE']->fe_user->user['username']=='sb_online_mmirsch') {
     	t3lib_div::devlog("maildata nachher","PM_SubmitEmailHook",0,$maildata);
     	t3lib_div::devlog("sendername nachher","PM_SubmitEmailHook",0,$senderName);
     }
     */
 }
 /**
  * checkChangesAndSendNotificationEmails
  *
  * TODO: Add "send overdue tickets" functionality and make this function
  * work standalone in order to use it with a cronjob.
  *
  * $changedFields and $changedInternalFields are comma-separated lists of the fields that have changed.
  *
  * @param integer $ticket_uid
  * @param string $changedFields
  * @param string $changedInternalFields
  * @access public
  * @return void
  */
 public function checkChangesAndSendNotificationEmails($ticket_uid, $changedFields, $changedInternalFields = '')
 {
     /*{{{*/
     $lcObj = t3lib_div::makeInstance('tslib_cObj');
     // a notification will be sent if a ticket has been updated and
     // 1. notification setting is "always"
     // 2. notification setting is "onstatuschange" and the "status" field changed
     // 3. notification setting is "defined in typoscript" and the typoscript
     // options match the list of changed fields
     // The notification setting is done in the plugin via flexform.
     // does this ticket exist?
     $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->tablename, 'uid=' . $ticket_uid . $lcObj->enableFields($this->tablename));
     if ($GLOBALS['TYPO3_DB']->sql_num_rows($res) > 0) {
         // get the ticket data
         $this->internal['currentTable'] = $this->tablename;
         $this->internal['currentRow'] = $this->pi_getRecord($this->tablename, $ticket_uid);
         // render the mailbody for standard mails to non-internal users
         // the second parameter has to be empty, because we don't want any
         // changes of internal fields sent to non-internal users!
         $emailbody = $this->renderNotificationMail($changedFields, '');
         // render the mailbody for internal mails
         // on new tickets, render all internal fields, on updated tickets, render
         // only fields which have changed
         if (stristr($changedFields, CONST_NEWTICKET)) {
             $emailbody_internal = $this->renderNotificationMail($changedFields, CONST_RENDER_ALL_INTERNAL_FIELDS);
         } else {
             $emailbody_internal = $this->renderNotificationMail($changedFields, $changedInternalFields);
         }
         // render the subject
         if ($this->conf['email_notifications.']['subject_prefix']) {
             $subject = $this->conf['email_notifications.']['subject_prefix'] . ' ';
         } else {
             $subject = '';
         }
         // add ticket uid to subject if set in TS
         if ($this->conf['email_notifications.']['add_uid_to_subject']) {
             $subject .= sprintf($this->conf['ticket_uid_formatstring'], $ticket_uid) . ' ';
         }
         // add the status to the subject if it has changed
         // otherwise just add the word "changed"
         if (stristr($changedFields, CONST_NEWTICKET)) {
             $subject .= $this->pi_getLL('email_subject_type_new', 'new') . ': ';
         } else {
             if (stristr($changedFields, CONST_REOPENANDCOMMENT)) {
                 $subject .= $this->pi_getLL('email_subject_type_newcomment_reopen', 'new comment and re-open') . ': ';
             } else {
                 if (stristr($changedFields, CONST_ONSTATUSCHANGE)) {
                     $subject .= $this->pi_getLL('SELECTLABEL_' . strtoupper(trim($this->internal['currentRow']['status'])), $this->internal['currentRow']['status']) . ': ';
                 } else {
                     $subject .= $this->pi_getLL('email_subject_type_changed', 'changed') . ': ';
                 }
             }
         }
         $subject .= $this->internal['currentRow']['title'];
         // Andreas Kiefer, kiefer@kennziffer.com, 15:15 15.05.2009
         // don't send if only internal fields are changed,
         // that are configured as "don't send notification" in TS
         $sendNotification = false;
         // always send notification if "normal" fields have been changed
         if ($changedFields != "") {
             $sendNotification = true;
         } else {
             // check if only fields have been changed where
             // no notification is wanted. this applies only to
             // internal fields
             $internalFieldsWithoutNotification = t3lib_div::trimExplode(',', $this->conf['email_notifications.']['internalFieldsWithoutNotification']);
             $changedInternalFieldsArray = explode(',', $changedInternalFields);
             foreach ($changedInternalFieldsArray as $internalField) {
                 if (!in_array($internalField, $internalFieldsWithoutNotification)) {
                     $sendNotification = true;
                 }
             }
         }
         // send notifications to owner
         if ($this->internal['currentRow']['owner_feuser'] && ($this->internal['currentRow']['notifications_owner'] == CONST_ONEVERYCHANGE || $this->internal['currentRow']['notifications_owner'] == CONST_ONSTATUSCHANGE && t3lib_div::inList($changedFields, 'status') || $this->internal['currentRow']['notifications_owner'] == CONST_TYPOSCRIPT && $this->checkCustomNotificationCondition($changedFields, $this->conf['email_notifications.']['ownerNotificationOnChangedFields'])) && $sendNotification) {
             // get the user data of the owner
             $fe_user_data = $this->getFeUserData($this->internal['currentRow']['owner_feuser']);
             // send standard mail
             if (is_array($fe_user_data) && t3lib_div::validEmail($fe_user_data['email']) && !empty($changedFields) && !$this->isUserInternalUser($fe_user_data['uid'])) {
                 $this->sendNotificationEmail($fe_user_data['email'], $subject, $emailbody);
             }
             // send internal mail
             if (is_array($fe_user_data) && t3lib_div::validEmail($fe_user_data['email']) && (!empty($changedFields) || !empty($changedInternalFields)) && $this->isUserInternalUser($fe_user_data['uid'])) {
                 $this->sendNotificationEmail($fe_user_data['email'], $subject, $emailbody_internal);
             }
         }
         // send notifications to responsible user
         if ($this->internal['currentRow']['responsible_feuser'] && ($this->internal['currentRow']['notifications_responsible'] == CONST_ONEVERYCHANGE || $this->internal['currentRow']['notifications_responsible'] == CONST_ONSTATUSCHANGE && t3lib_div::inList($changedFields, 'status') || $this->internal['currentRow']['notifications_responsible'] == CONST_TYPOSCRIPT && $this->checkCustomNotificationCondition($changedFields, $this->conf['email_notifications.']['responsibleNotificationOnChangedFields'])) && $sendNotification) {
             // get the user data of the responsible user
             $fe_user_data = $this->getFeUserData($this->internal['currentRow']['responsible_feuser']);
             // send standard mail
             if (is_array($fe_user_data) && t3lib_div::validEmail($fe_user_data['email']) && !empty($changedFields) && !$this->isUserInternalUser($fe_user_data['uid'])) {
                 $this->sendNotificationEmail($fe_user_data['email'], $subject, $emailbody);
             }
             // send internal mail
             if (is_array($fe_user_data) && t3lib_div::validEmail($fe_user_data['email']) && (!empty($changedFields) || !empty($changedInternalFields)) && $this->isUserInternalUser($fe_user_data['uid'])) {
                 $this->sendNotificationEmail($fe_user_data['email'], $subject, $emailbody_internal);
             }
         }
         // list of observers
         if ($this->internal['currentRow']['observers_feuser']) {
             $observers = t3lib_div::trimExplode(',', $this->internal['currentRow']['observers_feuser']);
         } else {
             $observers = array();
         }
         // if the owner, the responsible user or the observers have changed,
         // treat the former owner, former responsible user and former observers
         // temporarily as observers (for this change only). For example, This notifies former responsible
         // users that they are not responsible anymore.
         if ($this->internal['currentRow']['owner_feuser'] != $this->oldTicket['owner_feuser']) {
             $observers[] = $this->oldTicket['owner_feuser'];
         }
         if ($this->internal['currentRow']['responsible_feuser'] != $this->oldTicket['responsible_feuser']) {
             $observers[] = $this->oldTicket['responsible_feuser'];
         }
         if ($this->oldTicket['observers_feuser']) {
             $observers_old = t3lib_div::trimExplode(',', $this->oldTicket['observers_feuser']);
             foreach ($observers_old as $observer_old) {
                 if (!in_array($observer_old, $observers)) {
                     $observers[] = $observer_old;
                 }
             }
         }
         // send notifications to observers
         if (count($observers)) {
             foreach ($observers as $observer_uid) {
                 if ($this->checkIfNotificationShouldBeSentToObservers() && $sendNotification) {
                     // get the user data of the observer
                     $fe_user_data = $this->getFeUserData($observer_uid);
                     // send standard mail
                     if (is_array($fe_user_data) && t3lib_div::validEmail($fe_user_data['email']) && !empty($changedFields) && !$this->isUserInternalUser($fe_user_data['uid'])) {
                         $this->sendNotificationEmail($fe_user_data['email'], $subject, $emailbody);
                     }
                     // send internal mail
                     if (is_array($fe_user_data) && t3lib_div::validEmail($fe_user_data['email']) && (!empty($changedFields) || !empty($changedInternalFields)) && $this->isUserInternalUser($fe_user_data['uid'])) {
                         $this->sendNotificationEmail($fe_user_data['email'], $subject, $emailbody_internal);
                     }
                 }
             }
         }
         // send notification to external observers
         if (!empty($this->internal['currentRow']['externalobservers'])) {
             $emails = t3lib_div::trimExplode("\n", $this->internal['currentRow']['externalobservers'], TRUE);
             foreach ($emails as $email) {
                 if (t3lib_div::validEmail($email) && $this->checkIfNotificationShouldBeSentToObservers() && $sendNotification && !empty($changedFields)) {
                     // send standard email (not internal)
                     $this->sendNotificationEmail($email, $subject, $emailbody);
                 }
             }
         }
     }
 }