nus-yam/ex-repair huggingface dataset:
Program: CWE-79
Project: CVE-2022-0472
Buggy source:
<?php

namespace App\Shop\Products\Requests;

use App\Shop\Base\BaseFormRequest;
use Illuminate\Validation\Rule;

class UpdateProductRequest extends BaseFormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'sku' => ['required'],
            'name' => ['required', Rule::unique('products')->ignore($this->segment(3))],
            'quantity' => ['required', 'integer', 'min:0'],
            'price' => ['required', 'numeric', 'min:0'],
            'sale_price' => ['nullable', 'numeric'],
            'weight' => ['nullable', 'numeric', 'min:0']
        ];
    }
}


Fixed version (ground truth):
<?php

namespace App\Shop\Products\Requests;

use App\Shop\Base\BaseFormRequest;
use Illuminate\Validation\Rule;

class UpdateProductRequest extends BaseFormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'sku' => ['required'],
            'name' => ['required', Rule::unique('products')->ignore($this->segment(3))],
            'quantity' => ['required', 'integer', 'min:0'],
            'price' => ['required', 'numeric', 'min:0'],
            'sale_price' => ['nullable', 'numeric'],
            'weight' => ['nullable', 'numeric', 'min:0'],
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'cover' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ];
    }
}
Program: CWE-79
Project: CVE-2022-0558
Buggy source:
<?php

namespace MicroweberPackages\Helper;

class HTMLClean
{
    public function clean($html) {

        $antiXss = new \voku\helper\AntiXSS();
        $html = $antiXss->xss_clean($html);

        $path = storage_path() . '/html_purifier';
        if (!is_dir($path)) {
            mkdir_recursive($path);
        }

        $config = \HTMLPurifier_Config::createDefault();
        if ($path) {
            $config->set('Cache.SerializerPath', $path);
        }

        $config->set('URI.DisableExternal', true);
        $config->set('URI.DisableExternalResources', true);
    //    $config->set('URI.DisableResources', true);
        $config->set('URI.Host', site_hostname());

        $purifier = new \HTMLPurifier($config);
        $html = $purifier->purify($html);

        return $html;
    }
}


Fixed version (ground truth):
<?php

namespace MicroweberPackages\Helper;

class HTMLClean
{
    public function cleanArray($array) {
        if (is_array($array)) {

            $cleanedArray = [];
            foreach ($array as $key=>$value) {
                $cleanedArray[$key] = $this->clean($value);
            }

            return $cleanedArray;
        }
    }

    public function clean($html) {

        $antiXss = new \voku\helper\AntiXSS();
        $html = $antiXss->xss_clean($html);

        $path = storage_path() . '/html_purifier';
        if (!is_dir($path)) {
            mkdir_recursive($path);
        }

        $config = \HTMLPurifier_Config::createDefault();
        if ($path) {
            $config->set('Cache.SerializerPath', $path);
        }

        $config->set('URI.DisableExternal', true);
        $config->set('URI.DisableExternalResources', true);
    //    $config->set('URI.DisableResources', true);
        $config->set('URI.Host', site_hostname());

        $purifier = new \HTMLPurifier($config);
        $html = $purifier->purify($html);

        return $html;
    }
}
Program: CWE-79
Project: CVE-2022-0612
Buggy source:
<a rel="noreferrer" class="navbar-brand back-logo" href="<?php echo erLhcoreClassDesign::baseurl()?>" title="<?php echo htmlspecialchars(erLhcoreClassModelChatConfig::fetch('customer_company_name')->current_value)?>"><img class="img-fluid" src="<?php echo erLhcoreClassDesign::design('images/general/logo.png');?>" alt="<?php echo htmlspecialchars(erLhcoreClassModelChatConfig::fetch('customer_company_name')->current_value)?>" title="<?php echo htmlspecialchars(erLhcoreClassModelChatConfig::fetch('customer_company_name')->current_value)?>"></a>

Fixed version (ground truth):
<a rel="noreferrer" ng-non-bindable class="navbar-brand back-logo" href="<?php echo erLhcoreClassDesign::baseurl()?>" title="<?php echo htmlspecialchars(erLhcoreClassModelChatConfig::fetch('customer_company_name')->current_value)?>"><img class="img-fluid" src="<?php echo erLhcoreClassDesign::design('images/general/logo.png');?>" alt="<?php echo htmlspecialchars(erLhcoreClassModelChatConfig::fetch('customer_company_name')->current_value)?>" title="<?php echo htmlspecialchars(erLhcoreClassModelChatConfig::fetch('customer_company_name')->current_value)?>"></a>
Program: CWE-79
Project: CVE-2022-0690
Buggy source:
<?php
/**
 * Created by PhpStorm.
 * User: Bojidar
 * Date: 8/19/2020
 * Time: 4:09 PM
 */
namespace MicroweberPackages\Post\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use MicroweberPackages\App\Http\Controllers\AdminController;
use MicroweberPackages\Post\Http\Requests\PostRequest;
use MicroweberPackages\Post\Repositories\PostRepository;

class PostController extends AdminController
{
    public $repository;

    public function __construct(PostRepository $repository)
    {
        parent::__construct();

        $this->repository = $repository;
    }

    public function create() {

        return $this->view('post::admin.posts.edit', [
            'content_id'=>0
        ]);
    }

    public function edit(Request $request, $id) {

        return $this->view('post::admin.posts.edit', [
            'content_id'=>$id
        ]);
    }
}


Fixed version (ground truth):
<?php
/**
 * Created by PhpStorm.
 * User: Bojidar
 * Date: 8/19/2020
 * Time: 4:09 PM
 */
namespace MicroweberPackages\Post\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use MicroweberPackages\App\Http\Controllers\AdminController;
use MicroweberPackages\Post\Http\Requests\PostRequest;
use MicroweberPackages\Post\Repositories\PostRepository;

class PostController extends AdminController
{
    public $repository;

    public function __construct(PostRepository $repository)
    {
        parent::__construct();

        $this->repository = $repository;
    }

    public function create() {

        return $this->view('post::admin.posts.edit', [
            'content_id'=>0
        ]);
    }

    public function edit(Request $request, $id) {

        return $this->view('post::admin.posts.edit', [
            'content_id'=>intval($id)
        ]);
    }
}
Program: CWE-79
Project: CVE-2022-0752
Buggy source:
<?php

// Init
ob_start();
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");


// Check token
verify_csrf($_GET);

if (!empty($_GET['database'])) {
    $v_username = escapeshellarg($user);
    $v_database = escapeshellarg($_GET['database']);
    exec(HESTIA_CMD."v-unsuspend-database ".$v_username." ".$v_database, $output, $return_var);
    check_return_code($return_var, $output);
    unset($output);
}

$back=getenv("HTTP_REFERER");
if (!empty($back)) {
    header("Location: ".$back);
    exit;
}

header("Location: /list/db/");
exit;


Fixed version (ground truth):
<?php

// Init
ob_start();
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");


// Check token
verify_csrf($_GET);

if (!empty($_GET['database'])) {
    $v_database = escapeshellarg($_GET['database']);
    exec(HESTIA_CMD."v-unsuspend-database ".$user." ".$v_database, $output, $return_var);
    check_return_code($return_var, $output);
    unset($output);
}

$back=getenv("HTTP_REFERER");
if (!empty($back)) {
    header("Location: ".$back);
    exit;
}

header("Location: /list/db/");
exit;
Program: CWE-79
Project: CVE-2022-0753
Buggy source:
<?php

// Init
ob_start();
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");


// Check token
verify_csrf($_GET);

if (!empty($_GET['database'])) {
    $v_username = escapeshellarg($user);
    $v_database = escapeshellarg($_GET['database']);
    exec(HESTIA_CMD."v-unsuspend-database ".$v_username." ".$v_database, $output, $return_var);
    check_return_code($return_var, $output);
    unset($output);
}

$back=getenv("HTTP_REFERER");
if (!empty($back)) {
    header("Location: ".$back);
    exit;
}

header("Location: /list/db/");
exit;


Fixed version (ground truth):
<?php

// Init
ob_start();
include($_SERVER['DOCUMENT_ROOT']."/inc/main.php");


// Check token
verify_csrf($_GET);

if (!empty($_GET['database'])) {
    $v_database = escapeshellarg($_GET['database']);
    exec(HESTIA_CMD."v-unsuspend-database ".$user." ".$v_database, $output, $return_var);
    check_return_code($return_var, $output);
    unset($output);
}

$back=getenv("HTTP_REFERER");
if (!empty($back)) {
    header("Location: ".$back);
    exit;
}

header("Location: /list/db/");
exit;
Program: CWE-79
Project: CVE-2022-0877
Buggy source:
<?php

namespace BookStack\Http\Middleware;

use BookStack\Util\CspService;
use Closure;
use Illuminate\Http\Request;

class ApplyCspRules
{
    /**
     * @var CspService
     */
    protected $cspService;

    public function __construct(CspService $cspService)
    {
        $this->cspService = $cspService;
    }

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        view()->share('cspNonce', $this->cspService->getNonce());
        if ($this->cspService->allowedIFrameHostsConfigured()) {
            config()->set('session.same_site', 'none');
        }

        $response = $next($request);

        $this->cspService->setFrameAncestors($response);
        $this->cspService->setScriptSrc($response);
        $this->cspService->setObjectSrc($response);
        $this->cspService->setBaseUri($response);

        return $response;
    }
}


Fixed version (ground truth):
<?php

namespace BookStack\Http\Middleware;

use BookStack\Util\CspService;
use Closure;
use Illuminate\Http\Request;

class ApplyCspRules
{
    protected CspService $cspService;

    public function __construct(CspService $cspService)
    {
        $this->cspService = $cspService;
    }

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        view()->share('cspNonce', $this->cspService->getNonce());
        if ($this->cspService->allowedIFrameHostsConfigured()) {
            config()->set('session.same_site', 'none');
        }

        $response = $next($request);

        $cspHeader = $this->cspService->getCspHeader();
        $response->headers->set('Content-Security-Policy', $cspHeader, false);

        return $response;
    }
}
Program: CWE-79
Project: CVE-2022-0928
Buggy source:
<?php
/*
 * This file is part of the Microweber framework.
 *
 * (c) Microweber CMS LTD
 *
 * For full license information see
 * https://github.com/microweber/microweber/blob/master/LICENSE
 *
 */

namespace MicroweberPackages\Tax;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class TaxManagerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        /**
         * @property \MicroweberPackages\Tax    $tax_manager
         */
        $this->app->singleton('tax_manager', function ($app) {
            return new TaxManager();
        });

        $this->loadMigrationsFrom(__DIR__ . '/database/migrations/');
    }
}


Fixed version (ground truth):
<?php
/*
 * This file is part of the Microweber framework.
 *
 * (c) Microweber CMS LTD
 *
 * For full license information see
 * https://github.com/microweber/microweber/blob/master/LICENSE
 *
 */

namespace MicroweberPackages\Tax;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class TaxManagerServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        /**
         * @property \MicroweberPackages\Tax    $tax_manager
         */
        $this->app->singleton('tax_manager', function ($app) {
            return new TaxManager();
        });

        $this->loadMigrationsFrom(__DIR__ . '/database/migrations/');
    }

    public function register()
    {
        $this->loadRoutesFrom((__DIR__) . '/routes/api.php');
        $this->loadRoutesFrom((__DIR__) . '/routes/web.php');
    }
}
Program: CWE-79
Project: CVE-2022-0954
Buggy source:
<?php

namespace MicroweberPackages\Option\Http\Controllers\Api;

use Illuminate\Http\Request;

class SaveOptionApiController
{
    public function saveOption(Request $request) {

        $cleanFromXss = true;
        $option = $request->all();

        // Allow for this keys
        if (isset($option['option_key'])) {
            if ($option['option_key'] == 'website_head') {
                $cleanFromXss = false;
            }
            if ($option['option_key'] == 'website_footer') {
                $cleanFromXss = false;
            }
        }

        if ($cleanFromXss) {
            $clean = new HTMLClean();
            $option = $clean->cleanArray($option);
        }

        return save_option($option);
    }

}


Fixed version (ground truth):
<?php

namespace MicroweberPackages\Option\Http\Controllers\Api;

use Illuminate\Http\Request;

class SaveOptionApiController
{
    public $whitelistedGroupKeys = [
        'website' => [
            'website_head',
            'website_footer'
        ]
    ];

    public function saveOption(Request $request)
    {

        $cleanFromXss = true;
        $option = $request->all();

        // Allow for this keys and groups
        if (isset($option['option_key'])) {
            foreach ($this->whitelistedGroupKeys as $group => $keys) {
                if ($option['option_group'] == $group) {
                    foreach ($keys as $key) {
                        if ($option['option_key'] == $key) {
                            $cleanFromXss = false;
                            break;
                        }
                    }
                }
            }
        }

        if ($cleanFromXss) {
            $clean = new HTMLClean();
            $option = $clean->cleanArray($option);
        }

        return save_option($option);
    }

}
Program: CWE-79
Project: CVE-2022-1234
Buggy source:
<?php

// Debug
//erLhcoreClassLog::write(print_r($_POST,true));

@ini_set('session.cookie_samesite', 'None');
@ini_set('session.cookie_secure', true);

$currentUser = erLhcoreClassUser::instance();

if ($currentUser->authenticate($_POST['username'],$_POST['password']))
{     
        echo json_encode(
            array('result' => true)
        );
          
} else {

    if (($userAttempt = erLhcoreClassModelUser::findOne(array('filter' => array('username' => $_POST['Username'])))) instanceof erLhcoreClassModelUser) {
        erLhcoreClassModelUserLogin::logUserAction(array(
            'type' => erLhcoreClassModelUserLogin::TYPE_LOGIN_ATTEMPT,
            'user_id' => $userAttempt->id,
            'msg' => erTranslationClassLhTranslation::getInstance()->getTranslation('user/login','Failed login. XML_CHECK_LOGIN')
        ));

        erLhcoreClassModelUserLogin::disableIfRequired($userAttempt);
    }

    echo json_encode(
            array('result' => false)
        );    
}
  

exit;
?>

Fixed version (ground truth):
<?php

// Debug
//erLhcoreClassLog::write(print_r($_POST,true));

header('Content-type: application/json');

@ini_set('session.cookie_samesite', 'None');
@ini_set('session.cookie_secure', true);

$currentUser = erLhcoreClassUser::instance();

if ($currentUser->authenticate($_POST['username'],$_POST['password']))
{     
        echo json_encode(
            array('result' => true)
        );
          
} else {

    if (($userAttempt = erLhcoreClassModelUser::findOne(array('filter' => array('username' => $_POST['Username'])))) instanceof erLhcoreClassModelUser) {
        erLhcoreClassModelUserLogin::logUserAction(array(
            'type' => erLhcoreClassModelUserLogin::TYPE_LOGIN_ATTEMPT,
            'user_id' => $userAttempt->id,
            'msg' => erTranslationClassLhTranslation::getInstance()->getTranslation('user/login','Failed login. XML_CHECK_LOGIN')
        ));

        erLhcoreClassModelUserLogin::disableIfRequired($userAttempt);
    }

    echo json_encode(
            array('result' => false)
        );    
}
  

exit;
?>
Program: CWE-79
Project: CVE-2022-1291
Buggy source:
{
  "name": "tableexport.jquery.plugin",
  "version": "1.22.0",
  "description": "html table export",
  "main": "tableExport.min.js",
  "dependencies": {
    "jquery": ">=1.9.1",
    "file-saver": ">=2.0.1",
    "html2canvas": ">=1.0.0",
    "jspdf": ">=2.0.0",
    "pdfmake": "^0.1.71",
    "xlsx": ">=0.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/hhurz/tableExport.jquery.plugin.git"
  },
  "bugs": {
    "url": "https://github.com/hhurz/tableExport.jquery.plugin/issues"
  },
  "keywords": [
    "html5",
    "javascript",
    "jquery",
    "export",
    "table"
  ],
  "author": "hhurz",
  "license": "MIT",
  "homepage": "https://github.com/hhurz/tableExport.jquery.plugin/",
  "files": [
    "LICENSE",
    "README.md",
    "tableExport.min.js",
    "libs"
  ]
}


Fixed version (ground truth):
{
  "name": "tableexport.jquery.plugin",
  "version": "1.25.0",
  "description": "html table export",
  "main": "tableExport.min.js",
  "dependencies": {
    "jquery": ">=3.2.1",
    "file-saver": ">=2.0.1",
    "html2canvas": ">=1.0.0",
    "jspdf": ">=2.0.0",
    "pdfmake": "^0.1.71",
    "xlsx": ">=0.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/hhurz/tableExport.jquery.plugin.git"
  },
  "bugs": {
    "url": "https://github.com/hhurz/tableExport.jquery.plugin/issues"
  },
  "keywords": [
    "html5",
    "javascript",
    "jquery",
    "export",
    "table"
  ],
  "author": "hhurz",
  "license": "MIT",
  "homepage": "https://github.com/hhurz/tableExport.jquery.plugin/",
  "files": [
    "LICENSE",
    "README.md",
    "tableExport.min.js",
    "libs"
  ]
}
Program: CWE-79
Project: CVE-2022-1330
Buggy source:
{
  "name": "tableexport.jquery.plugin",
  "version": "1.22.0",
  "description": "html table export",
  "main": "tableExport.min.js",
  "dependencies": {
    "jquery": ">=1.9.1",
    "file-saver": ">=2.0.1",
    "html2canvas": ">=1.0.0",
    "jspdf": ">=2.0.0",
    "pdfmake": "^0.1.71",
    "xlsx": ">=0.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/hhurz/tableExport.jquery.plugin.git"
  },
  "bugs": {
    "url": "https://github.com/hhurz/tableExport.jquery.plugin/issues"
  },
  "keywords": [
    "html5",
    "javascript",
    "jquery",
    "export",
    "table"
  ],
  "author": "hhurz",
  "license": "MIT",
  "homepage": "https://github.com/hhurz/tableExport.jquery.plugin/",
  "files": [
    "LICENSE",
    "README.md",
    "tableExport.min.js",
    "libs"
  ]
}


Fixed version (ground truth):
{
  "name": "tableexport.jquery.plugin",
  "version": "1.25.0",
  "description": "html table export",
  "main": "tableExport.min.js",
  "dependencies": {
    "jquery": ">=3.2.1",
    "file-saver": ">=2.0.1",
    "html2canvas": ">=1.0.0",
    "jspdf": ">=2.0.0",
    "pdfmake": "^0.1.71",
    "xlsx": ">=0.16.0"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/hhurz/tableExport.jquery.plugin.git"
  },
  "bugs": {
    "url": "https://github.com/hhurz/tableExport.jquery.plugin/issues"
  },
  "keywords": [
    "html5",
    "javascript",
    "jquery",
    "export",
    "table"
  ],
  "author": "hhurz",
  "license": "MIT",
  "homepage": "https://github.com/hhurz/tableExport.jquery.plugin/",
  "files": [
    "LICENSE",
    "README.md",
    "tableExport.min.js",
    "libs"
  ]
}
Program: CWE-79
Project: CVE-2022-1811
Buggy source:
# frozen_string_literal: true

require "marcel"

class ResourceUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  before :cache, :check_image_content_type!

  def content_type_allowlist
    [%r{image/}, %r{audio/}, %r{video/}, "text/plain"]
  end

  def store_dir
    "files/#{model.class.to_s.underscore}/#{model.id}"
  end

  version :thumb, if: :image? do
    process dynamic_resize_to_fit: :thumb
  end

  version :medium, if: :image? do
    process dynamic_resize_to_fit: :medium
  end

  version :avatar, if: :image? do
    process dynamic_resize_to_fit: :avatar
  end

  def dynamic_resize_to_fit(size)
    resize_setting = model.blog.send("image_#{size}_size").to_i

    resize_to_fit(resize_setting, resize_setting)
  end

  def image?(new_file)
    content_type = new_file.content_type
    content_type&.include?("image")
  end

  def check_image_content_type!(new_file)
    if image?(new_file)
      magic_type = mime_magic_content_type(new_file)
      if magic_type != new_file.content_type
        raise CarrierWave::IntegrityError, "has MIME type mismatch"
      end
    end
  end

  private

  # NOTE: This method was adapted from MagicMimeBlacklist#extract_content_type
  # from CarrierWave 1.0.0 and SanitizedFile#mime_magic_content_type from CarrierWave 0.11.2
  def mime_magic_content_type(new_file)
    content_type = nil

    File.open(new_file.path) do |fd|
      content_type = Marcel::MimeType.for(fd)
    end

    content_type
  end
end


Fixed version (ground truth):
# frozen_string_literal: true

require "marcel"

class ResourceUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick
  before :cache, :check_content_type!

  def content_type_allowlist
    [%r{image/}, %r{audio/}, %r{video/}, "text/plain"]
  end

  def store_dir
    "files/#{model.class.to_s.underscore}/#{model.id}"
  end

  version :thumb, if: :image? do
    process dynamic_resize_to_fit: :thumb
  end

  version :medium, if: :image? do
    process dynamic_resize_to_fit: :medium
  end

  version :avatar, if: :image? do
    process dynamic_resize_to_fit: :avatar
  end

  def dynamic_resize_to_fit(size)
    resize_setting = model.blog.send("image_#{size}_size").to_i

    resize_to_fit(resize_setting, resize_setting)
  end

  def image?(new_file)
    content_type = new_file.content_type
    content_type&.include?("image")
  end

  def check_content_type!(new_file)
    detected_type = if image? new_file
                      file_content_content_type(new_file)
                    else
                      file_content_type(new_file)
                    end
    if detected_type != new_file.content_type
      raise CarrierWave::IntegrityError, "has MIME type mismatch"
    end
  end

  private

  def file_content_content_type(new_file)
    Marcel::MimeType.for Pathname.new(new_file.path)
  end

  def file_content_type(new_file)
    Marcel::MimeType.for Pathname.new(new_file.path), name: new_file.filename
  end
end
Program: CWE-79
Project: CVE-2022-1988
Buggy source:
<?php
/**
 * This file is part of FacturaScripts
 * Copyright (C) 2017       Francesc Pineda Segarra <francesc.pineda.segarra@gmail.com>
 * Copyright (C) 2017-2018  Carlos Garcia Gomez     <carlos@facturascripts.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

namespace FacturaScripts\Test\Core\Model;

use FacturaScripts\Core\Model\Subcuenta;
use FacturaScripts\Test\Core\CustomTest;

/**
 * @covers \Subcuenta
 *
 * @author Francesc Pineda Segarra <francesc.pineda.segarra@gmail.com>
 */
final class SubcuentaTest extends CustomTest
{

    protected function setUp(): void
    {
        $this->model = new Subcuenta();
    }
}


Fixed version (ground truth):
None
Program: CWE-79
Project: CVE-2022-2016
Buggy source:
None

Fixed version (ground truth):
<?php
/**
 * This file is part of FacturaScripts
 * Copyright (C) 2022 Carlos Garcia Gomez <carlos@facturascripts.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

namespace FacturaScripts\Test\Core\Model;

use FacturaScripts\Core\Model\Balance;
use PHPUnit\Framework\TestCase;

final class BalanceTest extends TestCase
{
    public function testCreate()
    {
        // creamos un balance
        $balance = new Balance();
        $balance->codbalance = 'test';
        $balance->descripcion1 = 'test';
        $balance->naturaleza = 'A';
        $this->assertTrue($balance->save(), 'cant-save-balance');

        // eliminamos
        $this->assertTrue($balance->delete(), 'cant-delete-balance');
    }

    public function testCantCreateEmpty()
    {
        $balance = new Balance();
        $this->assertFalse($balance->save(), 'cant-save-balance');
    }

    public function testHtmlOnFields()
    {
        $balance = new Balance();
        $balance->codbalance = '<test>';
        $balance->descripcion1 = '<test>';
        $balance->descripcion2 = '<test>';
        $balance->descripcion3 = '<test>';
        $balance->descripcion4 = '<test>';
        $balance->descripcion4ba = '<test>';
        $balance->naturaleza = '<test>';
        $this->assertFalse($balance->save(), 'cant-save-balance-with-html');

        // cambiamos el codigo a un codigo válido
        $balance->codbalance = 'test';
        $this->assertTrue($balance->save(), 'cant-save-balance-2');

        // comprobamos que el html se ha escapado
        $this->assertEquals('&lt;test&gt;', $balance->descripcion1);
        $this->assertEquals('&lt;test&gt;', $balance->descripcion2);
        $this->assertEquals('&lt;test&gt;', $balance->descripcion3);
        $this->assertEquals('&lt;test&gt;', $balance->descripcion4);
        $this->assertEquals('&lt;test&gt;', $balance->descripcion4ba);
        $this->assertEquals('&lt;test&gt;', $balance->naturaleza);

        // eliminamos
        $this->assertTrue($balance->delete(), 'cant-delete-balance');
    }
}
Program: CWE-79
Project: CVE-2022-21650
Buggy source:
None

Fixed version (ground truth):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"></html>
Program: CWE-79
Project: CVE-2022-21710
Buggy source:
function main() {
	var shortdesc = mw.config.get( 'wgShortDesc' ),
		tagline;

	if ( shortdesc ) {
		tagline = document.getElementById( 'siteSub' );
		// Wikipedia uses shortdescription class
		// Added for gadgets and extension compatibility
		tagline.classList.add( 'ext-shortdesc', 'shortdescription' );
		tagline.innerHTML = shortdesc;
	}
}

main();


Fixed version (ground truth):
function main() {
	var shortdesc = mw.config.get( 'wgShortDesc' ),
		tagline;

	if ( shortdesc ) {
		tagline = document.getElementById( 'siteSub' );
		// Wikipedia uses shortdescription class
		// Added for gadgets and extension compatibility
		tagline.classList.add( 'ext-shortdesc', 'shortdescription' );
		tagline.innerHTML = mw.html.escape( shortdesc );
	}
}

main();
Program: CWE-79
Project: CVE-2022-21715
Buggy source:
function main() {
	var shortdesc = mw.config.get( 'wgShortDesc' ),
		tagline;

	if ( shortdesc ) {
		tagline = document.getElementById( 'siteSub' );
		// Wikipedia uses shortdescription class
		// Added for gadgets and extension compatibility
		tagline.classList.add( 'ext-shortdesc', 'shortdescription' );
		tagline.innerHTML = shortdesc;
	}
}

main();


Fixed version (ground truth):
function main() {
	var shortdesc = mw.config.get( 'wgShortDesc' ),
		tagline;

	if ( shortdesc ) {
		tagline = document.getElementById( 'siteSub' );
		// Wikipedia uses shortdescription class
		// Added for gadgets and extension compatibility
		tagline.classList.add( 'ext-shortdesc', 'shortdescription' );
		tagline.innerHTML = mw.html.escape( shortdesc );
	}
}

main();
Program: CWE-79
Project: CVE-2022-22851
Buggy source:
None

Fixed version (ground truth):
# CVE-2022-22851
# Exploit Title: HPRMS - 'doctors' Stored XSS
# Exploit Author: (Sant268)
# Vendor Homepage: https://www.sourcecodester.com/
# Software Link: https://www.sourcecodester.com/php/15116/hospitals-patient-records-management-system-php-free-source-code.html
# Version: HPRMS 1.0
# Tested on: Ubuntu 20, Apache
# CVE: CVE-2022-22851

- Description:
A XSS issue in HPRMS v.1.0 allows remote attackers to inject JavaScript via /articles in the description parameter.

- Payload used:
<img src =q onerror=prompt(8)>

- Steps to reproduce:
1- Go to http://victim.com/admin/?page=doctors
2- Add a Doctor, paste the payload in specialisation
3- Alert will pop whenever the page is accessed.
Program: CWE-79
Project: CVE-2022-23599
Buggy source:
None

Fixed version (ground truth):
Security fix: prevent cache poisoning with the Referer header.
See `security advisory <https://github.com/plone/Products.ATContentTypes/security/advisories/GHSA-g4c2-ghfg-g5rh>`.
[maurits]
Program: CWE-79
Project: CVE-2022-23603
Buggy source:
None

Fixed version (ground truth):
Security fix: prevent cache poisoning with the Referer header.
See `security advisory <https://github.com/plone/Products.ATContentTypes/security/advisories/GHSA-g4c2-ghfg-g5rh>`.
[maurits]
Program: CWE-79
Project: CVE-2022-24717
Buggy source:
export function stringEncode(string: string) {
    let encodedString = '';
    for (let i = 0; i < string.length; i++) {
        let charCodePointHex = string.charCodeAt(i).toString(16);
        encodedString += `\\u${charCodePointHex}`;
    }
    return encodedString;
}

Fixed version (ground truth):
export function stringEncode(string: string) {
    let encodedString = '';
    for (let i = 0; i < string.length; i++) {
        let charCodePointHex = string.charCodeAt(i).toString(16);
        encodedString += `\\u{${charCodePointHex}}`;
    }
    return encodedString;
}
Program: CWE-79
Project: CVE-2022-24746
Buggy source:
<?php declare(strict_types=1);

namespace Shopware\Core\Checkout\Cart\LineItemFactoryHandler;

use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Checkout\Cart\Price\Struct\PercentagePriceDefinition;
use Shopware\Core\System\SalesChannel\SalesChannelContext;

class PromotionLineItemFactory implements LineItemFactoryInterface
{
    public function supports(string $type): bool
    {
        return $type === LineItem::PROMOTION_LINE_ITEM_TYPE;
    }

    public function create(array $data, SalesChannelContext $context): LineItem
    {
        $uniqueKey = 'promotion-' . $data['referencedId'];
        $item = new LineItem($uniqueKey, LineItem::PROMOTION_LINE_ITEM_TYPE);
        $item->setLabel($uniqueKey);
        $item->setGood(false);

        // this is used to pass on the code for later usage
        $item->setReferencedId($data['referencedId']);

        // this is important to avoid any side effects when calculating the cart
        // a percentage of 0,00 will just do nothing
        $item->setPriceDefinition(new PercentagePriceDefinition(0));

        return $item;
    }

    public function update(LineItem $lineItem, array $data, SalesChannelContext $context): void
    {
        throw new \RuntimeException(sprintf('You cannot update a line item of type "%s"', $lineItem->getType()));
    }
}


Fixed version (ground truth):
<?php declare(strict_types=1);

namespace Shopware\Core\Checkout\Cart\LineItemFactoryHandler;

use Shopware\Core\Checkout\Cart\LineItem\LineItem;
use Shopware\Core\Checkout\Cart\Price\Struct\PercentagePriceDefinition;
use Shopware\Core\System\SalesChannel\SalesChannelContext;

class PromotionLineItemFactory implements LineItemFactoryInterface
{
    public function supports(string $type): bool
    {
        return $type === LineItem::PROMOTION_LINE_ITEM_TYPE;
    }

    public function create(array $data, SalesChannelContext $context): LineItem
    {
        $code = $data['referencedId'];

        $uniqueKey = 'promotion-' . $code;
        $item = new LineItem($uniqueKey, LineItem::PROMOTION_LINE_ITEM_TYPE);
        $item->setLabel($uniqueKey);
        $item->setGood(false);

        // this is used to pass on the code for later usage
        $item->setReferencedId($code);

        // this is important to avoid any side effects when calculating the cart
        // a percentage of 0,00 will just do nothing
        $item->setPriceDefinition(new PercentagePriceDefinition(0));

        return $item;
    }

    public function update(LineItem $lineItem, array $data, SalesChannelContext $context): void
    {
        throw new \RuntimeException(sprintf('You cannot update a line item of type "%s"', $lineItem->getType()));
    }
}
Program: CWE-79
Project: CVE-2022-25303
Buggy source:
{% if config.theme %}
    {% if config.theme == 'system' %}
        <style>
            @import "{{ cb_url('light-theme.css') }}" screen;
            @import "{{ cb_url('dark-theme.css') }}" screen and (prefers-color-scheme: dark);
        </style>
    {% else %}
        <link rel="stylesheet" href="{{ cb_url(config.theme + '-theme.css') }}"/>
    {% endif %}
{% else %}
    <link rel="stylesheet" href="{{ cb_url(('dark' if config.dark else 'light') + '-theme.css') }}"/>
{% endif %}
<link rel="stylesheet" href="{{ cb_url('main.css') }}">
<link rel="stylesheet" href="{{ cb_url('error.css') }}">
<style>{{ config.style }}</style>
<div>
    <h1>Error</h1>
    <p>
        {{ error_message|safe }}
    </p>
    <hr>
    <p>
    {% if blocked is defined %}
        <h4><a class="link" href="https://farside.link">{{ translation['continue-search'] }}</a></h4>
        Whoogle:
        <br>
        <a class="link-color" href="{{farside}}/whoogle/search?q={{query}}{{params}}">
            {{farside}}/whoogle/search?q={{query}}{{params}}
        </a>
        <br><br>
        Searx:
        <br>
        <a class="link-color" href="{{farside}}/searx/search?q={{query}}">
            {{farside}}/searx/search?q={{query}}
        </a>
        <hr>
    {% endif %}
    </p>
    <a class="link" href="home">Return Home</a>
</div>


Fixed version (ground truth):
{% if config.theme %}
    {% if config.theme == 'system' %}
        <style>
            @import "{{ cb_url('light-theme.css') }}" screen;
            @import "{{ cb_url('dark-theme.css') }}" screen and (prefers-color-scheme: dark);
        </style>
    {% else %}
        <link rel="stylesheet" href="{{ cb_url(config.theme + '-theme.css') }}"/>
    {% endif %}
{% else %}
    <link rel="stylesheet" href="{{ cb_url(('dark' if config.dark else 'light') + '-theme.css') }}"/>
{% endif %}
<link rel="stylesheet" href="{{ cb_url('main.css') }}">
<link rel="stylesheet" href="{{ cb_url('error.css') }}">
<style>{{ config.style }}</style>
<div>
    <h1>Error</h1>
    <p>
        {{ error_message }}
    </p>
    <hr>
    <p>
    {% if blocked is defined %}
        <h4><a class="link" href="https://farside.link">{{ translation['continue-search'] }}</a></h4>
        Whoogle:
        <br>
        <a class="link-color" href="{{farside}}/whoogle/search?q={{query}}{{params}}">
            {{farside}}/whoogle/search?q={{query}}{{params}}
        </a>
        <br><br>
        Searx:
        <br>
        <a class="link-color" href="{{farside}}/searx/search?q={{query}}">
            {{farside}}/searx/search?q={{query}}
        </a>
        <hr>
    {% endif %}
    </p>
    <a class="link" href="home">Return Home</a>
</div>
Program: CWE-79
Project: CVE-2022-25875
Buggy source:
<script>
	export let props = {
		foo: '"></div><script>alert(42)</' + 'script>',
		bar: "'></div><script>alert(42)</" + 'script>',
		['"></div><script>alert(42)</' + 'script>']: 'baz',
		qux: '&&&',
	};
</script>

<div {...props}></div>

Fixed version (ground truth):
<script>
	const safe = { foo: 'foo' };
	const unsafe = { toString: () => '"><script>alert(42)<\/script>' };

	export let props = {
		foo: '"></div><script>alert(42)</' + 'script>',
		bar: "'></div><script>alert(42)</" + 'script>',
		['"></div><script>alert(42)</' + 'script>']: 'baz',
		qux: '&&&',
		quux: unsafe
	};
</script>

<div {...props}></div>
<div {...safe} {unsafe}></div>
Program: CWE-79
Project: CVE-2022-27475
Buggy source:
<?php

class Util
{
    const DB_SERVER_ERROR = "Server error occurred. Please try again later.";

    public static function dateToday($plus)
    {
        $dateToday = date("Y-m-d");
        if ($plus != '0') {
            return date('Y-m-d', strtotime($dateToday . ' + ' . $plus . ' days'));
        }
        return date("Y-m-d");
    }

    public static function timestampNow()
    {
        return date("Y-m-d H:i:s");
    }

    public static function displayAlertV1($msg, $type)
    {
        return '<div class="alert alert-' . $type . ' alert-dismissible fade show" role="alert">
          ' . $msg . '
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>';
    }

    public static function displayAlertV2($message, $type)
    {
        return '<div class="alert alert-' . $type . ' alert-dismissible fade show" role="alert">
          <h4 class="alert-heading">' . $message["heading"] . '</h4>
          <p>' . $message["content"] . '</p><hr>
          <p class="mb-0">' . $message["footer"] . '</p>
        </div>';
    }
}


Fixed version (ground truth):
<?php

class Util
{
    const DB_SERVER_ERROR = "Server error occurred. Please try again later.";

    public static function dateToday($plus)
    {
        $dateToday = date("Y-m-d");
        if ($plus != '0') {
            return date('Y-m-d', strtotime($dateToday . ' + ' . $plus . ' days'));
        }
        return date("Y-m-d");
    }

    public static function timestampNow()
    {
        return date("Y-m-d H:i:s");
    }

    public static function displayAlertV1($msg, $type)
    {
        return '<div class="alert alert-' . $type . ' alert-dismissible fade show" role="alert">
          ' . $msg . '
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>';
    }

    public static function displayAlertV2($message, $type)
    {
        return '<div class="alert alert-' . $type . ' alert-dismissible fade show" role="alert">
          <h4 class="alert-heading">' . $message["heading"] . '</h4>
          <p>' . $message["content"] . '</p><hr>
          <p class="mb-0">' . $message["footer"] . '</p>
        </div>';
    }

    public static function sanitize_xss($value) 
    {
      return htmlspecialchars(strip_tags($value));
    }
      
  
}
Program: CWE-79
Project: CVE-2022-2777
Buggy source:
<?php

namespace MicroweberPackages\App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use GrahamCampbell\SecurityCore\Security;
use MicroweberPackages\Helper\HTMLClean;

class XSS
{
    public function handle(Request $request, Closure $next)
    {
        $input = $request->all();


        if ($request->isMethod('post') and !empty($input)) {
            $clean = new HTMLClean();
            array_walk_recursive($input, function (&$input) use ($clean) {
                if (is_string($input)) {
                    $input = $clean->clean($input);
                }
            });
        }


        $request->merge($input);
        return $next($request);
    }

}


Fixed version (ground truth):
<?php

namespace MicroweberPackages\App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use GrahamCampbell\SecurityCore\Security;
use MicroweberPackages\Helper\HTMLClean;

class XSS
{
    public function handle(Request $request, Closure $next)
    {
        $input = $request->all();


        if (($request->isMethod('post')  or $request->isMethod('patch')) and !empty($input)) {

            $clean = new HTMLClean();
            array_walk_recursive($input, function (&$input) use ($clean) {
                if (is_string($input)) {
                    $input = $clean->clean($input);
                }
            });
        }

        $request->merge($input);
        return $next($request);
    }

}
Program: CWE-79
Project: CVE-2022-2871
Buggy source:
# Security Policy

## Reporting a Vulnerability

Please share privately the details of your security vulnerability by email to:
[Contact Info](support@notrinos.com)  
Or open an issue at [our forum](https://forums.notrinos.com/t/bugs-problems)

Make sure to include as much information as possible, with the detailed steps to reproduce the problem,
the versions that are affected, the expected results and actual results, and any other information that
might help us react faster and more efficiently.

## Vulnerability disclosure policy

Due to the nature of open source, security vulnerability fixes are public. Patches for minor issues are committed directly to stable repository branch, to be published with next planned minor release. Confirmed serious vulnerabilities are fixed and published as soon as possible, together with new emergency minor release.


Fixed version (ground truth):
# Security Policy

## Reporting a Vulnerability

Please share privately the details of your security vulnerability by email to: support@notrinos.com  
Or open an issue at [our forum](https://forums.notrinos.com/t/bugs-problems)

Make sure to include as much information as possible, with the detailed steps to reproduce the problem,
the versions that are affected, the expected results and actual results, and any other information that
might help us react faster and more efficiently.

## Vulnerability disclosure policy

Due to the nature of open source, security vulnerability fixes are public. Patches for minor issues are committed directly to stable repository branch, to be published with next planned minor release. Confirmed serious vulnerabilities are fixed and published as soon as possible, together with new emergency minor release.
Program: CWE-79
Project: CVE-2022-29532
Buggy source:
<?php
if (isset($field['raw'])) {
    $string = $field['raw'];
} else {
    $value = Hash::extract($data, $field['path']);
    $string = empty($value[0]) ? '' : h($value[0]);
}
if (!empty($field['url'])) {
    if (!empty($field['url_vars'])) {
        if (!is_array($field['url_vars'])) {
            $field['url_vars'] = [$field['url_vars']];
        }
        foreach ($field['url_vars'] as $k => $path) {
            $field['url'] = str_replace('{{' . $k . '}}', Hash::extract($data, $path)[0], $field['url']);
        }
    }
    $string = sprintf(
        '<a href="%s">%s</a>',
        h($field['url']),
        $string
    );
}
echo $string;


Fixed version (ground truth):
<?php
if (isset($field['raw'])) {
    $string = $field['raw'];
} else {
    $value = Hash::extract($data, $field['path']);
    $string = empty($value[0]) ? '' : h($value[0]);
}
if (!empty($field['url'])) {
    if (!empty($field['url_vars'])) {
        if (!is_array($field['url_vars'])) {
            $field['url_vars'] = [$field['url_vars']];
        }
        foreach ($field['url_vars'] as $k => $path) {
            $field['url'] = str_replace('{{' . $k . '}}', Hash::extract($data, $path)[0], $field['url']);
            $temp = explode(':', $field['url']);
            if (!in_array(strtolower($temp[0]), ['http', 'https'])) {
                $field['url'] = '#';
                $string = 'Malformed URL - invalid protocol (' . h($temp[0]) . ':)';
            }
        }
    }
    $string = sprintf(
        '<a href="%s">%s</a>',
        h($field['url']),
        $string
    );
}
echo $string;
Program: CWE-79
Project: CVE-2022-31049
Buggy source:
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" data-namespace-typo3-fluid="true">
<f:layout name="SystemEmail" />
<f:section name="Main">
    <f:spaceless>
        <f:variable name="recoveryLink">
            <f:link.external uri="{url}" target="_blank"><f:translate key="password_recovery_link" extensionName="felogin"/></f:link.external>
        </f:variable>

        {f:translate(
        key: 'forgot_validate_reset_password_html',
        extensionName: 'felogin',
        arguments: '{ 0: receiverName, 1: recoveryLink, 2: validUntil }'
        ) -> f:format.html()}
    </f:spaceless>
</f:section>
</html>


Fixed version (ground truth):
<html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" data-namespace-typo3-fluid="true">
<f:layout name="SystemEmail" />
<f:section name="Main">
    <f:spaceless>
        <f:variable name="recoveryLink">
            <f:link.external uri="{url}" target="_blank"><f:translate key="password_recovery_link" extensionName="felogin"/></f:link.external>
        </f:variable>

        {f:translate(
        key: 'forgot_validate_reset_password_html',
        extensionName: 'felogin',
        arguments: '{ 0: "{receiverName -> f:format.htmlspecialchars()}", 1: recoveryLink, 2: validUntil }'
        ) -> f:format.html()}
    </f:spaceless>
</f:section>
</html>