<?php
/*****************************************************************************
 * migrate_thumbs.php
 * Migrates old-style thumbnails (meta) to new table.
 *
 * Kabuki CMS (C) 2013-2015, Aaron van Geffen
 *****************************************************************************/

// Include the project's configuration.
require_once 'config.php';

// Set up the autoloader.
require_once 'vendor/autoload.php';

// Initialise the database.
$db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
Registry::set('db', $db);

// Do some authentication checks.
Session::start();
Registry::set('user', Authentication::isLoggedIn() ? Member::fromId($_SESSION['user_id']) : new Guest());


$res = $db->query('
	SELECT id_asset, variable, value
	FROM assets_meta
	WHERE variable LIKE {string:thumbs}',
	['thumbs' => 'thumb_%']);

while ($row = $db->fetch_assoc($res))
{
	if (!preg_match('~^thumb_(?<width>\d+)x(?<height>\d+)(?:_(?<mode>c[best]?))?$~', $row['variable'], $match))
		continue;

	echo 'Migrating ... ', $row['value'], '(#', $row['id_asset'], ")\r";

	$db->insert('replace', 'assets_thumbs', [
		'id_asset' => 'int',
		'width' => 'int',
		'height' => 'int',
		'mode' => 'string-3',
		'filename' => 'string-255',
	], [
		'id_asset' => $row['id_asset'],
		'width' => $match['width'],
		'height' => $match['height'],
		'mode' => $match['mode'] ?? '',
		'filename' => $row['value'],
	]);
}

echo "\nDone\n";