#!/usr/bin/php
<?php
/**
 * phpaga
 *
 * Migrate person's pictures to the "relation associated files".
 *
 * Remember: It never hurts to make a backup of both data and files
 * first.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: migrate_personpictures.php 828 2007-07-26 19:28:32Z florian $
 *
 * Copyright (c) 2007 Florian Lanthaler <florian@phpaga.net>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *
 *    * Neither the name of Florian Lanthaler nor the names of his
 *      contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

   /* Database system; currently supported values are
    *	pgsql : PostgreSQL
    *	mysql : MySQL
    */
define('PHPAGA_DB_SYSTEM', 'pgsql');

/* Name or IP address of the host the database server is running on */
define('PHPAGA_DB_HOST', '');

/* Database name */
define('PHPAGA_DB_NAME', 'dbname');

/* Database username */
define('PHPAGA_DB_LOGIN', 'dbuser');

/* Database password */
define('PHPAGA_DB_PASSWD', 'dbpasswd');

/* Full absolute path to phpaga's base directory with trailing slash.
 * The path should be recognized and set automatically, but if you run
 * into any problems, comment it out, uncomment the next line below,
 * and set the path manually. */

define('PHPAGA_BASEPATH', preg_replace("/tools$/i", "", dirname(__FILE__)));
#define('PHPAGA_BASEPATH', '/home/webs/phpaga/');

define("PHPAGA_FILEPATH", PHPAGA_BASEPATH."files/");


/* -------------------------------------------------- */
/* No neeed to touch anything below
/* -------------------------------------------------- */


function _msg($text = null, $err = false)
{
    if ($err)
        $pref = "ERROR: ";
    else
        $pref = "";

    print(sprintf("-> %s%s\n", $pref, $text));
}

if (!defined("PHPAGA_BASEPATH")) {
    _msg("\nUnable to proceed.\nPlease define PHPAGA_BASEPATH in this file.\n", true);
    exit;
}

include("DB.php");

$db = DB::connect(sprintf("%s://%s:%s@%s/%s",
                          PHPAGA_DB_SYSTEM,
                          PHPAGA_DB_LOGIN,
                          PHPAGA_DB_PASSWD,
                          PHPAGA_DB_HOST,
                          PHPAGA_DB_NAME));

if (DB::isError($db)) {
    die(sprintf("Unable to connect to the database:\n%s\n", $db->getDebugInfo()));
}

_msg("Connected");

$db->setFetchMode(DB_FETCHMODE_ASSOC);

$result = $db->query("select pe_id, pe_pe_id, pe_lastname, pe_firstname, pe_fotoname from persons where pe_fotoname is not null");

if (DB::isError($result)) {
    die(_msg(sprintf("Unable to fetch persons:\n%s", $result->getDebugInfo()), true));
}

if (PHPAGA_DB_SYSTEM == "pgsql") {
    $db->query("BEGIN TRANSACTION");
}

$status = true;

while (($r = $result->fetchRow()) && $status) {

    $statmsg = null;

    _msg(sprintf("Converting picture for person: (%s) %s %s", $r['pe_id'], $r["pe_lastname"], $r["pe_firstname"]));

    if (!strlen($r['pe_pe_id']))
        $r['pe_pe_id'] = (int)$r['pe_peid'];

    $fileinfo = array("pe_id" => $r['pe_pe_id'],
                      "file_original_name" => $r['pe_fotoname'],
                      "file_local_name" => $r['pe_fotoname'],
                      "file_rel_type" => 50, // PHPAGA_RELTYPE_PERSON
                      "file_rel_id" => $r['pe_id'],
                      "file_mimetype" => null);

    $dest_dir = PHPAGA_FILEPATH.$fileinfo["file_rel_type"]."/".$fileinfo["file_rel_id"];

    $source = PHPAGA_BASEPATH."pictures/".$r['pe_fotoname'];
    $destination = $dest_dir.'/'.$r['pe_fotoname'];

    if (!file_exists($source)) {
        _msg(sprintf("%s: This file does not exist. Skipping...", $source), true);
    } else {

        if (!is_dir(PHPAGA_FILEPATH))
            $statmsg = sprintf(_("%s: The directory does not exist"), PHPAGA_FILEPATH);

        elseif (!is_dir(PHPAGA_FILEPATH.$fileinfo["file_rel_type"]) && !mkdir(PHPAGA_FILEPATH.$fileinfo["file_rel_type"]))
            $statmsg = sprintf(_("%s: The directory does not exist and can't be created"), PHPAGA_FILEPATH.$fileinfo["file_rel_type"]);

        elseif (!is_dir($dest_dir) && !mkdir($dest_dir))
            $statmsg = sprintf(_("%s: The directory does not exist and can't be created"), $dest_dir);

        elseif (!is_writable($dest_dir))
            $statmsg = sprintf(_("%s: The directory is not writable"), $dest_dir);

        if (strlen($statmsg)) {
            _msg($statmsg, true);
            $status = false;
            exit;
        }

        if (!rename($source, $destination)) {
            $status = false;
            _msg(sprintf("Unable to move file from %s to %s", $source, $destination), true);
            break;
        }

        $fileinfo['file_id'] = $db->nextId("files_file_id");
        $fileinfo['file_mimetype'] = mime_content_type($source);

        $xres = $db->autoExecute("files", $fileinfo, DB_AUTOQUERY_INSERT);

        if (DB::isError($xres)) {
            $status = false;
            _msg("An error has occurred - unable to save the new file relationship.", true);
        } else {

            $fields = array("pe_fotoname" => null);

            $qi = $db->autoExecute("persons", $fields, DB_AUTOQUERY_UPDATE,
                                   "pe_id = ".$db->quoteSmart($r['pe_id']));

            if (DB::isError($qi))
            {
                $status = false;
                _msg("Unable to reset pe_fotoname to NULL", true);
                break;
            } else
                _msg("OK");
        }
    }

}

if (!$status) {
    _msg("Conversion aborted", true);
}

if (PHPAGA_DB_SYSTEM == "pgsql") {
    if ($status)
        $db->query("COMMIT TRANSACTION");
    else
    {
        $roll = $db->query("ROLLBACK");

        if (DB::isError($roll)) {
            _msg("Ugh - unable to ROLLBACK the transaction, this looks ugly. I go hide.", true);
        }
        else {
            _msg("ROLLBACK successful");
        }
    }
}


if ($status) {
    _msg("Done");
}

?>