*
 * based on w3concepts.form.v1 from Andreas Kummer (2004-08-20)
 * modified and adapted to Contenido 4.8 under PHP 5.x by Murat Purc (2013-08-24)
 */
$sFrontEndPath = cRegistry::getClientConfig(cRegistry::getClientId())['path']['frontend'] . 'securimage' . DIRECTORY_SEPARATOR;
$captchaInstalled = false;
if (is_readable($sFrontEndPath)) {
    require_once $sFrontEndPath . 'securimage.php';
    require_once $sFrontEndPath . 'CaptchaObject.php';
    require_once $sFrontEndPath . 'StorageAdapter/AdapterInterface.php';
    $captchaInstalled = true;
}
class FormGenerator
{
    public $emailAdresses;
    private array $email = ['adresses' => '', 'from' => ['name' => '', 'email' => ''], 'message' => '', 'subject' => ''];
    private array $unraveled = [];
    private array $form = ['form' => '', 'answer' => '', 'colorError' => ''];
    public function __construct(private bool $captchaInstalled, private cSession $cSession)
    {
    }
    private function sendEmail(): bool
    {
        $this->unravel($this->suppress('sent'));
        $this->generateEmailMessage();
        $phpMailer = new \PHPMailer\PHPMailer\PHPMailer(true);
        $phpMailer->isMail();
        $phpMailer->isHTML(false);
        $phpMailer->CharSet = "UTF-8";
        $phpMailer->AddAddress($this->email['adresses']);
        $phpMailer->setFrom($this->email['from']['email'], $this->email['from']['name']);
        $phpMailer->Subject = $this->email['subject'];
        $phpMailer->Body = $this->email['message'];
        try {
            if ($phpMailer->send()) {
                return true;
            }
        } catch (\PHPMailer\PHPMailer\Exception $e) {
            echo $e->errorMessage();
        }
        return false;
    }
    private function unravel($toUnravel, $prefix = ''): void
    {
        foreach ($toUnravel as $key => $value) {
            if (is_array($value)) {
                $this->unravel($value, $key . ' ');
            } else {
                $this->unraveled["{$prefix}{$key}"] = $value;
            }
        }
    }
    private function add2Message($key, $value): void
    {
        if (strlen($key) > 25 || strlen($value) > 54) {
            $this->email['message'] .= "$key\n$value\n";
        } else {
            $this->email['message'] .= $key;
            $this->email['message'] .= str_repeat(' ', 25 - strlen($key));
            $this->email['message'] .= "$value\n";
        }
    }
    private function generateEmailMessage(): void
    {
        foreach ($this->unraveled as $key => $value) {
            $this->add2Message($key, $value);
        }
    }
    private function suppress(...$suppress): array
    {
        $fields = [];
        foreach ($_POST as $key => $value) {
            if (!in_array($key, $suppress))
                $fields[$key] = $value;
        }
        return $fields;
    }
    public function addEmailAdress($email): void
    {
        if (empty($this->emailAdresses)) {
            $this->email['adresses'] .= "$email";
        } else {
            $this->email['adresses'] .= ", $email";
        }
    }
    public function setEmailSubject($subject): void
    {
        $this->email['subject'] = $subject;
    }
    public function setEmailFrom($email, $name): void
    {
        $this->email['from']['email'] = $email;
        $this->email['from']['name'] = $name;
    }
    public function setForm($form): void
    {
        $this->form['form'] = $form;
    }
    public function setAnswer($answer): void
    {
        $this->form['answer'] = $answer;
    }
    public function setBackgroundError($color): void
    {
        $this->form['colorError'] = $color;
    }
    public function formInterpretation(&$form): array
    {
        $fields = explode('###', $form);
        $field = [];
        $fieldsCount = count($fields);
        for ($i = 1; $i < $fieldsCount; $i += 2) {
            $attribute = explode(';', trim($fields[$i]));
            foreach ($attribute as $attribute) {
                $nameValue = explode(':', trim($attribute));
                if ($nameValue[0] != 'option' && $nameValue[0] != 'optionvalue') {
                    $field["{$fields[$i]}"]["{$nameValue[0]}"] = $nameValue[1];
                } else {
                    $field["{$fields[$i]}"]["{$nameValue[0]}"][] = $nameValue[1];
                }
            }
        }
        return $field;
    }
    public function formOutput($sent = false): void
    {
        $form_action = $this->cSession->url('front_content.php?idcat=' . cRegistry::getCategoryId() . '&idart=' . cRegistry::getArticleId());
        echo '
';
    }
    public function formField($attribute, $sent): void
    {
        $style = '';
        $value = '';
        $parameter = empty($attribute['id']) ? 'id="' . $attribute['name'] . '"' : 'id="' . $attribute['id'] . '"';
        $parameter .= ' name="' . $attribute['name'] . '"';
        if ($sent && !$this->formFieldCorrect($attribute)) {
            $style = 'style="background-color: ' . $this->form['colorError'] . ';"';
        }
        if (!empty($attribute['class'])) {
            $parameter .= ' class="' . $attribute['class'] . '"';
        }
        if (!empty($attribute['placeholder'])) {
            $parameter .= ' placeholder="' . $attribute['placeholder'] . '"';
        }
        switch ($attribute['type']) {
            case 'textarea':
            case 'text':
                if (!empty($attribute['size'])) {
                    $parameter .= ' size="' . $attribute['size'] . '"';
                }
                if (!empty($attribute['value'])) {
                    $value = $attribute['value'];
                }
                if (!empty($_POST["{$attribute['name']}"])) {
                    $value = $_POST["{$attribute['name']}"];
                }
                break;
            case 'select':
            case 'password':
                if (!empty($attribute['size'])) {
                    $parameter .= ' size="' . $attribute['size'] . '"';
                }
                break;
        }
        if (isset($attribute['required']) || isset($attribute['mandantory'])) {
            $parameter .= ' required';
        }
        switch ($attribute['type']) {
            case 'captcha':
                if ($this->captchaInstalled) {
                    if ($sent) {
                        $captcha = @$_POST['lets_check'];
                        $securimage = new Securimage();
                        if (!$securimage->check($captcha)) {
                            echo '';
                        }
                    }
                    // show captcha HTML using Securimage::getCaptchaHtml()
                    $options = [];
                    $options['show_audio_button'] = false;
                    $options['input_name'] = 'lets_check'; // change name of input element for form post input_text
                    $options['input_text'] = mi18n("Zeichen eingeben");
                    $options['input_required'] = true;
                    if (!empty($_SESSION['ctform']['captcha_error'])) {
                        // error html to show in captcha output
                        $options['error_html'] = $_SESSION['ctform']['captcha_error'];
                    }
                    echo "\n";
                    echo Securimage::getCaptchaHtml($options);
                    echo "\n
\n";
                    echo '';
                }
                break;
            case 'text':
            case 'email':
            case 'password':
                echo '';
                break;
            case 'textarea':
                echo "";
                break;
            case 'select':
                echo "";
                break;
            case 'checkbox':
                $formId = preg_split('[\[|\]]', $attribute['name']);
                if ($sent) {
                    if ($_POST["{$formId[0]}"]["{$formId[1]}"] == $attribute['value']) {
                        echo "";
                    } else {
                        echo "";
                    }
                } elseif (!empty($attribute['selected']) && $attribute['selected'] == 'true') {
                    echo "";
                } else {
                    echo "";
                }
                break;
            case 'radio':
                if (!empty($_POST["{$attribute['name']}"])) {
                    if ($_POST["{$attribute['name']}"] == $attribute['value']) {
                        echo "";
                    } else {
                        echo "";
                    }
                } elseif (!empty($attribute['selected']) && $attribute['selected'] == 'true') {
                    echo "";
                } else {
                    echo "";
                }
                break;
        }
    }
    private function formComplete(): bool
    {
        $form = $this->form['form'];
        $fields = $this->formInterpretation($form);
        foreach ($fields as $field) {
            switch ($field['type']) {
                case 'captcha':
                    if ($this->captchaInstalled) {
                        $captcha = @$_POST['lets_check'];
                        $capId = @$_POST['captcha_id'];
                        $securimage = new Securimage();
                        if (!$securimage->check($captcha, $capId, true)) {
                            echo '' . mi18n("Ihr Captcha Code war nicht korrekt. Bitte versuchen Sie es erneut.") . '
';
                            return false;
                        }
                    }
                    break;
                default:
                    if (!$this->formFieldCorrect($field)) {
                        return false;
                    }
            }
        }
        return true;
    }
    private function success(): void
    {
        if ($this->sendEmail()) {
            $answer = trim($this->form['answer']);
            if (mb_strlen($answer) > 0) {
                echo $this->form['answer'];
            } else {
                echo '' . mi18n("Form has been successfully send.") . '';
            }
        } else {
            echo '' . mi18n("Es ist  ein Fehler aufgetreten!
Bitte versuchen Sie es später noch einmal.") . '';
        }
    }
    private function formFieldCorrect(&$field): bool
    {
        $tmp_name = rtrim($field['name'], '[0]');
        preg_match('/\[(\d*)\]/', $field['name'], $matches);
        $bEmptyPost = false;
        $sPostFieldValue = $_POST[$tmp_name];
        if (is_array($_POST[$tmp_name])) {
            $sPostFieldValue = $_POST[$tmp_name][$matches[1]];
            if (empty($_POST[$tmp_name][$matches[1]])) {
                $bEmptyPost = true;
            }
        } elseif (empty($_POST[$tmp_name])) {
            $bEmptyPost = true;
        }
        if (!empty($field['mandatory']) && $field['mandatory'] == 'true' && $bEmptyPost) {
            return false;
        }
        // wenn das formularfeld kein pflichtfeld und nicht vorhanden ist, true zurückgeben
        if ($bEmptyPost) {
            return true;
        }
        // regular expression prüfungen
        if (!empty($field['valid'])) {
            switch ($field['valid']) {
                case 'textmitumbruch':
                    if (!filter_var($sPostFieldValue, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => "/^[\n\r,;:\. ÄÖÜäöüß\-\+\*§$%&\/()=?!\"'\w\d]*$/"]])) {
                        return false;
                    }
                    break;
                case 'simpletext':
                    if (!filter_var($sPostFieldValue, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => "/^[\w]*$/i"]])) {
                        return false;
                    }
                    break;
                case 'text':
                    if (!filter_var($sPostFieldValue, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => "/^[,;:\. ÄÖÜäöüß\-\+\*§$%&\/()=?!\"'\w\d]*$/"]])) {
                        return false;
                    }
                    break;
                case 'phone':
                    if (!filter_var($sPostFieldValue, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => "/^(\(?([\d \-\)\–\+\/\(]+){6,}\)?([ .\-–\/]?)([\d]+))$/"]])) {
                        return false;
                    }
                    break;
                case 'integer':
                    if (!filter_var($sPostFieldValue, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => "/^\d*$/"]])) {
                        return false;
                    }
                    break;
                case 'float':
                    if (!filter_var($sPostFieldValue, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => "/^[+-]?([0-9]*[.])?[0-9]+$/"]])) {
                        return false;
                    }
                    break;
                case 'date':
                    if (!filter_var($sPostFieldValue, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => "/^[0-9]{1,2}.[0-9]{1,2}.[0-9]{2,4}$/"]])) {
                        return false;
                    }
                    break;
                case 'email':
                    if (!filter_var($sPostFieldValue, FILTER_VALIDATE_REGEXP, ["options" => ["regexp" => "/^[öäüéàèâêîç_a-z0-9-]+(\.[öäüéàèâêîç_a-z0-9-]+)*@[öäüéàèâêîça-z0-9-]+(\.[öäüéàèâêîça-z0-9-]+)*$/"]])) {
                        return false;
                    }
                    break;
            }
        }
        // grössenbereich bei integer und float prüfen
        if (!empty($field['minvalue']) && $sPostFieldValue < $field['minvalue'])
            return false;
        if (!empty($field['maxvalue']) && $sPostFieldValue > $field['maxvalue'])
            return false;
        // längenbereich bei allen typen prüfen
        if (!empty($field['minlength']) && strlen($sPostFieldValue) < $field['minlength'])
            return false;
        return !(!empty($field['maxlength']) && strlen($sPostFieldValue) > $field['maxlength']);
    }
    public function process(): void
    {
        if (!isset($_POST['sent'])) {
            $this->formOutput();
        } elseif ($this->formComplete()) {
            $this->success();
        } else {
            $this->formOutput(true);
        }
    }
}
if (cRegistry::isBackendEditMode()) {
    echo "
";
    echo "" . mi18n("Formularkonfiguration") . "
";
    echo "" . mi18n("Hier ist das Formular sowie der Text einzugeben, der zusammen mit dem Formular ausgegeben werden soll:") . "
";
    echo "CMS_HTML[100]";
    echo "" . mi18n("Hier ist die Ausgabe einzugeben, die erscheint, wenn das Formular erfolgreich verschickt wurde:") . "
";
    echo "CMS_HTML[101]";
    echo "
";
} else {
    $form = new FormGenerator($captchaInstalled, $sess);
    $form->addEmailAdress("CMS_VALUE[0]");
    $form->setEmailSubject("CMS_VALUE[1]");
    $form->setEmailFrom("CMS_VALUE[2]", "CMS_VALUE[3]");
    $form->setBackgroundError("CMS_VALUE[4]");
    $form->setForm("CMS_HTML[100]");
    $form->setAnswer("CMS_HTML[101]");
    $form->process();
}
?>