Outputs csv of postal formatted addresses corresponding to an advanced query (#Closes...
[platal.git] / include / userset.inc.php
index 8c6040f..48c07b0 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /***************************************************************************
- *  Copyright (C) 2003-2009 Polytechnique.org                              *
+ *  Copyright (C) 2003-2010 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *                                                                         *
  *  This program is free software; you can redistribute it and/or modify   *
 
 class UserSet extends PlSet
 {
-    private $cond;
+    public function __construct(PlFilterCondition &$cond, $orders = null)
+    {
+        parent::__construct($cond, $orders);
+    }
 
-    public function __construct($cond = null)
+    protected function buildFilter(PlFilterCondition &$cond, $orders)
     {
-        $this->cond = new UFC_And();
-        if (!is_null($cond)) {
-            $this->cond->addChild($cond);
-        }
+        return new UserFilter($cond, $orders);
+    }
+}
+
+class ProfileSet extends PlSet
+{
+    public function __construct(PlFilterCondition &$cond, $orders = null)
+    {
+        parent::__construct($cond, $orders);
     }
 
-    public function &get($fields, $joins, $where, $groupby, $order, $limitcount = null, $limitfrom = null)
+    protected function buildFilter(PlFilterCondition &$cond, $orders)
     {
-        $uf = new UserFilter($this->cond);
-        $users = $uf->getUsers($limitcount, $limitfrom);
-        $this->count = $uf->getTotalCount();
-        return $users;
+        return new ProfileFilter($cond, $orders);
     }
 }
 
-class SearchSet extends UserSet
+class SearchSet extends ProfileSet
 {
     public  $advanced = false;
-    private $score = null;
-    private $order = null;
-    private $quick = false;
+    private $score    = null;
+    private $quick    = false;
+    private $valid    = true;
 
-    public function __construct($quick = false, $no_search = false, $join = '', $where = '')
+    public function __construct($quick = false, PlFilterCondition $cond = null)
     {
-        Platal::load('search', 'search.inc.php');
-        if ($no_search) {
+        if (isset($no_search)) {
             return;
         }
 
         $this->quick = $quick;
+
+        if (is_null($cond)) {
+            $conds = new PFC_And();
+        } else if ($cond instanceof PFC_And) {
+            $conds = $cond;
+        } else {
+            $conds = new PFC_And($cond);
+        }
+
         if ($quick) {
-            $this->getQuick($join, $where);
+            $this->getQuick($conds);
         } else {
-            $this->getAdvanced($join, $where);
+            $this->getAdvanced($conds);
         }
     }
 
-    private function getQuick($join, $where)
+    public function isValid()
+    {
+        return $this->valid;
+    }
+
+    /** Sets up the conditions for a Quick Search
+     * @param $conds Additional conds (as a PFC_And)
+     */
+    private function getQuick($conds)
     {
-        Platal::load('search', 'search.inc.php');
-        global $globals;
         if (!S::logged()) {
             Env::kill('with_soundex');
         }
-        $qSearch = new QuickSearch('quick');
-        $fields  = new SFieldGroup(true, array($qSearch));
-        if ($qSearch->isEmpty()) {
-            new ThrowError('Aucun critère de recherche n\'est spécifié.');
-        }
-        $this->score = $qSearch->get_score_statement();
-        $pwhere = $fields->get_where_statement();
-        if (trim($pwhere)) {
-            if (trim($where)) {
-                $where .= ' AND ';
-            }
-            $where .= $pwhere;
+
+        require_once 'ufbuilder.inc.php';
+        $ufb = new UFB_QuickSearch();
+
+        if (!$ufb->isValid()) {
+            $this->valid = false;
+            return;
         }
+
+        $ufc = $ufb->getUFC();
+        $conds->addChild($ufc);
+
+        $orders = $ufb->getOrders();
+
         if (S::logged() && Env::has('nonins')) {
-            if (trim($where)) {
-                $where .= ' AND ';
-            }
-            $where .= 'u.perms="pending" AND u.deces=0';
+            $conds = new PFC_And($conds,
+                new PFC_Not(new UFC_Dead()),
+                new PFC_Not(new UFC_Registered())
+            );
         }
-        parent::__construct($join . ' ' . $fields->get_select_statement(), $where);
 
-        $this->order = implode(',',array_filter(array($fields->get_order_statement(),
-                                                      'u.promo DESC, NomSortKey, prenom')));
+        parent::__construct($conds, $orders);
     }
 
-    private function getAdvanced($join, $where)
+    /** Sets up the conditions for an Advanced Search
+     * @param $conds Additional conds (as a PFC_And)
+     */
+    private function getAdvanced($conds)
     {
-        global $globals;
         $this->advanced = true;
-        $fields = new SFieldGroup(true, advancedSearchFromInput());
-        if ($fields->too_large()) {
-            new ThrowError('Recherche trop générale.');
-        }
-        parent::__construct(@$join . ' ' . $fields->get_select_statement(),
-                            @$where . ' ' . $fields->get_where_statement());
-        $this->order = implode(',',array_filter(array($fields->get_order_statement(),
-                                                      'promo DESC, NomSortKey, prenom')));
-    }
+        require_once 'ufbuilder.inc.php';
+        $ufb = new UFB_AdvancedSearch();
 
-    public function &get($fields, $joins, $where, $groupby, $order, $limitcount = null, $limitfrom = null)
-    {
-        if ($this->score) {
-            $fields .= ', ' . $this->score;
+        if (!$ufb->isValid()) {
+            $this->valid = false;
+            return;
         }
-        return parent::get($fields, $joins, $where, $groupby, $order, $limitcount, $limitfrom);
+
+        $ufc = $ufb->getUFC();
+        $conds->addChild($ufc);
+
+        $orders = $ufb->getOrders();
+
+        parent::__construct($conds, $orders);
     }
-}
 
-class ArraySet extends UserSet
-{
-    public function __construct(array $users)
+    /** Add a "rechercher=Chercher" field to the query to simulate the POST
+     * behaviour.
+     */
+    public function args()
     {
-        $where = $this->getUids($users);
-        if ($where) {
-            $where = "u.hruid IN ($where)";
-        } else {
-            $where = " 0 ";
+        $args = parent::args();
+        if (!isset($args['rechercher'])) {
+            $args['rechercher'] = 'Chercher';
         }
-        parent::__construct('', $where);
+        return $args;
     }
 
-    private function getUids(array $users)
+    protected function &getFilterResults(PlFilter &$pf, PlLimit $limit)
     {
-        $users = User::getBulkHruid($users, array('User', '_silent_user_callback'));
-        if (is_null($users)) {
-            return '';
-        }
-        return '\'' . implode('\', \'', $users) . '\'';
+        $profiles = $pf->getProfiles($limit, Profile::FETCH_MINIFICHES);
+        return $profiles;
     }
 }
 
-class MinificheView extends MultipageView
+/** Simple set based on an array of User objects
+ */
+class ArraySet extends ProfileSet
 {
-    public function __construct(PlSet &$set, $data, array $params)
+    public function __construct(array $users)
     {
-        require_once 'education.func.inc.php';
-        global $globals;
-        $this->entriesPerPage = $globals->search->per_page;
-        if (@$params['with_score']) {
-            $this->addSortKey('score', array('-score', '-date', '-d.promo', 'sort_name'), 'pertinence');
+        $hruids = User::getBulkHruid($users, array('User', '_silent_user_callback'));
+        if (is_null($hruids) || count($hruids) == 0) {
+            $cond = new PFC_False();
+        } else {
+            $cond = new UFC_Hruid($hruids);
         }
-        $this->addSortKey('name', array('sort_name'), 'nom');
-        $this->addSortKey('promo', array('-d.promo', 'sort_name'), 'promotion');
-        $this->addSortKey('date_mod', array('-date', '-d.promo', 'sort_name'), 'dernière modification');
-        parent::__construct($set, $data, $params);
-    }
-
-    public function bounds()
-    {
-        return null;
-    }
-
-    public function fields()
-    {
-        return null;
-    }
-
-    public function templateName()
-    {
-        return 'include/plview.minifiche.tpl';
+        parent::__construct($cond);
     }
 }
 
-class MentorView extends MultipageView
+/** A multipage view for profiles
+ * Allows the display of bounds when sorting by name or promo.
+ */
+abstract class ProfileView extends MultipageView
 {
-    public function __construct(PlSet &$set, $data, array $params)
+    protected function getBoundValue($obj)
     {
-        $this->entriesPerPage = 10;
-        $this->addSortKey('rand', array('RAND(' . S::i('uid') . ')'), 'aléatoirement');
-        $this->addSortKey('name', array('sort_name'), 'nom');
-        $this->addSortKey('promo', array('-d.promo', 'sort_name'), 'promotion');
-        $this->addSortKey('date_mod', array('-date', '-d.promo', 'sort_name'), 'dernière modification');
-        parent::__construct($set, $data, $params);
-    }
-
-    public function fields()
-    {
-        return "m.uid, d.promo, u.hruid,
-                m.expertise, mp.country, ms.sectorid, ms.subsectorid,
-                d.directory_name, d.sort_name";
-    }
-
-    public function joins()
-    {
-        return "INNER JOIN  profile_display AS d ON (d.pid = u.user_id)";
+        if ($obj instanceof Profile) {
+            switch ($this->bound_field) {
+            case 'name':
+                $name = $obj->name('%l');
+                return strtoupper($name);
+            case 'promo':
+                return $obj->promo();
+            default:
+                return null;
+            }
+        }
+        return null;
     }
 
     public function bounds()
@@ -201,7 +195,7 @@ class MentorView extends MultipageView
         $order = Env::v('order', $this->defaultkey);
         $show_bounds = 0;
         if (($order == "name") || ($order == "-name")) {
-            $this->bound_field = "nom";
+            $this->bound_field = "name";
             $show_bounds = 1;
         } elseif (($order == "promo") || ($order == "-promo")) {
             $this->bound_field = "promo";
@@ -212,53 +206,115 @@ class MentorView extends MultipageView
         }
         return $show_bounds;
     }
-
-    public function templateName()
-    {
-        return 'include/plview.referent.tpl';
-    }
 }
 
-class TrombiView extends MultipageView
+/** An extended multipage view for profiles, as minifiches.
+ * Allows to sort by:
+ * - score (for a search query)
+ * - name
+ * - promo
+ * - latest modification
+ *
+ * Paramaters for this view are:
+ * - with_score: whether to allow ordering by score (set only for a quick search)
+ * - starts_with: show only names beginning with the given letter
+ */
+class MinificheView extends ProfileView
 {
-    public function __construct(PlSet &$set, $data, array $params)
+    public function __construct(PlSet &$set, array $params)
     {
-        $this->entriesPerPage = 24;
-        $this->order = explode(',', Env::v('order', 'sort_name'));
+        global $globals;
+        $this->entriesPerPage = $globals->search->per_page;
         if (@$params['with_score']) {
-            $this->addSortKey('score', array('-score', '-watch_last', '-d.promo', 'sort_name'), 'pertinence');
+            $this->addSort(new PlViewOrder('score', array(
+                    new UFO_Score(true),
+                    new UFO_ProfileUpdate(true),
+                    new UFO_Promo(UserFilter::DISPLAY, true),
+                    new UFO_Name(Profile::DN_SORT),
+                ), 'pertinence'));
         }
-        $this->addSortKey('name', array('sort_name'), 'nom');
-        $this->addSortKey('promo', array('-d.promo', 'sort_name'), 'promotion');
-        parent::__construct($set, $data, $params);
+        $this->addSort(new PlViewOrder(
+                            'name',
+                            array(new UFO_Name(Profile::DN_SORT)),
+                            'nom'));
+        $this->addSort(new PlViewOrder('promo', array(
+                    new UFO_Promo(UserFilter::DISPLAY, true),
+                    new UFO_Name(Profile::DN_SORT),
+                ), 'promotion'));
+        $this->addSort(new PlViewOrder('date_mod', array(
+                    new UFO_ProfileUpdate(true),
+                    new UFO_Promo(UserFilter::DISPLAY, true),
+                    new UFO_Name(Profile::DN_SORT),
+                ), 'dernière modification'));
+        parent::__construct($set, $params);
     }
 
-    public function fields()
+    public function apply(PlPage &$page)
     {
-        return "u.user_id, d.directory_name, d.sort_name, u.promo, d.promo, u.hruid ";
+        if (array_key_exists('starts_with', $this->params)
+            && $this->params['starts_with'] != ""
+            && $this->params['starts_with'] != null) {
+
+            $this->set->addCond(
+                new UFC_Name(Profile::LASTNAME,
+                    $this->params['starts_with'], UFC_Name::PREFIX)
+            );
+        }
+        return parent::apply($page);
     }
 
-    public function joins()
+    public function templateName()
     {
-        return "INNER JOIN  photo           AS p  ON (p.uid = u.user_id)
-                INNER JOIN  profile_display AS d  ON (d.pid = u.user_id)";
+        return 'include/plview.minifiche.tpl';
     }
+}
 
-    public function bounds()
+class MentorView extends ProfileView
+{
+    public function __construct(PlSet &$set, array $params)
     {
-        $order = Env::v('order', $this->defaultkey);
-        $show_bounds = 0;
-        if (($order == "name") || ($order == "-name")) {
-            $this->bound_field = "nom";
-            $show_bounds = 1;
-        } elseif (($order == "promo") || ($order == "-promo")) {
-            $this->bound_field = "promo";
-            $show_bounds = -1;
-        }
-        if ($order{0} == '-') {
-            $show_bounds = -$show_bounds;
+        $this->entriesPerPage = 10;
+        $this->addSort(new PlViewOrder('rand', array(new PFO_Random(S::i('uid'))), 'aléatoirement'));
+        $this->addSort(new PlViewOrder('name', array(new UFO_Name(Profile::DN_SORT)), 'nom'));
+        $this->addSort(new PlViewOrder('promo', array(
+                    new UFO_Promo(UserFilter::DISPLAY, true),
+                    new UFO_Name(Profile::DN_SORT),
+                ), 'promotion'));
+        $this->addSort(new PlViewOrder('date_mod', array(
+                    new UFO_ProfileUpdate(true),
+                    new UFO_Promo(UserFilter::DISPLAY, true),
+                    new UFO_Name(Profile::DN_SORT),
+                ), 'dernière modification'));
+        parent::__construct($set, $params);
+    }
+
+    public function templateName()
+    {
+        return 'include/plview.referent.tpl';
+    }
+}
+
+class TrombiView extends ProfileView
+{
+    public function __construct(PlSet &$set, array $params)
+    {
+        $this->entriesPerPage = 24;
+        $this->defaultkey = 'name';
+        if (@$params['with_score']) {
+            $this->addSort(new PlViewOrder('score', array(
+                            new UFO_Score(true),
+                            new UFO_ProfileUpdate(true),
+                            new UFO_Promo(UserFilter::DISPLAY, true),
+                            new UFO_Name(Profile::DN_SORT),
+            ), 'pertinence'));
         }
-        return $show_bounds;
+        $set->addCond(new UFC_Photo());
+        $this->addSort(new PlViewOrder('name', array(new UFO_Name(Profile::DN_SORT)), 'nom'));
+        $this->addSort(new PlViewOrder('promo', array(
+                        new UFO_Promo(UserFilter::DISPLAY, true),
+                        new UFO_Name(Profile::DN_SORT),
+                    ), 'promotion'));
+        parent::__construct($set, $params);
     }
 
     public function templateName()
@@ -278,45 +334,57 @@ class TrombiView extends MultipageView
 
 class GadgetView implements PlView
 {
-    public function __construct(PlSet &$set, $data, array $params)
+    public function __construct(PlSet &$set, array $params)
     {
         $this->set =& $set;
     }
 
-    public function fields()
+    public function apply(PlPage &$page)
     {
-        return "u.user_id AS id, u.*," .
-               "u.perms != 'pending' AS inscrit,
-                u.perms != 'pending' AS wasinscrit,
-                u.deces != 0 AS dcd, u.deces,
-                FIND_IN_SET('femme', u.flags) AS sexe,
-                " // adr.city, gr.name AS region
-              . "gc.iso_3166_1_a2, gc.countryFR AS countrytxt" .
-                (S::logged() ? ", c.contact AS contact" : '');
+        $page->assign_by_ref('set', $this->set->get(new PlLimit(5, 0)));
     }
 
-    public function joins()
+    public function args()
     {
-        return "LEFT JOIN  profile_addresses          AS adr ON (u.user_id = adr.pid AND
-                                                                 FIND_IN_SET('current', adr.flags)"
-                                                                . (S::logged() ? "" : "AND adr.pub = 'public'") . ")
-                LEFT JOIN  geoloc_countries           AS gc  ON (adr.countryId = gc.iso_3166_1_a2)
-                LEFT JOIN  geoloc_administrativeareas AS gr  ON (adr.countryId = gr.country
-                                                                 AND adr.administrativeAreaId = gr.id)
-               " . (S::logged() ?
-               "LEFT JOIN  contacts                   AS c   ON (c.contact = u.user_id
-                                                                 AND c.uid = " . S::v('uid') . ")" : "");
+        return null;
+    }
+}
+
+class AddressesView implements PlView
+{
+    private $set;
+
+    public function __construct(PlSet &$set, array $params)
+    {
+        $this->set =& $set;
     }
 
     public function apply(PlPage &$page)
     {
-        $page->assign_by_ref('set',
-          $this->set->get($this->fields(), $this->joins(), null, null, null, 5, 0));
+        $res = $this->set->get(new PlLimit());
+        $visibility = new ProfileVisibility(ProfileVisibility::VIS_AX);
+        pl_content_headers('text/x-csv');
+
+        $csv = fopen('php://output', 'w');
+        fputcsv($csv, array('adresses'), ';');
+        foreach ($res as $profile) {
+            $addresses = $profile->getAddresses(Profile::ADDRESS_POSTAL);
+            if (!empty($addresses)) {
+                foreach ($addresses as $address) {
+                    if ($visibility->isVisible($address->pub)) {
+                        fputcsv($csv, array($profile->public_name, $address->postalText), ';');
+                        break;
+                    }
+                }
+            }
+        }
+        fclose($csv);
+        exit();
     }
 
     public function args()
     {
-        return null;
+        return $this->set->args();
     }
 }