public static function retrieveOrCreateByTagAndTaggable($tag_id, $taggable_id, $taggable_model)
 {
     $tagging = self::retrieveByTagAndTaggable($tag_id, $taggable_id, $taggable_model);
     if (!$tagging) {
         $tagging = new Tagging();
         $tagging->setTagId($tag_id);
         $tagging->setTaggableId($taggable_id);
         $tagging->setTaggableModel($taggable_model);
     }
     return $tagging;
 }
$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();
foreach (array(3, 4, 5) as $tag_id) {
    $tagging = new Tagging();
    $tagging->setTaggableModel('OppAtto');
    $tagging->setTaggableId($obj->getId());
    $tagging->setTagId($tag_id);
    $tagging->save();
    $tagging_ar[] = $tagging;
}
$related_news = getRelatedNews($obj);
$n_related_news = count($related_news);
$t->ok($n_related_news == 10, 'Ten news related to the act (three with tag_id not null)');
dumpNews($t, "news related to the act", $related_news);
// make the user monitor one of the tag assigned to the act
$t->diag('Have the test user monitor the test act');
if ($obj->isMonitoredByUser($test_user_id)) {
    $user_is_monitoring = true;
} else {
    $user_is_monitoring = false;
}
 /**
  * Tags saving logic, runned after the object himself has been saved
  *
  * @param      BaseObject  $object
  */
 public function postSave(BaseObject $object)
 {
     $tags = self::get_tags($object);
     $removed_tags = self::get_removed_tags($object);
     // save new tags
     foreach ($tags as $tagname) {
         $tag = TagPeer::retrieveOrCreateByTagName($tagname);
         $tag->save();
         $tagging = new Tagging();
         $tagging->setTagId($tag->getId());
         $tagging->setTaggableId($object->getPrimaryKey());
         $tagging->setTaggableModel(get_class($object));
         $tagging->save();
     }
     // remove removed tags
     $c = new Criteria();
     $c->add(TagPeer::NAME, $removed_tags, Criteria::IN);
     $rs = TagPeer::doSelectRS($c);
     $removed_tag_ids = array();
     while ($rs->next()) {
         $removed_tag_ids[] = $rs->getInt(1);
     }
     $c = new Criteria();
     $c->add(TaggingPeer::TAG_ID, $removed_tag_ids, Criteria::IN);
     $c->add(TaggingPeer::TAGGABLE_ID, $object->getPrimaryKey());
     $c->add(TaggingPeer::TAGGABLE_MODEL, get_class($object));
     TaggingPeer::doDelete($c);
     $tags = array_merge(self::get_tags($object), $this->getSavedTags($object));
     self::set_saved_tags($object, $tags);
     self::clear_tags($object);
     self::clear_removed_tags($object);
 }
/**
 * 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));
}
    $sfTag = TagPeer::retrieveOrCreateByTagname("{$teseo_tag_tipo_name}:{$teseo_tag_id}={$teseo_tag_value}");
    $sfTag->save();
    foreach ($teseo_tag->getOppTeseoHasTeseotts() as $teseo_tt) {
        $tt_id = $teseo_tt->getOppTeseott()->getId();
        $tt_denominazione = $teseo_tt->getOppTeseott()->getDenominazione();
        echo "  TT" . $tt_id . ": " . $tt_denominazione . "\n";
        $tt = OppTagHasTtPeer::retrieveByPK($sfTag->getId(), $tt_id);
        if (!$tt instanceof OppTagHasTt) {
            $tt = new OppTagHasTt();
        }
        $tt->setTagId($sfTag->getId());
        $tt->setTeseoTtId($tt_id);
        $tt->save();
    }
    foreach ($teseo_tag->getOppAttoHasTeseos() as $atto_tag) {
        if (!$atto_tag->getOppAtto() instanceof OppAtto) {
            continue;
        }
        $atto_id = $atto_tag->getOppAtto()->getId();
        $taggable_model = 'OppAtto';
        echo "   A" . $atto_id . ": " . substr($atto_tag->getOppAtto()->getTitolo(), 0, 80) . "\n";
        $atto_has_tag = TaggingPeer::retrieveByTagAndTaggable($sfTag->getId(), $atto_id, $taggable_model);
        if (!$atto_has_tag instanceof Tagging) {
            $atto_has_tag = new Tagging();
        }
        $atto_has_tag->setTagId($sfTag->getId());
        $atto_has_tag->setTaggableId($atto_id);
        $atto_has_tag->setTaggableModel($taggable_model);
        $atto_has_tag->save();
    }
}
     $results = TaggingPeer::doSelect($c);
     $number = $number + count($results);
     foreach ($results as $rs) {
         for ($x = 0; $x <= 1; $x++) {
             if ($macrotags[$k][$x] != 0) {
                 $c = new Criteria();
                 $c->add(TaggingPeer::TAG_ID, $macrotags[$k][$x]);
                 $c->add(TaggingPeer::TAGGABLE_ID, $rs->getTaggableId());
                 $c->add(TaggingPeer::TAGGABLE_MODEL, $rs->getTaggableModel());
                 $r = TaggingPeer::doSelectOne($c);
                 if (!$r) {
                     $t = TagPeer::retrieveByPk($macrotags[$k][$x]);
                     if ($t) {
                         $insert = new Tagging();
                         $insert->setTagId($macrotags[$k][$x]);
                         $insert->setTaggableId($rs->getTaggableId());
                         $insert->setTaggableModel($rs->getTaggableModel());
                         $insert->save();
                         echo "++++++++++++++++++++++++++++++++++++++++++ aggiunto " . $macrotags[$k][$x] . " - " . $t->getTripleValue() . " in " . $rs->getTaggableId() . "\n";
                         $number_tagging_ok = $number_tagging_ok + 1;
                     } else {
                         echo "!!!! non esiste Macrotags con id=" . $macrotags[$k][$x] . "\n";
                     }
                 } else {
                     echo "NON aggiungo, già esiste! \n";
                     $number_tagging_no = $number_tagging_no + 1;
                 }
             }
         }
     }
 }