Skip to content

Commit

Permalink
Adapted add-faq-form to #2886
Browse files Browse the repository at this point in the history
* fix: improved translations in forms

* refactor: moved add-faq-page to twig and improved form due to #2886

* fix: cleaned up add-faq-form

* fix: corrected translations due to #2886

* fix: fix minor bugs

* fix: added necessary blocks for twig

* fix: removed html from translations

* fix: resolve problem with missing escaping of html

* fix: remove inline css
  • Loading branch information
modelrailroader authored Jun 7, 2024
1 parent 3c2edfc commit 98804d3
Show file tree
Hide file tree
Showing 49 changed files with 244 additions and 67 deletions.
56 changes: 56 additions & 0 deletions phpmyfaq/add.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,22 @@

use phpMyFAQ\Captcha\Captcha;
use phpMyFAQ\Captcha\Helper\CaptchaHelper;
use phpMyFAQ\Category;
use phpMyFAQ\Configuration;
use phpMyFAQ\Enums\PermissionType;
use phpMyFAQ\Filter;
use phpMyFAQ\Helper\CategoryHelper as HelperCategory;
use phpMyFAQ\Question;
use phpMyFAQ\Strings;
use phpMyFAQ\System;
use phpMyFAQ\Template\TwigWrapper;
use phpMyFAQ\Translation;
use phpMyFAQ\User\CurrentUser;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use phpMyFAQ\Forms;
use phpMyFAQ\Enums\Forms\FormIds;
use phpMyFAQ\Enums\Forms\AddNewFaqInputIds;

if (!defined('IS_VALID_PHPMYFAQ')) {
http_response_code(400);
Expand Down Expand Up @@ -117,3 +122,54 @@
'msgNewContentSubmit' => Translation::get('msgNewContentSubmit'),
]
);

$forms = new Forms($faqConfig);
$formData = $forms->getFormData(FormIds::ADD_NEW_FAQ->value);

$category = new Category($faqConfig);
$categories = $category->getAllCategoryIds();

// Twig template variables
$templateVars = [
'baseHref' => $faqSystem->getSystemUri($faqConfig),
'msgNewContentHeader' => Translation::get('msgNewContentHeader'),
'msgNewContentAddon' => Translation::get('msgNewContentAddon'),
'lang' => $Language->getLanguage(),
'openQuestionID' => $selectedQuestion,
'defaultContentMail' => ($user->getUserId() > 0) ? $user->getUserData('email') : '',
'defaultContentName' =>
($user->getUserId() > 0) ? Strings::htmlentities($user->getUserData('display_name')) : '',
'msgNewContentName' => Translation::get('msgNewContentName'),
'msgNewContentMail' => Translation::get('msgNewContentMail'),
'msgNewContentCategory' => Translation::get('msgNewContentCategory'),
'renderCategoryOptions' => $categoryHelper->renderOptions($selectedCategory),
'msgNewContentTheme' => Translation::get('msgNewContentTheme'),
'readonly' => $readonly,
'printQuestion' => $question,
'msgNewContentArticle' => Translation::get('msgNewContentArticle'),
'msgNewContentKeywords' => Translation::get('msgNewContentKeywords'),
'msgNewContentLink' => Translation::get('msgNewContentLink'),
'captchaFieldset' =>
$captchaHelper->renderCaptcha($captcha, 'add', Translation::get('msgCaptcha'), $user->isLoggedIn()),
'msgNewContentSubmit' => Translation::get('msgNewContentSubmit'),
'enableWysiwygEditor' => $faqConfig->get('main.enableWysiwygEditorFrontend'),
'currentTimestamp' => $request->server->get('REQUEST_TIME'),
'msgSeperateKeywordsWithCommas' => Translation::get('msgSeperateKeywordsWithCommas'),
'noCategories' => empty($categories),
'msgFormDisabledDueToMissingCategories' => Translation::get('msgFormDisabledDueToMissingCategories')
];

// Collect data for displaying form
foreach ($formData as $input) {
if ((int)$input->input_active !== 0) {
$label = sprintf('id%d_label', (int)$input->input_id);
$required = sprintf('id%d_required', (int)$input->input_id);
$templateVars = [
...$templateVars,
$label => $input->input_label,
$required => ((int)$input->input_required !== 0) ? 'required' : ''
];
}
}

//echo $template1->render($templateVars);
7 changes: 5 additions & 2 deletions phpmyfaq/admin/assets/src/api/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ export const fetchEditTranslation = async (csrf, formId, inputId, label, lang) =
}
}

export const fetchDeleteTranslation = async (csrf, formId, inputId, lang) => {
export const fetchDeleteTranslation = async (csrf, formId, inputId, lang, element) => {
try {
const response = await fetch('api/forms/translation-delete', {
method: 'POST',
Expand All @@ -134,13 +134,16 @@ export const fetchDeleteTranslation = async (csrf, formId, inputId, lang) => {
if (result.success) {
pushNotification(result.success);
document.getElementById('item_' + element.getAttribute('data-pmf-lang')).remove();
const option = document.createElement('option');
option.innerText = element.getAttribute('data-pmf-langname');
document.getElementById('languageSelect').appendChild(option);
} else {
console.error(result.error);
}
} else {
throw new Error('Network response was not ok: ', response.text());
}
} catch {
} catch (error) {
console.error('Error deleting translation:', error);
throw error;
}
Expand Down
3 changes: 2 additions & 1 deletion phpmyfaq/admin/assets/src/configuration/forms.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,8 @@ export const handleFormTranslations = () => {
const inputId = element.getAttribute('data-pmf-inputId');
const formId = element.getAttribute('data-pmf-formId');
const lang = element.getAttribute('data-pmf-lang');
await fetchDeleteTranslation(csrf, formId, inputId, lang);
await fetchDeleteTranslation(csrf, formId, inputId, lang, element);

});
});
// Add Translation
Expand Down
117 changes: 117 additions & 0 deletions phpmyfaq/assets/templates/add.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
{% extends 'index.twig' %}

{% block content %}

<section class="col-12">
{% if noCategories == true %}
<div class="alert alert-danger">{{ msgFormDisabledDueToMissingCategories|raw }}</div>
{% else %}
{% if id1_label is defined %}
<h1>{{ id1_label }}</h1>
{% endif %}
{% if id2_label is defined %}
<p>{{ id2_label|raw }}</p>
{% endif %}

<div class="row mb-2">
<div class="col">
<div class="spinner-border text-primary d-none" id="loader" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<div id="pmf-add-faq-response"></div>
</div>
</div>

<form id="pmf-add-faq-form" action="#" method="post" accept-charset="utf-8" class="needs-validation" novalidate>
<input type="hidden" name="lang" id="lang" value="{{ lang }}">
<input type="hidden" value="{{ openQuestionID }}" id="openQuestionID" name="openQuestionID">

{% if id3_label is defined %}
<div class="row mb-2">
<label class="col-sm-3 form-control-label" for="name">{{ id3_label }}:
{% if id3_required == 'required' %}<span style="color: red"> *</span>{% endif %}
</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="name" id="name" value="{{ defaultContentName }}" {{ id3_required }}>
</div>
</div>
{% endif %}

{% if id4_label is defined %}
<div class="row mb-2">
<label class="col-sm-3 form-control-label" for="email">{{ id4_label }}:
{% if id4_required == 'required' %}<span style="color: red"> *</span>{% endif %}
</label>
<div class="col-sm-9">
<input type="email" class="form-control" name="email" id="email" value="{{ defaultContentMail }}" {{ id4_required }}>
</div>
</div>
{% endif %}

{% if id5_label is defined %}
<div class="row mb-2">
<label class="col-sm-3 form-control-label" for="rubrik">{{ id5_label }}:
{% if id5_required == 'required' %}<span style="color: red"> *</span>{% endif %}
</label>
<div class="col-sm-9">
<select name="rubrik" class="form-control" id="rubrik" multiple="multiple" size="5" {{ id5_required }}>
{{ renderCategoryOptions|raw }}
</select>
</div>
</div>
{% endif %}

{% if id6_label is defined %}
<div class="row mb-2">
<label class="col-sm-3 form-control-label" for="question">{{ id6_label }}:
{% if id6_required == 'required' %}<span style="color: red"> *</span>{% endif %}
</label>
<div class="col-sm-9">
<textarea class="form-control" cols="37" rows="3" name="question" id="question" {{ id6_required }} {{ readonly }}>
{{ printQuestion }}</textarea
>
</div>
</div>
{% endif %}

{% if id7_label is defined %}
<div class="row mb-2">
<label class="col-sm-3 form-control-label" for="answer">{{ id7_label }}:
{% if id7_required == 'required' %}<span style="color: red"> *</span>{% endif %}
</label>
<div class="col-sm-9">
<textarea class="form-control" cols="37" rows="10" name="answer" id="answer" {{ id7_required }}></textarea>
</div>
</div>
{% endif %}

{% if id8_label is defined %}
<div class="row mb-2">
<label class="col-sm-3 form-control-label" for="keywords">{{ id8_label }}:
{% if id8_required == 'required' %}<span style="color: red"> *</span>{% endif %}
</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="keywords" id="keywords" {{ id8_required }}>
<small class="text-muted">{{ msgSeperateKeywordsWithCommas }}</small>
</div>
</div>
{% endif %}

{{ captchaFieldset|raw }}

<div class="row mb-2">
<div class="col-sm-12 text-end">
<button class="btn btn-primary btn-lg" type="submit" id="pmf-submit-faq" data-pmf-form="add-faq">
{{ msgNewContentSubmit }}
</button>
</div>
</div>
</form>
</section>

{% if enableWysiwygEditor == true %}
<script src="{{ baseHref }}admin/assets/js/editor/tinymce.min.js?{{ currentTimestamp }}"></script>
{% endif %}
{% endif %}

{% endblock %}
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@
value="{{ translation.input_label }}" disabled /></td>
<td>
{% if translation.input_lang != 'default' %}
<span class="badge bg-primary" id="editTranslation" data-pmf-lang="{{ translation.input_lang }}"
<button class="btn btn-primary" id="editTranslation" data-pmf-lang="{{ translation.input_lang }}"
data-pmf-inputId="{{ inputId }}" data-pmf-formId="{{ formId }}"
data-pmf-csrf="{{ csrfTokenEditTranslation }}">
<i aria-hidden="true" class="bi bi-pencil bi-white"></i></span>
<span class="badge bg-danger" id="deleteTranslation" data-pmf-lang="{{ translation.input_lang }}"
<i aria-hidden="true" class="bi bi-pencil bi-white"></i></button>
<button class="btn btn-danger" id="deleteTranslation" data-pmf-lang="{{ translation.input_lang }}"
data-pmf-inputId="{{ inputId }}" data-pmf-formId="{{ formId }}"
data-pmf-csrf="{{ csrfTokenDeleteTranslation }}">
<i aria-hidden="true" class="bi bi-trash3 bi-white"></i></span>
data-pmf-csrf="{{ csrfTokenDeleteTranslation }}" data-pmf-langname="{{ translation.input_lang|languageCode }}">
<i aria-hidden="true" class="bi bi-trash3 bi-white"></i></button>
{% endif %}
</td>
</tr>
Expand Down
24 changes: 9 additions & 15 deletions phpmyfaq/src/phpMyFAQ/Controller/Frontend/FaqController.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ public function create(Request $request): JsonResponse
$answer = trim(nl2br($answer));
}

$contentLink = Filter::filterVar($data->contentlink, FILTER_VALIDATE_URL);
$keywords = Filter::filterVar($data->keywords, FILTER_SANITIZE_SPECIAL_CHARS);
if (isset($data->{'rubrik[]'})) {
if (is_string($data->{'rubrik[]'})) {
Expand All @@ -80,28 +79,22 @@ public function create(Request $request): JsonResponse
$data->{'rubrik[]'}
);
} else {
$categories = [];
$categories = [$category->getAllCategoryIds()[0]];
}

if (!$this->captchaCodeIsValid($request)) {
return $this->json(['error' => Translation::get('msgCaptcha')], Response::HTTP_BAD_REQUEST);
}
if (
!empty($author) && !empty($email) && ($questionText !== '' && $questionText !== '0') &&
$stopWords->checkBannedWord(strip_tags($questionText)) &&
($answer !== '' && $answer !== '0') && $stopWords->checkBannedWord(strip_tags($answer))
$stopWords->checkBannedWord(strip_tags($questionText))
) {
$session->userTracking('save_new_entry', 0);

if (!empty($contentLink) && Strings::substr($contentLink, 7) !== '') {
$answer = sprintf(
'%s<br><div id="newFAQContentLink">%s<a href="https://%s" target="_blank">%s</a></div>',
$answer,
Translation::get('msgInfo'),
Strings::substr($contentLink, 7),
$contentLink
);
if (!empty($answer)) {
$stopWords->checkBannedWord(strip_tags($answer));
} else {
$answer = '';
}
$session->userTracking('save_new_entry', 0);

$autoActivate = $this->configuration->get('records.defaultActivation');

Expand All @@ -118,7 +111,8 @@ public function create(Request $request): JsonResponse
->setComment(true)
->setNotes('');

$recordId = $faq->create($faqEntity);
$faq->create($faqEntity);
$recordId = $faqEntity->getId();

$openQuestionId = Filter::filterVar($data->openQuestionID, FILTER_VALIDATE_INT);
if ($openQuestionId) {
Expand Down
2 changes: 0 additions & 2 deletions phpmyfaq/src/phpMyFAQ/Enums/Forms/AddNewFaqInputIds.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,4 @@ enum AddNewFaqInputIds: int
case ANSWER = 7;

case KEYWORDS = 8;

case URI = 9;
}
2 changes: 1 addition & 1 deletion phpmyfaq/src/phpMyFAQ/Faq/MetaData.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public function save(): void

$userPermissions = $categoryPermission->get(Permission::USER, $this->categories);

$faqPermission->add(Permission::USER, $this->faqId, $userPermissions);
$faqPermission->add(Permission::USER, $this->categories, $userPermissions);
$categoryPermission->add(Permission::USER, $this->categories, $userPermissions);

if ($this->configuration->get('security.permLevel') !== 'basic') {
Expand Down
2 changes: 1 addition & 1 deletion phpmyfaq/translations/language_bn.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@

// new Content
$PMF_LANG["msgNewContentHeader"] = "প্রশ্ন উত্তর সম্পর্কে মতামত";
$PMF_LANG["msgNewContentAddon"] = "আপনার মতামত প্রশাসকের অনুমোদনের পর প্রকাশিত হবে। বাধ্যতামূলকঃ <strong>আপনার নাম</strong>, <strong>আপনার ই-মেইল ঠিকানা</strong>, <strong>বিভাগ</strong>, <strong>শিরোনাম</strong> এবং <strong>আপনার প্রশ্ন</strong>। চাবি-শব্দগুলি space দিয়ে আলাদা করুন";
$PMF_LANG["msgNewContentAddon"] = "আপনার পরামর্শ অবিলম্বে প্রদর্শিত হবে না, কিন্তু প্রকাশের আগে আমাদের দ্বারা চেক করা হবে. বাধ্যতামূলক ক্ষেত্র হল * দিয়ে চিহ্নিত ক্ষেত্র";
$PMF_LANG["msgNewContentName"] = "আপনার নাম";
$PMF_LANG["msgNewContentMail"] = "আপনার ই-মেইল ঠিকানা";
$PMF_LANG["msgNewContentCategory"] = "বিভাগ";
Expand Down
2 changes: 1 addition & 1 deletion phpmyfaq/translations/language_bs.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@

// new Content
$PMF_LANG["msgNewContentHeader"] = "Predlog za FAQ";
$PMF_LANG["msgNewContentAddon"] = "Va&#353; predlog ne&#263;e biti une&#353;en odmah, ve&#263; &#263;e biti poslan na pregled administratoru. Obavezna polja (za popunjavanje) su <strong>va&#353;e ime</strong>, <strong>e-mail adresa</strong>, <strong>kategorija</strong> i <strong>unos</strong>. Molimo vas da razdvojite klju&#269;ne re&#269;i (keywords) sa razmakom.";
$PMF_LANG["msgNewContentAddon"] = "Vaš prijedlog se neće pojaviti odmah, ali ćemo ga provjeriti prije objave. Obavezna polja su polja označena sa *.";
$PMF_LANG["msgNewContentName"] = "Va&#353;e Ime";
$PMF_LANG["msgNewContentMail"] = "Va&#353;a e-mail adresa";
$PMF_LANG["msgNewContentCategory"] = "Izbor kategorije?";
Expand Down
2 changes: 1 addition & 1 deletion phpmyfaq/translations/language_cy.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@

// new Content
$PMF_LANG["msgNewContentHeader"] = "Cynigion ar gyfer Cwestiynau Cyffredin";
$PMF_LANG["msgNewContentAddon"] = "Ni chaiff eich cynnig ei gyhoeddi ar unwaith, ond caiff ei ryddhau gan y gweinyddwr ar ôl ei dderbyn. Y meysydd gofynnol yw <strong> eich Enw </strong>, eich cyfeiriad e-bost </strong>,<strong>categori</strong>, <strong>pennawd</strong> ac <strong>eich cofnod</strong>. Rhowch ofod tab rhwng y geiriau allweddol yn unig.";
$PMF_LANG["msgNewContentAddon"] = "Ni fydd eich awgrym yn ymddangos ar unwaith, ond bydd yn cael ei wirio gennym ni cyn ei gyhoeddi. Mae meysydd gorfodol yn feysydd sydd wedi'u marcio â *.";
$PMF_LANG["msgNewContentName"] = "Eich Enw";
$PMF_LANG["msgNewContentMail"] = "Eich cyfeiriad e-bost";
$PMF_LANG["msgNewContentCategory"] = "Pa gategori i'w ddewis?";
Expand Down
2 changes: 1 addition & 1 deletion phpmyfaq/translations/language_da.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@
$PMF_LANG['msgSearchCategory'] = 'Kategori: ';
$PMF_LANG['msgSearchContent'] = 'indhold: ';
$PMF_LANG['msgNewContentHeader'] = 'Forslag til FAQ';
$PMF_LANG['msgNewContentAddon'] = 'Dit indlæg bliver ikke offenliggjort med det samme, da det først skal gennemlæses af en administrator. <br>Nødvendige felter: <strong>dit navn</strong>, <strong>din e-mail-adresse</strong>, <strong>kategori</strong>, <strong>overskrift</strong> og <strong>dit forslag</strong>.<br>Separer venligst søgeord med mellemrum (benyt ikke komma).';
$PMF_LANG['msgNewContentAddon'] = 'Dit forslag vises ikke med det samme, men vil blive kontrolleret af os inden offentliggørelse. Obligatoriske felter er felter markeret med *.';
$PMF_LANG['msgNewContentName'] = 'Dit navn:';
$PMF_LANG['msgNewContentMail'] = 'Din e-mail-adresse:';
$PMF_LANG['msgNewContentCategory'] = 'Vælg kategori:';
Expand Down
6 changes: 5 additions & 1 deletion phpmyfaq/translations/language_de.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@

// new Content
$PMF_LANG['msgNewContentHeader'] = "Vorschlag für neuen FAQ-Eintrag";
$PMF_LANG['msgNewContentAddon'] = "Ihr Vorschlag erscheint nicht sofort, sondern wird vor der Veröffentlichung von uns überprüft. Pflichtfelder sind Name, E-Mail-Adresse, Kategorie, Frage und Antwort. Die Suchbegriffe bitte nur Kommas trennen.";
$PMF_LANG['msgNewContentAddon'] = "Ihr Vorschlag erscheint nicht sofort, sondern wird vor der Veröffentlichung von uns überprüft. Pflichtfelder sind mit * gekennzeichnete Felder.";
$PMF_LANG['msgNewContentName'] = "Name";
$PMF_LANG['msgNewContentMail'] = "E-Mail";
$PMF_LANG['msgNewContentCategory'] = "Kategorie";
Expand Down Expand Up @@ -1427,4 +1427,8 @@
$PMF_LANG['msgNoQuestionAndAnswer'] = 'Keine Frage und Antwort gefunden.';
$PMF_LANG['msgNotInMaintenanceMode'] = 'Die FAQ ist nicht im Wartungs-Modus.';

// added v4.0.0-alpha.3 - 2024-06-03 by Jan
$PMF_LANG['msgSeperateKeywordsWithCommas'] = 'Mehrere Suchbegriffe müssen mit Kommas getrennt werden.';
$PMF_LANG['msgFormDisabledDueToMissingCategories'] = 'Du kannst nichts einreichen, weil keine Kategorien eingerichtet sind. Wende dich bitte an den <a class="alert-link" href="contact.html">Administrator</a>.';

return $PMF_LANG;
2 changes: 1 addition & 1 deletion phpmyfaq/translations/language_el.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
$PMF_LANG['msgSearchCategory'] = 'Κατηγορία: ';
$PMF_LANG['msgSearchContent'] = 'Απάντηση: ';
$PMF_LANG['msgNewContentHeader'] = 'Πρόταση για καταχώρηση';
$PMF_LANG['msgNewContentAddon'] = 'Η πρότασή σας δε θα εμφανιστεί αμέσως αλλά θα εκδοθεί από τον διαχειριστή του συστήματος κατά την παραλαβή της. Υποχρεωτικά πεδία είναι τα εξής: <strong>Το όνομά σας</strong>, <strong>το email σας</strong>, <strong>Κατηγορία</strong>, <strong>Τίτλος</strong> και <strong>η καταχώρησή σας</strong>. Παρακαλούμε διαχωρίστε τις λέξεις κλειδιά με κενό (space) ή στυλοθέτη (tab).';
$PMF_LANG['msgNewContentAddon'] = 'Η πρότασή σας δεν θα εμφανιστεί αμέσως, αλλά θα ελεγχθεί από εμάς πριν από τη δημοσίευση. Τα υποχρεωτικά πεδία είναι πεδία που επισημαίνονται με *.';
$PMF_LANG['msgNewContentName'] = 'Το όνομά σας:';
$PMF_LANG['msgNewContentMail'] = 'Το email σας:';
$PMF_LANG['msgNewContentCategory'] = 'Κατηγορία που αναφέρεστε';
Expand Down
Loading

0 comments on commit 98804d3

Please sign in to comment.