================================================================================
+VERSION 1.1.0 XX XX XXXX
+
+================================================================================
VERSION 1.0.2 XX XX XXXX
================================================================================
##
## jquery
##
-JQUERY_VERSION=1.4.2
+JQUERY_VERSION=1.4.3
JQUERY_PLUGINS=color form
JQUERY_PLUGINS_PATHES=$(addprefix htdocs/javascript/jquery.,$(addsuffix .js,$(JQUERY_PLUGINS)))
-JQUERY_UI_VERSION=1.6
-JQUERY_UI=core tabs
+JQUERY_UI_VERSION=1.8.5
+JQUERY_UI=core tabs widget
JQUERY_UI_PATHES=$(addprefix htdocs/javascript/jquery.ui.,$(addsuffix .js,$(JQUERY_UI)))
JSTREE_VERSION=1.0rc2
@-rm htdocs/javascript/jquery.ui*.$*.js
@$(download)
-htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).%.js: DOWNLOAD_SRC = http://jquery-ui.googlecode.com/svn/tags/$(JQUERY_UI_VERSION)/ui/ui.$*.js
+htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).%.js: DOWNLOAD_SRC = http://jquery-ui.googlecode.com/svn/tags/$(JQUERY_UI_VERSION)/ui/minified/jquery.ui.$*.min.js
htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).%.js:
@$(download)
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
***************************************************************************/
+ini_set('memory_limit', '64M');
ini_set('include_path', dirname(__FILE__) . '/../core/include:'
. dirname(__FILE__) . '/../include:'
. dirname(__FILE__) . '/../core/classes:'
new Xorg('core');
+// Do not store backtraces
+Platal::globals()->debug = 0;
+
// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
?>
}
}
-function info($sql, $comment = '', $onlyCounts = false) {
+function info($sql, $comment = '', $onlyCounts = false)
+{
global $opt_verbose;
if ($opt_verbose) {
if ($onlyCounts) {
}
}
+function infoCountEmpty($table, $field, $nonEmpty = false)
+{
+ $sql = "SELECT COUNT(*) FROM $table";
+ if ($nonEmpty) {
+ $sql .= " WHERE $field IS NOT NULL OR $field != ''";
+ $negation = ' non';
+ } else {
+ $sql .= " WHERE $field IS NULL OR $field = ''";
+ $negation = '';
+ }
+ $comment = "Nombre de champs '$field'$negation vides dans la table '$table'.";
+ info($sql, $comment, true);
+}
+
/* Parses options. */
$opts = Console_GetOpt::getopt($argv, 'v');
$opt_verbose = false;
WHERE a.type = 'a_vie'",
"Donne la liste des homonymes qui ont un alias égal à leur loginbis depuis plus d'un mois, il est temps de supprimer leur alias.");
+// Counts empty profile fields that should never be empty.
+infoCountEmpty('profile_addresses', 'text');
+infoCountEmpty('profile_addresses', 'postalText');
+infoCountEmpty('profile_education', 'eduid');
+infoCountEmpty('profile_education', 'degreeid');
+infoCountEmpty('profile_job', 'jobid');
+infoCountEmpty('profile_mentor', 'expertise');
+infoCountEmpty('profile_networking', 'address');
+infoCountEmpty('profile_phones', 'search_tel');
+infoCountEmpty('profile_phones', 'display_tel');
+
// XXX: counts the number of remaining issues due to the merge (to be removed once all merge related issues have been fixed)
-info('SELECT COUNT(*)
- FROM profile_merge_issues
- WHERE issues IS NULL OR issues = \'\'',
- 'Dénombre les erreurs dues à la fusion restantes.',
- true);
+infoCountEmpty('profile_merge_issues', 'issues', true);
// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
?>
require './connect.db.inc.php';
-ini_set('memory_limit', '16M');
-$globals->debug = 0; // Do not store backtraces
-
$res = XDB::iterRow('SELECT pid
FROM profiles');
$i = 0;
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
***************************************************************************/
-
-/******************
- * CONDITIONS
- ******************/
-
-// {{{ interface UserFilterCondition
-/** This interface describe objects which filter users based
- * on various parameters.
- * The parameters of the filter must be given to the constructor.
- * The buildCondition function is called by UserFilter when
- * actually building the query. That function must call
- * $uf->addWheteverFilter so that the UserFilter makes
- * adequate joins. It must return the 'WHERE' condition to use
- * with the filter.
- */
-interface UserFilterCondition extends PlFilterCondition
-{
-}
-// }}}
-
-// {{{ class UFC_HasProfile
-/** Filters users who have a profile
- */
-class UFC_HasProfile implements UserFilterCondition
-{
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return '$PID IS NOT NULL';
- }
-}
-// }}}
-
-// {{{ class UFC_AccountType
-/** Filters users who have one of the given account types
- */
-class UFC_AccountType implements UserFilterCondition
-{
- private $types;
-
- public function __construct()
- {
- $this->types = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireAccounts();
- return XDB::format('a.type IN {?}', $this->types);
- }
-}
-// }}}
-
-// {{{ class UFC_AccountPerm
-/** Filters users who have one of the given permissions
- */
-class UFC_AccountPerm implements UserFilterCondition
-{
- private $perms;
-
- public function __construct()
- {
- $this->perms = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requirePerms();
- $conds = array();
- foreach ($this->perms as $perm) {
- $conds[] = XDB::format('FIND_IN_SET({?}, IF(a.user_perms IS NULL, at.perms,
- CONCAT(at.perms, \',\', a.user_perms)))',
- $perm);
- }
- if (empty($conds)) {
- return self::COND_TRUE;
- } else {
- return implode(' OR ', $conds);
- }
- }
-}
-// }}}
-
-// {{{ class UFC_Hruid
-/** Filters users based on their hruid
- * @param $val Either an hruid, or a list of those
- */
-class UFC_Hruid implements UserFilterCondition
-{
- private $hruids;
-
- public function __construct()
- {
- $this->hruids = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireAccounts();
- return XDB::format('a.hruid IN {?}', $this->hruids);
- }
-}
-// }}}
-
-// {{{ class UFC_Hrpid
-/** Filters users based on the hrpid of their profiles
- * @param $val Either an hrpid, or a list of those
- */
-class UFC_Hrpid implements UserFilterCondition
-{
- private $hrpids;
-
- public function __construct()
- {
- $this->hrpids = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return XDB::format('p.hrpid IN {?}', $this->hrpids);
- }
-}
-// }}}
-
-// {{{ class UFC_Ip
-/** Filters users based on one of their last IPs
- * @param $ip IP from which connection are checked
- */
-class UFC_Ip implements UserFilterCondition
-{
- private $ip;
-
- public function __construct($ip)
- {
- $this->ip = $ip;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addLoggerFilter();
- $ip = ip_to_uint($this->ip);
- return XDB::format($sub . '.ip = {?} OR ' . $sub . '.forward_ip = {?}', $ip, $ip);
- }
-}
-// }}}
-
-// {{{ class UFC_Comment
-class UFC_Comment implements UserFilterCondition
-{
- private $text;
-
- public function __construct($text)
- {
- $this->text = $text;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return $uf->getVisibilityCondition('p.freetext_pub') . ' AND p.freetext ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->text);
- }
-}
-// }}}
-
-// {{{ class UFC_Promo
-/** Filters users based on promotion
- * @param $comparison Comparison operator (>, =, ...)
- * @param $grade Formation on which to restrict, UserFilter::DISPLAY for "any formation"
- * @param $promo Promotion on which the filter is based
- */
-class UFC_Promo implements UserFilterCondition
-{
-
- private $grade;
- private $promo;
- private $comparison;
-
- public function __construct($comparison, $grade, $promo)
- {
- $this->grade = $grade;
- $this->comparison = $comparison;
- $this->promo = $promo;
- if ($this->grade != UserFilter::DISPLAY) {
- UserFilter::assertGrade($this->grade);
- }
- if ($this->grade == UserFilter::DISPLAY && $this->comparison != '=') {
- // XXX: we might try to guess the grade from the first char of the promo and forbid only '<= 2004', but allow '<= X2004'
- Platal::page()->killError("Il n'est pas possible d'appliquer la comparaison '" . $this->comparison . "' aux promotions sans spécifier de formation (X/M/D)");
- }
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- if ($this->grade == UserFilter::DISPLAY) {
- $sub = $uf->addDisplayFilter();
- return XDB::format('pd' . $sub . '.promo ' . $this->comparison . ' {?}', $this->promo);
- } else {
- $sub = $uf->addEducationFilter(true, $this->grade);
- $field = 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
- return $field . ' IS NOT NULL AND ' . $field . ' ' . $this->comparison . ' ' . XDB::format('{?}', $this->promo);
- }
- }
-}
-// }}}
-
-// {{{ class UFC_SchoolId
-/** Filters users based on their shoold identifier
- * @param type Parameter type (Xorg, AX, School)
- * @param value School id value
- */
-class UFC_SchoolId implements UserFilterCondition
-{
- const AX = 'ax';
- const Xorg = 'xorg';
- const School = 'school';
-
- private $type;
- private $id;
-
- static public function assertType($type)
- {
- if ($type != self::AX && $type != self::Xorg && $type != self::School) {
- Platal::page()->killError("Type de matricule invalide: $type");
- }
- }
-
- public function __construct($type, $id)
- {
- $this->type = $type;
- $this->id = $id;
- self::assertType($type);
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireProfiles();
- $id = $this->id;
- $type = $this->type;
- if ($type == self::School) {
- $type = self::Xorg;
- $id = Profile::getXorgId($id);
- }
- return XDB::format('p.' . $type . '_id = {?}', $id);
- }
-}
-// }}}
-
-// {{{ class UFC_EducationSchool
-/** Filters users by formation
- * @param $val The formation to search (either ID or array of IDs)
- */
-class UFC_EducationSchool implements UserFilterCondition
-{
- private $val;
-
- public function __construct()
- {
- $this->val = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addEducationFilter();
- return XDB::format('pe' . $sub . '.eduid IN {?}', $this->val);
- }
-}
-// }}}
-
-// {{{ class UFC_EducationDegree
-class UFC_EducationDegree implements UserFilterCondition
-{
- private $diploma;
-
- public function __construct()
- {
- $this->diploma = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addEducationFilter();
- return XDB::format('pe' . $sub . '.degreeid IN {?}', $this->diploma);
- }
-}
-// }}}
-
-// {{{ class UFC_EducationField
-class UFC_EducationField implements UserFilterCondition
-{
- private $val;
-
- public function __construct()
- {
- $this->val = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addEducationFilter();
- return XDB::format('pe' . $sub . '.fieldid IN {?}', $this->val);
- }
-}
-// }}}
-
-// {{{ class UFC_Name
-/** Filters users based on name
- * @param $type Type of name field on which filtering is done (firstname, lastname...)
- * @param $text Text on which to filter
- * @param $mode Flag indicating search type (prefix, suffix, with particule...)
- */
-class UFC_Name implements UserFilterCondition
-{
- const EXACT = XDB::WILDCARD_EXACT; // 0x000
- const PREFIX = XDB::WILDCARD_PREFIX; // 0x001
- const SUFFIX = XDB::WILDCARD_SUFFIX; // 0x002
- const CONTAINS = XDB::WILDCARD_CONTAINS; // 0x003
- const PARTICLE = 0x004;
- const VARIANTS = 0x008;
-
- private $type;
- private $text;
- private $mode;
-
- public function __construct($type, $text, $mode)
- {
- $this->type = $type;
- $this->text = $text;
- $this->mode = $mode;
- }
-
- private function buildNameQuery($type, $variant, $where, UserFilter &$uf)
- {
- $sub = $uf->addNameFilter($type, $variant);
- return str_replace('$ME', 'pn' . $sub, $where);
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $left = '$ME.name';
- if (($this->mode & self::PARTICLE) == self::PARTICLE) {
- $left = 'CONCAT($ME.particle, \' \', $ME.name)';
- }
- $right = XDB::formatWildcards($this->mode & self::CONTAINS, $this->text);
-
- $cond = $left . $right;
- $conds = array($this->buildNameQuery($this->type, null, $cond, $uf));
- if (($this->mode & self::VARIANTS) != 0 && isset(Profile::$name_variants[$this->type])) {
- foreach (Profile::$name_variants[$this->type] as $var) {
- $conds[] = $this->buildNameQuery($this->type, $var, $cond, $uf);
- }
- }
- return implode(' OR ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_NameTokens
-/** Selects users based on tokens in their name (for quicksearch)
- * @param $tokens An array of tokens to search
- * @param $flags Flags the tokens must have (e.g 'public' for public search)
- * @param $soundex (bool) Whether those tokens are fulltext or soundex
- */
-class UFC_NameTokens implements UserFilterCondition
-{
- /* Flags */
- const FLAG_PUBLIC = 'public';
-
- private $tokens;
- private $flags;
- private $soundex;
- private $exact;
-
- public function __construct($tokens, $flags = array(), $soundex = false, $exact = false)
- {
- if (is_array($tokens)) {
- $this->tokens = $tokens;
- } else {
- $this->tokens = array($tokens);
- }
- if (is_array($flags)) {
- $this->flags = $flags;
- } else {
- $this->flags = array($flags);
- }
- $this->soundex = $soundex;
- $this->exact = $exact;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $conds = array();
- foreach ($this->tokens as $i => $token) {
- $sub = $uf->addNameTokensFilter($token);
- if ($this->soundex) {
- $c = XDB::format($sub . '.soundex = {?}', soundex_fr($token));
- } else if ($this->exact) {
- $c = XDB::format($sub . '.token = {?}', $token);
- } else {
- $c = $sub . '.token ' . XDB::formatWildcards(XDB::WILDCARD_PREFIX, $token);
- }
- if ($this->flags != null) {
- $c .= XDB::format(' AND ' . $sub . '.flags IN {?}', $this->flags);
- }
- $conds[] = $c;
- }
-
- return implode(' AND ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_Nationality
-class UFC_Nationality implements UserFilterCondition
-{
- private $val;
-
- public function __construct()
- {
- $this->val = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireProfiles();
- $nat = XDB::formatArray($this->val);
- $conds = array(
- 'p.nationality1 IN ' . $nat,
- 'p.nationality2 IN ' . $nat,
- 'p.nationality3 IN ' . $nat,
- );
- return implode(' OR ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_Dead
-/** Filters users based on death date
- * @param $comparison Comparison operator
- * @param $date Date to which death date should be compared (DateTime object, string or timestamp)
- */
-class UFC_Dead implements UserFilterCondition
-{
- private $comparison;
- private $date;
-
- public function __construct($comparison = null, $date = null)
- {
- $this->comparison = $comparison;
- $this->date = make_datetime($date);
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireProfiles();
- $str = 'p.deathdate IS NOT NULL';
- if (!is_null($this->comparison)) {
- $str .= ' AND p.deathdate ' . $this->comparison . ' ' . XDB::format('{?}', $this->date->format('Y-m-d'));
- }
- return $str;
- }
-}
-// }}}
-
-// {{{ class UFC_Registered
-/** Filters users based on registration state
- * @param $active Whether we want to use only "active" users (i.e with a valid redirection)
- * @param $comparison Comparison operator
- * @param $date Date to which users registration date should be compared
- */
-class UFC_Registered implements UserFilterCondition
-{
- private $active;
- private $comparison;
- private $date;
-
- public function __construct($active = false, $comparison = null, $date = null)
- {
- $this->active = $active;
- $this->comparison = $comparison;
- $this->date = make_datetime($date);
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireAccounts();
- if ($this->active) {
- $date = '$UID IS NOT NULL AND a.state = \'active\'';
- } else {
- $date = '$UID IS NOT NULL AND a.state != \'pending\'';
- }
- if (!is_null($this->comparison)) {
- $date .= ' AND a.registration_date != \'0000-00-00 00:00:00\' AND a.registration_date ' . $this->comparison . ' ' . XDB::format('{?}', $this->date->format('Y-m-d'));
- }
- return $date;
- }
-}
-// }}}
-
-// {{{ class UFC_ProfileUpdated
-/** Filters users based on profile update date
- * @param $comparison Comparison operator
- * @param $date Date to which profile update date must be compared
- */
-class UFC_ProfileUpdated implements UserFilterCondition
-{
- private $comparison;
- private $date;
-
- public function __construct($comparison = null, $date = null)
- {
- $this->comparison = $comparison;
- $this->date = $date;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return 'p.last_change ' . $this->comparison . XDB::format(' {?}', date('Y-m-d H:i:s', $this->date));
- }
-}
-// }}}
-
-// {{{ class UFC_Birthday
-/** Filters users based on next birthday date
- * @param $comparison Comparison operator
- * @param $date Date to which users next birthday date should be compared
- */
-class UFC_Birthday implements UserFilterCondition
-{
- private $comparison;
- private $date;
-
- public function __construct($comparison = null, $date = null)
- {
- $this->comparison = $comparison;
- $this->date = $date;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return 'p.next_birthday ' . $this->comparison . XDB::format(' {?}', date('Y-m-d', $this->date));
- }
-}
-// }}}
-
-// {{{ class UFC_Sex
-/** Filters users based on sex
- * @parm $sex One of User::GENDER_MALE or User::GENDER_FEMALE, for selecting users
- */
-class UFC_Sex implements UserFilterCondition
-{
- private $sex;
- public function __construct($sex)
- {
- $this->sex = $sex;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- if ($this->sex != User::GENDER_MALE && $this->sex != User::GENDER_FEMALE) {
- return self::COND_FALSE;
- } else {
- $uf->requireProfiles();
- return XDB::format('p.sex = {?}', $this->sex == User::GENDER_FEMALE ? 'female' : 'male');
- }
- }
-}
-// }}}
-
-// {{{ class UFC_Group
-/** Filters users based on group membership
- * @param $group Group whose members we are selecting
- * @param $anim Whether to restrict selection to animators of that group
- */
-class UFC_Group implements UserFilterCondition
-{
- private $group;
- private $anim;
- public function __construct($group, $anim = false)
- {
- $this->group = $group;
- $this->anim = $anim;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- // Groups have AX visibility.
- if ($uf->getVisibilityLevel() == ProfileVisibility::VIS_PUBLIC) {
- return self::COND_TRUE;
- }
- $sub = $uf->addGroupFilter($this->group);
- $where = 'gpm' . $sub . '.perms IS NOT NULL';
- if ($this->anim) {
- $where .= ' AND gpm' . $sub . '.perms = \'admin\'';
- }
- return $where;
- }
-}
-// }}}
-
-// {{{ class UFC_Binet
-/** Selects users based on their belonging to a given (list of) binet
- * @param $binet either a binet_id or an array of binet_ids
- */
-class UFC_Binet implements UserFilterCondition
-{
- private $val;
-
- public function __construct()
- {
- $this->val = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- // Binets are private.
- if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
- return self::CONF_TRUE;
- }
- $sub = $uf->addBinetsFilter();
- return XDB::format($sub . '.binet_id IN {?}', $this->val);
- }
-}
-// }}}
-
-// {{{ class UFC_Section
-/** Selects users based on section
- * @param $section ID of the section
- */
-class UFC_Section implements UserFilterCondition
-{
- private $section;
-
- public function __construct()
- {
- $this->section = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- // Sections are private.
- if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
- return self::CONF_TRUE;
- }
- $uf->requireProfiles();
- return XDB::format('p.section IN {?}', $this->section);
- }
-}
-// }}}
-
-// {{{ class UFC_Email
-/** Filters users based on an email or a list of emails
- * @param $emails List of emails whose owner must be selected
- */
-class UFC_Email implements UserFilterCondition
-{
- private $emails;
- public function __construct()
- {
- $this->emails = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $foreign = array();
- $virtual = array();
- $aliases = array();
- $cond = array();
-
- if (count($this->emails) == 0) {
- return PlFilterCondition::COND_TRUE;
- }
-
- foreach ($this->emails as $entry) {
- if (User::isForeignEmailAddress($entry)) {
- $foreign[] = $entry;
- } else if (User::isVirtualEmailAddress($entry)) {
- $virtual[] = $entry;
- } else {
- @list($user, $domain) = explode('@', $entry);
- $aliases[] = $user;
- }
- }
-
- if (count($foreign) > 0) {
- $sub = $uf->addEmailRedirectFilter($foreign);
- $cond[] = XDB::format('e' . $sub . '.email IS NOT NULL OR a.email IN {?}', $foreign);
- }
- if (count($virtual) > 0) {
- $sub = $uf->addVirtualEmailFilter($virtual);
- $cond[] = 'vr' . $sub . '.redirect IS NOT NULL';
- }
- if (count($aliases) > 0) {
- $sub = $uf->addAliasFilter($aliases);
- $cond[] = 'al' . $sub . '.alias IS NOT NULL';
- }
- return '(' . implode(') OR (', $cond) . ')';
- }
-}
-// }}}
-
-// {{{ class UFC_Address
-abstract class UFC_Address implements UserFilterCondition
-{
- /** Valid address type ('hq' is reserved for company addresses)
- */
- const TYPE_HOME = 1;
- const TYPE_PRO = 2;
- const TYPE_ANY = 3;
-
- /** Text for these types
- */
- protected static $typetexts = array(
- self::TYPE_HOME => 'home',
- self::TYPE_PRO => 'pro',
- );
-
- protected $type;
-
- /** Flags for addresses
- */
- const FLAG_CURRENT = 0x0001;
- const FLAG_TEMP = 0x0002;
- const FLAG_SECOND = 0x0004;
- const FLAG_MAIL = 0x0008;
- const FLAG_CEDEX = 0x0010;
-
- // Binary OR of those flags
- const FLAG_ANY = 0x001F;
-
- /** Text of these flags
- */
- protected static $flagtexts = array(
- self::FLAG_CURRENT => 'current',
- self::FLAG_TEMP => 'temporary',
- self::FLAG_SECOND => 'secondary',
- self::FLAG_MAIL => 'mail',
- self::FLAG_CEDEX => 'cedex',
- );
-
- protected $flags;
-
- public function __construct($type = null, $flags = null)
- {
- $this->type = $type;
- $this->flags = $flags;
- }
-
- protected function initConds($sub, $vis_cond)
- {
- $conds = array($vis_cond);
-
- $types = array();
- foreach (self::$typetexts as $flag => $type) {
- if ($flag & $this->type) {
- $types[] = $type;
- }
- }
- if (count($types)) {
- $conds[] = XDB::format($sub . '.type IN {?}', $types);
- }
-
- if ($this->flags != self::FLAG_ANY) {
- foreach(self::$flagtexts as $flag => $text) {
- if ($flag & $this->flags) {
- $conds[] = 'FIND_IN_SET(' . XDB::format('{?}', $text) . ', ' . $sub . '.flags)';
- }
- }
- }
- return $conds;
- }
-
-}
-// }}}
-
-// {{{ class UFC_AddressText
-/** Select users based on their address, using full text search
- * @param $text Text for filter in fulltext search
- * @param $textSearchMode Mode for search (one of XDB::WILDCARD_*)
- * @param $type Filter on address type
- * @param $flags Filter on address flags
- * @param $country Filter on address country
- * @param $locality Filter on address locality
- */
-class UFC_AddressText extends UFC_Address
-{
-
- private $text;
- private $textSearchMode;
-
- public function __construct($text = null, $textSearchMode = XDB::WILDCARD_CONTAINS,
- $type = null, $flags = self::FLAG_ANY, $country = null, $locality = null)
- {
- parent::__construct($type, $flags);
- $this->text = $text;
- $this->textSearchMode = $textSearchMode;
- $this->country = $country;
- $this->locality = $locality;
- }
-
- private function mkMatch($txt)
- {
- return XDB::formatWildcards($this->textSearchMode, $txt);
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addAddressFilter();
- $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
- if ($this->text != null) {
- $conds[] = $sub . '.text' . $this->mkMatch($this->text);
- }
-
- if ($this->country != null) {
- $subc = $uf->addAddressCountryFilter();
- $subconds = array();
- $subconds[] = $subc . '.country' . $this->mkMatch($this->country);
- $subconds[] = $subc . '.countryFR' . $this->mkMatch($this->country);
- $conds[] = implode(' OR ', $subconds);
- }
-
- if ($this->locality != null) {
- $subl = $uf->addAddressLocalityFilter();
- $conds[] = $subl . '.name' . $this->mkMatch($this->locality);
- }
-
- return implode(' AND ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_AddressField
-/** Filters users based on their address,
- * @param $val Either a code for one of the fields, or an array of such codes
- * @param $fieldtype The type of field to look for
- * @param $type Filter on address type
- * @param $flags Filter on address flags
- */
-class UFC_AddressField extends UFC_Address
-{
- const FIELD_COUNTRY = 1;
- const FIELD_ADMAREA = 2;
- const FIELD_SUBADMAREA = 3;
- const FIELD_LOCALITY = 4;
- const FIELD_ZIPCODE = 5;
-
- /** Data of the filter
- */
- private $val;
- private $fieldtype;
-
- public function __construct($val, $fieldtype, $type = null, $flags = self::FLAG_ANY)
- {
- parent::__construct($type, $flags);
-
- if (!is_array($val)) {
- $val = array($val);
- }
- $this->val = $val;
- $this->fieldtype = $fieldtype;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addAddressFilter();
- $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
-
- switch ($this->fieldtype) {
- case self::FIELD_COUNTRY:
- $field = 'countryId';
- break;
- case self::FIELD_ADMAREA:
- $field = 'administrativeAreaId';
- break;
- case self::FIELD_SUBADMAREA:
- $field = 'subAdministrativeAreaId';
- break;
- case self::FIELD_LOCALITY:
- $field = 'localityId';
- break;
- case self::FIELD_ZIPCODE:
- $field = 'postalCode';
- break;
- default:
- Platal::page()->killError('Invalid address field type: ' . $this->fieldtype);
- }
- $conds[] = XDB::format($sub . '.' . $field . ' IN {?}', $this->val);
-
- return implode(' AND ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_Corps
-/** Filters users based on the corps they belong to
- * @param $corps Corps we are looking for (abbreviation)
- * @param $type Whether we search for original or current corps
- */
-class UFC_Corps implements UserFilterCondition
-{
- const CURRENT = 1;
- const ORIGIN = 2;
-
- private $corps;
- private $type;
-
- public function __construct($corps, $type = self::CURRENT)
- {
- $this->corps = $corps;
- $this->type = $type;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- /** Tables shortcuts:
- * pc for profile_corps,
- * pceo for profile_corps_enum - orginal
- * pcec for profile_corps_enum - current
- */
- $sub = $uf->addCorpsFilter($this->type);
- $cond = $sub . '.abbreviation = ' . $corps;
- $cond .= ' AND ' . $uf->getVisibilityCondition($sub . '.corps_pub');
- return $cond;
- }
-}
-// }}}
-
-// {{{ class UFC_Corps_Rank
-/** Filters users based on their rank in the corps
- * @param $rank Rank we are looking for (abbreviation)
- */
-class UFC_Corps_Rank implements UserFilterCondition
-{
- private $rank;
- public function __construct($rank)
- {
- $this->rank = $rank;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- /** Tables shortcuts:
- * pc for profile_corps
- * pcr for profile_corps_rank
- */
- $sub = $uf->addCorpsRankFilter();
- $cond = $sub . '.abbreviation = ' . $rank;
- // XXX(x2006barrois): find a way to get rid of that hardcoded
- // reference to 'pc'.
- $cond .= ' AND ' . $uf->getVisibilityCondition('pc.corps_pub');
- return $cond;
- }
-}
-// }}}
-
-// {{{ class UFC_Job_Company
-/** Filters users based on the company they belong to
- * @param $type The field being searched (self::JOBID, self::JOBNAME or self::JOBACRONYM)
- * @param $value The searched value
- */
-class UFC_Job_Company implements UserFilterCondition
-{
- const JOBID = 'id';
- const JOBNAME = 'name';
- const JOBACRONYM = 'acronym';
-
- private $type;
- private $value;
-
- public function __construct($type, $value)
- {
- $this->assertType($type);
- $this->type = $type;
- $this->value = $value;
- }
-
- private function assertType($type)
- {
- if ($type != self::JOBID && $type != self::JOBNAME && $type != self::JOBACRONYM) {
- Platal::page()->killError("Type de recherche non valide.");
- }
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addJobCompanyFilter();
- $cond = $sub . '.' . $this->type . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->value);
- $jsub = $uf->addJobFilter();
- $cond .= ' AND ' . $uf->getVisibilityCondition($jsub . '.pub');
- return $cond;
- }
-}
-// }}}
-
-// {{{ class UFC_Job_Terms
-/** Filters users based on the job terms they assigned to one of their
- * jobs.
- * @param $val The ID of the job term, or an array of such IDs
- */
-class UFC_Job_Terms implements UserFilterCondition
-{
- private $val;
-
- public function __construct($val)
- {
- if (!is_array($val)) {
- $val = array($val);
- }
- $this->val = $val;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addJobTermsFilter(count($this->val));
- $conditions = array();
- foreach ($this->val as $i => $jtid) {
- $conditions[] = $sub[$i] . '.jtid_1 = ' . XDB::escape($jtid);
- }
- $jsub = $uf->addJobFilter();
- $conditions[] = $uf->getVisibilityCondition($jsub . '.pub');
- return implode(' AND ', $conditions);
- }
-}
-// }}}
-
-// {{{ class UFC_Job_Description
-/** Filters users based on their job description
- * @param $description The text being searched for
- * @param $fields The fields to search for (CV, user-defined)
- */
-class UFC_Job_Description implements UserFilterCondition
-{
-
- private $description;
- private $fields;
-
- public function __construct($description, $fields)
- {
- $this->fields = $fields;
- $this->description = $description;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $conds = array();
-
- $jsub = $uf->addJobFilter();
- // CV is private => if only CV requested, and not private,
- // don't do anything. Otherwise restrict to standard job visibility.
- if ($this->fields == UserFilter::JOB_CV) {
- if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
- return self::CONF_TRUE;
- }
- } else {
- $conds[] = $uf->getVisibilityCondition($jsub . '.pub');
- }
-
- if ($this->fields & UserFilter::JOB_USERDEFINED) {
- $conds[] = $jsub . '.description ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
- }
- if ($this->fields & UserFilter::JOB_CV && $uf->getVisibilityLevel() == ProfileVisibility::VIS_PRIVATE) {
- $uf->requireProfiles();
- $conds[] = 'p.cv ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
- }
- return implode(' OR ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_Networking
-/** Filters users based on network identity (IRC, ...)
- * @param $type Type of network (-1 for any)
- * @param $value Value to search
- */
-class UFC_Networking implements UserFilterCondition
-{
- private $type;
- private $value;
-
- public function __construct($type, $value)
- {
- $this->type = $type;
- $this->value = $value;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addNetworkingFilter();
- $conds = array();
- $conds[] = $uf->getVisibilityCondition($sub . '.pub');
- $conds[] = $sub . '.address ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->value);
- if ($this->type != -1) {
- $conds[] = $sub . '.nwid = ' . XDB::format('{?}', $this->type);
- }
- return implode(' AND ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_Phone
-/** Filters users based on their phone number
- * @param $num_type Type of number (pro/user/home)
- * @param $phone_type Type of phone (fixed/mobile/fax)
- * @param $number Phone number
- */
-class UFC_Phone implements UserFilterCondition
-{
- const NUM_PRO = 'pro';
- const NUM_USER = 'user';
- const NUM_HOME = 'address';
- const NUM_ANY = 'any';
-
- const PHONE_FIXED = 'fixed';
- const PHONE_MOBILE = 'mobile';
- const PHONE_FAX = 'fax';
- const PHONE_ANY = 'any';
-
- private $num_type;
- private $phone_type;
- private $number;
-
- public function __construct($number, $num_type = self::NUM_ANY, $phone_type = self::PHONE_ANY)
- {
- $phone = new Phone(array('display' => $number));
- $phone->format();
- $this->number = $phone->search();
- $this->num_type = $num_type;
- $this->phone_type = $phone_type;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addPhoneFilter();
- $conds = array();
-
- $conds[] = $uf->getVisibilityCondition($sub . '.pub');
-
- $conds[] = $sub . '.search_tel = ' . XDB::format('{?}', $this->number);
- if ($this->num_type != self::NUM_ANY) {
- $conds[] = $sub . '.link_type = ' . XDB::format('{?}', $this->num_type);
- }
- if ($this->phone_type != self::PHONE_ANY) {
- $conds[] = $sub . '.tel_type = ' . XDB::format('{?}', $this->phone_type);
- }
- return implode(' AND ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_Medal
-/** Filters users based on their medals
- * @param $medal ID of the medal
- * @param $grade Grade of the medal (null for 'any')
- */
-class UFC_Medal implements UserFilterCondition
-{
- private $medal;
- private $grade;
-
- public function __construct($medal, $grade = null)
- {
- $this->medal = $medal;
- $this->grade = $grade;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $conds = array();
-
- // This will require profiles => table 'p' will be available.
- $sub = $uf->addMedalFilter();
-
- $conds[] = $uf->getVisibilityCondition('p.medals_pub');
-
- $conds[] = $sub . '.mid = ' . XDB::format('{?}', $this->medal);
- if ($this->grade != null) {
- $conds[] = $sub . '.gid = ' . XDB::format('{?}', $this->grade);
- }
- return implode(' AND ', $conds);
- }
-}
-// }}}
-
-// {{{ class UFC_Photo
-/** Filters profiles with photo
- */
-class UFC_Photo implements UserFilterCondition
-{
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addPhotoFilter();
- return $sub . '.attach IS NOT NULL AND ' . $uf->getVisibilityCondition($sub . '.pub');
- }
-}
-// }}}
-
-// {{{ class UFC_Mentor
-class UFC_Mentor implements UserFilterCondition
-{
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addMentorFilter(UserFilter::MENTOR);
- return $sub . '.expertise IS NOT NULL';
- }
-}
-// }}}
-
-
-// {{{ class UFC_Mentor_Expertise
-/** Filters users by mentoring expertise
- * @param $expertise Domain of expertise
- */
-class UFC_Mentor_Expertise implements UserFilterCondition
-{
- private $expertise;
-
- public function __construct($expertise)
- {
- $this->expertise = $expertise;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addMentorFilter(UserFilter::MENTOR_EXPERTISE);
- return $sub . '.expertise ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->expertise);
- }
-}
-// }}}
-
-// {{{ class UFC_Mentor_Country
-/** Filters users by mentoring country
- * @param $country Two-letters code of country being searched
- */
-class UFC_Mentor_Country implements UserFilterCondition
-{
- private $country;
-
- public function __construct()
- {
- $this->country = pl_flatten(func_get_args());
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addMentorFilter(UserFilter::MENTOR_COUNTRY);
- return $sub . '.country IN ' . XDB::format('{?}', $this->country);
- }
-}
-// }}}
-
-// {{{ class UFC_Mentor_Terms
-/** Filters users based on the job terms they used in mentoring.
- * @param $val The ID of the job term, or an array of such IDs
- */
-class UFC_Mentor_Terms implements UserFilterCondition
-{
- private $val;
-
- public function __construct($val)
- {
- $this->val = $val;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addMentorFilter(UserFilter::MENTOR_TERM);
- return $sub . '.jtid_1 = ' . XDB::escape($this->val);
- }
-}
-// }}}
-
-// {{{ class UFC_UserRelated
-/** Filters users based on a relation toward a user
- * @param $user User to which searched users are related
- */
-abstract class UFC_UserRelated implements UserFilterCondition
-{
- protected $user;
- public function __construct(PlUser &$user)
- {
- $this->user =& $user;
- }
-}
-// }}}
-
-// {{{ class UFC_Contact
-/** Filters users who belong to selected user's contacts
- */
-class UFC_Contact extends UFC_UserRelated
-{
- public function buildCondition(PlFilter &$uf)
- {
- $sub = $uf->addContactFilter($this->user->id());
- return 'c' . $sub . '.contact IS NOT NULL';
- }
-}
-// }}}
-
-// {{{ class UFC_WatchRegistration
-/** Filters users being watched by selected user
- */
-class UFC_WatchRegistration extends UFC_UserRelated
-{
- public function buildCondition(PlFilter &$uf)
- {
- if (!$this->user->watchType('registration')) {
- return PlFilterCondition::COND_FALSE;
- }
- $uids = $this->user->watchUsers();
- if (count($uids) == 0) {
- return PlFilterCondition::COND_FALSE;
- } else {
- return XDB::format('$UID IN {?}', $uids);
- }
- }
-}
-// }}}
-
-// {{{ class UFC_WatchPromo
-/** Filters users belonging to a promo watched by selected user
- * @param $user Selected user (the one watching promo)
- * @param $grade Formation the user is watching
- */
-class UFC_WatchPromo extends UFC_UserRelated
-{
- private $grade;
- public function __construct(PlUser &$user, $grade = UserFilter::GRADE_ING)
- {
- parent::__construct($user);
- $this->grade = $grade;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $promos = $this->user->watchPromos();
- if (count($promos) == 0) {
- return PlFilterCondition::COND_FALSE;
- } else {
- $sube = $uf->addEducationFilter(true, $this->grade);
- $field = 'pe' . $sube . '.' . UserFilter::promoYear($this->grade);
- return XDB::format($field . ' IN {?}', $promos);
- }
- }
-}
-// }}}
-
-// {{{ class UFC_WatchContact
-/** Filters users watched by selected user
- */
-class UFC_WatchContact extends UFC_Contact
-{
- public function buildCondition(PlFilter &$uf)
- {
- if (!$this->user->watchContacts()) {
- return PlFilterCondition::COND_FALSE;
- }
- return parent::buildCondition($uf);
- }
-}
-// }}}
-
-// {{{ class UFC_MarketingHash
-/** Filters users using the hash generated
- * to send marketing emails to him.
- */
-class UFC_MarketingHash implements UserFilterCondition
-{
- private $hash;
-
- public function __construct($hash)
- {
- $this->hash = $hash;
- }
-
- public function buildCondition(PlFilter &$uf)
- {
- $table = $uf->addMarketingHash();
- return XDB::format('rm.hash = {?}', $this->hash);
- }
-}
-// }}}
-
-/******************
- * ORDERS
- ******************/
-
-// {{{ class UFO_Promo
-/** Orders users by promotion
- * @param $grade Formation whose promotion users should be sorted by (restricts results to users of that formation)
- * @param $desc Whether sort is descending
- */
-class UFO_Promo extends PlFilterGroupableOrder
-{
- private $grade;
-
- public function __construct($grade = null, $desc = false)
- {
- parent::__construct($desc);
- $this->grade = $grade;
- }
-
- protected function getSortTokens(PlFilter &$uf)
- {
- if (UserFilter::isGrade($this->grade)) {
- $sub = $uf->addEducationFilter($this->grade);
- return 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
- } else {
- $sub = $uf->addDisplayFilter();
- return 'pd' . $sub . '.promo';
- }
- }
-}
-// }}}
-
-// {{{ class UFO_Name
-/** Sorts users by name
- * @param $type Type of name on which to sort (firstname...)
- * @param $variant Variant of that name to use (marital, ordinary...)
- * @param $particle Set to true if particles should be included in the sorting order
- * @param $desc If sort order should be descending
- */
-class UFO_Name extends PlFilterOrder
-{
- private $type;
- private $variant;
- private $particle;
-
- public function __construct($type, $variant = null, $particle = false, $desc = false)
- {
- parent::__construct($desc);
- $this->type = $type;
- $this->variant = $variant;
- $this->particle = $particle;
- }
-
- protected function getSortTokens(PlFilter &$uf)
- {
- if (Profile::isDisplayName($this->type)) {
- $sub = $uf->addDisplayFilter();
- $token = 'pd' . $sub . '.' . $this->type;
- if ($uf->accountsRequired()) {
- $account_token = Profile::getAccountEquivalentName($this->type);
- return 'IFNULL(' . $token . ', a.' . $account_token . ')';
- } else {
- return $token;
- }
- } else {
- $sub = $uf->addNameFilter($this->type, $this->variant);
- if ($this->particle) {
- return 'CONCAT(pn' . $sub . '.particle, \' \', pn' . $sub . '.name)';
- } else {
- return 'pn' . $sub . '.name';
- }
- }
- }
-}
-// }}}
-
-// {{{ class UFO_Score
-class UFO_Score extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $toks = $uf->getNameTokens();
- $scores = array();
-
- // If there weren't any sort tokens, we shouldn't sort by score, sort by NULL instead
- if (count($toks) == 0) {
- return 'NULL';
- }
-
- foreach ($toks as $sub => $token) {
- $scores[] = XDB::format('SUM(' . $sub . '.score + IF (' . $sub . '.token = {?}, 5, 0) )', $token);
- }
- return implode(' + ', $scores);
- }
-}
-// }}}
-
-// {{{ class UFO_Registration
-/** Sorts users based on registration date
- */
-class UFO_Registration extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $uf->requireAccounts();
- return 'a.registration_date';
- }
-}
-// }}}
-
-// {{{ class UFO_Birthday
-/** Sorts users based on next birthday date
- */
-class UFO_Birthday extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return 'p.next_birthday';
- }
-}
-// }}}
-
-// {{{ class UFO_ProfileUpdate
-/** Sorts users based on last profile update
- */
-class UFO_ProfileUpdate extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return 'p.last_change';
- }
-}
-// }}}
-
-// {{{ class UFO_Death
-/** Sorts users based on death date
- */
-class UFO_Death extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return 'p.deathdate';
- }
-}
-// }}}
-
-// {{{ class UFO_Uid
-/** Sorts users based on their uid
- */
-class UFO_Uid extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $uf->requireAccounts();
- return '$UID';
- }
-}
-// }}}
-
-// {{{ class UFO_Hruid
-/** Sorts users based on their hruid
- */
-class UFO_Hruid extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $uf->requireAccounts();
- return 'a.hruid';
- }
-}
-// }}}
-
-// {{{ class UFO_Pid
-/** Sorts users based on their pid
- */
-class UFO_Pid extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return '$PID';
- }
-}
-// }}}
-
-// {{{ class UFO_Hrpid
-/** Sorts users based on their hrpid
- */
-class UFO_Hrpid extends PlFilterOrder
-{
- protected function getSortTokens(PlFilter &$uf)
- {
- $uf->requireProfiles();
- return 'p.hrpid';
- }
-}
-// }}}
-
+require_once dirname(__FILE__) . '/userfilter/conditions.inc.php';
+require_once dirname(__FILE__) . '/userfilter/orders.inc.php';
/***********************************
*********************************
}
}
- public function setCondition(PlFilterCondition &$cond)
+ public function setCondition(PlFilterCondition $cond)
{
$this->root =& $cond;
$this->query = null;
}
- public function addSort(PlFilterOrder &$sort)
+ public function addSort(PlFilterOrder $sort)
{
if (count($this->sort) == 0 && $sort instanceof PlFilterGroupableOrder)
{
$this->orderby = null;
}
+ public function export()
+ {
+ $export = array('conditions' => $this->root->export());
+ if (!empty($this->sort)) {
+ $export['sorts'] = array();
+ foreach ($this->sort as $sort) {
+ $export['sorts'][] = $sort->export();
+ }
+ }
+ return $export;
+ }
+
+ public function exportConditions()
+ {
+ return $this->root->export();
+ }
+
+ public static function fromExport(array $export)
+ {
+ $export = new PlDict($export);
+ if (!$export->has('conditions')) {
+ throw new Exception("Cannot build a user filter without conditions");
+ }
+ $cond = UserFilterCondition::fromExport($export->v('conditions'));
+ $sorts = null;
+ if ($export->has('sorts')) {
+ $sorts = array();
+ foreach ($export->v('sorts') as $sort) {
+ $sorts[] = UserFilterOrder::fromExport($sort);
+ }
+ }
+ return new UserFilter($cond, $sorts);
+ }
+
+ public static function fromJSon($json)
+ {
+ $export = json_decode($json, true);
+ if (is_null($export)) {
+ throw new Exception("Invalid json: $json");
+ }
+ return self::fromExport($json);
+ }
+
+ public static function fromExportedConditions(array $export)
+ {
+ $cond = UserFilterCondition::fromExport($export);
+ return new UserFilter($cond);
+ }
+
+ public static function fromJSonConditions($json)
+ {
+ $export = json_decode($json, true);
+ if (is_null($export)) {
+ throw new Exception("Invalid json: $json");
+ }
+ return self::fromExportedConditions($json);
+ }
+
static public function getLegacy($promo_min, $promo_max)
{
if ($promo_min != 0) {
}
}
// }}}
-
// {{{ class ProfileFilter
class ProfileFilter extends UserFilter
{
--- /dev/null
+<?php
+/***************************************************************************
+ * Copyright (C) 2003-2010 Polytechnique.org *
+ * http://opensource.polytechnique.org/ *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the Free Software *
+ * Foundation, Inc., *
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
+ ***************************************************************************/
+
+// {{{ abstract class UserFilterCondition
+/** This class describe objects which filter users based
+ * on various parameters.
+ * The parameters of the filter must be given to the constructor.
+ * The buildCondition function is called by UserFilter when
+ * actually building the query. That function must call
+ * $uf->addWheteverFilter so that the UserFilter makes
+ * adequate joins. It must return the 'WHERE' condition to use
+ * with the filter.
+ */
+abstract class UserFilterCondition implements PlFilterCondition
+{
+ const OP_EQUALS = '==';
+ const OP_GREATER = '>';
+ const OP_NOTGREATER = '<=';
+ const OP_LESSER = '<';
+ const OP_NOTLESSER = '>=';
+ const OP_NULL = 'null';
+ const OP_NOTNULL = 'not null';
+ const OP_CONTAINS = 'contains';
+ const OP_PREFIX = 'prefix';
+ const OP_SUFFIX = 'suffix';
+
+ protected function buildExport($type)
+ {
+ $export = array('type' => $type);
+ return $export;
+ }
+
+ public function export()
+ {
+ throw new Exception("This class is not exportable");
+ }
+
+ public static function comparisonFromXDBWildcard($wildcard)
+ {
+ switch ($wildcard) {
+ case XDB::WILDCARD_EXACT:
+ return self::OP_EQUALS;
+ case XDB::WILDCARD_PREFIX:
+ return self::OP_PREFIX;
+ case XDB::WILDCARD_SUFFIX:
+ return self::OP_SUFFIX;
+ case XDB::WILDCARD_CONTAINS:
+ return self::OP_CONTAINS;
+ }
+ throw new Exception("Unknown wildcard mode: $wildcard");
+ }
+
+ public static function xdbWildcardFromComparison($comparison)
+ {
+ if (!self::isStringComparison($comparison)) {
+ throw new Exception("Unknown string coparison: $comparison");
+ }
+ switch ($comparison) {
+ case self::OP_EQUALS:
+ return XDB::WILDCARD_EXACT;
+ case self::OP_PREFIX:
+ return XDB::WILDCARD_PREFIX;
+ case self::OP_SUFFIX:
+ return XDB::WILDCARD_SUFFIX;
+ case self::OP_CONTAINS:
+ return XDB::WILDCARD_CONTAINS;
+ }
+ }
+
+ private static function isNumericComparison($comparison)
+ {
+ return $comparison == self::OP_EQUALS
+ || $comparison == self::OP_GREATER
+ || $comparison == self::OP_NOTGREATER
+ || $comparison == self::OP_LESSER
+ || $comparison == self::OP_NOTLESSER;
+ }
+
+ private static function isStringComparison($comparison)
+ {
+ return $comparison == self::OP_EQUALS
+ || $comparison == self::OP_CONTAINS
+ || $comparison == self::OP_PREFIX
+ || $comparison == self::OP_SUFFIX;
+ }
+
+ public static function fromExport(array $export)
+ {
+ $export = new PlDict($export);
+ if (!$export->has('type')) {
+ throw new Exception("Missing type in export");
+ }
+ $type = $export->s('type');
+ $cond = null;
+ switch ($type) {
+ case 'and':
+ case 'or':
+ case 'not':
+ case 'true':
+ case 'false':
+ $class = 'pfc_' . $type;
+ $cond = new $class();
+ break;
+
+ case 'host':
+ if ($export->has('ip')) {
+ $cond = new UFC_Ip($export->s('ip'));
+ }
+ break;
+
+ case 'comment':
+ if ($export->has('text') && $export->s('comparison') == self::OP_CONTAINS) {
+ $cond = new UFC_Comment($export->s('text'));
+ }
+ break;
+
+ case 'promo':
+ if ($export->has('promo') && self::isNumericComparison($export->s('comparison'))) {
+ $cond = new UFC_Promo($export->s('comparison'),
+ $export->s('grade', UserFilter::DISPLAY),
+ $export->s('promo'));
+ }
+ break;
+
+ case 'lastname':
+ case 'name':
+ case 'firstname':
+ case 'nickname':
+ case 'pseudonym':
+ if ($export->has('text')) {
+ $flag = self::xdbWildcardFromComparison($export->s('comparison'));
+ if ($export->b('search_in_variants')) {
+ $flag |= UFC_Name::VARIANTS;
+ }
+ if ($export->b('search_in_particle')) {
+ $flag |= UFC_Name::PARTICLE;
+ }
+ $cond = new UFC_Name($type, $export->s('text'), $flag);
+ }
+ break;
+
+ case 'account_type':
+ case 'account_perm':
+ case 'hrpid':
+ case 'hruid':
+ $values = $export->v('values', array());
+ $class = 'ufc_' . str_replace('_', '', $type);
+ $cond = new $class($values);
+ break;
+
+ case 'has_profile':
+ $class = 'ufc_' . str_replace('_', '', $type);
+ $cond = new $class();
+ break;
+
+ default:
+ throw new Exception("Unknown condition type: $type");
+ }
+ if (is_null($cond)) {
+ throw new Exception("Unsupported $type definition");
+ }
+ if ($cond instanceof PFC_NChildren) {
+ $children = $export->v('children', array());
+ foreach ($children as $child) {
+ $cond->addChild(self::fromExport($child));
+ }
+ } else if ($cond instanceof PFC_OneChild) {
+ if ($export->has('child')) {
+ $cond->setChild(self::fromExport($export->v('child')));
+ }
+ }
+ return $cond;
+ }
+}
+// }}}
+// {{{ class UFC_HasProfile
+/** Filters users who have a profile
+ */
+class UFC_HasProfile extends UserFilterCondition
+{
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return '$PID IS NOT NULL';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('has_profile');
+ }
+}
+// }}}
+// {{{ class UFC_AccountType
+/** Filters users who have one of the given account types
+ */
+class UFC_AccountType extends UserFilterCondition
+{
+ private $types;
+
+ public function __construct()
+ {
+ $this->types = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireAccounts();
+ return XDB::format('a.type IN {?}', $this->types);
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport('account_type');
+ $export['values'] = $this->types;
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFC_AccountPerm
+/** Filters users who have one of the given permissions
+ */
+class UFC_AccountPerm extends UserFilterCondition
+{
+ private $perms;
+
+ public function __construct()
+ {
+ $this->perms = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requirePerms();
+ $conds = array();
+ foreach ($this->perms as $perm) {
+ $conds[] = XDB::format('FIND_IN_SET({?}, IF(a.user_perms IS NULL, at.perms,
+ CONCAT(at.perms, \',\', a.user_perms)))',
+ $perm);
+ }
+ if (empty($conds)) {
+ return self::COND_TRUE;
+ } else {
+ return implode(' OR ', $conds);
+ }
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport('account_perm');
+ $export['values'] = $this->perms;
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFC_Hruid
+/** Filters users based on their hruid
+ * @param $val Either an hruid, or a list of those
+ */
+class UFC_Hruid extends UserFilterCondition
+{
+ private $hruids;
+
+ public function __construct()
+ {
+ $this->hruids = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireAccounts();
+ return XDB::format('a.hruid IN {?}', $this->hruids);
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport('hruid');
+ $export['values'] = $this->hruids;
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFC_Hrpid
+/** Filters users based on the hrpid of their profiles
+ * @param $val Either an hrpid, or a list of those
+ */
+class UFC_Hrpid extends UserFilterCondition
+{
+ private $hrpids;
+
+ public function __construct()
+ {
+ $this->hrpids = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return XDB::format('p.hrpid IN {?}', $this->hrpids);
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport('hrpid');
+ $export['values'] = $this->hrpids;
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFC_Ip
+/** Filters users based on one of their last IPs
+ * @param $ip IP from which connection are checked
+ */
+class UFC_Ip extends UserFilterCondition
+{
+ private $ip;
+
+ public function __construct($ip)
+ {
+ $this->ip = $ip;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addLoggerFilter();
+ $ip = ip_to_uint($this->ip);
+ return XDB::format($sub . '.ip = {?} OR ' . $sub . '.forward_ip = {?}', $ip, $ip);
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport('host');
+ $export['ip'] = $this->ip;
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFC_Comment
+class UFC_Comment extends UserFilterCondition
+{
+ private $text;
+
+ public function __construct($text)
+ {
+ $this->text = $text;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return $uf->getVisibilityCondition('p.freetext_pub') . ' AND p.freetext ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->text);
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport('comment');
+ $export['comparison'] = self::OP_CONTAINS;
+ $export['text'] = $this->text;
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFC_Promo
+/** Filters users based on promotion
+ * @param $comparison Comparison operator (>, =, ...)
+ * @param $grade Formation on which to restrict, UserFilter::DISPLAY for "any formation"
+ * @param $promo Promotion on which the filter is based
+ */
+class UFC_Promo extends UserFilterCondition
+{
+
+ private $grade;
+ private $promo;
+ private $comparison;
+
+ public function __construct($comparison, $grade, $promo)
+ {
+ $this->grade = $grade;
+ $this->comparison = $comparison;
+ $this->promo = $promo;
+ if ($this->grade != UserFilter::DISPLAY) {
+ UserFilter::assertGrade($this->grade);
+ }
+ if ($this->grade == UserFilter::DISPLAY && $this->comparison != '=') {
+ // XXX: we might try to guess the grade from the first char of the promo and forbid only '<= 2004', but allow '<= X2004'
+ Platal::page()->killError("Il n'est pas possible d'appliquer la comparaison '" . $this->comparison . "' aux promotions sans spécifier de formation (X/M/D)");
+ }
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ if ($this->grade == UserFilter::DISPLAY) {
+ $sub = $uf->addDisplayFilter();
+ return XDB::format('pd' . $sub . '.promo ' . $this->comparison . ' {?}', $this->promo);
+ } else {
+ $sub = $uf->addEducationFilter(true, $this->grade);
+ $field = 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
+ return $field . ' IS NOT NULL AND ' . $field . ' ' . $this->comparison . ' ' . XDB::format('{?}', $this->promo);
+ }
+ }
+
+ public function export()
+ {
+ $export['comparison'] = $this->comparison;
+ if ($this->grade != UserFilter::DISPLAY) {
+ $export['grade'] = $this->grade;
+ }
+ $export['promo'] = $this->promo;
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFC_SchoolId
+/** Filters users based on their shoold identifier
+ * @param type Parameter type (Xorg, AX, School)
+ * @param value School id value
+ */
+class UFC_SchoolId extends UserFilterCondition
+{
+ const AX = 'ax';
+ const Xorg = 'xorg';
+ const School = 'school';
+
+ private $type;
+ private $id;
+
+ static public function assertType($type)
+ {
+ if ($type != self::AX && $type != self::Xorg && $type != self::School) {
+ Platal::page()->killError("Type de matricule invalide: $type");
+ }
+ }
+
+ public function __construct($type, $id)
+ {
+ $this->type = $type;
+ $this->id = $id;
+ self::assertType($type);
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ $id = $this->id;
+ $type = $this->type;
+ if ($type == self::School) {
+ $type = self::Xorg;
+ $id = Profile::getXorgId($id);
+ }
+ return XDB::format('p.' . $type . '_id = {?}', $id);
+ }
+}
+// }}}
+// {{{ class UFC_EducationSchool
+/** Filters users by formation
+ * @param $val The formation to search (either ID or array of IDs)
+ */
+class UFC_EducationSchool extends UserFilterCondition
+{
+ private $val;
+
+ public function __construct()
+ {
+ $this->val = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addEducationFilter();
+ return XDB::format('pe' . $sub . '.eduid IN {?}', $this->val);
+ }
+}
+// }}}
+// {{{ class UFC_EducationDegree
+class UFC_EducationDegree extends UserFilterCondition
+{
+ private $diploma;
+
+ public function __construct()
+ {
+ $this->diploma = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addEducationFilter();
+ return XDB::format('pe' . $sub . '.degreeid IN {?}', $this->diploma);
+ }
+}
+// }}}
+// {{{ class UFC_EducationField
+class UFC_EducationField extends UserFilterCondition
+{
+ private $val;
+
+ public function __construct()
+ {
+ $this->val = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addEducationFilter();
+ return XDB::format('pe' . $sub . '.fieldid IN {?}', $this->val);
+ }
+}
+// }}}
+// {{{ class UFC_Name
+/** Filters users based on name
+ * @param $type Type of name field on which filtering is done (firstname, lastname...)
+ * @param $text Text on which to filter
+ * @param $mode Flag indicating search type (prefix, suffix, with particule...)
+ */
+class UFC_Name extends UserFilterCondition
+{
+ const EXACT = XDB::WILDCARD_EXACT; // 0x000
+ const PREFIX = XDB::WILDCARD_PREFIX; // 0x001
+ const SUFFIX = XDB::WILDCARD_SUFFIX; // 0x002
+ const CONTAINS = XDB::WILDCARD_CONTAINS; // 0x003
+ const PARTICLE = 0x004;
+ const VARIANTS = 0x008;
+
+ private $type;
+ private $text;
+ private $mode;
+
+ public function __construct($type, $text, $mode)
+ {
+ $this->type = $type;
+ $this->text = $text;
+ $this->mode = $mode;
+ }
+
+ private function buildNameQuery($type, $variant, $where, UserFilter $uf)
+ {
+ $sub = $uf->addNameFilter($type, $variant);
+ return str_replace('$ME', 'pn' . $sub, $where);
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $left = '$ME.name';
+ if (($this->mode & self::PARTICLE) == self::PARTICLE) {
+ $left = 'CONCAT($ME.particle, \' \', $ME.name)';
+ }
+ $right = XDB::formatWildcards($this->mode & self::CONTAINS, $this->text);
+
+ $cond = $left . $right;
+ $conds = array($this->buildNameQuery($this->type, null, $cond, $uf));
+ if (($this->mode & self::VARIANTS) != 0 && isset(Profile::$name_variants[$this->type])) {
+ foreach (Profile::$name_variants[$this->type] as $var) {
+ $conds[] = $this->buildNameQuery($this->type, $var, $cond, $uf);
+ }
+ }
+ return implode(' OR ', $conds);
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport($this->type);
+ if ($this->mode & self::VARIANTS) {
+ $export['search_in_variants'] = true;
+ }
+ if ($this->mode & self::PARTICLE) {
+ $export['search_in_particle'] = true;
+ }
+ $export['comparison'] = self::comparisonFromXDBWildcard($this->mode & 0x3);
+ $export['text'] = $this->text;
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFC_NameTokens
+/** Selects users based on tokens in their name (for quicksearch)
+ * @param $tokens An array of tokens to search
+ * @param $flags Flags the tokens must have (e.g 'public' for public search)
+ * @param $soundex (bool) Whether those tokens are fulltext or soundex
+ */
+class UFC_NameTokens extends UserFilterCondition
+{
+ /* Flags */
+ const FLAG_PUBLIC = 'public';
+
+ private $tokens;
+ private $flags;
+ private $soundex;
+ private $exact;
+
+ public function __construct($tokens, $flags = array(), $soundex = false, $exact = false)
+ {
+ if (is_array($tokens)) {
+ $this->tokens = $tokens;
+ } else {
+ $this->tokens = array($tokens);
+ }
+ if (is_array($flags)) {
+ $this->flags = $flags;
+ } else {
+ $this->flags = array($flags);
+ }
+ $this->soundex = $soundex;
+ $this->exact = $exact;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $conds = array();
+ foreach ($this->tokens as $i => $token) {
+ $sub = $uf->addNameTokensFilter($token);
+ if ($this->soundex) {
+ $c = XDB::format($sub . '.soundex = {?}', soundex_fr($token));
+ } else if ($this->exact) {
+ $c = XDB::format($sub . '.token = {?}', $token);
+ } else {
+ $c = $sub . '.token ' . XDB::formatWildcards(XDB::WILDCARD_PREFIX, $token);
+ }
+ if ($this->flags != null) {
+ $c .= XDB::format(' AND ' . $sub . '.flags IN {?}', $this->flags);
+ }
+ $conds[] = $c;
+ }
+
+ return implode(' AND ', $conds);
+ }
+}
+// }}}
+// {{{ class UFC_Nationality
+class UFC_Nationality extends UserFilterCondition
+{
+ private $val;
+
+ public function __construct()
+ {
+ $this->val = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ $nat = XDB::formatArray($this->val);
+ $conds = array(
+ 'p.nationality1 IN ' . $nat,
+ 'p.nationality2 IN ' . $nat,
+ 'p.nationality3 IN ' . $nat,
+ );
+ return implode(' OR ', $conds);
+ }
+}
+// }}}
+// {{{ class UFC_Dead
+/** Filters users based on death date
+ * @param $comparison Comparison operator
+ * @param $date Date to which death date should be compared (DateTime object, string or timestamp)
+ */
+class UFC_Dead extends UserFilterCondition
+{
+ private $comparison;
+ private $date;
+
+ public function __construct($comparison = null, $date = null)
+ {
+ $this->comparison = $comparison;
+ $this->date = make_datetime($date);
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ $str = 'p.deathdate IS NOT NULL';
+ if (!is_null($this->comparison)) {
+ $str .= ' AND p.deathdate ' . $this->comparison . ' ' . XDB::format('{?}', $this->date->format('Y-m-d'));
+ }
+ return $str;
+ }
+}
+// }}}
+// {{{ class UFC_Registered
+/** Filters users based on registration state
+ * @param $active Whether we want to use only "active" users (i.e with a valid redirection)
+ * @param $comparison Comparison operator
+ * @param $date Date to which users registration date should be compared
+ */
+class UFC_Registered extends UserFilterCondition
+{
+ private $active;
+ private $comparison;
+ private $date;
+
+ public function __construct($active = false, $comparison = null, $date = null)
+ {
+ $this->active = $active;
+ $this->comparison = $comparison;
+ $this->date = make_datetime($date);
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireAccounts();
+ if ($this->active) {
+ $date = '$UID IS NOT NULL AND a.state = \'active\'';
+ } else {
+ $date = '$UID IS NOT NULL AND a.state != \'pending\'';
+ }
+ if (!is_null($this->comparison)) {
+ $date .= ' AND a.registration_date != \'0000-00-00 00:00:00\' AND a.registration_date ' . $this->comparison . ' ' . XDB::format('{?}', $this->date->format('Y-m-d'));
+ }
+ return $date;
+ }
+}
+// }}}
+// {{{ class UFC_ProfileUpdated
+/** Filters users based on profile update date
+ * @param $comparison Comparison operator
+ * @param $date Date to which profile update date must be compared
+ */
+class UFC_ProfileUpdated extends UserFilterCondition
+{
+ private $comparison;
+ private $date;
+
+ public function __construct($comparison = null, $date = null)
+ {
+ $this->comparison = $comparison;
+ $this->date = $date;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return 'p.last_change ' . $this->comparison . XDB::format(' {?}', date('Y-m-d H:i:s', $this->date));
+ }
+}
+// }}}
+// {{{ class UFC_Birthday
+/** Filters users based on next birthday date
+ * @param $comparison Comparison operator
+ * @param $date Date to which users next birthday date should be compared
+ */
+class UFC_Birthday extends UserFilterCondition
+{
+ private $comparison;
+ private $date;
+
+ public function __construct($comparison = null, $date = null)
+ {
+ $this->comparison = $comparison;
+ $this->date = $date;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return 'p.next_birthday ' . $this->comparison . XDB::format(' {?}', date('Y-m-d', $this->date));
+ }
+}
+// }}}
+// {{{ class UFC_Sex
+/** Filters users based on sex
+ * @parm $sex One of User::GENDER_MALE or User::GENDER_FEMALE, for selecting users
+ */
+class UFC_Sex extends UserFilterCondition
+{
+ private $sex;
+ public function __construct($sex)
+ {
+ $this->sex = $sex;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ if ($this->sex != User::GENDER_MALE && $this->sex != User::GENDER_FEMALE) {
+ return self::COND_FALSE;
+ } else {
+ $uf->requireProfiles();
+ return XDB::format('p.sex = {?}', $this->sex == User::GENDER_FEMALE ? 'female' : 'male');
+ }
+ }
+}
+// }}}
+// {{{ class UFC_Group
+/** Filters users based on group membership
+ * @param $group Group whose members we are selecting
+ * @param $anim Whether to restrict selection to animators of that group
+ */
+class UFC_Group extends UserFilterCondition
+{
+ private $group;
+ private $anim;
+ public function __construct($group, $anim = false)
+ {
+ $this->group = $group;
+ $this->anim = $anim;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ // Groups have AX visibility.
+ if ($uf->getVisibilityLevel() == ProfileVisibility::VIS_PUBLIC) {
+ return self::COND_TRUE;
+ }
+ $sub = $uf->addGroupFilter($this->group);
+ $where = 'gpm' . $sub . '.perms IS NOT NULL';
+ if ($this->anim) {
+ $where .= ' AND gpm' . $sub . '.perms = \'admin\'';
+ }
+ return $where;
+ }
+}
+// }}}
+// {{{ class UFC_Binet
+/** Selects users based on their belonging to a given (list of) binet
+ * @param $binet either a binet_id or an array of binet_ids
+ */
+class UFC_Binet extends UserFilterCondition
+{
+ private $val;
+
+ public function __construct()
+ {
+ $this->val = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ // Binets are private.
+ if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
+ return self::CONF_TRUE;
+ }
+ $sub = $uf->addBinetsFilter();
+ return XDB::format($sub . '.binet_id IN {?}', $this->val);
+ }
+}
+// }}}
+// {{{ class UFC_Section
+/** Selects users based on section
+ * @param $section ID of the section
+ */
+class UFC_Section extends UserFilterCondition
+{
+ private $section;
+
+ public function __construct()
+ {
+ $this->section = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ // Sections are private.
+ if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
+ return self::CONF_TRUE;
+ }
+ $uf->requireProfiles();
+ return XDB::format('p.section IN {?}', $this->section);
+ }
+}
+// }}}
+// {{{ class UFC_Email
+/** Filters users based on an email or a list of emails
+ * @param $emails List of emails whose owner must be selected
+ */
+class UFC_Email extends UserFilterCondition
+{
+ private $emails;
+ public function __construct()
+ {
+ $this->emails = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $foreign = array();
+ $virtual = array();
+ $aliases = array();
+ $cond = array();
+
+ if (count($this->emails) == 0) {
+ return PlFilterCondition::COND_TRUE;
+ }
+
+ foreach ($this->emails as $entry) {
+ if (User::isForeignEmailAddress($entry)) {
+ $foreign[] = $entry;
+ } else if (User::isVirtualEmailAddress($entry)) {
+ $virtual[] = $entry;
+ } else {
+ @list($user, $domain) = explode('@', $entry);
+ $aliases[] = $user;
+ }
+ }
+
+ if (count($foreign) > 0) {
+ $sub = $uf->addEmailRedirectFilter($foreign);
+ $cond[] = XDB::format('e' . $sub . '.email IS NOT NULL OR a.email IN {?}', $foreign);
+ }
+ if (count($virtual) > 0) {
+ $sub = $uf->addVirtualEmailFilter($virtual);
+ $cond[] = 'vr' . $sub . '.redirect IS NOT NULL';
+ }
+ if (count($aliases) > 0) {
+ $sub = $uf->addAliasFilter($aliases);
+ $cond[] = 'al' . $sub . '.alias IS NOT NULL';
+ }
+ return '(' . implode(') OR (', $cond) . ')';
+ }
+}
+// }}}
+// {{{ class UFC_Address
+abstract class UFC_Address extends UserFilterCondition
+{
+ /** Valid address type ('hq' is reserved for company addresses)
+ */
+ const TYPE_HOME = 1;
+ const TYPE_PRO = 2;
+ const TYPE_ANY = 3;
+
+ /** Text for these types
+ */
+ protected static $typetexts = array(
+ self::TYPE_HOME => 'home',
+ self::TYPE_PRO => 'pro',
+ );
+
+ protected $type;
+
+ /** Flags for addresses
+ */
+ const FLAG_CURRENT = 0x0001;
+ const FLAG_TEMP = 0x0002;
+ const FLAG_SECOND = 0x0004;
+ const FLAG_MAIL = 0x0008;
+ const FLAG_CEDEX = 0x0010;
+
+ // Binary OR of those flags
+ const FLAG_ANY = 0x001F;
+
+ /** Text of these flags
+ */
+ protected static $flagtexts = array(
+ self::FLAG_CURRENT => 'current',
+ self::FLAG_TEMP => 'temporary',
+ self::FLAG_SECOND => 'secondary',
+ self::FLAG_MAIL => 'mail',
+ self::FLAG_CEDEX => 'cedex',
+ );
+
+ protected $flags;
+
+ public function __construct($type = null, $flags = null)
+ {
+ $this->type = $type;
+ $this->flags = $flags;
+ }
+
+ protected function initConds($sub, $vis_cond)
+ {
+ $conds = array($vis_cond);
+
+ $types = array();
+ foreach (self::$typetexts as $flag => $type) {
+ if ($flag & $this->type) {
+ $types[] = $type;
+ }
+ }
+ if (count($types)) {
+ $conds[] = XDB::format($sub . '.type IN {?}', $types);
+ }
+
+ if ($this->flags != self::FLAG_ANY) {
+ foreach(self::$flagtexts as $flag => $text) {
+ if ($flag & $this->flags) {
+ $conds[] = 'FIND_IN_SET(' . XDB::format('{?}', $text) . ', ' . $sub . '.flags)';
+ }
+ }
+ }
+ return $conds;
+ }
+
+}
+// }}}
+// {{{ class UFC_AddressText
+/** Select users based on their address, using full text search
+ * @param $text Text for filter in fulltext search
+ * @param $textSearchMode Mode for search (one of XDB::WILDCARD_*)
+ * @param $type Filter on address type
+ * @param $flags Filter on address flags
+ * @param $country Filter on address country
+ * @param $locality Filter on address locality
+ */
+class UFC_AddressText extends UFC_Address
+{
+
+ private $text;
+ private $textSearchMode;
+
+ public function __construct($text = null, $textSearchMode = XDB::WILDCARD_CONTAINS,
+ $type = null, $flags = self::FLAG_ANY, $country = null, $locality = null)
+ {
+ parent::__construct($type, $flags);
+ $this->text = $text;
+ $this->textSearchMode = $textSearchMode;
+ $this->country = $country;
+ $this->locality = $locality;
+ }
+
+ private function mkMatch($txt)
+ {
+ return XDB::formatWildcards($this->textSearchMode, $txt);
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addAddressFilter();
+ $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
+ if ($this->text != null) {
+ $conds[] = $sub . '.text' . $this->mkMatch($this->text);
+ }
+
+ if ($this->country != null) {
+ $subc = $uf->addAddressCountryFilter();
+ $subconds = array();
+ $subconds[] = $subc . '.country' . $this->mkMatch($this->country);
+ $subconds[] = $subc . '.countryFR' . $this->mkMatch($this->country);
+ $conds[] = implode(' OR ', $subconds);
+ }
+
+ if ($this->locality != null) {
+ $subl = $uf->addAddressLocalityFilter();
+ $conds[] = $subl . '.name' . $this->mkMatch($this->locality);
+ }
+
+ return implode(' AND ', $conds);
+ }
+}
+// }}}
+// {{{ class UFC_AddressField
+/** Filters users based on their address,
+ * @param $val Either a code for one of the fields, or an array of such codes
+ * @param $fieldtype The type of field to look for
+ * @param $type Filter on address type
+ * @param $flags Filter on address flags
+ */
+class UFC_AddressField extends UFC_Address
+{
+ const FIELD_COUNTRY = 1;
+ const FIELD_ADMAREA = 2;
+ const FIELD_SUBADMAREA = 3;
+ const FIELD_LOCALITY = 4;
+ const FIELD_ZIPCODE = 5;
+
+ /** Data of the filter
+ */
+ private $val;
+ private $fieldtype;
+
+ public function __construct($val, $fieldtype, $type = null, $flags = self::FLAG_ANY)
+ {
+ parent::__construct($type, $flags);
+
+ if (!is_array($val)) {
+ $val = array($val);
+ }
+ $this->val = $val;
+ $this->fieldtype = $fieldtype;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addAddressFilter();
+ $conds = $this->initConds($sub, $uf->getVisibilityCondition($sub . '.pub'));
+
+ switch ($this->fieldtype) {
+ case self::FIELD_COUNTRY:
+ $field = 'countryId';
+ break;
+ case self::FIELD_ADMAREA:
+ $field = 'administrativeAreaId';
+ break;
+ case self::FIELD_SUBADMAREA:
+ $field = 'subAdministrativeAreaId';
+ break;
+ case self::FIELD_LOCALITY:
+ $field = 'localityId';
+ break;
+ case self::FIELD_ZIPCODE:
+ $field = 'postalCode';
+ break;
+ default:
+ Platal::page()->killError('Invalid address field type: ' . $this->fieldtype);
+ }
+ $conds[] = XDB::format($sub . '.' . $field . ' IN {?}', $this->val);
+
+ return implode(' AND ', $conds);
+ }
+}
+// }}}
+// {{{ class UFC_Corps
+/** Filters users based on the corps they belong to
+ * @param $corps Corps we are looking for (abbreviation)
+ * @param $type Whether we search for original or current corps
+ */
+class UFC_Corps extends UserFilterCondition
+{
+ const CURRENT = 1;
+ const ORIGIN = 2;
+
+ private $corps;
+ private $type;
+
+ public function __construct($corps, $type = self::CURRENT)
+ {
+ $this->corps = $corps;
+ $this->type = $type;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ /** Tables shortcuts:
+ * pc for profile_corps,
+ * pceo for profile_corps_enum - orginal
+ * pcec for profile_corps_enum - current
+ */
+ $sub = $uf->addCorpsFilter($this->type);
+ $cond = $sub . '.abbreviation = ' . $corps;
+ $cond .= ' AND ' . $uf->getVisibilityCondition($sub . '.corps_pub');
+ return $cond;
+ }
+}
+// }}}
+// {{{ class UFC_Corps_Rank
+/** Filters users based on their rank in the corps
+ * @param $rank Rank we are looking for (abbreviation)
+ */
+class UFC_Corps_Rank extends UserFilterCondition
+{
+ private $rank;
+ public function __construct($rank)
+ {
+ $this->rank = $rank;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ /** Tables shortcuts:
+ * pc for profile_corps
+ * pcr for profile_corps_rank
+ */
+ $sub = $uf->addCorpsRankFilter();
+ $cond = $sub . '.abbreviation = ' . $rank;
+ // XXX(x2006barrois): find a way to get rid of that hardcoded
+ // reference to 'pc'.
+ $cond .= ' AND ' . $uf->getVisibilityCondition('pc.corps_pub');
+ return $cond;
+ }
+}
+// }}}
+// {{{ class UFC_Job_Company
+/** Filters users based on the company they belong to
+ * @param $type The field being searched (self::JOBID, self::JOBNAME or self::JOBACRONYM)
+ * @param $value The searched value
+ */
+class UFC_Job_Company extends UserFilterCondition
+{
+ const JOBID = 'id';
+ const JOBNAME = 'name';
+ const JOBACRONYM = 'acronym';
+
+ private $type;
+ private $value;
+
+ public function __construct($type, $value)
+ {
+ $this->assertType($type);
+ $this->type = $type;
+ $this->value = $value;
+ }
+
+ private function assertType($type)
+ {
+ if ($type != self::JOBID && $type != self::JOBNAME && $type != self::JOBACRONYM) {
+ Platal::page()->killError("Type de recherche non valide.");
+ }
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addJobCompanyFilter();
+ $cond = $sub . '.' . $this->type . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->value);
+ $jsub = $uf->addJobFilter();
+ $cond .= ' AND ' . $uf->getVisibilityCondition($jsub . '.pub');
+ return $cond;
+ }
+}
+// }}}
+// {{{ class UFC_Job_Terms
+/** Filters users based on the job terms they assigned to one of their
+ * jobs.
+ * @param $val The ID of the job term, or an array of such IDs
+ */
+class UFC_Job_Terms extends UserFilterCondition
+{
+ private $val;
+
+ public function __construct($val)
+ {
+ if (!is_array($val)) {
+ $val = array($val);
+ }
+ $this->val = $val;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addJobTermsFilter(count($this->val));
+ $conditions = array();
+ foreach ($this->val as $i => $jtid) {
+ $conditions[] = $sub[$i] . '.jtid_1 = ' . XDB::escape($jtid);
+ }
+ $jsub = $uf->addJobFilter();
+ $conditions[] = $uf->getVisibilityCondition($jsub . '.pub');
+ return implode(' AND ', $conditions);
+ }
+}
+// }}}
+// {{{ class UFC_Job_Description
+/** Filters users based on their job description
+ * @param $description The text being searched for
+ * @param $fields The fields to search for (CV, user-defined)
+ */
+class UFC_Job_Description extends UserFilterCondition
+{
+
+ private $description;
+ private $fields;
+
+ public function __construct($description, $fields)
+ {
+ $this->fields = $fields;
+ $this->description = $description;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $conds = array();
+
+ $jsub = $uf->addJobFilter();
+ // CV is private => if only CV requested, and not private,
+ // don't do anything. Otherwise restrict to standard job visibility.
+ if ($this->fields == UserFilter::JOB_CV) {
+ if ($uf->getVisibilityLevel() != ProfileVisibility::VIS_PRIVATE) {
+ return self::CONF_TRUE;
+ }
+ } else {
+ $conds[] = $uf->getVisibilityCondition($jsub . '.pub');
+ }
+
+ if ($this->fields & UserFilter::JOB_USERDEFINED) {
+ $conds[] = $jsub . '.description ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
+ }
+ if ($this->fields & UserFilter::JOB_CV && $uf->getVisibilityLevel() == ProfileVisibility::VIS_PRIVATE) {
+ $uf->requireProfiles();
+ $conds[] = 'p.cv ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->description);
+ }
+ return implode(' OR ', $conds);
+ }
+}
+// }}}
+// {{{ class UFC_Networking
+/** Filters users based on network identity (IRC, ...)
+ * @param $type Type of network (-1 for any)
+ * @param $value Value to search
+ */
+class UFC_Networking extends UserFilterCondition
+{
+ private $type;
+ private $value;
+
+ public function __construct($type, $value)
+ {
+ $this->type = $type;
+ $this->value = $value;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addNetworkingFilter();
+ $conds = array();
+ $conds[] = $uf->getVisibilityCondition($sub . '.pub');
+ $conds[] = $sub . '.address ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->value);
+ if ($this->type != -1) {
+ $conds[] = $sub . '.nwid = ' . XDB::format('{?}', $this->type);
+ }
+ return implode(' AND ', $conds);
+ }
+}
+// }}}
+// {{{ class UFC_Phone
+/** Filters users based on their phone number
+ * @param $num_type Type of number (pro/user/home)
+ * @param $phone_type Type of phone (fixed/mobile/fax)
+ * @param $number Phone number
+ */
+class UFC_Phone extends UserFilterCondition
+{
+ const NUM_PRO = 'pro';
+ const NUM_USER = 'user';
+ const NUM_HOME = 'address';
+ const NUM_ANY = 'any';
+
+ const PHONE_FIXED = 'fixed';
+ const PHONE_MOBILE = 'mobile';
+ const PHONE_FAX = 'fax';
+ const PHONE_ANY = 'any';
+
+ private $num_type;
+ private $phone_type;
+ private $number;
+
+ public function __construct($number, $num_type = self::NUM_ANY, $phone_type = self::PHONE_ANY)
+ {
+ $phone = new Phone(array('display' => $number));
+ $phone->format();
+ $this->number = $phone->search();
+ $this->num_type = $num_type;
+ $this->phone_type = $phone_type;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addPhoneFilter();
+ $conds = array();
+
+ $conds[] = $uf->getVisibilityCondition($sub . '.pub');
+
+ $conds[] = $sub . '.search_tel = ' . XDB::format('{?}', $this->number);
+ if ($this->num_type != self::NUM_ANY) {
+ $conds[] = $sub . '.link_type = ' . XDB::format('{?}', $this->num_type);
+ }
+ if ($this->phone_type != self::PHONE_ANY) {
+ $conds[] = $sub . '.tel_type = ' . XDB::format('{?}', $this->phone_type);
+ }
+ return implode(' AND ', $conds);
+ }
+}
+// }}}
+// {{{ class UFC_Medal
+/** Filters users based on their medals
+ * @param $medal ID of the medal
+ * @param $grade Grade of the medal (null for 'any')
+ */
+class UFC_Medal extends UserFilterCondition
+{
+ private $medal;
+ private $grade;
+
+ public function __construct($medal, $grade = null)
+ {
+ $this->medal = $medal;
+ $this->grade = $grade;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $conds = array();
+
+ // This will require profiles => table 'p' will be available.
+ $sub = $uf->addMedalFilter();
+
+ $conds[] = $uf->getVisibilityCondition('p.medals_pub');
+
+ $conds[] = $sub . '.mid = ' . XDB::format('{?}', $this->medal);
+ if ($this->grade != null) {
+ $conds[] = $sub . '.gid = ' . XDB::format('{?}', $this->grade);
+ }
+ return implode(' AND ', $conds);
+ }
+}
+// }}}
+// {{{ class UFC_Photo
+/** Filters profiles with photo
+ */
+class UFC_Photo extends UserFilterCondition
+{
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addPhotoFilter();
+ return $sub . '.attach IS NOT NULL AND ' . $uf->getVisibilityCondition($sub . '.pub');
+ }
+}
+// }}}
+// {{{ class UFC_Mentor
+class UFC_Mentor extends UserFilterCondition
+{
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addMentorFilter(UserFilter::MENTOR);
+ return $sub . '.expertise IS NOT NULL';
+ }
+}
+// }}}
+// {{{ class UFC_Mentor_Expertise
+/** Filters users by mentoring expertise
+ * @param $expertise Domain of expertise
+ */
+class UFC_Mentor_Expertise extends UserFilterCondition
+{
+ private $expertise;
+
+ public function __construct($expertise)
+ {
+ $this->expertise = $expertise;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addMentorFilter(UserFilter::MENTOR_EXPERTISE);
+ return $sub . '.expertise ' . XDB::formatWildcards(XDB::WILDCARD_CONTAINS, $this->expertise);
+ }
+}
+// }}}
+// {{{ class UFC_Mentor_Country
+/** Filters users by mentoring country
+ * @param $country Two-letters code of country being searched
+ */
+class UFC_Mentor_Country extends UserFilterCondition
+{
+ private $country;
+
+ public function __construct()
+ {
+ $this->country = pl_flatten(func_get_args());
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addMentorFilter(UserFilter::MENTOR_COUNTRY);
+ return $sub . '.country IN ' . XDB::format('{?}', $this->country);
+ }
+}
+// }}}
+// {{{ class UFC_Mentor_Terms
+/** Filters users based on the job terms they used in mentoring.
+ * @param $val The ID of the job term, or an array of such IDs
+ */
+class UFC_Mentor_Terms extends UserFilterCondition
+{
+ private $val;
+
+ public function __construct($val)
+ {
+ $this->val = $val;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addMentorFilter(UserFilter::MENTOR_TERM);
+ return $sub . '.jtid_1 = ' . XDB::escape($this->val);
+ }
+}
+// }}}
+// {{{ class UFC_UserRelated
+/** Filters users based on a relation toward a user
+ * @param $user User to which searched users are related
+ */
+abstract class UFC_UserRelated extends UserFilterCondition
+{
+ protected $user;
+ public function __construct(PlUser &$user)
+ {
+ $this->user =& $user;
+ }
+}
+// }}}
+// {{{ class UFC_Contact
+/** Filters users who belong to selected user's contacts
+ */
+class UFC_Contact extends UFC_UserRelated
+{
+ public function buildCondition(PlFilter $uf)
+ {
+ $sub = $uf->addContactFilter($this->user->id());
+ return 'c' . $sub . '.contact IS NOT NULL';
+ }
+}
+// }}}
+// {{{ class UFC_WatchRegistration
+/** Filters users being watched by selected user
+ */
+class UFC_WatchRegistration extends UFC_UserRelated
+{
+ public function buildCondition(PlFilter $uf)
+ {
+ if (!$this->user->watchType('registration')) {
+ return PlFilterCondition::COND_FALSE;
+ }
+ $uids = $this->user->watchUsers();
+ if (count($uids) == 0) {
+ return PlFilterCondition::COND_FALSE;
+ } else {
+ return XDB::format('$UID IN {?}', $uids);
+ }
+ }
+}
+// }}}
+// {{{ class UFC_WatchPromo
+/** Filters users belonging to a promo watched by selected user
+ * @param $user Selected user (the one watching promo)
+ * @param $grade Formation the user is watching
+ */
+class UFC_WatchPromo extends UFC_UserRelated
+{
+ private $grade;
+ public function __construct(PlUser &$user, $grade = UserFilter::GRADE_ING)
+ {
+ parent::__construct($user);
+ $this->grade = $grade;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $promos = $this->user->watchPromos();
+ if (count($promos) == 0) {
+ return PlFilterCondition::COND_FALSE;
+ } else {
+ $sube = $uf->addEducationFilter(true, $this->grade);
+ $field = 'pe' . $sube . '.' . UserFilter::promoYear($this->grade);
+ return XDB::format($field . ' IN {?}', $promos);
+ }
+ }
+}
+// }}}
+// {{{ class UFC_WatchContact
+/** Filters users watched by selected user
+ */
+class UFC_WatchContact extends UFC_Contact
+{
+ public function buildCondition(PlFilter $uf)
+ {
+ if (!$this->user->watchContacts()) {
+ return PlFilterCondition::COND_FALSE;
+ }
+ return parent::buildCondition($uf);
+ }
+}
+// }}}
+// {{{ class UFC_MarketingHash
+/** Filters users using the hash generated
+ * to send marketing emails to him.
+ */
+class UFC_MarketingHash extends UserFilterCondition
+{
+ private $hash;
+
+ public function __construct($hash)
+ {
+ $this->hash = $hash;
+ }
+
+ public function buildCondition(PlFilter $uf)
+ {
+ $table = $uf->addMarketingHash();
+ return XDB::format('rm.hash = {?}', $this->hash);
+ }
+}
+// }}}
+
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+?>
--- /dev/null
+<?php
+/***************************************************************************
+ * Copyright (C) 2003-2010 Polytechnique.org *
+ * http://opensource.polytechnique.org/ *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the Free Software *
+ * Foundation, Inc., *
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
+ ***************************************************************************/
+
+// {{{ abstract class UserFilterOrder
+/** Class providing factories for the UserFilterOrders.
+ */
+abstract class UserFilterOrders
+{
+ public static function fromExport(array $export)
+ {
+ $export = new PlDict($export);
+ if (!$export->has('type')) {
+ throw new Exception("Missing type in export");
+ }
+ $type = $export->s('type');
+ $desc = ($export->s('order') == 'desc');
+ switch ($type) {
+ case 'promo':
+ return new UFO_Promo($export->v('grade'), $desc);
+
+ case 'lastname':
+ case 'name':
+ case 'firstname':
+ case 'nickname':
+ case 'pseudonym':
+ return new UFO_Name($type, $export->v('variant'),
+ $export->b('particle'), $desc);
+
+ case 'score':
+ case 'registration':
+ case 'birthday':
+ case 'profile_update':
+ case 'death':
+ case 'uid':
+ case 'hruid':
+ case 'pid':
+ case 'hrpid':
+ $class = 'UFO_' . str_replace('_', '', $type);
+ return new $class($desc);
+
+ default:
+ throw new Exception("Unknown order field: $type");
+ }
+ }
+}
+// }}}
+// {{{ class UFO_Promo
+/** Orders users by promotion
+ * @param $grade Formation whose promotion users should be sorted by (restricts results to users of that formation)
+ * @param $desc Whether sort is descending
+ */
+class UFO_Promo extends PlFilterGroupableOrder
+{
+ private $grade;
+
+ public function __construct($grade = null, $desc = false)
+ {
+ parent::__construct($desc);
+ $this->grade = $grade;
+ }
+
+ protected function getSortTokens(PlFilter $uf)
+ {
+ if (UserFilter::isGrade($this->grade)) {
+ $sub = $uf->addEducationFilter($this->grade);
+ return 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
+ } else {
+ $sub = $uf->addDisplayFilter();
+ return 'pd' . $sub . '.promo';
+ }
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport('promo');
+ if (!is_null($this->grade)) {
+ $export['grade'] = $this->grade;
+ }
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFO_Name
+/** Sorts users by name
+ * @param $type Type of name on which to sort (firstname...)
+ * @param $variant Variant of that name to use (marital, ordinary...)
+ * @param $particle Set to true if particles should be included in the sorting order
+ * @param $desc If sort order should be descending
+ */
+class UFO_Name extends PlFilterOrder
+{
+ private $type;
+ private $variant;
+ private $particle;
+
+ public function __construct($type, $variant = null, $particle = false, $desc = false)
+ {
+ parent::__construct($desc);
+ $this->type = $type;
+ $this->variant = $variant;
+ $this->particle = $particle;
+ }
+
+ protected function getSortTokens(PlFilter $uf)
+ {
+ if (Profile::isDisplayName($this->type)) {
+ $sub = $uf->addDisplayFilter();
+ $token = 'pd' . $sub . '.' . $this->type;
+ if ($uf->accountsRequired()) {
+ $account_token = Profile::getAccountEquivalentName($this->type);
+ return 'IFNULL(' . $token . ', a.' . $account_token . ')';
+ } else {
+ return $token;
+ }
+ } else {
+ $sub = $uf->addNameFilter($this->type, $this->variant);
+ if ($this->particle) {
+ return 'CONCAT(pn' . $sub . '.particle, \' \', pn' . $sub . '.name)';
+ } else {
+ return 'pn' . $sub . '.name';
+ }
+ }
+ }
+
+ public function export()
+ {
+ $export = $this->buildExport($this->type);
+ if (!is_null($this->variant)) {
+ $export['variant'] = $this->variant;
+ }
+ if ($this->particle) {
+ $export['particle'] = true;
+ }
+ return $export;
+ }
+}
+// }}}
+// {{{ class UFO_Score
+class UFO_Score extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $toks = $uf->getNameTokens();
+ $scores = array();
+
+ // If there weren't any sort tokens, we shouldn't sort by score, sort by NULL instead
+ if (count($toks) == 0) {
+ return 'NULL';
+ }
+
+ foreach ($toks as $sub => $token) {
+ $scores[] = XDB::format('SUM(' . $sub . '.score + IF (' . $sub . '.token = {?}, 5, 0) )', $token);
+ }
+ return implode(' + ', $scores);
+ }
+
+ public function export()
+ {
+ return $this->buildExport('score');
+ }
+}
+// }}}
+// {{{ class UFO_Registration
+/** Sorts users based on registration date
+ */
+class UFO_Registration extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $uf->requireAccounts();
+ return 'a.registration_date';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('registration');
+ }
+}
+// }}}
+// {{{ class UFO_Birthday
+/** Sorts users based on next birthday date
+ */
+class UFO_Birthday extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return 'p.next_birthday';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('birthday');
+ }
+}
+// }}}
+// {{{ class UFO_ProfileUpdate
+/** Sorts users based on last profile update
+ */
+class UFO_ProfileUpdate extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return 'p.last_change';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('profile_update');
+ }
+}
+// }}}
+// {{{ class UFO_Death
+/** Sorts users based on death date
+ */
+class UFO_Death extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return 'p.deathdate';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('death');
+ }
+}
+// }}}
+// {{{ class UFO_Uid
+/** Sorts users based on their uid
+ */
+class UFO_Uid extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $uf->requireAccounts();
+ return '$UID';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('uid');
+ }
+}
+// }}}
+// {{{ class UFO_Hruid
+/** Sorts users based on their hruid
+ */
+class UFO_Hruid extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $uf->requireAccounts();
+ return 'a.hruid';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('hruid');
+ }
+}
+// }}}
+// {{{ class UFO_Pid
+/** Sorts users based on their pid
+ */
+class UFO_Pid extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return '$PID';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('pid');
+ }
+}
+// }}}
+// {{{ class UFO_Hrpid
+/** Sorts users based on their hrpid
+ */
+class UFO_Hrpid extends PlFilterOrder
+{
+ protected function getSortTokens(PlFilter $uf)
+ {
+ $uf->requireProfiles();
+ return 'p.hrpid';
+ }
+
+ public function export()
+ {
+ return $this->buildExport('hrpid');
+ }
+}
+// }}}
+
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+?>
; 1 - DEBUG_BT: displays the backtraces (SQL, mailman, banana executions)
; 2 - DEBUG_VALID: checks that the html of the page is valid
; 4 - DEBUG_SMARTY: don't hide error reported during the execution of smarty
+; 8 - DEBUG_NOCACHE: disable data caching
+; 16 - DEBUG_SCRIPTCACHE: cache expires after the execution of the script (no caching
+; in session or via memcache)
; - provided by xorg:
-; 256 - DEBUG_NOCACHE: don't cache db content in the session
+; 256 - DEBUG_NOCACHE: don't cache db content in the session (this feature as been moved
+; to the core and this flag is deprecated)
;
; debug = 0
; The charset to use when talking to the database
; dbcharset = "utf8"
+; $globals->core->memcache
+; List of space separated addresses of memcache servers
+memcache = ""
+
; $globals->static_cache_duration
; Cache duration for static content
; static_cache_duration = "604800"
-Subproject commit 2055d886e01ef029b4eee998cea108351d74c188
+Subproject commit cb22cf2a3b34e4f263dcfb6b51396111f8d6b785
+++ /dev/null
-/***************************************************************************
- * Copyright (C) 2003-2010 Polytechnique.org *
- * http://opensource.polytechnique.org/ *
- * *
- * This program is free software; you can redistribute it and/or modify *
- * it under the terms of the GNU General Public License as published by *
- * the Free Software Foundation; either version 2 of the License, or *
- * (at your option) any later version. *
- * *
- * This program is distributed in the hope that it will be useful, *
- * but WITHOUT ANY WARRANTY; without even the implied warranty of *
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
- * GNU General Public License for more details. *
- * *
- * You should have received a copy of the GNU General Public License *
- * along with this program; if not, write to the Free Software *
- * Foundation, Inc., *
- * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
- ***************************************************************************/
-
-function AjaxEngine()
-{
- this.update_html = function(obj, src, func)
- {
- $.get(src,
- function(data, textStatus) {
- if (textStatus == "success") {
- if (obj) {
- $('#' + obj).html(data);
- }
- if (func) {
- func(data);
- }
- } else if (textStatus == "error") {
- alert("Une erreur s'est produite lors du traitement de la requête.\n"
- +"Ta session a peut-être expirée.");
- }
- }, 'text');
- return false;
- }
-}
-
-var Ajax = new AjaxEngine();
-
-var currentTempMessage = 0;
-function setOpacity(obj, opacity)
-{
- opacity = (opacity == 100)?99:opacity;
- // IE
- obj.style.filter = "alpha(opacity:"+opacity+")";
- // Safari < 1.2, Konqueror
- obj.style.KHTMLOpacity = opacity/100;
- // Old Mozilla
- obj.style.MozOpacity = opacity/100;
- // Safari >= 1.2, Firefox and Mozilla, CSS3
- obj.style.opacity = opacity/100
-}
-
-function _showTempMessage(id, state, back)
-{
- var obj = document.getElementById(id);
- if (currentTempMessage != state) {
- return;
- }
- setOpacity(obj, back * 4);
- if (back > 0) {
- setTimeout("_showTempMessage('" + id + "', " + currentTempMessage + "," + (back-1) + ")", 125);
- } else {
- obj.innerHTML = "";
- }
-}
-
-function showTempMessage(id, message, success)
-{
- var obj = document.getElementById(id);
- obj.innerHTML = (success ? "<img src='images/icons/wand.gif' alt='' /> "
- : "<img src='images/icons/error.gif' alt='' /> ") + message;
- obj.style.fontWeight = "bold";
- obj.style.color = (success ? "green" : "red");;
- currentTempMessage++;
- setOpacity(obj, 100);
- setTimeout("_showTempMessage('" + id + "', " + currentTempMessage + ", 25)", 1000);
-}
-
-function previewWiki(idFrom, idTo, withTitle, idShow)
-{
- var text = document.getElementById(idFrom).value;
- if (text == "") {
- return false;
- }
- var url = "wiki_preview";
- if (!withTitle) {
- url += "/notitle";
- }
- $.post(url, { text: text },
- function(data) {
- $("#" + idTo).html(data);
- },
- 'text');
- if (idShow != null) {
- document.getElementById(idShow).style.display = "";
- }
-}
-
-function sendTestEmail(token, hruid)
-{
- Ajax.update_html(null, 'emails/test' + (hruid == null ? '' : '/' + hruid) + '?token=' + token,
- function() {
- showTempMessage('mail_sent', "Un email a été envoyé avec succès"
- + (hruid == null ? " sur ton adresse." : " sur l'adresse de " + hruid),
- true); });
- return false;
-}
-
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
_toggle(_gel("mark-read-" + event_id));
_gel("evt-" + event_id).setAttribute("class", "read");
_gel("link-" + event_id).setAttribute("href", "events/unread/" + event_id);
- Ajax.update_html(null, "events/read/" + event_id);
+ $.xget("events/read/" + event_id);
return false;
}
while ($('#search_name_' + i).length != 0) {
i++;
}
- Ajax.update_html('search_name_' + i, 'profile/ajax/searchname/' + i + '/' + isFemale, function(data){
- $('#searchname').before(data);
- changeNameFlag(i);
- });
+ $('#search_name_' + i)
+ .updateHtml('profile/ajax/searchname/' + i + '/' + isFemale,
+ function(data) {
+ $('#searchname').before(data);
+ changeNameFlag(i);
+ });
}
function removeSearchName(i, isFemale)
searchnames += $('#search_name_' + i).find(':text').val() + ';;';
}
}
- Ajax.update_html(null, 'profile/ajax/buildnames/' + searchnames + '/' + isFemale, function(data){
- var name = data.split(';');
- $('#public_name').html(name[0]);
- $('#private_name').html(name[0] + name[1]);
- });
+ $.xget('profile/ajax/buildnames/' + searchnames + '/' + isFemale,
+ function(data){
+ var name = data.split(';');
+ $('#public_name').html(name[0]);
+ $('#private_name').html(name[0] + name[1]);
+ });
}
function toggleParticle(id)
i++;
}
$('#add_address').before('<div id="addresses_' + i + '_cont"></div>');
- Ajax.update_html('addresses_' + i + '_cont', 'profile/ajax/address/' + i, checkCurrentAddress());
+ $('#addresses_' + i + '_cont').updateHtml('profile/ajax/address/' + i,
+ checkCurrentAddress());
}
function addressChanged(prefid)
i++;
}
$('#' + prefix + 'add').before('<div id="' + prefix + i + '" style="clear: both; padding-top: 4px; padding-bottom: 4px"></div>');
- Ajax.update_html(prefix + i, 'profile/ajax/tel/' + prefid + '/' + prefname + '/' + i);
+ $('#' + prefix + i).updateHtml('profile/ajax/tel/' + prefid + '/' + prefname + '/' + i);
}
function removeTel(prefname, prefid, id)
var is_IE = $.browser.msie;
// {{{ function getNow()
+var days = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
+var months = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet',
+ 'août', 'septembre', 'octobre', 'novembre', 'décembre']
function getNow() {
- dt = new Date();
- dy = dt.getDay();
- mh = dt.getMonth();
- wd = dt.getDate();
- yr = dt.getYear();
+ var dt = new Date();
+ var dy = dt.getDay();
+ var mh = dt.getMonth();
+ var wd = dt.getDate();
+ var yr = dt.getYear();
if (yr<1000) yr += 1900;
- hr = dt.getHours();
- mi = dt.getMinutes();
-
- time = (mi < 10) ? hr +':0'+mi : hr+':'+mi;
- days = ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'];
- months = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet',
- 'août', 'septembre', 'octobre', 'novembre', 'décembre']
+ var hr = dt.getHours();
+ var mi = dt.getMinutes();
+ if (mi < 10) {
+ mi = '0' + mi;
+ }
+ var se = dt.getSeconds();
+ if (se < 10) {
+ se = '0' + se;
+ }
- return days[dy]+' '+wd+' '+months[mh]+' '+yr+'<br />'+time;
+ $(".date-heure").html(days[dy] + ' ' + wd + ' ' + months[mh] + ' ' + yr + '<br />'
+ + hr + ':' + mi + ':' + se);
}
// }}}
* POPUP THINGS
*/
-// {{{ function popWin()
-
-function popWin(theNode, w, h) {
- window.open(theNode.href, '_blank',
- 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width='+w+',height='+h);
- return false;
-}
-
-// }}}
// {{{ function goodiesPopup()
var __goodies_active = true;
// {{{ function auto_links()
function auto_links() {
- url = document.URL;
- fqdn = url.replace(/^https?:\/\/([^\/]*)\/.*$/,'$1');
- light = (url.indexOf('display=light') > url.indexOf('?'));
- resource_page = (url.indexOf('rss') > -1 || url.indexOf('ical') > -1);
-
- $("a,link").each(
- function(i) {
- node = $(this);
- href = this.href;
- if(!href || node.hasClass('xdx')
- || href.indexOf('mailto:') > -1 || href.indexOf('javascript:') > -1) {
- return;
- }
- if ((href.indexOf(fqdn) < 0 && this.className.indexOf('popup') < 0) || node.hasClass('popup')) {
- node.click(function () { window.open(this.href); return false; });
- }
- if (href.indexOf(fqdn) > -1 && light) {
- href = href.replace(/([^\#\?]*)\??([^\#]*)(\#.*)?/, "$1?display=light&$2$3");
- this.href = href;
- }
- rss = href.indexOf('rss') > -1;
- ical = href.indexOf('ical') > -1;
- if (rss || ical) {
- if (href.indexOf('http') < 0) {
- href = 'http://' + fqdn + '/' + href;
- }
- }
- if (this.nodeName.toLowerCase() == 'a' && !resource_page) {
- if (rss && href.indexOf('prefs/rss') < 0 && (href.indexOf('xml') > -1 || href.indexOf('hash'))) {
- goodiesPopup(this, __goodies_rss);
- } else if (ical) {
- goodiesPopup(this, __goodies_ical);
- }
+ var url = document.URL;
+ var fqdn = url.replace(/^https?:\/\/([^\/]*)\/.*$/,'$1');
+ var light = (url.indexOf('display=light') > url.indexOf('?'));
+ var resource_page = (url.indexOf('rss') > -1 || url.indexOf('ical') > -1);
+
+ $("a,link").each(function(i) {
+ var node = $(this);
+ var href = this.href;
+ if(!href || node.hasClass('xdx')
+ || href.indexOf('mailto:') > -1 || href.indexOf('javascript:') > -1) {
+ return;
+ }
+ if ((href.indexOf(fqdn) < 0 && this.className.indexOf('popup') < 0) || node.hasClass('popup')) {
+ node.click(function () {
+ window.open(href);
+ return false;
+ });
+ }
+ if (href.indexOf(fqdn) > -1 && light) {
+ href = href.replace(/([^\#\?]*)\??([^\#]*)(\#.*)?/, "$1?display=light&$2$3");
+ this.href = href;
+ }
+ var rss = href.indexOf('rss') > -1;
+ var ical = href.indexOf('ical') > -1;
+ if (rss || ical) {
+ if (href.indexOf('http') < 0) {
+ href = 'http://' + fqdn + '/' + href;
}
- if(matches = (/^popup_([0-9]*)x([0-9]*)$/).exec(this.className)) {
- var w = matches[1], h = matches[2];
- node.click(function() { return popWin(this, w, h); });
+ }
+ if (this.nodeName.toLowerCase() == 'a' && !resource_page) {
+ if (rss && href.indexOf('prefs/rss') < 0 && (href.indexOf('xml') > -1 || href.indexOf('hash'))) {
+ goodiesPopup(this, __goodies_rss);
+ } else if (ical) {
+ goodiesPopup(this, __goodies_ical);
}
}
- );
- $('.popup2').click(function() { return popWin(this, 840, 600); });
- $('.popup3').click(function() { return popWin(this, 640, 800); });
+ if(matches = (/^popup_([0-9]*)x([0-9]*)$/).exec(this.className)) {
+ var w = matches[1], h = matches[2];
+ node.popWin(w, h);
+ }
+ });
+ $('.popup2').popWin(840, 600);
+ $('.popup3').popWin(640, 800);
}
// }}}
-
/***************************************************************************
* Password check
*/
}
// }}}
+// {{{ jQuery object extension
+
+(function($) {
+ /* Add new functions to jQuery namesapce */
+ $.extend({
+ /* The goal of the following functions is to provide an AJAX API that
+ * take a different callback in case of HTTP success code (2XX) and in
+ * other cases.
+ */
+
+ xajax: function(source, method, data, onSuccess, onError, type) {
+ /* Shift argument */
+ if ($.isFunction(data)) {
+ type = type || onError;
+ onError = onSuccess;
+ onSuccess = data;
+ data = null;
+ }
+ if (onError != null && !$.isFunction(onError)) {
+ type = type || onError;
+ onError = null;
+ }
+
+ function ajaxHandler(data, textStatus, xhr) {
+ if (textStatus == 'success') {
+ if (onSuccess) {
+ onSuccess(data, textStatus, xhr);
+ }
+ } else if (textStatus == 'error') {
+ if (onError) {
+ onError(data, textStatus, xhr);
+ } else {
+ alert("Une error s'est produite lors du traitement de la requête.\n"
+ + "Ta session a peut-être expiré");
+ }
+ }
+ }
+ return $.ajax({
+ url: source,
+ type: method,
+ success: ajaxHandler,
+ data : data,
+ dataType: type
+ });
+ },
+
+ xget: function(source, data, onSuccess, onError, type) {
+ return $.xajax(source, 'GET', data, onSuccess, onError, type);
+ },
+
+ xgetJSON: function(source, data, onSuccess, onError) {
+ return $.xget(source, data, onSuccess, onError, 'json');
+ },
+
+ xgetScript: function(source, onSuccess, onError) {
+ return $.xget(source, null, onSuccess, onError, 'script');
+ },
+
+ xgetText: function(source, data, onSuccess, onError) {
+ return $.xget(source, data, onSuccess, onError, 'text');
+ },
+
+ xpost: function(source, data, onSuccess, onError, type) {
+ return $.xajax(source, 'POST', data, onSuccess, onError, type);
+ }
+ });
+
+ /* Add new functions to jQuery objects */
+ $.fn.extend({
+ tmpMessage: function(message, success) {
+ if (success) {
+ this.html("<img src='images/icons/wand.gif' alt='' /> " + message)
+ .css('color', 'green');
+ } else {
+ this.html("<img src='images/icons/error.gif' alt='' /> " + message)
+ .css('color', 'red');
+ }
+ return this.css('fontWeight', 'bold')
+ .show()
+ .delay(1000)
+ .fadeOut(500);
+ },
+
+ updateHtml: function(source, callback) {
+ var elements = this;
+ function handler(data) {
+ elements.html(data);
+ if (callback) {
+ callback(data);
+ }
+ }
+ $.xget(source, handler, 'text');
+ return this;
+ },
+
+ successMessage: function(source, message) {
+ var elements = this;
+ $.xget(source, function() {
+ elements.tmpMessage(message, true);
+ });
+ return this;
+ },
+
+ wiki: function(text, withTitle) {
+ if (text == '') {
+ return this.html('');
+ }
+ var url = 'wiki_preview';
+ if (!withTitle) {
+ url += '/notitile';
+ }
+ var $this = this;
+ $.post(url, { text: text },
+ function (data) {
+ $this.html(data);
+ }, 'text');
+ return this;
+ },
+
+ popWin: function(w, h) {
+ return this.click(function() {
+ window.open(this.href, '_blank',
+ 'toolbar=0,location=0,directories=0,status=0,'
+ +'menubar=0,scrollbars=1,resizable=1,'
+ +'width='+w+',height='+h);
+ return false;
+ });
+ }
+ });
+})(jQuery);
+
+// }}}
+// {{{ preview wiki
+
+function previewWiki(idFrom, idTo, withTitle, idShow)
+{
+ $('#' + idTo).wiki($('#' + idFrom).val(), withTitle);
+ if (idShow != null) {
+ $('#' + idShow).show();
+ }
+}
+
+// }}}
+// {{{ send test email
+
+function sendTestEmail(token, hruid)
+{
+ var url = 'emails/test';
+ var msg = "Un email a été envoyé avec succès";
+ if (hruid != null) {
+ url += '/' + hruid;
+ msg += " sur l'adresse de " + hruid + ".";
+ } else {
+ msg += " sur ton addresse.";
+ }
+ $('#mail_sent').successMessage($url + '?token=' + token, msg);
+ return false;
+}
+
+// }}}
/***************************************************************************
* The real OnLoad
*/
-$(document).ready(auto_links);
+$(document).ready(function() {
+ auto_links();
+ getNow();
+ setInterval(getNow, 1000);
+ $("#quick")
+ .focus(function() {
+ if ($(this).val() === 'Recherche dans l\'annuaire') {
+ $(this).val('');
+ }
+ $("#quick_button").show();
+ })
+ .blur(function() {
+ $("#quick_button").hide();
+ });
+ $("#quick_button").click(function() {
+ if ($("#quick").val() === 'Recherche dans l\'annuaire'
+ || $("#quick").val() === '') {
+ return false;
+ }
+ return true;
+ });
+});
// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
$emailsCount = 0;
while (true) {
+ $sent = array();
$users = User::getBulkUsersWithUIDs(XDB::fetchColumn($query));
if (count($users) == 0) {
return $emailsCount;
}
foreach ($users as $user) {
- $sent[] = XDB::format('uid = {?}', $user->id());
+ $sent[] = $user->id();
$this->sendTo($user, $hash);
++$emailsCount;
}
XDB::execute("UPDATE {$this->_subscriptionTable}
SET last = {?}
- WHERE " . implode(' OR ', $sent), $this->_id);
+ WHERE uid IN {?}", $this->_id, $sent);
sleep(60);
}
$page->assign_by_ref('mails', $sql);
}
- function handler_postfix_regexpsbounces(&$page, $new = null) {
- $page->changeTpl('admin/emails_bounces_re.tpl');
- $page->setTitle('Administration - Postfix : Regexps Bounces');
- $page->assign('new', $new);
-
- if (Post::has('submit')) {
- foreach (Env::v('lvl') as $id=>$val) {
- XDB::query(
- "REPLACE INTO emails_bounces_re (id,pos,lvl,re,text) VALUES ({?}, {?}, {?}, {?}, {?})",
- $id, $_POST['pos'][$id], $_POST['lvl'][$id], $_POST['re'][$id], $_POST['text'][$id]
- );
- }
- }
-
- $page->assign('bre', XDB::iterator("SELECT * FROM emails_bounces_re ORDER BY pos"));
- }
-
// {{{ logger view
/** Retrieves the available days for a given year and month.
$page->addJsLink('jquery.ui.core.js');
+ $page->addJsLink('jquery.ui.widget.js');
$page->addJsLink('jquery.ui.tabs.js');
$page->addJsLink('password.js');
$page->changeTpl('admin/validation.tpl');
$page->setTitle('Administration - Valider une demande');
$page->addCssLink('nl.css');
- $page->addJsLink('ajax.js');
if ($action == 'edit' && !is_null($id)) {
$page->assign('preview_id', $id);
function handler_send(&$page)
{
$page->changeTpl('emails/send.tpl');
- $page->addJsLink('ajax.js');
$page->setTitle('Envoyer un email');
function handler_ev(&$page, $action = 'list', $eid = null, $pound = null)
{
$page->changeTpl('events/index.tpl');
- $page->addJsLink('ajax.js');
$user = S::user();
function handler_ev_submit(&$page)
{
$page->changeTpl('events/submit.tpl');
- $page->addJsLink('ajax.js');
$wp = new PlWikiPage('Xorg.Annonce');
$wp->buildCache();
function handler_admin_events(&$page, $action = 'list', $eid = null)
{
$page->changeTpl('events/admin.tpl');
- $page->addJsLink('ajax.js');
$page->setTitle('Administration - Evenements');
$page->register_modifier('hde', 'html_entity_decode');
$domain = $this->prepare_client($page);
$page->changeTpl('lists/index.tpl');
- $page->addJsLink('ajax.js');
$page->setTitle('Listes de diffusion');
function luhn($nombre) {
$s = strrev($nombre);
$sum = 0;
- for ($i = 0; $i < strlen($s); $i++) {
+ for ($i = 0; $i < strlen($s); ++$i) {
$dgt = $s{$i};
- $sum += ($i % 2) ? (2*$dgt) % 9 : $dgt;
+ $sum += ($i % 2) ? (2 * $dgt) % 9 : $dgt;
}
return $sum % 10;
}
/* calcule la clé d'acceptation a partir de 5 champs */
-function cle_accept($d1,$d2,$d3,$d4,$d5)
+function cle_accept($d1, $d2, $d3, $d4, $d5)
{
- $m1 = luhn($d1.$d5);
- $m2 = luhn($d2.$d5);
- $m3 = luhn($d3.$d5);
- $m4 = luhn($d4.$d5);
+ $m1 = luhn($d1 . $d5);
+ $m2 = luhn($d2 . $d5);
+ $m3 = luhn($d3 . $d5);
+ $m4 = luhn($d4 . $d5);
$n = $m1 + $m2 + $m3 + $m4;
- $alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- return $alpha{$n-1}.$m1.$m2.$m3.$m4;
+ $alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
+ return $alpha{$n-1} . $m1 . $m2 . $m3 . $m4;
}
/* decode the comment */
function check_rib($rib)
{
if(strlen($rib) != 23) return false;
-
+
// extract fields
$rib = strtr(strtoupper($rib),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','12345678912345678923456789');
$bank = substr($rib,0,5);
$counter = substr($rib,5,5);
$account = substr($rib,10,11);
$key = substr($rib,21,2);
-
+
// check
- return 0 == fmod(89 * $bank + 15 * $counter + 3 * $account + $key, 97);
+ return (0 == fmod(89 * $bank + 15 * $counter + 3 * $account + $key, 97));
}
class PaymentModule extends PLModule
function handlers()
{
return array(
- 'payment' => $this->make_hook('payment', AUTH_MDP, 'payment'),
- 'payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC, 'user', NO_HTTPS),
- 'payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC, 'user', NO_HTTPS),
- 'payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC, 'user', NO_HTTPS),
- '%grp/paiement' => $this->make_hook('xnet_payment', AUTH_MDP),
- '%grp/payment' => $this->make_hook('xnet_payment', AUTH_MDP),
- '%grp/payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC, 'user', NO_HTTPS),
- '%grp/payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC, 'user', NO_HTTPS),
- '%grp/payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC, 'user', NO_HTTPS),
- 'admin/payments' => $this->make_hook('admin', AUTH_MDP, 'admin'),
- 'admin/payments/methods' => $this->make_hook('adm_methods', AUTH_MDP, 'admin'),
- 'admin/payments/transactions'=> $this->make_hook('adm_transactions', AUTH_MDP, 'admin'),
- 'admin/reconcile' => $this->make_hook('adm_reconcile', AUTH_MDP, 'admin'),
- 'admin/reconcile/importlogs' => $this->make_hook('adm_importlogs', AUTH_MDP, 'admin'),
- 'admin/reconcile/transfers' => $this->make_hook('adm_transfers', AUTH_MDP, 'admin'),
- 'admin/reconcile/bankaccounts'=> $this->make_hook('adm_bankaccounts', AUTH_MDP, 'admin'),
+ 'payment' => $this->make_hook('payment', AUTH_MDP, 'payment'),
+ 'payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC, 'user', NO_HTTPS),
+ 'payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC, 'user', NO_HTTPS),
+ 'payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC, 'user', NO_HTTPS),
+ '%grp/paiement' => $this->make_hook('xnet_payment', AUTH_MDP),
+ '%grp/payment' => $this->make_hook('xnet_payment', AUTH_MDP),
+ '%grp/payment/cyber_return' => $this->make_hook('cyber_return', AUTH_PUBLIC, 'user', NO_HTTPS),
+ '%grp/payment/cyber2_return' => $this->make_hook('cyber2_return', AUTH_PUBLIC, 'user', NO_HTTPS),
+ '%grp/payment/paypal_return' => $this->make_hook('paypal_return', AUTH_PUBLIC, 'user', NO_HTTPS),
+ 'admin/payments' => $this->make_hook('admin', AUTH_MDP, 'admin'),
+ 'admin/payments/methods' => $this->make_hook('adm_methods', AUTH_MDP, 'admin'),
+ 'admin/payments/transactions' => $this->make_hook('adm_transactions', AUTH_MDP, 'admin'),
+ 'admin/reconcile' => $this->make_hook('adm_reconcile', AUTH_MDP, 'admin'),
+ 'admin/reconcile/importlogs' => $this->make_hook('adm_importlogs', AUTH_MDP, 'admin'),
+ 'admin/reconcile/transfers' => $this->make_hook('adm_transfers', AUTH_MDP, 'admin'),
+ 'admin/reconcile/bankaccounts' => $this->make_hook('adm_bankaccounts', AUTH_MDP, 'admin'),
);
}
if (!$globals->asso('id')) {
return PL_NOT_FOUND;
}
- $res = XDB::query("SELECT asso_id
- FROM payments
- WHERE asso_id = {?} AND id = {?}",
+ $res = XDB::query('SELECT asso_id
+ FROM payments
+ WHERE asso_id = {?} AND id = {?}',
$globals->asso('id'), $ref);
if (!$res->numRows()) {
return PL_FORBIDDEN;
$page->trigError($e);
}
- if ($op=='submit') {
+ if ($op == 'submit') {
$pay->init($val, $meth);
$pay->prepareform($pay);
} else {
- $res = XDB::iterator("SELECT timestamp, amount
+ $res = XDB::iterator('SELECT timestamp, amount
FROM payment_transactions
WHERE uid = {?} AND ref = {?}
- ORDER BY timestamp DESC",
+ ORDER BY timestamp DESC',
S::v('uid', -1), $ref);
- if ($res->total()) $page->assign('transactions', $res);
+ if ($res->total()) {
+ $page->assign('transactions', $res);
+ }
}
- $val = floor($val).".".substr(floor(($val - floor($val))*100+100),1);
- $page->assign('montant',$val);
- $page->assign('comment',Env::v('comment'));
+ $val = floor($val) . '.' . substr(floor(($val - floor($val)) * 100 + 100), 1);
+ $page->assign('montant', $val);
+ $page->assign('comment', Env::v('comment'));
$page->assign('meth', $meth);
- $page->assign('pay', $pay);
+ $page->assign('pay', $pay);
$page->assign('evtlink', $pay->event());
}
}
echo ($ref = $matches[1]);
- $res = XDB::query("SELECT mail, text, confirmation
+ $res = XDB::query('SELECT mail, text, confirmation
FROM payments
- WHERE id={?}", $ref);
+ WHERE id = {?}', $ref);
if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
cb_erreur("référence de commande inconnue");
}
}
/* on fait l'insertion en base de donnees */
- XDB::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
- VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
+ XDB::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
+ VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
$champ901, $user->id(), $ref, $champ200, $montant, $champ905, Env::v('comment'));
// We check if it is an Xnet payment and then update the related ML.
/* on vérifie la signature */
$vads_params = array();
foreach($_REQUEST as $key => $value)
- if(substr($key,0,5) == "vads_")
+ if(substr($key,0,5) == 'vads_') {
$vads_params[$key] = $value;
+ }
ksort($vads_params);
- $signature = sha1(join('+',$vads_params).'+'.$globals->money->cyperplus_key);
+ $signature = sha1(join('+', $vads_params) . '+' . $globals->money->cyperplus_key);
//if($signature != Env::v('signature')) {
// cb_erreur("signature invalide");
//}
}
$ref = $matches[1];
- $res = XDB::query("SELECT mail, text, confirmation
+ $res = XDB::query('SELECT mail, text, confirmation
FROM payments
- WHERE id={?}", $ref);
+ WHERE id={?}', $ref);
if ($res->numRows() != 1) {
cb_erreur("référence de commande inconnue");
}
list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow();
/* on extrait le montant */
- if (Env::v('vads_currency') != "978") {
+ if (Env::v('vads_currency') != '978') {
cb_erreur("monnaie autre que l'euro");
}
$amount = ((float)Env::i('vads_amount')) / 100;
$montant = sprintf("%.02f EUR", $amount);
/* on extrait le code de retour */
- if (Env::v('vads_result') != "00") {
- cb_erreur("erreur lors du paiement : ?? (".Env::v('vads_result').")");
+ if (Env::v('vads_result') != '00') {
+ cb_erreur('erreur lors du paiement : ?? (' . Env::v('vads_result') . ')');
}
/* on fait l'insertion en base de donnees */
- XDB::execute("INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
- VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})",
- Env::v('vads_trans_date'), $user->id(), $ref, Env::v('vads_order_id'), $montant, "", Env::v('vads_order_info'));
+ XDB::execute('INSERT INTO payment_transactions (id, uid, ref, fullref, amount, pkey, comment)
+ VALUES ({?}, {?}, {?}, {?}, {?}, {?}, {?})',
+ Env::v('vads_trans_date'), $user->id(), $ref, Env::v('vads_order_id'), $montant, '', Env::v('vads_order_info'));
echo "Paiement stored.\n";
// We check if it is an Xnet payment and then update the related ML.
/* code retour */
$status = Env::s('st');
/* raison */
- $reason = ($status == 'Pending')? Env::s('pending_reason'): Env::s('reason_code');
+ $reason = ($status == 'Pending') ? Env::s('pending_reason') : Env::s('reason_code');
/* reference complete de la commande */
$fullref = Env::s('cm');
/* montant de la transaction */
/* on extrait le code de retour */
if ($status != "Completed") {
- if ($status)
+ if ($status) {
paypal_erreur("erreur lors du paiement : $status - $reason");
- else
+ } else {
paypal_erreur("Paiement annulé", false);
+ }
}
/* on extrait les informations sur l'utilisateur */
}
$ref = $matches[1];
- $res = XDB::query("SELECT mail, text, confirmation
+ $res = XDB::query('SELECT mail, text, confirmation
FROM payments
- WHERE id = {?}", $ref);
- if (!list($conf_mail,$conf_title,$conf_text) = $res->fetchOneRow()) {
- paypal_erreur("référence de commande inconnue");
+ WHERE id = {?}', $ref);
+ if (!list($conf_mail, $conf_title, $conf_text) = $res->fetchOneRow()) {
+ paypal_erreur('référence de commande inconnue');
}
/* on fait l'insertion en base de donnees */
return PL_FORBIDDEN;
}
$res = XDB::query("SELECT 1
- FROM group_events AS e
+ FROM group_events AS e
INNER JOIN group_event_participants AS ep ON (ep.eid = e.eid AND uid = {?})
WHERE e.paiement_id = {?} AND e.asso_id = {?}",
S::i('uid'), $pid, $globals->asso('id'));
WHERE asso_id = {?} AND NOT FIND_IN_SET('old', flags)
ORDER BY id DESC", $globals->asso('id'));
$tit = $res->fetchAllAssoc();
- $page->assign('titres', $tit);
-
+ $page->assign('titles', $tit);
- // TODO: replug sort.
$trans = array();
$event = array();
+ if (may_update()) {
+ static $orders = array('timestamp' => 'p', 'directory_name' => 'a', 'promo' => 'pd', 'comment' => 'p', 'amount' => 'p');
+
+ if (Get::has('order_id') && Get::has('order') && array_key_exists(Get::v('order'), $orders)) {
+ $order_id = Get::i('order_id');
+ $order = Get::v('order');
+ $ordering = ' ORDER BY ' . $orders[$order] . '.' . $order;
+ if (Get::has('order_inv') && Get::i('order_inv') == 1) {
+ $ordering .= ' DESC';
+ $page->assign('order_inv', 0);
+ } else {
+ $page->assign('order_inv', 1);
+ }
+ $page->assign('order_id', $order_id);
+ $page->assign('order', $order);
+ $page->assign('anchor', 'legend_' . $order_id);
+ } else {
+ $order_id = false;
+ $ordering = '';
+ $page->assign('order', false);
+ }
+ } else {
+ $ordering = '';
+ $page->assign('order', false);
+ }
foreach($tit as $foo) {
$pid = $foo['id'];
if (may_update()) {
- $res = XDB::query('SELECT t.uid, timestamp AS `date`, t.comment, amount
- FROM payment_transactions AS t
- WHERE t.ref = {?}', $pid);
+ $res = XDB::query('SELECT p.uid, IF(p.timestamp = \'0000-00-00\', 0, p.timestamp) AS date, p.comment, p.amount
+ FROM payment_transactions AS p
+ INNER JOIN accounts AS a ON (a.uid = p.uid)
+ LEFT JOIN account_profiles AS ap ON (ap.uid = p.uid AND FIND_IN_SET(\'owner\', ap.perms))
+ LEFT JOIN profile_display AS pd ON (ap.pid = pd.pid)
+ WHERE p.ref = {?}' . (($order_id == $pid) ? $ordering : ''),
+ $pid);
$trans[$pid] = User::getBulkUsersWithUIDs($res->fetchAllAssoc(), 'uid', 'user');
$sum = 0;
foreach ($trans[$pid] as $i => $t) {
$sum += strtr(substr($t['amount'], 0, strpos($t['amount'], 'EUR')), ',', '.');
$trans[$pid][$i]['amount'] = str_replace('EUR', '€', $t['amount']);
}
- $trans[$pid][] = array('nom' => 'somme totale',
- 'amount' => strtr($sum, '.', ',').' €');
+ $trans[$pid][] = array('limit' => true,
+ 'amount' => strtr($sum, '.', ',') . ' €');
}
- $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
- FROM group_events AS e
- LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
- INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
- WHERE e.paiement_id = {?}",
- S::v('uid'), $pid);
+ $res = XDB::iterRow("SELECT e.eid, e.short_name, e.intitule, ep.nb, ei.montant, ep.paid
+ FROM group_events AS e
+ LEFT JOIN group_event_participants AS ep ON (ep.eid = e.eid AND ep.uid = {?})
+ INNER JOIN group_event_items AS ei ON (ep.eid = ei.eid AND ep.item_id = ei.item_id)
+ WHERE e.paiement_id = {?}",
+ S::v('uid'), $pid);
$event[$pid] = array();
$event[$pid]['paid'] = 0;
if ($res->total()) {
$event[$pid]['paid'] = $paid;
}
}
- $res = XDB::query("SELECT amount
- FROM payment_transactions AS t
- WHERE ref = {?} AND uid = {?}", $pid, S::v('uid'));
+ $res = XDB::query('SELECT amount
+ FROM payment_transactions
+ WHERE id = {?} AND uid = {?}', $pid, S::v('uid'));
$montants = $res->fetchColumn();
foreach ($montants as $m) {
$table_editor->add_sort_field('flags');
$table_editor->add_sort_field('id', true, true);
$table_editor->on_delete("UPDATE payments SET flags = 'old' WHERE id = {?}", "Le paiement a été archivé");
- $table_editor->describe('text','intitulé',true);
- $table_editor->describe('url','site web',false);
- $table_editor->describe('amount_def','montant par défaut',false);
- $table_editor->describe('amount_min','montant minimum',false);
- $table_editor->describe('amount_max','montant maximum',false);
- $table_editor->describe('mail','email contact',true);
- $table_editor->describe('confirmation','message confirmation',false);
+ $table_editor->describe('text', 'intitulé', true);
+ $table_editor->describe('url', 'site web', false);
+ $table_editor->describe('amount_def', 'montant par défaut', false);
+ $table_editor->describe('amount_min', 'montant minimum', false);
+ $table_editor->describe('amount_max', 'montant maximum', false);
+ $table_editor->describe('mail', 'email contact', true);
+ $table_editor->describe('confirmation', 'message confirmation', false);
// adds a column with the start date of the linked event if there is one
- $table_editor->add_option_table('group_events','group_events.paiement_id = t.id');
+ $table_editor->add_option_table('group_events', 'group_events.paiement_id = t.id');
$table_editor->add_option_field('group_events.debut', 'related_event', 'évènement', 'timestamp');
$table_editor->apply($page, $action, $id);
}
-
+
function handler_adm_transactions(&$page, $payment_id = null, $action = "list", $id = null) {
// show transactions. FIXME: should not be modifiable
$page->setTitle('Administration - Paiements - Transactions');
$page->assign('title', "Liste des transactions pour le paiement {$payment_id}");
-
+
if ($payment_id == null)
$page->trigError("Aucun ID de paiement fourni.");
-
+
$table_editor = new PLTableEditor("admin/transactions/{$payment_id}",'payment_transactions','id');
$table_editor->set_where_clause(XDB::format('ref = {?}', $payment_id));
$table_editor->apply($page, 'list', $id); // only the 'list' action is allowed
- $page->assign("readonly","readonly"); // don't show modification features
+ $page->assign('readonly', 'readonly'); // don't show modification features
}
-
- function handler_adm_bankaccounts(&$page, $action = "list", $id = null) {
+
+ function handler_adm_bankaccounts(&$page, $action = 'list', $id = null) {
// managment of bank account used for money transfert
$page->setTitle('Administration - Paiements - RIBs');
$page->assign('title', "Liste des RIBs");
-
- $table_editor = new PLTableEditor("admin/payments/bankaccounts",'payment_bankaccounts','id');
- $table_editor->describe('asso_id','ID du groupe',false);
- $table_editor->describe('owner','titulaire',true);
- $table_editor->add_option_table('groups','groups.id = t.asso_id');
+
+ $table_editor = new PLTableEditor('admin/payments/bankaccounts', 'payment_bankaccounts', 'id');
+ $table_editor->describe('asso_id', 'ID du groupe', false);
+ $table_editor->describe('owner', 'titulaire', true);
+ $table_editor->add_option_table('groups', 'groups.id = t.asso_id');
$table_editor->add_option_field('groups.diminutif', 'group_name', 'groupe', 'varchar','account');
-
+
// check RIB key
- if ($action == "update" && Post::has("account") && !check_rib(Post::v("account"))) {
+ if ($action == 'update' && Post::has('account') && !check_rib(Post::v('account'))) {
$page->trigError("Le RIB n'est pas valide");
- $table_editor->apply($page, "edit", $id);
+ $table_editor->apply($page, 'edit', $id);
return;
}
-
+
$table_editor->apply($page, $action, $id);
}
-
- function handler_adm_methods(&$page, $action = "list", $id = null) {
+
+ function handler_adm_methods(&$page, $action = 'list', $id = null) {
// show and edit payment methods
$page->setTitle('Administration - Paiements - Méthodes');
- $page->assign('title', "Méthodes de paiement");
- $table_editor = new PLTableEditor("admin/payments/methods",'payment_methods','id');
+ $page->assign('title', 'Méthodes de paiement');
+ $table_editor = new PLTableEditor('admin/payments/methods', 'payment_methods', 'id');
$table_editor->apply($page, $action, $id);
}
$page->changeTpl('payment/reconcile.tpl');
$page->assign('step', $step);
$list = true;
-
+
// actions
if ($step == 'delete' && $param != null) {
S::assert_xsrf_token();
- XDB::execute("DELETE FROM payment_reconcilations WHERE id={?}", $param);
+ XDB::execute('DELETE FROM payment_reconcilations WHERE id = {?}', $param);
// FIXME: hardcoding !!!
- XDB::execute("UPDATE payment_transactions SET recon_id=NULL,commission=NULL WHERE recon_id={?} AND method_id=2", $param);
- XDB::execute("UPDATE payment_transactions SET recon_id=NULL WHERE recon_id={?} AND method_id=1", $param);
- $page->trigSuccess("L'entrée ".$param." a été supprimée.");
-
+ XDB::execute('UPDATE payment_transactions SET recon_id = NULL,commission = NULL WHERE recon_id = {?} AND method_id = 2', $param);
+ XDB::execute('UPDATE payment_transactions SET recon_id = NULL WHERE recon_id = {?} AND method_id = 1', $param);
+ $page->trigSuccess("L'entrée " . $param . ' a été supprimée.');
+
} elseif ($step == 'edit') {
$page->trigError("L'édition n'est pas implémentée.");
-
+
} elseif ($step == 'step5') {
$page->trigSuccess("La réconciliation est terminée. Il est maintenant nécessaire de générer les virements.");
-
+
}
-
+
if($list) {
// show list of reconciliations, with a "add" button
- $page->assign('title', "Réconciliation - Liste");
+ $page->assign('title', 'Réconciliation - Liste');
$page->assign('step', 'list');
-
+
$recongps = array();
-
+
$res = XDB::query("SELECT r.id, short_name AS method, period_start, period_end, status,
payment_count, sum_amounts, sum_commissions
FROM payment_reconcilations AS r
- LEFT JOIN payment_methods AS m ON r.method_id=m.id
+ LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
WHERE recongroup_id IS NULL
ORDER BY period_end DESC, period_start DESC");
foreach ($res->fetchAllAssoc() as $recon)
$recongps[] = array('recons' => array($recon), 'transfers' => array());
-
+
$res = XDB::query("SELECT recongroup_id AS id
FROM payment_reconcilations
GROUP BY recongroup_id
$res = XDB::query("SELECT r.id, short_name AS method, period_start, period_end, status,
payment_count, sum_amounts, sum_commissions
FROM payment_reconcilations AS r
- LEFT JOIN payment_methods AS m ON r.method_id=m.id
- WHERE recongroup_id={?}
+ LEFT JOIN payment_methods AS m ON (r.method_id = m.id)
+ WHERE recongroup_id = {?}
ORDER BY period_end DESC, period_start DESC",
$recongp['id']);
$recongp['recons'] = $res->fetchAllAssoc();
- $res = XDB::query("SELECT id, payment_id, amount, account_id, message, date
+ $res = XDB::query('SELECT id, payment_id, amount, account_id, message, date
FROM payment_transfers
- WHERE recongroup_id={?}",
+ WHERE recongroup_id = {?}',
$recongp['id']);
$recongp['transfers'] = $res->fetchAllAssoc();
-
+
$recongps[] = $recongp;
}
$page->assign_by_ref('recongps', $recongps);
}
}
-
+
function handler_adm_importlogs(&$page, $step, $param = null) {
$page->setTitle('Administration - Paiements - Réconciliations');
$page->changeTpl('payment/reconcile.tpl');
$page->assign('step', $step);
-
+
if (isset($_SESSION['paymentrecon_data'])) {
// create temporary table with imported data
- XDB::execute("CREATE TEMPORARY TABLE payment_tmp (
+ XDB::execute('CREATE TEMPORARY TABLE payment_tmp (
reference VARCHAR(255) PRIMARY KEY,
date DATE,
amount DECIMAL(9,2),
commission DECIMAL(9,2)
- )");
+ )');
foreach ($_SESSION['paymentrecon_data'] as $i)
- XDB::execute("INSERT INTO payment_tmp VALUES ({?},{?},{?},{?})",
+ XDB::execute('INSERT INTO payment_tmp VALUES ({?}, {?}, {?}, {?})',
$i['reference'], $i['date'], $i['amount'], $i['commission']);
}
-
+
if ($step == 'step1') {
- $page->assign('title', "Étape 1");
+ $page->assign('title', 'Étape 1');
unset($_SESSION['paymentrecon_method']);
unset($_SESSION['paymentrecon_data']);
unset($_SESSION['paymentrecon_id']);
-
+
// was a payment method choosen ?
if ($param != null) {
$_SESSION['paymentrecon_method'] = (int)$param;
- pl_redirect("admin/reconcile/importlogs/step2");
+ pl_redirect('admin/reconcile/importlogs/step2');
} else {
// ask to choose a payment method
- $res = XDB::query("SELECT id, text FROM payment_methods");
+ $res = XDB::query('SELECT id, text FROM payment_methods');
$page->assign('methods', $res->fetchAllAssoc());
}
} elseif ( $step == 'step2' ) {
- $page->assign('title', "Étape 2");
-
+ $page->assign('title', 'Étape 2');
+
// import logs formated in CVS
- $fields = array('date','reference','amount','commission');
+ $fields = array('date', 'reference', 'amount', 'commission');
$importer = new PaymentLogsImporter();
$importer->apply($page, 'admin/reconcile/importlogs/step2', $fields);
-
+
// if import is finished
$result = $importer->get_result();
if($result != null) {
$_SESSION['paymentrecon_data'] = $result;
- pl_redirect("admin/reconcile/importlogs/step3");
+ pl_redirect('admin/reconcile/importlogs/step3');
}
-
+
} elseif ($step == 'step3' ) {
- $page->assign('title', "Étape 3");
-
+ $page->assign('title', 'Étape 3');
+
// compute reconcilation summary data
- $res = XDB::query("SELECT MIN(date) AS period_start, MAX(date) AS period_end,
+ $res = XDB::query('SELECT MIN(date) AS period_start, MAX(date) AS period_end,
count(*) AS payment_count, SUM(amount) AS sum_amounts,
SUM(commission) AS sum_commissions
- FROM payment_tmp");
+ FROM payment_tmp');
$recon = $res->fetchOneAssoc();
$recon['method_id'] = $_SESSION['paymentrecon_method'];
-
+
// create reconciliation item in database
if(Post::has('next')) {
S::assert_xsrf_token();
-
+
// get parameters
- $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/','\3-\2-\1',Post::v('period_start'));
- $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/','\3-\2-\1',Post::v('period_end'));
+ $recon['period_start'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post::v('period_start'));
+ $recon['period_end'] = preg_replace('/([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/', '\3-\2-\1', Post::v('period_end'));
// FIXME: save checks to be done at next step
-
+
// Create reconcilation item in database
// FIXME: check if period doesn't overlap with others for the same method_id
- XDB::execute("INSERT INTO payment_reconcilations (method_id, period_start, period_end,
+ XDB::execute('INSERT INTO payment_reconcilations (method_id, period_start, period_end,
payment_count, sum_amounts, sum_commissions)
- VALUES ({?}, {?}, {?}, {?}, {?}, {?})",
+ VALUES ({?}, {?}, {?}, {?}, {?}, {?})',
$recon['method_id'], $recon['period_start'], $recon['period_end'],
$recon['payment_count'], $recon['sum_amounts'], $recon['sum_commissions']);
$_SESSION['paymentrecon_id'] = XDB::insertId();
-
+
// reconcile simple cases (trans.commission n'est modifié que s'il vaut NULL)
XDB::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
- SET trans.recon_id={?}, trans.commission=tmp.commission
- WHERE trans.fullref=tmp.reference
- AND trans.amount=tmp.amount AND DATE(trans.ts_confirmed)=tmp.date
- AND (trans.commission IS NULL OR trans.commission=tmp.commission)
- AND method_id={?} AND recon_id IS NULL AND status='confirmed'",
+ SET trans.recon_id = {?}, trans.commission=tmp.commission
+ WHERE trans.fullref = tmp.reference
+ AND trans.amount = tmp.amount AND DATE(trans.ts_confirmed) = tmp.date
+ AND (trans.commission IS NULL OR trans.commission = tmp.commission)
+ AND method_id = {?} AND recon_id IS NULL AND status = 'confirmed'",
$_SESSION['paymentrecon_id'], $recon['method_id']);
-
- pl_redirect("admin/reconcile/importlogs/step4");
-
+
+ pl_redirect("admin/reconcile/importlogs/step4");
+
// show summary of the imported data + ask form start/end of reconcilation period
} else {
$recon['period_start'] = preg_replace('/([0-9]{4})-([0-9]{2})-([0-9]{2})/', '\3/\2/\1', $recon['period_start']);
}
} elseif ($step == 'step4' ) {
- $page->assign('title', "Étape 4");
-
+ $page->assign('title', 'Étape 4');
+
// get reconcilation summary informations
- $res = XDB::query("SELECT * FROM payment_reconcilations WHERE id={?}", $_SESSION['paymentrecon_id']);
+ $res = XDB::query('SELECT * FROM payment_reconcilations WHERE id = {?}', $_SESSION['paymentrecon_id']);
$recon = $res->fetchOneAssoc();
$page->assign('recon', $recon);
if (Post::has('force')) {
S::assert_xsrf_token();
foreach (Post::v('force') as $id => $value) {
- XDB::execute("UPDATE payment_transactions AS trans, payment_tmp AS tmp
- SET trans.recon_id={?}, trans.commission=tmp.commission
- WHERE trans.id={?} AND trans.fullref=tmp.reference",
+ XDB::execute('UPDATE payment_transactions AS trans, payment_tmp AS tmp
+ SET trans.recon_id = {?}, trans.commission = tmp.commission
+ WHERE trans.id = {?} AND trans.fullref = tmp.reference',
$_SESSION['paymentrecon_id'], $id);
}
- $page->trigSuccess('La réconciliation a été forcée pour '.count(Post::v('force')).' transaction(s).');
-
+ $page->trigSuccess('La réconciliation a été forcée pour ' . count(Post::v('force')) . ' transaction(s).');
+
} elseif (Post::has('next')) {
- if (strlen($recon['comments'])<3) {
- $page->trigError("Le commentaire doit contenir au moins 3 caractères.");
+ if (strlen($recon['comments'])< 3 ) {
+ $page->trigError('Le commentaire doit contenir au moins 3 caractères.');
} else {
- XDB::execute("UPDATE payment_reconcilations SET status='transfering' WHERE id={?}", $_SESSION['paymentrecon_id']);
+ XDB::execute("UPDATE payment_reconcilations SET status = 'transfering' WHERE id = {?}", $_SESSION['paymentrecon_id']);
pl_redirect('admin/reconcile/step5');
}
-
+
} elseif (Post::has('savecomments')) {
S::assert_xsrf_token();
$recon['comments'] = Post::v('comments');
$page->assign('recon', $recon);
- XDB::execute("UPDATE payment_reconcilations SET comments={?} WHERE id={?}", $recon['comments'], $_SESSION['paymentrecon_id']);
+ XDB::execute('UPDATE payment_reconcilations SET comments = {?} WHERE id = {?}', $recon['comments'], $_SESSION['paymentrecon_id']);
$page->trigSuccess('Les commentaires ont été enregistrés.');
}
-
+
// reconcilation results - ok
- $res = XDB::query("SELECT count(*),SUM(amount),SUM(commission)
- FROM payment_transactions WHERE recon_id={?}",
+ $res = XDB::query('SELECT count(*), SUM(amount), SUM(commission)
+ FROM payment_transactions
+ WHERE recon_id = {?}',
$recon['id']);
- list($ok_count,$ok_sum_amounts,$ok_sum_coms) = $res->fetchOneRow();
+ list($ok_count, $ok_sum_amounts, $ok_sum_coms) = $res->fetchOneRow();
$page->assign('ok_count', $ok_count);
-
+
// reconcilation results - ref exists, but some data differs
- $res = XDB::query("SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
+ $res = XDB::query('SELECT id, fullref, method_id, ts_confirmed, trans.amount, trans.commission, status, recon_id,
reference, date, tmp.amount as amount2, tmp.commission as commission2
FROM payment_transactions AS trans
- INNER JOIN payment_tmp AS tmp ON trans.fullref=tmp.reference
- WHERE trans.recon_id IS NULL OR trans.recon_id != {?}",
+ INNER JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
+ WHERE trans.recon_id IS NULL OR trans.recon_id != {?}',
$recon['id']);
$differs = $res->fetchAllAssoc();
$page->assign_by_ref('differs', $differs);
$page->assign('differ_count', count($differs));
-
+
// reconcilation results - ref doesn't exists in database
- $res = XDB::query("SELECT tmp.*
- FROM payment_tmp AS tmp
- LEFT JOIN payment_transactions AS trans ON trans.fullref=tmp.reference
- WHERE trans.fullref IS NULL");
+ $res = XDB::query('SELECT tmp.*
+ FROM payment_tmp AS tmp
+ LEFT JOIN payment_transactions AS trans ON (trans.fullref = tmp.reference)
+ WHERE trans.fullref IS NULL');
$only_import = $res->fetchAllAssoc();
$page->assign_by_ref('only_import', $only_import);
$page->assign('onlyim_count', count($only_import));
-
+
// reconcilation results - exists in database but not in import
- $res = XDB::query("SELECT trans.*
+ $res = XDB::query('SELECT trans.*
FROM payment_transactions AS trans
- LEFT JOIN payment_tmp AS tmp ON trans.fullref=tmp.reference
- WHERE {?}<=DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed)<={?}
- AND tmp.reference IS NULL AND method_id={?}",
+ LEFT JOIN payment_tmp AS tmp ON (trans.fullref = tmp.reference)
+ WHERE {?} <= DATE(trans.ts_confirmed) AND DATE(trans.ts_confirmed) <= {?}
+ AND tmp.reference IS NULL AND method_id = {?}',
$recon['period_start'], $recon['period_end'], $recon['method_id']);
$only_database = $res->fetchAllAssoc();
$page->assign_by_ref('only_database', $only_database);
$page->assign('onlydb_count', count($only_database));
}
}
-
+
function handler_adm_transfers(&$page, $action = null, $id = null) {
// list/log all bank transfers and link them to individual transactions
-
+
if (Post::has('generate')) {
$recon_ids = array_keys(Post::v('recon_id'));
-
+
// generate a new reconcilation group ID
$res = XDB::query("SELECT MAX(recongroup_id)+1 FROM payment_reconcilations");
$recongp_id = $res->fetchOneCell();
if ($recongp_id == null) $recongp_id = 1;
-
+
// add reconcilations to group
// FIXME: should check if reconcilations are in good status
- XDB::execute("UPDATE payment_reconcilations SET recongroup_id={?}, status='closed'
- WHERE id IN {?}",
- $recongp_id, $recon_ids);
-
+ XDB::execute("UPDATE payment_reconcilations
+ SET recongroup_id = {?}, status = 'closed'
+ WHERE id IN {?}",
+ $recongp_id, $recon_ids);
+
// create transfers
- XDB::execute("INSERT INTO payment_transfers
+ XDB::execute('INSERT INTO payment_transfers
SELECT NULL, {?}, t.ref, SUM(t.amount+t.commission), NULL, p.text, NULL
FROM payment_transactions AS t
- LEFT JOIN payments AS p ON t.ref = p.id
- LEFT JOIN groups AS g ON p.asso_id = g.id
+ LEFT JOIN payments AS p ON (t.ref = p.id)
+ LEFT JOIN groups AS g ON (p.asso_id = g.id)
WHERE t.recon_id IN {?}
- GROUP BY t.ref",
- $recongp_id, $recon_ids);
-
+ GROUP BY t.ref',
+ $recongp_id, $recon_ids);
+
//$res = XDB::query("SELECT * FROM payment_reconcilations WHERE id IN {?}", $recon_ids);
//$recons = $res->fetchAllAssoc();
-
- $page->trigSuccess("Les virements ont été générés pour ".count($recon_ids)." réconciliations.");
+
+ $page->trigSuccess('Les virements ont été générés pour ' . count($recon_ids) . ' réconciliations.');
$this->handler_adm_reconcile($page);
-
- } elseif ($action == "delgroup") {
+
+ } elseif ($action == 'delgroup') {
S::assert_xsrf_token();
- XDB::execute("UPDATE payment_reconcilations SET status='transfering', recongroup_id=NULL WHERE recongroup_id={?}", $id);
- XDB::execute("DELETE FROM payment_transfers WHERE recongroup_id={?} AND date IS NULL", $id);
-
+ XDB::execute("UPDATE payment_reconcilations
+ SET status = 'transfering', recongroup_id = NULL
+ WHERE recongroup_id = {?}", $id);
+ XDB::execute("DELETE FROM payment_transfers
+ WHERE recongroup_id = {?} AND date IS NULL", $id);
+
$page->trigSuccess("Les virements non réalisés ont été supprimé du groupe ".$id.".");
$this->handler_adm_reconcile($page);
-
+
} elseif ($action == "confirm") {
S::assert_xsrf_token();
- XDB::execute("UPDATE payment_transfers SET date=NOW() WHERE id={?}", $id);
-
- $page->trigSuccess("Virement ".$id." confirmé.");
+ XDB::execute('UPDATE payment_transfers
+ SET date = NOW()
+ WHERE id = {?}', $id);
+
+ $page->trigSuccess('Virement ' . $id . ' confirmé.');
$this->handler_adm_reconcile($page);
-
+
} else {
- pl_redirect("admin/reconcile");
+ pl_redirect('admin/reconcile');
}
}
}
class PaymentLogsImporter extends CSVImporter {
protected $result;
-
+
public function __construct() {
parent::__construct('');
- $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this,"compute_systempay_commission"));
- $this->registerFunction('payment_id', 'Autocompute payment ID', array($this,"compute_payment_id"));
+ $this->registerFunction('systempay_commission', 'Compute BPLC commission', array($this, 'compute_systempay_commission'));
+ $this->registerFunction('payment_id', 'Autocompute payment ID', array($this, 'compute_payment_id'));
//$this->forceValue('payment_id','func_payment_id');
}
-
+
public function run($action = null, $insert_relation = null, $update_relation = null) {
$this->result = array();
foreach ($this->data as $line) {
$a = $this->makeAssoc($line, $insert_relation);
- $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/','\3-\2-\1', $a['date']);
- $a['amount'] = str_replace(',','.',$a['amount']);
- $a['commission'] = str_replace(',','.',$a['commission']);
+ $a['date'] = preg_replace('/([0-9]{2})\/([0-9]{2})\/([0-9]{4}).*/', '\3-\2-\1', $a['date']);
+ $a['amount'] = str_replace(',', '.', $a['amount']);
+ $a['commission'] = str_replace(',', '.', $a['commission']);
$this->result[] = $a;
}
}
-
+
public function get_result() {
return $this->result;
}
-
+
static public function compute_systempay_commission($line, $key, $relation) {
- static $EEE_countries = array('France','Allemagne','Autriche','Belgique','Bulgarie','Chypre',
- 'Danemark','Espagne','Estonie','Finlande','Grèce','Hongrie','Irlande','Islande','Italie',
- 'Lettonie','Liechtenstein','Lituanie','Luxembourg','Malte','Norvège','Pays-Bas','Pologne',
- 'Portugal','Roumanie','Royaume-Uni','Slovaquie','Slovénie','Suède','République Tchèque');
-
- if($key!='commission' || !array_key_exists('carte',$line)) return null;
+ static $EEE_countries = array(
+ 'France', 'Allemagne', 'Autriche', 'Belgique', 'Bulgarie', 'Chypre',
+ 'Danemark', 'Espagne', 'Estonie', 'Finlande', 'Grèce', 'Hongrie', 'Irlande', 'Islande', 'Italie',
+ 'Lettonie', 'Liechtenstein', 'Lituanie', 'Luxembourg', 'Malte', 'Norvège', 'Pays-Bas', 'Pologne',
+ 'Portugal', 'Roumanie', 'Royaume-Uni', 'Slovaquie', 'Slovénie', 'Suède', 'République Tchèque'
+ );
+
+ if($key!='commission' || !array_key_exists('carte', $line)) {
+ return null;
+ }
$amount = self::getValue($line, 'amount', $relation['amount']);
- if (in_array($line['pays carte'],$EEE_countries))
- return -0.20 - round($amount*0.005, 2);
- else
- return -0.20 - round($amount*0.005, 2) - 0.76;
+ if (in_array($line['pays carte'], $EEE_countries)) {
+ return -0.20 - round($amount * 0.005, 2);
+ } else {
+ return -0.20 - round($amount * 0.005, 2) - 0.76;
+ }
}
static public function compute_payment_id($line, $key, $relation) {
- if ($key != 'payment_id') return null;
+ if ($key != 'payment_id') {
+ return null;
+ }
$reference = self::getValue($line, 'reference', $relation['reference']);
- if (ereg('-([0-9]+)$', $reference, $matches))
+ if (ereg('-([0-9]+)$', $reference, $matches)) {
return $matches[1];
- else
+ } else {
return null;
+ }
}
}
}
// Build the page
- $page->addJsLink('ajax.js');
$page->addJsLink('education.js', false); /* dynamic content */
$page->addJsLink('grades.js', false); /* dynamic content */
$page->addJsLink('profile.js');
$page->changeTpl('search/index.tpl');
$page->setTitle('Annuaire');
$page->assign('formulaire', 1);
- $page->addJsLink('ajax.js');
return;
}
}
} else {
$page->assign('formulaire',1);
- $page->addJsLink('ajax.js');
}
$page->changeTpl('search/index.tpl');
}
$page->changeTpl('search/index.tpl', $model == 'mini' ? SIMPLE : SKINNED);
- $page->addJsLink('ajax.js');
$page->assign('public_directory',0);
}
class SurveyModule extends PLModule
{
- // {{{ function handlers() : registers the different handlers
function handlers()
{
return array(
- 'survey' => $this->make_hook('index', AUTH_PUBLIC),
- 'survey/vote' => $this->make_hook('vote', AUTH_PUBLIC),
- 'survey/result' => $this->make_hook('result', AUTH_PUBLIC),
+ 'survey' => $this->make_hook('index', AUTH_COOKIE),
+ 'survey/vote' => $this->make_hook('vote', AUTH_COOKIE),
+ /* 'survey/result' => $this->make_hook('result', AUTH_COOKIE),
'survey/edit' => $this->make_hook('edit', AUTH_COOKIE),
'survey/ajax' => $this->make_hook('ajax', AUTH_COOKIE),
'survey/admin' => $this->make_hook('admin', AUTH_MDP, 'admin'),
'survey/admin/edit' => $this->make_hook('adminEdit', AUTH_MDP, 'admin'),
'survey/admin/valid' => $this->make_hook('adminValidate', AUTH_MDP, 'admin'),
'survey/admin/del' => $this->make_hook('adminDelete', AUTH_MDP, 'admin'),
- );
+ */ );
}
- // }}}
- // {{{ function handler_index() : lists all available surveys
function handler_index(&$page, $action = null)
{
$this->load('survey.inc.php');
- $page->changeTpl('survey/index.tpl');
- $page->assign('survey_current', Survey::retrieveList('c'));
- $page->assign('survey_old', Survey::retrieveList('o'));
- $page->assign('survey_modes', Survey::getModes(false));
- }
- // }}}
- // {{{ function handler_vote() : handles the vote to a survey
- function handler_vote(&$page, $id = -1)
- {
- if (Post::has('survey_cancel')) { // if the user cancels, returns to index
- return $this->handler_index(&$page);
- }
- $id = intval($id);
- if ($id == -1) {
- return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey');
- }
- $this->load('survey.inc.php');
- $survey = Survey::retrieveSurvey($id); // retrieves the survey object structure
- if ($survey == null || !$survey->isValid()) {
- return $this->show_error($page, "Sondage ".$id." introuvable.", 'survey');
- } elseif ($survey->isEnded()) {
- return $this->show_error($page, "Le sondage ".$survey->getTitle()." est terminé.", 'survey');
- }
- if (!$this->check_surveyPerms($page, $survey)) {
- return PL_DO_AUTH;
- }
- if (Post::has('survey_submit')) { // checks if the survey has already been filled in
- // admins can see the survey but not vote
- if (!$this->check_surveyPerms($page, $survey, false, false)) {
- return PL_DO_AUTH;
- }
- $uid = 0;
- if (!$survey->isMode(Survey::MODE_ALL)) { // if survey is restriced to alumni
- $uid = S::v('uid');
- if ($survey->hasVoted($uid)) { // checks whether the user has already voted
- return $this->show_error($page, "Tu as déjà voté à ce sondage.", 'survey');
- }
- }
- $survey->vote($uid, Post::v('survey'.$id)); // performs vote
- $this->show_success($page, "Ta réponse a bien été prise en compte. Merci d'avoir participé à ce sondage.", 'survey');
- } else { // offers to fill in the survey
- if ($survey->isMode(Survey::MODE_ALL) || !$survey->hasVoted(S::v('uid'))) {
- $page->assign('survey_votemode', true);
- } else {
- $page->assign('survey_warning', "Tu as déjà voté à ce sondage.");
- }
- //$page->assign('survey_id', $id);
- $this->show_survey($page, $survey);
- }
- }
- // }}}
-
- // {{{ function handler_result() : show the results of the votes to a survey
- function handler_result($page, $id = -1, $show = 'all')
- {
- $id = intval($id);
- if ($id == -1) {
- return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey');
- }
- $this->load('survey.inc.php');
- $survey = Survey::retrieveSurvey($id); // retrieves the survey object structure
- if ($survey == null || !$survey->isValid()) {
- return $this->show_error($page, "Sondage ".$id." introuvable.", 'survey');
- } elseif (!$survey->isEnded() && !$survey->canSeeEarlyResults(S::user())) {
- return $this->show_error($page, "Le sondage ".$survey->getTitle()." n'est pas encore terminé.", 'survey');
- }
- if (!$survey->canSeeEarlyResults(S::user()) && !$this->check_surveyPerms($page, $survey)) {
- return PL_DO_AUTH;
- }
- if ($show == 'csv') {
- pl_content_headers("text/csv");
- header('Content-Disposition: attachment; filename="'.addslashes($survey->getTitle()).'.csv"');
- echo $survey->toCSV();
- exit;
- } else {
- $page->assign('survey_resultmode', true);
- $this->show_survey($page, $survey);
- }
- }
- // }}}
-
- // {{{ function handler_admin() : index of admin mode
- function handler_admin(&$page, $id = -1)
- {
- $this->load('survey.inc.php');
- $this->clear_session();
- if ($id == -1) {
- $page->changeTpl('survey/admin.tpl');
- $page->assign('survey_waiting', Survey::retrieveList('w'));
- $page->assign('survey_current', Survey::retrieveList('c'));
- $page->assign('survey_old', Survey::retrieveList('o'));
- $page->assign('survey_modes', Survey::getModes(false));
- } else {
- $id = intval($id);
- $survey = Survey::retrieveSurvey($id); // retrieves all survey object structure
- if ($survey == null) {
- $this->show_error($page, "Sondage ".$id." introuvable.", 'survey/admin');
- }
- $page->assign('survey_adminmode', true);
- $this->show_survey($page, $survey);
- }
- }
- // }}}
+ XDB::execute("DELETE FROM surveys");
- // {{{ function handler_adminEdit() : edits a survey in admin mode
- function handler_adminEdit(&$page, $id = -1, $req = -1)
- {
- if ($id == -1 || ($id == 'req' && $req == -1)) {
- return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey/admin');
- }
- $this->load('survey.inc.php');
- $this->clear_session(); // cleans session (in case there would have been a problem before)
- if ($id == 'req') {
- $survey = Survey::retrieveSurveyReq($req);
- if ($survey == null) {
- return $this->show_error($page, "Sondage introuvable.", 'survey/admin');
- }
- $this->store_session($survey, $req, true);
- } else {
- $id = intval($id);
- $survey = Survey::retrieveSurvey($id); // retrieves the survey in database
- if ($survey == null) {
- return $this->show_error($page, "Sondage ".$id." introuvable.", 'survey/admin');
- }
- $this->store_session($survey, $id);
- }
- $this->handler_edit($page, 'show'); // calls handler_edit, but in admin mode since 'survey_id' is in session
- }
- // }}}
+ $survey = new Survey();
+ $survey->id = null;
+ $survey->shortname = "blah";
+ $survey->title = "Blah";
+ $survey->description = "Blih blih blih blih";
+ $survey->uid = S::user()->id();
+ $survey->begin = "09/09/2010";
+ $survey->end = "30/12/2011";
- // {{{ function handler_adminValidate() : validates a survey (admin mode)
- function handler_adminValidate(&$page, $id = -1)
- {
- $id = Post::i('survey_id', $id);
- if (Post::has('survey_cancel')) { // if the admin cancels the validation, returns to the admin index
- $this->clear_session();
- return $this->handler_admin(&$page, $id);
- }
- if ($id == -1) {
- return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey/admin');
- }
- $id = intval($id);
- $this->load('survey.inc.php');
- $surveyInfo = Survey::retrieveSurveyInfo($id); // retrieves information about the survey (does not retrieve and unserialize the object structure)
- if ($surveyInfo == null) {
- return $this->show_error($page, "Sondage ".$id." introuvable.", 'survey/admin');
- }
- if (Post::has('survey_submit')) { // needs a confirmation before validation
- if (Survey::validateSurvey($id)) { // validates the survey (in the database)
- $this->show_success($page, "Le sondage \"".$surveyInfo['title']."\" a bien été validé, les votes sont maintenant ouverts.", 'survey/admin');
- } else {
- $this->show_error($page, '', 'survey/admin');
- }
- } else { // asks for a confirmation
- $this->show_confirm($page, "Êtes-vous certain de vouloir valider le sondage \"".$surveyInfo['title']."\" ? "
- ."Les votes seront immédiatement ouverts.", 'admin/valid', array('id' => $id));
- }
- }
- // }}}
+ $qpage = $survey->newQuestion("section");
+ $qpage->parameters = array('type' => 'page');
+ $qpage->label = 'Première page';
- // {{{ function handler_adminDelete() : deletes a survey (admin mode)
- function handler_adminDelete(&$page, $id = -1)
- {
- $id = Post::i('survey_id', $id);
- if (Post::has('survey_cancel')) { // if the admin cancels the suppression, returns to the admin index
- return $this->handler_admin(&$page, $id);
- }
- if ($id == -1) {
- return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey/admin');
- }
- $id = intval($id);
- $this->load('survey.inc.php');
- $surveyInfo = Survey::retrieveSurveyInfo($id); // retrieves information about the survey (does not retrieve and unserialize the object structure)
- if ($surveyInfo == null) {
- return $this->show_error($page, "Sondage ".$id." introuvable.", 'survey/admin');
- }
- if (Post::has('survey_submit')) { // needs a confirmation before suppression
- if (Survey::deleteSurvey($id)) { // deletes survey in database
- $this->show_success($page, "Le sondage \"".$surveyInfo['title']."\" a bien été supprimé, ainsi que tous les votes le concernant.", 'survey/admin');
- } else {
- $this->show_error($page, '', 'survey/admin');
- }
- } else { // asks for a confirmation
- $this->show_confirm($page, "Êtes-vous certain de vouloir supprimer le sondage \"".$surveyInfo['title']."\" ?", 'admin/del', array('id' => $id));
- }
- }
- // }}}
+ $question = $qpage->newQuestion("text");
+ $question->label = "Super question";
+ $question->flags = "mandatory";
+ $question->parameters = array("type" => "text", "limit" => 256);
- // {{{ function handler_edit() : edits a survey (in normal mode unless called by handler_adminEdit() )
- function handler_edit(&$page, $action = 'show', $qid = 'root')
- {
- $this->load('survey.inc.php');
- $action = Post::v('survey_action', $action);
- $qid = Post::v('survey_qid', $qid);
- if (Post::has('survey_cancel')) { // after cancelling changes, shows the survey
- if (S::has('survey')) {
- $action = 'show';
- } else { // unless no editing has been done at all (shows to the surveys index page)
- return $this->handler_index($page);
- }
- }
- $page->assign('survey_editmode', true);
- if (S::has('survey_id')) { // if 'survey_id' is in session, it means we are modifying a survey in admin mode
- $page->assign('survey_updatemode', true);
- }
- if ($action == 'show' && !S::has('survey')) {
- $action = 'new';
- }
- if ($action == 'question') { // {{{ modifies an existing question
- if (Post::has('survey_submit')) { // if the form has been submitted, makes the modifications
- $survey = unserialize(S::v('survey'));
- $args = Post::v('survey_question');
- if (!$survey->editQuestion($qid, $args)) { // update the survey object structure
- return $this->show_error($page, '', 'survey/edit');
- }
- $this->show_survey($page, $survey);
- $this->store_session($survey);
- } else { // if a form has not been submitted, shows modification form
- $survey = unserialize(S::v('survey'));
- $current = $survey->toArray($qid); // gets the current parameters of the question
- if ($current == null) {
- return $this->show_error($page, '', 'survey/edit');
- }
- $this->show_form($page, $action, $qid, $current['type'], $current);
- } // }}}
- } elseif ($action == 'new') { // {{{ create a new survey : actually store the root question
- if (Post::has('survey_submit')) { // if the form has been submitted, creates the survey
- $this->clear_session();
- $survey = new Survey(Post::v('survey_question')); // creates the object structure
- $this->show_survey($page, $survey);
- $this->store_session($survey);
- } else {
- $this->clear_session();
- $this->show_form($page, $action, 'root', 'newsurvey');
- } // }}}
- } elseif ($action == 'add') { // {{{ adds a new question
- if (Post::has('survey_submit')) { // if the form has been submitted, adds the question
- $survey = unserialize(S::v('survey'));
- if (!$survey->addQuestion($qid, $survey->factory(Post::v('survey_type'), Post::v('survey_question')))) {
- return $this->show_error($page, '', 'survey/edit');
- }
- $this->show_survey($page, $survey);
- $this->store_session($survey);
- } else {
- $this->show_form($page, $action, $qid);
- } // }}}
- } elseif ($action == 'del') { // {{{ deletes a question
- if (Post::has('survey_submit')) { // if a confirmation has been sent, deletes the question
- $survey = unserialize(S::v('survey'));
- if (!$survey->delQuestion(Post::v('survey_qid'))) { // deletes the node in the survey object structure
- return $this->show_error($page, '', 'survey/edit');
- }
- $this->show_survey($page, $survey);
- $this->store_session($survey);
- } else { // if user has not confirmed, shows a confirmation form
- $survey = unserialize(S::v('survey'));
- $current = $survey->toArray($qid); // needed to get the title of the question to delete (more user-friendly than an id)
- if ($current == null) {
- return $this->show_error($page, '', 'survey/edit');
- }
- $this->show_confirm($page, 'Êtes-vous certain de vouloir supprimer la question intitulé "'.$current['question'].'" ? '
- .'Attention, cela supprimera en même temps toutes les questions qui dépendent de celle-ci.',
- 'edit', array('action' => 'del', 'qid' => $qid));
- } // }}}
- } elseif ($action == 'show') { // {{{ simply shows the survey in its current state
- $this->show_survey($page, unserialize(S::v('survey'))); // }}}
- } elseif ($action == 'valid') { // {{{ validates the proposition, i.e stores the proposition in the database
- // but an admin will still need to validate the survey before it is activated
- if (Post::has('survey_submit')) { // needs a confirmation before storing the proposition
- $survey = unserialize(S::v('survey'));
- if (S::has('survey_id')) { // if 'survey_id' is in session, we are modifying an existing survey (in admin mode) instead of proposing a new one
- $link = (S::has('survey_validate'))? 'admin/validate' : 'survey/admin';
- if ($survey->updateSurvey()) { // updates the database according the new survey object structure
- $this->show_success($page, "Les modifications sur le sondage ont bien été enregistrées.", $link);
- } else {
- $this->show_error($page, '', $link);
- }
- } else { // if no 'survey_id' is in session, we are indeed proposing a new survey
- if ($survey->proposeSurvey()) { // stores the survey object structure in database
- $this->show_success($page, "Votre proposition de sondage a bien été enregistrée,
- elle est en attente de validation par un administrateur du site.", 'survey');
- } else {
- $this->show_error($page, '', 'survey');
- }
- }
- $this->clear_session();
- } else { // asks for a confirmation if it has not been sent
- $survey = unserialize(S::v('survey'));
- $errors = $survey->checkSyntax();
- if (!is_null($errors)) {
- $this->show_error($page, "", 'survey/edit', $errors);
- } else {
- if (S::has('survey_id')) {
- $this->show_confirm($page, "Veuillez confirmer l'enregistrement des modifications apportées à ce sondage.", 'edit', array('action' => 'valid'));
- } else {
- $this->show_confirm($page, "Veuillez confirmer l'envoi de cette proposition de sondage.", 'edit', array('action' => 'valid'));
- }
- }
- } // }}}
- } elseif ($action == 'cancel') { // {{{ cancels the creation/modification of a survey
- if (Post::has('survey_submit')) { // needs a confirmation
- if (S::has('survey_id')) { // only possible when modifying a survey in admin mode
- if (S::has('survey_validate')) { // if a link has been supplied, uses it
- $this->clear_session();
- return $this->show_success($page, "Les modifications effectuées ont été annulées", 'admin/validate');
- } else { // else shows the admin index
- $this->clear_session();
- return $this->handler_admin($page);
- }
- } else {
- $this->clear_session();
- return $this->handler_index($page); // else shows the 'normal' index
- }
- } else { // asks for a confirmation if it has not been sent
- $this->show_confirm(&$page, "Êtes-vous certain de vouloir annuler totalement l'édition de ce sondage ? Attention, "
- ."toutes les données éditées jusque là seront définitivement perdues.",
- 'edit', array('action' => $action));
- }
- } // }}}
- }
- // }}}
+ $question = $qpage->newQuestion("text");
+ $question->label = "Super question 2";
- // {{{ function handler_ajax() : some ajax in editing a new question (for now, there may be a little more later)
- function handler_ajax(&$page, $type)
- {
- $this->load('survey.inc.php');
- pl_content_headers("text/html");
- if (Survey::isType($type)) { // when type has been chosen, the form is updated to fit exactly the type of question chosen
- $page->changeTpl('survey/edit_new.tpl', NO_SKIN);
- $page->assign('survey_types', Survey::getTypes());
- $page->assign('survey_type', $type);
- }
- }
- // }}}
+ $qpage = $survey->newQuestion("section");
+ $qpage->parameters = array('type' => 'page');
+ $qpage->label = 'Deuxième page';
- // {{{ function clear_session() : clears the data stored in session
- function clear_session()
- {
- S::kill('survey');
- S::kill('survey_id');
- S::kill('survey_validate');
- }
- // }}}
+ $survey->flags = 'validated';
+ $survey->insert(true);
- // {{{ function store_session() : serializes and stores survey (and survey_id) in session
- function store_session($survey, $survey_id = -1, $survey_validate = false)
- {
- $_SESSION['survey'] = serialize($survey);
- if ($survey_id != -1) {
- $_SESSION['survey_id'] = $survey_id;
- }
- if ($survey_validate) {
- $_SESSION['survey_validate'] = true;
- }
+ $page->changeTpl('survey/index.tpl');
+ $page->assign('active', Survey::iterActive());
}
- // }}}
- // {{{ function check_surveyPerms() : checks the particular surveys access permissions
- function check_surveyPerms(&$page, $survey, $silent = false, $admin_allowed = true)
+ function handler_vote(PlPage $page, $name)
{
$this->load('survey.inc.php');
- if ($survey->isMode(Survey::MODE_ALL)) { // if the survey is not reserved to alumni
- return true;
- }
- if (!S::logged()) {
- return false;
- }
- $profile = S::user()->profile();
- if (!$profile) {
- return false;
- }
- // checks promotion
- $allowed = false;
- foreach ($profile->yearspromo() as $p) {
- if ($survey->checkPromo($p)) {
- $allowed = true;
- break;
- }
- }
- if ($allowed) {
- return true;
- }
- if (S::admin() && $admin_allowed) {
- if (!$silent) {
- $page->trigWarning('Tu as accès à ce sondage car tu es administrateur du site.');
+ $page->changeTpl('survey/vote.tpl');
+ $survey = Survey::get($name);
+ if (is_null($survey)) {
+ return PL_NOT_FOUND;
+ }
+ if (!$survey->canSee(S::user())) {
+ return PL_FORBIDDEN;
+ }
+ if (Post::has('vote')) {
+ $answers = Post::v('qid');
+ $vote = $survey->vote(S::user(), $answers);
+ if (is_null($vote)) {
+ $page->kill("Tu n'as pas le droit de voter à ce sondage.");
+ } else if ($vote->inError()) {
+ $page->trigError("Certaines réponses sont invalides et doivent être corrigées");
+ } else {
+ $vote->insert(true);
+ $page->trigSuccess("Ton vote a été enregistré");
}
- return true;
- }
- if (!$silent) {
- $page->kill("Tu n'as pas accès à ce sondage car il est réservé à d'autres promotions.");
- }
- return false;
- }
- // }}}
-
- // {{{ function show_survey() : calls the template to display a survey, for editing, voting, or consulting the results
- function show_survey(&$page, $survey)
- {
- $page->changeTpl('survey/show_root.tpl');
- $page->assign('survey', $survey->toArray());
- $page->assign('survey_modes', Survey::getModes());
- }
- // }}}
-
- // {{{ function show_form() : calls the template to display the editing form
- function show_form(&$page, $action, $qid, $type = 'new', $current = null)
- {
- $page->changeTpl('survey/edit_survey.tpl');
- $page->assign('survey_action', $action);
- $page->assign('survey_qid', $qid);
- $page->assign('survey_formaction', './survey/edit');
- $page->assign('survey_type', $type);
- if (!is_null($current) && is_array($current)) {
- $page->assign('survey_current', $current);
- } elseif ($type == 'new') {
- $page->addJsLink('ajax.js');
- $page->assign('survey_types', Survey::getTypes());
}
- if ($type == 'root' || $type == 'newsurvey') {
- $page->assign('survey_modes', Survey::getModes());
- }
- }
- // }}}
-
- // {{{ function show_confirm() : calls the template to display a confirm form
- function show_confirm(&$page, $message, $formaction, $formhidden = null)
- {
- $page->changeTpl('survey/confirm.tpl');
- $page->assign('survey_message', $message);
- $page->assign('survey_formaction', './survey/'.$formaction);
- $page->assign('survey_formhidden', $formhidden);
- }
- // }}}
-
- // {{{ function show_error() : calls the template to display an error message
- function show_error(&$page, $message, $link = "", $errArray = null)
- {
- $page->changeTpl('survey/error.tpl');
- $page->assign('survey_message', $message);
- $page->assign('survey_link', $link); // 'return' link to let the user leave the page
- if (!is_null($errArray)) {
- $page->assign('survey_errors', $errArray);
- }
-
- }
- // }}}
-
- // {{{ function show_success() : calls the template to display a success message
- function show_success(&$page, $message = "", $link = "")
- {
- $page->changeTpl('survey/success.tpl');
- $page->assign('survey_message', $message);
- $page->assign('survey_link', $link); // 'return' link to let the user leave the page
+ $page->assign('survey', $survey);
}
- // }}}
}
// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
--- /dev/null
+<?php
+/***************************************************************************
+ * Copyright (C) 2003-2010 Polytechnique.org *
+ * http://opensource.polytechnique.org/ *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the Free Software *
+ * Foundation, Inc., *
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
+ ***************************************************************************/
+
+class SurveyVote extends PlDBTableEntry
+{
+ protected $survey;
+ protected $user;
+
+ private $answers = array();
+ private $fetchAnswers;
+
+ public function __construct(Survey $survey, User $user)
+ {
+ parent::__construct('survey_votes');
+ $this->survey = $survey;
+ $this->user = $user;
+ $this->sid = $survey->id;
+ }
+
+ protected function postSave()
+ {
+ Platal::assert(!is_null($this->vid), "Cannot process a vote without its identifier");
+ XDB::execute("REPLACE INTO survey_voters (sid, uid, vid)
+ VALUES ({?}, {?}, {?})",
+ $this->survey->id, $this->user->id(),
+ $this->survey->flags->hasFlag('anonymous') ? null : $this->vid);
+
+ /* Save answers */
+ $selector = new SurveyAnswer($this);
+ $selector->delete();
+
+ $answers = array();
+ foreach ($this->answers as $key=>$answer) {
+ if (!is_null($answer)) {
+ $answer->vid = $this->vid;
+ $answers[] = $answer;
+ }
+ }
+ PlDBTableEntry::insertBatch($answers);
+ return true;
+ }
+
+ protected function postFetch()
+ {
+ $selector = new SurveyAnswer($this);
+ foreach ($selector as $answer) {
+ $question = $this->survey->questionForId($answer->qid);
+ $this->answers[$answer->qid] = $answer;
+ }
+ return true;
+ }
+
+ public function inError()
+ {
+ foreach ($this->answers as $answer) {
+ if ($answer->inError !== false) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public function getAnswer(SurveyQuestion $question)
+ {
+ if (!isset($this->answers[$question->qid])) {
+ $val = new SurveyAnswer($this);
+ $val->qid = $question->qid;
+ $this->answers[$question->qid] = $val;
+ }
+ return $this->answers[$question->qid];
+ }
+
+ public function export()
+ {
+ $export = array();
+ foreach ($this->answers as $qid=>$answer) {
+ $export[$qid] = $answer->export();
+ }
+ return $export;
+ }
+
+ public static function getVote(Survey $survey, User $user, $fetchAnswers = true)
+ {
+ $vid = XDB::query('SELECT vid
+ FROM survey_voters
+ WHERE sid = {?} AND uid = {?}',
+ $survey->id, $user->id());
+ if ($vid->numRows() == 0) {
+ $vote = new SurveyVote($survey, $user);
+ $vote->fetchAnswers = $fetchAnswers;
+ return $vote;
+ }
+ $vid = $vid->fetchOneCell();
+ if (is_null($vid)) {
+ /* User already vote, but survey is anonymous and the vote
+ * cannot be changed
+ */
+ return null;
+ }
+ $vote = new SurveyVote($survey, $user);
+ $vote->vid = $vid;
+ $vote->fetchAnswers = $fetchAnswers;
+ $vote->fetch();
+ return $vote;
+ }
+}
+
+class SurveyAnswer extends PlDBTableEntry
+{
+ public $inError = false;
+ public $vote;
+
+ public function __construct(SurveyVote $vote)
+ {
+ parent::__construct('survey_vote_answers');
+ $this->registerFieldFormatter('answer', 'JSonFieldFormatter');
+ $this->vote = $vote;
+ if (!is_null($vote->vid)) {
+ $this->vid = $vote->vid;
+ }
+ }
+
+ protected function preSave()
+ {
+ Platal::assert(!$this->inError, "Cannot save an invalid answer");
+ $this->sid = $this->vote->sid;
+ $this->vid = $this->vote->vid;
+ return true;
+ }
+
+ public function export()
+ {
+ $export = array();
+ if (!is_null($this->answer)) {
+ $export['value'] = $this->answer->export();
+ }
+ if ($this->inError !== false) {
+ $export['error'] = $this->inError;
+ }
+ return $export;
+ }
+}
+
+// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
+?>
--- /dev/null
+<?php
+/***************************************************************************
+ * Copyright (C) 2003-2010 Polytechnique.org *
+ * http://opensource.polytechnique.org/ *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the Free Software *
+ * Foundation, Inc., *
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
+ ***************************************************************************/
+
+interface SurveyQuestionContainer
+{
+ public function addQuestion(SurveyQuestion $question, $pos = null);
+ public function newQuestion($type, $pos = null);
+ public function reassignQuestionIds();
+}
+
+class SurveyQuestion extends PlDBTableEntry
+{
+ protected $survey;
+ protected $parentQuestion;
+
+ public function __construct(Survey $survey)
+ {
+ parent::__construct('survey_questions');
+ $this->registerFieldFormatter('parameters', 'JSonFieldFormatter');
+ $this->survey = $survey;
+ }
+
+ public function typedInstance()
+ {
+ $instance = self::instanceForType($this->survey, $this->type);
+ $instance->copy($this);
+ return $instance;
+ }
+
+ public static function instanceForType(Survey $survey, $type)
+ {
+ require_once dirname(__FILE__) . '/' . $type . '.inc.php';
+ $class = 'SurveyQuestion' . $type;
+ return new $class($survey);
+ }
+
+ public function voteTemplate()
+ {
+ return 'survey/question.' . $this->type . '.tpl';
+ }
+
+ public function editTemplate()
+ {
+ return 'survey/edit.' . $this->type . '.tpl';
+ }
+
+ protected function buildAnswer(SurveyAnswer $answer, PlDict $answers)
+ {
+ Platal::assert(false, "This should not happen");
+ }
+
+ public function vote(SurveyVote $vote, PlDict $answers)
+ {
+ if ($this->flags->hasFlag('noanswer')) {
+ if ($answers->has($this->qid)) {
+ throw new Exception("Des réponses ont été données à une question n'en attendant pas");
+ }
+ return null;
+ }
+ $answer = $vote->getAnswer($this);
+ if (is_null($answer)) {
+ return null;
+ }
+ if (!$this->buildAnswer($answer, $answers)) {
+ return $answer;
+ }
+ if ($this->flags->hasFlag('mandatory') && is_null($answer->answer)) {
+ $answer->inError = 'Tu dois répondre à cette question';
+ }
+ return $answer;
+ }
+}
+
+class SurveyQuestionGroup extends SurveyQuestion implements SurveyQuestionContainer
+{
+ public $children = array();
+
+ public function __construct(Survey $survey)
+ {
+ parent::__construct($survey);
+ }
+
+ public function addQuestion(SurveyQuestion $question, $pos = null)
+ {
+ $question->parentQuestion = $this;
+ if (is_null($pos)) {
+ $this->children[] = $question;
+ } else {
+ array_splice($this->children, $pos, 0, $question);
+ }
+ }
+
+ public function newQuestion($type, $pos = null)
+ {
+ $question = SurveyQuestion::instanceForType($this->survey, $type);
+ $this->addQuestion($question, $pos);
+ return $question;
+ }
+
+ public function reassignQuestionIds()
+ {
+ $id = $this->qid + 1;
+ foreach ($this->children as $question) {
+ $question->qid = $id;
+ if ($question instanceof SurveyQuestionContainer) {
+ $id = $question->reassignQuestionIds();
+ } else {
+ $id++;
+ }
+ }
+ return $id;
+ }
+
+ protected function postSave()
+ {
+ foreach ($this->children as $question) {
+ $question->sid = $this->sid;
+ $question->parent = $this->qid;
+ $question->insert();
+ }
+ }
+
+ public function export()
+ {
+ $export = parent::export();
+ $export['children'] = array();
+ foreach ($this->children as $child) {
+ $export['children'][] = $child->export();
+ }
+ return $export;
+ }
+
+ public function vote(SurveyVote $vote, PlDict $answers)
+ {
+ $a = parent::vote($vote, $answers);
+ foreach ($this->children as $child) {
+ $child->vote($vote, $answers);
+ }
+ return $a;
+ }
+
+ public function child($qid)
+ {
+ $prev = null;
+ foreach ($this->children as $question) {
+ if ($qid == $question->qid) {
+ return $question;
+ } else if ($qid < $question->qid) {
+ Platal::assert($prev instanceof SurveyQuestionGroup);
+ return $prev->child($qid);
+ }
+ $prev = $question;
+ }
+ Platal::assert($prev instanceof SurveyQuestionGroup);
+ return $prev->child($qid);
+ }
+}
+
+// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
+?>
--- /dev/null
+<?php
+/***************************************************************************
+ * Copyright (C) 2003-2010 Polytechnique.org *
+ * http://opensource.polytechnique.org/ *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the Free Software *
+ * Foundation, Inc., *
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
+ ***************************************************************************/
+
+class SurveyQuestionSection extends SurveyQuestionGroup
+{
+ public function __construct(Survey $survey)
+ {
+ parent::__construct($survey);
+ $this->type = "section";
+ $this->flags = 'noanswer';
+ }
+}
+
+// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
+?>
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
***************************************************************************/
-// {{{ class Survey : root of any survey, contains all questions
-class Survey
-{
- // {{{ static properties and functions, regarding survey modes and question types
- const MODE_ALL = 0;
- const MODE_XANON = 1;
- const MODE_XIDENT = 2;
- private static $longModes = array(self::MODE_ALL => "sondage ouvert à tout le monde, anonyme",
- self::MODE_XANON => "sondage restreint aux polytechniciens, anonyme",
- self::MODE_XIDENT => "sondage restreint aux polytechniciens, non anonyme");
- private static $shortModes = array(self::MODE_ALL => "tout le monde, anonyme",
- self::MODE_XANON => "polytechniciens, anonyme",
- self::MODE_XIDENT => "polytechniciens, non anonyme");
-
- public static function getModes($long = true) {
- return ($long)? self::$longModes : self::$shortModes;
- }
-
- private static $types = array('text' => 'Texte court',
- 'textarea' => 'Texte long',
- 'num' => 'Numérique',
- 'radio' => 'Choix multiples (une réponse)',
- 'checkbox' => 'Choix multiples (plusieurs réponses)',
- 'radiotable' => 'Questions multiples à choix multiples (une réponse)',
- 'checkboxtable' => 'Questions multiples à choix mutliples (plusieurs réponses)');
-
- public static function getTypes()
- {
- return self::$types;
- }
+require_once dirname(__FILE__) . '/question.inc.php';
+require_once dirname(__FILE__) . '/answer.inc.php';
- public static function isType($t)
- {
- return array_key_exists($t, self::$types);
- }
- // }}}
-
- // {{{ properties, constructor and basic methods
- private $id;
- private $title;
- private $description;
- private $end;
- private $mode;
- private $promos;
- private $valid;
- private $questions;
- private $creator;
+class Survey extends PlDBTableEntry implements SurveyQuestionContainer
+{
+ private $fetchQuestions = true;
+ public $questions = array();
+ public $viewerFilter = null;
+ public $voterFilter = null;
- public function __construct($args, $id = -1, $valid = false, $questions = null)
+ public function __construct()
{
- $this->update($args);
- $this->id = $id;
- $this->valid = $valid;
- $this->questions = ($questions == null)? array() : $questions;
+ parent::__construct('surveys');
+ $this->registerFieldValidator('shortname', 'ShortNameFieldValidator');
+ $this->registerFieldFormatter('voters', 'JSonFieldFormatter');
+ $this->registerFieldFormatter('viewers', 'JSonFieldFormatter');
}
- public function update($args)
+ protected function postFetch()
{
- $this->title = $args['title'];
- $this->description = $args['description'];
- $this->end = $args['end'];
- $this->mode = (isset($args['mode']))? $args['mode'] : self::MODE_ALL;
- $this->creator = $args['uid'];
- if ($this->mode == self::MODE_ALL) {
- $args['promos'] = '';
+ if (!is_null($this->voters)) {
+ $this->voterFilter = UserFilter::fromExportedConditions($this->voters);
+ } else {
+ $this->voterFilter = null;
}
- $args['promos'] = str_replace(' ', '', $args['promos']);
- $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
- }
-
- public function canSeeEarlyResults(User $user)
- {
- return $user->id() == $this->creator || $user->checkPerms('admin');
- }
- // }}}
-
- // {{{ functions to access general information
- public function isMode($mode)
- {
- return ($this->mode == $mode);
- }
-
- public function checkPromo($promo)
- {
- if ($this->promos == '') {
- return true;
+ if (!is_null($this->viewers)) {
+ $this->viewerFilter = UserFilter::fromExportedConditions($this->viewers);
+ } else {
+ $this->viewerFilter = null;
}
- $promos = explode(',', $this->promos);
- foreach ($promos as $p) {
- if ((preg_match('#^\d{4}$#', $p) && $p == $promo) ||
- (preg_match('#^\d{4}-$#', $p) && intval(substr($p, 0, 4)) <= $promo) ||
- (preg_match('#^-\d{4}$#', $p) && intval(substr($p, 1)) >= $promo) ||
- (preg_match('#^\d{4}-\d{4}$#', $p) &&
- (intval(substr($p, 0, 4)) <= $promo && intval(substr($p, 5)) >= $promo ||
- intval(substr($p, 0, 4)) >= $promo && intval(substr($p, 5)) <= $promo ))) {
- return true;
- }
+ if (!$this->fetchQuestions) {
+ return true;
}
- return false;
- }
-
- public function isValid()
- {
- return $this->valid;
- }
-
- public function isEnded()
- {
- return (strtotime($this->end) - time() <= 0);
- }
-
- public function getTitle()
- {
- return $this->title;
- }
- // }}}
-
- // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended
- public function toArray($i = 'all')
- {
- if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
- $i = intval($i);
- if (array_key_exists($i, $this->questions)) {
- return $this->questions[$i]->toArray();
+ $selector = new SurveyQuestion($this);
+ $selector->sid = $this->id;
+
+ $stack = array();
+ foreach ($selector as $question) {
+ $question = $question->typedInstance();
+ if (is_null($question->parent)) {
+ $this->addQuestion($question);
} else {
- return null;
- }
- } else { // else returns the root converted to array in any case
- $a = array('title' => $this->title,
- 'description' => $this->description,
- 'end' => $this->end,
- 'mode' => $this->mode,
- 'promos' => $this->promos,
- 'valid' => $this->valid,
- 'type' => 'root');
- if ($this->id != -1) {
- $a['id'] = $this->id;
- }
- if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
- $sql = 'SELECT COUNT(id)
- FROM survey_votes
- WHERE survey_id={?};';
- $tot = XDB::query($sql, $this->id);
- $a['votes'] = $tot->fetchOneCell();
- }
- if ($i == 'all' && count($this->questions) > 0) { // if the whole survey is requested, then returns all the questions converted to array
- $qArr = array();
- for ($k = 0; $k < count($this->questions); $k++) {
- $q = $this->questions[$k]->toArray();
- $q['id'] = $k;
- if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
- $q['result'] = $this->questions[$k]->getResultArray($this->id, $k);
- }
- $qArr[$k] = $q;
+ $pos = count($stack) - 1;
+ while ($stack[$pos]->qid != $question->parent) {
+ --$pos;
+ array_pop($stack);
}
- $a['questions'] = $qArr;
+ Platal::assert(count($stack) > 0, "Invalid question structure");
+ Platal::assert($stack[$pos] instanceof SurveyQuestionContainer, "Invalid question type");
+ $stack[$pos]->addQuestion($question);
}
- return $a;
+ array_push($stack, $question);
}
+ return true;
}
- // }}}
- // {{{ function toCSV() : builds a CSV file containing all the results of the survey
- public function toCSV($sep = ',', $enc = '"', $asep='|')
+ protected function preSave()
{
- $nbq = count($this->questions);
- //require_once dirname(__FILE__) . '/../../classes/varstream.php';
- VarStream::init();
- global $csv_output;
- $csv_output = '';
- $csv = fopen('var://csv_output', 'w');
- $line = ($this->isMode(self::MODE_XIDENT))? array('id', 'Nom', 'Prenom', 'Promo') : array('id');
- $qids = array();
- for ($qid = 0; $qid < $nbq; $qid++) {
- $qids[$qid] = count($line); // stores the first id of a question (in case of questions with subquestions)
- array_splice($line, count($line), 0, $this->questions[$qid]->getCSVColumns()); // the first line contains the questions
- }
- $nbf = count($line);
- $users = array();
- if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
- $users = User::getBulkUsersWithUIDs(XDB::fetchAllAssoc('vid', 'SELECT v.id AS vid, v.uid
- FROM survey_votes AS v
- WHERE v.survey_id = {?}
- ORDER BY vid ASC',
- $this->id));
+ if (!is_null($this->voterFilter)) {
+ $this->voters = $this->voterFilter->exportConditions();
+ } else {
+ $this->voters = null;
}
- $sql = 'SELECT v.id AS vid, a.question_id AS qid, a.answer AS answer
- FROM survey_votes AS v
- INNER JOIN survey_answers AS a ON a.vote_id=v.id
- WHERE v.survey_id={?}
- ORDER BY vid ASC, qid ASC, answer ASC';
- $res = XDB::iterator($sql, $this->id); // retrieves all answers from database
- $vid = -1;
- $vid_ = 0;
- while (($cur = $res->next()) != null) {
- if ($vid != $cur['vid']) { // if the vote id changes, then starts a new line
- fputcsv($csv, $line, $sep, $enc); // stores the former line into $csv_output
- $vid = $cur['vid'];
- $line = array_fill(0, $nbf, ''); // creates an array full of empty string
- $line[0] = $vid_; // the first field is a 'clean' vote id (not the one stored in database)
- if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
- if (array_key_exists($vid, $users)) { // and if the user data can be found
- $line[1] = $users[$vid]->lastName(); // adds the user data (in the first fields of the line)
- $line[2] = $users[$vid]->firstName();;
- $line[3] = $users[$vid]->promo();
- }
- }
- $vid_++;
- }
- $ans = $this->questions[$cur['qid']]->formatAnswer($cur['answer']); // formats the current answer
- if (!is_null($ans)) {
- if (is_array($ans)) {
- $fid = $qids[$cur['qid']] + $ans['id']; // computes the field id
- $a = $ans['answer'];
- } else {
- $fid = $qids[$cur['qid']];
- $a = $ans;
- }
- if ($line[$fid] != '') { // if this field already contains something
- $line[$fid] .= $asep; // then adds a separator before adding the new answer
- }
- $line[$fid] .= $a; // adds the current answer to the correct field
- }
+ if (!is_null($this->viewerFilter)) {
+ $this->viewers = $this->viewerFilter->exportConditions();
+ } else {
+ $this->viewers = null;
}
- fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output
- return $csv_output;
+ return true;
}
- // }}}
- // {{{ function factory($type, $args) : builds a question according to the given type
- public function factory($t, $args)
+ protected function postSave()
{
- switch ($t) {
- case 'text':
- return new SurveyText($args);
- case 'textarea':
- return new SurveyTextarea($args);
- case 'num':
- return new SurveyNum($args);
- case 'radio':
- return new SurveyRadio($args);
- case 'checkbox':
- return new SurveyCheckbox($args);
- case 'radiotable':
- return new SurveyRadioTable($args);
- case 'checkboxtable':
- return new SurveyCheckboxTable($args);
- default:
- return null;
+ $questions = array();
+ $selector = new SurveyQuestion($this);
+ $selector->sid = $this->id;
+ $selector->delete();
+
+ $this->reassignQuestionIds();
+ foreach ($this->questions as $question) {
+ $question->sid = $this->id;
+ $question->insert();
}
}
- // }}}
- // {{{ questions manipulation functions
- public function addQuestion($i, $c)
+ public function addQuestion(SurveyQuestion $question, $pos = null)
{
- $i = intval($i);
- if ($this->valid || $i > count($this->questions)) {
- return false;
+ $question->parent = null;
+ if (is_null($pos)) {
+ $this->questions[] = $question;
} else {
- array_splice($this->questions, $i, 0, array($c));
- return true;
+ array_splice($this->questions, $pos, 0, $question);
}
}
- public function delQuestion($i)
+ public function newQuestion($type, $pos = null)
{
- $i = intval($i);
- if ($this->valid || !array_key_exists($i, $this->questions)) {
- return false;
- } else {
- array_splice($this->questions, $i, 1);
- return true;
- }
+ $question = SurveyQuestion::instanceForType($this, $type);
+ $this->addQuestion($question, $pos);
+ return $question;
}
- public function editQuestion($i, $a)
+ public function questionForId($qid)
{
- if ($i == 'root') {
- $this->update($a);
- } else {
- $i = intval($i);
- if ($this->valid ||!array_key_exists($i, $this->questions)) {
- return false;
- } else {
- $this->questions[$i]->update($a);
+ $prev = null;
+ foreach ($this->questions as $question) {
+ if ($qid == $question->qid) {
+ return $question;
+ } else if ($qid < $question->qid) {
+ Platal::assert($prev instanceof SurveyQuestionGroup,
+ "Id gap must be caused by question groups");
+ return $prev->child($qid);
}
+ $prev = $question;
}
- return true;
+ Platal::assert($prev instanceof SurveyQuestionGroup,
+ "Id gap must be caused by question groups");
+ return $prev->child($qid);
}
- // }}}
-
- // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
- private static $errorMessages = array(
- "datepassed" => "la date de fin de sondage est déjà dépassée : vous devez préciser une date future",
- "promoformat" => "les restrictions à certaines promotions sont mal formattées"
- );
- public function checkSyntax()
+ public function reassignQuestionIds()
{
- $rArr = array();
- // checks that the end date given is not already passed
- // (unless the survey has already been validated : an admin can have a validated survey expired)
- if (!$this->valid && $this->isEnded()) {
- $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["datepassed"]);
- }
- if ($this->promos != '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos)) {
- $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["promoformat"]);
+ $id = 0;
+ foreach ($this->questions as $question) {
+ $question->qid = $id;
+ if ($question instanceof SurveyQuestionContainer) {
+ $id = $question->reassignQuestionIds();
+ } else {
+ $id++;
+ }
}
- return (empty($rArr))? null : $rArr;
+ return $id;
}
- // }}}
- // {{{ functions that manipulate surveys in database
- // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
- public static function retrieveList($type, $tpl = true)
+ public function export()
{
- switch ($type) {
- case 'c':
- case 'current':
- $where = 'end > NOW()';
- break;
- case 'o':
- case 'old':
- $where = 'end <= NOW()';
- break;
- default:
- return null;
- }
- $sql = 'SELECT id, title, end, mode
- FROM surveys
- WHERE '.$where.'
- ORDER BY end DESC;';
- if ($tpl) {
- return XDB::iterator($sql);
- } else {
- return XDB::iterRow($sql);
+ $export = parent::export();
+ $export['questions'] = array();
+ foreach ($this->questions as $question) {
+ $export['questions'][] = $question->export();
}
+ return $export;
}
- // }}}
- // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
- public static function retrieveSurvey($sid)
+ /* Return an indicator of the progression of the survey:
+ * negative values means 'the survey is not started'
+ * 0 means 'the survey is in progress'
+ * positive values means 'the survey expired'
+ */
+ public function progression()
{
- $sql = 'SELECT questions, title, description, end, mode, promos, uid
- FROM surveys
- WHERE id={?}';
- $res = XDB::query($sql, $sid);
- $data = $res->fetchOneAssoc();
- if (is_null($data) || !is_array($data)) {
- return null;
+ if (!$this->flags->hasFlag('validated')) {
+ return -2;
}
- $survey = new Survey($data, $sid, true, unserialize($data['questions']));
- return $survey;
- }
- // }}}
-
- // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
- public static function retrieveSurveyInfo($sid)
- {
- $sql = 'SELECT title, description, end, mode, promos
- FROM surveys
- WHERE id={?}';
- $res = XDB::query($sql, $sid);
- return $res->fetchOneAssoc();
- }
- // }}}
-
- // {{{ static function retrieveSurveyReq() : gets a survey request to validate
- public static function retrieveSurveyReq($id)
- {
- $surveyreq = Validate::get_request_by_id($id);
- if ($surveyreq == null) {
- return null;
+ $now = time();
+ if ($this->begin->format('U') > $now) {
+ return -1;
}
- $data = array('title' => $surveyreq->title,
- 'description' => $surveyreq->description,
- 'end' => $surveyreq->end,
- 'mode' => $surveyreq->mode,
- 'promos' => $surveyreq->promos);
- $survey = new Survey($data, $id, false, $surveyreq->questions);
- return $survey;
- }
- // }}}
-
- // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
- public function proposeSurvey()
- {
- $surveyreq = new SurveyReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions, S::user());
- return $surveyreq->submit();
- }
- // }}}
-
- // {{{ function updateSurvey() : updates a survey in database (before validation)
- public function updateSurvey()
- {
- if ($this->valid) {
- $sql = 'UPDATE surveys
- SET questions={?},
- title={?},
- description={?},
- end={?},
- mode={?},
- promos={?}
- WHERE id={?};';
- return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, $this->end, $this->mode, $this->promos, $this->id);
- } else {
- $surveyreq = Validate::get_request_by_id($this->id);
- if ($surveyreq == null) {
- return false;
- }
- return $surveyreq->updateReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions);
+ if ($this->end->format('U') <= $now) {
+ return 1;
}
+ return 0;
}
- // }}}
- // {{{ functions vote() and hasVoted() : handles vote to a survey
- public function vote($uid, $args)
+ public function canSee(User $user)
{
- XDB::execute('INSERT INTO survey_votes
- SET survey_id = {?}, uid = {?}',
- $this->id, ($uid == 0) ? null : $uid); // notes the user as having voted
- $vid = XDB::insertId();
- for ($i = 0; $i < count($this->questions); $i++) {
- $ans = $this->questions[$i]->checkAnswer($args[$i]);
- if (!is_null($ans) && is_array($ans)) {
- foreach ($ans as $a) {
- XDB::execute('INSERT INTO survey_answers
- SET vote_id = {?},
- question_id = {?},
- answer = {?}', $vid, $i, $a);
- }
- }
+ if ($this->canSeeResults($user) || $this->canVote($user)) {
+ return true;
}
+ return false;
}
- public function hasVoted($uid)
- {
- $res = XDB::query('SELECT id
- FROM survey_votes
- WHERE survey_id = {?} AND uid = {?};', $this->id, $uid); // checks whether the user has already voted
- return ($res->numRows() != 0);
- }
- // }}}
-
- // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
- public static function deleteSurvey($sid)
- {
- $sql = 'DELETE s.*, v.*, a.*
- FROM surveys AS s
- LEFT JOIN survey_votes AS v
- ON v.survey_id=s.id
- LEFT JOIN survey_answers AS a
- ON a.vote_id=v.id
- WHERE s.id={?};';
- return XDB::execute($sql, $sid);
- }
- // }}}
-
- // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
- public static function purgeVotes($sid)
- {
- $sql = 'DELETE v.*, a.*
- FROM survey_votes AS v
- LEFT JOIN survey_answers AS a
- ON a.vote_id=v.id
- WHERE v.survey_id={?};';
- return XDB::execute($sql, $sid);
- }
- // }}}
-
- // }}}
-}
-// }}}
-
-// {{{ abstract class SurveyQuestion
-abstract class SurveyQuestion
-{
- // {{{ common properties, constructor, and basic methods
- private $question;
- private $comment;
-
- public function __construct($args)
- {
- $this->update($args);
- }
-
- public function update($a)
- {
- $this->question = $a['question'];
- $this->comment = $a['comment'];
- }
-
- abstract protected function getQuestionType();
- // }}}
-
- // {{{ function toArray() : converts to array
- public function toArray()
- {
- return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment);
- }
- // }}}
-
- // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
- protected function checkSyntax()
- {
- return null;
- }
- // }}}
-
- // {{{ function checkAnswer : returns a correct answer (or a null value if error)
- public function checkAnswer($ans)
- {
- return null;
- }
- // }}}
-
- // {{{ functions regarding the results of a survey
- abstract public function getResultArray($sid, $qid);
-
- public function formatAnswer($ans)
- {
- return $ans;
- }
-
- public function getCSVColumns()
- {
- return $this->question;
- }
- // }}}
-}
-// }}}
-
-// {{{ abstract class SurveySimple and its derived classes : "open" questions
-// {{{ abstract class SurveySimple extends SurveyQuestion
-abstract class SurveySimple extends SurveyQuestion
-{
- public function checkAnswer($ans)
- {
- return array($ans);
- }
-
- public function getResultArray($sid, $qid)
- {
- $sql = 'SELECT answer
- FROM survey_answers
- WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
- AND question_id={?}
- ORDER BY RAND()
- LIMIT 5;';
- $res = XDB::query($sql, $sid, $qid);
- return $res->fetchAllAssoc();
- }
-}
-// }}}
-
-// {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
-class SurveyText extends SurveySimple
-{
- public function getQuestionType()
- {
- return "text";
- }
-}
-// }}}
-
-// {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
-class SurveyTextarea extends SurveySimple
-{
- public function getQuestionType()
- {
- return "textarea";
- }
-}
-// }}}
-
-// {{{ class SurveyNum extends SurveySimple : allows numerical answers
-class SurveyNum extends SurveySimple
-{
- public function checkAnswer($ans)
- {
- return array(intval($ans));
- }
-
- protected function getQuestionType()
- {
- return "num";
- }
-}
-// }}}
-// }}}
-
-// {{{ abstract class SurveyList and its derived classes : restricted questions that allows only a list of possible answers
-// {{{ abstract class SurveyList extends SurveyQuestion
-abstract class SurveyList extends SurveyQuestion
-{
- protected $choices;
-
- public function update($args)
+ public function canSeeResults(User $user)
{
- parent::update($args);
- $this->choices = array();
- foreach ($args['choices'] as $val) {
- if (trim($val) || trim($val) == '0') {
- $this->choices[] = $val;
- }
+ if ($user->id() == $this->uid || $user->hasFlag('admin')) {
+ return true;
}
- }
-
- public function toArray()
- {
- $rArr = parent::toArray();
- $rArr['choices'] = $this->choices;
- return $rArr;
- }
-
- public function getResultArray($sid, $qid)
- {
- $sql = 'SELECT answer, COUNT(id) AS count
- FROM survey_answers
- WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
- AND question_id={?}
- GROUP BY answer ASC';
- $res = XDB::query($sql, $sid, $qid);
- return $res->fetchAllAssoc();
- }
-
- public function formatAnswer($ans)
- {
- if (array_key_exists($ans, $this->choices)) {
- return $this->choices[$ans];
- } else {
- return null;
+ if (is_null($this->viewerFilter)) {
+ return $this->viewerFilter->checkUser($user);
}
- }
-}
-// }}}
-
-// {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
-class SurveyRadio extends SurveyList
-{
- public function checkAnswer($ans)
- {
- $a = intval($ans);
- return (array_key_exists($a, $this->choices))? array($a) : null;
+ return false;
}
- protected function getQuestionType()
+ public function canVote(User $user)
{
- return "radio";
- }
-}
-// }}}
-
-// {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
-class SurveyCheckbox extends SurveyList
-{
- public function checkAnswer($ans)
- {
- $rep = array();
- foreach ($ans as $a) {
- $a = intval($a);
- if (array_key_exists($a, $this->choices)) {
- $rep[] = $a;
- }
+ $status = $this->progression();
+ if ($status < 0) {
+ return "Ce sondage n'est pas encore commencé";
+ } else if ($status > 0) {
+ return "Ce sondage est terminé";
}
- return (count($rep) == 0)? null : $rep;
- }
-
- protected function getQuestionType()
- {
- return "checkbox";
- }
-}
-// }}}
-// }}}
-
-// {{{ abstract class SurveyTable and its derived classes : table question, each column represents a choice, each line represents a question
-// {{{ abstract class SurveyTable extends SurveyList
-abstract class SurveyTable extends SurveyList
-{
- protected $subquestions;
-
- public function update($args)
- {
- parent::update($args);
- $this->subquestions = array();
- foreach ($args['subquestions'] as $val) {
- if (trim($val) || trim($val) == '0') {
- $this->subquestions[] = $val;
- }
+ if (!is_null($this->voterFilter) && !$this->voterFilter->checkUser($user)) {
+ return "Ce sondage ne s'adresse pas à toi";
}
+ $vote = SurveyVote::getVote($this, $user, false);
+ if (is_null($vote)) {
+ return "Tu as déjà voté à ce sondage.";
+ }
+ return true;
}
- public function toArray()
- {
- $rArr = parent::toArray();
- $rArr['subquestions'] = $this->subquestions;
- return $rArr;
- }
-
- public function getResultArray($sid, $qid)
+ public function vote(User $user, array $answers)
{
- $sql = 'SELECT answer, COUNT(id) AS count
- FROM survey_answers
- WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
- AND question_id={?}
- GROUP BY answer ASC';
- $res = XDB::iterator($sql, $sid, $qid);
- $result = array();
- for ($i = 0; $i < count($this->subquestions); $i++) {
- $result[$i] = array_fill(0, count($this->choices), 0);
+ if (!$this->canVote($user)) {
+ return array('survey' => "Tu n'es pas autorisé à voter à ce sondage.");
}
- while ($r = $res->next()) {
- list($i, $j) = explode(':', $r['answer']);
- $result[$i][$j] = $r['count'];
+ $vote = SurveyVote::getVote($this, $user);
+ if (is_null($vote)) {
+ return $vote;
}
- return $result;
- }
-
- public function formatAnswer($ans)
- {
- list($q, $c) = explode(':', $ans);
- if (array_key_exists($q, $this->subquestions) && array_key_exists($c, $this->choices)) {
- return array('id' => $q, 'answer' => $this->choices[$c]);
- } else {
- return null;
+ $answers = new PlDict($answers);
+ foreach ($this->questions as $question) {
+ $question->vote($vote, $answers);
}
+ return $vote;
}
- public function getCSVColumns()
+ public static function get($name, $fetchQuestions = true)
{
- $q = parent::getCSVColumns();
- if (empty($this->subquestions)) {
- return $q;
+ if (is_array($name)) {
+ $name = $name[0];
}
- $a = array();
- for ($k = 0; $k < count($this->subquestions); $k++) {
- $a[$k] = $q.' : '.$this->subquestions[$k];
+ $survey = new Survey();
+ $survey->fetchQuestions = $fetchQuestions;
+ if (can_convert_to_integer($name)) {
+ $survey->id = $name;
+ } else {
+ $survey->shortname = $name;
}
- return $a;
- }
-}
-// }}}
-
-// {{{ class SurveyRadioTable extends SurveyTable : SurveyTable with radio type choices
-class SurveyRadioTable extends SurveyTable
-{
- public function checkAnswer($ans)
- {
- $rep = array();
- foreach ($ans as $k => $a) {
- if (!array_key_exists($k, $this->subquestions)) {
- continue;
- }
- $a = intval($a);
- if (array_key_exists($a, $this->choices)) {
- $rep[] = $k . ':' . $a;
- }
+ if (!$survey->fetch()) {
+ return null;
}
- return (count($rep) == 0)? null : $rep;
+ return $survey;
}
- protected function getQuestionType()
+ public static function iterActive()
{
- return "radiotable";
+ $survey = new Survey();
+ $survey->fetchQuestions = false;
+ return $survey->iterateOnCondition('begin <= CURDATE() AND end >= CURDATE()
+ AND FIND_IN_SET(\'validated\', flags)');
}
-
}
-// }}}
-// {{{ class SurveyCheckboxTable extends SurveyTable : SurveyTable with checkbox type choices
-class SurveyCheckboxTable extends SurveyTable
+class ShortNameFieldValidator implements PlDBTableFieldValidator
{
- public function checkAnswer($ans)
+ public function __construct(PlDBTableField $field, $value)
{
- $rep = array();
- foreach ($ans as $k => $aa) {
- if (!array_key_exists($k, $this->subquestions)) {
- continue;
- }
- foreach ($aa as $a) {
- $a = intval($a);
- if (array_key_exists($a, $this->choices)) {
- $rep[] = $k . ':' . $a;
- }
- }
+ if (can_convert_to_integer($value) || !preg_match('/^[a-z0-9]+[-_\.a-z0-9]*[a-z0-9]+$/i', $value)) {
+ throw new PlDBBadValueException($value, $field,
+ 'The shortname can only contain alphanumerical caracters, dashes, underscores and dots');
}
- return (count($rep) == 0)? null : $rep;
- }
-
- protected function getQuestionType()
- {
- return "checkboxtable";
}
-
}
-// }}}
-// }}}
// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
?>
--- /dev/null
+<?php
+/***************************************************************************
+ * Copyright (C) 2003-2010 Polytechnique.org *
+ * http://opensource.polytechnique.org/ *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the Free Software *
+ * Foundation, Inc., *
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
+ ***************************************************************************/
+
+class SurveyQuestionText extends SurveyQuestion
+{
+ public function __construct(Survey $survey)
+ {
+ parent::__construct($survey);
+ $this->type = "text";
+ }
+
+ protected function buildAnswer(SurveyAnswer $answer, PlDict $data)
+ {
+ $value = $data->t($this->qid);
+ if (!empty($value)) {
+ $answer->answer = array('text' => $value);
+ } else {
+ $answer->answer = null;
+ }
+ return true;
+ }
+}
+
+// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
+?>
$globals->asso('mail_domain'));
$page->assign('listes', $mmlist->get_lists());
$page->assign('user', S::user());
- $page->addJsLink('ajax.js');
if (Post::has('send')) {
S::assert_xsrf_token();
global $globals;
$page->changeTpl('xnetgrp/membres-add.tpl');
- $page->addJsLink('ajax.js');
if (is_null($email)) {
return;
<ul>
<li><a href="admin/add_accounts">Ajout d'un ensemble d'utilisateurs</a></li>
- <li>Ajouter une secrétaire de l'AX:</li>
+ <li>Ajouter un compte manuel :</li>
</ul>
<p>
<form action="admin/accounts" method="post">
<option value="fx">Personnel de la FX</option>
<option value="school">Personnel de l'Ecole</option>
</select>
+ <a href="admin/account/types">Détail des permissions associées</a>
</td>
</tr>
<tr>
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-
-<h1>Regexps pour les détections de bounces</h1>
-
-<p>
-Rappel sur les niveaux :
-</p>
-<ul>
- <li>0: IGNORE == ignorer le bounce</li>
- <li>1: NOTICE == forwarder le bounce (typiquement vacation)</li>
- <li>2: ERREUR == erreur</li>
-</ul>
-
-
-<form action="admin/postfix/regexp_bounces" method="post">
- <table class="bicol" cellpadding='0' cellspacing='0'>
- <tr>
- <th>Position/Niveau</th>
- <th>Regexp/Raison</th>
- </tr>
- {if $new}
- <tr class="impair">
- <td>
- <input type='text' name='pos[NULL]' value='' size='4' maxlength='4' />
- </td>
- <td>
- <input type="text" size="82" name='re[NULL]' value="{$re.re}" />
- </td>
- </tr>
- <tr class="impair">
- <td style="white-space: nowrap">
- <input type='radio' name='lvl[NULL]' value='0' {if $re.lvl eq 0}checked="checked"{/if} />
- <input type='radio' name='lvl[NULL]' value='1' {if $re.lvl eq 1}checked="checked"{/if} />
- <input type='radio' name='lvl[NULL]' value='2' {if $re.lvl eq 2}checked="checked"{/if} />
- </td>
- <td>
- <input type="text" size="32" name='text[NULL]' value="{$re.text}" />
- </td>
- </tr>
- {else}
- <tr class="impair">
- <td colspan="2" class="right action">
- <a href="admin/postfix/regexp_bounces/new">nouveau</a>
- </td>
- </tr>
- {/if}
- {iterate from=$bre item=re}
- <tr class="{cycle values="pair,pair,impair,impair"}">
- <td>
- <input type='text' name='pos[{$re.id}]' value='{$re.pos}' size='4' maxlength='4' />
- </td>
- <td>
- <input type="text" size="82" name='re[{$re.id}]' value="{$re.re}" />
- </td>
- </tr>
- <tr class="{cycle values="pair,pair,impair,impair"}">
- <td style="white-space: nowrap">
- <input type='radio' name='lvl[{$re.id}]' value='0' {if $re.lvl eq 0}checked="checked"{/if} />
- <input type='radio' name='lvl[{$re.id}]' value='1' {if $re.lvl eq 1}checked="checked"{/if} />
- <input type='radio' name='lvl[{$re.id}]' value='2' {if $re.lvl eq 2}checked="checked"{/if} />
- </td>
- <td>
- <input type="text" size="32" name='text[{$re.id}]' value="{$re.text}" /><br />
- </td>
- </tr>
- {/iterate}
- <tr class="{cycle values="pair,impair"}">
- <td colspan="2" class="center">
- <input type="submit" value="valider" name="submit" />
- </td>
- </tr>
- </table>
-</form>
-
-
-{* vim:set et sw=2 sts=2 sws=2 enc=utf-8: *}
<a href="admin/postfix/whitelist">Whitelist</a>
|
<a href="admin/postfix/delayed">Retardés</a>
- |
- <a href="admin/postfix/regexp_bounces">Regexps Bounces</a>
</td>
</tr>
<tr class="pair">
}
$(document).ready(function() {
- $('#tabs > ul').tabs();
+ $('#tabs').tabs();
$('.ui-tabs-nav li').width('24%')
.click(function() { $(this).children('a').click() });
});
<div id="tabs">
<ul style="margin-top: 0">
- <li><a href="{$platal->pl_self()}#account"><span >Compte de {$user->login()}</span></a></li>
- <li><a href="{$platal->pl_self()}#emails"><span>Emails</span></a></li>
- <li><a href="{$platal->pl_self()}#authext"><span>OpenID</span></a></li>
- <li><a href="{$platal->pl_self()}#forums"><span>Forums</span></a></li>
+ <li><a href="#account"><span>Compte de {$user->login()}</span></a></li>
+ <li><a href="#emails"><span>Emails</span></a></li>
+ <li><a href="#authext"><span>OpenID</span></a></li>
+ <li><a href="#forums"><span>Forums</span></a></li>
</ul>
</div>
</table>
</form>
-{javascript name="ajax"}
{test_email hruid=$user->login()}
<h1>Autres adresses de l'utilisateur</h1>
</h1>
{if $actuel}
- {javascript name=ajax}
{if $user->hasProfile()}
<table class="flags">
<tr>
<td class="orange">
<input type="checkbox" {if $mail_public}checked="checked"{/if}
- onclick="
- Ajax.update_html(null,'{$globals->baseurl}/emails/alias/set/'+(this.checked?'public':'private')+'?token={xsrf_token}');
- document.getElementById('mail_public').innerHTML = (this.checked?'public et apparaît donc sur ta fiche':'privé et n\'apparaît nulle part sur le site') + '.';
+ onclick="$.xget('{$globals->baseurl}/emails/alias/set/'+(this.checked?'public':'private')+'?token={xsrf_token}');
+ $('#mail_public').html((this.checked?'public et apparaît donc sur ta fiche':'privé et n\'apparaît nulle part sur le site') + '.');
" />
</td>
<td>
{include wiki=Xorg.Antispam part=1}
-{javascript name=ajax}
<script type="text/javascript">//<![CDATA[
{literal}
- function bogoUpdated()
- {
- showTempMessage('bogo-msg', "Le changement de réglage de l'antispam a bien été effectué.", true);
- }
+ $(document).ready(function() {
+ var url = '{/literal}{$globals->baseurl}/emails/antispam/{literal}';
+ var msg = "Le changement de réglage de l'antispam a bien été effectué.";
+ $(':radio[name=statut_filtre]').change(function() {
+ $("#bogo-msg").successMessage(url + $(this).val(), msg);
+ });
+ });
{/literal}
//]]></script>
<fieldset>
<legend><strong>Choisis ton propre réglage :</strong></legend>
- <input id='s0' type='radio' name='statut_filtre' value='0' {if $filtre eq 0}checked="checked"{/if} onclick="Ajax.update_html(null, '{$globals->baseurl}/emails/antispam/'+this.value, bogoUpdated)" />
+ <input id='s0' type='radio' name='statut_filtre' value='0' {if $filtre eq 0}checked="checked"{/if} />
<label for='s0'>(1) le filtre anti-spam n'agit pas sur tes emails</label>
<br />
- <input id='s1' type='radio' name='statut_filtre' value='1' {if $filtre eq 1}checked="checked"{/if} onclick="Ajax.update_html(null, '{$globals->baseurl}/emails/antispam/'+this.value, bogoUpdated)" />
+ <input id='s1' type='radio' name='statut_filtre' value='1' {if $filtre eq 1}checked="checked"{/if} />
<label for='s1'>(2) le filtre anti-spam marque les emails</label>
<br />
- <input id='s2' type='radio' name='statut_filtre' value='2' {if $filtre eq 2}checked="checked"{/if} onclick="Ajax.update_html(null, '{$globals->baseurl}/emails/antispam/'+this.value, bogoUpdated)" />
+ <input id='s2' type='radio' name='statut_filtre' value='2' {if $filtre eq 2}checked="checked"{/if} />
<label for='s2'>(3) le filtre anti-spam marque les emails, et élimine les spams avec des notes les plus hautes</label>
<br />
- <input id='s3' type='radio' name='statut_filtre' value='3' {if $filtre eq 3}checked="checked"{/if} onclick="Ajax.update_html(null, '{$globals->baseurl}/emails/antispam/'+this.value, bogoUpdated)" />
+ <input id='s3' type='radio' name='statut_filtre' value='3' {if $filtre eq 3}checked="checked"{/if} />
<label for='s3'>(4) le filtre anti-spam élimine les emails détectés comme spams</label>
</fieldset>
<h1>Gestion de mes emails</h1>
-{javascript name=ajax}
{literal}
<script type="text/javascript">
- function bestaliasUpdated() {
- showTempMessage('bestalias-msg', "Le changement a bien été effectué.", true);
- }
+ //<![CDATA[
+ $(document).ready(function() {
+ var url = '{/literal}{$globals->baseurl}/emails/best/{literal}';
+ var tok = '{/literal}{xsrf_token}{literal}';
+ var msg = "Le changement a bien été effectué.";
+ $(':radio[name=best]').change(function() {
+ $("#bestalias-msg").successMessage(url + $(this).val() + '?token=' + tok, msg);
+ });
+ });
+ //]]>
</script>
{/literal}
Tes adresses polytechniciennes sont :<br />
<div>
{iterate from=$aliases item=a}
- <label><input type='radio' {if $a.best}checked="checked"{/if} name='best' value='{$a.alias}' onclick='Ajax.update_html(null,"{$globals->baseurl}/emails/best/{$a.alias}?token={xsrf_token}",bestaliasUpdated)' />
+ <label><input type='radio' {if $a.best}checked="checked"{/if} name='best' value='{$a.alias}' />
{if $a.a_vie}(**){/if}{if $a.cent_ans}(*){/if} <strong>{$a.alias}</strong>@{#globals.mail.domain#} et
@{#globals.mail.domain2#}</label>
{if $a.expire}<span class='erreur'>(expire le {$a.expire|date_format})</span>{/if}
<a href="Xorg/SMTPSecurise">service d'envoi d'email SMTP sécurisé</a>.
</p>
- {javascript name=ajax}
<script type="text/javascript">//<![CDATA[
{literal}
function activeEnable()
function redirectUpdate()
{
- showTempMessage('redirect-msg', "Tes redirections ont été mises à jour.", true);
+ $('#redirect-msg').tmpMessage("Tes redirections ont été mises à jour.", true);
activeEnable();
}
function updateRedirect(checked, email)
{
activeEnable();
- Ajax.update_html(null, 'emails/redirect/' + (checked ? '' : 'in') + 'active/' + email, redirectUpdate);
+ $.xget('emails/redirect/' + (checked ? '' : 'in') + 'active/' + email,
+ redirectUpdate);
}
function rewriteUpdate(mail, allow, box)
onchange="updateRedirect(this.checked, '{$e->email}')" /></td>
<td style="text-align: left">
{if $e->has_rewrite()}
- <select onchange="Ajax.update_html(null,'emails/redirect/rewrite/{$e->email}/'+this.value, rewriteUpdate('{$e->email}', {$e->allow_rewrite|default:"0"}, this))">
+ <select onchange="$.get('emails/redirect/rewrite/{$e->email}/'+this.value, 'text', rewriteUpdate('{$e->email}', {$e->allow_rewrite|default:"0"}, this)); return false">
<option value=''>--- aucune ---</option>
{assign var=dom1 value=#globals.mail.domain#}
{assign var=dom2 value=#globals.mail.domain2#}
{literal}
function removeAttachments()
{
- Ajax.update_html(null, 'emails/send', null);
- document.getElementById('att_already').style.display = 'none';
- document.getElementById('att_form').style.display = '';
+ $.xget('email/send');
+ $('#att_already').hide();
+ $('#att_form').show();
}
{/literal}
//]]></script>
page = "{$globals->baseurl}/" + page;
{literal}
}
- Ajax.update_html('preview', page, null);
+ $('#preview').updateHtml(page);
return false;
}
{/literal}
if (link.childNodes[i].nodeName == 'STRONG') {
link.replaceChild(link.childNodes[i].firstChild,link.childNodes[i]);
}
- Ajax.update_html(null, 'events/read/'+id);
+ $.xget('events/read/'+id);
return false;
}
-->
<link rel="stylesheet" type="text/css" href="css/igoogle.css" media="all"/>
<script type="text/javascript">var platal_baseurl = "{$globals->baseurl}/";</script>
{javascript name=jquery}
- {javascript name=ajax}
{javascript name=xorg}
{javascript name=igoogle}
</head>
{if $name eq "email"}<td></td>{/if}
<td>
<span class="{$new}" style="display: none">
- <input type="text" maxlength="60" {if $error}class="error" value="{$val}"{/if} name="{if (($name neq "email_directory")
+ <input type="text" maxlength="255" {if $error}class="error" value="{$val}"{/if} name="{if (($name neq "email_directory")
&& ($name neq "email"))}jobs[{$i}][{$prefix}email_new]{else}{$name}_new{/if}"/>
</span>
<script type="text/javascript">//<![CDATA[
{/tidy}
{if !t($nochange)}
<div class="right">
- <a href="events" onclick="Ajax.update_html('tod', 'ajax/tips/{$tips.id}'); return false" style="text-decoration: none">
+ <a href="events" onclick="$('#tod').updateHtml('ajax/tips/{$tips.id}'); return false" style="text-decoration: none">
Astuce suivante {icon name=resultset_next title="Astuce suivante"}
</a>
</div>
{* *}
{**************************************************************************}
+<script type="text/javascript">
+ //<![CDATA[
+ {literal}
+ function updateHtml(id, url)
+ {
+ if (is_IE) {
+ return true;
+ } else {
+ $('#' + id).updateHtml(url);
+ return false;
+ }
+ }
+ {/literal}
+ //]]>
+</script>
+
<h1>
Listes de diffusion de Polytechnique.org
</h1>
<strong>• Demandes d'inscription</strong><br />
{foreach from=$liste.subscriptions item=s}
<a href='{$platal->ns}lists/moderate/{$liste.list}?sadd={$s.id}&token={xsrf_token}'
- onclick="return (is_IE || Ajax.update_html('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?sadd={$s.id}&token={xsrf_token}'));">
+ onclick="return updateHtml('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?sadd={$s.id}&token={xsrf_token}');">
{icon name=add title="Accepter"}
</a>
<a href='{$platal->ns}lists/moderate/{$liste.list}?sid={$s.id}'>
<span class="smaller">
{foreach from=$liste.mails item=m}
<a href='{$platal->ns}lists/moderate/{$liste.list}?mid={$m.id}&mok=1&token={xsrf_token}'
- onclick="return (is_IE || Ajax.update_html('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?mid={$m.id}&mok=1&token={xsrf_token}'));">
+ onclick="return updateHtml('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?mid={$m.id}&mok=1&token={xsrf_token}');">
{icon name=add title="Valider l'email"}
</a>
<a href='{$platal->ns}lists/moderate/{$liste.list}?mid={$m.id}&mdel=1&token={xsrf_token}'
- onclick="return (is_IE || Ajax.update_html('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?mid={$m.id}&mdel=1&token={xsrf_token}'));">
+ onclick="return updateHtml('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?mid={$m.id}&mdel=1&token={xsrf_token}');">
{icon name=delete title="Spam"}
</a>
De : {$m.sender}<br />
<td class='right'>
{if $liste.sub eq 2}
<a href='{$platal->ns}lists?del={$liste.list}&token={xsrf_token}'
- onclick="return (is_IE || Ajax.update_html('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?unsubscribe=1&token={xsrf_token}'));">
+ onclick="return updateHtml('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?unsubscribe=1&token={xsrf_token}');">
{icon name=cross title="me désinscrire"}
</a>
{elseif $liste.sub eq 1}
{icon name=flag_orange title='inscription en attente de modération'}
{else}
<a href='{$platal->ns}lists?add={$liste.list}&token={xsrf_token}'
- onclick="return (is_IE || Ajax.update_html('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?subscribe=1&token={xsrf_token}'));">
+ onclick="return updateHtml('list_{$liste.list}', '{$platal->ns}lists/ajax/{$liste.list}?subscribe=1&token={xsrf_token}');">
{icon name=add title="m'inscrire"}
</a>
{/if}
{* *}
{**************************************************************************}
+{if t($anchor)}
+{literal}
+<script type="text/javascript">
+//<![CDATA[
+$(document).ready(function() {
+{/literal}
+ location.hash = "#{$anchor}";
+{literal}
+});
+// ]]>
+</script>
+{/literal}
+{/if}
+
<h1>{$asso->nom} : Gestion des télépaiements </h1>
<p class="descr">
Voici la liste des paiements en ligne possible pour le groupe {$asso->nom} :
</p>
-{foreach from=$titres item=p}
+{foreach from=$titles item=p}
<fieldset>
-<legend><a href="{$platal->ns}payment/{$p.id}">{icon name=money title="Télépaiement"}{$p.text}</a></legend>
+<legend id="legend_{$p.id}"><a href="{$platal->ns}payment/{$p.id}">{icon name=money title="Télépaiement"}{$p.text}</a></legend>
{if $event[$p.id]}
{assign var='ev' value=$event[$p.id]}
<p>
- {if $p.url}
+ {if t($p.url)}
Plus d'informations sur ce télépaiement sont disponibles sur <a href="{$p.url}">cette page</a>.<br />
{/if}
- {if $ev.eid}
+ {if t($ev.eid)}
Ce paiement est associé à l'événement <a href="{$platal->ns}events">{$ev.title}</a>.<br />
{if $ev.ins}
Tu es inscrit à cet événements.
<table cellpadding="0" cellspacing="0" id="list_{$p.id}" class='bicol'>
<tr>
<th>
- {if $order eq 'timestamp'}
- <a href='{$platal->ns}payment?order={$order}&order_inv={$order_inv}'>
+ {if $order eq 'timestamp' && $order_id eq $p.id}
+ <a href='{$platal->ns}payment?order={$order}&order_inv={$order_inv}&order_id={$p.id}'>
<img src="{$platal->baseurl}images/{if !$order_inv}dn{else}up{/if}.png" alt="" title="Tri {if $order_inv}dé{/if}croissant" />
{else}
- <a href='{$platal->ns}payment?order=timestamp'>
+ <a href='{$platal->ns}payment?order=timestamp&order_id={$p.id}'>
{/if}Date</a>
</th>
<th colspan="2">
- {if $order eq 'nom'}
- <a href='{$platal->ns}payment?order={$order}&order_inv={$order_inv}'>
+ {if $order eq 'directory_name' && $order_id eq $p.id}
+ <a href='{$platal->ns}payment?order={$order}&order_inv={$order_inv}&order_id={$p.id}'>
<img src="{$platal->baseurl}images/{if $order_inv}dn{else}up{/if}.png" alt="" title="Tri {if !$order_inv}dé{/if}croissant" />
{else}
- <a href='{$platal->ns}payment?order=nom'>{/if}
+ <a href='{$platal->ns}payment?order=directory_name&order_id={$p.id}'>{/if}
NOM Prénom</a>
</th>
<th>
- {if $order eq 'promo'}
- <a href='{$platal->ns}payment?order={$order}&order_inv={$order_inv}'>
+ {if $order eq 'promo' && $order_id eq $p.id}
+ <a href='{$platal->ns}payment?order={$order}&order_inv={$order_inv}&order_id={$p.id}'>
<img src="{$platal->baseurl}images/{if $order_inv}dn{else}up{/if}.png" alt="" title="Tri {if !$order_inv}dé{/if}croissant" />
{else}
- <a href='{$platal->ns}payment?order=promo'>
+ <a href='{$platal->ns}payment?order=promo&order_id={$p.id}'>
{/if}Promo</a>
</th>
<th>
- {if $order eq 't.comment'}
- <a href='{$platal->ns}payment?order=comment&order_inv={$order_inv}'>
+ {if $order eq 'comment' && $order_id eq $p.id}
+ <a href='{$platal->ns}payment?order=comment&order_inv={$order_inv}&order_id={$p.id}'>
<img src="{$platal->baseurl}images/{if $order_inv}dn{else}up{/if}.png" alt="" title="Tri {if !$order_inv}dé{/if} siant" />
{else}
- <a href='{$platal->ns}payment?order=comment'>
+ <a href='{$platal->ns}payment?order=comment&order_id={$p.id}'>
{/if}Commentaire</a>
</th>
<th>
- {if $order eq 'amount'}
- <a href='{$platal->ns}payment?order={$order}&order_inv={$order_inv}'>
+ {if $order eq 'amount' && $order_id eq $p.id}
+ <a href='{$platal->ns}payment?order={$order}&order_inv={$order_inv}&order_id={$p.id}'>
<img src="{$platal->baseurl}images/{if $order_inv}dn{else}up{/if}.png" alt="" title="Tri {if !$order_inv}dé{/if}croissant" />
{else}
- <a href='{$platal->ns}payment?order=montant'>
+ <a href='{$platal->ns}payment?order=amount&order_id={$p.id}'>
{/if}Montant</a>
</th>
</tr>
{assign var="somme" value=0}
{foreach from=$trans[$p.id] item=p name=people}
- {if $p.nom neq "somme totale"}
+ {if !t($p.limit)}
<tr>
- <td class="center">{$p.date|date_format:"%d/%m/%y"}</td>
+ <td class="center">{if $p.date eq 0}-{else}{$p.date|date_format:"%d/%m/%y"}{/if}</td>
<td>
{profile user=$p.user promo=false}
</td>
{* *}
{**************************************************************************}
-{javascript name=ajax}
{assign var=terms value=$profile->getMentoringTerms()}
{assign var=countries value=$profile->getMentoringCountries()}
<div id="fiche">
{$reminder->text()}
</div>
<div class="center">
- <a href="reminder/yes" onclick="Ajax.update_html('reminder', '{$reminder->baseurl()}/yes'); return false" style="text-decoration: none">
+ <a href="reminder/yes" onclick="$('#reminder').updateHtml('{$reminder->baseurl()}/yes'); return false" style="text-decoration: none">
{icon name=add} M'inscrire
</a> -
- <a href="reminder/no" onclick="Ajax.update_html('reminder', '{$reminder->baseurl()}/no'); return false" style="text-decoration: none">
+ <a href="reminder/no" onclick="$('#reminder').updateHtml('{$reminder->baseurl()}/no'); return false" style="text-decoration: none">
{icon name=delete} Ne pas m'inscrire
</a> -
- <a href="reminder/later" onclick="Ajax.update_html('reminder', '{$reminder->baseurl()}/dismiss'); return false" style="text-decoration: none">
+ <a href="reminder/later" onclick="$('#reminder').updateHtml('{$reminder->baseurl()}/dismiss'); return false" style="text-decoration: none">
{icon name=cross} Décider plus tard
</a>
{if $reminder->info()}
<a href="{$reminder->baseurl()}/yes" style="text-decoration: none">
{icon name=add} M'inscrire
</a> -
- <a href="reminder/no" onclick="Ajax.update_html('reminder', '{$reminder->baseurl()}/no'); return false" style="text-decoration: none">
+ <a href="reminder/no" onclick="$('#reminder').updateHtml('{$reminder->baseurl()}/no'); return false" style="text-decoration: none">
{icon name=delete} Ne pas m'inscrire
</a> -
- <a href="reminder/later" onclick="Ajax.update_html('reminder', '{$reminder->baseurl()}/dismiss'); return false" style="text-decoration: none">
+ <a href="reminder/later" onclick="$('#reminder').updateHtml('{$reminder->baseurl()}/dismiss'); return false" style="text-decoration: none">
{icon name=cross} Décider plus tard
</a> -
<a class="popup2" style="text-decoration: none" href="Xorg/GoogleApps">{icon name=information} En savoir plus</a>
<div class="center">
<input type="submit" value="M'inscrire aux listes" /> -
- <a href="reminder/no" onclick="Ajax.update_html('reminder', '{$reminder->baseurl()}/no'); return false" style="text-decoration: none">
+ <a href="reminder/no" onclick="$('#reminder').updateHtml('{$reminder->baseurl()}/no'); return false" style="text-decoration: none">
{icon name=delete} Ne pas m'inscrire
</a> -
- <a href="reminder/later" onclick="Ajax.update_html('reminder', '{$reminder->baseurl()}/dismiss'); return false" style="text-decoration: none">
+ <a href="reminder/later" onclick="$('#reminder').updateHtml('{$reminder->baseurl()}/dismiss'); return false" style="text-decoration: none">
{icon name=cross} Décider plus tard
</a>
</div>
{/if}
<div class="right">
- <a href="reminder/later" onclick="Ajax.update_html('reminder', '{$reminder->baseurl()}/dismiss'); return false" style="text-decoration: none">
+ <a href="reminder/later" onclick="$('#reminder').updateHtml('{$reminder->baseurl()}/dismiss'); return false" style="text-decoration: none">
{icon name=cross} Mettre à jour plus tard
</a>
</div>
{if $search_results_nb eq 1}{literal}
<script type="text/javascript">
// popup automatically if only one result
- var alinks = document.getElementById('content').getElementsByTagName('a');
- for (i = 0; i < alinks.length; i++) {
- if (alinks[i].className == 'popup2') {
- popWin(alinks[i], 840, 600);
- break;
- }
- }
+ $(document).ready(function() {
+ $('#content a.popup2').click();
+ });
</script>
{/literal}{/if}
Actuellement, {$mentors_number} mentors et référents se sont déclarés sur {#globals.core.sitename#}.
</p>
-{javascript name=ajax}
{javascript name=jquery.jstree}
{javascript name=jobtermstree}
<script type="text/javascript">//<![CDATA[
var baseurl = platal_baseurl + "referent/";
{literal}
-var Ajax2 = new AjaxEngine();
/** Hides or display tree of all job terms */
function toggleJobTermsTree()
{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
{* *}
{**************************************************************************}
- <table>
- <tr>
- <td class="date-heure">
- <script type="text/javascript">
- <!--
- document.write(getNow());
- //-->
- </script>
- </td>
- <td class="inscrits">
- {$globals->core->NbIns|number_format} polytechniciens sur le web
- {if t($smarty.request.quick)}
- {assign var=requestQuick value=$smarty.request.quick}
- {else}
- {assign var=requestQuick value='Recherche dans l\'annuaire'}
- {/if}
- <form action="search" method="get">
- <div>
- <button id="quick_button" type="submit" style="display: none"
- onclick="if ($('#quick').val() === 'Recherche dans l\'annuaire') $('#quick').val('')">
- OK
- </button>
- <input type="text" size="20" name="quick" id="quick" class="quick_search"
- value="{$requestQuick}"
- onfocus="if (this.value === 'Recherche dans l\'annuaire') this.value='';
- $('#quick_button').show()"
- onblur="if (this.value === '') this.value='{$requestQuick|escape:javascript}'"
- />
- </div>
- </form>
- {if $smarty.session.auth gt AUTH_PUBLIC && $smarty.session.notifs}
- <a href="carnet/panel">{$smarty.session.notifs} événement{if $smarty.session.notifs gt 1}s{/if}</a>
- {/if}
- </td>
- </tr>
- </table>
+
+<table>
+ <tr>
+ <td class="date-heure"></td>
+ <td class="inscrits">
+ {$globals->core->NbIns|number_format} polytechniciens sur le web
+ {if t($smarty.request.quick)}
+ {assign var=requestQuick value=$smarty.request.quick}
+ {else}
+ {assign var=requestQuick value='Recherche dans l\'annuaire'}
+ {/if}
+ <form action="search" method="get">
+ <div>
+ <button id="quick_button" type="submit" style="display: none">
+ OK
+ </button>
+ <input type="text" size="20" name="quick" id="quick" class="quick_search"
+ value="{$requestQuick}" />
+ </div>
+ </form>
+ {if $smarty.session.auth gt AUTH_PUBLIC && $smarty.session.notifs}
+ <a href="carnet/panel">{$smarty.session.notifs} événement{if $smarty.session.notifs gt 1}s{/if}</a>
+ {/if}
+ </td>
+ </tr>
+</table>
{* vim:set et sw=2 sts=2 sws=2 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-<h1>Sondages</h1>
-
-<table class="bicol">
- <tr>
- <th>
- Sondages en cours
- </th>
- </tr>
- {iterate item=s from=$survey_current}
- <tr class="{cycle name=cs_cycle values="impair,pair"}">
- <td class="half">
- •
- <a href="survey/admin/{$s.id}">
- {$s.title} [{$s.end|date_format:"%x"} - {$survey_modes[$s.mode]}]
- </a>
- </td>
- </tr>
- {assign var="has_cs" value="true"}
- {/iterate}
- {if !$has_cs}
- <tr>
- <td class="half">Aucun sondage en cours</td>
- </tr>
- {/if}
-</table>
-
-<br />
-
-<table class="bicol">
- <tr>
- <th>
- Anciens sondages
- </th>
- </tr>
- {iterate item=s from=$survey_old}
- <tr class="{cycle name=os_cycle values="impair,pair"}">
- <td class="half">
- •
- <a href="survey/admin/{$s.id}">
- {$s.title} [{$s.end|date_format:"%x"} - {$survey_modes[$s.mode]}]
- </a>
- </td>
- </tr>
- {assign var="has_os" value="true"}
- {/iterate}
- {if !$has_os}
- <tr>
- <td class="half">Aucun ancien sondage</td>
- </tr>
- {/if}
-</table>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-<h1>Sondages : confirmation</h1>
-
-<form action="{$survey_formaction}" method="post">
- {if is_array($survey_formhidden)}
- {foreach from=$survey_formhidden item=s_value key=s_key}
- <input type="hidden" name="survey_{$s_key}" value="{$s_value}"/>
- {/foreach}
- {/if}
- {if $survey_message neq ""}
- {$survey_message}
- {else}
- Une confirmation est requise
- {/if}
- <br/>
- <input type="submit" name="survey_submit" value="Confirmer"/>
- <input type="submit" name="survey_cancel" value="Annuler"/>
-</form>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
- <tr>
- <td class="titre">Type</td>
- <td>
- <select name="survey_type" id="survey_type" onchange="Ajax.update_html('survey_form', 'survey/ajax/' + document.getElementById('survey_type').value); return false">
- {foreach from=$survey_types key='stype_v' item='stype_t'}
- <option value="{$stype_v}"{if $survey_type eq $stype_v} selected="selected"{/if}>{$stype_t}</option>
- {/foreach}
- </select>
- </td>
- </tr>
- {if $survey_type == "new"}
- {include file='survey/edit_question.tpl'}
- {else}
- {include file="survey/edit_$survey_type.tpl"}
- {/if}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
- {include file='survey/edit_question.tpl'}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
- <tr>
- <td class="titre">Question</td>
- <td><input type="text" name="survey_question[question]" size="50" maxlength="200" value="{$survey_current.question}"{if $disable_question} disabled="disabled"{/if}/></td>
- </tr>
- <tr>
- <td class="titre">Commentaire</td>
- <td><textarea name="survey_question[comment]" rows="5" cols="60">{$survey_current.comment}</textarea></td>
- </tr>
- <tr>
- <td></td>
- <td class="smaller">
- <a href="wiki_help/notitle" class="popup3">
- {icon name=information title="Syntaxe wiki"} Voir la syntaxe wiki autorisée pour le commentaire d'une question
- </a>
- </td>
- </tr>
- <script type="text/javascript">//<![CDATA[
- var id = new Array();
- id['choices'] = {$survey_current.choices|@count};
- id['subquestions'] = {$survey_current.subquestions|@count};
- {literal}
- function newField(name, tid)
- {
- fid = "t" + id[name];
- $("#" + name + "_" + tid).before('<div id="' + name + '_' + fid + '">'
- + '<input id="' + name + '_' + fid + '_field" type="text" name="survey_question[' + name + '][' + fid + ']" size="50" maxlength="200" value="" /> '
- + '<a href="javascript:removeField("' + name + '","' + fid + '")"><img src="images/icons/delete.gif" alt="" title="Supprimer" /></a>'
- + '</div>');
- id[name]++;
- $("#" + name + "_" + fid + "_field").focus();
- }
- function removeField(name, tid)
- {
- $("#" + name + "_" + tid).remove();
- }
- {/literal}
- //]]></script>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
- {include file='survey/edit_question.tpl'}
- <tr>
- <td class="titre">Choix</td>
- <td>
- {foreach from=$survey_current.choices key=value item=choice}
- <div id="choices_t{$value}">
- <input type="text" name="survey_question[choices][t{$value}]" size="50" maxlength="200" value="{$choice}" />
- <a href="javascript:removeField('choices','t{$value}')">{icon name=delete title="Supprimer"}</a>
- </div>
- {/foreach}
- <div id="choices_last">
- <a href="javascript:newField('choices','last')">{icon name=add}</a>
- </div>
- </td>
- </tr>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-{include file='survey/edit_radio.tpl'}
- <tr>
- <td class="titre">Sous-questions</td>
- <td>
- {foreach from=$survey_current.subquestions key=value item=subquestion}
- <div id="subquestions_t{$value}">
- <input type="text" name="survey_question[subquestions][t{$value}]" size="50" maxlength="200" value="{$subquestion}" />
- <a href="javascript:removeField('subquestions','t{$value}')">{icon name=delete title="Supprimer"}</a>
- </div>
- {/foreach}
- <div id="subquestions_last">
- <a href="javascript:newField('subquestions','last')">{icon name=add}</a>
- </div>
- </td>
- </tr>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
- <tr>
- <td class="titre">Titre</td>
- <td><input type="text" name="survey_question[title]" size="50" maxlength="200" value="{$survey_current.title}"/></td>
- </tr>
- <tr>
- <td class="titre">Commentaire</td>
- <td><textarea name="survey_question[description]" rows="5" cols="60">{$survey_current.description}</textarea></td>
- </tr>
- <tr>
- <td></td>
- <td class="smaller">
- <a href="wiki_help/notitle" class="popup3">
- {icon name=information title="Syntaxe wiki"} Voir la syntaxe wiki autorisée pour le commentaire du sondage
- </a>
- </td>
- </tr>
- <tr>
- <td class="titre">Date de fin</td>
- <td>
- {valid_date name="survey_question[end]" value=$survey_current.end to=90}
- <script type="text/javascript">//<![CDATA[
- {literal}
- $(document).ready(function() {
- function hidePromo(value) {
- if (value == "0" || value == "") {
- $("#ln_promo").hide();
- $("#ln_promo_exp").hide();
- } else {
- $("#ln_promo").show();
- $("#ln_promo_exp").show();
- }
- }
- $("[name='survey_question[mode]']").change(function() { hidePromo(this.value); });
- hidePromo({/literal}"{$survey_current.mode}"{literal});
- });
- {/literal}
- //]]></script>
- </td>
- </tr>
- <tr>
- <td class="titre">Type de sondage</td>
- <td>
- <select name="survey_question[mode]">
- {foreach from=$survey_modes item=text key=name}
- <option value="{$name}" {if $name eq $survey_current.mode}selected="selected"{/if}>{$text}</option>
- {/foreach}
- </select>
- </td>
- </tr>
- <tr id="ln_promo">
- <td class="titre">Promotions</td>
- <td><input type="text" name="survey_question[promos]" size="50" maxlength="200" value="{$survey_current.promos}"/></td>
- </tr>
- <tr id="ln_promo_exp">
- <td></td>
- <td class="smaller">
- Exemple : 1954,1986-1989,-1942,2000- restreindra le sondage à toutes les promotions suivantes :<br/>
- 1954, 1986 à 1989, toutes jusqu'à 1942 et toutes à partir 2000 (les bornes sont systématiquement incluses).<br />
- Pour sélectionner toutes les promotions, laisser le vide.
- </td>
- </tr>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-<h1>Sondage :
- {if $survey_type == 'newsurvey'} créer un nouveau sondage
- {elseif $survey_type == 'new'} ajouter une question
- {elseif $survey_type == 'root'} modifier la description
- {else} modifier une question
- {/if}
-</h1>
-
-<form action="{$survey_formaction}" method="post">
- <input type="hidden" name="survey_action" value="{$survey_action}"/>
- <input type="hidden" name="survey_qid" value="{$survey_qid}"/>
- <table class="bicol" id="survey_form">
- {include file="survey/edit_$survey_type.tpl"}
- </table>
- <div class="center">
- <input type="submit" name="survey_submit" value="{if $survey_type == 'newsurvey'}Continuer{else}Valider{/if}"/>
- <input type="reset" name="survey_reset" value="Réinitialiser"/>
- <input type="submit" name="survey_cancel" value="Annuler"/>
- </div>
-</form>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
- {include file='survey/edit_question.tpl'}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
- {include file='survey/edit_question.tpl'}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-<h1>Sondages : erreur</h1>
-
-{if !is_null($survey_errors) && is_array($survey_errors)}
-<table class="bicol">
- <tr>
- <th colspan='2'>Une ou plusieurs erreurs sont survenues</th>
- </tr>
- {foreach from=$survey_errors item=survey_error}
- <tr class="{cycle values="impair,pair"}">
- <td>• {$survey_error.error}</td>
- <td><a href="survey/edit/question/{$survey_error.question}">corriger</a></td>
- </tr>
- {/foreach}
-</table>
-{elseif $survey_message neq ""}
- {$survey_message}
-{else}
-Une erreur inconnue est survenue dans l'édition de ce sondage. N'hésite pas à <a href='send_bug/{ $smarty.server.REQUEST_URI }'>signaler ce bug</a> s'il persiste.
-{/if}
-<br/>
-<a href="{$survey_link}">Retour</a>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
<h1>Sondages</h1>
-{* Survey::MODE_ALL equals 0. *}
-{assign var=SurveyMODE_ALL value=0}
-{if $survey_current->total() > 0 || $smarty.session.auth}
+{if $active->total() > 0}
<table class="bicol">
<tr>
- <th colspan="3">
+ <th>
Sondages en cours
</th>
</tr>
- {iterate item=s from=$survey_current}
- {if $smarty.session.auth || $s.mode == $SurveyMODE_ALL}
- <tr class="{cycle name=cs_cycle values="impair,pair"}">
- <td class="half" style="clear: both">
- <a href="survey/vote/{$s.id}">{$s.title}</a>
- {if $s.uid eq $smarty.session.user->id() || hasPerm('admin')}
- (<a href="survey/result/{$s.id}">résultats partiels</a>)
- {/if}
- </td>
- <td>
- {$s.end|date_format:"%x"}
- </td>
- <td>
- {$survey_modes[$s.mode]}
- </td>
- </tr>
- {assign var="has_cs" value="true"}
- {/if}
- {/iterate}
- <tr class="impair">
- <td colspan="3" style="text-align: right">
- {if $smarty.session.auth}<a href="survey/edit/new">{icon name=page_edit} Proposer un sondage</a>{/if}
- </td>
- </tr>
-</table>
-{/if}
-
-<br />
-
-<table class="bicol">
+ {iterate from=$active item=survey}
<tr>
- <th colspan="3">
- Anciens sondages
- </th>
- </tr>
- {iterate item=s from=$survey_old}
- {if $smarty.session.auth || $s.mode == $SurveyMODE_ALL}
- <tr class="{cycle name=os_cycle values="impair,pair"}">
- <td>
- <a href="survey/result/{$s.id}">
- {$s.title}
- </a>
- </td>
<td>
- {$s.end|date_format:"%x"}
- </td>
- <td>
- {$survey_modes[$s.mode]}
+ <a href="survey/vote/{$survey->shortname}">{$survey->title}</a>
</td>
</tr>
- {assign var="has_os" value="true"}
- {/if}
{/iterate}
- {if !$has_os}
- <tr>
- <td class="half">Aucun ancien sondage</td>
- </tr>
- {/if}
</table>
+{/if}
{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
{* *}
{**************************************************************************}
-{include file='survey/edit_radiotable.tpl'}
+<fieldset>
+ <legend>{$question->label}</legend>
+
+{foreach from=$question->children item=child}
+ {include file=$child->voteTemplate() question=$child}
+{/foreach}
+</fieldset>
{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
{* *}
{**************************************************************************}
-{include file='survey/edit_radio.tpl'}
+<div>
+ <div>{$question->label}</div>
+ <input type="text" name="qid[{$question->qid}]" value="" />
+</div>
{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-{if $survey_resultmode}
- <ul>
- {foreach item=sresult from=$squestion.result}
- <li>{$squestion.choices[$sresult.answer]} : {$sresult.count*100/$survey.votes|string_format:"%.1f"}% ({$sresult.count} votes)</li>
- {/foreach}
- </ul>
-{else}
- {assign var=sid value=$survey.id}
- {assign var=sqid value=$squestion.id}
- {if $survey_votemode}
- {html_checkboxes name="survey$sid[$sqid]" options=$squestion.choices separator='<br/>'}
- {else}
- {html_checkboxes name="survey$sid[$sqid]" options=$squestion.choices separator='<br/>' disabled='disabled'}
- {/if}
-{/if}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-<table class="bicol">
- <tr class="pair">
- <td></td>
- {foreach from=$squestion.choices item=schoice}
- <td>{$schoice}</td>
- {/foreach}
- </tr>
-{foreach from=$squestion.subquestions item=ssubq key=ssqid}
- <tr class="{cycle values="impair,pair"}">
- <td>{$ssubq}</td>
- {assign var=sid value=$survey.id}
- {assign var=sqid value=$squestion.id}
- {if $survey_resultmode}
- {foreach from=$squestion.choices item=schoice key=value}
- <td>
- {$squestion.result.$ssqid.$value*100/$survey.votes|string_format:"%.1f"}% ({$squestion.result.$ssqid.$value} votes)
- </td>
- {/foreach}
- {else}
- {foreach from=$squestion.choices item=schoice key=value}
- <td>
- <label><input type="checkbox" name="survey{$sid}[{$sqid}][{$ssqid}][]" value="{$value}" {if !$survey_votemode}disabled="disabled" {/if}/></label>
- </td>
- {/foreach}
- {/if}
- </tr>
-{/foreach}
-</table>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-{include file='survey/show_text.tpl'}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
- <h2>{$squestion.question}</h2>
-{if $squestion.comment != ''}
- {$squestion.comment|miniwiki|smarty:nodefaults}<br/>
-{/if}
-{assign var='squestion_type' value=$squestion.type}
-{include file="survey/show_$squestion_type.tpl"}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-{if $survey_resultmode}
- <ul>
- {foreach item=sresult from=$squestion.result}
- <li>{$squestion.choices[$sresult.answer]} : {$sresult.count*100/$survey.votes|string_format:"%.1f"}% ({$sresult.count} votes)</li>
- {/foreach}
- </ul>
-{else}
- {assign var=sid value=$survey.id}
- {assign var=sqid value=$squestion.id}
- {if $survey_votemode}
- {html_radios name="survey$sid[$sqid]" options=$squestion.choices separator='<br/>'}
- {else}
- {html_radios name="survey$sid[$sqid]" options=$squestion.choices separator='<br/>' disabled='disabled'}
- {/if}
-{/if}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-<table class="bicol">
- <tr class="pair">
- <td></td>
- {foreach from=$squestion.choices item=schoice}
- <td>{$schoice}</td>
- {/foreach}
- </tr>
-{foreach from=$squestion.subquestions item=ssubq key=ssqid}
- <tr class="{cycle values="impair,pair"}">
- <td>{$ssubq}</td>
- {assign var=sid value=$survey.id}
- {assign var=sqid value=$squestion.id}
- {if $survey_resultmode}
- {foreach from=$squestion.choices item=schoice key=value}
- <td>
- {$squestion.result.$ssqid.$value*100/$survey.votes|string_format:"%.1f"}% ({$squestion.result.$ssqid.$value} votes)
- </td>
- {/foreach}
- {else}
- {foreach from=$squestion.choices item=schoice key=value}
- <td>
- <label><input type="radio" name="survey{$sid}[{$sqid}][{$ssqid}]" value="{$value}" {if !$survey_votemode}disabled="disabled" {/if}/></label>
- </td>
- {/foreach}
- {/if}
- </tr>
-{/foreach}
-</table>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-<h1>Sondage : {$survey.title}</h1>
-<form action="survey/vote{if $survey_votemode}/{$survey.id}{/if}" method='post'>
-<table style="width: 100%">
- <tr>
- <td>
- <table class="bicol">
- <tr class="pair">
- <td colspan="2">{$survey.description|miniwiki|smarty:nodefaults}</td>
- </tr>
- <tr>
- <td class="titre">Fin du sondage :</td>
- <td>{$survey.end|date_format:"%x"}</td>
- </tr>
- <tr>
- <td class="titre">Type de sondage :</td>
- <td>{$survey_modes[$survey.mode]}</td>
- </tr>
- {if $survey.mode != Survey::MODE_ALL}
- <tr>
- <td class="titre">Promotions :</td>
- <td>
- {if $survey.promos eq "#"}
- <span class="erreur">erreur</span>
- {elseif $survey.promos eq ""}
- aucune restriction
- {else}
- {$survey.promos}
- {/if}
- </td>
- </tr>
- {/if}
- {if $survey_warning}
- <tr class="pair">
- <td colspan="2">{$survey_warning}</td>
- </tr>
- {/if}
- </table>
- {if $survey_resultmode}
- <p class="smaller">{$survey.votes} personnes ont répondu à ce sondage.<br />
- Récupérer <a href="survey/result/{$survey.id}/csv">l'ensemble des résultats</a> au format csv
- </p>
- {/if}
- </td>
- {if $survey_editmode && !$survey.valid}
- {assign var="survey_editallmode" value=true}
- {/if}
- {if $survey_editmode}
- <td style="width: 30%">
- <a href='survey/edit/question/root'>{icon name=page_edit alt="Modifier" title="Modifier la description"}</a>
- {if $survey_editallmode}<br /><a href='survey/edit/add/0'>{icon name=add title="Ajouter une question au début" alt="Ajouter"}</a>{/if}
- </td>
- {/if}
- </tr>
- {if is_array($survey.questions)}
- {foreach from=$survey.questions item=squestion}
- <tr>
- <td>
- {include file='survey/show_question.tpl' squestion=$squestion}
- </td>
- {if $survey_editallmode}
- <td class="smaller" style="width: 30%; vertical-align: middle">
- <a href='survey/edit/question/{$squestion.id}'>{icon name=page_edit title="Modifier cette question" alt="Modifier"}</a><br />
- <a href='survey/edit/del/{$squestion.id}'>{icon name=delete title="Supprimer cette question" alt="Supprimer"}</a><br />
- <a href='survey/edit/add/{$squestion.id+1}'>{icon name=add title="Ajouter une question après" alt="Ajouter"}</a>
- </td>
- {/if}
- </tr>
- {/foreach}
- {/if}
-</table>
-<p class="center">
- {if $smarty.session.survey_validate || ($survey_editmode && !$survey_updatemode)}
- <a href='survey/edit/valid'>
- {icon name=tick}
- Proposer ce sondage
- </a> |
- <a href='survey/edit/cancel'>
- {icon name=cross}
- Annuler totalement la création de ce sondage
- </a>
- {elseif $survey_adminmode}
- {if !$survey.valid}<a href="survey/admin/valid/{$survey.id}">Valider ce sondage</a> | {/if}
- <a href="survey/admin/edit/{$survey.id}">{icon name=tick} Modifier ce sondage</a> |
- <a href="survey/admin/del/{$survey.id}">{icon name=cross} Supprimer ce sondage</a> |
- <a href="survey/admin">Retour</a>
- {elseif $survey_votemode}
- <input type='submit' name='survey_submit' value='Voter'/>
- <input type='submit' name='survey_cancel' value='Annuler'/>
- {else}
- <a href="survey">Retour</a>
- {/if}
-</p>
-</form>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-{if $survey_resultmode}
- {if count($squestion.result) == 0}
- Aucune réponse n'a été donnée.
- {else}
- {if count($squestion.result) ==1}
- Une réponse donnée par une d{else}Quelques réponses données par l{/if}es personnes sondées :
- <ul>
- {assign var=nbhidden value=0}
- {foreach item=sresult from=$squestion.result}
- {if trim($result.answer)}
- <li>{$sresult.answer}</li>
- {else}
- {assign var=nbhidden value=$nbhidden+1}
- {/if}
- {/foreach}
- {if $nbhidden > 0}
- <li>{$nbhidden} réponse{if $nbhidden > 1}s{/if} vide{if $nbhidden > 1}s{/if}</li>
- {/if}
- </ul>
- {/if}
-{else}
- <input type="text" name="survey{$survey.id}[{$squestion.id}]" value="" size="50" maxlength="200" {if !$survey_votemode}disabled="disabled"{/if}/>
-{/if}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-
-{if $survey_resultmode}
- {if count($squestion.result) == 0}
- Aucune réponse n'a été donnée.
- {else}
- {if count($squestion.result) ==1}
- Une réponse donnée par une d{else}Quelques réponses données par l{/if}es personnes sondées :
- <ul>
- {assign var=nbhidden value=0}
- {foreach item=sresult from=$squestion.result}
- {if trim($result.answer)}
- <li>{$sresult.answer}</li>
- {else}
- {assign var=nbhidden value=$nbhidden+1}
- {/if}
- {/foreach}
- {if $nbhidden > 0}
- <li><em>{$nbhidden} réponse{if $nbhidden > 1}s{/if} vide{if $nbhidden > 1}s{/if}</em></li>
- {/if}
- </ul>
- {/if}
-{else}
- <textarea name="survey{$survey.id}[{$squestion.id}]" rows="5" cols="60" {if !$survey_votemode}disabled="disabled"{/if}></textarea>
-{/if}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+++ /dev/null
-{**************************************************************************}
-{* *}
-{* Copyright (C) 2003-2010 Polytechnique.org *}
-{* http://opensource.polytechnique.org/ *}
-{* *}
-{* This program is free software; you can redistribute it and/or modify *}
-{* it under the terms of the GNU General Public License as published by *}
-{* the Free Software Foundation; either version 2 of the License, or *}
-{* (at your option) any later version. *}
-{* *}
-{* This program is distributed in the hope that it will be useful, *}
-{* but WITHOUT ANY WARRANTY; without even the implied warranty of *}
-{* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *}
-{* GNU General Public License for more details. *}
-{* *}
-{* You should have received a copy of the GNU General Public License *}
-{* along with this program; if not, write to the Free Software *}
-{* Foundation, Inc., *}
-{* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *}
-{* *}
-{**************************************************************************}
-<h1>Sondages : succès</h1>
-
-{if $survey_message neq ""}
- {$survey_message}
-{else}
- Opération réussie
-{/if}
-<br/>
-<a href="{$survey_link}">Retour</a>
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
{* *}
{**************************************************************************}
- <tr>
- <td colspan='2'>
- Remplissez ici une description générale du sondage, puis cliquer sur "Continuer"
- pour passer à l'édition des questions.
- </td>
- </tr>
-{include file='survey/edit_root.tpl'}
+<h1>{$survey->title}</h1>
+
+<p>{$survey->description|miniwiki}</p>
+
+<div>
+<form action="survey/vote/{$survey->shortname}" method="post">
+ {foreach from=$survey->questions item=question}
+ {include file=$question->voteTemplate() question=$question}
+ {/foreach}
+
+ <div class="center">
+ {xsrf_token_field}
+ <input type="submit" name="vote" value="Enregister mon vote" />
+ </div>
+</form>
+</div>
{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
<li><salutation>, <prenom>, <nom>, <montant> et <comment> seront <strong>automatiquement</strong> remplacés par les informations adaptées.</li>
<li><a href="wiki_help" class="popup3">{icon name=information} Tu peux utiliser une syntaxe wiki pour formatter ton texte.</a></li>
</ul>
- {javascript name=ajax}
<div id="pay_preview" style="display: none">
<strong>Aperçu du texte :</strong>
<hr />
</div>
<div class="center">
- {javascript name=ajax}
<div id="preview_descr" style="display: none; text-align: justify"></div>
<br />
<a href="wiki_help" class="popup3">
document.getElementById('xprenom').style.display = state;
document.getElementById('xpromo').style.display = state;
document.getElementById('xsearch').style.display = state;
- Ajax.update_html('search_result',
- '{/literal}{$platal->ns}{literal}member/new/ajax?login=' + document.getElementById('email').value);
+ $('#search_result').updateHtml('{/literal}{$platal->ns}{literal}member/new/ajax?login='
+ + $('#email').val());
}
var nom;
var nom = document.getElementById('nom').value;
var prenom = document.getElementById('prenom').value;
var promo = document.getElementById('promo').value;
- Ajax.update_html('search_result',
- '{/literal}{$platal->ns}{literal}member/new/ajax?prenom=' + prenom + '&nom=' + nom + '&promo=' + promo);
+ $('#search_result').updateHtml('{/literal}{$platal->ns}{literal}member/new/ajax?prenom=' + prenom + '&nom=' + nom + '&promo=' + promo);
}
{/literal}
//]]></script>
--- /dev/null
+DROP TABLE IF EXISTS email_source_account;
+DROP TABLE IF EXISTS email_source_other;
+DROP TABLE IF EXISTS homonyms_list;
+DROP TABLE IF EXISTS email_redirect_account;
+DROP TABLE IF EXISTS email_redirect_other;
+DROP TABLE IF EXISTS email_virtual;
+DROP TABLE IF EXISTS email_virtual_domains;
+
+CREATE TABLE email_source_account (
+ email VARCHAR(255) NOT NULL PRIMARY KEY,
+ uid INT(11) UNSIGNED NOT NULL,
+ type ENUM('forlife','alias') NOT NULL DEFAULT 'forlife',
+ flags SET('bestalias','usage','marital') NOT NULL DEFAULT '',
+ expire DATE DEFAULT NULL,
+ KEY (uid),
+ KEY (type),
+ FOREIGN KEY (uid) REFERENCES accounts (uid) ON UPDATE CASCADE ON DELETE CASCADE
+) ENGINE=InnoDB, CHARSET=utf8 ;
+
+CREATE TABLE email_source_other (
+ email VARCHAR(255) NOT NULL PRIMARY KEY,
+ hrmid VARCHAR(255) NOT NULL,
+ type ENUM('homonym','ax','honeypot'),
+ expire DATE NOT NULL DEFAULT '0000-00-00'
+) ENGINE=InnoDB, CHARSET=utf8 ;
+
+CREATE TABLE homonyms_list (
+ hrmid VARCHAR(255) NOT NULL,
+ uid INT(11) UNSIGNED NOT NULL,
+ KEY(hrmid)
+) ENGINE=InnoDB, CHARSET=utf8 ;
+
+CREATE TABLE email_redirect_account (
+ uid INT(11) UNSIGNED NOT NULL,
+ redirect VARCHAR(255) NOT NULL DEFAULT '',
+ rewrite VARCHAR(255) NOT NULL DEFAULT '',
+ type ENUM('smtp','googleapps','imap','homonym') NOT NULL DEFAULT 'smtp',
+ action ENUM('default',
+ 'drop_spams',
+ 'let_spams',
+ 'tag_and_drop_spams',
+ 'tag_spams',
+ 'imap_and_bounce',
+ 'homonym')
+ NOT NULL DEFAULT 'default',
+ broken DATE NOT NULL DEFAULT '0000-00-00',
+ broken_level TINYINT(1) NOT NULL DEFAULT 0,
+ last DATE NOT NULL DEFAULT '0000-00-00',
+ flags ENUM('active','broken','disabled') NOT NULL,
+ hash VARCHAR(32) DEFAULT NULL,
+ allow_rewrite TINYINT(1) DEFAULT 0,
+ KEY (uid),
+ KEY (redirect)
+) ENGINE=InnoDB, CHARSET=utf8 ;
+
+CREATE TABLE email_redirect_other (
+ hrmid VARCHAR(255) NOT NULL DEFAULT '',
+ redirect VARCHAR(255) NOT NULL DEFAULT '',
+ type ENUM('smtp','googleapps','imap','homonym') NOT NULL DEFAULT 'smtp',
+ action ENUM('default',
+ 'drop_spams',
+ 'let_spams',
+ 'tag_and_drop_spams',
+ 'tag_spams',
+ 'imap_and_bounce',
+ 'homonym')
+ NOT NULL DEFAULT 'default',
+ KEY (hrmid),
+ KEY (redirect)
+) ENGINE=InnoDB, CHARSET=utf8 ;
+
+CREATE TABLE email_virtual (
+ email VARCHAR(255) NOT NULL,
+ redirect VARCHAR(255) NOT NULL,
+ type ENUM('user','list','domain','event','admin','partner'),
+ expire DATE NOT NULL DEFAULT '0000-00-00',
+ KEY (email)
+) ENGINE=InnoDB, CHARSET=utf8 ;
+
+CREATE TABLE email_virtual_domains (
+ domain VARCHAR(255) NOT NULL PRIMARY KEY
+) ENGINE=InnoDB, CHARSET=utf8;
+
+-- vim:set syntax=mysql:
--- /dev/null
+INSERT INTO email_source_account (uid,email,type,flags,expire)
+ SELECT a.uid,CONCAT(a.alias,'@polytechnique.org'),IF(a.type='a_vie','forlife','alias'),REPLACE(a.flags,'epouse','marital'),a.expire
+ FROM aliases AS a
+ WHERE a.type = 'a_vie'
+ OR a.type = 'alias';
+INSERT INTO email_source_account (uid,email,type,flags,expire)
+ SELECT a.uid,CONCAT(a.alias,'@m4x.org'),IF(a.type='a_vie','forlife','alias'),REPLACE(a.flags,'epouse','marital'),a.expire
+ FROM aliases AS a
+ WHERE a.type = 'a_vie'
+ OR a.type = 'alias';
+INSERT INTO email_source_account (uid,email,type,flags,expire)
+ SELECT a.uid,CONCAT(a.alias,'@m4x.net'),IF(a.type='a_vie','forlife','alias'),REPLACE(a.flags,'epouse','marital'),a.expire
+ FROM aliases AS a
+ WHERE a.type = 'a_vie'
+ OR a.type = 'alias';
+INSERT INTO email_source_account (uid,email,type)
+ SELECT a.uid,v.alias,'alias'
+ FROM virtual AS v
+ LEFT JOIN virtual_redirect AS vr ON (v.vid=vr.vid)
+ LEFT JOIN accounts AS a ON ( a.hruid=LEFT(vr.redirect,LOCATE('@',vr.redirect)-1) )
+ WHERE v.type='user'
+ AND v.alias LIKE "%@melix.net"
+ AND a.uid IS NOT NULL;
+INSERT INTO email_source_account (uid,email,type)
+ SELECT a.uid,REPLACE(v.alias,'@melix.net','@melix.org'),'alias'
+ FROM virtual AS v
+ LEFT JOIN virtual_redirect AS vr ON (v.vid=vr.vid)
+ LEFT JOIN accounts AS a ON ( a.hruid=LEFT(vr.redirect,LOCATE('@',vr.redirect)-1) )
+ WHERE v.type='user'
+ AND v.alias LIKE "%@melix.net"
+ AND a.uid IS NOT NULL;
+
+INSERT INTO email_source_other (hrmid,email,type)
+ SELECT CONCAT(CONCAT('h.',a.alias),'.polytechnique.org'),
+ CONCAT(a.alias,'@polytechnique.org'),'homonym'
+ FROM aliases AS a
+ WHERE a.type = 'homonyme'
+ GROUP BY (a.alias);
+INSERT INTO email_source_other (hrmid,email,type)
+ SELECT CONCAT(CONCAT('h.',a.alias),'.polytechnique.org'),
+ CONCAT(a.alias,'@m4x.org'),'homonym'
+ FROM aliases AS a
+ WHERE a.type = 'homonyme'
+ GROUP BY (a.alias);
+INSERT INTO email_source_other (hrmid,email,type)
+ SELECT CONCAT(CONCAT('h.',a.alias),'.polytechnique.org'),
+ CONCAT(a.alias,'@m4x.net'),'homonym'
+ FROM aliases AS a
+ WHERE a.type = 'homonyme'
+ GROUP BY (a.alias);
+
+INSERT INTO homonyms_list (hrmid,uid)
+ SELECT CONCAT(CONCAT('h.',a.alias),'.polytechnique.org'), h.uid
+ FROM homonyms AS h
+ INNER JOIN aliases AS a ON (a.uid=h.homonyme_id)
+ WHERE a.type = 'homonyme';
+
+INSERT INTO email_redirect_account (uid,redirect,rewrite,type,action,
+ broken,broken_level,last,flags,hash,allow_rewrite)
+ SELECT a.uid,e.email,e.rewrite,'smtp',ef.email,
+ e.panne,e.panne_level,e.last,IF(e.flags='','disabled',IF(e.flags='disable','disabled',IF(e.flags='panne','broken',e.flags))),e.hash,e.allow_rewrite
+ FROM emails AS e
+ LEFT JOIN emails AS ef ON (e.uid=ef.uid)
+ LEFT JOIN accounts AS a ON (e.uid=a.uid)
+ WHERE e.flags != 'filter'
+ AND ef.flags = 'filter';
+INSERT INTO email_redirect_account (uid,redirect,type,action,flags)
+ SELECT a.uid,CONCAT(a.hruid,"@g.polytechnique.org"),'googleapps',ef.email,'active'
+ FROM email_options AS eo
+ LEFT JOIN accounts AS a ON (a.uid=eo.uid)
+ LEFT JOIN emails AS ef ON (eo.uid=ef.uid)
+ WHERE FIND_IN_SET('googleapps',eo.storage)
+ AND ef.flags="filter";
+INSERT INTO email_redirect_account (uid,redirect,type,action,flags)
+ SELECT a.uid,CONCAT(a.hruid,"@imap.polytechnique.org"),'imap','let_spams','active'
+ FROM email_options AS eo
+ LEFT JOIN accounts AS a ON (a.uid=eo.uid)
+ WHERE FIND_IN_SET('imap',eo.storage);
+
+INSERT INTO email_redirect_other (hrmid,type,action)
+ SELECT eso.hrmid,'homonym','homonym'
+ FROM email_source_other AS eso
+ WHERE eso.type = 'homonym'
+ GROUP BY (eso.hrmid);
+
+INSERT INTO email_virtual (email,redirect,type)
+ SELECT v.alias,vr.redirect,IF(v.type='dom','domain',IF(v.type='evt','event',v.type))
+ FROM virtual AS v
+ LEFT JOIN virtual_redirect AS vr ON (vr.vid=v.vid)
+ WHERE v.alias NOT LIKE "%@melix.net"
+ AND vr.vid IS NOT NULL
+ AND v.alias != '@melix.org';
+INSERT INTO email_virtual (email,redirect,type)
+ SELECT CONCAT(a.alias,"@polytechnique.org"),
+ CONCAT(
+ 'polytechnique.org_',
+ REPLACE(
+ REPLACE(
+ REPLACE(
+ CONCAT(a.alias, '+post@listes.polytechnique.org'),
+ '-admin+post', '+admin'
+ ),
+ '-owner+post', '+owner'
+ ),
+ '-bounces+post', '+bounces'
+ )
+ ),
+ 'list'
+ FROM aliases AS a
+ WHERE type='liste';
+INSERT INTO email_virtual (email,redirect,type)
+ SELECT CONCAT(a.alias,"@m4x.org"),
+ CONCAT(
+ 'polytechnique.org_',
+ REPLACE(
+ REPLACE(
+ REPLACE(
+ CONCAT(a.alias, '+post@listes.polytechnique.org'),
+ '-admin+post', '+admin'
+ ),
+ '-owner+post', '+owner'
+ ),
+ '-bounces+post', '+bounces'
+ )
+ ),
+ 'list'
+ FROM aliases AS a
+ WHERE type='liste';
+INSERT INTO email_virtual (email,redirect,type)
+ SELECT CONCAT(a.alias,"@m4x.net"),
+ CONCAT(
+ 'polytechnique.org_',
+ REPLACE(
+ REPLACE(
+ REPLACE(
+ CONCAT(a.alias, '+post@listes.polytechnique.org'),
+ '-admin+post', '+admin'
+ ),
+ '-owner+post', '+owner'
+ ),
+ '-bounces+post', '+bounces'
+ )
+ ),
+ 'list'
+ FROM aliases AS a
+ WHERE type='liste';
+INSERT INTO email_virtual (email,redirect,type)
+ SELECT vr.redirect,v.alias,'user'
+ FROM virtual AS v
+ LEFT JOIN virtual_redirect AS vr ON (v.vid=vr.vid)
+ LEFT JOIN accounts AS a ON ( a.hruid=LEFT(vr.redirect,LOCATE('@',vr.redirect)-1) )
+ WHERE v.type='user'
+ AND v.alias LIKE "%@melix.net"
+ AND vr.vid IS NOT NULL
+ AND a.uid IS NULL;
+INSERT INTO email_virtual (email,redirect,type)
+ SELECT vr.redirect,REPLACE(v.alias,'@melix.net','@melix.org'),'user'
+ FROM virtual AS v
+ LEFT JOIN virtual_redirect AS vr ON (v.vid=vr.vid)
+ LEFT JOIN accounts AS a ON ( a.hruid=LEFT(vr.redirect,LOCATE('@',vr.redirect)-1) )
+ WHERE v.type='user'
+ AND v.alias LIKE "%@melix.net"
+ AND vr.vid IS NOT NULL
+ AND a.uid IS NULL;
+
+-- Note: There are some adresses on virtual that have no match on the virtual_redirect.
+-- The adresses in this situation are dropped.
+
+INSERT INTO email_virtual_domains (domain)
+ VALUES ("polytechnique.org"),
+ ("m4x.org"),
+ ("m4x.net");
+INSERT INTO email_virtual_domains (domain)
+ SELECT domain
+ FROM virtual_domains;
+
+-- From aliases file
+INSERT INTO email_virtual (email,redirect,type) VALUES
+ ("otrs.platal@polytechnique.org","otrs@svoboda.polytechnique.org","admin"),
+ ("otrs.platal@m4x.org","otrs.platal@polytechnique.org","admin"),
+ ("otrs.platal@m4x.net","otrs.platal@polytechnique.org","admin"),
+ ("validation@polytechnique.org","hotliners@staff.polytechnique.org","admin"),
+ ("validation@m4x.org","validation@polytechnique.org","admin"),
+ ("validation@m4x.net","validation@polytechnique.org","admin"),
+ ("listes+admin@polytechnique.org","br@staff.polytechnique.org","admin"),
+ ("listes+admin@m4x.org","listes+admin@polytechnique.org","admin"),
+ ("listes+admin@m4x.net","listes+admin@polytechnique.org","admin"),
+ ("listes@polytechnique.org","otrs.platal+listes@polytechnique.org","admin"),
+ ("listes@m4x.org","listes@polytechnique.org","admin"),
+ ("listes@m4x.net","listes@polytechnique.org","admin"),
+ ("gld@polytechnique.org","listes@polytechnique.org","admin"),
+ ("gld@m4x.org","gld@polytechnique.org","admin"),
+ ("gld@m4x.net","gld@polytechnique.org","admin"),
+ ("support@polytechnique.org","otrs.platal+support@polytechnique.org","admin"),
+ ("support@m4x.org","support@polytechnique.org","admin"),
+ ("support@m4x.net","support@polytechnique.org","admin"),
+ ("contact@polytechnique.org","otrs.platal+contact@polytechnique.org","admin"),
+ ("contact@m4x.org","contact@polytechnique.org","admin"),
+ ("contact@m4x.net","contact@polytechnique.org","admin"),
+ ("register@polytechnique.org","otrs.platal+register@polytechnique.org","admin"),
+ ("register@m4x.org","register@polytechnique.org","admin"),
+ ("register@m4x.net","register@polytechnique.org","admin"),
+ ("info@polytechnique.org","otrs.platal+info@polytechnique.org","admin"),
+ ("info@m4x.org","info@polytechnique.org","admin"),
+ ("info@m4x.net","info@polytechnique.org","admin"),
+ ("bug@polytechnique.org","otrs.platal+bug@polytechnique.org","admin"),
+ ("bug@m4x.org","bug@polytechnique.org","admin"),
+ ("bug@m4x.net","bug@polytechnique.org","admin"),
+ ("resetpass@polytechnique.org","otrs.platal+resetpass@polytechnique.org","admin"),
+ ("resetpass@m4x.org","resetpass@polytechnique.org","admin"),
+ ("resetpass@m4x.net","resetpass@polytechnique.org","admin"),
+ ("association@polytechnique.org","otrs.platal+association@polytechnique.org","admin"),
+ ("association@m4x.org","association@polytechnique.org","admin"),
+ ("association@m4x.net","association@polytechnique.org","admin"),
+ ("x-org@polytechnique.org","association@polytechnique.org","admin"),
+ ("x-org@m4x.org","x-org@polytechnique.org","admin"),
+ ("x-org@m4x.net","x-org@polytechnique.org","admin"),
+ ("manageurs@polytechnique.org","otrs@support.manageurs.com","partner"),
+ ("manageurs@m4x.org","manageurs@polytechnique.org","partner"),
+ ("manageurs@m4x.net","manageurs@polytechnique.org","partner"),
+ ("fondation@polytechnique.org","fondation@fondationx.org","partner"),
+ ("fondation@m4x.org","fondation@polytechnique.org","partner"),
+ ("fondation@m4x.net","fondation@polytechnique.org","partner"),
+ ("ax@polytechnique.org","ax@wanadoo.fr","partner"),
+ ("ax@m4x.org","ax@polytechnique.org","partner"),
+ ("ax@m4x.net","ax@polytechnique.org","partner"),
+ ("annuaire-ax@polytechnique.org","annuaire-ax@wanadoo.fr","partner"),
+ ("annuaire-ax@m4x.org","annuaire-ax@polytechnique.org","partner"),
+ ("annuaire-ax@m4x.net","annuaire-ax@polytechnique.org","partner"),
+ ("ax-bdc@polytechnique.org","ax-bdc@wanadoo.fr","partner"),
+ ("ax-bdc@m4x.org","ax-bdc@polytechnique.org","partner"),
+ ("ax-bdc@m4x.net","ax-bdc@polytechnique.org","partner"),
+ ("jaune@polytechnique.org","null@hruid.polytechnique.org","partner"),
+ ("jaune@m4x.org","jaune@polytechnique.org","partner"),
+ ("jaune@m4x.net","jaune@polytechnique.org","partner"),
+ ("jaune+rouge@polytechnique.org","jaune_rouge@wanadoo.fr","partner"),
+ ("jaune+rouge@m4x.org","jaune+rouge@polytechnique.org","partner"),
+ ("jaune+rouge@m4x.net","jaune+rouge@polytechnique.org","partner"),
+ ("xcourseaularge@polytechnique.org","info@xcourseaularge.polytechnique.org","partner"),
+ ("xcourseaularge@m4x.org","xcourseaularge@polytechnique.org","partner"),
+ ("xcourseaularge@m4x.net","xcourseaularge@polytechnique.org","partner"),
+ ("xim@polytechnique.org","membres@x-internet.polytechnique.org","partner"),
+ ("xim@m4x.org","xim@polytechnique.org","partner"),
+ ("xim@m4x.net","xim@polytechnique.org","partner"),
+ ("x-consult@polytechnique.org","info@x-consult.polytechnique.org","partner"),
+ ("x-consult@m4x.org","x-consult@polytechnique.org","partner"),
+ ("x-consult@m4x.net","x-consult@polytechnique.org","partner"),
+ ("xmcb@polytechnique.org","xmcb@x-consult.polytechnique.org","partner"),
+ ("xmcb@m4x.org","xmcb@polytechnique.org","partner"),
+ ("xmcb@m4x.net","xmcb@polytechnique.org","partner"),
+ ("x-maroc@polytechnique.org","allam@mtpnet.gov.ma","partner"),
+ ("x-maroc@m4x.org","x-maroc@polytechnique.org","partner"),
+ ("x-maroc@m4x.net","x-maroc@polytechnique.org","partner"),
+ ("x-musique@polytechnique.org","xmusique@free.fr","partner"),
+ ("x-musique@m4x.org","x-musique@polytechnique.org","partner"),
+ ("x-musique@m4x.net","x-musique@polytechnique.org","partner"),
+ ("x-resistance@polytechnique.org","info@xresistance.org","partner"),
+ ("x-resistance@m4x.org","x-resistance@polytechnique.org","partner"),
+ ("x-resistance@m4x.net","x-resistance@polytechnique.org","partner"),
+ ("x-israel@polytechnique.org","info@x-israel.polytechnique.org","partner"),
+ ("x-israel@m4x.org","x-israel@polytechnique.org","partner"),
+ ("x-israel@m4x.net","x-israel@polytechnique.org","partner"),
+ ("gpx@polytechnique.org","g.p.x@infonie.fr","partner"),
+ ("gpx@m4x.org","gpx@polytechnique.org","partner"),
+ ("gpx@m4x.net","gpx@polytechnique.org","partner"),
+ ("g.p.x@polytechnique.org","gpx@polytechnique.org","partner"),
+ ("g.p.x@m4x.org","g.p.x@polytechnique.org","partner"),
+ ("g.p.x@m4x.net","g.p.x@polytechnique.org","partner"),
+ ("pointgamma@polytechnique.org","gamma@frankiz.polytechnique.fr","partner"),
+ ("pointgamma@m4x.org","pointgamma@polytechnique.org","partner"),
+ ("pointgamma@m4x.net","pointgamma@polytechnique.org","partner"),
+ ("xmpentrepreneur@polytechnique.org","xmp.entrepreneur@gmail.com","partner"),
+ ("xmpentrepreneur@m4x.org","xmpentrepreneur@polytechnique.org","partner"),
+ ("xmpentrepreneur@m4x.net","xmpentrepreneur@polytechnique.org","partner"),
+ ("xmp-entrepreneur@polytechnique.org","xmp.entrepreneur@gmail.com","partner"),
+ ("xmp-entrepreneur@m4x.org","xmp-entrepreneur@polytechnique.org","partner"),
+ ("xmp-entrepreneur@m4x.net","xmp-entrepreneur@polytechnique.org","partner"),
+ ("xmpangels@polytechnique.org","xmpangels@xmp-ba.m4x.org","partner"),
+ ("xmpangels@m4x.org","xmpangels@polytechnique.org","partner"),
+ ("xmpangels@m4x.net","xmpangels@polytechnique.org","partner"),
+ ("xmp-angels@polytechnique.org","xmpangels@xmp-ba.m4x.org","partner"),
+ ("xmp-angels@m4x.org","xmp-angels@polytechnique.org","partner"),
+ ("xmp-angels@m4x.net","xmp-angels@polytechnique.org","partner"),
+ ("relex@polytechnique.org","relex@staff.polytechnique.org","admin"),
+ ("relex@m4x.org","relex@polytechnique.org","admin"),
+ ("relex@m4x.net","relex@polytechnique.org","admin"),
+ ("tresorier@polytechnique.org","tresorier@staff.polytechnique.org","admin"),
+ ("tresorier@m4x.org","tresorier@polytechnique.org","admin"),
+ ("tresorier@m4x.net","tresorier@polytechnique.org","admin"),
+ ("aaege-sso@polytechnique.org","aaege-sso@staff.polytechnique.org","admin"),
+ ("aaege-sso@m4x.org","aaege-sso@polytechnique.org","admin"),
+ ("aaege-sso@m4x.net","aaege-sso@polytechnique.org","admin"),
+ ("innovation@polytechnique.org","innovation@staff.polytechnique.org","admin"),
+ ("innovation@m4x.org","innovation@polytechnique.org","admin"),
+ ("innovation@m4x.net","innovation@polytechnique.org","admin"),
+ ("groupes@polytechnique.org","groupes@staff.polytechnique.org","admin"),
+ ("groupes@m4x.org","groupes@polytechnique.org","admin"),
+ ("groupes@m4x.net","groupes@polytechnique.org","admin"),
+ ("br@polytechnique.org","br@staff.polytechnique.org","admin"),
+ ("br@m4x.org","br@polytechnique.org","admin"),
+ ("br@m4x.net","br@polytechnique.org","admin"),
+ ("ca@polytechnique.org","ca@staff.polytechnique.org","admin"),
+ ("ca@m4x.org","ca@polytechnique.org","admin"),
+ ("ca@m4x.net","ca@polytechnique.org","admin"),
+ ("personnel@polytechnique.org","br@staff.polytechnique.org","admin"),
+ ("personnel@m4x.org","personnel@polytechnique.org","admin"),
+ ("personnel@m4x.net","personnel@polytechnique.org","admin"),
+ ("cil@polytechnique.org","cil@staff.polytechnique.org","admin"),
+ ("cil@m4x.org","cil@polytechnique.org","admin"),
+ ("cil@m4x.net","cil@polytechnique.org","admin"),
+ ("opensource@polytechnique.org","contact@polytechnique.org","admin"),
+ ("opensource@m4x.org","opensource@polytechnique.org","admin"),
+ ("opensource@m4x.net","opensource@polytechnique.org","admin"),
+ ("forums@polytechnique.org","forums@staff.m4x.org","admin"),
+ ("forums@m4x.org","forums@polytechnique.org","admin"),
+ ("forums@m4x.net","forums@polytechnique.org","admin"),
+ ("telepaiement@polytechnique.org","telepaiement@staff.m4x.org","admin"),
+ ("telepaiement@m4x.org","telepaiement@polytechnique.org","admin"),
+ ("telepaiement@m4x.net","telepaiement@polytechnique.org","admin"),
+ ("hotliners@polytechnique.org","hotliners@staff.m4x.org","admin"),
+ ("hotliners@m4x.org","hotliners@polytechnique.org","admin"),
+ ("hotliners@m4x.net","hotliners@polytechnique.org","admin"),
+ ("kes@polytechnique.org","kes@frankiz.polytechnique.fr","partner"),
+ ("kes@m4x.org","kes@polytechnique.org","partner"),
+ ("kes@m4x.net","kes@polytechnique.org","partner"),
+ ("kes1999@polytechnique.org","cariokes@polytechnique.org","partner"),
+ ("kes1999@m4x.org","kes1999@polytechnique.org","partner"),
+ ("kes1999@m4x.net","kes1999@polytechnique.org","partner"),
+ ("kes2000@polytechnique.org","kestinpowers@polytechnique.org","partner"),
+ ("kes2000@m4x.org","kes2000@polytechnique.org","partner"),
+ ("kes2000@m4x.net","kes2000@polytechnique.org","partner");
+
+INSERT INTO email_source_other (hrmid,email,type) VALUES
+ ("ax.test.polytechnique.org","AX-test@polytechnique.org","ax"),
+ ("ax.test.polytechnique.org","AX-test@m4x.org","ax"),
+ ("ax.test.polytechnique.org","AX-test@m4x.net","ax"),
+ ("ax.nicolas.zarpas.polytechnique.org","AX-nicolas.zarpas@polytechnique.org","ax"),
+ ("ax.nicolas.zarpas.polytechnique.org","AX-nicolas.zarpas@m4x.org","ax"),
+ ("ax.nicolas.zarpas.polytechnique.org","AX-nicolas.zarpas@m4x.net","ax"),
+ ("ax.carrieres.polytechnique.org","AX-carrieres@polytechnique.org","ax"),
+ ("ax.carrieres.polytechnique.org","AX-carrieres@m4x.org","ax"),
+ ("ax.carrieres.polytechnique.org","AX-carrieres@m4x.net","ax"),
+ ("ax.info1.polytechnique.org","AX-info1@polytechnique.org","ax"),
+ ("ax.info1.polytechnique.org","AX-info1@m4x.org","ax"),
+ ("ax.info1.polytechnique.org","AX-info1@m4x.net","ax"),
+ ("ax.info2.polytechnique.org","AX-info2@polytechnique.org","ax"),
+ ("ax.info2.polytechnique.org","AX-info2@m4x.org","ax"),
+ ("ax.info2.polytechnique.org","AX-info2@m4x.net","ax"),
+ ("ax.bal.polytechnique.org","AX-bal@polytechnique.org","ax"),
+ ("ax.bal.polytechnique.org","AX-bal@m4x.org","ax"),
+ ("ax.bal.polytechnique.org","AX-bal@m4x.net","ax"),
+ ("ax.annuaire.polytechnique.org","AX-annuaire@polytechnique.org","ax"),
+ ("ax.annuaire.polytechnique.org","AX-annuaire@m4x.org","ax"),
+ ("ax.annuaire.polytechnique.org","AX-annuaire@m4x.net","ax"),
+ ("ax.jaune-rouge.polytechnique.org","AX-jaune-rouge@polytechnique.org","ax"),
+ ("ax.jaune-rouge.polytechnique.org","AX-jaune-rouge@m4x.org","ax"),
+ ("ax.jaune-rouge.polytechnique.org","AX-jaune-rouge@m4x.net","ax"),
+ ("honey.jean-pierre.bilah.1980.polytechnique.org","jean-pierre.bilah.1980@polytechnique.org","honeypot"),
+ ("honey.jean-pierre.bilah.1980.polytechnique.org","jean-pierre.bilah.1980@m4x.org","honeypot"),
+ ("honey.jean-pierre.bilah.1980.polytechnique.org","jean-pierre.bilah.1980@m4x.net","honeypot"),
+ ("honey.jean-pierre.bilah.1980.polytechnique.org","jean-pierre.blah.1980@polytechnique.org","honeypot"),
+ ("honey.jean-pierre.bilah.1980.polytechnique.org","jean-pierre.blah.1980@m4x.org","honeypot"),
+ ("honey.jean-pierre.bilah.1980.polytechnique.org","jean-pierre.blah.1980@m4x.net","honeypot");
+
+INSERT INTO email_redirect_other (hrmid,redirect,type,action) VALUES
+ ("ax.nicolas.zarpas.polytechnique.org","nicolas.zarpas-ax@wanadoo.fr","smtp","tag_spams"),
+ ("ax.carrieres.polytechnique.org","manuela.brasseur-bdc@wanadoo.fr","smtp","tag_spams"),
+ ("ax.info1.polytechnique.org","sylvie.clairefond-ax@wanadoo.fr","smtp","tag_spams"),
+ ("ax.info2.polytechnique.org","catherine.perot-ax@wanadoo.fr","smtp","tag_spams"),
+ ("ax.bal.polytechnique.org","baldelx-ax@wanadoo.fr","smtp","tag_spams"),
+ ("ax.annuaire.polytechnique.org","annuaire-ax@wanadoo.fr","smtp","tag_spams"),
+ ("ax.jaune-rouge.polytechnique.org","jaune_rouge@wanadoo.fr","smtp","tag_spams"),
+ ("honey.jean-pierre.bilah.1980.polytechnique.org","jean-pierre.bilah.1980.mbox@murphy.m4x.org","smtp","let_spams"),
+ ("honey.jean-pierre.bilah.1980.polytechnique.org","raphael.barrois.2006@polytechnique.org","smtp","let_spams");
+
+-- Drop renamed list
+DELETE FROM email_virtual WHERE email LIKE "tech-email%@polytechnique.org";
+DELETE FROM email_virtual WHERE email LIKE "tech-email%@m4x.org";
+DELETE FROM email_virtual WHERE email LIKE "tech-email%@m4x.net";
+
+-- Imap and bounce
+UPDATE email_redirect_account AS e,
+ (SELECT IF( SUM(IF(type!='imap',1,0))=0, 'imap_only', 'normal' ) AS status, uid
+ FROM email_redirect_account
+ WHERE flags = 'active'
+ GROUP BY uid) AS sub
+ SET e.action='imap_and_bounce'
+ WHERE sub.status='imap_only'
+ AND sub.uid = e.uid
+ AND type='imap';
+
+-- vim:set syntax=mysql:
--- /dev/null
+DROP TABLE aliases;
+DROP TABLE virtual;
+DROP TABLE virtual_redirect;
+DROP TABLE homonyms;
+DROP TABLE emails;
+DROP TABLE email_options;
+DROP TABLE domain;
+
+-- vim:set syntax=mysql:
--- /dev/null
+#RENAME TABLE surveys TO old_surveys,
+# survey_answers TO old_survey_answers,
+# survey_votes TO old_survey_votes;
+
+DROP TABLE IF EXISTS survey_vote_answers;
+DROP TABLE IF EXISTS survey_voters;
+DROP TABLE IF EXISTS survey_votes;
+DROP TABLE IF EXISTS survey_questions;
+DROP TABLE IF EXISTS surveys;
+
+CREATE TABLE surveys (
+ id INT(11) UNSIGNED NOT NULL auto_increment,
+ uid INT(11) UNSIGNED NOT NULL,
+ shortname VARCHAR(32) NOT NULL,
+ title VARCHAR(255) NOT NULL,
+ description TEXT NOT NULL,
+ begin DATE NOT NULL,
+ end DATE NOT NULL,
+
+ voters TEXT DEFAULT NULL COMMENT "Filter users who can vote",
+ viewers TEXT DEFAULT NULL COMMENT "Filter users who can see the results",
+
+ flags SET('validated', 'anonymous'),
+
+ PRIMARY KEY id (id),
+ UNIQUE KEY shortname (shortname),
+ FOREIGN KEY (uid) REFERENCES accounts (uid)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE
+) ENGINE=InnoDB, CHARSET=utf8, COMMENT="Describe a survey";
+
+CREATE TABLE survey_questions (
+ sid INT(11) UNSIGNED NOT NULL,
+ qid INT(11) UNSIGNED NOT NULL,
+ parent INT(11) UNSIGNED DEFAULT NULL COMMENT "Id of the parent question",
+
+ type VARCHAR(32) NOT NULL, -- XXX: Use an enum of possible types?
+ label TEXT DEFAULT NULL,
+ parameters TEXT DEFAULT NULL COMMENT "Parameters of the question",
+ flags SET('multiple', 'mandatory', 'noanswer') NOT NULL DEFAULT '',
+
+ PRIMARY KEY id (sid, qid),
+ FOREIGN KEY (sid) REFERENCES surveys (id)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE
+) ENGINE=InnoDB, CHARSET=utf8, COMMENT="Describe the questions of the surveys";
+
+CREATE TABLE survey_votes (
+ vid INT(11) UNSIGNED NOT NULL auto_increment,
+ sid INT(11) UNSIGNED NOT NULL,
+
+ PRIMARY KEY vid (vid),
+ FOREIGN KEY (sid) REFERENCES surveys (id)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE
+) ENGINE=InnoDB, CHARSET=utf8, COMMENT="Identify unique votes";
+
+CREATE TABLE survey_voters (
+ sid INT(11) UNSIGNED NOT NULL,
+ uid INT(11) UNSIGNED NOT NULL,
+ vid INT(11) UNSIGNED DEFAULT NULL, -- NULL for anonymous votes
+
+ PRIMARY KEY id (sid, uid),
+ FOREIGN KEY (uid) REFERENCES accounts (uid)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE,
+ FOREIGN KEY (sid) REFERENCES surveys (id)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE
+) ENGINE=InnoDB, CHARSET=utf8, COMMENT="List voters";
+
+CREATE TABLE survey_vote_answers (
+ sid INT(11) UNSIGNED NOT NULL,
+ qid INT(11) UNSIGNED NOT NULL,
+ vid INT(11) UNSIGNED NOT NULL,
+
+ answer TEXT DEFAULT NULL,
+
+ PRIMARY KEY id (sid, vid, qid),
+ FOREIGN KEY (vid) REFERENCES survey_votes (vid)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE,
+ FOREIGN KEY (sid, qid) REFERENCES survey_questions (sid, qid)
+ ON UPDATE CASCADE
+ ON DELETE CASCADE
+) ENGINE=InnoDB, CHARSET=utf8, COMMENT="Answers to the surveys";
+
+-- vim:set syntax=mysql:
--- /dev/null
+<?php
+/***************************************************************************
+ * Copyright (C) 2003-2010 Polytechnique.org *
+ * http://opensource.polytechnique.org/ *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the Free Software *
+ * Foundation, Inc., *
+ * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
+ ***************************************************************************/
+
+// {{{ class Survey : root of any survey, contains all questions
+class Survey
+{
+ // {{{ static properties and functions, regarding survey modes and question types
+ const MODE_ALL = 0;
+ const MODE_XANON = 1;
+ const MODE_XIDENT = 2;
+ private static $longModes = array(self::MODE_ALL => "sondage ouvert à tout le monde, anonyme",
+ self::MODE_XANON => "sondage restreint aux polytechniciens, anonyme",
+ self::MODE_XIDENT => "sondage restreint aux polytechniciens, non anonyme");
+ private static $shortModes = array(self::MODE_ALL => "tout le monde, anonyme",
+ self::MODE_XANON => "polytechniciens, anonyme",
+ self::MODE_XIDENT => "polytechniciens, non anonyme");
+
+ public static function getModes($long = true) {
+ return ($long)? self::$longModes : self::$shortModes;
+ }
+
+ private static $types = array('text' => 'Texte court',
+ 'textarea' => 'Texte long',
+ 'num' => 'Numérique',
+ 'radio' => 'Choix multiples (une réponse)',
+ 'checkbox' => 'Choix multiples (plusieurs réponses)',
+ 'radiotable' => 'Questions multiples à choix multiples (une réponse)',
+ 'checkboxtable' => 'Questions multiples à choix mutliples (plusieurs réponses)');
+
+ public static function getTypes()
+ {
+ return self::$types;
+ }
+
+ public static function isType($t)
+ {
+ return array_key_exists($t, self::$types);
+ }
+ // }}}
+
+ // {{{ properties, constructor and basic methods
+ private $id;
+ private $title;
+ private $description;
+ private $end;
+ private $mode;
+ private $promos;
+ private $valid;
+ private $questions;
+ private $creator;
+
+ public function __construct($args, $id = -1, $valid = false, $questions = null)
+ {
+ $this->update($args);
+ $this->id = $id;
+ $this->valid = $valid;
+ $this->questions = ($questions == null)? array() : $questions;
+ }
+
+ public function update($args)
+ {
+ $this->title = $args['title'];
+ $this->description = $args['description'];
+ $this->end = $args['end'];
+ $this->mode = (isset($args['mode']))? $args['mode'] : self::MODE_ALL;
+ $this->creator = $args['uid'];
+ if ($this->mode == self::MODE_ALL) {
+ $args['promos'] = '';
+ }
+ $args['promos'] = str_replace(' ', '', $args['promos']);
+ $this->promos = ($args['promos'] == '' || preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $args['promos']))? $args['promos'] : '#';
+ }
+
+ public function canSeeEarlyResults(User $user)
+ {
+ return $user->id() == $this->creator || $user->checkPerms('admin');
+ }
+ // }}}
+
+ // {{{ functions to access general information
+ public function isMode($mode)
+ {
+ return ($this->mode == $mode);
+ }
+
+ public function checkPromo($promo)
+ {
+ if ($this->promos == '') {
+ return true;
+ }
+ $promos = explode(',', $this->promos);
+ foreach ($promos as $p) {
+ if ((preg_match('#^\d{4}$#', $p) && $p == $promo) ||
+ (preg_match('#^\d{4}-$#', $p) && intval(substr($p, 0, 4)) <= $promo) ||
+ (preg_match('#^-\d{4}$#', $p) && intval(substr($p, 1)) >= $promo) ||
+ (preg_match('#^\d{4}-\d{4}$#', $p) &&
+ (intval(substr($p, 0, 4)) <= $promo && intval(substr($p, 5)) >= $promo ||
+ intval(substr($p, 0, 4)) >= $promo && intval(substr($p, 5)) <= $promo ))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public function isValid()
+ {
+ return $this->valid;
+ }
+
+ public function isEnded()
+ {
+ return (strtotime($this->end) - time() <= 0);
+ }
+
+ public function getTitle()
+ {
+ return $this->title;
+ }
+ // }}}
+
+ // {{{ function toArray() : converts a question (or the whole survey) to array, with results if the survey is ended
+ public function toArray($i = 'all')
+ {
+ if ($i != 'all' && $i != 'root') { // if a specific question is requested, then just returns this question converted to array
+ $i = intval($i);
+ if (array_key_exists($i, $this->questions)) {
+ return $this->questions[$i]->toArray();
+ } else {
+ return null;
+ }
+ } else { // else returns the root converted to array in any case
+ $a = array('title' => $this->title,
+ 'description' => $this->description,
+ 'end' => $this->end,
+ 'mode' => $this->mode,
+ 'promos' => $this->promos,
+ 'valid' => $this->valid,
+ 'type' => 'root');
+ if ($this->id != -1) {
+ $a['id'] = $this->id;
+ }
+ if ($this->isEnded()) { // if the survey is ended, then adds here the number of votes
+ $sql = 'SELECT COUNT(id)
+ FROM survey_votes
+ WHERE survey_id={?};';
+ $tot = XDB::query($sql, $this->id);
+ $a['votes'] = $tot->fetchOneCell();
+ }
+ if ($i == 'all' && count($this->questions) > 0) { // if the whole survey is requested, then returns all the questions converted to array
+ $qArr = array();
+ for ($k = 0; $k < count($this->questions); $k++) {
+ $q = $this->questions[$k]->toArray();
+ $q['id'] = $k;
+ if ($this->isEnded()) { // if the survey is ended, then adds here the results of this question
+ $q['result'] = $this->questions[$k]->getResultArray($this->id, $k);
+ }
+ $qArr[$k] = $q;
+ }
+ $a['questions'] = $qArr;
+ }
+ return $a;
+ }
+ }
+ // }}}
+
+ // {{{ function toCSV() : builds a CSV file containing all the results of the survey
+ public function toCSV($sep = ',', $enc = '"', $asep='|')
+ {
+ $nbq = count($this->questions);
+ //require_once dirname(__FILE__) . '/../../classes/varstream.php';
+ VarStream::init();
+ global $csv_output;
+ $csv_output = '';
+ $csv = fopen('var://csv_output', 'w');
+ $line = ($this->isMode(self::MODE_XIDENT))? array('id', 'Nom', 'Prenom', 'Promo') : array('id');
+ $qids = array();
+ for ($qid = 0; $qid < $nbq; $qid++) {
+ $qids[$qid] = count($line); // stores the first id of a question (in case of questions with subquestions)
+ array_splice($line, count($line), 0, $this->questions[$qid]->getCSVColumns()); // the first line contains the questions
+ }
+ $nbf = count($line);
+ $users = array();
+ if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
+ $users = User::getBulkUsersWithUIDs(XDB::fetchAllAssoc('vid', 'SELECT v.id AS vid, v.uid
+ FROM survey_votes AS v
+ WHERE v.survey_id = {?}
+ ORDER BY vid ASC',
+ $this->id));
+ }
+ $sql = 'SELECT v.id AS vid, a.question_id AS qid, a.answer AS answer
+ FROM survey_votes AS v
+ INNER JOIN survey_answers AS a ON a.vote_id=v.id
+ WHERE v.survey_id={?}
+ ORDER BY vid ASC, qid ASC, answer ASC';
+ $res = XDB::iterator($sql, $this->id); // retrieves all answers from database
+ $vid = -1;
+ $vid_ = 0;
+ while (($cur = $res->next()) != null) {
+ if ($vid != $cur['vid']) { // if the vote id changes, then starts a new line
+ fputcsv($csv, $line, $sep, $enc); // stores the former line into $csv_output
+ $vid = $cur['vid'];
+ $line = array_fill(0, $nbf, ''); // creates an array full of empty string
+ $line[0] = $vid_; // the first field is a 'clean' vote id (not the one stored in database)
+ if ($this->isMode(self::MODE_XIDENT)) { // if the mode is non anonymous
+ if (array_key_exists($vid, $users)) { // and if the user data can be found
+ $line[1] = $users[$vid]->lastName(); // adds the user data (in the first fields of the line)
+ $line[2] = $users[$vid]->firstName();;
+ $line[3] = $users[$vid]->promo();
+ }
+ }
+ $vid_++;
+ }
+ $ans = $this->questions[$cur['qid']]->formatAnswer($cur['answer']); // formats the current answer
+ if (!is_null($ans)) {
+ if (is_array($ans)) {
+ $fid = $qids[$cur['qid']] + $ans['id']; // computes the field id
+ $a = $ans['answer'];
+ } else {
+ $fid = $qids[$cur['qid']];
+ $a = $ans;
+ }
+ if ($line[$fid] != '') { // if this field already contains something
+ $line[$fid] .= $asep; // then adds a separator before adding the new answer
+ }
+ $line[$fid] .= $a; // adds the current answer to the correct field
+ }
+ }
+ fputcsv($csv, $line, $sep, $enc); // stores the last line into $csv_output
+ return $csv_output;
+ }
+ // }}}
+
+ // {{{ function factory($type, $args) : builds a question according to the given type
+ public function factory($t, $args)
+ {
+ switch ($t) {
+ case 'text':
+ return new SurveyText($args);
+ case 'textarea':
+ return new SurveyTextarea($args);
+ case 'num':
+ return new SurveyNum($args);
+ case 'radio':
+ return new SurveyRadio($args);
+ case 'checkbox':
+ return new SurveyCheckbox($args);
+ case 'radiotable':
+ return new SurveyRadioTable($args);
+ case 'checkboxtable':
+ return new SurveyCheckboxTable($args);
+ default:
+ return null;
+ }
+ }
+ // }}}
+
+ // {{{ questions manipulation functions
+ public function addQuestion($i, $c)
+ {
+ $i = intval($i);
+ if ($this->valid || $i > count($this->questions)) {
+ return false;
+ } else {
+ array_splice($this->questions, $i, 0, array($c));
+ return true;
+ }
+ }
+
+ public function delQuestion($i)
+ {
+ $i = intval($i);
+ if ($this->valid || !array_key_exists($i, $this->questions)) {
+ return false;
+ } else {
+ array_splice($this->questions, $i, 1);
+ return true;
+ }
+ }
+
+ public function editQuestion($i, $a)
+ {
+ if ($i == 'root') {
+ $this->update($a);
+ } else {
+ $i = intval($i);
+ if ($this->valid ||!array_key_exists($i, $this->questions)) {
+ return false;
+ } else {
+ $this->questions[$i]->update($a);
+ }
+ }
+ return true;
+ }
+ // }}}
+
+ // {{{ function checkSyntax() : checks syntax of the questions (currently the root only) before storing the survey in database
+ private static $errorMessages = array(
+ "datepassed" => "la date de fin de sondage est déjà dépassée : vous devez préciser une date future",
+ "promoformat" => "les restrictions à certaines promotions sont mal formattées"
+ );
+
+ public function checkSyntax()
+ {
+ $rArr = array();
+ // checks that the end date given is not already passed
+ // (unless the survey has already been validated : an admin can have a validated survey expired)
+ if (!$this->valid && $this->isEnded()) {
+ $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["datepassed"]);
+ }
+ if ($this->promos != '' && !preg_match('#^(\d{4}-?|(\d{4})?-\d{4})(,(\d{4}-?|(\d{4})?-\d{4}))*$#', $this->promos)) {
+ $rArr[] = array('question' => 'root', 'error' => self::$errorMessages["promoformat"]);
+ }
+ return (empty($rArr))? null : $rArr;
+ }
+ // }}}
+
+ // {{{ functions that manipulate surveys in database
+ // {{{ static function retrieveList() : gets the list of available survey (current, old and not validated surveys)
+ public static function retrieveList($type, $tpl = true)
+ {
+ switch ($type) {
+ case 'c':
+ case 'current':
+ $where = 'end > NOW()';
+ break;
+ case 'o':
+ case 'old':
+ $where = 'end <= NOW()';
+ break;
+ default:
+ return null;
+ }
+ $sql = 'SELECT id, title, end, mode
+ FROM surveys
+ WHERE '.$where.'
+ ORDER BY end DESC;';
+ if ($tpl) {
+ return XDB::iterator($sql);
+ } else {
+ return XDB::iterRow($sql);
+ }
+ }
+ // }}}
+
+ // {{{ static function retrieveSurvey() : gets a survey in database (and unserialize the survey object structure)
+ public static function retrieveSurvey($sid)
+ {
+ $sql = 'SELECT questions, title, description, end, mode, promos, uid
+ FROM surveys
+ WHERE id={?}';
+ $res = XDB::query($sql, $sid);
+ $data = $res->fetchOneAssoc();
+ if (is_null($data) || !is_array($data)) {
+ return null;
+ }
+ $survey = new Survey($data, $sid, true, unserialize($data['questions']));
+ return $survey;
+ }
+ // }}}
+
+ // {{{ static function retrieveSurveyInfo() : gets information about a survey (title, description, end date, restrictions) but does not unserialize the survey object structure
+ public static function retrieveSurveyInfo($sid)
+ {
+ $sql = 'SELECT title, description, end, mode, promos
+ FROM surveys
+ WHERE id={?}';
+ $res = XDB::query($sql, $sid);
+ return $res->fetchOneAssoc();
+ }
+ // }}}
+
+ // {{{ static function retrieveSurveyReq() : gets a survey request to validate
+ public static function retrieveSurveyReq($id)
+ {
+ $surveyreq = Validate::get_request_by_id($id);
+ if ($surveyreq == null) {
+ return null;
+ }
+ $data = array('title' => $surveyreq->title,
+ 'description' => $surveyreq->description,
+ 'end' => $surveyreq->end,
+ 'mode' => $surveyreq->mode,
+ 'promos' => $surveyreq->promos);
+ $survey = new Survey($data, $id, false, $surveyreq->questions);
+ return $survey;
+ }
+ // }}}
+
+ // {{{ function proposeSurvey() : stores a proposition of survey in database (before validation)
+ public function proposeSurvey()
+ {
+ $surveyreq = new SurveyReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions, S::user());
+ return $surveyreq->submit();
+ }
+ // }}}
+
+ // {{{ function updateSurvey() : updates a survey in database (before validation)
+ public function updateSurvey()
+ {
+ if ($this->valid) {
+ $sql = 'UPDATE surveys
+ SET questions={?},
+ title={?},
+ description={?},
+ end={?},
+ mode={?},
+ promos={?}
+ WHERE id={?};';
+ return XDB::execute($sql, serialize($this->questions), $this->title, $this->description, $this->end, $this->mode, $this->promos, $this->id);
+ } else {
+ $surveyreq = Validate::get_request_by_id($this->id);
+ if ($surveyreq == null) {
+ return false;
+ }
+ return $surveyreq->updateReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions);
+ }
+ }
+ // }}}
+
+ // {{{ functions vote() and hasVoted() : handles vote to a survey
+ public function vote($uid, $args)
+ {
+ XDB::execute('INSERT INTO survey_votes
+ SET survey_id = {?}, uid = {?}',
+ $this->id, ($uid == 0) ? null : $uid); // notes the user as having voted
+ $vid = XDB::insertId();
+ for ($i = 0; $i < count($this->questions); $i++) {
+ $ans = $this->questions[$i]->checkAnswer($args[$i]);
+ if (!is_null($ans) && is_array($ans)) {
+ foreach ($ans as $a) {
+ XDB::execute('INSERT INTO survey_answers
+ SET vote_id = {?},
+ question_id = {?},
+ answer = {?}', $vid, $i, $a);
+ }
+ }
+ }
+ }
+
+ public function hasVoted($uid)
+ {
+ $res = XDB::query('SELECT id
+ FROM survey_votes
+ WHERE survey_id = {?} AND uid = {?};', $this->id, $uid); // checks whether the user has already voted
+ return ($res->numRows() != 0);
+ }
+ // }}}
+
+ // {{{ static function deleteSurvey() : deletes a survey (and all its votes)
+ public static function deleteSurvey($sid)
+ {
+ $sql = 'DELETE s.*, v.*, a.*
+ FROM surveys AS s
+ LEFT JOIN survey_votes AS v
+ ON v.survey_id=s.id
+ LEFT JOIN survey_answers AS a
+ ON a.vote_id=v.id
+ WHERE s.id={?};';
+ return XDB::execute($sql, $sid);
+ }
+ // }}}
+
+ // {{{ static function purgeVotes() : clears all votes concerning a survey (I'm not sure whether it's really useful)
+ public static function purgeVotes($sid)
+ {
+ $sql = 'DELETE v.*, a.*
+ FROM survey_votes AS v
+ LEFT JOIN survey_answers AS a
+ ON a.vote_id=v.id
+ WHERE v.survey_id={?};';
+ return XDB::execute($sql, $sid);
+ }
+ // }}}
+
+ // }}}
+}
+// }}}
+
+// {{{ abstract class SurveyQuestion
+abstract class SurveyQuestion
+{
+ // {{{ common properties, constructor, and basic methods
+ private $question;
+ private $comment;
+
+ public function __construct($args)
+ {
+ $this->update($args);
+ }
+
+ public function update($a)
+ {
+ $this->question = $a['question'];
+ $this->comment = $a['comment'];
+ }
+
+ abstract protected function getQuestionType();
+ // }}}
+
+ // {{{ function toArray() : converts to array
+ public function toArray()
+ {
+ return array('type' => $this->getQuestionType(), 'question' => $this->question, 'comment' => $this->comment);
+ }
+ // }}}
+
+ // {{{ function checkSyntax() : checks question elements (before storing into database), not currently needed (with new structure)
+ protected function checkSyntax()
+ {
+ return null;
+ }
+ // }}}
+
+ // {{{ function checkAnswer : returns a correct answer (or a null value if error)
+ public function checkAnswer($ans)
+ {
+ return null;
+ }
+ // }}}
+
+ // {{{ functions regarding the results of a survey
+ abstract public function getResultArray($sid, $qid);
+
+ public function formatAnswer($ans)
+ {
+ return $ans;
+ }
+
+ public function getCSVColumns()
+ {
+ return $this->question;
+ }
+ // }}}
+}
+// }}}
+
+// {{{ abstract class SurveySimple and its derived classes : "open" questions
+// {{{ abstract class SurveySimple extends SurveyQuestion
+abstract class SurveySimple extends SurveyQuestion
+{
+ public function checkAnswer($ans)
+ {
+ return array($ans);
+ }
+
+ public function getResultArray($sid, $qid)
+ {
+ $sql = 'SELECT answer
+ FROM survey_answers
+ WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
+ AND question_id={?}
+ ORDER BY RAND()
+ LIMIT 5;';
+ $res = XDB::query($sql, $sid, $qid);
+ return $res->fetchAllAssoc();
+ }
+}
+// }}}
+
+// {{{ class SurveyText extends SurveySimple : simple text field, allowing a few words
+class SurveyText extends SurveySimple
+{
+ public function getQuestionType()
+ {
+ return "text";
+ }
+}
+// }}}
+
+// {{{ class SurveyTextarea extends SurveySimple : textarea field, allowing longer comments
+class SurveyTextarea extends SurveySimple
+{
+ public function getQuestionType()
+ {
+ return "textarea";
+ }
+}
+// }}}
+
+// {{{ class SurveyNum extends SurveySimple : allows numerical answers
+class SurveyNum extends SurveySimple
+{
+ public function checkAnswer($ans)
+ {
+ return array(intval($ans));
+ }
+
+ protected function getQuestionType()
+ {
+ return "num";
+ }
+}
+// }}}
+// }}}
+
+// {{{ abstract class SurveyList and its derived classes : restricted questions that allows only a list of possible answers
+// {{{ abstract class SurveyList extends SurveyQuestion
+abstract class SurveyList extends SurveyQuestion
+{
+ protected $choices;
+
+ public function update($args)
+ {
+ parent::update($args);
+ $this->choices = array();
+ foreach ($args['choices'] as $val) {
+ if (trim($val) || trim($val) == '0') {
+ $this->choices[] = $val;
+ }
+ }
+ }
+
+ public function toArray()
+ {
+ $rArr = parent::toArray();
+ $rArr['choices'] = $this->choices;
+ return $rArr;
+ }
+
+ public function getResultArray($sid, $qid)
+ {
+ $sql = 'SELECT answer, COUNT(id) AS count
+ FROM survey_answers
+ WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
+ AND question_id={?}
+ GROUP BY answer ASC';
+ $res = XDB::query($sql, $sid, $qid);
+ return $res->fetchAllAssoc();
+ }
+
+ public function formatAnswer($ans)
+ {
+ if (array_key_exists($ans, $this->choices)) {
+ return $this->choices[$ans];
+ } else {
+ return null;
+ }
+ }
+}
+// }}}
+
+// {{{ class SurveyRadio extends SurveyList : radio question, allows one answer among the list offered
+class SurveyRadio extends SurveyList
+{
+ public function checkAnswer($ans)
+ {
+ $a = intval($ans);
+ return (array_key_exists($a, $this->choices))? array($a) : null;
+ }
+
+ protected function getQuestionType()
+ {
+ return "radio";
+ }
+}
+// }}}
+
+// {{{ class SurveyCheckbox extends SurveyList : checkbox question, allows any number of answers among the list offered
+class SurveyCheckbox extends SurveyList
+{
+ public function checkAnswer($ans)
+ {
+ $rep = array();
+ foreach ($ans as $a) {
+ $a = intval($a);
+ if (array_key_exists($a, $this->choices)) {
+ $rep[] = $a;
+ }
+ }
+ return (count($rep) == 0)? null : $rep;
+ }
+
+ protected function getQuestionType()
+ {
+ return "checkbox";
+ }
+}
+// }}}
+// }}}
+
+// {{{ abstract class SurveyTable and its derived classes : table question, each column represents a choice, each line represents a question
+// {{{ abstract class SurveyTable extends SurveyList
+abstract class SurveyTable extends SurveyList
+{
+ protected $subquestions;
+
+ public function update($args)
+ {
+ parent::update($args);
+ $this->subquestions = array();
+ foreach ($args['subquestions'] as $val) {
+ if (trim($val) || trim($val) == '0') {
+ $this->subquestions[] = $val;
+ }
+ }
+ }
+
+ public function toArray()
+ {
+ $rArr = parent::toArray();
+ $rArr['subquestions'] = $this->subquestions;
+ return $rArr;
+ }
+
+ public function getResultArray($sid, $qid)
+ {
+ $sql = 'SELECT answer, COUNT(id) AS count
+ FROM survey_answers
+ WHERE vote_id IN (SELECT id FROM survey_votes WHERE survey_id={?})
+ AND question_id={?}
+ GROUP BY answer ASC';
+ $res = XDB::iterator($sql, $sid, $qid);
+ $result = array();
+ for ($i = 0; $i < count($this->subquestions); $i++) {
+ $result[$i] = array_fill(0, count($this->choices), 0);
+ }
+ while ($r = $res->next()) {
+ list($i, $j) = explode(':', $r['answer']);
+ $result[$i][$j] = $r['count'];
+ }
+ return $result;
+ }
+
+ public function formatAnswer($ans)
+ {
+ list($q, $c) = explode(':', $ans);
+ if (array_key_exists($q, $this->subquestions) && array_key_exists($c, $this->choices)) {
+ return array('id' => $q, 'answer' => $this->choices[$c]);
+ } else {
+ return null;
+ }
+ }
+
+ public function getCSVColumns()
+ {
+ $q = parent::getCSVColumns();
+ if (empty($this->subquestions)) {
+ return $q;
+ }
+ $a = array();
+ for ($k = 0; $k < count($this->subquestions); $k++) {
+ $a[$k] = $q.' : '.$this->subquestions[$k];
+ }
+ return $a;
+ }
+}
+// }}}
+
+// {{{ class SurveyRadioTable extends SurveyTable : SurveyTable with radio type choices
+class SurveyRadioTable extends SurveyTable
+{
+ public function checkAnswer($ans)
+ {
+ $rep = array();
+ foreach ($ans as $k => $a) {
+ if (!array_key_exists($k, $this->subquestions)) {
+ continue;
+ }
+ $a = intval($a);
+ if (array_key_exists($a, $this->choices)) {
+ $rep[] = $k . ':' . $a;
+ }
+ }
+ return (count($rep) == 0)? null : $rep;
+ }
+
+ protected function getQuestionType()
+ {
+ return "radiotable";
+ }
+
+}
+// }}}
+
+// {{{ class SurveyCheckboxTable extends SurveyTable : SurveyTable with checkbox type choices
+class SurveyCheckboxTable extends SurveyTable
+{
+ public function checkAnswer($ans)
+ {
+ $rep = array();
+ foreach ($ans as $k => $aa) {
+ if (!array_key_exists($k, $this->subquestions)) {
+ continue;
+ }
+ foreach ($aa as $a) {
+ $a = intval($a);
+ if (array_key_exists($a, $this->choices)) {
+ $rep[] = $k . ':' . $a;
+ }
+ }
+ }
+ return (count($rep) == 0)? null : $rep;
+ }
+
+ protected function getQuestionType()
+ {
+ return "checkboxtable";
+ }
+
+}
+// }}}
+// }}}
+
+// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
+?>
--- /dev/null
+#!/bin/bash
+
+. ../inc/pervasive.sh
+
+###########################################################
+[ "$DATABASE" != "x4dat" ] || die "Cannot target x4dat"
+copy_db
+
+confirm "* Running database upgrade scripts"
+#mysql_run_directory .