/**
  * Returns an instance of sfSolr configured for this environment.
  */
 protected function getSolrInstance()
 {
     return deppOppSolr::getInstance();
 }
 /**
  * fetch and return user alerts data structure
  *
  * @param string $user 
  * @param string $max_results
  * @param string $force_last_alert - date to test as if it was last alerted on...
  * @return array of hashes ('term' => $term, 'results' => $results)
  * @author Guglielmo Celata
  */
 public static function getUserAlerts($user, $max_results = 10, $last_alert = null)
 {
     // arguments validation
     if (!$user instanceof OppUser) {
         throw new Exception("first argument must be of type user");
     }
     // if last alert is not passed, then fetch it, as not to break compatibility
     if (is_null($last_alert)) {
         $last_alert = $user->getLastAlertedAt("%Y-%m-%dT%H:%M:%SZ");
     }
     // loop to build static data-structure (self::$user_alerts)
     $user_alerts = array();
     $alert = OppAlertUserPeer::fetchUserAlerts($user);
     foreach ($alert as $alert) {
         $alert_term = $alert->getOppAlertTerm()->getTerm();
         if ($last_alert) {
             $fields_constraints = 'created_at_dt:' . sprintf("[%s TO NOW]", $last_alert);
         } else {
             $fields_constraints = 'created_at_dt:' . sprintf("[NOW-%dDAYS/SECOND TO NOW]", sfConfig::get('app_alert_default_days_back', 9));
         }
         $type_filters_s = OppAlertTermPeer::get_filters_labels($alert->getTypeFilters());
         if (!is_null($type_filters_s) && $type_filters_s != '') {
             $type_filters = explode("|", $alert->getTypeFilters());
         } else {
             $type_filters = array();
         }
         if (count($type_filters)) {
             $type_constraints = "";
             foreach ($type_filters as $cnt => $type_filter) {
                 $type_constraint = "";
                 switch ($type_filter) {
                     case 'politici':
                         $type_constraint = "(+sfl_model:OppPolitico)";
                         break;
                     case 'argomenti':
                         $type_constraint = "(+sfl_model:Tag)";
                         break;
                     case 'emendamenti':
                         $type_constraint = "(+sfl_model:OppEmendamento)";
                         break;
                     case 'votazioni':
                         $type_constraint = "(+sfl_model:OppVotazione)";
                         break;
                     case 'resoconti':
                         $type_constraint = "(+sfl_model:OppResoconto)";
                         break;
                     case 'disegni':
                     case 'decreti':
                     case 'decrleg':
                     case 'mozioni':
                     case 'interpellanze':
                     case 'interrogazioni':
                     case 'risoluzioni':
                     case 'odg':
                     case 'comunicazionigoverno':
                     case 'audizioni':
                         $type_constraint = "(+sfl_model:(OppAtto OppDocumento) +tipo_atto_s:{$type_filter})";
                         break;
                 }
                 $type_constraints .= ($cnt > 0 ? ' OR ' : '') . $type_constraint;
             }
             if ($type_constraints != "") {
                 $fields_constraints .= $fields_constraints != '' ? " AND ({$type_constraints})" : $type_constraints;
             }
         }
         $alert_results = deppOppSolr::getSfResults($alert_term, 0, $max_results, $fields_constraints, true);
         $user_alert = array('term' => $alert_term, 'type_filters' => $type_filters_s, 'results' => $alert_results);
         $user_alerts[] = $user_alert;
     }
     return $user_alerts;
 }
 /**                                                                                                       
  * get results using the standard query handler
  *                                                                                                        
  * @param string $querystring     
  * @param int    $offset
  * @param int    $limit                                                                        
  * @param mixed $fields_constraints  a string or a hash of the form $field => $constraint - ('model' => 'OppAtto') 
  * @param boolean $quotes_mode  specifies wether terms should be only searched as quoted text (for Alerts)
  * @param string $sort    
  * @return sfSolrPager                                                                                      
  * @throws sfSolrException     
  * @author Guglielmo Celata                                                                               
  */
 public static function getSfStandardResults($querystring, $offset = 0, $limit = 10, $fields_constraints = array(), $quotes_mode = false, $sort_specification = '')
 {
     sfLogger::getInstance()->info(sprintf("{deppOppSolr::getSfStandardResults} using Standard query type for %s", $querystring));
     $query = strip_tags(trim($querystring));
     // opzioni aggiuntive per la ricerca
     $query_options = array('fl' => '*,score');
     // aggiunge specifica del sort, se presente
     if ($sort_specification != '') {
         $query_options['sort'] = $sort_specification;
     }
     $q_first = "";
     $quoted = false;
     if (strpos($query, '"') === false) {
         // se utente non ha inserito esplicitamente le virgolette
         // crea stringhe quoted e q_first
         $words = split(" ", $query);
         $q_first = $words[0];
         $quoted = '"' . $query . '"';
     } else {
         // se utente ha inserito virgolette, entra in quotes_mode
         // con la stringa quoted uguale alla query
         $quotes_mode = true;
         $quoted = $query;
     }
     // definizione dei boost (spostare in config??)
     $nominativo_boost = 10.0;
     $triple_value_boost = 6.0;
     $titolo_boost = 6.0;
     $testo_boost = 1.5;
     $descrizioneWiki_boost = 1.0;
     $quoted_boost = 5.0;
     $qfirst_boost = 2.0;
     // compone la query ponderata
     $composed_query = "+(";
     if ($quoted) {
         $composed_query .= " nominativo: ({$quoted})^" . $nominativo_boost * $quoted_boost . " ";
         $composed_query .= " triple_value: ({$quoted})^" . $triple_value_boost * $quoted_boost . " ";
         $composed_query .= " titolo: ({$quoted})^" . $titolo_boost * $quoted_boost . " ";
         $composed_query .= " testo: ({$quoted})^" . $testo_boost * $quoted_boost . " ";
         $composed_query .= " descrizioneWiki: ({$quoted})^" . $descrizioneWiki_boost * $quoted_boost . " ";
     }
     // aggiunge ricerca per termini che iniziano come il primo termine e in OR su tutti i termini
     if ($quotes_mode == false) {
         if ($q_first) {
             $composed_query .= " nominativo: ({$q_first}*)^" . $nominativo_boost * $qfirst_boost . " ";
             $composed_query .= " triple_value: ({$q_first}*)^" . $triple_value_boost * $qfirst_boost . " ";
             $composed_query .= " titolo: ({$q_first}*)^" . $titolo_boost * $qfirst_boost . " ";
             $composed_query .= " testo: ({$q_first}*)^" . $testo_boost * $qfirst_boost . " ";
             $composed_query .= " descrizioneWiki: ({$q_first}*)^" . $descrizioneWiki_boost * $qfirst_boost . " ";
         }
         $composed_query .= " nominativo:(" . $query . ")^" . $nominativo_boost;
         $composed_query .= " triple_value:(" . $query . ")^" . $triple_value_boost;
         $composed_query .= " titolo:(" . $query . ")^" . $titolo_boost;
         $composed_query .= " testo:(" . $query . ")^" . $testo_boost;
         $composed_query .= " descrizioneWiki:(" . $query . ")^" . $descrizioneWiki_boost;
     }
     $composed_query .= ") ";
     // aggiunge i constraints (+ obbligatori)
     if (is_string($fields_constraints)) {
         $composed_query .= " " . $fields_constraints;
     } else {
         foreach ($fields_constraints as $field => $constraint) {
             $composed_query .= " +{$field}:{$constraint} ";
         }
     }
     # query debug
     if (sfConfig::get('solr_query_debug_level', 1) > 0) {
         // add debug query parameter
         $query_options['debugQuery'] = 'true';
     }
     // returns the pager or trap the exception
     try {
         $results = deppOppSolr::getInstance()->friendlySearch($composed_query, $offset, $limit, $query_options);
         return $results;
     } catch (Exception $e) {
         sfLogger::getInstance()->err('{sfSolrActions::getResults} ' . $e->getMessage());
         throw new sfSolrException($e->getMessage());
     }
 }
/**
* Fetch news and show them, for each users
*/
function run_opp_test_alerts($task, $args, $options)
{
    static $loaded;
    // load application context
    if (!$loaded) {
        define('SF_ROOT_DIR', sfConfig::get('sf_root_dir'));
        define('SF_APP', 'fe');
        define('SF_ENVIRONMENT', 'task');
        define('SF_DEBUG', true);
        require_once SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'apps' . DIRECTORY_SEPARATOR . SF_APP . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
        sfContext::getInstance();
        sfConfig::set('pake', true);
        error_reporting(E_ALL);
        $loaded = true;
    }
    $last_alert = null;
    if (array_key_exists('last-alert', $options)) {
        $last_alert = strftime("%Y-%m-%dT%H:%M:%SZ", strtotime($options['last-alert']));
    }
    // create a solr instance to read solr.yml config
    $solr_instance = deppOppSolr::getInstance();
    sfLoader::loadHelpers(array('Partial', 'sfSolr', 'DeppNews'));
    $start_time = microtime(true);
    echo pakeColor::colorize("Hi, there!\n", array('fg' => 'green', 'bold' => true));
    $c = new Criteria();
    $c->add(OppUserPeer::WANTS_OPP_ALERTS, 1);
    $c->add(OppUserPeer::IS_ACTIVE, 1);
    $c->add(OppUserPeer::N_ALERTS, 0, Criteria::GREATER_THAN);
    if (count($args)) {
        $c->add(OppUserPeer::ID, $args, Criteria::IN);
    }
    $users = OppUserPeer::doSelect($c);
    $n_users = count($users);
    echo pakeColor::colorize("{$n_users} users set alerts. Here are the notifications we would send them.\n", array('fg' => 'green'));
    foreach ($users as $cnt => $user) {
        $last_alert = $user->getLastAlertedAt("%Y-%m-%dT%H:%M:%SZ");
        echo "{$cnt}/{$n_users} ";
        opp_test_single_user_alerts($user, $last_alert);
    }
    $total_time = microtime(true) - $start_time;
    echo pakeColor::colorize('All done! ', array('fg' => 'green', 'bold' => true));
    echo 'Processed ';
    echo pakeColor::colorize(count($users), array('fg' => 'cyan'));
    echo ' users in ';
    echo pakeColor::colorize(sprintf("%f", $total_time), array('fg' => 'cyan'));
    echo " seconds\n";
}