Exemplo n.º 1
0
 /**
  * Tags saving logic, runned after the object himself has been saved
  *
  * @param      Doctrine_Event  $event
  */
 public function postSave(Doctrine_Event $event)
 {
     $object = $event->getInvoker();
     $added_tags = Taggable::get_tags($object);
     $removed_tags = array_keys(Taggable::get_removed_tags($object));
     sfContext::getInstance()->getLogger()->notice(print_r($added_tags, true) . print_r($removed_tags, true));
     // save new tags
     foreach ($added_tags as $tagname) {
         $tag = PluginTagTable::findOrCreateByTagName($tagname);
         $tag->save();
         $tagging = new Tagging();
         $tagging->tag_id = $tag->id;
         $tagging->taggable_id = $object->id;
         $tagging->taggable_model = get_class($object);
         $tagging->save();
     }
     if ($removed_tags) {
         $q = Doctrine_Query::create()->select('t.id')->from('Tag t INDEXBY t.id')->whereIn('t.name', $removed_tags);
         $removed_tag_ids = array_keys($q->execute(array(), Doctrine::HYDRATE_ARRAY));
         Doctrine::getTable('Tagging')->createQuery()->delete()->whereIn('tag_id', $removed_tag_ids)->addWhere('taggable_id = ?', $object->id)->addWhere('taggable_model = ?', get_class($object))->execute();
     }
     $tags = array_merge(Taggable::get_tags($object), $object->getSavedTags());
     Taggable::set_saved_tags($object, $tags);
     Taggable::clear_tags($object);
     Taggable::clear_removed_tags($object);
 }
Exemplo n.º 2
0
 function adminupdateAction()
 {
     $reportTab = new ReportTab();
     $data = array('campaign_id' => $this->getRequest()->getParam('campaign_id'), 'name' => $this->getRequest()->getParam('name'), 'description' => $this->getRequest()->getParam('description'));
     $reportTab->update($data, "id = " . $this->getRequest()->getParam('id'));
     $tagging = new Tagging();
     $where = $tagging->getAdapter()->quoteInto('report_tab_id = ?', $this->getRequest()->getParam('id'));
     $tagging->delete($where);
     $tags = $this->getRequest()->getParam('tags');
     foreach ($tags as $tag) {
         $data = array("report_tab_id" => $this->getRequest()->getParam('id'), "tag_id" => $tag);
         $tagging->save($data);
     }
     $this->_helper->redirector('adminindex', 'reporttab');
 }
Exemplo n.º 3
0
	public function setUp()
	{
		parent::setUp();
	
		$bar = new SearchBar;
		$bar->title = 'Bar Title';
		$bar->someOtherPrimary = 'The Primary';
		$bar->body = 'Lorem Ipsum';
		$bar->language = 'en';
		$bar->save();
	
		$foo = new SearchFoo;
		$foo->title = 'My Title';
		$foo->someOtherPrimary = 'other-primary';
		$foo->datePrimary = '2010-01-01';
		$foo->body = 'Somewhere over the rainbow goes, tudeludoedoe <bold>This is some text that has to be searched</bold>';
		$foo->barTitle = 'Bar Title';
		$foo->barSomeOtherPrimary = 'The Primary';
		$foo->identity = 'Keep Me As I am';
		$foo->language = 'en';
		$foo->save();
		
		$tag = new Tagging;
		$tag->title = 'Some Title';
		$tag->language = 'en';
		$tag->body = 'Some Very Long body.';
		$tag->save();
		$tag->tag('Gamma');
		$tag->tag('Alpha');
		$tag->tag('Beta');
		
		$tag = new Tagging;
		$tag->title = 'Some Other Title';
		$tag->language = 'en';
		$tag->body = 'Some Very short body.';
		$tag->save();
		$tag->tag('Aay');
		$tag->tag('Bee');
		$tag->tag('Cee');
	}
 public function addAction()
 {
     $data = $_POST;
     $destination = HTMLPurifier::getInstance()->purify(trim($data['path']));
     $form = $this->_getForm();
     $valid = $form->isValid($this->getRequest()->getPost());
     if (!$valid) {
         $taggingSession = new Zend_Session_Namespace('tagging');
         $taggingSession->post = serialize($_POST);
         $this->_helper->redirector->gotoUrl($destination . '#tagging-form');
     }
     // Currently, tags are allowed only on items.
     if (HTMLPurifier::getInstance()->purify(trim($data['record_type'])) != 'Item') {
         $this->_helper->flashMessenger(__('This record does not accept tags.'), 'warning');
         $this->_helper->redirector->gotoUrl($destination);
     }
     // Security check.
     $record = get_record_by_id(HTMLPurifier::getInstance()->purify(trim($data['record_type'])), (int) HTMLPurifier::getInstance()->purify(trim($data['record_id'])));
     if (!$record) {
         $this->_helper->flashMessenger(__('Record does not exist.'), 'warning');
         $this->_helper->redirector->gotoUrl($destination);
     }
     // Moderation or not.
     $user = current_user();
     // If the user can moderate, the proposition is automatically approved.
     $moderationRoles = unserialize(get_option('tagging_moderate_roles'));
     if (in_array($user->role, $moderationRoles)) {
         $status = 'approved';
     } else {
         if (empty($user)) {
             $user_id = 0;
             $requireModeration = (bool) get_option('tagging_public_require_moderation');
         } else {
             $user_id = $user->id;
             $requireModerationRoles = unserialize(get_option('tagging_require_moderation_roles'));
             $requireModeration = in_array($user->role, $requireModerationRoles);
         }
         $status = $requireModeration ? 'proposed' : 'allowed';
     }
     // Default values for tagging.
     $data['ip'] = $_SERVER['REMOTE_ADDR'];
     $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
     $data['status'] = $status;
     // Need getValue to run the filter.
     $userTagging = HTMLPurifier::getInstance()->purify(trim($form->getElement('tagging')->getValue()));
     $proposedTaggingsNames = explode(get_option('tag_delimiter'), $userTagging);
     // Prepare checks of existing tags.
     $db = get_db();
     $recordTags = $record->getTags();
     $recordTaggings = $db->getTable('Tagging')->findByRecord($record);
     $recordTagsNames = $this->_getTagsNames($recordTags);
     $recordTaggingsNames = $this->_getTagsNames($recordTaggings);
     // There is one tagging by tag to simplify management.
     $tagsToAdd = array();
     $approvedExistingTags = array();
     foreach ($proposedTaggingsNames as $proposedTag) {
         $data['name'] = $proposedTag;
         $tagging = new Tagging();
         $tagging->user_id = $user_id;
         $tagging->setArray($data);
         $sanitizedName = $tagging->sanitizeName();
         // Check the quality of tag.
         if (!$sanitizedName) {
             continue;
         }
         // Check if this tagging is not a duplicate.
         if (in_array($sanitizedName, $tagsToAdd)) {
             continue;
         }
         // Check if this tagging is not already set.
         if (in_array($sanitizedName, $recordTagsNames)) {
             continue;
         }
         // Check size of a tag.
         if (strlen($sanitizedName) > get_option('tagging_max_length_tag')) {
             $this->_helper->flashMessenger(__('Individual tags can\'t be longer than %d characters.', get_option('tagging_max_length_tag')), 'error');
             continue;
         }
         // Check if this tagging is not already saved.
         if (in_array($sanitizedName, $recordTaggingsNames)) {
             $existingTagging = $recordTaggings[array_search($sanitizedName, $recordTaggingsNames)];
             // Check status.
             // Normally, an existing approved tagging is already an item tag.
             if ($tagging->status == 'approved') {
                 $existingTagging->status = 'approved';
                 try {
                     $existingTagging->save();
                 } catch (Exception $e) {
                     _log($e->getMessage());
                 }
                 $approvedExistingTags[] = $sanitizedName;
             }
             // In all other cases (already approved or rejected), the
             // old tagging is kept in place of the new one.
             continue;
         }
         $tagsToAdd[] = $sanitizedName;
         // Taggings are automatically added to item if they are appoved.
         try {
             $tagging->save();
         } catch (Exception $e) {
             _log($e->getMessage());
         }
     }
     // Information for user.
     if (count($approvedExistingTags)) {
         $this->_helper->flashMessenger(__('Your tags "%s" have been approved.', implode(', ', $approvedExistingTags)), 'success');
     }
     if (count($tagsToAdd) == 0 && count($approvedExistingTags) == 0) {
         $this->_helper->flashMessenger(__('This tag has already been submitted "%s" or it is not correctly formatted.', $userTagging), 'warning');
     } else {
         if ($requireModeration) {
             $this->_helper->flashMessenger(__('Your tag "%s" is awaiting approval', $userTagging), 'success');
         } else {
             if (count($tagsToAdd) == 0) {
                 // In that case, this is approved existing tags.
             } elseif (count($tagsToAdd) == 1) {
                 $this->_helper->flashMessenger(__('Your tag "%s" has been added', implode(', ', $tagsToAdd)), 'success');
             } else {
                 $this->_helper->flashMessenger(__('Your tags "%s" have been added', implode(', ', $tagsToAdd)), 'success');
             }
         }
     }
     $this->_helper->redirector->gotoUrl($destination);
 }
$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;
}
$obj->addMonitoringUser(8);
// send the newsletter
 /**
  * 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);
 }
Exemplo n.º 7
0
	public function testDelete()
	{
		$tag = Tagging::get('Some Title');
		$tag->delete();
		
		$tag = new Tagging;
		$tag->title = 'Some Title';
		$tag->language = 'en';
		$tag->body = 'Some Very Long body.';
		$tag->save();
		$this->assertEquals(array(), $tag->tags());
	}
/**
 * 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();
    }
}
        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;
                    }
                }
            }
        }
    }
} else {
    echo "!!!!! Gli array hanno un numero di elementi diversi!";