<?

/*
 * This file is part of the Science-ation project
 * Science-ation Website: https://science-ation.ca
 *
 * This file was part of the 'Science Fair In A Box' project
 *
 *
 * Copyright (C) 2005 Sci-Tech Ontario Inc <info@scitechontario.org>
 * Copyright (C) 2005 James Grant <james@lightbox.org>
 * Copyright (C) 2024 AlgoLibre Inc. <science-ation@algolibre.io>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation, version 2.
 *
 * 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
 *  General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

require_once ('./data/config.inc.php');

$dsn = "mysql:host=db;dbname=$DBNAME;charset=utf8mb4";
$pdo = new PDO($dsn, $DBUSER, $DBPASS);

function use_hash_passwords() {
    global $pdo;

    $q = $pdo->prepare("ALTER TABLE `users` MODIFY COLUMN `password` varchar(60)");
    $q->execute();
    $q = $pdo->prepare("ALTER TABLE `users` MODIFY COLUMN `oldpassword` varchar(60)");
    $q->execute();

    $q = $pdo->prepare("SELECT `id`, `password`, `oldpassword` FROM `users`");
    $q->execute();

    while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
        $id = $r['id'];

        $password=$r['password'];
        $oldpassword=$r['oldpassword'];

        if (_password_not_hashed($password)) {
            $password = password_hash($r['password'], PASSWORD_BCRYPT);
        }
        
        if (_password_not_hashed($oldpassword)) {
            $oldpassword = password_hash($r['oldpassword'], PASSWORD_BCRYPT);
        }
        
        $stmt = $pdo->prepare("UPDATE `users` SET `password`=?, `oldpassword`=? WHERE `id`=?");
        $stmt->execute([$password, $oldpassword, $id]);

        printf("Done: %d\n", $id);
    }
}

function _password_not_hashed($password) {
    return (password_get_info($password)['algo'] == 0);
}


function theme_config() {
    global $pdo;

    $q = $pdo->prepare("UPDATE `config` SET `val`='science_ation' WHERE `var`='theme'");
    $q->execute();

    $q = $pdo->prepare("UPDATE `config` SET `val`='icons_science_ation' WHERE `var`='theme_icons'");
    $q->execute();
}

function path_config() {
    global $pdo;

    $q = $pdo->prepare("UPDATE `config` SET `val`='' WHERE `var`='SFIABDIRECTORY'");
    $q->execute();
}

use_hash_passwords();
theme_config();
path_config();

?>