CVE-2022-3608 (published 2022-10-19T13:15Z)

Cross-site Scripting (XSS) - Stored in GitHub repository thorsten/phpmyfaq prior to 3.2.0-alpha.

CVSS v3 base score: 8.4, HIGH (CVSS:3.1/AV:N/AC:L/PR:H/UI:R/S:C/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/thorsten/phpmyfaq
commit_details: repo_url: https://github.com/thorsten/phpmyfaq
author: Thorsten Rinne
author_date: 2022-10-09 17:51:32+02:00
msg: feat(backup): added verification of backup files
repository: repo_url: https://github.com/thorsten/phpmyfaq
repo_name: thorsten/phpMyFAQ
description: phpMyFAQ - Open Source FAQ web application for PHP 8.1+ and MySQL, PostgreSQL and other databases
repo_language: PHP
owner: thorsten
file_changes: filename: CHANGELOG.md
change_type: ModificationType.MODIFY
diff: @@ -15,6 +15,7 @@ This is a log of major user-visible changes in each phpMyFAQ release.
 - added HTTPS support for local Docker development (Thorsten)
 - added Monolog v2 as logging solution (Thorsten)
 - added REST API v2.2 to fetch groups (Thorsten)
+- added verification of backup files (Thorsten)
 - migrated from SwiftMailer to Symfony Mailer (Thorsten)
 - updated to Bootstrap v5.1 (Thorsten)
 - updated to TinyMCE v5.10 (Thorsten)

programming_language: Markdown
filename: composer.json
change_type: ModificationType.MODIFY
diff: @@ -29,6 +29,7 @@
     "ext-filter": "*",
     "ext-gd": "*",
     "ext-json": "*",
+    "ext-sodium": "*",
     "ext-xml": "*",
     "ext-zip": "*",
     "ext-xmlwriter": "*",

programming_language: PHP
filename: composer.lock
change_type: ModificationType.MODIFY
diff: @@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "dba4f03bccb10ea790582b909d306ac5",
+    "content-hash": "c4432f3947b3f562463e6633dd744fe6",
     "packages": [
         {
             "name": "abraham/twitteroauth",
@@ -290,16 +290,16 @@
         },
         {
             "name": "elasticsearch/elasticsearch",
-            "version": "v7.17.0",
+            "version": "v7.17.1",
             "source": {
                 "type": "git",
-                "url": "https://github.com/elastic/elasticsearch-php.git",
-                "reference": "1890f9d7fde076b5a3ddcf579a802af05b2e781b"
+                "url": "git@github.com:elastic/elasticsearch-php.git",
+                "reference": "f1b8918f411b837ce5f6325e829a73518fd50367"
             },
             "dist": {
                 "type": "zip",
-                "url": "https://api.github.com/repos/elastic/elasticsearch-php/zipball/1890f9d7fde076b5a3ddcf579a802af05b2e781b",
-                "reference": "1890f9d7fde076b5a3ddcf579a802af05b2e781b",
+                "url": "https://api.github.com/repos/elastic/elasticsearch-php/zipball/f1b8918f411b837ce5f6325e829a73518fd50367",
+                "reference": "f1b8918f411b837ce5f6325e829a73518fd50367",
                 "shasum": ""
             },
             "require": {
@@ -349,11 +349,7 @@
                 "elasticsearch",
                 "search"
             ],
-            "support": {
-                "issues": "https://github.com/elastic/elasticsearch-php/issues",
-                "source": "https://github.com/elastic/elasticsearch-php/tree/v7.17.0"
-            },
-            "time": "2022-02-03T13:40:04+00:00"
+            "time": "2022-09-30T12:28:55+00:00"
         },
         {
             "name": "erusev/parsedown",
@@ -4847,6 +4843,7 @@
         "ext-filter": "*",
         "ext-gd": "*",
         "ext-json": "*",
+        "ext-sodium": "*",
         "ext-xml": "*",
         "ext-zip": "*",
         "ext-xmlwriter": "*"

programming_language: JavaScript
filename: backup.export.php
change_type: ModificationType.MODIFY
diff: @@ -15,6 +15,7 @@
  * @since     2009-08-18
  */
 
+use phpMyFAQ\Backup;
 use phpMyFAQ\Database;
 use phpMyFAQ\Database\DatabaseHelper;
 use phpMyFAQ\Filter;
@@ -49,11 +50,12 @@ if ($user) {
 }
 
 if ($user->perm->hasPermission($user->getUserId(), 'backup')) {
-    $tables = $tableNames = $faqConfig->getDb()->getTableNames(Database::getTablePrefix());
-    $tablePrefix = (Database::getTablePrefix() !== '') ? Database::getTablePrefix() . '.phpmyfaq' : 'phpmyfaq';
+    $tables = $faqConfig->getDb()->getTableNames(Database::getTablePrefix());
     $tableNames = '';
-    $majorVersion = substr($faqConfig->getVersion(), 0, 3);
+
     $dbHelper = new DatabaseHelper($faqConfig);
+    $backup = new Backup($faqConfig, $dbHelper);
+
     $httpHelper = new HttpHelper();
     $httpHelper->addHeader();
     $httpHelper->addExtraHeader('Content-Type: application/octet-stream');
@@ -82,49 +84,29 @@ if ($user->perm->hasPermission($user->getUserId(), 'backup')) {
             break;
     }
 
-    $text[] = '-- pmf' . $majorVersion . ': ' . $tableNames;
-    $text[] = '-- DO NOT REMOVE THE FIRST LINE!';
-    $text[] = '-- pmftableprefix: ' . Database::getTablePrefix();
-    $text[] = '-- DO NOT REMOVE THE LINES ABOVE!';
-    $text[] = '-- Otherwise this backup will be broken.';
-
     switch ($action) {
         case 'backup_content':
-            $header = sprintf(
-                'Content-Disposition: attachment; filename=%s',
-                urlencode(
-                    sprintf(
-                        '%s-data.%s.sql',
-                        $tablePrefix,
-                        date('Y-m-d-H-i-s')
-                    )
-                )
-            );
-            $httpHelper->addExtraHeader($header);
-            foreach (explode(' ', $tableNames) as $table) {
-                echo implode("\r\n", $text);
-                if ('' !== $table) {
-                    $text = $dbHelper->buildInsertQueries('SELECT * FROM ' . $table, $table);
-                }
+            $backupQueries = $backup->generateBackupQueries($tableNames);
+            try {
+                $backupFileName = $backup->createBackup(Backup::BACKUP_TYPE_DATA, $backupQueries);
+                $header = sprintf('Content-Disposition: attachment; filename=%s', urlencode($backupFileName));
+                $httpHelper->addExtraHeader($header);
+
+                echo $backupQueries;
+            } catch (SodiumException $e) {
+                // Handle exception
             }
             break;
         case 'backup_logs':
-            $header = sprintf(
-                'Content-Disposition: attachment; filename=%s',
-                urlencode(
-                    sprintf(
-                        '%s-logs.%s.sql',
-                        $tablePrefix,
-                        date('Y-m-d-H-i-s')
-                    )
-                )
-            );
-            $httpHelper->addExtraHeader($header);
-            foreach (explode(' ', $tableNames) as $table) {
-                echo implode("\r\n", $text);
-                if ('' !== $table) {
-                    $text = $dbHelper->buildInsertQueries('SELECT * FROM ' . $table, $table);
-                }
+            $backupQueries = $backup->generateBackupQueries($tableNames);
+            try {
+                $backupFileName = $backup->createBackup(Backup::BACKUP_TYPE_LOGS, $backupQueries);
+                $header = sprintf('Content-Disposition: attachment; filename=%s', urlencode($backupFileName));
+                $httpHelper->addExtraHeader($header);
+
+                echo $backupQueries;
+            } catch (SodiumException $e) {
+                // Handle exception
             }
             break;
     }

programming_language: PHP
filename: backup.import.php
change_type: ModificationType.MODIFY
diff: @@ -15,11 +15,13 @@
  * @since     2003-02-24
  */
 
+use phpMyFAQ\Backup;
 use phpMyFAQ\Component\Alert;
 use phpMyFAQ\Database;
 use phpMyFAQ\Database\DatabaseHelper;
 use phpMyFAQ\Filter;
 use phpMyFAQ\Strings;
+use phpMyFAQ\Translation;
 
 if (!defined('IS_VALID_PHPMYFAQ')) {
     http_response_code(400);
@@ -37,7 +39,7 @@ if (!isset($_SESSION['phpmyfaq_csrf_token']) || $_SESSION['phpmyfaq_csrf_token']
     <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
         <h1 class="h2">
             <i aria-hidden="true" class="fa fa-download"></i>
-            <?= $PMF_LANG['ad_csv_rest'] ?>
+            <?= Translation::get('ad_csv_rest') ?>
         </h1>
     </div>
 <?php
@@ -47,20 +49,38 @@ if ($user->perm->hasPermission($user->getUserId(), 'restore') && $csrfCheck) {
         $ok = 1;
         $fileInfo = new finfo(FILEINFO_MIME_ENCODING);
 
+        $dbHelper = new DatabaseHelper($faqConfig);
+        $backup = new Backup($faqConfig, $dbHelper);
+
         if ('utf-8' !== $fileInfo->file($_FILES['userfile']['tmp_name'])) {
             echo 'This file is not UTF-8 encoded.<br>';
             $ok = 0;
         }
+
         $handle = fopen($_FILES['userfile']['tmp_name'], 'r');
         $backupData = fgets($handle, 65536);
         $versionFound = Strings::substr($backupData, 0, 9);
         $versionExpected = '-- pmf' . substr($faqConfig->getVersion(), 0, 3);
         $queries = [];
 
+        $fileName = $_FILES['userfile']['name'];
+
+        try {
+            $verification = $backup->verifyBackup(file_get_contents($_FILES['userfile']['tmp_name']), $fileName);
+            if ($verification) {
+                $ok = 1;
+            } else {
+                $ok = 0;
+            }
+        } catch (SodiumException $e) {
+            echo 'This file cannot be verified.<br>';
+            $ok = 0;
+        }
+
         if ($versionFound !== $versionExpected) {
             printf(
                 '%s (Version check failure: "%s" found, "%s" expected)',
-                $PMF_LANG['ad_csv_no'],
+                Translation::get('ad_csv_no'),
                 $versionFound,
                 $versionExpected
             );
@@ -78,7 +98,7 @@ if ($user->perm->hasPermission($user->getUserId(), 'restore') && $csrfCheck) {
 
         if ($ok == 1) {
             $tablePrefix = '';
-            printf("<p>%s</p>\n", $PMF_LANG['ad_csv_prepare']);
+            printf("<p>%s</p>\n", Translation::get('ad_csv_prepare'));
             while ($backupData = fgets($handle, 65536)) {
                 $backupData = trim($backupData);
                 $backupPrefixPattern = '-- pmftableprefix:';
@@ -93,11 +113,14 @@ if ($user->perm->hasPermission($user->getUserId(), 'restore') && $csrfCheck) {
 
             $k = 0;
             $g = 0;
-            printf("<p>%s</p>\n", $PMF_LANG['ad_csv_process']);
+
+            printf("<p>%s</p>\n", Translation::get('ad_csv_process'));
+
             $numTables = count($queries);
             $kg = '';
             for ($i = 0; $i < $numTables; ++$i) {
                 $queries[$i] = DatabaseHelper::alignTablePrefix($queries[$i], $tablePrefix, Database::getTablePrefix());
+
                 $kg = $faqConfig->getDb()->query($queries[$i]);
                 if (!$kg) {
                     printf(
@@ -119,9 +142,9 @@ if ($user->perm->hasPermission($user->getUserId(), 'restore') && $csrfCheck) {
             printf(
                 '<p class="alert alert-success">%d %s %d %s</p>',
                 $g,
-                $PMF_LANG['ad_csv_of'],
+                Translation::get('ad_csv_of'),
                 $numTables,
-                $PMF_LANG['ad_csv_suc']
+                Translation::get('ad_csv_suc')
             );
         }
     } else {
@@ -138,5 +161,5 @@ if ($user->perm->hasPermission($user->getUserId(), 'restore') && $csrfCheck) {
         echo Alert::danger('ad_csv_no', $errorMessage);
     }
 } else {
-    echo $PMF_LANG['err_NotAuth'];
+    echo Translation::get('err_NotAuth');
 }

programming_language: PHP
filename: _mixins.scss
change_type: ModificationType.ADD
diff: @@ -0,0 +1,172 @@
+@mixin text-shadow($string: 0 1px 3px rgba(0, 0, 0, 0.25)) {
+  text-shadow: $string;
+}
+@mixin box-shadow($string) {
+  -webkit-box-shadow: $string;
+  -moz-box-shadow: $string;
+  box-shadow: $string;
+}
+
+@mixin box-sizing($type: border-box) {
+  -webkit-box-sizing: $type;
+  -moz-box-sizing: $type;
+  box-sizing: $type;
+}
+
+@mixin border-radius($radius: 5px) {
+  -webkit-border-radius: $radius;
+  -moz-border-radius: $radius;
+  -ms-border-radius: $radius;
+  -o-border-radius: $radius;
+  border-radius: $radius;
+
+  -moz-background-clip: padding;
+  -webkit-background-clip: padding-box;
+  background-clip: padding-box;
+}
+@mixin border-radiuses($topright: 0, $bottomright: 0, $bottomleft: 0, $topleft: 0) {
+  -webkit-border-top-right-radius: $topright;
+  -webkit-border-bottom-right-radius: $bottomright;
+  -webkit-border-bottom-left-radius: $bottomleft;
+  -webkit-border-top-left-radius: $topleft;
+
+  -moz-border-radius-topright: $topright;
+  -moz-border-radius-bottomright: $bottomright;
+  -moz-border-radius-bottomleft: $bottomleft;
+  -moz-border-radius-topleft: $topleft;
+
+  border-top-right-radius: $topright;
+  border-bottom-right-radius: $bottomright;
+  border-bottom-left-radius: $bottomleft;
+  border-top-left-radius: $topleft;
+
+  -moz-background-clip: padding;
+  -webkit-background-clip: padding-box;
+  background-clip: padding-box;
+}
+
+@mixin opacity($opacity: 0.5) {
+  -webkit-opacity: $opacity;
+  -moz-opacity: $opacity;
+  opacity: $opacity;
+}
+
+@mixin gradient($startColor: #eee, $endColor: white) {
+  background-color: $startColor;
+  background: -webkit-gradient(linear, left top, left bottom, from($startColor), to($endColor));
+  background: -webkit-linear-gradient(top, $startColor, $endColor);
+  background: -moz-linear-gradient(top, $startColor, $endColor);
+  background: -ms-linear-gradient(top, $startColor, $endColor);
+  background: -o-linear-gradient(top, $startColor, $endColor);
+}
+@mixin horizontal-gradient($startColor: #eee, $endColor: white) {
+  background-color: $startColor;
+  background-image: -webkit-gradient(linear, left top, right top, from($startColor), to($endColor));
+  background-image: -webkit-linear-gradient(left, $startColor, $endColor);
+  background-image: -moz-linear-gradient(left, $startColor, $endColor);
+  background-image: -ms-linear-gradient(left, $startColor, $endColor);
+  background-image: -o-linear-gradient(left, $startColor, $endColor);
+}
+
+@mixin animation($name, $duration: 300ms, $delay: 0, $ease: ease) {
+  -webkit-animation: $name $duration $delay $ease;
+  -moz-animation: $name $duration $delay $ease;
+  -ms-animation: $name $duration $delay $ease;
+}
+
+@mixin transition($transition) {
+  -webkit-transition: $transition;
+  -moz-transition: $transition;
+  -ms-transition: $transition;
+  -o-transition: $transition;
+}
+@mixin transform($string) {
+  -webkit-transform: $string;
+  -moz-transform: $string;
+  -ms-transform: $string;
+  -o-transform: $string;
+}
+@mixin scale($factor) {
+  -webkit-transform: scale($factor);
+  -moz-transform: scale($factor);
+  -ms-transform: scale($factor);
+  -o-transform: scale($factor);
+}
+@mixin rotate($deg) {
+  -webkit-transform: rotate($deg);
+  -moz-transform: rotate($deg);
+  -ms-transform: rotate($deg);
+  -o-transform: rotate($deg);
+}
+@mixin skew($deg, $deg2) {
+  -webkit-transform: skew($deg, $deg2);
+  -moz-transform: skew($deg, $deg2);
+  -ms-transform: skew($deg, $deg2);
+  -o-transform: skew($deg, $deg2);
+}
+@mixin translate($x, $y: 0) {
+  -webkit-transform: translate($x, $y);
+  -moz-transform: translate($x, $y);
+  -ms-transform: translate($x, $y);
+  -o-transform: translate($x, $y);
+}
+@mixin translate3d($x, $y: 0, $z: 0) {
+  -webkit-transform: translate3d($x, $y, $z);
+  -moz-transform: translate3d($x, $y, $z);
+  -ms-transform: translate3d($x, $y, $z);
+  -o-transform: translate3d($x, $y, $z);
+}
+@mixin perspective($value: 1000) {
+  -webkit-perspective: $value;
+  -moz-perspective: $value;
+  -ms-perspective: $value;
+  perspective: $value;
+}
+@mixin transform-origin($x: center, $y: center) {
+  -webkit-transform-origin: $x $y;
+  -moz-transform-origin: $x $y;
+  -ms-transform-origin: $x $y;
+  -o-transform-origin: $x $y;
+}
+
+@mixin reset-box-sizing($size: content-box) {
+  &,
+  *,
+  *:before,
+  *:after {
+    @include box-sizing($size);
+  }
+}
+
+@mixin truncate($max-width: 250px) {
+  max-width: $max-width;
+  white-space: nowrap;
+  overflow: hidden;
+  text-overflow: ellipsis;
+}
+
+@mixin background-size($string: contain) {
+  -webkit-background-size: $string;
+  -moz-background-size: $string;
+  -o-background-size: $string;
+  background-size: $string;
+}
+
+@mixin placeholder($color: #999) {
+  &::-webkit-input-placeholder {
+    /* WebKit browsers */
+    color: $color;
+  }
+  &:-moz-placeholder {
+    /* Mozilla Firefox 4 to 18 */
+    color: $color;
+  }
+  &::-moz-placeholder {
+    /* Mozilla Firefox 19+ */
+    color: $color;
+  }
+  &:-ms-input-placeholder {
+    /* Internet Explorer 10+ */
+    color: $color;
+  }
+}

programming_language: CSS
filename: _theme.scss
change_type: ModificationType.ADD
diff: @@ -0,0 +1,26 @@
+$color-primary: #fd7e14;
+$color-green: #75c181;
+$color-red: #f77b6b;
+$color-blue: #58bbee;
+$color-orange: #f88c30;
+$color-pink: #ea5395;
+$color-purple: #8a40a7;
+
+$text-color: #494d55;
+$text-color-secondary: lighten($text-color, 10%);
+$text-grey: lighten($text-color-secondary, 25%);
+
+$grey: lighten($text-color-secondary, 25%);
+$light-grey: #c3c3c3;
+$dark-grey: #666;
+$black: #000;
+$smoky-white: #f5f5f5;
+$smoky-grey: #f9f9fb;
+$divider: #f0f0f0;
+
+$new: #60a823;
+$error: #e65348;
+$facebook: #3b5998;
+$twitter: #55acee;
+$google: #dd4b39;
+$github: #444;

programming_language: PHP
filename: _startpage.scss
change_type: ModificationType.ADD
diff: @@ -0,0 +1 @@
+

programming_language: None
filename: update.php
change_type: ModificationType.MODIFY
diff: @@ -395,6 +395,7 @@ if ($step == 3) {
     //
     if (version_compare($version, '3.2.0-alpha', '<=')) {
         // Azure AD support
+        $faqConfig->add('security.enableSignInWithMicrosoft', false);
         if ('sqlite3' === $DB['type']) {
             $query[] = 'ALTER TABLE ' . $prefix . 'faquser 
                 ADD COLUMN refresh_token TEXT NULL DEFAULT NULL,
@@ -408,7 +409,16 @@ if ($step == 3) {
                 ADD code_verifier VARCHAR(255) NULL DEFAULT NULL,
                 ADD jwt TEXT NULL DEFAULT NULL';
         }
-        $faqConfig->add('security.enableSignInWithMicrosoft', false);
+
+        // New backup
+        $query[] = 'CREATE TABLE ' . $prefix . 'faqbackup (
+            id INT(11) NOT NULL,
+            filename VARCHAR(255) NOT NULL,
+            authkey VARCHAR(255) NOT NULL,
+            authcode VARCHAR(255) NOT NULL,
+            created timestamp NOT NULL,
+            PRIMARY KEY (id))';
+
 
         if ('sqlserv' === $DB['type']) {
             // queries to update VARCHAR -> NVARCHAR on MS SQL Server

programming_language: PHP
filename: Backup.php
change_type: ModificationType.ADD
diff: @@ -0,0 +1,147 @@
+<?php
+
+/**
+ * Provides methods for phpMyFAQ backups
+ *
+ * This Source Code Form is subject to the terms of the Mozilla Public License,
+ * v. 2.0. If a copy of the MPL was not distributed with this file, You can
+ * obtain one at https://mozilla.org/MPL/2.0/.
+ *
+ * @package   phpMyFAQ
+ * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
+ * @copyright 2022 phpMyFAQ Team
+ * @license   https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
+ * @link      https://www.phpmyfaq.de
+ * @since     2022-10-08
+ */
+
+namespace phpMyFAQ;
+
+use phpMyFAQ\Core\Exception;
+use phpMyFAQ\Database\DatabaseHelper;
+use SodiumException;
+
+/**
+ * Class Backup
+ *
+ * @package phpMyFAQ
+ */
+class Backup
+{
+    public const BACKUP_TYPE_DATA = 'data';
+    public const BACKUP_TYPE_LOGS = 'logs';
+
+    /** @var Configuration */
+    private Configuration $config;
+
+    /** @var DatabaseHelper */
+    private DatabaseHelper $databaseHelper;
+
+    /**
+     * Constructor.
+     *
+     * @param Configuration  $config
+     * @param DatabaseHelper $databaseHelper
+     */
+    public function __construct(Configuration $config, DatabaseHelper $databaseHelper)
+    {
+        $this->config = $config;
+        $this->databaseHelper = $databaseHelper;
+    }
+
+    /**
+     * @param string $backupType
+     * @param string $backupFile
+     * @return string
+     * @throws SodiumException
+     */
+    public function createBackup(string $backupType, string $backupFile): string
+    {
+        $backupDate = date('Y-m-d-H-i-s');
+
+        $fileNamePrefix = (Database::getTablePrefix() !== '') ? Database::getTablePrefix() . '.phpmyfaq' : 'phpmyfaq';
+        $fileName = sprintf('%s-%s.%s.sql', $fileNamePrefix, $backupType, $backupDate);
+
+        $authKey = sodium_crypto_auth_keygen();
+        $authCode = sodium_crypto_auth($backupFile, $authKey);
+
+        $query = sprintf(
+            "INSERT INTO %sfaqbackup (id, filename, authkey, authcode, created) VALUES (%d, '%s', '%s', '%s', '%s')",
+            Database::getTablePrefix(),
+            $this->config->getDb()->nextId(Database::getTablePrefix() . 'faqbackup', 'id'),
+            $this->config->getDb()->escape($fileName),
+            $this->config->getDb()->escape(sodium_bin2hex($authKey)),
+            $this->config->getDb()->escape(sodium_bin2hex($authCode)),
+            $backupDate
+        );
+
+        $this->config->getDb()->query($query);
+
+        return $fileName;
+    }
+
+    /**
+     * @param string $backup
+     * @param string $backupFileName
+     * @return bool
+     * @throws SodiumException
+     */
+    public function verifyBackup(string $backup, string $backupFileName): bool
+    {
+        $query = sprintf(
+            "SELECT id, filename, authkey, authcode, created FROM %sfaqbackup WHERE filename = '%s'",
+            Database::getTablePrefix(),
+            $this->config->getDb()->escape($backupFileName),
+        );
+
+        $result = $this->config->getDb()->query($query);
+
+        if ($this->config->getDb()->numRows($result) > 0) {
+            $row = $this->config->getDb()->fetchObject($result);
+
+            return sodium_crypto_auth_verify(
+                sodium_hex2bin($row->authcode),
+                $backup,
+                sodium_hex2bin($row->authkey)
+            );
+        }
+
+        return false;
+    }
+
+    /**
+     * @param string $tableNames
+     * @return string
+     */
+    public function generateBackupQueries(string $tableNames): string
+    {
+        $backup = implode("\r\n", $this->getBackupHeader($tableNames));
+
+        foreach (explode(' ', $tableNames) as $table) {
+            if ('' !== $table) {
+                $backup .= implode(
+                    "\r\n",
+                    $this->databaseHelper->buildInsertQueries('SELECT * FROM ' . $table, $table)
+                );
+            }
+        }
+
+        return $backup;
+    }
+
+    /**
+     * Returns the backup file header
+     * @param string $tableNames
+     * @return string[]
+     */
+    private function getBackupHeader(string $tableNames): array
+    {
+        return [
+            sprintf('-- pmf%s: %s', substr($this->config->getVersion(), 0, 3), $tableNames),
+            '-- DO NOT REMOVE THE FIRST LINE!',
+            '-- pmftableprefix: ' . Database::getTablePrefix(),
+            '-- DO NOT REMOVE THE LINES ABOVE!',
+            '-- Otherwise this backup will be broken.'
+        ];
+    }
+}

programming_language: PHP
filename: Database.php
change_type: ModificationType.MODIFY
diff: @@ -141,13 +141,15 @@ class Database
      *
      * @param string $method
      */
-    public static function errorPage(string $method)
+    public static function errorPage(string $method): void
     {
         echo '<!DOCTYPE html>
             <html lang="en" class="no-js">
             <head>
                 <meta charset="utf-8">
                 <title>Fatal phpMyFAQ Error</title>
+                <link href="assets/dist/styles.css" rel="stylesheet">
+                <script src="assets/dist/frontend.js"></script>
             </head>
             <body>
                 <div class="container">
@@ -163,7 +165,7 @@ class Database
      *
      * @param string $tablePrefix
      */
-    public static function setTablePrefix(string $tablePrefix)
+    public static function setTablePrefix(string $tablePrefix): void
     {
         self::$tablePrefix = $tablePrefix;
     }

programming_language: PHP
filename: DatabaseHelper.php
change_type: ModificationType.MODIFY
diff: @@ -7,13 +7,13 @@
  * v. 2.0. If a copy of the MPL was not distributed with this file, You can
  * obtain one at https://mozilla.org/MPL/2.0/.
  *
- * @package phpMyFAQ
- * @author Thorsten Rinne <thorsten@phpmyfaq.de>
- * @author Matteo Scaramuccia <matteo@phpmyfaq.de>
+ * @package   phpMyFAQ
+ * @author    Thorsten Rinne <thorsten@phpmyfaq.de>
+ * @author    Matteo Scaramuccia <matteo@phpmyfaq.de>
  * @copyright 2012-2022 phpMyFAQ Team
- * @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
- * @link https://www.phpmyfaq.de
- * @since 2012-04-12
+ * @license   https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
+ * @link      https://www.phpmyfaq.de
+ * @since     2012-04-12
  */
 
 namespace phpMyFAQ\Database;
@@ -28,10 +28,8 @@ use phpMyFAQ\Strings;
  */
 class DatabaseHelper
 {
-    /**
-     * @var Configuration
-     */
-    private $config;
+    /** @var Configuration */
+    private Configuration $config;
 
     /**
      * Constructor.
@@ -103,7 +101,7 @@ class DatabaseHelper
      *
      * @param string $query
      * @param string $table
-     * @return array
+     * @return string[]
      */
     public function buildInsertQueries(string $query, string $table): array
     {
@@ -118,6 +116,9 @@ class DatabaseHelper
             $p1 = [];
             $p2 = [];
             foreach ($row as $key => $val) {
+                if (is_int($key)) {
+                    continue; // Fix for SQLite3
+                }
                 $p1[] = $key;
                 if ('rights' != $key && is_numeric($val)) {
                     $p2[] = $val;

programming_language: PHP
filename: Export.php
change_type: ModificationType.MODIFY
diff: @@ -30,14 +30,14 @@ use phpMyFAQ\Export\Pdf;
  */
 class Export
 {
-    /** @var Faq */
-    protected $faq = null;
+    /** @var Faq|null */
+    protected ?Faq $faq = null;
 
-    /** @var Category */
-    protected $category = null;
+    /** @var Category|null */
+    protected ?Category $category = null;
 
-    /** @var Configuration */
-    protected $config = null;
+    /** @var Configuration|null */
+    protected ?Configuration $config = null;
 
     /**
      * Factory.
@@ -49,18 +49,14 @@ class Export
      * @return mixed
      * @throws \Exception
      */
-    public static function create(Faq $faq, Category $category, Configuration $config, string $mode = 'pdf')
+    public static function create(Faq $faq, Category $category, Configuration $config, string $mode = 'pdf'): mixed
     {
-        switch ($mode) {
-            case 'json':
-                return new Json($faq, $category, $config);
-            case 'pdf':
-                return new Pdf($faq, $category, $config);
-            case 'html5':
-                return new Html5($faq, $category, $config);
-            default:
-                throw new Exception('Export not implemented!');
-        }
+        return match ($mode) {
+            'json' => new Json($faq, $category, $config),
+            'pdf' => new Pdf($faq, $category, $config),
+            'html5' => new Html5($faq, $category, $config),
+            default => throw new Exception('Export not implemented!'),
+        };
     }
 
     /**

programming_language: PHP
filename: Filesystem.php
change_type: ModificationType.MODIFY
diff: @@ -29,27 +29,27 @@ class Filesystem
     /**
      * @var string
      */
-    private $rootPath;
+    private string $rootPath;
 
     /**
      * @var string
      */
-    private $path;
+    private string $path;
 
     /**
      * @var string[]
      */
-    private $folders = [];
+    private array $folders = [];
 
     /**
      * Constructor, sets the root path of the master phpMyFAQ installation.
      *
      * @param string $rootPath
      */
-    public function __construct($rootPath = '')
+    public function __construct(string $rootPath = '')
     {
         if (empty($rootPath)) {
-            $this->rootPath = dirname(dirname(__DIR__));
+            $this->rootPath = dirname(__DIR__, 2);
         } else {
             $this->rootPath = $rootPath;
         }
@@ -141,7 +141,7 @@ class Filesystem
      *                          specified in the pathname.
      * @return bool
      */
-    public function createDirectory(string $pathname, $mode = 0777, $recursive = false): bool
+    public function createDirectory(string $pathname, int $mode = 0777, bool $recursive = false): bool
     {
         if (is_dir($pathname)) {
             return true; // Directory already exists

programming_language: PHP
filename: CategoryHelper.php
change_type: ModificationType.MODIFY
diff: @@ -342,31 +342,20 @@ class CategoryHelper extends Helper
         }
 
         $decks = '';
-        $key = 1;
         foreach ($categories as $category) {
-            $decks .= '<div class="card mb-4"><a href="' . $category['url'] . '">';
+            $decks .= '<div class="phpmyfaq-startpage-item phpmyfaq-startpage-item-primary col-lg-4 col-6">';
+            $decks .= ' <div class="phpmyfaq-startpage-item-inner">';
+            $decks .= '   <div class="icon-holder">';
             if ('' !== $category['image']) {
                 $decks .= '<img class="card-img-top embed-responsive-item" width="200" alt="' .
-                $category['name'] . '" src="' . $category['image'] . '" />';
+                    $category['name'] . '" src="' . $category['image'] . '" />';
             }
-            $decks .= '</a>' .
-                '<div class="card-body">' .
-                '<h4 class="card-title text-center">' .
-                '<a href="' . $category['url'] . '">' . $category['name'] . '</a>' .
-                '</h4>' .
-                '<p class="card-text">' . $category['description'] . '</p>' .
-                '</div>' .
-                '</div>';
-            if ($key % 2 === 0) {
-                $decks .= '<div class="w-100 d-none d-sm-block d-md-none"></div>';
-            }
-            if ($key % 3 === 0) {
-                $decks .= '<div class="w-100 d-none d-md-block d-lg-none"></div>';
-            }
-            if ($key % 4 === 0) {
-                $decks .= '<div class="w-100 d-none d-lg-block d-xl-block"></div>';
-            }
-            $key++;
+            $decks .= '     </div>';
+            $decks .= '     <h3 class="title">' . $category['name'] . '</h3>';
+            $decks .= '     <p class="intro">' . $category['description'] . '</p>';
+            $decks .= '     <a class="link" href="' . $category['url'] . '"><span></span></a>';
+            $decks .= ' </div>';
+            $decks .= '</div>';
         }
 
         return $decks;

programming_language: PHP
filename: Mysqli.php
change_type: ModificationType.MODIFY
diff: @@ -57,6 +57,14 @@ class Mysqli extends Database implements Driver
             contents BLOB NOT NULL,
             PRIMARY KEY (virtual_hash)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci',
 
+        'faqbackup' => 'CREATE TABLE %sfaqbackup (
+            id INT(11) NOT NULL,
+            filename VARCHAR(255) NOT NULL,
+            authkey VARCHAR(255) NOT NULL,
+            authcode VARCHAR(255) NOT NULL,
+            created timestamp NOT NULL,
+            PRIMARY KEY (id))',
+
         'faqcaptcha' => 'CREATE TABLE %sfaqcaptcha (
             id VARCHAR(6) NOT NULL,
             useragent VARCHAR(255) NOT NULL,

programming_language: SQL
filename: Pgsql.php
change_type: ModificationType.MODIFY
diff: @@ -59,6 +59,14 @@ class Pgsql extends Database implements Driver
             contents BYTEA,
             PRIMARY KEY (virtual_hash))',
 
+        'faqbackup' => 'CREATE TABLE %sfaqbackup (
+            id INT(11) NOT NULL,
+            filename VARCHAR(255) NOT NULL,
+            authkey VARCHAR(255) NOT NULL,
+            authcode VARCHAR(255) NOT NULL,
+            created timestamp NOT NULL,
+            PRIMARY KEY (id))',
+
         'faqcaptcha' => 'CREATE TABLE %sfaqcaptcha (
             id VARCHAR(6) NOT NULL,
             useragent VARCHAR(255) NOT NULL,

programming_language: SQL
filename: Sqlite3.php
change_type: ModificationType.MODIFY
diff: @@ -57,6 +57,14 @@ class Sqlite3 extends Database implements Driver
             contents TEXT NOT NULL,
             PRIMARY KEY (virtual_hash))',
 
+        'faqbackup' => 'CREATE TABLE %sfaqbackup (
+            id INT(11) NOT NULL,
+            filename VARCHAR(255) NOT NULL,
+            authkey VARCHAR(255) NOT NULL,
+            authcode VARCHAR(255) NOT NULL,
+            created timestamp NOT NULL,
+            PRIMARY KEY (id))',
+
         'faqcaptcha' => 'CREATE TABLE %sfaqcaptcha (
             id VARCHAR(6) NOT NULL,
             useragent VARCHAR(255) NOT NULL,

programming_language: SQL
filename: Sqlsrv.php
change_type: ModificationType.MODIFY
diff: @@ -57,6 +57,14 @@ class Sqlsrv extends Database implements Driver
             contents NVARCHAR(MAX) NOT NULL,
             PRIMARY KEY (virtual_hash))',
 
+        'faqbackup' => 'CREATE TABLE %sfaqbackup (
+            id INT(11) NOT NULL,
+            filename VARCHAR(255) NOT NULL,
+            authkey VARCHAR(255) NOT NULL,
+            authcode VARCHAR(255) NOT NULL,
+            created timestamp NOT NULL,
+            PRIMARY KEY (id))',
+
         'faqcaptcha' => 'CREATE TABLE %sfaqcaptcha (
             id NVARCHAR(6) NOT NULL,
             useragent NVARCHAR(255) NOT NULL,

programming_language: SQL
filename: Setup.php
change_type: ModificationType.MODIFY
diff: @@ -31,7 +31,7 @@ class Setup
     /**
      * @var string
      */
-    private $rootDir;
+    private string $rootDir;
 
     /**
      * Setup constructor.
@@ -46,7 +46,7 @@ class Setup
      *
      * @param string $rootDir
      */
-    public function setRootDir($rootDir)
+    public function setRootDir(string $rootDir): void
     {
         $this->rootDir = $rootDir;
     }
@@ -73,9 +73,9 @@ class Setup
      * Checks basic folders and creates them if necessary.
      *
      * @param  string[] $dirs
-     * @return array
+     * @return string[]
      */
-    public function checkDirs(array $dirs)
+    public function checkDirs(array $dirs): array
     {
         $failedDirs = [];
 
@@ -113,11 +113,11 @@ class Setup
     /**
      * Creates the file /config/database.php.
      *
-     * @param  array  $data   Array with database credentials
-     * @param  string $folder Folder
+     * @param  int[]|string[] $data   Array with database credentials
+     * @param  string         $folder Folder
      * @return int|bool
      */
-    public function createDatabaseFile(array $data, $folder = '/config')
+    public function createDatabaseFile(array $data, string $folder = '/config'): int|bool
     {
         return file_put_contents(
             $this->rootDir . $folder . '/database.php',
@@ -136,11 +136,11 @@ class Setup
     /**
      * Creates the file /config/ldap.php.
      *
-     * @param  array  $data   Array with LDAP credentials
-     * @param  string $folder Folder
+     * @param  int[]|string[] $data   Array with LDAP credentials
+     * @param  string         $folder Folder
      * @return int|bool
      */
-    public function createLdapFile(array $data, string $folder = '/config')
+    public function createLdapFile(array $data, string $folder = '/config'): int|bool
     {
         return file_put_contents(
             $this->rootDir . $folder . '/config/ldap.php',
@@ -157,11 +157,11 @@ class Setup
     /**
      * Creates the file /config/elasticsearch.php
      *
-     * @param  array  $data   Array with LDAP credentials
-     * @param  string $folder Folder
+     * @param  int[]|string[] $data   Array with Elasticsearch credentials
+     * @param  string         $folder Folder
      * @return int|bool
      */
-    public function createElasticsearchFile(array $data, string $folder = '/config')
+    public function createElasticsearchFile(array $data, string $folder = '/config'): int|bool
     {
         return file_put_contents(
             $this->rootDir . $folder . '/config/elasticsearch.php',

programming_language: PHP
filename: ApiTest.php
change_type: ModificationType.MODIFY
diff: @@ -13,7 +13,6 @@ use PHPUnit\Framework\TestCase;
  */
 class ApiTest extends TestCase
 {
-
     /** @var Configuration */
     private Configuration $configuration;
 
@@ -29,6 +28,7 @@ class ApiTest extends TestCase
 
     /**
      * @testdox return the available versions
+     * @throws Core\Exception
      */
     public function testGetVersions(): void
     {
@@ -52,6 +52,7 @@ class ApiTest extends TestCase
 
     /**
      * @testdox return the current verification hashes
+     * @throws Core\Exception
      */
     public function testGetVerificationIssues(): void
     {

programming_language: PHP
filename: BackupTest.php
change_type: ModificationType.ADD
diff: @@ -0,0 +1,87 @@
+<?php
+
+namespace phpMyFAQ;
+
+use phpMyFAQ\Database\DatabaseHelper;
+use phpMyFAQ\Database\Sqlite3;
+use PHPUnit\Framework\TestCase;
+use SodiumException;
+
+/**
+ * Class BackupTest
+ *
+ * @testdox Backup should
+ * @package phpMyFAQ
+ */
+class BackupTest extends TestCase
+{
+    /** @var Configuration */
+    protected Configuration $configuration;
+
+    /** @var DatabaseHelper */
+    protected DatabaseHelper $databaseHelper;
+
+    /** @var Backup */
+    protected Backup $backup;
+
+    protected function setUp(): void
+    {
+        parent::setUp();
+
+        $dbHandle = new Sqlite3();
+        $dbHandle->connect(PMF_TEST_DIR . '/test.db', '', '');
+
+        $this->configuration = new Configuration($dbHandle);
+        $this->configuration->config['main.currentVersion'] = System::getVersion();
+
+        $this->databaseHelper = new DatabaseHelper($this->configuration);
+
+        $this->backup = new Backup($this->configuration, $this->databaseHelper);
+    }
+
+    /**
+     * @testdox create a complete backup file
+     * @throws SodiumException
+     */
+    public function testCreateBackup(): void
+    {
+        $tableNames = 'faqconfig faqinstances';
+        $backupQueries = $this->backup->generateBackupQueries($tableNames);
+        $dataBackup = $this->backup->createBackup(Backup::BACKUP_TYPE_DATA, $backupQueries);
+        $expected = 'phpmyfaq-data.' . date('Y-m-d-H-i-s') . '.sql';
+
+        $this->assertEquals($expected, $dataBackup);
+
+        $tableNames = 'faqadminlog faqsessions';
+        $backupQueries = $this->backup->generateBackupQueries($tableNames);
+        $logsBackup = $this->backup->createBackup(Backup::BACKUP_TYPE_LOGS, $backupQueries);
+        $expected = 'phpmyfaq-logs.' . date('Y-m-d-H-i-s') . '.sql';
+
+        $this->assertEquals($expected, $logsBackup);
+    }
+
+    /**
+     * @throws SodiumException
+     */
+    public function testVerifyBackup(): void
+    {
+        $tableNames = 'faqconfig faqinstances';
+        $backupQueries = $this->backup->generateBackupQueries($tableNames);
+        $dataBackup = $this->backup->createBackup(Backup::BACKUP_TYPE_DATA, $backupQueries);
+
+        $result = $this->backup->verifyBackup($backupQueries, $dataBackup);
+
+        $this->assertTrue($result);
+    }
+
+    /**
+     * @testdox generates correct INSERT queries for the backup
+     */
+    public function testGenerateBackupQueries(): void
+    {
+        $tableNames = 'faqconfig faqinstances';
+        $queries = $this->backup->generateBackupQueries($tableNames);
+
+        $this->assertStringContainsString('DO NOT REMOVE THE FIRST LINE!', $queries);
+    }
+}

programming_language: PHP
filename: DatabaseHelperTest.php
change_type: ModificationType.ADD
diff: @@ -0,0 +1,63 @@
+<?php
+
+namespace phpMyFAQ\Database;
+
+use phpMyFAQ\Configuration;
+use phpMyFAQ\System;
+use PHPUnit\Framework\TestCase;
+
+/**
+ * Class DatabaseHelperTest
+ *
+ * @testdox DatabaseHelper should
+ * @package phpMyFAQ
+ */
+class DatabaseHelperTest extends TestCase
+{
+    /** @var DatabaseHelper */
+    private DatabaseHelper $databaseHelper;
+
+    protected function setUp(): void
+    {
+        parent::setUp();
+
+        $dbHandle = new Sqlite3();
+        $dbHandle->connect(PMF_TEST_DIR . '/test.db', '', '');
+        $dbHandle->query(
+            'CREATE TABLE faqtest (name VARCHAR(255) NOT NULL, testvalue VARCHAR(255) DEFAULT NULL, PRIMARY KEY (name))'
+        );
+        $dbHandle->query("INSERT INTO faqtest (name,testvalue) VALUES ('foo','bar')");
+        $dbHandle->query("INSERT INTO faqtest (name,testvalue) VALUES ('bar','baz')");
+
+        $configuration = new Configuration($dbHandle);
+        $configuration->config['main.currentVersion'] = System::getVersion();
+
+        $this->databaseHelper = new DatabaseHelper($configuration);
+    }
+
+    protected function tearDown(): void
+    {
+        parent::tearDown();
+
+        $dbHandle = new Sqlite3();
+        $dbHandle->connect(PMF_TEST_DIR . '/test.db', '', '');
+        $dbHandle->query('DROP TABLE faqtest');
+    }
+
+    /**
+     * @testdox create the correct INSERT queries
+     */
+    public function testBuildInsertQueries(): void
+    {
+        $table = 'faqtest';
+        $queries = $this->databaseHelper->buildInsertQueries('SELECT * FROM ' . $table, $table);
+
+        $expected = [
+            "\r\n-- Table: faqtest",
+            "INSERT INTO faqtest (name,testvalue) VALUES ('foo','bar');",
+            "INSERT INTO faqtest (name,testvalue) VALUES ('bar','baz');"
+        ];
+
+        $this->assertEquals($expected, $queries);
+    }
+}

programming_language: PHP