<?php
// Copyright 1999-2014. Parallels IP Holdings GmbH. All Rights Reserved.
// detect VE before db_connect();
require_once('api-common/cu.php');


function correctNotes()
{
    require_once('class.Note.php');

    $defaults = Note::getDefaultNotes();

    $phpsettingsBroker = Db_Table_Broker::get('PhpSettings');
    $select = $phpsettingsBroker->select()->from($phpsettingsBroker, array('id', 'noteId'))->where("noteId IS NOT NULL AND noteId > 0 AND noteId <= 26");
    foreach ($phpsettingsBroker->fetchAll($select) as $phpsettingRow) {
        $notesBroker = Db_Table_Broker::get('Notes');
        $select = $notesBroker->select()->from($notesBroker, 'text')->where("id = ?", $phpsettingRow->noteId);
        $noteRow = $notesBroker->fetchRow($select);
        

        try {
            $phpsettingsBroker->getAdapter()->beginTransaction();

            // reinsert at the end of the Notes table
            $insertRes = $notesBroker->insert(array(
                'text' => $noteRow->text
            ));

            // update reference in PhpSettings table
            $where = $phpsettingsBroker->getAdapter()->quoteInto('id = ?', $phpsettingRow->id);
            $phpsettingsBroker->update(array(
                'noteId' => $insertRes
            ), $where);

            // update row in the Notes table by default text
            foreach ($defaults as $id => $text) {
                if ($id != $phpsettingRow->noteId) {
                    continue;
                }

                $where = $notesBroker->getAdapter()->quoteInto('id = ?', $phpsettingRow->noteId);
                $notesBroker->update(array(
                    'text' => $text
                ), $where);

                break;
            }

            $phpsettingsBroker->getAdapter()->commit();
        } catch (Exception $e) {
            $phpsettingsBroker->getAdapter()->rollBack();
            throw $e;
        }
    }
}

/**
 * Disable interfaces in postinstall script
 * http://bugs.plesk.ru/show_bug.cgi?id=142535
 */
require_once('interfaces/InterfacesManager.php');
InterfacesManager::disable();

/*************************************************/

cu::initCLI();
$cu = new cu();

try {
    correctNotes();

} catch (Exception $e) {
    cu::print_stderr("Error: " . $e->getMessage());
    cu::cuExit(1);
}

cu::cuExit(0);
