<?php

require_once "config.php";
use newznab\db\Settings;
$s = new Sites();
$site = $s->get();
$patches = $s->getUnappliedPatches($site);
if (count($patches) == 0) {
    echo "Patchn : No patches required applying. At version " . $site->dbversion . "\n";
} else {
    echo "Patchn : Database at version " . $site->dbversion . "\n";
    foreach ($patches as $patch) {
        echo "Patchn : Executing patch " . basename($patch) . "\n";
        $db = new Settings();
        $rows = $db->query("select * from site");
        $dbData = file_get_contents($patch);
        //fix to remove BOM in UTF8 files
        $bom = pack("CCC", 0xef, 0xbb, 0xbf);
        if (0 == strncmp($dbData, $bom, 3)) {
            $dbData = substr($dbData, 3);
        }
        $queries = explode(";", $dbData);
        $queries = array_map("trim", $queries);
        foreach ($queries as $q) {
            if (strlen($q) > 0) {
                $db->exec($q);
            }
        }
    }
}
}
if ($page->site->rawretentiondays > 10) {
    $statusmsgs[] = addmsg("Binary header retention is set at " . $page->site->rawretentiondays . ". Having this value any higher than 2 can cause the database to grow very large.", "site-edit.php");
}
if ($page->site->newznabID == "") {
    $statusmsgs[] = addmsg("Newznab ID missing. You have not entered a newznab ID, and will not be using the latest matching regex's.", "http://www.newznab.com/chat.html", "exclamation");
}
//
// database patches uptodate
//
$s = new Sites();
if (!property_exists($page->site, "dbversion")) {
    $db = new DB();
    $db->queryInsert('INSERT INTO site (setting, value, updateddate ) VALUES (\'dbversion\', \'$Rev: 2248 $\', now())');
    $page->site = $s->get();
}
if (!preg_match("/\\d+/", $page->site->dbversion, $matches)) {
    $statusmsgs[] = addmsg("Bad database version. " . $page->site->dbversion . " cannot be parsed.", "http://newznab.readthedocs.org/en/latest/install/#updating", "exclamation");
}
$patches = $s->getUnappliedPatches($page->site);
$patches = array_map("basename", $patches);
if (count($patches) > 0) {
    $statusmsgs[] = addmsg("Database out of date. Ensure all database patches in /db/patch/0.2.3/ are ran by using the script misc/update_scripts/update_database_version.php<br/><small>" . implode("<br/>", $patches) . "</small>", "http://newznab.readthedocs.org/en/latest/install/#updating", "exclamation");
}
$page->smarty->assign('statusmsgs', $statusmsgs);
$page->content = $page->smarty->fetch('index.tpl');
$page->render();
function addmsg($msg, $url = "", $icon = "")
{
    return array('msg' => $msg, 'url' => $url, 'icon' => $icon == "" ? "information" : $icon);
}