$firma->setOppCarica($car);
$firma->setOppAtto($obj);
$firma->setData($obj->getDataPres());
$firma->save();
$pol_related_news = getRelatedNews($pol);
$n_pol_related_news = count($pol_related_news);
$t->ok($n_pol_related_news == 3, 'Three news related to the politician');
dumpNews($t, "news related to the politician", $pol_related_news);
$related_news = getRelatedNews($obj);
$n_related_news = count($related_news);
$t->ok($n_related_news == 5, 'Five news related to the act (no new news)');
dumpNews($t, "news related to the act", $related_news);
$t->diag('Get a site');
$sede = OppSedePeer::retrieveByPK(11);
$t->diag('Add an intervention on the act by the politician');
$int = new OppIntervento();
$int->setData('2008-11-20');
$int->setOppCarica($car);
$int->setOppSede($sede);
$int->setOppAtto($obj);
$int->save();
$pol_related_news = getRelatedNews($pol);
$n_pol_related_news = count($pol_related_news);
$t->ok($n_pol_related_news == 4, 'Four news related to the politician');
dumpNews($t, "news related to the politician", $pol_related_news);
$related_news = getRelatedNews($obj);
$n_related_news = count($related_news);
$t->ok($n_related_news == 7, 'Seven news related to the act (two more, detailed and group)');
dumpNews($t, "news related to the act", $related_news);
$t->diag('Add three different tags to the object');
$tagging_ar = array();
define('SF_APP', 'fe');
define('SF_ENVIRONMENT', 'test');
define('SF_DEBUG', true);
include dirname(__FILE__) . '/../bootstrap/unit.php';
require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
sfContext::getInstance();
$t = new lime_test(2, new lime_output_color());
$t->diag('unit test to verify the mechanisms to upgrade the opp_atto.n_interventi field');
$t->diag('Tests beginning');
$atto_id = 12066;
$carica_id = 801;
$atto = OppAttoPeer::retrieveByPK($atto_id);
$n_interventi = $atto->getNInterventi();
$t->diag("L'atto {$atto_id} ha {$n_interventi} interventi");
$t->diag("Creato nuovo un intervento per la carica {$carica_id}");
$int_new = new OppIntervento();
$int_new->setAttoId($atto_id);
$int_new->setCaricaId($carica_id);
$int_new->setTipologia('Assemblea');
$int_new->setSedeId('36');
$int_new->setData('2009-02-06');
$int_new->setUrl('http://pippo.it');
$int_new->setNumero(2);
$int_new->save();
$atto = OppAttoPeer::retrieveByPK($atto_id);
$t->ok($atto->getNInterventi() == $n_interventi + 1, "L'atto ha ora un intervento in più (" . $atto->getNInterventi() . ")");
$t->diag("Rimosso l'intervento");
$int_new->delete();
$atto = OppAttoPeer::retrieveByPK($atto_id);
$t->ok($atto->getNInterventi() == $n_interventi, "L'atto ha ora di nuovo lo stesso n. di interventi (" . $atto->getNInterventi() . ")");
/**
 * Processa il file specificato in --yaml-file per l'upgrade di un atto
 *
 */
function run_opp_update_ddl_from_yaml($task, $args, $options)
{
    static $loaded;
    // load application context
    if (!$loaded) {
        _loader();
    }
    $dry_run = false;
    if (array_key_exists('dry-run', $options)) {
        $dry_run = true;
    }
    if (array_key_exists('yaml-file', $options)) {
        $yaml_file = strtolower($options['yaml-file']);
    } else {
        throw new Exception("Specificare il file contenente i dati dei ddl con l'opzione --yaml-file=FILE_COMPLETE_PATH");
    }
    echo "memory usage: " . memory_get_usage() . "\n";
    $start_time = time();
    $msg = sprintf("upgrade ddl da {$yaml_file}\n");
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
    if (file_exists($yaml_file)) {
        $up_ddl = sfYaml::Load($yaml_file);
    } else {
        throw new Exception("Impossibile trovare il file {$yaml_file}");
    }
    $con = Propel::getConnection(OppAttoPeer::DATABASE_NAME);
    $opp_id = $up_ddl['opp_id'];
    $atto = OppAttoPeer::retrieveByPK($opp_id);
    $parl_id = $up_ddl['parl_id'];
    if (is_null($atto->getParlamentoId()) || $atto->getParlamentoId() != $parl_id) {
        $atto->setParlamentoId($parl_id);
    }
    $key = 'titolo';
    if (array_key_exists($key, $up_ddl)) {
        $titolo = $up_ddl['titolo'];
        $atto->setTitolo($titolo);
        print "{$key}\n";
        print str_repeat("=", strlen($key)) . "\n";
        print "{$titolo}\n";
        print "\n";
    }
    # firme
    $firmatari = array('P' => 'primi_firmatari', 'R' => 'relatori', 'C' => 'co_firmatari');
    foreach ($firmatari as $tipo_firma => $key) {
        if (array_key_exists($key, $up_ddl) && !is_null($up_ddl[$key])) {
            print "{$key}\n";
            print str_repeat("=", strlen($key)) . "\n";
            foreach ($up_ddl[$key] as $id => $signature_data) {
                $ca = new OppCaricaHasAtto();
                $ca->setAttoId($opp_id);
                $ca->setCaricaId($id);
                $ca->setTipo($tipo_firma);
                $name = $signature_data['nome'];
                $signature_date = $signature_data['data_firma'];
                $ca->setData($signature_date);
                $ca->save();
                print "  {$name} ({$id}) il {$signature_date}\n";
            }
            print "\n";
        }
    }
    # commissioni
    $commissioni = array('referente', 'consultiva');
    foreach ($commissioni as $tipo_commissione) {
        if (array_key_exists($tipo_commissione, $up_ddl)) {
            print "{$tipo_commissione}\n";
            print str_repeat("=", strlen($tipo_commissione)) . "\n";
            foreach ($up_ddl[$tipo_commissione] as $id => $name) {
                $as = new OppAttoHasSede();
                $as->setAttoId($opp_id);
                $as->setSedeId($id);
                $as->setTipo(ucfirst($tipo_commissione));
                $as->save();
                print "  {$name} ({$id})\n";
            }
            print "\n";
        }
    }
    # tagging
    if (array_key_exists('tags', $up_ddl)) {
        print "tagging\n";
        print "=======\n";
        foreach ($up_ddl['tags'] as $tag_id => $name) {
            $t = new Tagging();
            $t->setTaggableModel('OppAtto');
            $t->setTaggableId($opp_id);
            $t->setTagId($tag_id);
            $t->save();
            print "  {$name} ({$tag_id})\n";
        }
        print "\n";
    }
    # documenti
    if (array_key_exists('documenti', $up_ddl)) {
        print "documenti\n";
        print "=========\n";
        foreach ($up_ddl['documenti'] as $cnt => $doc) {
            if (!array_key_exists('titolo', $doc)) {
                $doc['titolo'] = "Testo della Proposta di Legge";
            }
            $d = new OppDocumento();
            $d->setAttoId($opp_id);
            $d->setTitolo($doc['titolo']);
            $d->setUrlPdf($doc['url_pdf']);
            $d->setUrlTesto($doc['url_testo']);
            printf("titolo: %s\n", $doc['titolo']);
            printf("  pdf:  %s\n", $doc['url_pdf']);
            printf("  html: %s\n", $doc['url_testo']);
            if (file_exists($doc['file_testo'])) {
                $doc_txt = file_get_contents($doc['file_testo']);
                $d->setTesto($doc_txt);
                printf("  text: %s\n", $doc['file_testo']);
            }
            $d->save();
        }
        print "\n";
    }
    #pred e succ
    if (array_key_exists('pred_id', $up_ddl)) {
        $atto->setPred($up_ddl['pred_id']);
        printf(" pred: %d\n\n", $up_ddl['pred_id']);
    }
    if (array_key_exists('succ_id', $up_ddl)) {
        $atto->setSucc($up_ddl['succ_id']);
        printf(" succ: %d\n\n", $up_ddl['succ_id']);
    }
    # iter
    if (array_key_exists('iter', $up_ddl)) {
        print "iter\n";
        print "====\n";
        foreach ($up_ddl['iter'] as $id => $details) {
            $ai = new OppAttoHasIter();
            $ai->setAttoId($opp_id);
            $ai->setIterId($id);
            $ai->setData($details['data_pres']);
            $ai->save();
            printf("  %s (%s) - %s\n", $details['fase'], $id, $details['data_pres']);
        }
        print "\n";
    }
    # relazioni
    if (array_key_exists('relazioni', $up_ddl)) {
        print "relazioni\n";
        print "=========\n";
        foreach ($up_ddl['relazioni'] as $key => $details) {
            $r = new OppRelazioneAtto();
            $r->setAttoFromId($details['from_id']);
            $r->setAttoToId($details['to_id']);
            $r->setTipoRelazioneId($details['tipo_id']);
            $r->save();
            printf("  from: %s to: %s - %s (%s)\n", $details['from_id'], $details['to_id'], $details['tipo_relazione'], $details['tipo_id']);
        }
        print "\n";
    }
    # trattazione (esiti, sedute e interventi)
    $tipi_commissione = array('primaria' => 'Primaria', 'consultiva' => 'Consultiva', 'assemblea' => 'Aula');
    foreach ($tipi_commissione as $key => $tipo_commissione) {
        $trattazione_key = "trattazione_{$key}";
        if (array_key_exists('trattazioni', $up_ddl)) {
            print "trattazione {$tipo_commissione}\n";
            print "============" . str_repeat("=", strlen($tipo_commissione)) . "\n";
            foreach ($up_ddl['trattazioni'][$trattazione_key] as $seduta_id => $details) {
                list($seduta, $id) = explode("_", $seduta_id);
                $es = new OppEsitoSeduta();
                $es->setAttoId($opp_id);
                $es->setSedeId($details['comm_id']);
                $es->setData($details['date']);
                $es->setEsito($details['esito']);
                $es->setTipologia($details['comm_type']);
                $es->save();
                print "  seduta {$id}\n";
                printf("    %s - %s: %s\n", $details['date'], $details['comm_type'], $details['comm_id']);
                printf("    esito: %s\n", $details['esito']);
                printf("    %d interventi\n", count($details['interventi']));
                foreach ($details['interventi'] as $carica_id => $i_details) {
                    try {
                        $con->begin();
                        # cancella tutti i record con interventi di carica su atto, in sede e data
                        $c = OppInterventoPeer::criterionByAttoCaricaSedeData($opp_id, $carica_id, $details['comm_id'], $details['date']);
                        $deleted = OppInterventoPeer::doDelete($c, $con);
                        printf("      trovati e rimossi %d record\n", $deleted);
                        # riscrive un solo record, con tutte le url raggruppate
                        $i = new OppIntervento();
                        $i->setAttoId($opp_id);
                        $i->setCaricaId($carica_id);
                        $i->setData($details['date']);
                        $i->setSedeId($details['comm_id']);
                        $i->setTipologia($details['comm_type']);
                        $i->setUrl($i_details['urls']);
                        $i->save($con);
                        printf("      %s (%d) - %s\n", $i_details['cognome'], $carica_id, $i_details['urls']);
                        $con->commit();
                    } catch (PropelException $e) {
                        printf("problemi nell'aggiornamento interventi di %d su %d, sede %d, data %s\n%s\n", $carica_id, $opp_id, $details['comm_id'], $details['date'], $e->getMessage());
                        $con->rollback();
                    }
                }
            }
            print "\n";
        }
    }
    $atto->setDataAgg(time());
    $atto->save($con);
    # l'md5 viene ri-salvato dopo il salvataggio per evitare che atti inconsistenti siano
    # marcati come uguali
    $atto->setMd5($up_ddl['md5']);
    $atto->save();
    unset($atto);
    $msg = sprintf("fine elaborazione atto\n");
    echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true));
    $msg = sprintf(" [%4d sec] [%10d bytes]\n", time() - $start_time, memory_get_usage());
    echo pakeColor::colorize($msg, array('fg' => 'red', 'bold' => false));
}