function getImportantActs($xml_url, $xsl_filename, $n_nodes) { try { // read the xml from url $xmldoc = new DomDocument(); $xmldoc->load($xml_url); // read xslt file $xsldoc = new DomDocument(); $xsldoc->load($xsl_filename); $xsl = new XSLTProcessor(); $xsl->importStyleSheet($xsldoc); // trasforma XML secondo l'XSLT ed estrae il contenuto del div $transformed_xml = new SimpleXMLElement($xsl->transformToXML($xmldoc)); $nodes = $transformed_xml->children(); // write values to screen $cnt = 0; foreach ($nodes as $node) { $cnt++; $atto = OppAttoPeer::retrieveByPK($node['atto_id']); printf("\t%d. %s => %f\n", $cnt, $atto->getTitoloCompleto(), $node['totale']); if ($cnt >= $n_nodes) { break; } } } catch (Exception $e) { printf("Errore durante la scrittura del file: %s\n", $e->getMessage()); } }
public function executeAttiutenti() { // costruzione del criterio di ordinamento switch ($this->type) { case 'commenti': $order_clause = ' order by nb_commenti desc '; break; case 'monitor': $order_clause = ' order by n_monitoring_users desc '; break; case 'voti': $order_clause = ' order by (ut_fav+ut_contr) desc '; break; default: $order_clause = ''; break; } $limit = 5; $con = Propel::getConnection(OppAttoPeer::DATABASE_NAME); // estrazione degli atti (sia positivi che negativi) $sql = sprintf("select id from opp_atto where legislatura=17 %s limit %d;", $order_clause, $limit); $stm = $con->createStatement(); $rs = $stm->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); // estrazione atti che verificano $atti = array(); while ($rs->next()) { $row = $rs->getRow(); $atti[] = OppAttoPeer::retrieveByPK($row['id']); } $this->atti = $atti; }
/** * torna i ddl collegati agli emendamenti firmati dalle cariche * * @param string $cariche_ids * @return array di OppAtto * @author Guglielmo Celata */ public static function getDDLCollegatiCariche($cariche_ids) { $con = Propel::getConnection(self::DATABASE_NAME); $sql = sprintf("select ae.atto_id, count(ae.atto_id) n_emendamenti from opp_carica_has_emendamento ce, opp_emendamento e, opp_atto_has_emendamento ae where ae.emendamento_id=e.id and e.id=ce.emendamento_id and ce.carica_id in (%s) and ae.portante=1 group by ae.atto_id order by n_emendamenti desc", implode(",", $cariche_ids)); $stm = $con->createStatement(); $rs = $stm->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); $ddl = array(); while ($rs->next()) { $row = $rs->getRow(); $ddl[] = OppAttoPeer::retrieveByPK($row['atto_id']); } return $ddl; }
/** * torna i ddl collegati agli interventi delle cariche * * @param string $cariche_ids * @return array di OppAtto * @author Guglielmo Celata */ public static function getDDLCollegatiCariche($cariche_ids) { $con = Propel::getConnection(self::DATABASE_NAME); $sql = sprintf("select i.atto_id, count(i.atto_id) n_interventi from opp_intervento i where i.carica_id in (%s) group by i.atto_id order by n_interventi desc", implode(",", $cariche_ids)); $stm = $con->createStatement(); $rs = $stm->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); $ddl = array(); while ($rs->next()) { $row = $rs->getRow(); $ddl[] = OppAttoPeer::retrieveByPK($row['atto_id']); } return $ddl; }
protected function setPage($page_name = null) { // Get page from request if not given as parameter (default behaviour) if (is_null($page_name)) { $page_name = $this->getRequestParameter('page', $this->startPage); } // Handle case insensitivity $page_name = strtolower($page_name); // Support default page if not specified in namespace if (substr($page_name, -1) == ':') { $page_name .= $this->startPage; } // Retrieve the page, or start a new one if cannot be found $this->page = nahoWikiPagePeer::retrieveByName($page_name); if (!$this->page) { return; } // Retrieve the revision $revision = $this->getRequestParameter('revision', $this->page->getLatestRevision()); $this->revision = $this->page->getRevision($revision); if (!$this->revision) { $this->initNewRevision(); } // Generate the URI parameters to keep trace of the requested page $this->uriParams = 'page=' . $this->page->getName(); if ($this->revision->getRevision() != $this->page->getLatestRevision()) { $this->uriParams .= '&revision=' . $this->revision->getRevision(); } // Permissions management $this->canView = $this->page->canView($this->getUser()); $this->canEdit = $this->page->canEdit($this->getUser()); // Retriev item name and type of item (tab and breadcrumbs) list($tipo, $id) = split("_", $this->page->getName()); switch ($tipo) { case 'atto': $this->item = OppAttoPeer::retrieveByPK($id); $this->item_name = Text::denominazioneAttoShort($this->item); break; case 'votazione': $this->item = OppVotazionePeer::retrieveByPK($id); $this->item_name = $this->item->getTitolo(); break; case 'emendamento': $this->item = OppEmendamentoPeer::retrieveByPK($id); $attoPortante = $this->item->getAttoPortante(); $this->item_name = "Emendamento " . $this->item->getTitolo() . " relativo a " . Text::denominazioneAttoShort($attoPortante) . " - " . $attoPortante->getTitolo(); break; } $this->item_type = $tipo; }
<th scope="col">indice:</th> <th scope="col">azioni:</th> </tr> </thead> <tbody> <?php $tr_class = 'even'; ?> <?php foreach ($pager->getResults() as $record) { ?> <?php $atto = OppAttoPeer::retrieveByPK($record->getChiId()); ?> <tr class="<?php echo $tr_class; ?> "> <?php $tr_class = $tr_class == 'even' ? 'odd' : 'even'; ?> <td><?php echo $atto->getOppTipoAtto()->getDenominazione(); ?> </td> <th scope="row"> <?php
<?php $atto = OppAttoPeer::retrieveByPK($result->propel_id); $tipo_atto = OppTipoAttoPeer::retrieveByPK($result->tipo_atto_id); ?> <?php echo $tipo_atto->getDescrizione(); ?> - <?php echo link_to_in_mail(highlight_keywords($atto->getTitoloCompleto(), $term, sfConfig::get('app_lucene_result_highlighter', '<strong class="highlight">%s</strong>')), add_highlight_qs($result->getInternalUri(), $term)); ?> - presentato il <?php echo $atto->getDataPres('d/m/Y'); ?>
/** * returns an array with all pred and succ * order criterion, by date * * @return OppAtto object * @author Ettore Di Cesare **/ public function getAllPred() { $allPred = array(); $atto = $this; $pred = $atto->getPred(); while ($pred != '' && !is_null($pred)) { $result = OppAttoPeer::retrieveByPK($atto->getId()); if ($result->getPred() != '' && !is_null($result->getPred())) { $atto = OppAttoPeer::retrieveByPk($result->getPred()); $pred = $atto->getId(); $allPred[] = $atto; } else { $pred = ''; } } return array_reverse($allPred); }
public function executeAct() { $this->act_id = $this->getRequestParameter('id'); $this->act = OppAttoPeer::retrieveByPK($this->act_id); $this->n_news = oppNewsPeer::countNewsForItem('OppAtto', $this->act_id); $this->getResponse()->setTitle('tutte le notizie su ' . $this->act->getOppTipoAtto()->getDescrizione() . ' ' . Text::denominazioneAttoShort($this->act) . ' - ' . sfConfig::get('app_main_title')); $this->response->addMeta('description', 'Tutte le notizie aggiornate quotidianamente su presentazione e iter ' . $this->act->getOppTipoAtto()->getDescrizione() . ' ' . Text::denominazioneAttoShort($this->act), true); $c = oppNewsPeer::getNewsForItemCriteria('OppAtto', $this->act_id); $c->addDescendingOrderByColumn(NewsPeer::DATE); if ($this->hasRequestParameter('itemsperpage')) { $this->getUser()->setAttribute('itemsperpage', $this->getRequestParameter('itemsperpage')); } $itemsperpage = $this->getUser()->getAttribute('itemsperpage', sfConfig::get('app_pagination_limit')); $pager = new deppNewsPager('News', $itemsperpage); $pager->setCriteria($c); $pager->setPage($this->getRequestParameter('page', 1)); $pager->init(); $this->pager = $pager; }
/** * estrae il dettaglio degli interessi di un politico per gli argomenti, a una certa data * * @param string $carica_id * @param string $argomenti_ids * @param string $data * @param string $fetch_interventi * @return hash * 'firme_r' => [{'atto' => 1, 'punti_atto' => 232.23}, {'atto' => ID, 'punti_atto' => 12.34}, ...], * 'totale_firme_r' => 344.12, * 'firme_p' => [{'atto' => 2, 'punti_atto' => 123.45}, {'atto' => ID, 'punti_atto' => 23.34}, ...], * 'totale_firme_p' => 244.12, * 'firme_c' => [{'atto' => 3, 'punti_atto' => 234.56}, {'atto' => ID, 'punti_atto' => 34.56}, ...], * 'totale_firme_c' => 354.12, * 'interventi' => [{'atto' => 4, 'punti_atto' => 345.67, {'atto' => ID, 'punti_atto' => 56.67}, ...], * 'totale_interventi' => 456.12, * * @author Guglielmo Celata */ public static function getDettaglioInteresseArgomenti($carica_id, $argomenti_ids, $data, $fetch_interventi = true) { $con = Propel::getConnection(self::DATABASE_NAME); $dettaglio = array(); // estrazione di tutte le firme della carica relative ad atti taggati con argomento e del peso degli atti foreach (array('P', 'R', 'C') as $tipo_firma) { $dettaglio["firme_" . strtolower($tipo_firma)] = array(); $dettaglio['totale_firme_' . strtolower($tipo_firma)] = 0; foreach (array(0, 1) as $is_omnibus) { if ($is_omnibus) { $tagging_table = 'sf_tagging_for_index'; $tagging_conditions = "t.atto_id=ca.atto_id"; } else { $tagging_table = 'sf_tagging'; $tagging_conditions = "t.taggable_id=ca.atto_id and t.taggable_model='OppAtto'"; } $sql = sprintf("select ca.atto_id, ah.indice, ah.priorita from opp_atto a, opp_carica_has_atto ca, {$tagging_table} t, opp_act_history_cache ah where a.id=ca.atto_id and (ca.tipo != 'P' or ca.tipo = 'P' and a.pred is null) and a.is_omnibus={$is_omnibus} and ca.tipo='%s' and ca.carica_id=%d and {$tagging_conditions} and ah.chi_tipo='A' and ah.data='%s' and ah.chi_id=ca.atto_id and t.tag_id in (%s) group by ca.atto_id", $tipo_firma, $carica_id, $data, implode(", ", $argomenti_ids)); $stm = $con->createStatement(); $rs = $stm->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); // costruzione array del dettaglio firme $totale = 0; while ($rs->next()) { $row = $rs->getRow(); $atto_id = $row['atto_id']; $priorita = $row['priorita']; $punti_atto = $row['indice'] / (double) $priorita; $dettaglio["firme_" . strtolower($tipo_firma)][] = array('atto' => OppAttoPeer::retrieveByPK($atto_id), 'punti_atto' => $punti_atto); $totale += OppCaricaHasAttoPeer::get_nuovo_fattore_firma($tipo_firma) * $punti_atto; } $dettaglio['totale_firme_' . strtolower($tipo_firma)] += $totale; } } if ($fetch_interventi) { $dettaglio["interventi"] = array(); $dettaglio['totale_interventi'] = 0; foreach (array(0, 1) as $is_omnibus) { if ($is_omnibus) { $tagging_table = 'sf_tagging_for_index'; $tagging_conditions = "t.atto_id=i.atto_id"; } else { $tagging_table = 'sf_tagging'; $tagging_conditions = "t.taggable_id=i.atto_id and t.taggable_model='OppAtto'"; } // estrazione di tutti gli interventi della carica relativo ad atti taggati con argomento $sql = sprintf("select count(*) as ni, i.atto_id, ah.indice, ah.priorita from opp_atto a, opp_intervento i, {$tagging_table} t, opp_act_history_cache ah where a.id=i.atto_id and a.is_omnibus={$is_omnibus} and ah.chi_id=i.atto_id and i.carica_id = %d and ah.data='%s' and {$tagging_conditions} and t.tag_id in (%s) group by i.atto_id order by i.atto_id;", $carica_id, $data, implode(", ", $argomenti_ids)); $stm = $con->createStatement(); $rs = $stm->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); // costruzione array del dettaglio interventi $totale = 0; while ($rs->next()) { $row = $rs->getRow(); $n_interventi = $row['ni']; $atto_id = $row['atto_id']; $priorita = $row['priorita']; $punti_atto = $row['indice'] / (double) $priorita; $dettaglio["interventi"][] = array('atto' => OppAttoPeer::retrieveByPK($atto_id), 'atto_id' => $atto_id, 'punti_atto' => $punti_atto, 'n_interventi' => $n_interventi); $totale += OppCaricaHasAttoPeer::get_nuovo_fattore_firma('I') * $n_interventi * $punti_atto; } $dettaglio['totale_interventi'] += $totale; } } return $dettaglio; }
/** * API (protetta da una API key) * torna flusso xml con i dati di un singolo atto * progetto op_fb * * <opp xmlns="http://www.openpolis.it/2010/opp" * xmlns:op="http://www.openpolis.it/2010/op" * xmlns:xlink="http://www.w3.org/1999/xlink"> * <op:content> * <atto opp_id="38631"> * <ramo>S</ramo> * <numero>1611-4-B</numero> * <tipo_atto>12</tipo_atto> * <titolo><![CDATA[ * [Ddl intercettazioni] Norme in materia di intercettazioni telefoniche, telematiche e ambientali. Modifica della disciplina in materia di astensione del giudice e degli atti di indagine. Integrazione della disciplina sulla responsabilità amministrativa delle persone giuridiche * ]]> * </titolo> * <presentato_il>2009-06-11</presentato_il> * <tipo_iniziativa>2</tipo_iniziativa> * <primi_firmatari> * <parlamentare opp_id="167"> * <tipo>On</tipo> * <nome>Angelino</nome> * <cognome>ALFANO</cognome> * <gruppo> * <nome>Popolo delle Libertà</nome> * <acronimo>PdL</acronimo> * </gruppo> * <data_inizio_carica>2008-04-29</data_inizio_carica> * <circoscrizione>Sicilia 1</circoscrizione> * </parlamentare> * </primi_firmatari> * <cofirmatari> * * </cofirmatari> * <relatori> * <parlamentare opp_id="1518"> * <tipo>Sen</tipo> * <nome>Roberto</nome> * <cognome>CENTARO</cognome> * <gruppo> * <nome>Popolo delle Libertà</nome> * <acronimo>PdL</acronimo> * </gruppo> * <data_inizio_carica>2008-04-29</data_inizio_carica> * <circoscrizione>Sicilia</circoscrizione> * </parlamentare> * </relatori> * <commissioni_assegnatarie> * <commissione tipo_sede="referente">Senato Commissione II Giustizia</commissione> * <commissione tipo_sede="consultiva">Senato Commissione I Affari Costituzionali</commissione> * <commissione tipo_sede="consultiva">Senato Commissione III Affari Esteri</commissione> * <commissione tipo_sede="consultiva">Senato Commissione V Bilancio</commissione> * </commissioni_assegnatarie> * <url_fonte_ufficiale xlink:href="http://www.senato.it/leg/16/BGT/Schede/Ddliter/33809.htm"/> * <testi_atto> * <url_testo_atto xlink:href="http://www.senato.it/loc/link.asp?tipodoc=DDLPRES&leg=16&id=424336"/> * </testi_atto> * </atto> * </op:content> * </opp> * * * Return error in case something's wrong * <opp xlmns="http://www.openpolis.it/2010/opp" * xmlns:op="http://www.openpolis.it/2010/op" * <op:error>Messaggio di errore</op:error> * </opp> * @return String * @author Guglielmo Celata **/ public function executeAtto() { $key = $this->getRequestParameter('key'); $id = $this->getRequestParameter('opp_id'); $is_valid_key = deppApiKeysPeer::isValidKey($key); $storage_path = sfConfig::get('sf_root_cache_dir'); $file_path = sprintf("%s/atti/%s.xml", $storage_path, $id); $resp_node = new SimpleXMLExtended('<opp xmlns="' . $this->opp_ns . '" ' . ' xmlns:op="' . $this->op_ns . '" ' . ' xmlns:xlink="' . $this->xlink_ns . '" >' . '</opp>'); $is_error = false; if ($is_valid_key) { // controllo esistenza del file if ($fp = @fopen($file_path, "r")) { // retrieve contenuto XML dalla cache sfContext::getInstance()->getLogger()->info("reading from cache: " . $file_path); $xmlContent = fread($fp, filesize($file_path)); fclose($fp); // send xml to output $this->_send_output($xmlContent); return sfView::NONE; } // estrazione informazioni $atto = OppAttoPeer::retrieveByPK($id); if ($atto) { $titulo = $atto->getTitolo(); $data_pres = $atto->getDataPres('Y-m-d'); $ramo = $atto->getRamo(); $numero = str_replace("/", "-", $atto->getNumfase()); $legislatura = $atto->getLegislatura(); // produzione xml $content_node = $resp_node->addChild('op:content', null, $this->op_ns); $atto_node = $content_node->addChild('atto', null, $this->opp_ns); $atto_node->addAttribute('opp_id', $id); $atto_node->addChild('ramo', $ramo); $atto_node->addChild('numero', $numero); $tipo_atto = $atto_node->addChild('tipo_atto', $atto->getOppTipoAtto()->getDenominazione()); // $tipo_atto->addAttribute('id', $atto->getTipoAttoId()); $titulo_node = $atto_node->addChild('titolo', null); $titulo_node->addCData($titulo); $atto_node->addChild('presentato_il', $data_pres); //tipo di iniziativa $tipo_iniziativa = ''; if ($atto->getIniziativa()) { switch ($atto->getIniziativa()) { case '1': $tipo_iniziativa = 'Parlamentare'; break; case '2': $tipo_iniziativa = 'di Governo'; break; case '4': $tipo_iniziativa = 'Popolare'; break; default: $tipo_iniziativa = ''; break; } } $primi_firmatari_node = $atto_node->addChild('primi_firmatari'); $this->addFirmatari('P', $atto, $primi_firmatari_node); $relatori_node = $atto_node->addChild('relatori'); $this->addFirmatari('R', $atto, $relatori_node); $co_firmatari_node = $atto_node->addChild('co_firmatari'); $this->addFirmatari('C', $atto, $co_firmatari_node); $commissioni_node = $atto_node->addChild('commissioni_assegnatarie'); $commissioni = $atto->getCommissioni(); foreach ($commissioni as $commissione) { $tipo_sede = $commissione->getTipo(); $commissione_node = $commissioni_node->addChild('commissione'); $commissione_node->addChild('tipo_sede', $tipo_sede); $commissione_node->addChild('ramo', $commissione->getOppSede()->getRamo()); $commissione_node->addChild('nome', $commissione->getOppSede()->getDenominazione()); } $atto_node->addChild('tipo_iniziativa', $tipo_iniziativa); // individuazione link fonte /* if ($atto->getTipoAttoId() == '1') $link = 'http://www.senato.it/leg/' . $atto->getLegislatura() . '/BGT/Schede/Ddliter/' . $atto->getParlamentoId() . '.htm'; else if ($atto->getTipoAttoId() > '1' && $atto->getTipoAttoId() < '12' ) $link = 'http://banchedati.camera.it/sindacatoispettivo_' . $atto->getLegislatura() . '/showXhtml.Asp?idAtto=' . $atto->getParlamentoId() . '&stile=6&highLight=1'; else if ($atto->getTipoAttoId() == '12' ) { $anno = explode("-",$atto->getDataPres()); $numero = explode("/",$atto->getNumfase()); $link = "http://www.normattiva.it/uri-res/N2Ls?urn:nir:stato:decreto.legge:".$anno[0].";".$numero[0]; } else if ($atto->getTipoAttoId() == '14' ) { if ($atto->getRamo()=='C') $link = 'http://www.camera.it/_dati/leg' . $atto->getLegislatura() . '/lavori/stencomm/' . $atto->getNumfase() . '/s010.htm'; else $link = 'http://www.senato.it/leg/' . $atto->getLegislatura() . '/BGT/Schede/ProcANL/ProcANLscheda' . $atto->getParlamentoId() . '.htm'; } else if ($atto->getTipoAttoId() > '14' && $atto->getTipoAttoId() < '18' ) { $str = $atto->getParlamentoId(); $len = 5 - strlen($str); for($i=0; $i<$len; $i++) $str = '0' . $str; $link = 'http://www.camera.it/parlam/leggi/deleghe/'.$str.'dl.htm'; } if ($atto->getTipoAttoId() == '13') $link = 'http://www.governo.it/GovernoInforma/Comunicati/testo_int.asp?d='.$atto->getParlamentoId(); $fonte_node = $atto_node->addChild('fonte'); $fonte_node->addAttribute('href', $link); */ // estrazione documenti $c = new Criteria(); $c->add(OppDocumentoPeer::DOSSIER, 0); $documenti = $atto->getOppDocumentos($c); $documenti_node = $atto_node->addChild('documenti'); foreach ($documenti as $documento) { $documento_node = $documenti_node->addChild('documento'); if ($documento->getUrlTesto()) { $documento_node->addCData($documento->getTesto()); // $documento_node->addAttribute('href_txt', $documento->getUrlTesto()); if ($documento->getUrlPdf()) { $documento_node->addAttribute('href_pdf', $documento->getUrlPdf()); } } } $documenti_node->addAttribute('n', count($documenti)); // determina ultimo status $status = $atto->getStatus(); $status_str = ""; foreach ($status as $data => $status_iter) { $iter = OppIterPeer::retrieveByPK($status_iter); $status_str = $iter->getFase(); } $atto_node->addChild('status', $status_str); // determina lettura $preds = $atto->getAllPred(); $atto_node->addChild('lettura', 1 + count($preds)); } else { $is_error = true; $resp_node->addChild('op:error', 'Nessun atto trovato per questo ID', $this->op_ns); } } else { $is_error = true; $resp_node->addChild('op:error', 'Chiave di accesso non valida', $this->op_ns); } // build xml content out of respNode $xmlContent = $resp_node->asXML(); // write xml cache to file system (for non-error xml's) if (!$is_error) { $fp = @fopen($file_path, "w"); sfContext::getInstance()->getLogger()->info("writing to cache: " . $file_path); fwrite($fp, $xmlContent); fclose($fp); } // send xml to output $this->_send_output($xmlContent); return sfView::NONE; }
/** * Executes index action * */ public function executeIndex() { $this->session = $this->getUser(); $this->atto = OppAttoPeer::retrieveByPK($this->getRequestParameter('id')); $this->getResponse()->setTitle('Lista degli emendamenti al ddl ' . $this->atto->getRamo() . '.' . $this->atto->getNumfase() . ' ' . Text::denominazioneAtto($this->atto, 'index') . ' - ' . sfConfig::get('app_main_title')); $this->response->addMeta('description', 'La lista con i testi e gli aggiornamenti degli emendamenti presentati per il disegno di legge ' . $this->atto->getRamo() . '.' . $this->atto->getNumfase() . ' ' . Text::denominazioneAtto($this->atto, 'index'), true); // extracts distinct articoli for listed emendamenti $articles = $this->atto->getAvailableEmendamentiArticles(); $ar = array('0' => 'tutti'); foreach ($articles as $article) { $ar[$article] = $article; } $this->available_articles = $ar; // extracts distinct sedi for listed emendamenti $sites = $this->atto->getAvailableEmendamentiSites(); $ar = array('0' => 'tutte'); foreach ($sites as $id => $site) { $ar[$id] = $site; } $this->available_sites = $ar; // extracts distinct presentatori for listed emendamenti $presenters = $this->atto->getAvailableEmendamentiPresenters(); $ar = array('0' => 'tutti'); foreach ($presenters as $id => $presenter) { $ar[$id] = $presenter; } $this->available_presenters = $ar; // extracts distinct statuses for listed emendamenti $statuses = $this->atto->getAvailableEmendamentiStatuses(); $ar = array('0' => 'tutti'); foreach ($statuses as $id => $status) { $ar[$id] = $status; } $this->available_statuses = $ar; // set number of items per page to be displayed (as specified in the pager) if ($this->hasRequestParameter('itemsperpage')) { $this->getUser()->setAttribute('itemsperpage', $this->getRequestParameter('itemsperpage')); } $itemsperpage = $this->getUser()->getAttribute('itemsperpage', sfConfig::get('app_pagination_limit')); // reset filters and sort session variables when changing action $this->_reset_session_vars(); // reset filter request variables if explicitly asked if ($this->getRequestParameter('reset_filters', 'false') == 'true') { foreach (self::$filter_names as $filter_name) { $this->getRequest()->getParameterHolder()->set('filter_' . $filter_name, '0'); } } // set filter request variables $this->processFilters(array('article', 'site', 'presenter', 'status')); // if all filters were reset, then restart from scratch $all_filters_are_null = true; foreach (self::$filter_names as $filter_name) { $all_filters_are_null &= $this->getRequestParameter('filter_' . $filter_name) == '0'; } if ($all_filters_are_null) { $this->redirect('@emendamenti_atto?id=' . $this->atto->getId()); } // build pager with all emendamenti for this atto, sorted by pres_date $this->pager = new sfPropelPager('OppAttoHasEmendamento', $itemsperpage); $c = new Criteria(); $c->add(OppAttoHasEmendamentoPeer::ATTO_ID, $this->atto->getId()); //$c->addDescendingOrderByColumn(OppEmendamentoPeer::DATA_PRES); $c->addAscendingOrderByColumn(OppEmendamentoPeer::NUMFASE); // add filters to pager query criteria $this->addFiltersCriteria($c); $this->pager->setCriteria($c); $this->pager->setPage($this->getRequestParameter('page', 1)); $this->pager->setPeerMethod('doSelectJoinOppEmendamento'); $this->pager->setPeerCountMethod('doCountJoinOppEmendamento'); $this->pager->init(); }
public function executeSetIsMainUnified() { $atto_id = $this->getRequestParameter('atto_id'); $value = $this->getRequestParameter('is_main_unified'); $atto = OppAttoPeer::retrieveByPK($atto_id); $atto->setIsMainUnified($value); $atto->save(); $this->redirect('@singolo_atto?id=' . $atto_id); }
/** * Calcola o ri-calcola la cache dell'indice di rilevanza degli atti * Si può specificare il una data fino alla quale calcolare la rilevanza * Se sono passati degli ID (argomenti), sono interpretati come ID di atti e il calcolo è fatto solo per loro */ function run_opp_build_cache_atti($task, $args, $options) { static $loaded; // load application context if (!$loaded) { task_loader(); $loaded = true; } echo "memory usage: " . memory_get_usage() . "\n"; $data = ''; $verbose = false; $offset = null; $limit = null; if (array_key_exists('data', $options)) { $data = $options['data']; } if (array_key_exists('verbose', $options)) { $verbose = true; } if (array_key_exists('offset', $options)) { $offset = $options['offset']; } if (array_key_exists('limit', $options)) { $limit = $options['limit']; } if ($data != '') { $legislatura_corrente = OppLegislaturaPeer::getCurrent($data); $data_lookup = $data; } else { $legislatura_corrente = OppLegislaturaPeer::getCurrent(); $data = date('Y-m-d'); $data_lookup = OppActHistoryCachePeer::fetchLastData(); } $msg = sprintf("calcolo rilevanza - fino a: %10s\n", $data); echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true)); $start_time = time(); if (count($args) > 0) { try { $atti_rs = OppAttoPeer::getRSFromIDArray($args); } catch (Exception $e) { throw new Exception("Specificare degli ID validi. \n" . $e); } } else { $atti_rs = OppAttoPeer::getAttiDataRS($data, $offset, $limit); } $n_atti = $atti_rs->getRecordCount(); echo "memory usage: " . memory_get_usage() . "\n"; $cnt = 0; while ($atti_rs->next()) { $a = $atti_rs->getRow(); $atto_id = $a['id']; $tipo_atto_id = $a['tipo_atto_id']; $cnt++; $atto = OppAttoPeer::retrieveByPK($atto_id); if (!array_key_exists($tipo_atto_id, OppTipoAttoPeer::$tipi_per_indice)) { continue; } printf("%5d/%6d) %40s %d ... ", $cnt, $n_atti, OppTipoAttoPeer::$tipi_per_indice[$tipo_atto_id], $atto_id); $indice = OppIndiceRilevanzaPeer::calcola_rilevanza_atto($atto, $tipo_atto_id, $data, $verbose); // inserimento o aggiornamento del valore in opp_politician_history_cache $cache_record = OppActHistoryCachePeer::retrieveByDataChiTipoChiId($data_lookup, 'A', $atto_id); if (!$cache_record) { $cache_record = new OppActHistoryCache(); } $cache_record->setLegislatura($legislatura_corrente); $cache_record->setChiTipo('A'); $cache_record->setChiId($atto_id); $cache_record->setTipoAttoId($tipo_atto_id); $cache_record->setIndice($indice); $cache_record->setData($data); $cache_record->setUpdatedAt(date('Y-m-d H:i')); // forza riscrittura updated_at, per tenere traccia esecuzioni $cache_record->save(); unset($cache_record); $msg = sprintf("%7.2f", $indice); 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)); } $msg = sprintf("%d atti elaborati\n", $cnt); echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true)); }
/** * calcola l'indice di rilevanza, per un atto, nel suo complesso * * @param integer $atto_id * @param integer $tipo_atto_id * @param date $data * @param SimpleXMLElement $xml_node * @param boolean $verbose * @return float * @author Guglielmo Celata */ public static function calcolaRilevanzaAtto($atto, $tipo_atto_id, $data, $xml_node, $verbose = false) { $atto_node = $xml_node->addChild('atto', null, self::$opp_ns); $atto_id = $atto->getId(); // calcolo gruppi e schieramenti che presentano list($schier_pres, $grup_pres) = OppCaricaHasAttoPeer::getSchierGrupPresAtto($atto_id, $data); if ($verbose) { printf("\n presentazione:\n"); printf(" schieramenti: %s\n", join(',', $schier_pres)); printf(" gruppi: %s\n", join(',', $grup_pres)); } // il peso di un atto non dipende mai da chi lo ha presentato // il coefficiente che si considera è sempre quello di maggioranza $di_maggioranza = true; // determina la priorità dell'atto $priorita = is_null($atto->getPriorityValue()) ? 1 : $atto->getPriorityValue(); $atto_is_ratifica = $atto->isRatifica(); // determina il tipo di atto (per quello che concerne il calcolo dell'indice) $tipo_atto = OppTipoAttoPeer::getTipoPerIndice($tipo_atto_id); if (is_null($tipo_atto)) { return 0; } $atto_node->addAttribute('tipo_atto', $tipo_atto); $atto_node->addAttribute('priorita', $priorita); $atto_node->addAttribute('id', $atto_id); $punteggio = 0.0; // punteggio dato all'atto per-se, a seconda del tipo if ($tipo_atto == 'SDDL') { $punteggio = 1.0; } else { $punteggio = 0.5; } $presentazione_node = $atto_node->addChild('presentazione', null, self::$opp_ns); $presentazione_node->addAttribute('totale', $punteggio); // --- consenso --- $consenso_node = $atto_node->addChild('consenso', null, self::$opp_ns); $firmeRS = OppCaricaHasAttoPeer::getFirmeAttoDataTipoRS($atto_id, $data, "'C'"); $n_firme = array('gruppo' => 0, 'altri' => 0, 'opp' => 0); while ($firmeRS->next()) { $row = $firmeRS->getRow(); if ($verbose) { printf(" %d firme per gruppo %d\n", $row['nf'], $row['gruppo_id']); } // gestione del caso in cui l'atto è presentato dai due schieramenti // tutte le firme sono assegnate a gruppo, altri e opp if (count($schier_pres) > 1) { $n_firme['gruppo'] += $row['nf']; $n_firme['altri'] += $row['nf']; $n_firme['opp'] += $row['nf']; continue; } // gestione del caso in cui l'atto è presentato da più di un gruppo // le firme dello schieramento di pres. sono assegnate a gruppo e altri if (count($grup_pres) > 1) { if ($row['maggioranza'] == $schier_pres[0]) { $n_firme['gruppo'] += $row['nf']; $n_firme['altri'] += $row['nf']; } else { $n_firme['opp'] += $row['nf']; } continue; } if (in_array($row['gruppo_id'], $grup_pres)) { if ($row['nf'] > 1) { $n_firme['gruppo'] += $row['nf']; } } else { if (count($schier_pres) > 0 && $row['maggioranza'] == $schier_pres[0]) { $n_firme['altri'] += $row['nf']; } else { $n_firme['gruppo'] += $row['nf']; } } } $d_punteggio = 0.0; foreach ($n_firme as $tipo => $value) { if (!$value) { continue; } $soglia = self::$soglia_cofirme; if ($tipo_atto == 'mozione') { $soglia = self::$soglia_cofirme_mozioni; } if ($value <= $soglia) { $d_punteggio += $dd_punteggio = self::getPunteggio($tipo_atto, "cofirme_{$tipo}_lo", $di_maggioranza); } else { $d_punteggio += $dd_punteggio = self::getPunteggio($tipo_atto, "cofirme_{$tipo}_hi", $di_maggioranza); } $firme_node = $consenso_node->addChild('firme_' . $tipo, null, self::$opp_ns); $firme_node->addAttribute('n_firme', $value); $firme_node->addAttribute('totale', $dd_punteggio); if ($verbose) { printf(" firme %s (%d) %7.2f\n", $tipo, $value, $dd_punteggio); } } $punteggio += $d_punteggio; if ($verbose) { printf(" totale firme %7.2f\n", $d_punteggio); } $consenso_node->addAttribute('n_firme', $n_firme['gruppo'] + $n_firme['altri'] + $n_firme['opp']); $consenso_node->addAttribute('totale', $d_punteggio); // --- iter --- // controlla se atti non assorbiti sono diventati legge dopo passaggi in altri rami // atti diventati legge non prendono il punteggio di approvazione $diventato_legge_in_altri_rami = false; if (!isset($passaggio) || $passaggio != 'assorbito') { $atto = OppAttoPeer::retrieveByPK($atto_id); $c = new Criteria(); $c->add(OppAttoHasIterPeer::ITER_ID, 16); $c->add(OppAttoHasIterPeer::DATA, $data, Criteria::LESS_EQUAL); while ($atto_succ_id = $atto->getSucc()) { $atto = OppAttoPeer::retrieveByPK($atto_succ_id); if ($atto->countOppAttoHasIters($c) > 0) { $diventato_legge_in_altri_rami = true; } } unset($c); unset($atto); } // determina se l'atto è parte di un Testo Unificato $is_unified = OppAttoPeer::isUnifiedText($atto_id); // determina se l'atto è stato assorbito $is_absorbed = OppAttoPeer::isAbsorbed($atto_id); // determina se l'atto unificato è principale o meno $is_unificato_non_main = is_array($is_unified) && !$is_unified['is_main_unified']; $is_unificato_main = is_array($is_unified) && $is_unified['is_main_unified']; $itinera_atto_rs = OppAttoHasIterPeer::getItineraAttoDataRS($atto_id, $data); $iter_node = $atto_node->addChild('iter', null, self::$opp_ns); $d_punteggio = 0.0; $n_passaggi = 0; while ($itinera_atto_rs->next()) { $iter_atto = $itinera_atto_rs->getRow(); $passaggio = OppIterPeer::getIterPerIndice($iter_atto['iter_id']); if (is_null($passaggio)) { continue; } // se l'atto è unificato e non-main, allora prende il punteggio come gli atti assorbiti if ($is_unificato_non_main && $passaggio == 'approvato') { $passaggio = 'assorbito'; } // se diventato legge in altri rami, non prende punteggio di approvazione if ($diventato_legge_in_altri_rami && $passaggio == 'approvato') { continue; } $n_passaggi++; $passaggio_node = $iter_node->addChild('passaggio', null, self::$opp_ns); if ($passaggio == 'assorbito' && $is_unificato_non_main) { $passaggio_node->addAttribute('tipo', 'assorbimento come unificato non principale'); } else { $passaggio_node->addAttribute('tipo', $passaggio); } $d_punteggio += $dd_punteggio = self::getPunteggio($tipo_atto, $passaggio, $di_maggioranza); if ($verbose) { if ($passaggio == 'assorbito' && $is_unificato_non_main) { printf(" iter %s %7.2f\n", 'assorbimento come unificato non principale', $dd_punteggio); } else { printf(" iter %s %7.2f\n", $passaggio, $dd_punteggio); } } $passaggio_node->addAttribute('totale', $dd_punteggio); // il break su atti assorbiti avviene dopo l'assegnazione del punteggio if ($passaggio == 'assorbito') { break; } // --- bonus maggioranza --- if ($passaggio == 'approvato') { if ($di_maggioranza && OppAttoPeer::isAttoVotatoDaOpposizione($atto_id, $data)) { $d_punteggio += $dd_punteggio = self::getPunteggio($tipo_atto, 'bonus_bi_partisan', true); $bonus_node = $iter_node->addChild('bonus_maggioranza', null, self::$opp_ns); $bonus_node->addAttribute('totale', $dd_punteggio); if ($verbose) { printf(" bonus di maggioranza! %7.2f\n", $dd_punteggio); } } } // break se mozione, risoluzione o odg approvato if (in_array($tipo_atto, array('mozione', 'risoluzione', 'odg')) && $passaggio == 'approvato') { break; } } // assegna punteggio se diventato legge in altri rami if ($diventato_legge_in_altri_rami && is_null($is_absorbed) && (is_null($is_unified) || $is_unificato_main)) { $d_punteggio += $dd_punteggio = self::getPunteggio($tipo_atto, 'diventato_legge', $di_maggioranza); $passaggio_node = $iter_node->addChild('passaggio', null, self::$opp_ns); $passaggio_node->addAttribute('tipo', "diventato legge in altri rami"); $passaggio_node->addAttribute('totale', $dd_punteggio); if ($verbose) { printf(" iter %s %7.2f\n", "diventato legge in altri rami", $dd_punteggio); } } $punteggio += $d_punteggio; if ($verbose) { printf(" totale iter %7.2f\n", $d_punteggio); } $iter_node->addAttribute('n_passaggi', $n_passaggi); $iter_node->addAttribute('totale', $d_punteggio); // --- componente emendamenti con funzione sigmoide --- $punteggio += $d_punteggio = self::calcolaComponenteEmendamentiPerAtto($atto_id, $data, $atto_node, $verbose); // --- sedute con interventi in commissione e assemblea --- $sedute_con_interventi_node = $atto_node->addChild('sedute_con_interventi', null, self::$opp_ns); $sedute_commissioni_node = $sedute_con_interventi_node->addChild('commissioni', null, self::$opp_ns); $n_sedute_commissioni = OppInterventoPeer::getNSeduteConInterventiAttoData($atto_id, 'C', $data); if ($n_sedute_commissioni) { $n_sedute_commissioni--; } if ($verbose) { printf(" n. sedute in commissione %d\n", $n_sedute_commissioni); } $d_punteggio_sedute_commissioni = $n_sedute_commissioni * parent::$punteggi['seduta_in_comm']; $sedute_commissioni_node->addAttribute('n_sedute', $n_sedute_commissioni); $sedute_commissioni_node->addAttribute('totale', $d_punteggio_sedute_commissioni); $sedute_assemblea_node = $sedute_con_interventi_node->addChild('assemblea', null, self::$opp_ns); $n_sedute_assemblea = OppInterventoPeer::getNSeduteConInterventiAttoData($atto_id, 'A', $data); if ($n_sedute_assemblea) { $n_sedute_assemblea--; } if ($verbose) { printf(" n. sedute in commissione %d\n", $n_sedute_assemblea); } $d_punteggio_sedute_assemblea = $n_sedute_assemblea * parent::$punteggi['seduta_in_ass']; $sedute_assemblea_node->addAttribute('n_sedute', $n_sedute_assemblea); $sedute_assemblea_node->addAttribute('totale', $d_punteggio_sedute_assemblea); $punteggio += $d_punteggio_sedute = $d_punteggio_sedute_commissioni + $d_punteggio_sedute_assemblea; if ($verbose) { printf(" totale sedute %7.2f\n", $d_punteggio_sedute); } $sedute_con_interventi_node->addAttribute('totale', $d_punteggio_sedute); if ($atto_is_ratifica) { $atto_node->addAttribute('totale_pre_decurtazione_ratifica', $punteggio); if ($verbose) { print "questo ATTO è una ratifica\n"; } $punteggio = $punteggio / self::$punteggi['fattore_diminuzione_ratifica']; } $punteggio = $priorita * $punteggio; $atto_node->addAttribute('totale', $punteggio); return $punteggio; }
/** * Genera i files di testo degli atti * $prefix/$atto_id */ function run_nltk_genera_files($task, $args, $options) { static $loaded; // load application context if (!$loaded) { _loader(); } $files_path = sfConfig::get('sf_data_dir') . DIRECTORY_SEPARATOR . "nltk"; $act_types = array(); $prefix = null; // usato per differenziare training, test e dev, è aggiunto prima dell'id $offset = null; $limit = null; if (array_key_exists('offset', $options)) { $offset = $options['offset']; } if (array_key_exists('limit', $options)) { $limit = $options['limit']; } if (array_key_exists('path', $options)) { $files_path = strtolower($options['path']); } if (array_key_exists('types', $options)) { $act_types = explode(",", $options['types']); } if (array_key_exists('prefix', $options)) { $prefix = strtolower($options['prefix']); } if (count($args) > 0) { try { $atti_rs = OppAttoPeer::getRSFromIDArray($args); } catch (Exception $e) { throw new Exception("Specificare degli ID validi. \n" . $e); } } else { $atti_rs = OppAttoPeer::getAttiTipoRS($act_types, $offset, $limit); } echo "memory usage: " . memory_get_usage() . "\n"; $start_time = time(); $msg = sprintf("generazione files dei testi degli atti\n"); echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true)); // loop principale $n_atti = $atti_rs->getRecordCount(); $cnt = 0; while ($atti_rs->next()) { $a = $atti_rs->getRow(); $atto_id = $a['id']; $tipo_atto_id = $a['tipo_atto_id']; $atto = OppAttoPeer::retrieveByPK($atto_id); if ($n_docs = $atto->countOppDocumentos()) { $docs = $atto->getOppDocumentos(); // path di tutti i testi dei doc relativi all'atto $atto_txt = ""; foreach ($docs as $doc) { $atto_txt .= $doc->getTesto(); } unset($docs); $fh = fopen($files_path . "/" . $atto_id, 'w'); fwrite($fh, $atto_txt); fclose($fh); } printf(" %d %d docs - ok (%d)\n", $atto_id, $n_docs, memory_get_usage()); unset($atto); $cnt++; } $msg = sprintf("%d atti elaborati\n", $cnt); 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)); }
/** * generate the html representation for the given news * * @param string $news * @return string (html) * @author Guglielmo Celata */ function community_news_text($news) { $news_string = ""; // fetch generator model $generator_model = $news->getGeneratorModel(); // fetch related model and object (item) $related_model = $news->getRelatedModel(); $related_id = $news->getRelatedId(); $item = call_user_func_array($related_model . 'Peer::retrieveByPK', array($related_id)); if (is_null($item)) { return "notizia su oggetto inesistente: ({$related_model}:{$related_id})"; } // build item link switch ($related_model) { case 'OppPolitico': // link al politico $item_type = 'il parlamentare'; $link = link_to_in_mail($item, '@parlamentare?' . $item->getUrlParams(), array('title' => 'Vai alla scheda del politico')); break; case 'OppDocumento': // link al documento $link = link_to_in_mail($item->getTitolo(), '@documento?id=' . $related_id, array('title' => $item->getTitolo())); $related_atto = OppAttoPeer::retrieveByPK($item->getAttoId()); // costruzione del link all'atto relativo al documento if (in_array($related_atto->getTipoAttoId(), array(1, 3, 4, 5, 6, 10, 11, 14))) { $atto_article = 'all\''; } elseif (in_array($related_atto->getTipoAttoId(), array(12, 13, 15, 16, 17))) { $atto_article = 'al '; } else { $atto_article = 'alla '; } $atto_link = $atto_article . $related_atto->getOppTipoAtto()->getDescrizione() . " "; $atto_link .= link_to_in_mail(Text::denominazioneAtto($related_atto, 'list', true), 'atto/index?id=' . $related_atto->getId(), array('title' => $related_atto->getTitolo())); break; case 'OppAtto': // link all'atto if (in_array($item->getTipoAttoId(), array(1, 10, 11, 12, 13, 15, 16, 17))) { $gender = 'm'; } else { $gender = 'f'; } $item_type = articolo($item->getTipoAttoId()) . $item->getOppTipoAtto()->getDescrizione() . " "; $link = link_to_in_mail(Text::denominazioneAtto($item, 'list'), 'atto/index?id=' . $related_id, array('title' => $item->getTitolo())); break; case 'OppVotazione': // link alla votazione $item_type = 'la votazione'; $link = link_to_in_mail($item->getTitolo(), '@votazione?' . $item->getUrlParams(), array('title' => 'Vai alla pagina della votazione')); break; case 'OppEmendamento': // link all'emendamento $item_type = 'l\'emendamento'; $link = link_to_in_mail($item->getTitoloCompleto(), '@singolo_emendamento?id=' . $item->getId(), array('title' => 'Vai alla pagina dell\'emendamento')); break; case 'Tag': // link all'argomento $item_type = 'l\'argomento'; $link = link_to_in_mail($item->getTripleValue(), '@argomento?triple_value=' . $item->getTripleValue(), array('title' => 'Vai alla pagina dell\'argomento')); break; } // build html code switch ($generator_model) { case 'sfEmendComment': // link al documento $link = link_to_in_mail($item->getTitolo(), '@documento?id=' . $related_id, array('title' => $item->getTitolo())); if ($news->getType() == 'C') { return sprintf("<div class='ico-type float-left'>%s</div><p>%s ha commentato il documento</p><p><strong>%s</strong></p><p>relativo %s</p>", image_tag('/images/ico-type-commento.png', array('alt' => 'commento')), strtolower($news->getUsername()), $link, $atto_link); } break; case 'sfComment': return sprintf("<div class='ico-type float-left'>%s</div><p>%s ha commentato %s</p><p> %s</p>", image_tag('/images/ico-type-commento.png', array('alt' => 'commento')), strtolower($news->getUsername()), $item_type, $link); break; case 'Monitoring': if ($news->getType() == 'C') { if ($news->getTotal() > 0) { if ($news->getTotal() > 1) { return sprintf("<div class='ico-type float-left'>%s</div><p>un utente si è aggiunto agli altri %d che stanno monitorando %s</p><p> %s", image_tag('/images/ico-type-monitoring.png', array('alt' => 'monitor')), $news->getTotal(), $item_type, $link); } else { return sprintf("<div class='ico-type float-left'>%s</div><p>un utente si è aggiunto a un altro che sta monitorando %s</p><p> %s", image_tag('/images/ico-type-monitoring.png', array('alt' => 'monitor')), $item_type, $link); } } else { return sprintf("<div class='ico-type float-left'>%s</div><p>un primo utente ha avviato il monitoraggio per %s</p><p> %s", image_tag('/images/ico-type-monitoring.png', array('alt' => 'monitor')), $item_type, $link); } } else { return sprintf("<div class='ico-type float-left'>%s</div><p>un utente ha smesso di monitorare %s</p><p> %s</p>", image_tag('/images/ico-type-monitoring.png', array('alt' => 'monitor')), $item_type, $link); } break; case 'sfVoting': if ($news->getType() == 'C') { if ($news->getVote() == 1) { $fav_contr = '<span style="color:green; font-weight:bold;">favorevoli</span>'; } else { $fav_contr = '<span style="color:red; font-weight:bold;">contrari</span>'; } if ($news->getTotal() > 0) { if ($news->getTotal() > 1) { return sprintf("<div class='ico-type float-left'>%s</div><p>un utente si è aggiunto agli altri %d %s al%s </p><p> %s</p>", image_tag('/images/ico-type-votazione-user.png', array('alt' => 'voto')), $news->getTotal(), $fav_contr, $item_type, $link); } else { if (substr_count($fav_contr, 'favorevoli') == 1) { $fav_contr = '<span style="color:green; font-weight:bold;">favorevole</span>'; } else { $fav_contr = '<span style="color:red; font-weight:bold;">contrario</span>'; } return sprintf("<div class='ico-type float-left'>%s</div><p>un utente si è aggiunto a un altro %s al%s</p><p>%s</p>", image_tag('/images/ico-type-votazione-user.png', array('alt' => 'voto')), $fav_contr, $item_type, $link); } } else { if (substr_count($fav_contr, 'favorevoli') == 1) { $fav_contr = '<span style="color:green; font-weight:bold;">favorevole</span>'; } else { $fav_contr = '<span style="color:red; font-weight:bold;">contrario</span>'; } return sprintf("<div class='ico-type float-left'>%s</div><p>un utente è %s al%s</p><p> %s</p>", image_tag('/images/ico-type-votazione-user.png', array('alt' => 'voto')), $fav_contr, $item_type, $link); } } else { return sprintf("<div class='ico-type float-left'>%s</div><p>utente ha ritirato il suo voto per %s</p><p> %s</p>", image_tag('/images/ico-type-votazione-user.png', array('alt' => 'voto')), $item_type, $link); } break; case 'nahoWikiRevision': return sprintf("<div class='ico-type float-left'>%s</div><p>%s ha modificato la descrizione wiki per %s</p><p> %s</p>", image_tag('/images/ico-type-descrizione.png', array('alt' => 'wiki!')), strtolower($news->getUsername()), $item_type, $link); break; } }
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() . ")");
/** * create as many news as the number of monitorable objects related to the * generating object * * @param BaseObject $object - the generator object * @param int $priority - the priority (it's an override if not null) * @param bool $isSuccNews - flag to generate a succNews (only called from batch script) * * @return int - the number of generated news * @author Guglielmo Celata **/ public function generateNews(BaseObject $object, $priority = null, $isSuccNews = null) { $n_gen_news = 0; // fetch the monitorable objects related to this generator $monitorable_objects = $this->getRelatedMonitorableObjects($object); foreach ($monitorable_objects as $obj) { // temporarily skip news generation when tagging emendamento if (get_class($object) == 'Tagging' && $object->getTaggableModel() == 'OppEmendamento') { continue; } $n = new News(); $n->setGeneratorModel(get_class($object)); $n->setGeneratorPrimaryKeys(serialize($this->getPrimaryKeysArray($object))); $n->setRelatedMonitorableModel(get_class($obj)); $n->setRelatedMonitorableId($obj->getPrimaryKey()); // the following methods store data related to the generating object in the cache // only data needed to sort, sum, average, or count, are cached if ($object->getCreatedAt() != null) { $n->setCreatedAt($object->getCreatedAt()); } $n->setDate($object->getNewsDate()); if (!is_null($priority)) { $n->setPriority($priority); } else { $n->setPriority($object->getNewsPriority()); } # TODO: spostare le eccezioni fuori dal plugin, in un contesto di applicazione // eccezioni // eccezione per non generare notizia alla presentazione di un decreto legge if ($object instanceof OppAtto && $object->getTipoAttoId() == 12) { continue; } if ($obj instanceof OppAtto) { $n->setDataPresentazioneAtto($obj->getDataPres()); $n->setTipoAttoId($obj->getOppTipoAtto()->getId()); $n->setRamoVotazione($obj->getRamo()); } // eccezione per modifica valore campo succ (opp_atto) if (isset($this->succNews) && $this->succNews || $isSuccNews) { $n->setSucc($object->getSucc()); $succ_obj = OppAttoPeer::retrieveByPK($object->getSucc()); $n->setDate($succ_obj->getDataPres('Y-m-d h:i:s')); } // eccezione per news generate dal tagging if ($object instanceof Tagging) { $n->setTagId($object->getTagId()); } $n->save(); $n_gen_news++; } return $n_gen_news; }
/** * Add one or more tags to different acts */ function run_opp_add_tags_to_acts($task, $args, $options) { static $loaded; // load application context if (!$loaded) { _loader(); } if (array_key_exists('tags', $options)) { $tags = $options['tags']; $tags_names = trim(strip_tags(getNamesFromValues($tags))); } else { throw new Exception("No tags specified, use --tags=TAG1,TAG2"); } echo "memory usage: " . memory_get_usage() . "\n"; $start_time = time(); $msg = sprintf("aggiunta dei tag %s\n", $tags); echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true)); // lettura argomenti da stdin (id degli atti da taggare) stream_set_blocking(STDIN, false); $stdin_atti = array(); while ($stdin = trim(fgets(STDIN))) { if ($stdin) { $stdin_atti[] = $stdin; } } if (count($stdin_atti)) { $msg = sprintf("%d atti letti da STDIN\n", count($stdin_atti)); echo pakeColor::colorize($msg, array('fg' => 'cyan', 'bold' => true)); } $atti = array_merge($args, $stdin_atti); foreach ($atti as $atto_id) { $msg = sprintf("atto ID: {$atto_id} ..."); echo pakeColor::colorize($msg, array('fg' => 'green', 'bold' => false)); $atto = OppAttoPeer::retrieveByPK($atto_id); if ($atto instanceof OppAtto) { $atto->addTag($tags_names); $atto->save(); $msg = sprintf("OK (%d)\n", memory_get_usage()); echo pakeColor::colorize($msg, array('fg' => 'green', 'bold' => true)); } else { $msg = sprintf("SKIP - Atto non in DB (%d)\n", memory_get_usage()); echo pakeColor::colorize($msg, array('fg' => 'red', 'bold' => true)); } unset($atto); } }
/** * Prepara uno o più atti, specificati dall'id nell'elenco argomenti per un test * Vengono rimossi tutti i dati accessori: * firme, assrgnazioni in commissione, documenti, tagging, esiti, interventi * Sono resettati il titolo e l'md5 * * Necessario per pulire un oggetto prima di un test di upgrade */ function run_opp_prepare_ddl_for_test($task, $args, $options) { static $loaded; // load application context if (!$loaded) { _loader(); } $dry_run = false; if (array_key_exists('dry-run', $options)) { $dry_run = true; } $con = Propel::getConnection(OppAttoPeer::DATABASE_NAME); echo "memory usage: " . memory_get_usage() . "\n"; $start_time = time(); try { $atti_rs = OppAttoPeer::getRSFromIDArray($args, $con); } catch (Exception $e) { throw new Exception("Specificare degli ID validi. \n" . $e); } $n_atti = $atti_rs->getRecordCount(); $cnt = 0; while ($atti_rs->next()) { $a = $atti_rs->getRow(); $atto_id = $a['id']; print "atto: {$atto_id}\n"; $atto = OppAttoPeer::retrieveByPK($atto_id); $atto->setTitolo(""); $atto->setMd5(""); $atto->save(); print " titolo e md5 annullat1\n"; # firme $items = $atto->getOppCaricaHasAttos(null, $con); $nitems = count($items); foreach ($items as $cnt => $item) { $item->delete($con); } print " {$nitems} firme rimosse\n"; # assegnazioni $items = $atto->getOppAttoHasSedes(null, $con); $nitems = count($items); foreach ($items as $cnt => $item) { $item->delete($con); } print " {$nitems} assegnazioni in commissione rimosse\n"; # tag (sf_tagging) $items = $atto->getTagsAsTaggingObjects(null, $con); $nitems = count($items); foreach ($items as $cnt => $item) { $item->delete($con); } print " {$nitems} tagging dell'atto rimossi\n"; # documenti $items = $atto->getOppDocumentos(null, $con); $nitems = count($items); foreach ($items as $cnt => $item) { $item->delete($con); } print " {$nitems} documenti allegati rimossi\n"; # iter $last_iter = $atto->getLastIter(); $last_iter->delete(); # relazioni $items = $atto->getRelazioni(); $nitems = count($items); foreach ($items as $cnt => $item) { $item->delete($con); } print " {$nitems} relazioni rimosse\n"; # esito sedute $items = $atto->getOppEsitoSedutas(); $nitems = count($items); foreach ($items as $cnt => $item) { $item->delete($con); } print " {$nitems} esiti rimossi\n"; # interventi $items = $atto->getOppInterventos(); $nitems = count($items); foreach ($items as $cnt => $item) { $item->delete($con); } print " {$nitems} interventi rimossi\n"; print "\n"; } $msg = sprintf("fine task\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)); }