Merge remote branch 'origin/xorg/maint' into xorg/master
authorFlorent Bruneau <florent.bruneau@polytechnique.org>
Mon, 31 Jan 2011 19:21:13 +0000 (20:21 +0100)
committerFlorent Bruneau <florent.bruneau@polytechnique.org>
Mon, 31 Jan 2011 19:21:22 +0000 (20:21 +0100)
Conflicts:
ChangeLog
Makefile
classes/userfilter/conditions.inc.php
core
htdocs/javascript/do_challenge_response.js
htdocs/javascript/password.js
htdocs/javascript/wiki.js
htdocs/javascript/xorg.js
include/massmailer.inc.php
modules/admin.php
modules/api.php
modules/axletter/axletter.inc.php
templates/admin/user.tpl
templates/axletter/admin.tpl
templates/axletter/edit.tpl
templates/axletter/index.tpl
templates/axletter/show.tpl
templates/emails/antispam.tpl
templates/emails/index.tpl
templates/events/form.tpl
templates/gadgets/ig-skin.tpl
templates/lists/index.tpl
templates/profile/fiche_referent.tpl
templates/search/index.tpl
templates/skin/common.bandeau.head.tpl
templates/skin/common.title.header.tpl
templates/survey/show_textarea.tpl
templates/survey/success.tpl

Signed-off-by: Florent Bruneau <florent.bruneau@polytechnique.org>
155 files changed:
ChangeLog
Makefile
bin/cron/checkdb.php
bin/cron/clean.php
classes/address.php
classes/group.php
classes/jobterms.php
classes/phone.php
classes/user.php
classes/xnetpage.php
classes/xorg.php
classes/xorgpage.php
classes/xorgsession.php
configs/mails.conf
configs/platal.ini
core
htdocs/css/bandeau.css
htdocs/css/base.css
htdocs/css/default.css
htdocs/css/keynote.css
htdocs/css/openweb.css
htdocs/css/print.css [deleted file]
htdocs/javascript/.gitignore
htdocs/javascript/do_challenge_response.js [deleted file]
htdocs/javascript/jobtermstree.js
htdocs/javascript/password.js [deleted file]
htdocs/javascript/profile.js
htdocs/javascript/sha1.js [deleted file]
htdocs/javascript/survey.js [new file with mode: 0644]
htdocs/javascript/wiki.js [deleted file]
htdocs/javascript/xorg.js
include/banana/forum.inc.php
include/profilefields.inc.php
include/ufbuilder.inc.php
include/validations/listes.inc.php
include/vcard.inc.php
modules/admin.php
modules/api.php [moved from htdocs/javascript/secure_hash.js with 60% similarity]
modules/bandeau.php
modules/carnet.php
modules/carnet/contacts.pdf.inc.php
modules/events.php
modules/googleapps.php
modules/payment.php
modules/payment/money/bplccyberplus.inc.php
modules/payment/money/paypal.inc.php
modules/platal.php
modules/profile.php
modules/profile/jobs.inc.php
modules/profile/skills.inc.php
modules/register.php
modules/search.php
modules/survey.php
modules/survey/answer.inc.php [new file with mode: 0644]
modules/survey/multiple.inc.php [new file with mode: 0644]
modules/survey/question.inc.php [new file with mode: 0644]
modules/survey/section.inc.php [moved from htdocs/javascript/close_on_esc.js with 83% similarity]
modules/survey/survey.inc.php
modules/survey/text.inc.php [moved from htdocs/javascript/do_challenge_response_logged.js with 72% similarity]
modules/xnetevents.php
modules/xnetevents/xnetevents.inc.php
modules/xnetgrp.php
plugins/function.poison.php
templates/admin/emails_bounces_re.tpl [deleted file]
templates/admin/geocoding.tpl [moved from templates/survey/admin.tpl with 52% similarity]
templates/admin/geocoding_edit.tpl [moved from templates/survey/show_textarea.tpl with 60% similarity]
templates/admin/index.tpl
templates/admin/user.tpl
templates/core/password_prompt_logged.tpl
templates/emails/antispam.tpl
templates/emails/index.tpl
templates/emails/send.tpl
templates/events/form.tpl
templates/fusionax/ids.tpl
templates/fusionax/import.tpl
templates/gadgets/ig-skin.tpl
templates/include/emails.combobox.tpl
templates/include/form.valid.edit-listes.tpl
templates/lists/index.tpl
templates/payment/xnet.tpl
templates/platal/preferences.tpl
templates/platal/skins.tpl
templates/profile/fiche_referent.tpl
templates/profile/jobs.job.tpl
templates/profile/mentor.tpl
templates/profile/profile.tpl
templates/profile/skill.tpl
templates/register/end.tpl
templates/register/step3.tpl
templates/search/adv.form.tpl
templates/search/index.tpl
templates/search/quick.form.tpl
templates/search/referent.tpl
templates/skin/common.bandeau.tpl
templates/skin/common.header.tpl
templates/skin/common.title.header.tpl
templates/skin/default.tpl
templates/skin/espace.tpl
templates/skin/humlinux.tpl
templates/skin/keynote.tpl
templates/skin/linux.tpl
templates/skin/liteskin.tpl
templates/skin/nbviolet.tpl
templates/skin/newxorg.tpl
templates/skin/oldtimes.tpl
templates/skin/openweb.tpl
templates/skin/register.tpl
templates/skin/sharky.tpl
templates/skin/spectral.tpl
templates/skin/trapped.tpl
templates/survey/confirm.tpl [deleted file]
templates/survey/edit.questions.tpl [new file with mode: 0644]
templates/survey/edit.tpl [new file with mode: 0644]
templates/survey/edit_checkbox.tpl [deleted file]
templates/survey/edit_checkboxtable.tpl [deleted file]
templates/survey/edit_new.tpl [deleted file]
templates/survey/edit_newsurvey.tpl [deleted file]
templates/survey/edit_num.tpl [deleted file]
templates/survey/edit_question.tpl [deleted file]
templates/survey/edit_radio.tpl [deleted file]
templates/survey/edit_radiotable.tpl [deleted file]
templates/survey/edit_root.tpl [deleted file]
templates/survey/edit_survey.tpl [deleted file]
templates/survey/edit_text.tpl [deleted file]
templates/survey/edit_textarea.tpl [deleted file]
templates/survey/error.tpl [deleted file]
templates/survey/index.tpl
templates/survey/show_checkbox.tpl [deleted file]
templates/survey/show_num.tpl [deleted file]
templates/survey/show_question.tpl [deleted file]
templates/survey/show_radio.tpl [deleted file]
templates/survey/show_radiotable.tpl [deleted file]
templates/survey/show_root.tpl [deleted file]
templates/survey/show_text.tpl [deleted file]
templates/survey/vote.questions.tpl [moved from templates/survey/show_checkboxtable.tpl with 57% similarity]
templates/survey/vote.tpl [moved from templates/skin/common.bandeau.head.tpl with 74% similarity]
templates/xnet/skin.tpl
templates/xnetevents/edit.tpl
templates/xnetevents/index.tpl
templates/xnetevents/subscription-notif.mail.tpl [moved from templates/survey/success.tpl with 76% similarity]
templates/xnetgrp/asso.tpl
templates/xnetgrp/edit.tpl
templates/xnetgrp/membres-edit.tpl
upgrade/1.1.0/01_new_mail_schema.sql [new file with mode: 0644]
upgrade/1.1.0/02_new_mail_insertion.sql [new file with mode: 0644]
upgrade/1.1.0/04_xnetgrp.sql [new file with mode: 0644]
upgrade/1.1.0/05_permissions.sql [new file with mode: 0644]
upgrade/1.1.0/05_xnetevents.sql [new file with mode: 0644]
upgrade/1.1.0/06_language.sql [new file with mode: 0644]
upgrade/1.1.0/10_surveys.sql [new file with mode: 0644]
upgrade/1.1.0/connect.db.inc.php [new symlink]
upgrade/1.1.0/languages.php [new file with mode: 0755]
upgrade/1.1.0/new_mail_delete_old.sql.noauto [new file with mode: 0644]
upgrade/1.1.0/old_surveys.inc.php [new file with mode: 0644]
upgrade/1.1.0/update.sh [new file with mode: 0755]

index 4b6ad77..6b16616 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,4 +1,46 @@
 ================================================================================
+VERSION 1.1.0                                                         XX XX XXXX
+
+Bug/Wish:
+
+    * Admin:
+      - #1320: Add administrations pages for country and language edition  -JAC
+      - #1371: Allows email edition before mailing list validation         -JAC
+
+    * Carnet:
+      - #1139: Fixes contact pdf export with pictures                      -JAC
+
+    * Core:
+      - #1040: Adapts login page for non-X users                           -FRU
+      - #1325: Fixes csv downloading with IE8                              -JAC
+
+    * Emails:
+      - #1201: Increases allowed email size                                -JAC
+
+    * Payments:
+      - #1314,1295: Finally fix "has paid" lists                           -Xel
+
+    * Profile:
+      - #1288: Adds explaination about job keywords in profile edition     -JAC
+      - #1294: Fixes email in job information                              -JAC
+      - #1322: Removes duplicated city and postal code in vcard addresses  -JAC
+      - #1323: Displays email aliases in vcards when public                -JAC
+
+    * Search:
+      - #1283: Restricts second operation on promo search                  -Car
+      - #1312: Adds search on subadministrativearea                        -JAC
+      - #1313: Fixes advanced form js in IE7                               -Car
+
+    * Xnet:
+      - #1347: Fixes menu when changing rights in Xnet                     -JAC
+
+    * XnetEvent:
+      - #1233: Enables event subscribtion notification                     -JAC
+
+    * XnetGrp:
+      - #1230: Adds custom welcome message for group subscription          -JAC
+
+================================================================================
 VERSION 1.0.2                                                         31 01 2011
 
 Bug/Wish:
index d7ee751..283e02e 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -73,7 +73,10 @@ htdocs/.htaccess: htdocs/.htaccess.in Makefile
 ##
 ## static content
 ##
-static: htdocs/javascript@VERSION
+static: htdocs/javascript/core.js htdocs/javascript@VERSION
+
+htdocs/javascript/core.js:
+       cd htdocs/javascript/ && ln -s ../../core/htdocs/javascript/core.js
 
 %@VERSION: % Makefile ChangeLog
        cd $< && rm -f $(VERSION) && ln -sf . $(VERSION)
@@ -119,10 +122,10 @@ wiki/pub/skins/empty:
 
 get-wiki:
        @if ! test -d wiki; then                                          \
-           wget http://www.pmwiki.org/pub/pmwiki/pmwiki-latest.tgz;      \
-           tar -xzvf pmwiki-latest.tgz;                                  \
-           rm pmwiki-latest.tgz;                                         \
-           mv pmwiki-* wiki;                                             \
+               wget http://www.pmwiki.org/pub/pmwiki/pmwiki-latest.tgz;      \
+               tar -xzvf pmwiki-latest.tgz;                                  \
+               rm pmwiki-latest.tgz;                                         \
+               mv pmwiki-* wiki;                                             \
        fi
 
 ##
@@ -132,14 +135,17 @@ get-wiki:
 openid: get-openid spool/openid/store
 
 # There is no obvious way to automatically use the latest version
-OPENID_VERSION = 2.1.3
+OPENID_VERSION = 2.2.2
+OPENID_COMMIT  = 782224d
 get-openid:
        @if ! test -d include/Auth; then                                  \
-           wget http://openidenabled.com/files/php-openid/packages/php-openid-$(OPENID_VERSION).tar.bz2; \
-           tar -xjf php-openid-$(OPENID_VERSION).tar.bz2;                \
-           mv php-openid-$(OPENID_VERSION)/Auth include/;                \
-           rm php-openid-$(OPENID_VERSION).tar.bz2;                      \
-           rm -r php-openid-$(OPENID_VERSION);                           \
+               wget --no-check-certificate                                   \
+                       https://github.com/openid/php-openid/tarball/$(OPENID_VERSION) \
+                       -O php-openid-$(OPENID_VERSION).tar.gz; \
+               tar -xzf php-openid-$(OPENID_VERSION).tar.gz;                \
+               mv openid-php-openid-$(OPENID_COMMIT)/Auth include/;                \
+               rm php-openid-$(OPENID_VERSION).tar.gz;                      \
+               rm -r openid-php-openid-$(OPENID_COMMIT);                           \
        fi
 
 spool/openid/store:
@@ -178,7 +184,7 @@ JQUERY_PLUGINS=color form
 JQUERY_PLUGINS_PATHES=$(addprefix htdocs/javascript/jquery.,$(addsuffix .js,$(JQUERY_PLUGINS)))
 
 JQUERY_UI_VERSION=1.8.7
-JQUERY_UI=core tabs widget
+JQUERY_UI=core widget tabs datepicker
 JQUERY_UI_PATHES=$(addprefix htdocs/javascript/jquery.ui.,$(addsuffix .js,$(JQUERY_UI)))
 
 JQUERY_TMPL_VERSION=vBeta1.0.0
@@ -190,7 +196,13 @@ JSTREE_PATH=htdocs/javascript/jquery.jstree.js
 # TODO: jquery.autocomplete.js should rather be downloaded from an official source. The issue
 # is that the version we use is not available anymore on the Internet, and the latest version
 # we could use is not backward compatible with our current code.
-jquery: htdocs/javascript/jquery.js $(JQUERY_PLUGINS_PATHES) $(JQUERY_UI_PATHES) $(JQUERY_TMPL_PATH) $(JSTREE_PATH)
+jquery: htdocs/javascript/jquery.xorg.js htdocs/javascript/jquery.ui.xorg.js $(JSTREE_PATH)
+
+htdocs/javascript/jquery.xorg.js: htdocs/javascript/jquery.js $(JQUERY_PLUGINS_PATHES) $(JQUERY_TMPL_PATH) htdocs/javascript/jquery.autocomplete.js
+       cat $^ > $@
+
+htdocs/javascript/jquery.ui.xorg.js: $(JQUERY_UI_PATHES) htdocs/javascript/jquery.ui.datepicker-fr.js
+       cat $^ > $@
 
 htdocs/javascript/jquery-$(JQUERY_VERSION).min.js: DOWNLOAD_SRC = http://jquery.com/src/$(@F)
 htdocs/javascript/jquery-$(JQUERY_VERSION).min.js:
@@ -209,7 +221,19 @@ htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).%.js: DOWNLOAD_SRC = http://jqu
 htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).%.js:
        @$(download)
 
-$(JQUERY_UI_PATHES): htdocs/javascript/jquery.ui.%.js: htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).%.js
+htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).datepicker-fr.js: DOWNLOAD_SRC = http://jquery-ui.googlecode.com/svn/tags/$(JQUERY_UI_VERSION)/ui/minified/i18n/jquery.ui.datepicker-fr.min.js
+htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).datepicker-fr.js:
+       @$(download)
+
+$(JQUERY_UI_PATHES) htdocs/javascript/jquery.ui.datepicker-fr.js: htdocs/javascript/jquery.ui.%.js: htdocs/javascript/jquery.ui-$(JQUERY_UI_VERSION).%.js
+       ln -snf $(<F) $@
+
+htdocs/javascript/jquery.tmpl-$(JQUERY_TMPL_VERSION).js: DOWNLOAD_SRC = https://github.com/jquery/jquery-tmpl/raw/$(JQUERY_TMPL_VERSION)/jquery.tmpl.js --no-check-certificate
+htdocs/javascript/jquery.tmpl-$(JQUERY_TMPL_VERSION).js:
+       @-rm htdocs/javascript/jquery.tmpl*.js
+       @$(download)
+
+$(JQUERY_TMPL_PATH): htdocs/javascript/jquery.tmpl-$(JQUERY_TMPL_VERSION).js
        ln -snf $(<F) $@
 
 htdocs/javascript/jquery.tmpl-$(JQUERY_TMPL_VERSION).js: DOWNLOAD_SRC = https://github.com/jquery/jquery-tmpl/raw/$(JQUERY_TMPL_VERSION)/jquery.tmpl.min.js --no-check-certificate
index ed564af..999bf9c 100755 (executable)
@@ -61,7 +61,8 @@ function checkCount($sql, $comment = '')
     }
 }
 
-function info($sql, $comment = '', $onlyCounts = false) {
+function info($sql, $comment = '', $onlyCounts = false)
+{
     global $opt_verbose;
     if ($opt_verbose) {
         if ($onlyCounts) {
@@ -72,6 +73,20 @@ function info($sql, $comment = '', $onlyCounts = false) {
     }
 }
 
+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;
@@ -128,12 +143,19 @@ check("SELECT  a.alias AS username, b.alias AS loginbis, b.expire
         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:
 ?>
index add5458..5925900 100755 (executable)
@@ -48,7 +48,7 @@ query('ALTER TABLE  profile_education_field_enum
 query('ALTER TABLE  profile_job_enum
           ORDER BY  name');
 query('ALTER TABLE  profile_langskill_enum
-          ORDER BY  langue_fr');
+          ORDER BY  language');
 query('ALTER TABLE  profile_medal_enum
           ORDER BY  text');
 query('ALTER TABLE  profile_networking_enum
index 07f310b..6c1880b 100644 (file)
@@ -366,7 +366,7 @@ class Address
 
     public function addPhone(Phone &$phone)
     {
-        if ($phone->linkType() == Phone::LINK_ADDRESS && $phone->pid() == $this->pid) {
+        if ($phone->link_type == Phone::LINK_ADDRESS && $phone->pid == $this->pid) {
             $this->phones[$phone->uniqueId()] = $phone;
         }
     }
@@ -897,7 +897,7 @@ class AddressIterator implements PlIterator
         // Adds phones to addresses.
         $it = Phone::iterate(array($data['pid']), array(Phone::LINK_ADDRESS), array($data['id']));
         while ($phone = $it->next()) {
-            $data['phones'][$phone->id()] = $phone->toFormArray();
+            $data['phones'][$phone->id] = $phone->toFormArray();
         }
         return new Address($data);
     }
index e3ed9b6..db1a7ef 100644 (file)
@@ -37,6 +37,9 @@ class Group
         }
         $this->id = intval($this->data['id']);
         $this->shortname = $this->data['diminutif'];
+        if (!is_null($this->axDate)) {
+            $this->axDate = format_datetime($this->axDate, '%d/%m/%Y');
+        }
     }
 
     public function __get($name)
@@ -125,7 +128,13 @@ class Group
             }
             return null;
         }
-        return new Group($res->fetchOneAssoc());
+        $data = $res->fetchOneAssoc();
+        $positions = XDB::fetchAllAssoc('SELECT  position, uid
+                                           FROM  group_members
+                                          WHERE  asso_id = {?} AND position IS NOT NULL
+                                       ORDER BY  position',
+                                        $data['id']);
+        return new Group(array_merge($data, array('positions' => $positions)));
     }
 }
 
index ae5c758..85f3a07 100644 (file)
@@ -117,9 +117,9 @@ class JobTerms {
         return '$("'.addslashes($domElement).'").jstree({
             "core" : {"strings":{"loading":"Chargement ..."}},
             "plugins" : ["themes","json_data"],
-            "themes" : { "url" : platal_baseurl + "css/jstree.css" },
+            "themes" : { "url" : $.plURL("css/jstree.css") },
             "json_data" : { "ajax" : {
-                "url" : platal_baseurl + "'.addslashes($platalpage).'",
+                "url" : $.plURL("'.addslashes($platalpage).'"),
                 "data" : function(nod) {
                     var jtid = 0;
                     if (nod != -1) {
index 9a9f1b0..8a63d66 100644 (file)
@@ -59,17 +59,17 @@ class Phone
     /** The following fields, but $error, all correspond to the fields of the
      * database table profile_phones.
      */
-    private $id = 0;
-    private $pid = 0;
-    private $search = '';
-    private $link_type = 'user';
-    private $link_id = 0;
+    public $id = 0;
+    public $pid = 0;
+    public $search = '';
+    public $link_type = 'user';
+    public $link_id = 0;
     // The following fields are the fields of the form in the profile edition.
-    private $type = 'fixed';
+    public $type = 'fixed';
     public $display = '';
     public $pub = 'ax';
     public $comment = '';
-    private $error = false;
+    public $error = false;
 
     public function __construct(array $data = array())
     {
@@ -80,31 +80,6 @@ class Phone
         }
     }
 
-    public function linkType()
-    {
-        return $this->link_type;
-    }
-
-    public function linkId()
-    {
-        return $this->link_id;
-    }
-
-    public function id()
-    {
-        return $this->id;
-    }
-
-    public function pid()
-    {
-        return $this->pid;
-    }
-
-    public function search()
-    {
-        return $this->search;
-    }
-
     public function setId($id)
     {
         $this->id = $id;
index a0a7b3a..9a7c48c 100644 (file)
 
 class User extends PlUser
 {
-    const PERM_GROUPS            = 'groups';
-    const PERM_MAIL              = 'mail';
+    const PERM_API_USER_READONLY = 'api_user_readonly';
     const PERM_DIRECTORY_AX      = 'directory_ax';
     const PERM_DIRECTORY_PRIVATE = 'directory_private';
     const PERM_EDIT_DIRECTORY    = 'edit_directory';
     const PERM_FORUMS            = 'forums';
+    const PERM_GROUPS            = 'groups';
     const PERM_LISTS             = 'lists';
+    const PERM_MAIL              = 'mail';
     const PERM_PAYMENT           = 'payment';
 
     private $_profile_fetched = false;
@@ -172,6 +173,7 @@ class User extends PlUser
             $joins .= XDB::format("LEFT JOIN group_members AS gpm ON (gpm.uid = a.uid AND gpm.asso_id = {?})\n", $globals->asso('id'));
             $fields[] = 'gpm.perms AS group_perms';
             $fields[] = 'gpm.comm AS group_comm';
+            $fields[] = 'gpm.position AS group_position';
         }
         if (count($fields) > 0) {
             $fields = ', ' . implode(', ', $fields);
index 42bf9e9..0a3af26 100644 (file)
@@ -41,9 +41,9 @@ class XnetPage extends PlPage
             $this->assign('is_admin', may_update());
             $this->assign('is_member', is_member());
         }
-        $this->addJsLink('jquery.js');
+        $this->addJsLink('jquery.xorg.js');
         $this->addJsLink('overlib.js');
-        $this->addJsLink('wiki.js');
+        $this->addJsLink('core.js');
         $this->addJsLink('xorg.js');
         $this->setTitle('Les associations polytechniciennes');
     }
index 593af76..9ff621c 100644 (file)
@@ -28,7 +28,7 @@ class Xorg extends Platal
                             'profile', 'register', 'search', 'stats', 'admin',
                             'newsletter', 'axletter', 'epletter', 'bandeau', 'survey',
                             'fusionax', 'gadgets', 'googleapps', 'poison',
-                            'openid', 'reminder');
+                            'openid', 'reminder', 'api');
     }
 
     public function find_hook()
@@ -44,10 +44,8 @@ class Xorg extends Platal
         header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
         if (S::logged()) {
             $page->changeTpl('core/password_prompt_logged.tpl');
-            $page->addJsLink('do_challenge_response_logged.js');
         } else {
             $page->changeTpl('core/password_prompt.tpl');
-            $page->addJsLink('do_challenge_response.js');
         }
         $page->assign_by_ref('platal', $this);
         $page->run();
index f831b54..83824d8 100644 (file)
@@ -27,11 +27,9 @@ class XorgPage extends PlPage
 
         // Set the default page
         $this->changeTpl('platal/index.tpl');
-        $this->addJsLink('jquery.js');
+        $this->addJsLink('jquery.xorg.js');
         $this->addJsLink('overlib.js');
-        $this->addJsLink('secure_hash.js');
-        $this->addJsLink('sha1.js');
-        $this->addJsLink('wiki.js');
+        $this->addJsLink('core.js');
         $this->addJsLink('xorg.js');
         $this->setTitle('le site des élèves et anciens élèves de l\'École polytechnique');
         if (S::logged() && S::user()->checkPerms('admin')) {
index b8980e1..2e85275 100644 (file)
@@ -258,6 +258,54 @@ class XorgSession extends PlSession
         }
     }
 
+    /**
+     * The authentication schema is based on three query parameters:
+     *   ?user=<hruid>&timestamp=<timestamp>&sig=<sig>
+     * where:
+     *   - hruid is the hruid of the querying user
+     *   - timestamp is the current UNIX timestamp, which has to be within a
+     *     given distance of the server-side UNIX timestamp
+     *   - sig is the HMAC of "<method>#<resource>#<payload>#<timestamp>" using
+     *     a known secret of the user as the key.
+     *
+     * At the moment, the shared secret of the user is the sha1 hash of its
+     * password. This is temporary, though, until better support for tokens is
+     * implemented in plat/al.
+     * TODO(vzanotti): Switch to dedicated secrets for authentication.
+     */
+    public function apiAuth($method, $resource, $payload)
+    {
+        // Verify that the timestamp is within acceptable bounds.
+        $timestamp = Env::i('timestamp', 0);
+        if (abs($timestamp - time()) > Platal::globals()->api->timestamp_tolerance) {
+            return null;
+        }
+
+        // Retrieve the user corresponding to the forlife. Note that at the
+        // moment, other aliases are also accepted.
+        $user = User::getSilent(Env::s('user', ''));
+        if (is_null($user) || !$user->isActive()) {
+            return null;
+        }
+
+        // Determine the list of tokens associated with the user. At the moment,
+        // this is just the sha1 of the password.
+        $tokens = array($user->password());
+
+        // For each token, try to validate the signature.
+        $message = implode('#', array($method, $resource, $payload, $timestamp));
+        $signature = Env::s('sig');
+        foreach ($tokens as $token) {
+            $expected_signature = hash_hmac(
+                Platal::globals()->api->hmac_algo, $message, $token);
+            if ($signature == $expected_signature) {
+                return $user;
+            }
+        }
+
+        return null;
+    }
+
     public function tokenAuth($login, $token)
     {
         $res = XDB::query('SELECT  a.uid, a.hruid
index 059b0d9..6afd15b 100644 (file)
@@ -71,3 +71,6 @@ replyto=registration+watch@staff.m4x.org
 from="Polytechnique.org" <validation_modification@polytechnique.org>
 cc="Polytechnique.org" <validation_modification@polytechnique.org>
 
+[xnet_notification]
+from="Polytechnique.org" <contact@polytechnique.org>
+
index 1e4e830..c6ae06f 100644 (file)
@@ -156,6 +156,21 @@ register_skin = "register"
 econfiance = ""
 
 
+; The API section contains  the configuration for the web services.
+[Api]
+
+; $globals->api->hmac_algo
+; Algorithm to use for HMAC-based authentication of API requests. Note that this
+; value is shared with clients, and must be changed in all places at once.
+hmac_algo = "sha256"
+
+; $globals->api->timestamp_tolerance
+; Maximum number of seconds of drift allowed between the client-side UNIX clock
+; and the server-side clock. This should be big enough to also allow for network
+; latency, but not too high, to limit replay opportunities.
+timestamp_tolerance = 10
+
+
 ; The banana section contains the configuration of the forums.
 [Banana]
 
@@ -214,6 +229,7 @@ gmaps_hl = "fr"
 ; Default location preference.
 gmaps_gl = "fr"
 
+
 ; The lists section contains parameters used to interact with mailman.
 [Lists]
 
diff --git a/core b/core
index 9261ede..9007d49 160000 (submodule)
--- a/core
+++ b/core
@@ -1 +1 @@
-Subproject commit 9261ede012d3edda638f614494df31e876e8d758
+Subproject commit 9007d4955f2487e82c0f9f4059e1f6b450bdb528
index 2ccb3d8..8c2e225 100644 (file)
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-#bandeau-X a        { vertical-align: middle; }
-#bandeau-X a:link, #bandeau-X a:visited    { text-decoration: none ; color: #505050; }
-#bandeau-X a:hover   { text-decoration: underline; color: black; }
-#bandeau-X a:active  { color: #CCCCCC ; background: #505050 ; }
-body {margin:0px;}
-#bandeau-X {
-background:#CCCCCC;color:#505050;font-size:10px;font-family:Verdana, Arial, Helvetica, sans-serif;height:15px;border:none;padding:0;margin:0 }
-#bandeau-X img { vertical-align:middle;border:0;padding:0;margin:0 }
+@media screen {
+    #bandeau-X a        { vertical-align: middle; }
+    #bandeau-X a:link, #bandeau-X a:visited    { text-decoration: none ; color: #505050; }
+    #bandeau-X a:hover   { text-decoration: underline; color: black; }
+    #bandeau-X a:active  { color: #CCCCCC ; background: #505050 ; }
+    body {margin:0px;}
+    #bandeau-X {
+    background:#CCCCCC;color:#505050;font-size:10px;font-family:Verdana, Arial, Helvetica, sans-serif;height:15px;border:none;padding:0;margin:0 }
+    #bandeau-X img { vertical-align:middle;border:0;padding:0;margin:0 }
+}
index 669c239..710172e 100644 (file)
 
 .ui-tabs-hide { display: none; }
 
+.ui-icon {
+    width: 16px;
+    height: 16px;
+}
+
+.ui-datepicker {
+    background: #ffffff;
+    color: #000000;
+    position: absolute;
+}
+
+.ui-datepicker a {
+    color: black;
+    text-decoration: none;
+    text-align: center;
+}
+
+.ui-datepicker-header {
+    padding: 2px;
+    margin: 1px;
+    background: #777;
+    border: 1px solid;
+    border-color: #333;
+}
+
+.ui-datepicker-title {
+    text-align: center;
+    height: 19px;
+}
+
+.ui-datepicker-prev {
+    background: #777 url('/images/icons/resultset_previous.gif');
+    position: absolute;
+    width: 16px;
+    height: 16px;
+    top: 4px;
+    left: 4px;
+    outline: none;
+    display: block;
+}
+
+.ui-datepicker-next {
+    background: #777 url('/images/icons/resultset_next.gif');
+    position: absolute;
+    width: 16px;
+    height: 16px;
+    top: 4px;
+    right: 4px;
+    outline: none;
+    display: block;
+}
+
+.ui-datepicker-next span, .ui-datepicker-prev span {
+    display: block;
+    position: absolute;
+    text-indent: -99999px;
+    overflow: hidden;
+}
+
+.ui-datepicker-calendar {
+    border-collapse: collapse;
+    text-align: right;
+}
+
+.ui-datepicker-calendar td {
+    width: 20px;
+}
+
+.ui-datepicker-week-end {
+    background-color: #eee;
+}
+
+.ui-datepicker-unselectable {
+    color: #777;
+}
+
+/* print */
+@media print {
+    #body-menu, #body-top, #body-logo, #body-bottom, #dev, .backtrace, .xdx, .noprint
+    { display:none; }
+
+    table#body, img { border:0px; }
+}
+
 /* vim: set et ts=4 sts=4 sw=4: */
index 759b0a6..bdf3fb8 100644 (file)
@@ -212,6 +212,18 @@ table.tinybicol td, table.bicol td {
     background: inherit;
 }
 
+table.tinybicol td.error, table.bicol td.error {
+    background: #faa;
+}
+
+table.tinybicol td.warning, table.bicol td.warning {
+    background: #fda;
+}
+
+table.tinybicol td.valid, table.bicol td.valid {
+    background: #afa;
+}
+
 table.tinybicol td, table.bicol td, table.tinybicol tr, table.bicol tr { padding: 4px; }
 
 td.half { width: 50%; padding: 4px; }
index 14acd49..73894fd 100644 (file)
@@ -231,6 +231,18 @@ table.tinybicol td, table.bicol td {
     background: inherit;
 }
 
+table.tinybicol td.error, table.bicol td.error {
+    background: #faa;
+}
+
+table.tinybicol td.warning, table.bicol td.warning {
+    background: #fda;
+}
+
+table.tinybicol td.valid, table.bicol td.valid {
+    background: #afa;
+}
+
 table.tinybicol td, table.bicol td, table.tinybicol tr, table.bicol tr { padding: 4px; }
 
 td.half { width: 50%; padding: 4px; }
index f6ec61c..0682da6 100644 (file)
@@ -201,6 +201,18 @@ table.tinybicol td, table.bicol td {
     padding: 0px 4px;
 }
 
+table.tinybicol td.error, table.bicol td.error {
+    background: #faa;
+}
+
+table.tinybicol td.warning, table.bicol td.warning {
+    background: #fda;
+}
+
+table.tinybicol td.valid, table.bicol td.valid {
+    background: #afa;
+}
+
 td.half { width: 50%; padding: 4px; }
 
 td.titre {
diff --git a/htdocs/css/print.css b/htdocs/css/print.css
deleted file mode 100644 (file)
index d548d4a..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-#body-menu, #body-top, #body-logo, #body-bottom, #dev, .backtrace, .xdx, .noprint
-{ display:none; }
-
-table#body, img { border:0px; }
index fe7a6a6..85fe6a4 100644 (file)
@@ -1,9 +1,7 @@
 # Versioning links
-/0.10.*
-/0.f.*
 /1.*
 
 # jQuery and its plugins are downloaded by the Makefile
 /jquery*.*js
-/ui.*js
+/core.js
 !/jquery.autocomplete.js
diff --git a/htdocs/javascript/do_challenge_response.js b/htdocs/javascript/do_challenge_response.js
deleted file mode 100644 (file)
index 43d551e..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/***************************************************************************
- *  Copyright (C) 2003-2011 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 correctUserName() {
-    var u = document.forms.login.username;
-    // login with no space
-    if (u.value.indexOf(' ') < 0) return true;
-    var mots = u.value.split(' ');
-    // jean paul.du pont -> jean-paul.du-pont
-    if (u.value.indexOf('.') > 0) { u.value = mots.join('-'); return true; }
-    // jean dupont  -> jean.dupont
-    if (mots.length == 2) { u.value = mots[0]+"."+mots[1]; return true; }
-    // jean dupont 2001 -> jean.dupont.2001
-    if (mots.length == 3 && mots[2] > 1920 && mots[2] < 3000) { u.value = mots.join('.'); return true; }
-    // jean de la vallee -> jean.de-la-vallee
-    if (mots[1].toUpperCase() == 'DE') { u.value = mots[0]+"."+mots.join('-').substr(mots[0].length+1); return true; }
-    // jean paul dupont -> jean-paul.dupont
-    if (mots.length == 3 && mots[0].toUpperCase() == 'JEAN') { u.value = mots[0]+"-"+mots[1]+"."+mots[2]; return true; }
-
-    alert('Ton email ne doit pas contenir de blanc.\nLe format standard est\n\nprenom.nom.promotion\n\nSi ton nom ou ton prenom est composé,\nsépare les mots par des -');
-
-    return false;
-}
-
-function doChallengeResponse() {
-
-    if (!correctUserName()) return false;
-
-    var new_pass = hash_encrypt(document.forms.login.password.value);
-    var old_pass = hash_encrypt(document.forms.login.password.value.substr(0, 10));
-
-    str = document.forms.login.username.value + ":" +
-        new_pass + ":" +
-        document.forms.loginsub.challenge.value;
-
-    document.forms.loginsub.response.value = hash_encrypt(str);
-    if (new_pass != old_pass) {
-        document.forms.loginsub.xorpass.value = hash_xor(new_pass, old_pass);
-    }
-    document.forms.loginsub.username.value = document.forms.login.username.value;
-    document.forms.loginsub.remember.value = document.forms.login.remember.checked;
-    document.forms.loginsub.domain.value = document.forms.login.domain.value;
-    document.forms.login.password.value = "";
-    document.forms.loginsub.submit();
-}
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
index 936f430..46266fc 100644 (file)
@@ -37,9 +37,9 @@ function createJobTermsTree(domElement, platalpage, treeid, clickFunc, text_filt
     $(domElement).jstree({
         "core" : {"strings":{"loading":"Chargement ..."}},
         "plugins" : ["themes","json_data"],
-        "themes" : { "url" : platal_baseurl + "css/jstree.css" },
+        "themes" : { "url" : $.plURL("css/jstree.css") },
         "json_data" : { "ajax" : {
-            "url" : platal_baseurl + platalpage,
+            "url" : $.plURL(platalpage),
             "data" : function(nod) {
                 var jtid = 0;
                 if (nod != -1) {
diff --git a/htdocs/javascript/password.js b/htdocs/javascript/password.js
deleted file mode 100644 (file)
index af708a8..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/***************************************************************************
- *  Copyright (C) 2003-2011 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 hashResponse(password1, password2, hasConfirmation) {
-    pw1 = $('[name=' + password1 + ']').val();
-
-    if (hasConfirmation) {
-        pw2 = $('[name=' + password2 + ']').val();
-        if (pw1 != pw2) {
-            alert("\nErreur : les deux champs ne sont pas identiques !");
-            return false;
-        }
-        $('[name=' + password2 + ']').val('');
-    } else if (pw1 == '********') {
-        return true;
-    }
-
-    if (pw1.length < 6) {
-        alert("\nErreur : le nouveau mot de passe doit faire au moins 6 caractères !");
-        return false;
-    }
-    if (!differentTypes(pw1)) {
-        alert ("\nErreur : le nouveau mot de passe doit comporter au moins deux types de caractères parmi les suivants : lettres minuscules, lettres majuscules, chiffres, caractères spéciaux.");
-        return false;
-    }
-
-    alert("Le mot de passe que tu as rentré va être chiffré avant de nous parvenir par Internet ! Ainsi il ne circulera pas en clair.");
-    $('[name=' + password1 + ']').val('');
-    $('[name=pwhash]').val(hash_encrypt(pw1));
-    return true;
-}
-
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
index b70fb06..f0ca309 100644 (file)
@@ -211,7 +211,7 @@ function addEdu()
     i++;
     $('#edu_add').addClass(prefix + i);
     i--;
-    $.get(platal_baseurl + 'profile/ajax/edu/' + i + '/' + class_parity,
+    $.xget('profile/ajax/edu/' + i + '/' + class_parity,
           function(data) {
               $('#edu_add').before(data);
               prepareType(i);
@@ -489,7 +489,7 @@ function makeAddProcess(id)
 function addMedal()
 {
     var id = $('#medals').find('[name=medal_sel]').val();
-    $.get(platal_baseurl + 'profile/ajax/medal/' + id, makeAddProcess(id));
+    $.xget('profile/ajax/medal/' + id, makeAddProcess(id));
 }
 
 function removeMedal(id)
@@ -532,7 +532,7 @@ function addJob()
     while ($('#jobs_' + i).length != 0) {
         ++i;
     }
-    $.get(platal_baseurl + 'profile/ajax/job/' + i, makeAddJob(i));
+    $.xget('profile/ajax/job/' + i, makeAddJob(i));
 }
 
 function addEntreprise(id)
@@ -638,6 +638,8 @@ function selectJobTerm(li)
  */
 function toggleJobTermsTree(jobid, textfilter)
 {
+    $('#term_tree_comment').toggle();
+
     var treepath;
     if (jobid < 0) {
         treepath = '';
@@ -671,7 +673,7 @@ function addSkill(cat)
 {
     var val  = $('#' + cat + '_table').find('[name=' + cat + '_sel]').val();
     var text = $('#' + cat + '_table').find('[name=' + cat + '_sel] :selected').text();
-    $.get(platal_baseurl + 'profile/ajax/skill/' + cat + '/' + val,
+    $.xget('profile/ajax/skill/' + cat + '/' + val,
           function(data) {
               $('#' + cat).append(data);
               $('#' + cat + '_' + val + '_title').text(text);
@@ -701,7 +703,7 @@ function registerEnterpriseAutocomplete(id)
     $(".enterpriseName").each(
       function() {
         if (id == -1 || this.name == "jobs[" + id + "][name]") {
-            $(this).autocomplete(platal_baseurl + "search/autocomplete/entreprise",
+            $(this).autocomplete($.plURL("search/autocomplete/entreprise"),
                                  {
                                      selectOnly:1,
                                      field:this.name,
@@ -714,7 +716,7 @@ function registerEnterpriseAutocomplete(id)
     $(".sectorName").each(
       function() {
         if (id == -1 || this.name == "jobs[" + id + "][subSubSectorName]") {
-            $(this).autocomplete(platal_baseurl + "search/autocomplete/subSubSector",
+            $(this).autocomplete($.plURL("search/autocomplete/subSubSector"),
                                  {
                                      selectOnly:1,
                                      field:this.name,
diff --git a/htdocs/javascript/sha1.js b/htdocs/javascript/sha1.js
deleted file mode 100644 (file)
index a546ee3..0000000
+++ /dev/null
@@ -1,203 +0,0 @@
-/*\r
- * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined\r
- * in FIPS PUB 180-1\r
- * Version 2.1a Copyright Paul Johnston 2000 - 2002.\r
- * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\r
- * Distributed under the BSD License\r
- * See http://pajhome.org.uk/crypt/md5 for details.\r
- */\r
-\r
-/*\r
- * Configurable variables. You may need to tweak these to be compatible with\r
- * the server-side, but the defaults work in most cases.\r
- */\r
-var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */\r
-var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */\r
-var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */\r
-\r
-/*\r
- * These are the functions you'll usually want to call\r
- * They take string arguments and return either hex or base-64 encoded strings\r
- */\r
-function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}\r
-function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}\r
-function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}\r
-function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}\r
-function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}\r
-function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}\r
-\r
-/*\r
- * Perform a simple self-test to see if the VM is working\r
- */\r
-function sha1_vm_test()\r
-{\r
-  return hex_sha1("abc") == "a9993e364706816aba3e25717850c26c9cd0d89d";\r
-}\r
-\r
-/*\r
- * Calculate the SHA-1 of an array of big-endian words, and a bit length\r
- */\r
-function core_sha1(x, len)\r
-{\r
-  /* append padding */\r
-  x[len >> 5] |= 0x80 << (24 - len % 32);\r
-  x[((len + 64 >> 9) << 4) + 15] = len;\r
-\r
-  var w = Array(80);\r
-  var a =  1732584193;\r
-  var b = -271733879;\r
-  var c = -1732584194;\r
-  var d =  271733878;\r
-  var e = -1009589776;\r
-\r
-  for(var i = 0; i < x.length; i += 16)\r
-  {\r
-    var olda = a;\r
-    var oldb = b;\r
-    var oldc = c;\r
-    var oldd = d;\r
-    var olde = e;\r
-\r
-    for(var j = 0; j < 80; j++)\r
-    {\r
-      if(j < 16) w[j] = x[i + j];\r
-      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);\r
-      var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),\r
-                       safe_add(safe_add(e, w[j]), sha1_kt(j)));\r
-      e = d;\r
-      d = c;\r
-      c = rol(b, 30);\r
-      b = a;\r
-      a = t;\r
-    }\r
-\r
-    a = safe_add(a, olda);\r
-    b = safe_add(b, oldb);\r
-    c = safe_add(c, oldc);\r
-    d = safe_add(d, oldd);\r
-    e = safe_add(e, olde);\r
-  }\r
-  return Array(a, b, c, d, e);\r
-\r
-}\r
-\r
-/*\r
- * Perform the appropriate triplet combination function for the current\r
- * iteration\r
- */\r
-function sha1_ft(t, b, c, d)\r
-{\r
-  if(t < 20) return (b & c) | ((~b) & d);\r
-  if(t < 40) return b ^ c ^ d;\r
-  if(t < 60) return (b & c) | (b & d) | (c & d);\r
-  return b ^ c ^ d;\r
-}\r
-\r
-/*\r
- * Determine the appropriate additive constant for the current iteration\r
- */\r
-function sha1_kt(t)\r
-{\r
-  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :\r
-         (t < 60) ? -1894007588 : -899497514;\r
-}\r
-\r
-/*\r
- * Calculate the HMAC-SHA1 of a key and some data\r
- */\r
-function core_hmac_sha1(key, data)\r
-{\r
-  var bkey = str2binb(key);\r
-  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);\r
-\r
-  var ipad = Array(16), opad = Array(16);\r
-  for(var i = 0; i < 16; i++)\r
-  {\r
-    ipad[i] = bkey[i] ^ 0x36363636;\r
-    opad[i] = bkey[i] ^ 0x5C5C5C5C;\r
-  }\r
-\r
-  var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);\r
-  return core_sha1(opad.concat(hash), 512 + 160);\r
-}\r
-\r
-/*\r
- * Add integers, wrapping at 2^32. This uses 16-bit operations internally\r
- * to work around bugs in some JS interpreters.\r
- */\r
-function safe_add(x, y)\r
-{\r
-  var lsw = (x & 0xFFFF) + (y & 0xFFFF);\r
-  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);\r
-  return (msw << 16) | (lsw & 0xFFFF);\r
-}\r
-\r
-/*\r
- * Bitwise rotate a 32-bit number to the left.\r
- */\r
-function rol(num, cnt)\r
-{\r
-  return (num << cnt) | (num >>> (32 - cnt));\r
-}\r
-\r
-/*\r
- * Convert an 8-bit or 16-bit string to an array of big-endian words\r
- * In 8-bit function, characters >255 have their hi-byte silently ignored.\r
- */\r
-function str2binb(str)\r
-{\r
-  var bin = Array();\r
-  var mask = (1 << chrsz) - 1;\r
-  for(var i = 0; i < str.length * chrsz; i += chrsz)\r
-    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);\r
-  return bin;\r
-}\r
-\r
-/*\r
- * Convert an array of big-endian words to a string\r
- */\r
-function binb2str(bin)\r
-{\r
-  var str = "";\r
-  var mask = (1 << chrsz) - 1;\r
-  for(var i = 0; i < bin.length * 32; i += chrsz)\r
-    str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);\r
-  return str;\r
-}\r
-\r
-/*\r
- * Convert an array of big-endian words to a hex string.\r
- */\r
-function binb2hex(binarray)\r
-{\r
-  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";\r
-  var str = "";\r
-  for(var i = 0; i < binarray.length * 4; i++)\r
-  {\r
-    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +\r
-           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);\r
-  }\r
-  return str;\r
-}\r
-\r
-/*\r
- * Convert an array of big-endian words to a base-64 string\r
- */\r
-function binb2b64(binarray)\r
-{\r
-  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";\r
-  var str = "";\r
-  for(var i = 0; i < binarray.length * 4; i += 3)\r
-  {\r
-    var triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)\r
-                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )\r
-                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);\r
-    for(var j = 0; j < 4; j++)\r
-    {\r
-      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;\r
-      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);\r
-    }\r
-  }\r
-  return str;\r
-}\r
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
diff --git a/htdocs/javascript/survey.js b/htdocs/javascript/survey.js
new file mode 100644 (file)
index 0000000..19adaa7
--- /dev/null
@@ -0,0 +1,265 @@
+/***************************************************************************
+ *  Copyright (C) 2003-2011 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($) {
+    var dispatchType = function(method) {
+        return function(type) {
+            var name = type + '_' + method;
+            var args = Array.prototype.slice.call(arguments, 1);
+            if ($.isFunction(this[name])) {
+                return this[name].apply(this, args);
+            }
+            return this;
+        };
+    };
+
+    $.extend({
+        questions: function() {
+            return $('.q_edit:not(#questions)');
+        },
+
+        lastQuestion: function() {
+            return $.questions().last();
+        },
+
+        renumberQuestions: function() {
+            var q = $.questions();
+            q.each(function(idx) {
+                var elt = $(this);
+                var old_id = elt.attr('id');
+                var new_id = 'q_edit[' + idx + ']';
+                var fixAttrs;
+
+                if (old_id === new_id) {
+                    return;
+                }
+
+                fixAttrs = function(attr) {
+                    elt.find('[' + attr + '^="' + old_id + '"]').each(function() {
+                        var cid = $(this).attr(attr);
+                        if (cid.startsWith(old_id)) {
+                            $(this).attr(attr, new_id + cid.substring(old_id.length, cid.length));
+                        }
+                    });
+                };
+                fixAttrs('id');
+                fixAttrs('name');
+                elt.children().children('.q_edit_label').text('Question ' + (idx + 1));
+                elt.attr('id', new_id);
+            });
+        },
+
+        debugPrintQuestions: function() {
+            var q = $.questions();
+            var str = '';
+            q.each(function() {
+                str += $(this).attr('id') + '\n';
+            });
+            alert(str);
+        }
+    });
+
+    $.fn.extend({
+        showQuestions: function(questions) {
+            var data = $('#question_base').tmpl(questions);
+            this.empty();
+            data.appendTo(this);
+            return this;
+        },
+
+        /* Edition form */
+        prepareQuestions: function(questions) {
+            var q, child;
+            for (q in questions) {
+                q = questions[q];
+                child = this.addQuestion(q);
+                if ($.isArray(q.children)) {
+                    child.prepareQuestions(q.children);
+                }
+            }
+            return this;
+        },
+
+        isQuestion: function() {
+            return this.hasClass('q_edit');
+        },
+
+        isRootSection: function() {
+            return this.attr('id') === 'questions';
+        },
+
+        question: function() {
+            return this.isQuestion() ? this : this.parentQuestion();
+        },
+
+        questionForm: function() {
+            return this.question().children('.q_edit_form');
+        },
+
+        qid: function() {
+            var question = this.question();
+            if (typeof question.get(0) === 'undefined') {
+                return;
+            }
+            var id = question.attr('id');
+            if (id.substr(0, 7) !== 'q_edit[') {
+                return;
+            }
+            if (id.charAt(id.length - 1) !== ']') {
+                return;
+            }
+            id = id.substr(7, id.length - 8);
+            return parseInt(id, 10);
+        },
+
+        parentQuestion: function() {
+            return this.parent().closest('.q_edit');
+        },
+
+        childrenContainer: function() {
+            var question = this.question();
+            return question.isRootSection() ? question : question.questionForm().children();
+        },
+
+        childrenQuestion: function() {
+            return this.childrenContainer().children('.q_edit');
+        },
+
+        addQuestion: function(q) {
+            var id = $.lastQuestion().qid();
+            if (!id) {
+                id = 0;
+            } else {
+                id++;
+            }
+            if (!q) {
+                q = { qid: id };
+            }
+            console.log(q);
+            var question = $("#q_edit_new").tmpl(q);
+            var type = question
+                .find('select[name$="[type]"]')
+                .change(function () {
+                    var type = $(this).val();
+                    var form = question.children('.q_edit_form');
+                    var qid = $(this).qid();
+                    form.empty();
+                    if (type) {
+                        $("#q_edit_base").tmpl({ qid: qid, type: type })
+                            .bindQuestion(type, qid)
+                            .appendTo(form);
+                    }
+                    return true;
+                });
+            if (type.val()) {
+                question.children('.q_edit_form')
+                        .bindQuestion(type.val(), q.qid, q)
+            }
+            this.childrenContainer().children('.add_question').before(question);
+            $.renumberQuestions();
+            return question;
+        },
+
+        bindQuestion: dispatchType('bindQuestion'),
+
+        removeQuestion: function(force) {
+            var question = this.parentQuestion();
+            if (!force && question.children('.q_edit_form').children().children('.q_edit').length > 0) {
+                if (!alert('Vous avez demander la suppression d\'une section contenant des questions. '
+                         + 'Ces questions seront supprimées. Etes-vous sur de vouloir continuer ?')) {
+                    return this;
+                }
+            }
+            var res;
+            if (question.isRootSection()) {
+                res = question.empty();
+            } else {
+                res = question.remove();
+            }
+            $.renumberQuestions();
+            return res;
+        },
+
+        buildParentsQuestions: function() {
+            var $this = $(this);
+            $.questions().each(function() {
+                var parent = $(this).parentQuestion();
+                if (!parent.isRootSection()) {
+                    $('<input>', {
+                        type: 'hidden',
+                        name: 'q_edit[' + $(this).qid() + '][parent]',
+                        value: parent.qid()
+                    }).appendTo($this);
+                }
+            });
+            return $this;
+        },
+
+        /* Multiple choices questions */
+        multiple_selectSubtype: function() {
+            return this.find('select[name$="[subtype]"]');
+        },
+
+        multiple_bindQuestion: function(id, parameters) {
+            var $question = this;
+            var answer;
+            var value;
+            this.multiple_selectSubtype()
+                .assertLength(1)
+                .change(function() {
+                    $question.find('.q_edit_answer_box')
+                        .empty()
+                        .append($('<input>', {
+                            type: $(this).val(),
+                            disabled: "disabled"
+                        }));
+                });
+            if (parameters) {
+                for (answer = 0; answer < parameters.answers.length; answer++) {
+                    this.multiple_addAnswer(parameters.answers[answer]);
+                }
+            }
+            return this;
+        },
+
+        multiple_addAnswer: function(value) {
+            var question = this.question();
+            var answer = $("#q_edit_multiple_answer").tmpl({ qid: question.qid(), value: value });
+            question.childrenContainer().children('.add_answer').before(answer);
+            question.multiple_selectSubtype().change();
+            return answer;
+        },
+
+        multiple_removeAnswer: function() {
+            return this.parent().remove();
+        }
+    });
+}(jQuery));
+
+
+$(function() {
+    $(".datepicker").datepicker({
+        hideIfNoPrevNext: true,
+        minDate: new Date()
+    });
+});
+
+
+// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
diff --git a/htdocs/javascript/wiki.js b/htdocs/javascript/wiki.js
deleted file mode 100644 (file)
index b1bf1a6..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/***************************************************************************
- *  Copyright (C) 2003-2011 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                *
- ***************************************************************************/
-
-
-Nix = {
-  map: null,
-  convert: function(a) {
-      Nix.init();
-      var s = '';
-      for (i = 0; i < a.length ; i++) {
-          var b = a.charAt(i);
-          s += ((b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') ? Nix.map[b] : b);
-      }
-      return s;
-  },
-  init: function() {
-            if (Nix.map != null)
-                return;
-            var map = new Array();
-            var s='abcdefghijklmnopqrstuvwxyz';
-            for (i = 0; i < s.length; i++)
-                map[s.charAt(i)] = s.charAt((i+13)%26);
-            for (i=0; i<s.length; i++)map[s.charAt(i).toUpperCase()] = s.charAt((i+13)%26).toUpperCase();
-            Nix.map = map;
-        },
-  decode: function(a) {
-              document.write(Nix.convert(a));
-          }
-}
-
-// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
index 8805ed4..7ed0138 100644 (file)
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-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']
+              'août', 'septembre', 'octobre', 'novembre', 'décembre'];
 
 function getNow() {
     var dt = new Date();
@@ -31,13 +29,16 @@ function getNow() {
     var mh = dt.getMonth();
     var wd = dt.getDate();
     var yr = dt.getYear();
-    if (yr<1000) yr += 1900;
     var hr = dt.getHours();
     var mi = dt.getMinutes();
+    var se = dt.getSeconds();
+
+    if (yr<1000) {
+        yr += 1900;
+    }
     if (mi < 10) {
         mi = '0' + mi;
     }
-    var se = dt.getSeconds();
     if (se < 10) {
         se = '0' + se;
     }
@@ -51,8 +52,8 @@ function getNow() {
 
 function canAddSearchEngine()
 {
-    if (((typeof window.sidebar == "object") && $.isFunction(window.sidebar.addSearchEngine))
-        || ((typeof window.external == "object") && $.isFunction(window.external.AddSearchProvider))) {
+    if (((typeof window.sidebar === "object") && $.isFunction(window.sidebar.addSearchEngine))
+        || ((typeof window.external === "object") && $.isFunction(window.external.AddSearchProvider))) {
         return true;
     }
     return false;
@@ -61,7 +62,7 @@ function canAddSearchEngine()
 function addSearchEngine()
 {
     var searchURI = "http://www.polytechnique.org/xorg.opensearch.xml";
-    if ((typeof window.sidebar == "object") && $.isFunction(window.sidebar.addSearchEngine)) {
+    if ((typeof window.sidebar === "object") && $.isFunction(window.sidebar.addSearchEngine)) {
         window.sidebar.addSearchEngine(
             searchURI,
             "http://www.polytechnique.org/images/xorg.png",
@@ -77,53 +78,6 @@ function addSearchEngine()
 }
 
 // }}}
-// {{{ dynpost()
-
-function dynpost(action, values)
-{
-    var form = document.createElement('form');
-    form.action = action;
-    form.method = 'post';
-
-    $('body').get(0).appendChild(form);
-
-    for (var k in values) {
-        var input = document.createElement('input');
-        input.type = 'hidden';
-        input.name = k;
-        input.value = values[k];
-        form.appendChild(input);
-    }
-
-    form.submit();
-}
-
-
-function dynpostkv(action, k, v)
-{
-    var dict = {};
-    dict[k] = v;
-    dynpost(action, dict);
-}
-
-// }}}
-// {{{ function RegExp.escape()
-
-RegExp.escape = function(text) {
-  if (!arguments.callee.sRE) {
-    var specials = [
-      '/', '.', '*', '+', '?', '|',
-      '(', ')', '[', ']', '{', '}',
-      '\\', '^' , '$'
-    ];
-    arguments.callee.sRE = new RegExp(
-      '(\\' + specials.join('|\\') + ')', 'g'
-    );
-  }
-  return text.replace(arguments.callee.sRE, '\\$1');
-}
-
-// }}}
 
 /***************************************************************************
  * POPUP THINGS
@@ -131,72 +85,76 @@ RegExp.escape = function(text) {
 
 // {{{ function goodiesPopup()
 
-var __goodies_active = true;
-
-var __goodies_ical = {
-    default_title: 'Calendrier iCal',
-    sites: [
-        {'url_prefix': '',
-         'img': 'images/icons/calendar_view_day.gif',
-         'title': 'Calendrier iCal'},
-        {'url_prefix': 'http://www.google.com/calendar/render?cid=',
-         'img': 'images/goodies/add-google-calendar.gif',
-         'title': 'Ajouter à Google Calendar'},
-        {'url_prefix': 'https://www.google.com/calendar/hosted/polytechnique.org/render?cid=',
-         'img': 'images/goodies/add-google-calendar.gif',
-         'title': 'Ajouter à Google Apps / Calendar'}
-    ]
-};
-
-var __goodies_rss = {
-    default_title: 'Fils RSS',
-    sites: [
-        {'url_prefix': '',
-         'img': 'images/icons/feed.gif',
-         'title': 'Fil rss'},
-        {'url_prefix': 'http://fusion.google.com/add?feedurl=',
-         'img': 'images/goodies/add-google.gif',
-         'alt': 'Add to Google',
-         'title': 'Ajouter à iGoogle/Google Reader'},
-        {'url_prefix': 'http://www.netvibes.com/subscribe.php?url=',
-         'img': 'images/goodies/add-netvibes.gif',
-         'title': 'Ajouter à Netvibes'},
-        {'url_prefix': 'http://add.my.yahoo.com/content?.intl=fr&url=',
-         'img': 'images/goodies/add-yahoo.gif',
-         'alt': 'Add to My Yahoo!',
-         'title': 'Ajouter à My Yahoo!'}
-    ]
-};
-
-function disableGoodiesPopups() {
-    __goodies_active = false;
-}
-
-function goodiesPopup(node, goodies) {
-    var text = '<div style="text-align: center; line-height: 2.2">';
-    for (var site in goodies.sites) {
-        var entry = goodies.sites[site];
-        var s_alt   = entry["alt"] ? entry["alt"] : "";
-        var s_img   = entry["img"];
-        var s_title = entry["title"] ? entry["title"] : "";
-        var s_url   = entry["url_prefix"].length > 0 ? entry["url_prefix"] + escape(this.href) : this.href;
-
-        text += '<a href="' + s_url + '"><img src="' + s_img + '" title="' + s_title + '" alt="' + s_alt + '"></a><br />';
-    }
-    text += '<a href="https://www.polytechnique.org/Xorg/Goodies">Plus de bonus</a> ...</div>';
+(function($) {
+    var goodies = {
+        ical: {
+            default_title: 'Calendrier iCal',
+            sites: [
+                {url_prefix: '',
+                 img: 'images/icons/calendar_view_day.gif',
+                 title: 'Calendrier iCal'},
+                {url_prefix: 'http://www.google.com/calendar/render?cid=',
+                 img: 'images/goodies/add-google-calendar.gif',
+                 title: 'Ajouter à Google Calendar'},
+                {url_prefix: 'https://www.google.com/calendar/hosted/polytechnique.org/render?cid=',
+                 img: 'images/goodies/add-google-calendar.gif',
+                 title: 'Ajouter à Google Apps / Calendar'}
+            ]
+        },
 
-    var title = node.title ? node.title : goodies.default_title;
+        rss: {
+            default_title: 'Fils RSS',
+            sites: [
+                {url_prefix: '',
+                 img: 'images/icons/feed.gif',
+                 title: 'Fil rss'},
+                {url_prefix: 'http://fusion.google.com/add?feedurl=',
+                 img: 'images/goodies/add-google.gif',
+                 alt: 'Add to Google',
+                 title: 'Ajouter à iGoogle/Google Reader'},
+                {url_prefix: 'http://www.netvibes.com/subscribe.php?url=',
+                 img: 'images/goodies/add-netvibes.gif',
+                 title: 'Ajouter à Netvibes'},
+                {url_prefix: 'http://add.my.yahoo.com/content?.intl=fr&url=',
+                 img: 'images/goodies/add-yahoo.gif',
+                 alt: 'Add to My Yahoo!',
+                 title: 'Ajouter à My Yahoo!'}
+            ]
+        }
+    };
 
-    $(node)
-        .mouseover(
-            function() {
-                if (__goodies_active) {
-                    return overlib(text, CAPTION, title, CLOSETEXT, 'Fermer', DELAY, 800, STICKY, WIDTH, 150);
+    $.fn.extend({
+        goodiesPopup: function goodiesPopup(type) {
+            var text = '<div style="text-align: center; line-height: 2.2">';
+            var site;
+            var entry;
+            var s_alt;
+            var s_img;
+            var s_title;
+            var s_url;
+
+            for (site in goodies[type].sites) {
+                entry = goodies[type].sites[site];
+                s_alt   = entry.alt || "";
+                s_img   = entry.img;
+                s_title = entry.title || "";
+                s_url   = entry.url_prefix.length > 0 ? entry.url_prefix + escape(this.href) : this.href;
+
+                text += '<a href="' + s_url + '"><img src="' + s_img + '" title="' + s_title + '" alt="' + s_alt + '"></a><br />';
                 }
-            }
-        )
-        .mouseout(nd);
-}
+            text += '<a href="https://www.polytechnique.org/Xorg/Goodies">Plus de bonus</a> ...</div>';
+
+            return this.overlib({
+                text: text,
+                caption: this.attr('title') || goodies.default_title,
+                close_text: 'Fermer',
+                delay: 800,
+                sticky: true,
+                width: 150
+            });
+        }
+    });
+}(jQuery));
 
 // }}}
 // {{{ function auto_links()
@@ -204,43 +162,47 @@ function goodiesPopup(node, goodies) {
 function auto_links() {
     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);
+    var light = url.indexOf('display=light') > url.indexOf('?');
+    var resource_page = url.contains('rss') || url.contains('ical');
 
     $("a,link").each(function(i) {
         var node = $(this);
         var href = this.href;
+        var matches;
+        var rss;
+        var ical;
+
         if(!href || node.hasClass('xdx')
-           || href.indexOf('mailto:') > -1 || href.indexOf('javascript:') > -1) {
+           || href.startsWith('mailto:') || href.startsWith('javascript:')) {
             return;
         }
-        if ((href.indexOf(fqdn) < 0 && this.className.indexOf('popup') < 0) || node.hasClass('popup')) {
+        if ((!href.contains(fqdn) && !this.className.contains('popup')) || node.hasClass('popup')) {
             node.click(function () {
                 window.open(href);
                 return false;
             });
         }
-        if (href.indexOf(fqdn) > -1 && light) {
+        if (href.contains(fqdn) && light) {
             href = href.replace(/([^\#\?]*)\??([^\#]*)(\#.*)?/, "$1?display=light&$2$3");
             this.href = href;
         }
-        var rss  = href.indexOf('rss') > -1;
-        var ical = href.indexOf('ical') > -1;
+        rss  = href.contains('rss');
+        ical = href.contains('ical');
         if (rss || ical) {
-            if (href.indexOf('http') < 0) {
+            if (!href.startsWith('http')) {
                 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);
+        if (this.nodeName.toLowerCase() === 'a' && !resource_page) {
+            if (rss && !href.contains('prefs/rss') && (href.contains('xml') || href.contains('hash'))) {
+                node.goodiesPopup('rss');
             } else if (ical) {
-                goodiesPopup(this, __goodies_ical);
+                node.goodiesPopup('ical');
             }
         }
-        if(matches = (/^popup_([0-9]*)x([0-9]*)$/).exec(this.className)) {
-            var w = matches[1], h = matches[2];
-            node.popWin(w, h);
+        matches = /^popup_([0-9]*)x([0-9]*)$/.exec(this.className);
+        if (matches) {
+            node.popWin(matches[1], matches[2]);
         }
     });
     $('.popup2').popWin(840, 600);
@@ -256,6 +218,257 @@ function auto_links() {
 
 // {{{ function checkPassword
 
+/* {{{ SHA1 Implementation */
+
+/*
+ * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
+ * in FIPS PUB 180-1
+ * Version 2.1a Copyright Paul Johnston 2000 - 2002.
+ * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
+ * Distributed under the BSD License
+ * See http://pajhome.org.uk/crypt/md5 for details.
+ */
+
+/*
+ * Configurable variables. You may need to tweak these to be compatible with
+ * the server-side, but the defaults work in most cases.
+ */
+var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
+var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
+var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */
+
+/*
+ * These are the functions you'll usually want to call
+ * They take string arguments and return either hex or base-64 encoded strings
+ */
+function hex_sha1(s){return binb2hex(core_sha1(str2binb(s),s.length * chrsz));}
+function b64_sha1(s){return binb2b64(core_sha1(str2binb(s),s.length * chrsz));}
+function str_sha1(s){return binb2str(core_sha1(str2binb(s),s.length * chrsz));}
+function hex_hmac_sha1(key, data){ return binb2hex(core_hmac_sha1(key, data));}
+function b64_hmac_sha1(key, data){ return binb2b64(core_hmac_sha1(key, data));}
+function str_hmac_sha1(key, data){ return binb2str(core_hmac_sha1(key, data));}
+
+/*
+ * Perform a simple self-test to see if the VM is working
+ */
+function sha1_vm_test()
+{
+  return hex_sha1("abc") === "a9993e364706816aba3e25717850c26c9cd0d89d";
+}
+
+/*
+ * Calculate the SHA-1 of an array of big-endian words, and a bit length
+ */
+function core_sha1(x, len)
+{
+  var w, a, b, c, d, e;
+  var olda, oldb, oldc, oldd, olde;
+  var i, j, t;
+
+  /* append padding */
+  x[len >> 5] |= 0x80 << (24 - len % 32);
+  x[((len + 64 >> 9) << 4) + 15] = len;
+
+  w = Array(80);
+  a =  1732584193;
+  b = -271733879;
+  c = -1732584194;
+  d =  271733878;
+  e = -1009589776;
+
+  for(i = 0; i < x.length; i += 16)
+  {
+    olda = a;
+    oldb = b;
+    oldc = c;
+    oldd = d;
+    olde = e;
+
+    for(j = 0; j < 80; j++)
+    {
+      if(j < 16) w[j] = x[i + j];
+      else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
+      t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
+                       safe_add(safe_add(e, w[j]), sha1_kt(j)));
+      e = d;
+      d = c;
+      c = rol(b, 30);
+      b = a;
+      a = t;
+    }
+
+    a = safe_add(a, olda);
+    b = safe_add(b, oldb);
+    c = safe_add(c, oldc);
+    d = safe_add(d, oldd);
+    e = safe_add(e, olde);
+  }
+  return Array(a, b, c, d, e);
+
+}
+
+/*
+ * Perform the appropriate triplet combination function for the current
+ * iteration
+ */
+function sha1_ft(t, b, c, d)
+{
+  if(t < 20) return (b & c) | ((~b) & d);
+  if(t < 40) return b ^ c ^ d;
+  if(t < 60) return (b & c) | (b & d) | (c & d);
+  return b ^ c ^ d;
+}
+
+/*
+ * Determine the appropriate additive constant for the current iteration
+ */
+function sha1_kt(t)
+{
+  return (t < 20) ?  1518500249 : (t < 40) ?  1859775393 :
+         (t < 60) ? -1894007588 : -899497514;
+}
+
+/*
+ * Calculate the HMAC-SHA1 of a key and some data
+ */
+function core_hmac_sha1(key, data)
+{
+  var bkey = str2binb(key);
+  var i, ipad, opad;
+  var hash;
+
+  if(bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);
+
+  ipad = Array(16);
+  opad = Array(16);
+  for(i = 0; i < 16; i++)
+  {
+    ipad[i] = bkey[i] ^ 0x36363636;
+    opad[i] = bkey[i] ^ 0x5C5C5C5C;
+  }
+
+  hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
+  return core_sha1(opad.concat(hash), 512 + 160);
+}
+
+/*
+ * Add integers, wrapping at 2^32. This uses 16-bit operations internally
+ * to work around bugs in some JS interpreters.
+ */
+function safe_add(x, y)
+{
+  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
+  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+  return (msw << 16) | (lsw & 0xFFFF);
+}
+
+/*
+ * Bitwise rotate a 32-bit number to the left.
+ */
+function rol(num, cnt)
+{
+  return (num << cnt) | (num >>> (32 - cnt));
+}
+
+/*
+ * Convert an 8-bit or 16-bit string to an array of big-endian words
+ * In 8-bit function, characters >255 have their hi-byte silently ignored.
+ */
+function str2binb(str)
+{
+  var bin = Array();
+  var mask = (1 << chrsz) - 1;
+  var i;
+  for(i = 0; i < str.length * chrsz; i += chrsz)
+    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i%32);
+  return bin;
+}
+
+/*
+ * Convert an array of big-endian words to a string
+ */
+function binb2str(bin)
+{
+  var str = "";
+  var mask = (1 << chrsz) - 1;
+  var i;
+  for(i = 0; i < bin.length * 32; i += chrsz)
+    str += String.fromCharCode((bin[i>>5] >>> (32 - chrsz - i%32)) & mask);
+  return str;
+}
+
+/*
+ * Convert an array of big-endian words to a hex string.
+ */
+function binb2hex(binarray)
+{
+  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
+  var str = "";
+  var i;
+  for(i = 0; i < binarray.length * 4; i++)
+  {
+    str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
+           hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8  )) & 0xF);
+  }
+  return str;
+}
+
+/*
+ * Convert an array of big-endian words to a base-64 string
+ */
+function binb2b64(binarray)
+{
+  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+  var str = "";
+  var i, j, triplet;
+  for(i = 0; i < binarray.length * 4; i += 3)
+  {
+    triplet = (((binarray[i   >> 2] >> 8 * (3 -  i   %4)) & 0xFF) << 16)
+                | (((binarray[i+1 >> 2] >> 8 * (3 - (i+1)%4)) & 0xFF) << 8 )
+                |  ((binarray[i+2 >> 2] >> 8 * (3 - (i+2)%4)) & 0xFF);
+    for(j = 0; j < 4; j++)
+    {
+      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
+      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
+    }
+  }
+  return str;
+}
+
+/* }}} */
+
+function hash_encrypt(a) {
+    return hex_sha1(a);
+}
+
+var hexa_h = "0123456789abcdef";
+
+function dechex(a) {
+    return hexa_h.charAt(a);
+}
+
+function hexdec(a) {
+    return hexa_h.indexOf(a);
+}
+
+function hash_xor(a, b) {
+    var c,i,j,k,d;
+    c = "";
+    i = a.length;
+    j = b.length;
+    if (i < j) {
+        d = a; a = b; b = d;
+        k = i; i = j; j = k;
+    }
+    for (k = 0; k < j; k++) {
+        c += dechex(hexdec(a.charAt(k)) ^ hexdec(b.charAt(k)));
+    }
+    for (; k < i; k++) {
+        c += a.charAt(k);
+    }
+    return c;
+}
+
 function getType(c) {
     if (c >= 'a' && c <= 'z') {
         return 1;
@@ -270,10 +483,11 @@ function getType(c) {
 
 function differentTypes(password) {
     var prev = 0;
+    var type;
 
     for (i = 0 ; i < password.length ; ++i) {
-        var type = getType(password.charAt(i));
-        if (prev != 0 && prev != type) {
+        type = getType(password.charAt(i));
+        if (prev !== 0 && prev !== type) {
             return true;
         }
         prev = type;
@@ -286,15 +500,16 @@ function passwordStrength(password) {
     var prev = 0;
     var firstType = true;
     var types = Array(0, 0, 0, 0, 0);
+    var type;
 
     for (i = 0 ; i < password.length ; ++i) {
-        var type = getType(password.charAt(i));
-        if (prev != 0 && prev != type) {
+        type = getType(password.charAt(i));
+        if (prev !== 0 && prev !== type) {
             prop += 5;
             firstType = false;
         }
         prop += i;
-        if (types[type] == 0 && !firstType) {
+        if (types[type] === 0 && !firstType) {
             prop += 15;
         }
         types[type]++;
@@ -318,6 +533,7 @@ function passwordStrength(password) {
 function checkPassword(box, okLabel) {
     var password = box.value;
     var prop = passwordStrength(password);
+    var submitButton;
 
     if (prop >= 60) {
         color = "#4f4";
@@ -339,7 +555,7 @@ function checkPassword(box, okLabel) {
                     }, 750)
            .parent().stop()
                     .animate({ backgroundColor: bgcolor }, 750);
-    var submitButton = $(":submit[name='" + passwordprompt_submit + "']");
+    submitButton = $(":submit[name='" + passwordprompt_submit + "']");
     if (ok && password.length >= 6 && differentTypes(password)) {
         submitButton.attr("value", okLabel);
         submitButton.removeAttr("disabled");
@@ -349,6 +565,129 @@ function checkPassword(box, okLabel) {
     }
 }
 
+function hashResponse(password1, password2, hasConfirmation) {
+    var pw1 = $('[name=' + password1 + ']').val();
+    var pw2;
+
+    if (hasConfirmation) {
+        pw2 = $('[name=' + password2 + ']').val();
+        if (pw1 !== pw2) {
+            alert("\nErreur : les deux champs ne sont pas identiques !");
+            return false;
+        }
+        $('[name=' + password2 + ']').val('');
+    } else if (pw1 === '********') {
+        return true;
+    }
+
+    if (pw1.length < 6) {
+        alert("\nErreur : le nouveau mot de passe doit faire au moins 6 caractères !");
+        return false;
+    }
+    if (!differentTypes(pw1)) {
+        alert ("\nErreur : le nouveau mot de passe doit comporter au moins deux types de caractères parmi les suivants : lettres minuscules, lettres majuscules, chiffres, caractères spéciaux.");
+        return false;
+    }
+
+    alert("Le mot de passe que tu as rentré va être chiffré avant de nous parvenir par Internet ! Ainsi il ne circulera pas en clair.");
+    $('[name=' + password1 + ']').val('');
+    $('[name=pwhash]').val(hash_encrypt(pw1));
+    return true;
+}
+
+function correctUserName() {
+    var u = document.forms.login.username;
+    var mots;
+
+    // login with no space
+    if (!u.value.contains(' ')) {
+        return true;
+    }
+    mots = u.value.split(' ');
+    // jean paul.du pont -> jean-paul.du-pont
+    if (u.value.contains('.')) {
+        u.value = mots.join('-');
+        return true;
+    }
+    // jean dupont  -> jean.dupont
+    if (mots.length === 2) {
+        u.value = mots[0] + "." + mots[1];
+        return true;
+    }
+    // jean dupont 2001 -> jean.dupont.2001
+    if (mots.length === 3 && mots[2] > 1920 && mots[2] < 3000) {
+        u.value = mots.join('.');
+        return true;
+    }
+    // jean de la vallee -> jean.de-la-vallee
+    if (mots[1].toUpperCase() === 'DE') {
+        u.value = mots[0] + "." + mots.join('-').substr(mots[0].length+1);
+        return true;
+    }
+    // jean paul dupont -> jean-paul.dupont
+    if (mots.length === 3 && mots[0].toUpperCase() === 'JEAN') {
+        u.value = mots[0] + "-" + mots[1] + "." + mots[2];
+        return true;
+    }
+
+    alert('Ton email ne doit pas contenir de blanc.\nLe format standard est\n\nprenom.nom.promotion\n\nSi ton nom ou ton prenom est composé,\nsépare les mots par des -');
+
+    return false;
+}
+
+function doChallengeResponse() {
+    var new_pass, old_pass, str;
+
+    if (!correctUserName()) {
+        return false;
+    }
+
+    new_pass = hash_encrypt(document.forms.login.password.value);
+    old_pass = hash_encrypt(document.forms.login.password.value.substr(0, 10));
+
+    str = document.forms.login.username.value + ":" +
+        new_pass + ":" +
+        document.forms.loginsub.challenge.value;
+
+    document.forms.loginsub.response.value = hash_encrypt(str);
+    if (new_pass !== old_pass) {
+        document.forms.loginsub.xorpass.value = hash_xor(new_pass, old_pass);
+    }
+    document.forms.loginsub.username.value = document.forms.login.username.value;
+    document.forms.loginsub.remember.value = document.forms.login.remember.checked;
+    document.forms.loginsub.domain.value = document.forms.login.domain.value;
+    document.forms.login.password.value = "";
+    document.forms.loginsub.submit();
+}
+
+function doChallengeResponseLogged() {
+    var str = document.forms.loginsub.username.value + ":" +
+        hash_encrypt(document.forms.login.password.value) + ":" +
+        document.forms.loginsub.challenge.value;
+
+    document.forms.loginsub.response.value = hash_encrypt(str);
+    document.forms.loginsub.remember.value = document.forms.login.remember.checked;
+    document.forms.login.password.value = "";
+    document.forms.loginsub.submit();
+}
+
+// }}}
+// {{{ send test email
+
+function sendTestEmail(token, hruid)
+{
+    var url = 'emails/test';
+    var msg = "Un email a été envoyé avec succès";
+    if (hruid) {
+        url += '/' + hruid;
+        msg += " sur l'adresse de " + hruid + ".";
+    } else {
+        msg += " sur ton addresse.";
+    }
+    $('#mail_sent').successMessage($url + '?token=' + token, msg);
+    return false;
+}
+
 // }}}
 // {{{ jQuery object extension
 
@@ -513,10 +852,67 @@ function sendTestEmail(token, hruid)
 
 
 /***************************************************************************
+ * Overlib made simple
+ */
+
+(function($) {
+    $.fn.extend({
+        overlib: function(text, width, height) {
+            var args = [ ];
+            var key;
+
+            if (typeof text === 'string') {
+                args.push(text);
+                if (width) {
+                    args.push(width);
+                }
+                if (height) {
+                    args.push(height);
+                }
+            } else {
+                for (key in text) {
+                    switch (key) {
+                      case 'text':
+                        args.unshift(text[key]);
+                        break;
+                      case 'caption':
+                        args.push(CAPTION, text[key]);
+                        break;
+                      case 'close_text':
+                        args.push(CLOSETEXT, text[key]);
+                        break;
+                      case 'delay':
+                        args.push(DELAY, text[key]);
+                        break;
+                      case 'sticky':
+                        if (text[key]) {
+                            args.push(STICKY);
+                        }
+                        break;
+                      case 'width':
+                        args.push(WIDTH, text[key]);
+                        break;
+                      case 'height':
+                        args.push(HEIGHT, text[key]);
+                        break;
+                    }
+                }
+            }
+            return this
+                .mouseover(function () {
+                    return overlib.apply(null, args);
+                })
+                .mouseout(nd);
+        }
+    });
+}(jQuery));
+
+
+/***************************************************************************
  * The real OnLoad
  */
 
-$(document).ready(function() {
+$(function() {
     auto_links();
     getNow();
     setInterval(getNow, 1000);
index 74bd27f..e81fd2b 100644 (file)
@@ -147,7 +147,7 @@ class ForumsBanana extends Banana
         } else {
             // Register custom Banana links and tabs
             if (!Banana::$profile['autoup']) {
-                Banana::$page->registerAction('<a href=\'javascript:dynpostkv("'
+                Banana::$page->registerAction('<a href=\'javascript:$.dynPost("'
                                     . $platal->path . '", "updateall", ' . time() . ')\'>'
                                     . 'Marquer tous les messages comme lus'
                                     . '</a>', array('forums', 'thread', 'message'));
index a3c26fd..f34e3b8 100644 (file)
@@ -150,7 +150,7 @@ class Company
 
     public function setPhone(Phone &$phone)
     {
-        if ($phone->linkType() == Phone::LINK_COMPANY && $phone->linkId() == $this->id) {
+        if ($phone->link_type == Phone::LINK_COMPANY && $phone->link_id == $this->id) {
             $this->phone = $phone;
         }
     }
@@ -223,7 +223,7 @@ class Job
 
     public function addPhone(Phone &$phone)
     {
-        if ($phone->linkType() == Phone::LINK_JOB && $phone->linkId() == $this->id && $phone->pid() == $this->pid) {
+        if ($phone->link_type == Phone::LINK_JOB && $phone->link_id == $this->id && $phone->pid == $this->pid) {
             $this->phones[$phone->uniqueId()] = $phone;
         }
     }
@@ -544,10 +544,10 @@ class ProfileAddresses extends ProfileField
         $p = $phones->get(Profile::PHONE_LINK_ADDRESS | Profile::PHONE_TYPE_ANY);
         foreach ($p as $phone) {
             /* We must iterate on the addresses because id is not uniq thus,
-             * $this->addresse[$phone->linkId()] is invalid.
+             * $this->addresse[$phone->link_id] is invalid.
              */
             foreach ($this->addresses as $address) {
-                if ($address->type == Address::LINK_PROFILE && $address->id == $phone->linkId()) {
+                if ($address->type == Address::LINK_PROFILE && $address->id == $phone->link_id) {
                     $address->addPhone($phone);
                 }
             }
@@ -634,8 +634,8 @@ class ProfileJobs extends ProfileField
     {
         $p = $phones->get(Profile::PHONE_LINK_JOB | Profile::PHONE_TYPE_ANY);
         foreach ($p as $phone) {
-            if ($phone->linkType() == Phone::LINK_JOB && array_key_exists($phone->linkId(), $this->jobs)) {
-                $this->jobs[$phone->linkId()]->addPhone($phone);
+            if ($phone->link_type == Phone::LINK_JOB && array_key_exists($phone->link_id, $this->jobs)) {
+                $this->jobs[$phone->link_id]->addPhone($phone);
             }
         }
     }
@@ -756,7 +756,7 @@ class CompanyList
         if (count($newcompanies)) {
             $it = Phone::iterate(array(), array(Phone::LINK_COMPANY), $newcompanies);
             while ($phone = $it->next()) {
-                self::$companies[$phone->linkId()]->setPhone($phone);
+                self::$companies[$phone->link_id]->setPhone($phone);
             }
         }
 
index 2c39237..b3233e1 100644 (file)
@@ -1114,6 +1114,32 @@ class UFBF_SubAdminArea extends UFBF_Index
 }
 // }}}
 
+// {{{ class UFBF_SubAdminArea
+class UFBF_SubAdminArea extends UFBF_Index
+{
+    protected $direnum = DirEnum::SUBADMINAREAS;
+    protected $onlycurrentfield;
+
+    public function __construct($envfield, $formtext = '', $onlycurrentfield = 'only_current')
+    {
+        parent::__construct($envfield, $formtext);
+        $this->onlycurrentfield = $onlycurrentfield;
+    }
+
+
+    protected function buildUFC(UserFilterBuilder &$ufb)
+    {
+        if ($ufb->isOn($this->onlycurrentfield)) {
+            $flags = UFC_Address::FLAG_CURRENT;
+        } else {
+            $flags = UFC_Address::FLAG_ANY;
+        }
+
+        return new UFC_AddressField($this->val, UFC_AddressField::FIELD_SUBADMAREA, UFC_Address::TYPE_ANY, $flags);
+    }
+}
+// }}}
+
 // {{{ class UFBF_JobCompany
 class UFBF_JobCompany extends UFBF_Text
 {
index e7b2b4d..4be1f5e 100644 (file)
@@ -82,17 +82,23 @@ class ListeReq extends Validate
         global $globals;
 
         if (Env::has('listname')) {
-            $this->liste = trim(Env::v('listname'));
+            $this->liste = Post::t('listname');
         }
         if (Env::has('domainname')) {
-            $this->domain = trim(Env::v('domainname'));
+            $this->domain = Post::t('domainname');
         }
         if (Env::has('assotype')) {
-            $this->asso = trim(Env::v('assotype'));
+            $this->asso = Post::t('assotype');
         }
         if (!$this->asso) {
             $this->domain = $globals->mail->domain;
         }
+        foreach ($this->owners as $key => &$email) {
+            $email = Post::t('owners_' . $key);
+        }
+        foreach ($this->members as $key => &$email) {
+            $email = Post::t('members_' . $key);
+        }
         return true;
     }
 
index ca37a62..758714e 100644 (file)
@@ -90,16 +90,15 @@ class VCard extends PlVCard
                                 null, $adr->administrativeArea, null,
                                 $adr->hasFlag('current'), $adr->hasFlag('mail'), $adr->hasFlag('mail'));
             } else {
-                // TODO : find a way to fetch only the "street" part of the address
-                $group = $entry->addHome($adr->text, null, null, $adr->postalCode,
+                $group = $entry->addHome(trim(Geocoder::getFirstLines($adr->text, $adr->postalCode, 4)), null, null, $adr->postalCode,
                                 $adr->locality, $adr->administrativeArea, $adr->country,
                                 $adr->hasFlag('current'), $adr->hasFlag('mail'), $adr->hasFlag('mail'));
             }
             foreach ($adr->phones() as $phone) {
-                if ($phone->linkType() == Phone::TYPE_FIXED) {
+                if ($phone->link_type == Phone::TYPE_FIXED) {
                     $entry->addTel($group, $phone->display, false, true, true, false, false,
                                    $adr->hasFlag('current') && empty($pf->mobile));
-                } else if ($phone->linkType() == Phone::TYPE_FAX) {
+                } else if ($phone->link_type == Phone::TYPE_FAX) {
                     $entry->addTel($group, $phone->display, true, false, false, false, false, false);
                 }
             }
@@ -115,13 +114,13 @@ class VCard extends PlVCard
             } else {
                 // TODO : link address to company
                 $group = $entry->addWork(null, null, null, null,
-                                         $adr->text, null, null, $adr->postalCode,
+                                         trim(Geocoder::getFirstLines($adr->text, $adr->postalCode, 4)), null, null, $adr->postalCode,
                                          $adr->locality, $adr->administrativeArea, $adr->country);
             }
             foreach ($adr->phones() as $phone) {
-                if ($phone->linkType() == Phone::TYPE_FIXED) {
+                if ($phone->link_type == Phone::TYPE_FIXED) {
                     $entry->addTel($group, $phone->display);
-                } else if ($phone->linkType() == Phone::TYPE_FAX) {
+                } else if ($phone->link_type == Phone::TYPE_FAX) {
                     $entry->addTel($group, $phone->display, true);
                 }
             }
@@ -130,14 +129,14 @@ class VCard extends PlVCard
         // Melix
         if (!is_null($user)) {
             $alias = $user->emailAlias();
-            if (!is_null($alias) && $pf->alias_pub == 'pub') {
+            if (!is_null($alias) && $pf->alias_pub == 'public') {
                 $entry->addMail(null, $alias);
             }
         }
 
         // Custom fields
         if (!is_null($user)) {
-            $groups = $user->groups();
+            $groups = $user->groups(true, true);
             if (count($groups)) {
                 $gn = DirEnum::getOptions(DirEnum::GROUPESX);
                 $gns = array();
@@ -159,8 +158,7 @@ class VCard extends PlVCard
             $entry->set('X-BINETS', join(', ', $bns));
         }
         if (!empty($pf->section)) {
-            $sections = DirEnum::getOptions(DirEnum::SECTIONS);
-            $entry->set('X-SECTION', $sections[$pf->section]);
+            $entry->set('X-SECTION', $pf->section);
         }
 
         // Photo
index ac2b4ed..c288bee 100644 (file)
@@ -47,6 +47,7 @@ class AdminModule extends PLModule
             'admin/wiki'                   => $this->make_hook('wiki',                   AUTH_MDP, 'admin'),
             'admin/ipwatch'                => $this->make_hook('ipwatch',                AUTH_MDP, 'admin'),
             'admin/icons'                  => $this->make_hook('icons',                  AUTH_MDP, 'admin'),
+            'admin/geocoding'              => $this->make_hook('geocoding',              AUTH_MDP, 'admin'),
             'admin/accounts'               => $this->make_hook('accounts',               AUTH_MDP, 'admin'),
             'admin/account/watch'          => $this->make_hook('account_watch',          AUTH_MDP, 'admin'),
             'admin/account/types'          => $this->make_hook('account_types',          AUTH_MDP, 'admin'),
@@ -128,23 +129,6 @@ class AdminModule extends PLModule
         $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.
@@ -691,10 +675,7 @@ class AdminModule extends PLModule
         // }}}
 
 
-        $page->addJsLink('jquery.ui.core.js');
-        $page->addJsLink('jquery.ui.widget.js');
-        $page->addJsLink('jquery.ui.tabs.js');
-        $page->addJsLink('password.js');
+        $page->addJsLink('jquery.ui.xorg.js');
 
         // Displays last login and last host information.
         $res = XDB::query("SELECT  start, host
@@ -1207,11 +1188,232 @@ class AdminModule extends PLModule
         $table_editor->apply($page, $action, $id);
     }
 
+    private static function isCountryIncomplete(array &$item)
+    {
+        $warning = false;
+        foreach (array('worldRegion', 'country', 'capital', 'phonePrefix', 'licensePlate', 'countryPlain') as $field) {
+            if ($item[$field] == '') {
+                $item[$field . '_warning'] = true;
+                $warning = true;
+            }
+        }
+        if (is_null($item['belongsTo'])) {
+            foreach (array('nationality', 'nationalityEn') as $field) {
+                if ($item[$field] == '') {
+                    $item[$field . '_warning'] = true;
+                    $warning = true;
+                }
+            }
+        }
+        return $warning;
+    }
+
+    private static function updateCountry(array $item)
+    {
+        XDB::execute('UPDATE  geoloc_countries
+                         SET  countryPlain = {?}
+                       WHERE  iso_3166_1_a2 = {?}',
+                     mb_strtoupper(replace_accent($item['country'])), $item['iso_3166_1_a2']);
+    }
+
+    private static function isLanguageIncomplete(array &$item)
+    {
+        if ($item['language'] == '') {
+            $item['language_warning'] = true;
+            return true;
+        }
+        return false;
+    }
+
+    private static function updateLanguage(array $item) {}
+
+    function handler_geocoding(&$page, $category = null, $action = null, $id = null)
+    {
+        // Warning, this handler requires the following packages:
+        //  * pkg-isocodes
+        //  * isoquery
+
+        static $properties = array(
+            'country'  => array(
+                'name'         => 'pays',
+                'isocode'      => '3166',
+                'table'        => 'geoloc_countries',
+                'id'           => 'iso_3166_1_a2',
+                'main_fields'  => array('iso_3166_1_a3', 'iso_3166_1_num', 'countryEn'),
+                'other_fields' => array('worldRegion', 'country', 'capital', 'nationality', 'nationalityEn',
+                                        'phonePrefix', 'phoneFormat', 'licensePlate', 'belongsTo')
+            ),
+            'language' => array(
+                'name'         => 'langages',
+                'isocode'      => '639',
+                'table'        => 'profile_langskill_enum',
+                'id'           => 'iso_639_2b',
+                'main_fields'  => array('iso_639_2t', 'iso_639_1', 'language_en'),
+                'other_fields' => array('language')
+
+            )
+        );
+
+        if (is_null($category) || !array_key_exists($category, $properties)) {
+            pl_redirect('admin');
+        }
+
+        $data = $properties[$category];
+
+        if ($action == 'edit' || $action == 'add') {
+            $main_fields = array_merge(array($data['id']), $data['main_fields']);
+            $all_fields = array_merge($main_fields, $data['other_fields']);
+
+            if (is_null($id)) {
+                if (Post::has('new_id')) {
+                    $id = Post::v('new_id');
+                } else {
+                    pl_redirect('admin/geocoding/' . $category);
+                }
+            }
+
+            $list = array();
+            exec('isoquery --iso=' . $data['isocode'] . ' ' . $id, $list);
+            if (count($list) == 1) {
+                $array = explode("\t", $list[0]);
+                foreach ($main_fields as $i => $field) {
+                    $iso[$field] = $array[$i];
+                }
+            } else {
+                $iso = array();
+            }
+
+            if ($action == 'add') {
+                if (Post::has('new_id')) {
+                    S::assert_xsrf_token();
+                }
+
+                if (count($iso)) {
+                    $item = $iso;
+                } else {
+                    $item = array($data['id'] => $id);
+                }
+                XDB::execute('INSERT INTO  ' . $data['table'] . '(' . implode(', ', array_keys($item)) . ')
+                                   VALUES  ' . XDB::formatArray($item));
+                $page->trigSuccess($id . ' a bien été ajouté à la base.');
+            } elseif ($action == 'edit') {
+                if (Post::has('edit')) {
+                    S::assert_xsrf_token();
+
+                    $item = array();
+                    $set  = array();
+                    foreach ($all_fields as $field) {
+                        $item[$field] = Post::t($field);
+                        $set[] = $field . XDB::format(' = {?}', ($item[$field] ? $item[$field] : null));
+                    }
+                    XDB::execute('UPDATE  ' . $data['table'] . '
+                                     SET  ' . implode(', ', $set) . '
+                                   WHERE  ' . $data['id'] . ' = {?}',
+                                 $id);
+                    call_user_func_array(array('self', 'update' . ucfirst($category)), array($item));
+                    $page->trigSuccess($id . ' a bien été mis à jour.');
+                } elseif (Post::has('del')) {
+                    S::assert_xsrf_token();
+
+                    XDB::execute('DELETE FROM  ' . $data['table'] . '
+                                        WHERE  ' . $data['id'] . ' = {?}',
+                                 $id);
+                    $page->trigSuccessRedirect($id . ' a bien été supprimé.', 'admin/geocoding/' . $category);
+                } else {
+                    $item = XDB::fetchOneAssoc('SELECT  *
+                                                  FROM  ' . $data['table'] . '
+                                                 WHERE  ' . $data['id'] . ' = {?}',
+                                               $id);
+                }
+            }
+
+            $page->changeTpl('admin/geocoding_edit.tpl');
+            $page->setTitle('Administration - ' . ucfirst($data['name']));
+            $page->assign('category', $category);
+            $page->assign('name', $data['name']);
+            $page->assign('all_fields', $all_fields);
+            $page->assign('id', $id);
+            $page->assign('iso', $iso);
+            $page->assign('item', $item);
+            return;
+        }
+
+        $page->changeTpl('admin/geocoding.tpl');
+        $page->setTitle('Administration - ' . ucfirst($data['name']));
+        $page->assign('category', $category);
+        $page->assign('name', $data['name']);
+        $page->assign('id', $data['id']);
+        $page->assign('main_fields', $data['main_fields']);
+        $page->assign('all_fields', array_merge($data['main_fields'], $data['other_fields']));
+
+        // First build the list provided by the iso codes.
+        $list = array();
+        exec('isoquery --iso=' . $data['isocode'], $list);
+
+        foreach ($list as $key => $item) {
+            $array = explode("\t", $item);
+            unset($list[$key]);
+            $list[$array[0]] = array();
+            foreach ($data['main_fields'] as $i => $field) {
+                $list[$array[0]][$field] = $array[$i + 1];
+            }
+        }
+        ksort($list);
+
+        // Retrieve all data from the database.
+        $db_list = XDB::rawFetchAllAssoc('SELECT  *
+                                            FROM  ' . $data['table'] . '
+                                        ORDER BY  ' . $data['id'],
+                                         $data['id']);
+
+        // Sort both iso and database data into 5 categories:
+        //  $missing: data from the iso list not in the database,
+        //  $non_existing: data from the database not in the iso list,
+        //  $erroneous: data that differ on main fields,
+        //  $incomplete: data with empty fields in the data base,
+        //  $remaining: remaining correct and complete data from the database.
+
+        $missing = $non_existing = $erroneous = $incomplete = $remaining = array();
+        foreach (array_keys($list) as $id) {
+            if (!array_key_exists($id, $db_list)) {
+                $missing[$id] = $list[$id];
+            }
+        }
+
+        foreach ($db_list as $id => $item) {
+            if (!array_key_exists($id, $list)) {
+                $non_existing[$id] = $item;
+            } else {
+                $error = false;
+                foreach ($data['main_fields'] as $field) {
+                    if ($item[$field] != $list[$id][$field]) {
+                        $item[$field . '_error'] = true;
+                        $error = true;
+                    }
+                }
+                if ($error == true) {
+                    $erroneous[$id] = $item;
+                } elseif (call_user_func_array(array('self', 'is' . ucfirst($category) . 'Incomplete'), array(&$item))) {
+                    $incomplete[$id] = $item;
+                } else {
+                    $remaining[$id] = $item;
+                }
+            }
+        }
+
+        $page->assign('lists', array(
+                'manquant'  => $missing,
+                'disparu'   => $non_existing,
+                'erroné'    => $erroneous,
+                'incomplet' => $incomplete,
+                'restant'   => $remaining
+        ));
+    }
+
     function handler_accounts(PlPage $page)
     {
         $page->changeTpl('admin/accounts.tpl');
         $page->setTitle('Administration - Comptes');
-        $page->addJsLink('password.js');
 
         if (Post::has('create_account')) {
             S::assert_xsrf_token();
similarity index 60%
rename from htdocs/javascript/secure_hash.js
rename to modules/api.php
index 6053109..1fa485f 100644 (file)
@@ -1,51 +1,54 @@
-/***************************************************************************\r
- *  Copyright (C) 2003-2011 Polytechnique.org                              *\r
- *  http://opensource.polytechnique.org/                                   *\r
- *                                                                         *\r
- *  This program is free software; you can redistribute it and/or modify   *\r
- *  it under the terms of the GNU General Public License as published by   *\r
- *  the Free Software Foundation; either version 2 of the License, or      *\r
- *  (at your option) any later version.                                    *\r
- *                                                                         *\r
- *  This program is distributed in the hope that it will be useful,        *\r
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *\r
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *\r
- *  GNU General Public License for more details.                           *\r
- *                                                                         *\r
- *  You should have received a copy of the GNU General Public License      *\r
- *  along with this program; if not, write to the Free Software            *\r
- *  Foundation, Inc.,                                                      *\r
- *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *\r
- ***************************************************************************/\r
-\r
-function hash_encrypt(a) {\r
-    return hex_sha1(a);\r
-}\r
-\r
-var hexa_h = "0123456789abcdef";\r
-\r
-function dechex(a) {\r
-    return hexa_h.charAt(a);\r
-}\r
-\r
-function hexdec(a) {\r
-    return hexa_h.indexOf(a);\r
-}\r
-\r
-function hash_xor(a, b) {\r
-    var c,i,j,k;\r
-    c = "";\r
-    i = a.length;\r
-    j = b.length;\r
-    if (i < j) {\r
-        var d;\r
-        d = a; a = b; b = d;\r
-        k = i; i = j; j = k;\r
-    }\r
-    for (k = 0; k < j; k++)\r
-        c += dechex(hexdec(a.charAt(k)) ^ hexdec(b.charAt(k)));\r
-    for (; k < i; k++)\r
-        c += a.charAt(k);\r
-    return c;\r
-}\r
+<?php
+/***************************************************************************
+ *  Copyright (C) 2003-2011 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 ApiModule extends PlModule
+{
+    function handlers()
+    {
+        return array(
+            // TODO(vzanotti): Extend the plat/al engine to support placeholders
+            // in handler urls, for instance "api/1/user/%forlife/isRegistered".
+            'api/1/user' => $this->make_api_hook('user', AUTH_COOKIE, 'api_user_readonly'),
+        );
+    }
+
+    // This handler supports the following URL patterns:
+    //   /api/1/user/{forlife}/isRegistered
+    function handler_user(PlPage& $page, PlUser& $authUser, $payload, $user = null, $selector = null)
+    {
+        // Retrieve the PlUser referenced in the request. Note that this is the
+        // target user, not the authenticated user.
+        $user = PlUser::getSilent($user);
+        if (empty($user)) {
+            return PL_NOT_FOUND;
+        }
+
+        if ($selector == 'isRegistered') {
+            $page->jsonAssign('isRegistered', $user->isActive());
+            return PL_JSON;
+        } else {
+            return PL_NOT_FOUND;
+        }
+    }
+}
+
 // vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
+?>
index 09d0ad6..f5008c0 100644 (file)
@@ -43,6 +43,7 @@ class BandeauModule extends PLModule
         $page->changeTpl('skin/common.bandeau.tpl', NO_SKIN);
         $page->assign('login', $login == 'login');
         $page->assign('seed', $login);
+        $page->assign('external', true);
     }
 
     function handler_css(&$page)
index 2c9f629..82d0609 100644 (file)
@@ -24,18 +24,18 @@ class CarnetModule extends PLModule
     function handlers()
     {
         return array(
-            'carnet'                => $this->make_hook('index',    AUTH_COOKIE, 'directory_private'),
-            'carnet/panel'          => $this->make_hook('panel',    AUTH_COOKIE, 'directory_private'),
-            'carnet/notifs'         => $this->make_hook('notifs',   AUTH_COOKIE, 'directory_private'),
-
-            'carnet/contacts'       => $this->make_hook('contacts', AUTH_COOKIE, 'directory_private'),
-            'carnet/contacts/pdf'   => $this->make_hook('pdf',      AUTH_COOKIE, 'directory_private'),
-            'carnet/contacts/vcard' => $this->make_hook('vcard',    AUTH_COOKIE, 'directory_private'),
-            'carnet/contacts/ical'  => $this->make_hook('ical',     AUTH_PUBLIC, 'directory_private', NO_HTTPS),
-            'carnet/contacts/csv'   => $this->make_hook('csv',     AUTH_PUBLIC,  'directory_private', NO_HTTPS),
-            'carnet/contacts/csv/birthday'  => $this->make_hook('csv_birthday',     AUTH_PUBLIC, 'directory_private', NO_HTTPS),
-
-            'carnet/rss'            => $this->make_hook('rss',      AUTH_PUBLIC, 'directory_private', NO_HTTPS),
+            'carnet'                => $this->make_hook('index',      AUTH_COOKIE, 'directory_private'),
+            'carnet/panel'          => $this->make_hook('panel',      AUTH_COOKIE, 'directory_private'),
+            'carnet/notifs'         => $this->make_hook('notifs',     AUTH_COOKIE, 'directory_private'),
+
+            'carnet/contacts'       => $this->make_hook('contacts',   AUTH_COOKIE, 'directory_private'),
+            'carnet/contacts/pdf'   => $this->make_hook('pdf',        AUTH_COOKIE, 'directory_private'),
+            'carnet/contacts/vcard' => $this->make_hook('vcard',      AUTH_COOKIE, 'directory_private'),
+            'carnet/contacts/ical'  => $this->make_token_hook('ical', AUTH_COOKIE, 'directory_private'),
+            'carnet/contacts/csv'   => $this->make_token_hook('csv',  AUTH_COOKIE, 'directory_private'),
+            'carnet/contacts/csv/birthday' => $this->make_token_hook('csv_birthday', AUTH_COOKIE, 'directory_private'),
+
+            'carnet/rss'            => $this->make_token_hook('rss',  AUTH_COOKIE, 'directory_private'),
         );
     }
 
@@ -358,11 +358,11 @@ class CarnetModule extends PLModule
         exit;
     }
 
-    function handler_rss(&$page, $user = null, $hash = null)
+    function handler_rss(PlPage& $page, PlUser& $user)
     {
         $this->load('feed.inc.php');
         $feed = new CarnetFeed();
-        return $feed->run($page, $user, $hash);
+        return $feed->run($page, $user);
     }
 
     function buildBirthRef(Profile $profile)
@@ -378,17 +378,8 @@ class CarnetModule extends PLModule
         );
     }
 
-    function handler_csv_birthday(&$page, $alias = null, $hash = null)
+    function handler_csv_birthday(PlPage& $page, PlUser& $user)
     {
-        $user = Platal::session()->tokenAuth($alias, $hash);
-        if (is_null($user)) {
-            if (S::logged()) {
-                $user = S::user();
-            } else {
-                return PL_FORBIDDEN;
-            }
-        }
-
         $page->changeTpl('carnet/calendar.outlook.tpl', NO_SKIN);
         $filter = new UserFilter(new UFC_Contact($user));
         $profiles = $filter->iterProfiles();
@@ -411,17 +402,8 @@ class CarnetModule extends PLModule
         pl_content_headers("text/comma-separated-values;charset=".$encoding);
     }
 
-    function handler_ical(&$page, $alias = null, $hash = null)
+    function handler_ical(PlPage& $page, PlUser& $user)
     {
-        $user = Platal::session()->tokenAuth($alias, $hash);
-        if (is_null($user)) {
-            if (S::logged()) {
-                $user = S::user();
-            } else {
-                return PL_FORBIDDEN;
-            }
-        }
-
         require_once 'ical.inc.php';
         $page->changeTpl('carnet/calendar.tpl', NO_SKIN);
         $page->register_function('display_ical', 'display_ical');
@@ -441,17 +423,8 @@ class CarnetModule extends PLModule
         $vcard->show();
     }
 
-    function handler_csv(&$page, $alias = null, $hash = null)
+    function handler_csv(PlPage& $page, PlUser& $user)
     {
-        $user = Platal::session()->tokenAuth($alias, $hash);
-        if (is_null($user)) {
-            if (S::logged()) {
-                $user = S::user();
-            } else {
-                return PL_FORBIDDEN;
-            }
-        }
-
         $page->changeTpl('carnet/mescontacts.outlook.tpl', NO_SKIN);
         $pf = new ProfileFilter(new UFC_Contact($user));
         require_once 'carnet/outlook.inc.php';
index fa284fc..ed79ee9 100644 (file)
@@ -265,23 +265,27 @@ class ContactsPDF extends FPDF
         if ($wp) {
             $photo = $profile->getPhoto(false, true);
             if ($photo) {
-                $old2  = clone $self;
-                $width = $photo->width() * 20 / $photo->height();
-                $_x = $self->getX();
-                $_y = $self->getY();
-                $self->Cell(0, 20, '', '', 0, '', 1);
-                error_reporting(0);
-                $self->Image($photo->path(), $_x, $_y, $width, 20, $photo->mimeType());
-                error_reporting($self->report);
-
-                if ($self->error) {
-                    $self = clone $old2;
-                } else {
-                    $self->setX($_x);
-                    $self->Cell($width, 20, '', "T");
-                    $h = 20 / $self->wordwrap($nom, 90 - $width);
-                    $self->MultiCell(0, $h, $nom, 'T', 'C');
-                    $ok = true;
+                list(, $type) = explode('/', $photo->mimeType());
+                $type = ($type == 'jpeg') ? 'jpg' : $type;
+                if (method_exists($self, '_parse' . $type)) {
+                    $old2  = clone $self;
+                    $width = $photo->width() * 20 / $photo->height();
+                    $_x = $self->getX();
+                    $_y = $self->getY();
+                    $self->Cell(0, 20, '', '', 0, '', 1);
+                    error_reporting(0);
+                    $self->Image($photo->path(), $_x, $_y, $width, 20, $type);
+                    error_reporting($self->report);
+
+                    if ($self->error) {
+                        $self = clone $old2;
+                    } else {
+                        $self->setX($_x);
+                        $self->Cell($width, 20, '', "T");
+                        $h = 20 / $self->wordwrap($nom, 90 - $width);
+                        $self->MultiCell(0, $h, $nom, 'T', 'C');
+                        $ok = true;
+                    }
                 }
             }
         }
index 95b7c2a..b9cca56 100644 (file)
@@ -25,11 +25,11 @@ class EventsModule extends PLModule
     {
         return array(
             'events'         => $this->make_hook('ev',           AUTH_COOKIE),
-            'rss'            => $this->make_hook('rss',          AUTH_PUBLIC, 'user', NO_HTTPS),
             'events/preview' => $this->make_hook('preview',      AUTH_PUBLIC, 'user', NO_AUTH),
             'events/photo'   => $this->make_hook('photo',        AUTH_PUBLIC),
             'events/submit'  => $this->make_hook('ev_submit',    AUTH_MDP),
             'admin/events'   => $this->make_hook('admin_events', AUTH_MDP,    'admin'),
+            'rss'            => $this->make_token_hook('rss',    AUTH_COOKIE),
 
             'ajax/tips'      => $this->make_hook('tips',         AUTH_COOKIE, 'user', NO_AUTH),
             'admin/tips'     => $this->make_hook('admin_tips',   AUTH_MDP,    'admin'),
@@ -228,11 +228,11 @@ class EventsModule extends PLModule
         exit;
     }
 
-    function handler_rss(&$page, $user = null, $hash = null)
+    function handler_rss(PlPage& $page, PlPage& $user)
     {
         $this->load('feed.inc.php');
         $feed = new EventFeed();
-        return $feed->run($page, $user, $hash);
+        return $feed->run($page, $user);
     }
 
     function handler_preview(&$page)
index 6964887..c1b8e16 100644 (file)
@@ -41,7 +41,6 @@ class GoogleAppsModule extends PLModule
         require_once("emails.inc.php");
         require_once("googleapps.inc.php");
         $page->changeTpl('googleapps/index.tpl');
-        $page->addJsLink('password.js');
         $page->setTitle('Compte Google Apps');
 
         $user = S::user();
index c5477e7..6f8896d 100644 (file)
@@ -55,23 +55,23 @@ function paypal_erreur($text, $send=true)
 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 */
@@ -88,16 +88,16 @@ function comment_decode($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
@@ -105,22 +105,22 @@ 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'),
         );
     }
 
@@ -134,9 +134,9 @@ class PaymentModule extends PLModule
             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;
@@ -160,25 +160,27 @@ class PaymentModule extends PLModule
             $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());
         $page->assign('sex', S::user()->isFemale());
     }
@@ -214,9 +216,9 @@ class PaymentModule extends PLModule
         }
 
         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");
         }
@@ -235,8 +237,8 @@ class PaymentModule extends PLModule
         }
 
         /* 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.
@@ -288,10 +290,11 @@ class PaymentModule extends PLModule
         /* 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");
         //}
@@ -308,30 +311,30 @@ class PaymentModule extends PLModule
         }
 
         $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.
@@ -389,7 +392,7 @@ class PaymentModule extends PLModule
         /* 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 */
@@ -400,10 +403,11 @@ class PaymentModule extends PLModule
 
         /* 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 */
@@ -418,11 +422,11 @@ class PaymentModule extends PLModule
         }
 
         $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 */
@@ -503,33 +507,60 @@ class PaymentModule extends PLModule
                   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()) {
@@ -543,9 +574,9 @@ class PaymentModule extends PLModule
                     $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) {
@@ -566,61 +597,61 @@ class PaymentModule extends PLModule
         $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);
     }
 
@@ -631,40 +662,40 @@ class PaymentModule extends PLModule
         $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
@@ -673,114 +704,114 @@ class PaymentModule extends PLModule
                 $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']);
@@ -789,179 +820,194 @@ class PaymentModule extends PLModule
             }
 
         } 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;
+        }
     }
 }
 
index 3f40979..225c337 100644 (file)
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-/*
-    Numéros de cartes de test :
-    Commerçant non enrôlé 3D-Secure
-    4970 1000 0000 0003 Paiement accepté (autorisation accordée)
-    Commerçant enrôlé 3D-Secure
-    4970 1000 0000 0000 Paiement accepté avec authentification internaute
-    4970 1000 0000 0001 Paiement accepté sans authentification internaute (Internaute non enrôlé 3D-Secure)
-    4970 1000 0000 0002 contacter l'émetteur de carte (Transaction à forcer). Authentification réalisée avec succès.
-    4970 1000 0000 0006 Problème technique lors du calcul de la garantie de paiement
-    4970 1000 0000 0007 Problème technique lors de l’authentification porteur
-    4970 1000 0000 0097 Paiement refusé pour cause d’authentification 3D-Secure échouée (l'internaute n'est pas parvenu à s'authentifier)
-    4970 1000 0000 0098 Paiement refusé (autorisation refusée pour cause de plafond dépassé)
-    4970 1000 0000 0099 Paiement refusé (autorisation refusée suite à erreur dans le cryptogramme visuel saisi)
+/** Card numbers for tests.
+ * Non 3D-Secure shop:
+ *  4970 1000 0000 0003 Payment accepted (authorized)
+ * 3D-Secure shop:
+ *  4970 1000 0000 0000 Payment accepted, with user authentication.
+ *  4970 1000 0000 0001 Payment accepted, without user authentication (non 3D-Secure user).
+ *  4970 1000 0000 0002 Must contact card issuer (which must force transaction). Succesful authentication.
+ *  4970 1000 0000 0006 Technical issue while computing payment warranty.
+ *  4970 1000 0000 0007 Technical issue during user authentication.
+ *  4970 1000 0000 0097 Payment refused due to 3D-Secure authentication failure (user failed to authenticate).
+ *  4970 1000 0000 0098 Payment refused (user credit limit overrun).
+ *  4970 1000 0000 0099 Payment refused (invalid credit card visual cryptogramm).
 */
 
 class BPLCCyberPlus
@@ -49,7 +48,7 @@ class BPLCCyberPlus
 
     function BPLCCyberPlus($val)
     {
-        // SVA : nombre de chiffres après la virgule dépendant de currency ?
+        // Improvement: number of digits after the coma might depend from the currency.
         $this->val = 100 * strtr(sprintf("%.02f", (float)$val), '.', ',');
     }
 
@@ -61,14 +60,14 @@ class BPLCCyberPlus
         global $globals, $platal;
         $log = S::v('log');
 
-        // on constuit la reference de la transaction
+        // Transaction's reference computation.
         $prefix = ($pay->flags->hasflag('unique')) ? str_pad("",15,"0") : rand_url_id();
         $fullref = substr("$prefix-{$pay->id}",-12); // FIXME : check for duplicates
         $ts = time();
         $trans_date = date("YmdHis", $ts);
         $trans_id = date("His", $ts); // FIXME : check for duplicates
 
-        // contenu du formulaire
+        // Form's content.
         $this->urlform = "https://systempay.cyberpluspaiement.com/vads-payment/";
         $this->infos['commercant'] = Array(
             'vads_site_id' => $globals->money->cyperplus_account,
@@ -92,7 +91,7 @@ class BPLCCyberPlus
             'vads_page_action' => 'PAYMENT',
             'vads_action_mode' => 'INTERACTIVE');
 
-        // calcul de la clé d'acceptation en entrée
+        // Entry key computation.
         $all_params = array_merge($this->infos['commercant'],$this->infos['client'],$this->infos['commande'],$this->infos['divers']);
         ksort($all_params);
         $this->infos['divers']['signature'] = sha1(join('+',$all_params).'+'.$globals->money->cyperplus_key);
index 6ae107a..71de323 100644 (file)
@@ -66,22 +66,26 @@ class PayPal
             'email'      => $user->bestEmail()
         );
 
-        $res = XDB::query("SELECT  pa.text, gl.name AS city, pa.postalCode AS zip, pa.countryId AS country,
-                                   IF(pp1.display_tel != '', pp1.display_tel, pp2.display_tel) AS night_phone_b
-                             FROM  profile_addresses AS pa
-                        LEFT JOIN  profile_phones    AS pp1 ON (pp1.pid = pa.pid AND pp1.link_type = 'address'
-                                                                AND pp1.link_id = pa.id)
-                        LEFT JOIN  profile_phones    AS pp2 ON (pp2.pid = pa.pid AND pp2.link_type = 'user'
-                                                                AND pp2.link_id = 0)
-                        LEFT JOIN  geoloc_localities AS gl  ON (gl.id = pa.localityId)
-                            WHERE  pa.pid = {?} AND FIND_IN_SET('current', pa.flags)
-                            LIMIT  1",
-                          $user->profile()->id());
-        $this->infos['client'] = array_map('replace_accent', array_merge($info_client, $res->fetchOneAssoc()));
-        list($this->infos['client']['address1'], $this->infos['client']['address2']) =
-            explode("\n", Geocoder::getFirstLines($this->infos['client']['text'],
-                                                  $this->infos['client']['zip'], 2));
-        unset($this->infos['client']['text']);
+        if ($user->hasProfile() {
+            $res = XDB::query("SELECT  pa.text, gl.name AS city, pa.postalCode AS zip, pa.countryId AS country,
+                                       IF(pp1.display_tel != '', pp1.display_tel, pp2.display_tel) AS night_phone_b
+                                 FROM  profile_addresses AS pa
+                            LEFT JOIN  profile_phones    AS pp1 ON (pp1.pid = pa.pid AND pp1.link_type = 'address'
+                                                                    AND pp1.link_id = pa.id)
+                            LEFT JOIN  profile_phones    AS pp2 ON (pp2.pid = pa.pid AND pp2.link_type = 'user'
+                                                                    AND pp2.link_id = 0)
+                            LEFT JOIN  geoloc_localities AS gl  ON (gl.id = pa.localityId)
+                                WHERE  pa.pid = {?} AND FIND_IN_SET('current', pa.flags)
+                                LIMIT  1",
+                              $user->profile()->id());
+            $this->infos['client'] = array_map('replace_accent', array_merge($info_client, $res->fetchOneAssoc()));
+            list($this->infos['client']['address1'], $this->infos['client']['address2']) =
+                explode("\n", Geocoder::getFirstLines($this->infos['client']['text'],
+                                                      $this->infos['client']['zip'], 2));
+            unset($this->infos['client']['text']);
+        } else {
+            $this->infos['client'] = replace_accent($info_client);
+        }
 
         // We build the transaction's reference
         $prefix = ($pay->flags->hasflag('unique')) ? str_pad("", 15, "0") : rand_url_id();
index 03883d4..820f6c3 100644 (file)
@@ -228,7 +228,6 @@ class PlatalModule extends PLModule
         }
 
         $page->changeTpl('platal/password.tpl');
-        $page->addJsLink('password.js');
         $page->setTitle('Mon mot de passe');
     }
 
@@ -387,7 +386,6 @@ Adresse de secours : " . Post::v('email') : ""));
             $page->changeTpl('platal/tmpPWD.success.tpl');
         } else {
             $page->changeTpl('platal/password.tpl');
-            $page->addJsLink('password.js');
         }
     }
 
index 5617b7c..0ac4d0b 100644 (file)
@@ -293,7 +293,6 @@ class ProfileModule extends PLModule
         $page->assign('view', $view);
         $page->assign('logged', S::logged());
 
-        $page->addJsLink('close_on_esc.js');
         header('Last-Modified: ' . date('r', strtotime($profile->last_change)));
     }
 
@@ -333,7 +332,6 @@ class ProfileModule extends PLModule
         $page->addJsLink('education.js', false); /* dynamic content */
         $page->addJsLink('grades.js', false);    /* dynamic content */
         $page->addJsLink('profile.js');
-        $page->addJsLink('jquery.autocomplete.js');
         $wiz = new PlWizard('Profil', PlPage::getCoreTpl('plwizard.tpl'), true, true, false);
         $wiz->addUserData('profile', $profile);
         $wiz->addUserData('owner', $profile->owner());
@@ -524,8 +522,6 @@ class ProfileModule extends PLModule
               LEFT JOIN  geoloc_countries       AS gc ON (m.country = gc.iso_3166_1_a2)
                   WHERE  pid = {?}", $pf->id());
         $page->assign('pays', $res->fetchColumn());
-
-        $page->addJsLink('close_on_esc.js');
     }
 
     function handler_ref_country(&$page)
index 9dee7b0..cc39c27 100644 (file)
@@ -92,7 +92,7 @@ class ProfileSettingJob implements ProfileSetting
         }
         $it = Phone::iterate(array($page->pid()), array(Phone::LINK_JOB));
         while ($phone = $it->next()) {
-            $jobs[$phone->linkId()]['w_phone'][$phone->id()] = $phone->toFormArray();
+            $jobs[$phone->link_id]['w_phone'][$phone->id] = $phone->toFormArray();
         }
         $res = XDB::iterator("SELECT  e.jtid, e.full_name, j.jid
                                 FROM  profile_job_term_enum AS e
index 21e3aa6..2ad367e 100644 (file)
 class ProfileSettingSkill implements ProfileSetting
 {
     private $table;
+    private $id;
     private $skill_field;
     private $text_field;
 
-    public function __construct($table, $skill, $text)
+    public function __construct($table, $id, $skill, $text)
     {
         $this->table = $table;
+        $this->id = $id;
         $this->skill_field = $skill;
         $this->text_field = $text;
     }
@@ -36,9 +38,9 @@ class ProfileSettingSkill implements ProfileSetting
     {
         if (is_null($value)) {
             $value = array();
-            $res = XDB::iterRow("SELECT  s.id, s.{$this->text_field}, i.level
+            $res = XDB::iterRow("SELECT  s.{$this->id}, s.{$this->text_field}, i.level
                                    FROM  profile_{$this->table}_enum AS s
-                             INNER JOIN  profile_{$this->table}s AS i ON(s.id = i.{$this->skill_field})
+                             INNER JOIN  profile_{$this->table}s     AS i ON (s.{$this->id} = i.{$this->skill_field})
                                   WHERE  i.pid = {?}",
                                 $page->pid());
             while (list($sid, $text, $level) = $res->next()) {
@@ -52,7 +54,7 @@ class ProfileSettingSkill implements ProfileSetting
                 if (!isset($skill['text']) || empty($skill['text'])) {
                     $res = XDB::query("SELECT  {$this->text_field}
                                          FROM  profile_{$this->table}_enum
-                                        WHERE  id = {?}", $id);
+                                        WHERE  {$this->id} = {?}", $id);
                     $skill['text'] = $res->fetchOneCell();
                 }
             }
@@ -109,8 +111,8 @@ class ProfilePageSkills extends ProfilePage
     public function __construct(PlWizard &$wiz)
     {
         parent::__construct($wiz);
-        $this->settings['competences'] = new ProfileSettingSkill('skill', 'cid', 'text_fr');
-        $this->settings['langues'] = new ProfileSettingSkill('langskill', 'lid', 'langue_fr');
+        $this->settings['competences'] = new ProfileSettingSkill('skill', 'id', 'cid', 'text_fr');
+        $this->settings['langues'] = new ProfileSettingSkill('langskill', 'iso_639_2b', 'lid', 'language');
     }
 
     public function _prepare(PlPage &$page, $id)
@@ -120,9 +122,9 @@ class ProfilePageSkills extends ProfilePage
         $page->assign('comp_level', array('initié' => 'initié',
                                           'bonne connaissance' => 'bonne connaissance',
                                           'expert' => 'expert'));
-        $page->assign('lang_list', XDB::iterator("SELECT  id, langue_fr
+        $page->assign('lang_list', XDB::iterator('SELECT  iso_639_2b, language
                                                     FROM  profile_langskill_enum
-                                                ORDER BY  langue_fr"));
+                                                ORDER BY  language'));
         $page->assign('lang_level', array(1 => 'connaissance basique',
                                           2 => 'maîtrise des bases',
                                           3 => 'maîtrise limitée',
index 0dfd5c3..34f2358 100644 (file)
@@ -52,7 +52,7 @@ class RegisterModule extends PLModule
             $nameTypes = DirEnum::getOptions(DirEnum::NAMETYPES);
             $nameTypes = array_flip($nameTypes);
             $res = XDB::query("SELECT  a.uid, pd.promo, pnl.name AS lastname, pnf.name AS firstname, p.xorg_id AS xorgid,
-                                       p.birthdate_ref AS birthdateRef, FIND_IN_SET('watch', a.flags) AS watch, m.hash, a.type as eduType
+                                       p.birthdate_ref AS birthdateRef, FIND_IN_SET('watch', a.flags) AS watch, m.hash
                                  FROM  register_marketing AS m
                            INNER JOIN  accounts           AS a   ON (m.uid = a.uid)
                            INNER JOIN  account_profiles   AS ap  ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))
@@ -171,13 +171,8 @@ class RegisterModule extends PLModule
                     }
 
                     // Register the optional services requested by the user.
-                    if ($subState->v('eduType') == 'x') {
-                        $proposedServices = array('ax_letter', 'imap', 'ml_promo', 'nl');
-                    } else {
-                        $proposedServices = array('ax_letter', 'nl');
-                    }
                     $services = array();
-                    foreach ($proposedServices as $service) {
+                    foreach (array('ax_letter', 'imap', 'ml_promo', 'nl') as $service) {
                         if (Post::b($service)) {
                             $services[] = $service;
                         }
@@ -254,7 +249,6 @@ class RegisterModule extends PLModule
         }
 
         $page->changeTpl('register/step' . $subState->i('step') . '.tpl');
-        $page->addJsLink('password.js');
         if (isset($error)) {
             $page->trigError($error);
         }
@@ -314,7 +308,6 @@ class RegisterModule extends PLModule
 
         // Prepare the template for display.
         $page->changeTpl('register/end.tpl');
-        $page->addJsLink('do_challenge_response_logged.js');
         $page->assign('forlife', $forlife);
         $page->assign('firstname', $firstname);
 
@@ -354,15 +347,8 @@ class RegisterModule extends PLModule
 
         // Add the registration email address as first and only redirection.
         require_once 'emails.inc.php';
-        $user = User::getSilentWithUID($uid);
-        if ($isX) {
-            $redirect = new Redirect($user);
-            $redirect->add_email($email);
-        } else {
-            XDB::execute('UPDATE  accounts
-                             SET  email = {?}
-                           WHERE  uid = {?}', $email, $uid);
-        }
+        $redirect = new Redirect($user);
+        $redirect->add_email($email);
 
         // Try to start a session (so the user don't have to log in); we will use
         // the password available in Post:: to authenticate the user.
@@ -409,11 +395,10 @@ class RegisterModule extends PLModule
 
         // Congratulate our newly registered user by email.
         $mymail = new PlMailer('register/success.mail.tpl');
+        $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
         if ($isX) {
-            $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
             $mymail->setSubject('Bienvenue parmi les X sur le web !');
         } else {
-            $mymail->addTo($email);
             $mymail->setSubject('Bienvenue sur Polytechnique.org !');
         }
         $mymail->assign('forlife', $forlife);
index 64adb5f..eb01b60 100644 (file)
@@ -151,7 +151,6 @@ class SearchModule extends PLModule
     {
         global $globals;
         $page->assign('advanced',1);
-        $page->addJsLink('jquery.autocomplete.js');
 
         $networks = DirEnum::getOptions(DirEnum::NETWORKS);
         $networks[-1] = 'Tous types';
@@ -376,8 +375,6 @@ class SearchModule extends PLModule
         $res = XDB::query("SELECT count(distinct pid) FROM profile_mentor_term");
         $page->assign('mentors_number', $res->fetchOneCell());
 
-        $page->addJsLink('jquery.autocomplete.js');
-
         // Search for mentors matching filters
         require_once 'ufbuilder.inc.php';
         $ufb = new UFB_MentorSearch();
index 3c53625..66b65c4 100644 (file)
 
 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/edit'         => $this->make_hook('edit',          AUTH_COOKIE),
+            /*
+            'survey/result'       => $this->make_hook('result',        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)
+    private function setup_page(PlPage $page)
     {
         $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);
-        }
+        $page->addJsLink('jquery.ui.xorg.js');
+        $page->addJsLink('survey.js');
     }
-    // }}}
 
-    // {{{ function handler_result() : show the results of the votes to a survey
-    function handler_result($page, $id = -1, $show = 'all')
+    function handler_index(&$page, $action = null)
     {
-        $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);
-        }
-    }
-    // }}}
+        $this->setup_page($page);
 
-    // {{{ 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);
-        }
+        $page->changeTpl('survey/index.tpl');
+        $page->assign('active', Survey::iterActive());
     }
-    // }}}
 
-    // {{{ function handler_adminEdit() : edits a survey in admin mode
-    function handler_adminEdit(&$page, $id = -1, $req = -1)
+    function handler_vote(PlPage $page, $name)
     {
-        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
-    }
-    // }}}
+        $this->setup_page($page);
+        $page->changeTpl('survey/vote.tpl');
 
-    // {{{ 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);
+        XDB::execute('delete from survey_votes');
+        XDB::execute('delete from survey_voters');
+        $survey = Survey::get($name);
+        if (is_null($survey)) {
+            return PL_NOT_FOUND;
         }
-        if ($id == -1) {
-            return $this->show_error($page, "Un identifiant de sondage doit être précisé.", 'survey/admin');
+        if (!$survey->canSee(S::user())) {
+            return PL_FORBIDDEN;
         }
-        $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');
+        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 {
-                $this->show_error($page, '', 'survey/admin');
+                $vote->insert(true);
+                $page->trigSuccess("Ton vote a été enregistré");
             }
-        } 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));
         }
+        $page->assign('survey', $survey);
     }
-    // }}}
 
-    // {{{ function handler_adminDelete() : deletes a survey (admin mode)
-    function handler_adminDelete(&$page, $id = -1)
+    function handler_edit(PlPage $page, $name = null)
     {
-        $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));
-        }
-    }
-    // }}}
+        $this->setup_page($page);
+        $page->changeTpl('survey/edit.tpl');
 
-    // {{{ 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);
-                    }
+        if (!is_null($name)) {
+            $survey = Survey::get($name);
+        } else {
+            $survey = new Survey();
+            $survey->id = null;
+            $survey->uid = S::user()->id();
+        }
+        if (Post::has('valid')) {
+            $survey->title = Post::t('title');
+            $survey->shortname = Post::t('shortname');
+            $survey->description = Post::t('description');
+            $survey->begin     = Post::t('begin');
+            $survey->end       = Post::t('end');
+            $survey->flags     = 'validated';
+            $survey->flags->addFlag('anonymous', Post::b('anonymous'));
+
+            $q_edit = Post::v('q_edit');
+            $qs = array();
+            $survey->clearQuestions();
+            foreach ($q_edit as $qid => $q_desc) {
+                if (isset($q_desc['parent'])) {
+                    $parent = $qs[$q_desc['parent']];
                 } else {
-                    $this->clear_session();
-                    return $this->handler_index($page); // else shows the 'normal' index
+                    $parent = $survey;
                 }
-            } 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));
-            }
-        } // }}}
-    }
-    // }}}
-
-    // {{{ 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);
-        }
-    }
-    // }}}
-
-    // {{{ function clear_session() : clears the data stored in session
-    function clear_session()
-    {
-        S::kill('survey');
-        S::kill('survey_id');
-        S::kill('survey_validate');
-    }
-    // }}}
-
-    // {{{ 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;
-        }
-    }
-    // }}}
-
-    // {{{ function check_surveyPerms() : checks the particular surveys access permissions
-    function check_surveyPerms(&$page, $survey, $silent = false, $admin_allowed = true)
-    {
-        $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.');
+                $question = $parent->newQuestion($q_desc['type']);
+                $question->label = $q_desc['label'];
+                unset($q_desc['type']);
+                unset($q_desc['parent']);
+                unset($q_desc['label']);
+                $question->parameters = $q_desc;
+                $qs[$qid] = $question;
             }
-            return true;
+            $survey->insert('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:
diff --git a/modules/survey/answer.inc.php b/modules/survey/answer.inc.php
new file mode 100644 (file)
index 0000000..6b7d699
--- /dev/null
@@ -0,0 +1,163 @@
+<?php
+/***************************************************************************
+ *  Copyright (C) 2003-2011 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:
+?>
diff --git a/modules/survey/multiple.inc.php b/modules/survey/multiple.inc.php
new file mode 100644 (file)
index 0000000..c073da7
--- /dev/null
@@ -0,0 +1,72 @@
+<?php
+/***************************************************************************
+ *  Copyright (C) 2003-2011 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 SurveyQuestionMultiple extends SurveyQuestion
+{
+    public function __construct(Survey $survey)
+    {
+        parent::__construct($survey);
+        $this->type = "multiple";
+    }
+
+    protected function buildAnswer(SurveyAnswer $answer, PlDict $data)
+    {
+        $content = $data->v($this->qid);
+        $value   = $content['answers'];
+        if (empty($value)) {
+            $answer->answer = null;
+            return true;
+        }
+        if ($this->parameters['subtype'] == 'radio') {
+            if (count($value) > 1) {
+                throw new Exception("You cannot select more than one answer");
+            }
+        }
+        $answers = array();
+        $answers['answers'] = array();
+        foreach ($value as $key=>$text) {
+            if (can_convert_to_integer($key)) {
+                $key = to_integer($key);
+                if ($text != $this->parameters['answers'][$key]) {
+                    throw new Exception("Answer text does not match");
+                }
+                $answers['answers'][] = $key;
+            } else if ($key != 'other') {
+                throw new Exception("Unsupported answer id $key");
+            } else if (!$this->parameters['allow_other']) {
+                throw new Exception("Got 'Other' answer while not supported");
+            } else if (!isset($content['other'])) {
+                $answers['other'] = '';
+            } else {
+                $answers['other'] = $content['other'];
+            }
+        }
+        if (empty($value)) {
+            $answer->answer = null;
+            return false;
+        } else {
+            $answer->answer = $answers;
+        }
+        return true;
+    }
+}
+
+?>
diff --git a/modules/survey/question.inc.php b/modules/survey/question.inc.php
new file mode 100644 (file)
index 0000000..c29af36
--- /dev/null
@@ -0,0 +1,195 @@
+<?php
+/***************************************************************************
+ *  Copyright (C) 2003-2011 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)
+    {
+        $file = dirname(__FILE__) . '/' . $type . '.inc.php';
+        if (!file_exists($file)) {
+            throw new Exception("Unknown question type \"$type\"");
+        }
+        require_once $file;
+        $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;
+    }
+
+    public function export()
+    {
+        $export = parent::export();
+        if (isset($export['parameters'])) {
+            foreach ($export['parameters'] as $key=>$value) {
+                $export[$key] = $value;
+            }
+            unset($export['parameters']);
+        }
+        return $export;
+    }
+
+}
+
+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:
+?>
similarity index 83%
rename from htdocs/javascript/close_on_esc.js
rename to modules/survey/section.inc.php
index fa54f33..5d2493c 100644 (file)
@@ -1,3 +1,4 @@
+<?php
 /***************************************************************************
  *  Copyright (C) 2003-2011 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-$(window).keydown(
-    function(e)  {
-        if (e.keyCode == 27) {
-            window.close();
-        }
-    });
+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 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
+?>
index 497a7f8..7e715fd 100644 (file)
  *  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;
-        }
-    }
-    // }}}
-
-    // {{{ 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;
+            array_push($stack, $question);
         }
+        return true;
     }
 
-    public function delQuestion($i)
+    protected function preSave()
     {
-        $i = intval($i);
-        if ($this->valid || !array_key_exists($i, $this->questions)) {
-            return false;
+        if (!is_null($this->voterFilter)) {
+            $this->voters = $this->voterFilter->exportConditions();
         } else {
-            array_splice($this->questions, $i, 1);
-            return true;
+            $this->voters = null;
         }
-    }
-
-    public function editQuestion($i, $a)
-    {
-        if ($i == 'root') {
-            $this->update($a);
+        if (!is_null($this->viewerFilter)) {
+            $this->viewers = $this->viewerFilter->exportConditions();
         } else {
-            $i = intval($i);
-            if ($this->valid ||!array_key_exists($i, $this->questions)) {
-                return false;
-            } else {
-                $this->questions[$i]->update($a);
-            }
+            $this->viewers = null;
         }
         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()
+    protected function postSave()
     {
-        $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);
-        }
-    }
-    // }}}
+        $questions = array();
+        $selector = new SurveyQuestion($this);
+        $selector->sid = $this->id;
+        $selector->delete();
 
-    // {{{ 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;
+        $this->reassignQuestionIds();
+        foreach ($this->questions as $question) {
+            $question->sid = $this->id;
+            $question->insert();
         }
-        $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)
+    public function clearQuestions()
     {
-        $sql = 'SELECT title, description, end, mode, promos
-                  FROM surveys
-                 WHERE id={?}';
-        $res = XDB::query($sql, $sid);
-        return $res->fetchOneAssoc();
+        $this->fetchQuestions = true;
+        $this->questions = array();
     }
-    // }}}
 
-    // {{{ static function retrieveSurveyReq() : gets a survey request to validate
-    public static function retrieveSurveyReq($id)
+    public function addQuestion(SurveyQuestion $question, $pos = null)
     {
-        $surveyreq = Validate::get_request_by_id($id);
-        if ($surveyreq == null) {
-            return null;
+        $question->parent = null;
+        if (is_null($pos)) {
+            $this->questions[] = $question;
+        } else {
+            array_splice($this->questions, $pos, 0, $question);
         }
-        $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()
+    public function newQuestion($type, $pos = null)
     {
-        $surveyreq = new SurveyReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions, S::user());
-        return $surveyreq->submit();
+        $question = SurveyQuestion::instanceForType($this, $type);
+        $this->addQuestion($question, $pos);
+        return $question;
     }
-    // }}}
 
-    // {{{ function updateSurvey() : updates a survey in database (before validation)
-    public function updateSurvey()
+    public function questionForId($qid)
     {
-        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;
+        $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);
             }
-            return $surveyreq->updateReq($this->title, $this->description, $this->end, $this->mode, $this->promos, $this->questions);
+            $prev = $question;
         }
+        Platal::assert($prev instanceof SurveyQuestionGroup,
+                       "Id gap must be caused by question groups");
+        return $prev->child($qid);
     }
-    // }}}
 
-    // {{{ functions vote() and hasVoted() : handles vote to a survey
-    public function vote($uid, $args)
+    public function reassignQuestionIds()
     {
-        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);
-                }
+        $id = 0;
+        foreach ($this->questions as $question) {
+            $question->qid = $id;
+            if ($question instanceof SurveyQuestionContainer) {
+                $id = $question->reassignQuestionIds();
+            } else {
+                $id++;
             }
         }
+        return $id;
     }
 
-    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()
+    public function export()
     {
-        return null;
+        $export = parent::export();
+        $export['questions'] = $this->exportQuestions();
+        return $export;
     }
-    // }}}
 
-    // {{{ function checkAnswer : returns a correct answer (or a null value if error)
-    public function checkAnswer($ans)
+    public function exportQuestions()
     {
-        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;
-            }
+        $export = array();
+        foreach ($this->questions as $question) {
+            $export[] = $question->export();
         }
+        return $export;
     }
 
-    public function toArray()
-    {
-        $rArr = parent::toArray();
-        $rArr['choices'] = $this->choices;
-        return $rArr;
-    }
-
-    public function getResultArray($sid, $qid)
+    public function exportQuestionsToJSON()
     {
-        $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();
+        return json_encode($this->exportQuestions());
     }
 
-    public function formatAnswer($ans)
+    /* 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()
     {
-        if (array_key_exists($ans, $this->choices)) {
-            return $this->choices[$ans];
-        } else {
-            return null;
+        if (!$this->flags->hasFlag('validated')) {
+            return -2;
         }
-    }
-}
-// }}}
-
-// {{{ 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;
-            }
+        $now = time();
+        if ($this->begin->format('U') > $now) {
+            return -1;
         }
-        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 ($this->end->format('U') <= $now) {
+            return 1;
         }
+        return 0;
     }
 
-    public function toArray()
+    public function canSee(User $user)
     {
-        $rArr = parent::toArray();
-        $rArr['subquestions'] = $this->subquestions;
-        return $rArr;
+        if ($this->canSeeResults($user) || $this->canVote($user)) {
+            return true;
+        }
+        return false;
     }
 
-    public function getResultArray($sid, $qid)
+    public function canSeeResults(User $user)
     {
-        $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 ($user->id() == $this->uid || $user->hasFlag('admin')) {
+            return true;
         }
-        while ($r = $res->next()) {
-            list($i, $j) = explode(':', $r['answer']);
-            $result[$i][$j] = $r['count'];
+        if (is_null($this->viewerFilter)) {
+            return $this->viewerFilter->checkUser($user);
         }
-        return $result;
+        return false;
     }
 
-    public function formatAnswer($ans)
+    public function canVote(User $user)
     {
-        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;
+        $status = $this->progression();
+        if ($status < 0) {
+            return "Ce sondage n'est pas encore commencé";
+        } else if ($status > 0) {
+            return "Ce sondage est terminé";
+        }
+        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 getCSVColumns()
+    public function vote(User $user, array $answers)
     {
-        $q = parent::getCSVColumns();
-        if (empty($this->subquestions)) {
-            return $q;
+        if (!$this->canVote($user)) {
+            return array('survey' => "Tu n'es pas autorisé à voter à ce sondage.");
+        }
+        $vote = SurveyVote::getVote($this, $user);
+        if (is_null($vote)) {
+            return $vote;
         }
-        $a = array();
-        for ($k = 0; $k < count($this->subquestions); $k++) {
-            $a[$k] = $q.' : '.$this->subquestions[$k];
+        $answers = new PlDict($answers);
+        foreach ($this->questions as $question) {
+            $question->vote($vote, $answers);
         }
-        return $a;
+        return $vote;
     }
-}
-// }}}
 
-// {{{ class SurveyRadioTable extends SurveyTable : SurveyTable with radio type choices
-class SurveyRadioTable extends SurveyTable
-{
-    public function checkAnswer($ans)
+    public static function get($name, $fetchQuestions = true)
     {
-        $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 (is_array($name)) {
+            $name = $name[0];
         }
-        return (count($rep) == 0)? null : $rep;
+        $survey = new Survey();
+        $survey->fetchQuestions = $fetchQuestions;
+        if (can_convert_to_integer($name)) {
+            $survey->id = $name;
+        } else {
+            $survey->shortname = $name;
+        }
+        if (!$survey->fetch()) {
+            return null;
+        }
+        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:
 ?>
similarity index 72%
rename from htdocs/javascript/do_challenge_response_logged.js
rename to modules/survey/text.inc.php
index 29fc83c..0ca61b4 100644 (file)
@@ -1,3 +1,4 @@
+<?php
 /***************************************************************************
  *  Copyright (C) 2003-2011 Polytechnique.org                              *
  *  http://opensource.polytechnique.org/                                   *
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
-function doChallengeResponse() {
-    var new_pass = hash_encrypt(document.forms.login.password.value);
+class SurveyQuestionText extends SurveyQuestion
+{
+    public function __construct(Survey $survey)
+    {
+        parent::__construct($survey);
+        $this->type = "text";
+    }
 
-    str = document.forms.loginsub.username.value + ":" +
-        hash_encrypt(document.forms.login.password.value) + ":" +
-        document.forms.loginsub.challenge.value;
-
-    document.forms.loginsub.response.value = hash_encrypt(str);
-    document.forms.loginsub.remember.value = document.forms.login.remember.checked;
-    document.forms.login.password.value = "";
-    document.forms.loginsub.submit();
+    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 sws=4 foldmethod=marker enc=utf-8:
+// vim:set et sw=4 sts=4 ts=4 foldmethod=marker enc=utf-8:
+?>
index 64ca542..96f563d 100644 (file)
@@ -267,6 +267,25 @@ class XnetEventsModule extends PLModule
         if ($updated !== false) {
             $page->trigSuccess('Ton inscription à l\'événement a été mise à jour avec succès.');
             subscribe_lists_event(S::i('uid'), $evt, ($total > 0 ? 1 : 0), 0);
+
+            if ($evt['subscription_notification'] != 'nobody') {
+                $mailer = new PlMailer('xnetevents/subscription-notif.mail.tpl');
+                if ($evt['subscription_notification'] != 'creator') {
+                    $admins = $globals->asso()->iterAdmins();
+                    while ($admin = $admins->next()) {
+                        $mailer->addTo($admin);
+                    }
+                }
+                if ($evt['subscription_notification'] != 'animator') {
+                    $mailer->addTo($evt['organizer']);
+                }
+                $mailer->assign('group', $globals->asso('nom'));
+                $mailer->assign('event', $evt['intitule']);
+                $mailer->assign('subs', $subs);
+                $mailer->assign('moments', $evt['moments']);
+                $mailer->assign('name', S::user()->fullName('promo'));
+                $mailer->send();
+            }
         }
         $page->assign('event', get_event_detail($eid));
     }
@@ -390,7 +409,7 @@ class XnetEventsModule extends PLModule
                 'short_name'       => $short_name,
             );
 
-            $trivial = array('intitule', 'descriptif', 'noinvite',
+            $trivial = array('intitule', 'descriptif', 'noinvite', 'subscription_notification',
                              'show_participants', 'accept_nonmembre', 'uid');
             foreach ($trivial as $k) {
                 $evt[$k] = Post::v($k);
@@ -411,18 +430,18 @@ class XnetEventsModule extends PLModule
             XDB::execute('INSERT INTO  group_events (eid, asso_id, uid, intitule, paiement_id,
                                                      descriptif, debut, fin, show_participants,
                                                      short_name, deadline_inscription, noinvite,
-                                                     accept_nonmembre)
-                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})
+                                                     accept_nonmembre, subscription_notification)
+                               VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})
               ON DUPLICATE KEY UPDATE  asso_id = VALUES(asso_id), uid = VALUES(uid), intitule = VALUES(intitule),
                                        paiement_id = VALUES(paiement_id), descriptif = VALUES(descriptif), debut = VALUES(debut),
                                        fin = VALUES(fin), show_participants = VALUES(show_participants), short_name = VALUES(short_name),
                                        deadline_inscription = VALUES(deadline_inscription), noinvite = VALUES(noinvite),
-                                       accept_nonmembre = VALUES(accept_nonmembre)',
+                                       accept_nonmembre = VALUES(accept_nonmembre), subscription_notification = VALUES(subscription_notification)',
                          $evt['eid'], $evt['asso_id'], $evt['uid'],
                          $evt['intitule'], $evt['paiement_id'], $evt['descriptif'],
                          $evt['debut'], $evt['fin'], $evt['show_participants'],
                          $evt['short_name'], $evt['deadline_inscription'],
-                         $evt['noinvite'], $evt['accept_nonmembre']);
+                         $evt['noinvite'], $evt['accept_nonmembre'], $evt['subscription_notification']);
 
             // if new event, get its id
             if (!$eid) {
@@ -485,7 +504,7 @@ class XnetEventsModule extends PLModule
             $res = XDB::query(
                     "SELECT  eid, intitule, descriptif, debut, fin, uid,
                              show_participants, paiement_id, short_name,
-                             deadline_inscription, noinvite, accept_nonmembre
+                             deadline_inscription, noinvite, accept_nonmembre, subscription_notification
                        FROM  group_events
                       WHERE eid = {?}", $eid);
             $evt = $res->fetchOneAssoc();
index f8a95e8..1380295 100644 (file)
@@ -34,7 +34,8 @@ function get_event_detail($eid, $item_id = false, $asso_id = null)
                                LEFT(10, e.debut) AS start_day, LEFT(10, e.fin) AS last_day,
                                LEFT(NOW(), 10) AS now,
                                ei.titre, al.vid AS absent_list, pl.vid AS participant_list,
-                               pyl.vid AS payed_list, bl.vid AS booked_unpayed_list
+                               pyl.vid AS payed_list, bl.vid AS booked_unpayed_list,
+                               e.subscription_notification
                          FROM  group_events              AS e
                    INNER JOIN  group_event_items        AS ei ON (e.eid = ei.eid)
                     LEFT JOIN  group_event_participants AS ep ON(e.eid = ep.eid AND ei.item_id = ep.item_id)
index 9274953..68e0d3d 100644 (file)
@@ -48,7 +48,7 @@ class XnetGrpModule extends PLModule
             '%grp/member/new/ajax' => $this->make_hook('admin_member_new_ajax', AUTH_MDP,    'user', NO_AUTH),
             '%grp/member/del'      => $this->make_hook('admin_member_del',      AUTH_MDP,    'groupadmin'),
 
-            '%grp/rss'             => $this->make_hook('rss',                   AUTH_PUBLIC, 'user', NO_HTTPS),
+            '%grp/rss'             => $this->make_token_hook('rss',             AUTH_PUBLIC),
             '%grp/announce/new'    => $this->make_hook('edit_announce',         AUTH_MDP,    'groupadmin'),
             '%grp/announce/edit'   => $this->make_hook('edit_announce',         AUTH_MDP,    'groupadmin'),
             '%grp/announce/photo'  => $this->make_hook('photo_announce',        AUTH_PUBLIC),
@@ -184,22 +184,29 @@ class XnetGrpModule extends PLModule
                     $page->trigError('Ni le nom ni le diminutif du groupe ne peuvent être vide.');
                     return;
                 }
+                $axDate = make_datetime(Post::v('axDate'));
+                if (Post::t('axDate') != '') {
+                    $axDate = make_datetime(Post::v('axDate'))->format('Y-m-d');
+                } else {
+                    $axDate = null;
+                }
                 XDB::execute(
                     "UPDATE  groups
                         SET  nom={?}, diminutif={?}, cat={?}, dom={?},
                              descr={?}, site={?}, mail={?}, resp={?},
-                             forum={?}, mail_domain={?}, ax={?}, pub={?},
+                             forum={?}, mail_domain={?}, ax={?}, axDate = {?}, pub={?},
                              sub_url={?}, inscriptible={?}, unsub_url={?},
-                             flags={?}
+                             flags = {?}, welcome_msg = {?}
                       WHERE  id={?}",
                       Post::v('nom'), Post::v('diminutif'),
                       Post::v('cat'), (Post::i('dom') == 0) ? null : Post::i('dom'),
                       Post::v('descr'), $site,
                       Post::v('mail'), Post::v('resp'),
                       Post::v('forum'), Post::v('mail_domain'),
-                      Post::has('ax'), Post::v('pub'),
+                      Post::has('ax'), $axDate, Post::v('pub'),
                       Post::v('sub_url'), Post::v('inscriptible'),
-                      Post::v('unsub_url'), $flags, $globals->asso('id'));
+                      Post::v('unsub_url'), $flags, Post::t('welcome_msg'),
+                      $globals->asso('id'));
                 if (Post::v('mail_domain')) {
                     XDB::execute('INSERT IGNORE INTO virtual_domains (domain) VALUES({?})',
                                            Post::v('mail_domain'));
@@ -209,13 +216,14 @@ class XnetGrpModule extends PLModule
                     "UPDATE  groups
                         SET  descr={?}, site={?}, mail={?}, resp={?},
                              forum={?}, pub= {?}, sub_url={?},
-                             unsub_url={?},flags={?}
+                             unsub_url = {?}, flags = {?}, welcome_msg = {?}
                       WHERE  id={?}",
                       Post::v('descr'), $site,
                       Post::v('mail'), Post::v('resp'),
                       Post::v('forum'), Post::v('pub'),
                       Post::v('sub_url'), Post::v('unsub_url'),
-                      $flags, $globals->asso('id'));
+                      $flags, Post::t('welcome_msg'),
+                      $globals->asso('id'));
             }
 
 
@@ -401,6 +409,7 @@ class XnetGrpModule extends PLModule
                      . "\n"
                      . "  Suite à ta demande d'adhésion à " . $globals->asso('nom')
                      . ", j'ai le plaisir de t'annoncer que ton inscription a été validée !\n"
+                     . (is_null($globals->asso('welcome_msg')) ? '' : "\n" . $globals->asso('welcome_msg') . "\n")
                      . "\n"
                      . "Bien cordialement,\n"
                      . "-- \n"
@@ -913,11 +922,12 @@ class XnetGrpModule extends PLModule
             // Update group params for user
             $perms = Post::v('group_perms');
             $comm  = Post::t('comm');
-            if ($user->group_perms != $perms || $user->group_comm != $comm) {
+            $position = (Post::t('group_position') == '') ? null : Post::v('group_position');
+            if ($user->group_perms != $perms || $user->group_comm != $comm || $user->group_position != $position) {
                 XDB::query('UPDATE  group_members
-                               SET  perms = {?}, comm = {?}
+                               SET  perms = {?}, comm = {?}, position = {?}
                              WHERE  uid = {?} AND asso_id = {?}',
-                            ($perms == 'admin') ? 'admin' : 'membre', $comm,
+                            ($perms == 'admin') ? 'admin' : 'membre', $comm, $position,
                             $user->id(), $globals->asso('id'));
                 if (XDB::affectedRows()) {
                     if ($perms != $user->group_perms) {
@@ -926,6 +936,9 @@ class XnetGrpModule extends PLModule
                     if ($comm != $user->group_comm) {
                         $page->trigSuccess('Commentaire mis à jour.');
                     }
+                    if ($position != $user->group_position) {
+                        $page->trigSuccess('Poste mis à jour.');
+                    }
                 }
             }
 
@@ -986,19 +999,23 @@ class XnetGrpModule extends PLModule
             }
         }
 
+        $res = XDB::rawFetchAllAssoc('SHOW COLUMNS FROM group_members LIKE \'position\'');
+        $positions = str_replace(array('enum(', ')', '\''), '', $res[0]['Type']);
+
         $page->assign('user', $user);
         $page->assign('listes', $mmlist->get_lists($user->forlifeEmail()));
         $page->assign('alias', $user->emailAliases($globals->asso('mail_domain'), 'user', true));
+        $page->assign('positions', explode(',', $positions));
     }
 
-    function handler_rss(&$page, $user = null, $hash = null)
+    function handler_rss(PlPage& $page, PlUser& $user)
     {
         global $globals;
         $page->assign('asso', $globals->asso());
 
         $this->load('feed.inc.php');
         $feed = new XnetGrpEventFeed();
-        return $feed->run($page, $user, $hash, false);
+        return $feed->run($page, $user, false);
     }
 
     private function upload_image(PlPage &$page, PlUpload &$upload)
index 6e2c4aa..2a4beaa 100644 (file)
@@ -20,6 +20,9 @@
  ***************************************************************************/
 
 function smarty_function_poison($params, &$smarty) {
+    if (S::logged()) {
+        return '';
+    }
     $count = isset($params['count']) ? $params['count'] : 20;
     $seed  = isset($params['seed']) ? $params['seed'] : date('r');
     Platal::load('poison', 'poison.inc.php');
diff --git a/templates/admin/emails_bounces_re.tpl b/templates/admin/emails_bounces_re.tpl
deleted file mode 100644 (file)
index 282cfd7..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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&nbsp;:
-</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: *}
similarity index 52%
rename from templates/survey/admin.tpl
rename to templates/admin/geocoding.tpl
index 5772098..89d88e8 100644 (file)
@@ -1,6 +1,6 @@
 {**************************************************************************}
 {*                                                                        *}
-{*  Copyright (C) 2003-2010 Polytechnique.org                             *}
+{*  Copyright (C) 2003-2011 Polytechnique.org                             *}
 {*  http://opensource.polytechnique.org/                                  *}
 {*                                                                        *}
 {*  This program is free software; you can redistribute it and/or modify  *}
 {*                                                                        *}
 {**************************************************************************}
 
-<h1>Sondages</h1>
+<h1>{$name|ucfirst}</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">
-      &bull;
-      <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 />
+{foreach from=$lists item=list key=list_description}
+{if $list_description eq "manquant"}
+{assign var="fields" value=$main_fields}
+{assign var="action" value="add"}
+{else}
+{assign var="fields" value=$all_fields}
+{assign var="action" value="edit"}
+{/if}
 
+<h2>{$list|@count} {$name} {$list_description}{if $list|@count > 1}s{/if}.</h2>
+{if $list|@count}
 <table class="bicol">
   <tr>
-    <th>
-      Anciens sondages
-    </th>
+    <th>{$id}</th>
+    {foreach from=$fields item=field}
+    <th>{$field}</th>
+    {/foreach}
+    <th>{$action}</th>
   </tr>
-  {iterate item=s from=$survey_old}
-  <tr class="{cycle name=os_cycle values="impair,pair"}">
-    <td class="half">
-      &bull;
-      <a href="survey/admin/{$s.id}">
-        {$s.title} [{$s.end|date_format:"%x"} - {$survey_modes[$s.mode]}]
-      </a>
-    </td>
+{foreach from=$list item=item key=key}
+  <tr>
+    <td>{$key}</td>
+    {foreach from=$fields item=field}
+    {assign var="error" value=$field|cat:'_error'}
+    {assign var="warning" value=$field|cat:'_warning'}
+    <td{if t($item.$error)} class="error"{elseif t($item.$warning)} class="warning"{/if}>{$item.$field}</td>
+    {/foreach}
+    <td><a href="admin/geocoding/{$category}/{$action}/{$key}">{icon name="page_edit"}</a></td>
   </tr>
-  {assign var="has_os" value="true"}
-  {/iterate}
-  {if !$has_os}
+{/foreach}
   <tr>
-    <td class="half">Aucun ancien sondage</td>
+    <th>{$id}</th>
+    {foreach from=$fields item=field}
+    <th>{$field}</th>
+    {/foreach}
+    <th>{$action}</th>
   </tr>
-  {/if}
 </table>
+{/if}
+{/foreach}
+
+<form method="post" action="admin/geocoding/{$category}/add">
+  {xsrf_token_field}
+  <p>
+    Ajouter un champ (n'indiquer que l'indentifiant principal)&nbsp;:
+    <input type="text" name="new_id" size="3" maxlength="3" />
+    <input type="submit" value="Ajouter" />
+  </p>
+</form>
 
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+{* vim:set et sw=2 sts=2 sws=2 enc=utf-8: *}
similarity index 60%
rename from templates/survey/show_textarea.tpl
rename to templates/admin/geocoding_edit.tpl
index 12fe1fc..72f598d 100644 (file)
 {*                                                                        *}
 {**************************************************************************}
 
-{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&nbsp;:
-    <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>
+<h1><a href="admin/geocoding/{$category}">{$name|ucfirst}&nbsp;: édition</a></h1>
+
+<form method="post" action="admin/geocoding/{$category}/edit/{$id}">
+  {xsrf_token_field}
+
+  {if $iso|@count eq 0}
+  <p class="error">Cet élément ne figure pas dans la liste ISO.</p>
   {/if}
-{else}
-  <textarea name="survey{$survey.id}[{$squestion.id}]" rows="5" cols="60" {if !$survey_votemode}disabled="disabled"{/if}></textarea>
-{/if}
+  <table class="tinybicol">
+    <tr>
+      <th>Champs</th>
+      <th>Élément</th>
+      <th>Données ISO</th>
+    </tr>
+    {foreach from=$all_fields item=field}
+    <tr>
+      <th>{$field}</th>
+      <td>
+        <input type="text" name="{$field}" value="{$item.$field}"
+               {if t($iso.$field)}{if !$item.$field} class="warning"{elseif $iso.$field neq $item.$field} class="error"{/if}{/if} />
+      </td>
+      <td>{if t($iso.$field)}{$iso.$field}{/if}</td>
+    </tr>
+    {/foreach}
+  </table>
+
+  <p class="center">
+    <input type="submit" name="edit" value="Éditer" />&nbsp;&nbsp;&nbsp;
+    <input type="submit" name="del" value="Supprimer" onclick="return confirm('Es-tu sûr de vouloir supprimer cet élément&nbsp;?')" />
+  </p>
+</form>
 
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+{* vim:set et sw=2 sts=2 sws=2 enc=utf-8: *}
index 297a4c8..2af78b5 100644 (file)
@@ -32,8 +32,6 @@
       <a href="admin/postfix/whitelist">Whitelist</a>
       &nbsp;&nbsp;|&nbsp;&nbsp;
       <a href="admin/postfix/delayed">Retardés</a>
-      &nbsp;&nbsp;|&nbsp;&nbsp;
-      <a href="admin/postfix/regexp_bounces">Regexps Bounces</a>
     </td>
   </tr>
   <tr class="pair">
 
   <tr><th colspan="2">{icon name=user_gray} Champs</th></tr>
   <tr class="impair">
+    <td class="titre">Pays / Langues</td>
+    <td>
+      <a href="admin/geocoding/country">Pays</a>
+      &nbsp;&nbsp;|&nbsp;&nbsp;
+      <a href="admin/geocoding/language">Langues</a>
+    </td>
+  </tr>
+  <tr class="impair">
     <td class="titre">Formation</td>
     <td>
       <a href="admin/education">Formations</a>
index 10ad40a..2f448ea 100644 (file)
@@ -93,7 +93,7 @@ function ban_read()
     document.forms.bans.read_perm.value = "!xorg.*";
 }
 
-$(document).ready(function() {
+$(function() {
   $('#tabs').tabs();
   $('.ui-tabs-nav li').width('24%')
     .click(function() { $(this).children('a').click() });
index 2bbcee4..45b9201 100644 (file)
@@ -28,7 +28,7 @@
 </div>
 <br />
 
-<form action="{$smarty.server.REQUEST_URI}" method="post" id="login" onsubmit='doChallengeResponse(); return false;'>
+<form action="{$smarty.server.REQUEST_URI}" method="post" id="login" onsubmit='doChallengeResponseLogged(); return false;'>
   <table class="bicol" cellpadding="4" summary="Formulaire de login">
     <tr>
       <td class="titre">
index f588dc3..628cf37 100644 (file)
@@ -24,7 +24,7 @@
 
 <script type="text/javascript">//<![CDATA[
   {literal}
-  $(document).ready(function() {
+  $(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() {
index 69aef02..de94958 100644 (file)
@@ -25,7 +25,7 @@
 {literal}
 <script type="text/javascript">
   //<![CDATA[
-  $(document).ready(function() {
+  $(function() {
       var url = '{/literal}{$globals->baseurl}/emails/best/{literal}';
       var tok = '{/literal}{xsrf_token}{literal}';
       var msg = "Le changement a bien été effectué.";
index 263fce4..1434bc5 100644 (file)
@@ -65,7 +65,7 @@
     for (var i = 0 ; i < form['cc_contacts[]'].length ; ++i) {
       ccc += form['cc_contacts[]'].options[i].value + ";";
     }
-    $.post(platal_baseurl + "emails/send",
+    $.xpost("emails/send",
            { save: true,
              token: '{xsrf_token}',
              from: form.from.value,
       saveMessage();
       return true;
     });
-  $(document).ready(
+  $(
     function() {
       // Remove empty options in select (they were added only for HTML
       // compatibility).
       $('#cc_contacts option[value=""]').remove();
     });
 
-    $(document).ready(function() {
+    $(function() {
       $("[name='to']").focus();
     });
   {/literal}
index b5e9bcb..6f7aa84 100644 (file)
       document.getElementById('info').style.display = 'none';
     }
     var page  = 'events/preview?titre=' + encodeURIComponent(titre) + '&texte=' + encodeURIComponent(texte);
-    if (is_IE) {
-      {/literal}
-      page = "{$globals->baseurl}/" + page;
-      {literal}
-    }
     $('#preview').updateHtml(page);
     return false;
   }
index 3ffa0e7..f103aec 100644 (file)
@@ -66,7 +66,7 @@ trouver une correspondance entre les personnes renseignés dans ces annuaires.<b
 <script type="text/javascript">
 {literal}
 //<!--
-$(document).ready(function() {
+$(function() {
     $('#autolink a.fusion-action').click(function(a){
         $.get(a.currentTarget.href,{},function(){
             $(a.currentTarget).hide();
index 0b01fff..deb7ec6 100644 (file)
@@ -23,7 +23,7 @@
 <script type="text/javascript">
 {literal}
 //<!--
-    $(document).ready(function() {
+    $(function() {
         $('#fusionax_import input').click(function() {
             $('#fusionax input').hide();
             $('#fusionax').append('Lancement de l\'import.<br/>');
index 12cc8fe..6349484 100644 (file)
@@ -24,8 +24,8 @@
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     <link rel="stylesheet" type="text/css" href="css/base.css" media="all"/>
     <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=jquery.xorg}
+    {javascript name=core}
     {javascript name=xorg}
     {javascript name=igoogle}
   </head>
index d4227a8..b1a3f7e 100644 (file)
   {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[
index 1f91e85..5d73119 100644 (file)
 <label><input type="radio" name="assotype" value="" {if !$valid->asso}checked="checked"{/if} />quelconque</label>
 <label><input type="radio" name="assotype" value="alias" {if $valid->asso eq "alias"}checked="checked"{/if} />alias</label>
 <label><input type="radio" name="assotype" value="groupex" {if $valid->asso eq "groupex"}checked="checked"{/if} />groupe X</label><br />
-<strong>Domaine&nbsp;:</strong> <input type="text" name="domainname" size="25" maxlength="200" value="{$valid->domain}" />
+<strong>Domaine&nbsp;:</strong> <input type="text" name="domainname" size="25" maxlength="200" value="{$valid->domain}" /><br />
+<strong>Gestionnaires&nbsp;:</strong>
+{foreach from=$valid->owners item=email key=i}
+<input type="text" name="owners_{$i}" size="40" value="{$email}" /><br />
+{/foreach}
+<strong>Membres&nbsp;:</strong>
+{foreach from=$valid->members item=email key=i}
+<input type="text" name="members_{$i}" size="40" value="{$email}" /><br />
+{/foreach}
 
 {* vim:set et sw=2 sts=2 sws=2 enc=utf-8: *}
index 36bce05..6320468 100644 (file)
@@ -25,7 +25,7 @@
   {literal}
   function updateHtml(id, url)
   {
-      if (is_IE) {
+      if ($.browser.msie) {
           return true;
       } else {
           $('#' + id).updateHtml(url);
index 0647738..3dbe870 100644 (file)
 {*                                                                        *}
 {**************************************************************************}
 
+{if t($anchor)}
+{literal}
+<script type="text/javascript">
+//<![CDATA[
+$(function() {
+{/literal}
+  location.hash = "#{$anchor}";
+{literal}
+});
+// ]]>
+</script>
+{/literal}
+{/if}
+
 <h1>{$asso->nom}&nbsp;: Gestion des télépaiements </h1>
 
 <p class="descr">
 Voici la liste des paiements en ligne possible pour le groupe {$asso->nom}&nbsp;:
 </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.
@@ -68,51 +82,51 @@ Voici la liste des paiements en ligne possible pour le groupe {$asso->nom}&nbsp;
 <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}&amp;order_inv={$order_inv}&amp;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&amp;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}&amp;order_inv={$order_inv}&amp;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&amp;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}&amp;order_inv={$order_inv}&amp;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&amp;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&amp;order_inv={$order_inv}&amp;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&amp;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}&amp;order_inv={$order_inv}&amp;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&amp;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>
index 61c00d3..985ed11 100644 (file)
@@ -27,7 +27,7 @@
 <script type="text/javascript">
 {literal}
 /* <![CDATA[ */
-$(document).ready(function() {
+$(function() {
   $("form input:radio").change(function() {
     $("#form").submit();
   });
index 4556f89..e5bea8d 100644 (file)
@@ -37,7 +37,7 @@ Pour toute information complémentaire, n'hésite pas à écrire à
   <tr>
     <td class="skigauche">
       <input type="radio" name="newskin" value="{$skin.id}" {if $skin_id eq $skin.id}checked="checked"{/if}
-        onclick="dynpostkv('prefs/skin', 'newskin', {$skin.id})" />
+        onclick="$.dynPost('prefs/skin', 'newskin', {$skin.id})" />
     </td>
     <td class="skimilieu">
       <strong>{$skin.name}</strong>
index 922f938..18313db 100644 (file)
 {*                                                                        *}
 {**************************************************************************}
 
+<script type="text/javascript">
+  $($.closeOnEsc);
+</script>
+
 {assign var=terms value=$profile->getMentoringTerms()}
 {assign var=countries value=$profile->getMentoringCountries()}
 <div id="fiche">
index f350a6a..b1dade3 100644 (file)
           {foreach from=$job.terms item=term}
           addJobTerm("{$i}", "{$term.jtid}", "{$term.full_name|replace:'"':'\\"'}");
           {/foreach}
-          $('#jobs_{$i} .term_search').autocomplete(platal_baseurl + 'profile/jobterms',
+          $('#jobs_{$i} .term_search').autocomplete($.plURL('profile/jobterms'),
             {ldelim}
               "formatItem" : displayJobTerm,
               "extraParams" : {ldelim} "jobid" : "{$i}" {rdelim},
       <td colspan="2" class="term_tree">
       </td>
     </tr>
+    <tr class="pair" id="term_tree_comment" style="display: none">
+      <td colspan="2" class="center"><small>La catégorie « Emplois » donne une liste de métiers, « Secteurs d'activité » décrit des secteurs.</small></td>
+    </tr>
     <tr class="pair" {if $hiddenjob}style="display: none"{/if}>
       <td class="titre">Description</td>
       <td>
index 5fc41e3..2d942ef 100644 (file)
         {foreach from=$terms item=term}
         addJobTerm(-1, "{$term.jtid}", "{$term.full_name|replace:'"':'\\"'}");
         {/foreach}
-        $('.term_search').autocomplete(platal_baseurl + 'profile/jobterms',
+        $('.term_search').autocomplete($.plURL('profile/jobterms'),
           {ldelim}
             "formatItem" : displayJobTerm,
             "extraParams" : {ldelim} "jobid" : "-1" {rdelim},
index 967bf7e..2df497b 100644 (file)
@@ -24,7 +24,7 @@
 <script type="text/javascript">//<![CDATA[
 function chgMainWinLoc(strPage)
 {
-  strPage = platal_baseurl + strPage;
+  strPage = $.plURL(strPage);
   if (parent.opener) {
     try {
       parent.opener.document.location = strPage;
@@ -36,6 +36,9 @@ function chgMainWinLoc(strPage)
     document.location = strPage;
   }
 }
+
+$($.closeOnEsc);
+
 //]]></script>
 {/literal}
 
index 280aa92..7b423a8 100644 (file)
@@ -76,7 +76,7 @@
       <select name="langues_sel" onchange="updateElement('langues')">
         <option value="">&nbsp;</option>
         {iterate from=$lang_list item=lang}
-        <option value="{$lang.id}">{$lang.langue_fr}</option>
+        <option value="{$lang.iso_639_2b}">{$lang.language}</option>
         {/iterate}
       </select>
       <span id="langues_add" style="display: none">
index e8d938f..fbd5e05 100644 (file)
@@ -28,7 +28,7 @@
 il te suffit de taper ton mot de passe ci-dessous. Tu pourras ensuite librement
 accéder au site, et à notre annuaire en ligne&nbsp;!</p>
 
-<form action="{$smarty.server.REQUEST_URI}" method="post" id="login" onsubmit='doChallengeResponse(); return false;'>
+<form action="{$smarty.server.REQUEST_URI}" method="post" id="login" onsubmit='doChallengeResponseLogged(); return false;'>
   <table class="bicol">
     <tr>
       <td class="titre">Nom d'utilisateur&nbsp;:</td>
index 94b171d..ebfe16d 100644 (file)
           <dd>
             de recevoir les informations importantes de l'AX.
           </dd>
-          {if $smarty.session.subState.eduType eq 'x'}
           <dt><label><input type="checkbox" checked="checked" name="ml_promo" /> ta promotion</label></dt>
           <dd>
             de recevoir les informations plus spécifiques de ta promotion pour pouvoir participer plus facilement aux événements
           <dd>
             d'avoir un accès de secours aux 30 derniers jours d'emails reçus sur ton adresse Polytechnique.org.
           </dd>
-          {/if}
         </dl>
       </td>
     </tr>
index 5613057..ecc0301 100644 (file)
 <p class="center"><strong>Voulez-vous télécharger le <a href="{$globals->baseurl}/search/adv/addresses{$plset_args}">tableau des adresses postales</a> pour la recette précédente&nbsp;?</strong></p>
 {/if}
 
-{javascript name=jquery.form}
-
 <script type="text/javascript">// <!--
-  var baseurl = platal_baseurl + "search/";
+  var baseurl = $.plURL("search/");
   {literal}
-  String.prototype.htmlEntities = function () {
-    return this.replace(/&/g,'&amp;').replace(new RegExp('<','g'),'&lt;').replace(/>/g,'&gt;');
-  };
+
   // display an autocomplete row : blabla (nb of found matches)
   function make_format_autocomplete(block) {
     return function(row) {
       }
     }
 
-  $(document).ready(function() {
+  $(function() {
       $(".autocompleteTarget").hide();
       $(".autocomplete").show().each(function() {
         targeted = $("../.autocompleteTarget",this)[0];
@@ -285,7 +281,7 @@ function cleanForm(f) {
               f.egal2.value = '>=';
             }
           }
-          $(document).ready(function() { updatepromofields($('select[name=egal1]')[0]); });
+          $(function() { updatepromofields($('select[name=egal1]')[0]); });
           {/literal}
         /*]]>*/</script>
         <select name="egal1" onchange="updatepromofields(this)" style="text-align:center">
@@ -524,6 +520,7 @@ function cleanForm(f) {
       </td>
         {/if}
         {if $smarty.session.auth ge AUTH_COOKIE}
+    </tr>
     <tr>
       <td colspan="2">
           <input type='checkbox' name='order' value='date_mod' {if $smarty.request.order eq "date_mod"}checked='checked'{/if} id="order"/>
index 904e6ed..b8988b3 100644 (file)
@@ -47,7 +47,7 @@
   {if $search_results_nb eq 1}{literal}
     <script type="text/javascript">
       // popup automatically if only one result
-      $(document).ready(function() {
+      $(function() {
         $('#content a.popup2').click();
       });
     </script>
index e05423d..f513fc4 100644 (file)
@@ -66,7 +66,7 @@
 {if $show_js}
 {literal}
 <script type="text/javascript">
-  $(document).ready(function() {
+  $(function() {
     $("#quick_form input[name='quick']").focus();
   });
 </script>
index 40559e6..f11a265 100644 (file)
@@ -37,7 +37,7 @@ Actuellement, {$mentors_number} mentors et référents se sont déclarés sur {#
 {javascript name=jobtermstree}
 <script type="text/javascript">//<![CDATA[
 
-var baseurl = platal_baseurl + "referent/";
+var baseurl = $.plURL("referent/");
 {literal}
 
 /** Hides or display tree of all job terms */
@@ -81,7 +81,7 @@ function updateJobTerm(jtid, country)
   $('#jobterm').val(jtid);
   $('#country_chg').closest('tr').show();
   $('#keywords').show();
-  $('#country_chg').load(platal_baseurl + 'search/referent/countries/' + jtid, function(response, status, xhr) {
+  $('#country_chg').load($.plURL('search/referent/countries/' + jtid), function(response, status, xhr) {
     if (country) {
       if (status != "error") {
         $('#country_chg select').val(country);
index c904f1c..e790abd 100644 (file)
@@ -24,7 +24,7 @@
   incluez le fichier http://www.polytechnique.org/bandeau dans vos php
   ou http://www.polytechnique.org/bandeau/login pour profiter du login
   automatique. Et rajoutez à la liste de css de vos pages
-  http://www.polytechnique.org/bandeau.css.
+  http://www.polytechnique.org/css/bandeau.css.
   Pour avoir l'icone, pour des raisons de sécurité il n'y a pas d'accès
   direct, il faut alors rediriger bandeau/icone.png vers celle du site&nbsp;:
   http://www.polytechnique.org/bandeau/icone.png
@@ -45,7 +45,7 @@
 
 
 <div id="bandeau-X">
-  <img src="bandeau/icone.png" alt=""/>
+  <img src="{if $external}bandeau/icone.png{else}images/x.png{/if}" width="13" height="14" alt=""/>
   <a href="http://www.polytechnique.fr/">L'&Eacute;cole</a> &middot;
   <a href="http://www.polytechnique.edu/">Institutional site</a>
   &tilde;&tilde;
index 78affff..fc1558f 100644 (file)
@@ -29,7 +29,7 @@
     <link rel="apple-touch-icon" href="images/logo.png" type="image/png" />
 
     <link rel="stylesheet" type="text/css" href="css/base.css" media="all"/>
-    <link rel="stylesheet" type="text/css" href="css/print.css" media="print"/>
+    <link rel="stylesheet" type="text/css" href="css/bandeau.css" />
 
     <link rel="index"  href="index" />
     <link rel="author" href="changelog" />
index f574601..95ee884 100644 (file)
@@ -26,7 +26,7 @@
     <td class="inscrits">
       {$globals->core->NbIns|number_format} polytechniciens sur le web
       {if t($smarty.request.quick)}
-        {assign var=requestQuick value=$smarty.request.quick}
+        {assign var=requestQuick value=$smarty.request.quick|smarty:nodefaults}
       {else}
         {assign var=requestQuick value='Recherche dans l\'annuaire'}
       {/if}
index 696dc7a..3b99315 100644 (file)
@@ -23,7 +23,6 @@
 {include file=skin/common.doctype.tpl}
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index ea8d1f2..6e6bf9b 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/espace.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index dac7c4d..3b4e58d 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/humlinux.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index e31a983..1e473da 100644 (file)
@@ -23,7 +23,6 @@
 {include file=skin/common.doctype.tpl}
     <link rel="stylesheet" type="text/css" href="css/keynote.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index c8b017f..6f3dfcc 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/linux.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index dcbbad1..2d8231c 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/liteskin.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index fc46d53..09f8ce2 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/nbviolet.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index 9dd40f8..bd2e552 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/newxorg.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index 46b9abd..3077d5b 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/oldtimes.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index 519442e..aad38c6 100644 (file)
@@ -23,7 +23,6 @@
 {include file=skin/common.doctype.tpl}
     <link rel="stylesheet" type="text/css" href="css/openweb.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index fa7acdb..047629e 100644 (file)
@@ -23,7 +23,6 @@
 {include file=skin/common.doctype.tpl}
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index e8e18b8..a2fe7ea 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/sharky.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index be3b1c5..68752a1 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/spectral.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
index ce5db23..7c1f581 100644 (file)
@@ -24,7 +24,6 @@
     <link rel="stylesheet" type="text/css" href="css/default.css" media="all" />
     <link rel="stylesheet" type="text/css" href="css/trapped.css" media="all" />
     {include file=skin/common.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
diff --git a/templates/survey/confirm.tpl b/templates/survey/confirm.tpl
deleted file mode 100644 (file)
index b6f5552..0000000
+++ /dev/null
@@ -1,40 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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&nbsp;: 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: *}
diff --git a/templates/survey/edit.questions.tpl b/templates/survey/edit.questions.tpl
new file mode 100644 (file)
index 0000000..4fbfceb
--- /dev/null
@@ -0,0 +1,128 @@
+{**************************************************************************}
+{*                                                                        *}
+{*  Copyright (C) 2003-2011 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               *}
+{*                                                                        *}
+{**************************************************************************}
+
+{literal}
+<script id="q_edit_new" type="text/x-jquery-tmpl">
+  <fieldset style="clear: both; padding-top: 1em; background: inherit; color: inherit"
+            class="q_edit" id="q_edit[${qid}]">
+    <legend>
+      <span class="q_edit_label" style="font-weight: bold">Question ${qid + 1}</span> 
+      <input type="text" name="q_edit[${qid}][label]" value="{{if label}}${label}{{/if}}" />
+      (<a onclick="$(this).removeQuestion()" style="text-decoration: none">
+        {/literal}{icon name="delete"}{literal} Supprimer
+      </a>)<br />
+      Type de question&nbsp;: <select name="q_edit[${qid}][type]">
+        <option value=""></option>
+        <option value="section" {{if type}}{{if type == 'section'}}selected="selected"{{/if}}{{/if}}>
+          Section
+        </option>
+        <option value="text" {{if type}}{{if type == 'text'}}selected="selected"{{/if}}{{/if}}>
+          Champ libre
+        </option>
+        <option value="multiple" {{if type}}{{if type == 'multiple'}}selected="selected"{{/if}}{{/if}}>
+          Question à choix multiples
+        </option>
+      </select>
+    </legend>
+    <div class="q_edit_form">
+      {{tmpl "#q_edit_base"}}
+    </div>
+  </fieldset>
+</script>
+
+<script id="q_edit_base" type="text/x-jquery-tmpl">
+  {{if type}}
+    {{tmpl "#q_edit_" + type}}
+  {{/if}}
+</script>
+
+<script id="q_edit_text" type="text/x-jquery-tmpl">
+  Type de texte&nbsp;:
+  <select name="q_edit[${qid}][subtype]">
+    <option value="monoline" {{if subtype}}{{if subtype == 'monoline'}}selected="selected"{{/if}}{{/if}}>
+      Une seule ligne
+    </option>
+    <option value="multiline" {{if subtype}}{{if subtype == 'multiline'}}selected="selected"{{/if}}{{/if}}>
+      Plusieurs lignes
+    </option>
+  </select>
+</script>
+
+<script id="q_edit_section" type="text/x-jquery-tmpl">
+  <div>
+    Type de section&nbsp;:
+    <select name="q_edit[${qid}][subtype]">
+      <option value="group" {{if subtype}}{{if subtype == 'group'}}selected="selected"{{/if}}{{/if}}>
+        Groupe de questions
+      </option>
+      <option value="page" {{if subtype}}{{if subtype == 'page'}}selected="selected"{{/if}}{{/if}}>
+        Nouvelle page
+      </option>
+    </select>
+  </div>
+  <div id="q_edit[${qid}][section]">
+    <div class="add_question">
+      <a onclick="$(this).addQuestion()" style="text-decoration: none">
+        {/literal}{icon name="add"}{literal} Ajouter une question
+      </a>
+    </div>
+  </div>
+</script>
+
+<script id="q_edit_multiple" type="text/x-jquery-tmpl">
+  <div id="q_edit[${qid}][answers]">
+    <div>
+      Permettre la sélection de plusieurs réponses ?
+      <select name="q_edit[${qid}][subtype]">
+        <option value="checkbox" {{if subtype}}{{if subtype == 'checkbox'}}selected="selected"{{/if}}{{/if}}>
+          Oui
+        </option>
+        <option value="radio" {{if subtype}}{{if subtype == 'radio'}}selected="selected"{{/if}}{{/if}}>
+          Non
+        </option>
+      </select>
+    </div>
+    <div class="add_answer">
+      <a onclick="$(this).multiple_addAnswer()">
+        {/literal}{icon name="add"}{literal} Ajouter une réponse
+      </a>
+    </div>
+    <div>
+      Ajouter une case Autre ?
+      <select name="q_edit[${qid}][allow_other]">
+        <option value="1" {{if allow_other}}selected="selected"{{/if}}>Oui</option>
+        <option value="" {{if !allow_other}}selected="selected"{{/if}}>Non</option>
+      </select>
+    </div>
+  </div>
+</script>
+
+<script id="q_edit_multiple_answer" type="text/x-jquery-tmpl">
+  <div>
+    <span class="q_edit_answer_box"></span>
+    <input type="text" name="q_edit[${qid}][answers][]" value="${value}" />
+    <a onclick="$(this).multiple_removeAnswer()">{/literal}{icon name="delete"}{literal}</a>
+  </div>
+</script>
+{/literal}
+
+{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
diff --git a/templates/survey/edit.tpl b/templates/survey/edit.tpl
new file mode 100644 (file)
index 0000000..d2abf46
--- /dev/null
@@ -0,0 +1,76 @@
+{**************************************************************************}
+{*                                                                        *}
+{*  Copyright (C) 2003-2011 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>Edition de sondage</h1>
+
+<form action="survey/edit/{$survey->shortname}" method="post" id="form">
+  <fieldset>
+    <legend>Description du sondage</legend>
+
+    Titre&nbsp;: <input type="text" name="title" value="{$survey->title}" /><br />
+    Nom&nbsp;: <input type="text" name="shortname" value="{$survey->shortname}" /><br />
+    Description&nbsp;:<br /><textarea name="description" style="width: 100%">{$survey->description}</textarea>
+  </fieldset>
+
+  <fieldset>
+    <legend>Paramètre du sondage</legend>
+    Premier jour&nbsp;: <input type="text" class="datepicker" name="begin" value="{$survey->begin}" /><br />
+    Dernier jour&nbsp;: <input type="text" class="datepicker" name="end" value="{$survey->end}" /><br />
+    Sondage anonyme&nbsp;: <label>Oui&nbsp;<input type="radio" name="anonymous" value="1" checked="checked" /></label>
+    <label><input type="radio" name="anonymous" value="0" />&nbsp;Non</label>
+  </fieldset>
+
+  <h2>Questions</h2>
+
+  <div id="questions" class="q_edit">
+    <div class="add_question">
+      <a onclick="$(this).addQuestion()" style="text-decoration: none">
+        {icon name="add"} Ajouter une question
+      </a>
+    </div>
+  </div>
+
+  <div class="center">
+    <input type="submit" name="valid" value="Soumettre" />
+  </div>
+</form>
+
+{include file="survey/vote.questions.tpl"}
+{include file="survey/edit.questions.tpl"}
+
+{literal}
+<script type="text/javascript">
+  //<![CDATA[
+  var questions = {/literal}{$survey->exportQuestionsToJSON()|smarty:nodefaults}{literal};
+
+  $(function() {
+    $('#form').submit(function() {
+      $(this).buildParentsQuestions();
+      return true;
+    });
+    $('#questions').prepareQuestions(questions);
+  });
+  //]]>
+</script>
+{/literal}
+
+{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
diff --git a/templates/survey/edit_checkbox.tpl b/templates/survey/edit_checkbox.tpl
deleted file mode 100644 (file)
index 3569cb6..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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'}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
diff --git a/templates/survey/edit_checkboxtable.tpl b/templates/survey/edit_checkboxtable.tpl
deleted file mode 100644 (file)
index 14b11d9..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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_radiotable.tpl'}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
diff --git a/templates/survey/edit_new.tpl b/templates/survey/edit_new.tpl
deleted file mode 100644 (file)
index ea6d666..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/edit_newsurvey.tpl b/templates/survey/edit_newsurvey.tpl
deleted file mode 100644 (file)
index ec9e61e..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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 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'}
-
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
diff --git a/templates/survey/edit_num.tpl b/templates/survey/edit_num.tpl
deleted file mode 100644 (file)
index b62ed4b..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/edit_question.tpl b/templates/survey/edit_question.tpl
deleted file mode 100644 (file)
index 11e0858..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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="" />&nbsp;'
-            + '<a href="javascript:removeField(&quot;' + name + '&quot;,&quot;' + fid + '&quot;)"><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: *}
diff --git a/templates/survey/edit_radio.tpl b/templates/survey/edit_radio.tpl
deleted file mode 100644 (file)
index 8b4e1b2..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/edit_radiotable.tpl b/templates/survey/edit_radiotable.tpl
deleted file mode 100644 (file)
index 0e034c3..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/edit_root.tpl b/templates/survey/edit_root.tpl
deleted file mode 100644 (file)
index 3bc93cf..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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&nbsp;: 1954,1986-1989,-1942,2000-&nbsp;&nbsp;&nbsp;restreindra le sondage à toutes les promotions suivantes&nbsp;:<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: *}
diff --git a/templates/survey/edit_survey.tpl b/templates/survey/edit_survey.tpl
deleted file mode 100644 (file)
index 0d3160b..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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&nbsp;:
-  {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: *}
diff --git a/templates/survey/edit_text.tpl b/templates/survey/edit_text.tpl
deleted file mode 100644 (file)
index b62ed4b..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/edit_textarea.tpl b/templates/survey/edit_textarea.tpl
deleted file mode 100644 (file)
index b62ed4b..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/error.tpl b/templates/survey/error.tpl
deleted file mode 100644 (file)
index 63c96d4..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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&nbsp;: 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>&bull; {$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: *}
index 294a558..6f8d914 100644 (file)
 
 <h1>Sondages</h1>
 
-{* Survey::MODE_ALL equals 0. *}
-{assign var=SurveyMODE_ALL value=0}
-{if $survey_current->total() > 0 || $smarty.session.auth}
-<table class="bicol">
+{if $active->total() > 0}
+<table class="bicol" id="surveyList">
   <tr>
-    <th colspan="3">
+    <th>
       Sondages en cours
     </th>
+    {if hasPerm('admin')}
+    <th></th>
+    {/if}
   </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>
+  {iterate from=$active item=survey}
+  <tr class="{cycle values="impair,pair"}">
     <td>
-      {$s.end|date_format:"%x"}
+      <a href="survey/vote/{$survey->shortname}">{$survey->title}</a>
     </td>
-    <td>
-      {$survey_modes[$s.mode]}
+    {if hasPerm('admin')}
+    <td style="text-align: right">
+      <a href="survey/edit/{$survey->shortname}">{icon name=page_edit}</a>
     </td>
+    {/if}
   </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">
-  <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]}
-    </td>
-  </tr>
-      {assign var="has_os" value="true"}
-    {/if}
-  {/iterate}
-  {if !$has_os}
-  <tr>
-    <td class="half">Aucun ancien sondage</td>
-  </tr>
-  {/if}
-</table>
+<div class="center">
+  <a href="survey/edit">{icon name=page_edit} Proposer un nouveau sondage</a>
+</div>
 
 {* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
diff --git a/templates/survey/show_checkbox.tpl b/templates/survey/show_checkbox.tpl
deleted file mode 100644 (file)
index 8fc5388..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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]}&nbsp;: {$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: *}
diff --git a/templates/survey/show_num.tpl b/templates/survey/show_num.tpl
deleted file mode 100644 (file)
index 37ca12f..0000000
+++ /dev/null
@@ -1,25 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/show_question.tpl b/templates/survey/show_question.tpl
deleted file mode 100644 (file)
index 4acb162..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/show_radio.tpl b/templates/survey/show_radio.tpl
deleted file mode 100644 (file)
index 473bb05..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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]}&nbsp;: {$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: *}
diff --git a/templates/survey/show_radiotable.tpl b/templates/survey/show_radiotable.tpl
deleted file mode 100644 (file)
index 9f24aa1..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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: *}
diff --git a/templates/survey/show_root.tpl b/templates/survey/show_root.tpl
deleted file mode 100644 (file)
index ca606fd..0000000
+++ /dev/null
@@ -1,117 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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&nbsp;: {$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&nbsp;:</td>
-        <td>{$survey.end|date_format:"%x"}</td>
-      </tr>
-      <tr>
-        <td class="titre">Type de sondage&nbsp;:</td>
-        <td>{$survey_modes[$survey.mode]}</td>
-      </tr>
-      {if $survey.mode != Survey::MODE_ALL}
-      <tr>
-        <td class="titre">Promotions&nbsp;:</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: *}
diff --git a/templates/survey/show_text.tpl b/templates/survey/show_text.tpl
deleted file mode 100644 (file)
index 595b171..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-{**************************************************************************}
-{*                                                                        *}
-{*  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&nbsp;:
-    <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: *}
similarity index 57%
rename from templates/survey/show_checkboxtable.tpl
rename to templates/survey/vote.questions.tpl
index 22f9bd3..a7ad4e1 100644 (file)
 {*                                                                        *}
 {**************************************************************************}
 
-<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>
+{literal}
+<script id="question_base" type="text/x-jquery-tmpl">
+  {{tmpl "#question_" + type}}
+</script>
+
+<script id="question_section" type="text/x-jquery-tmpl">
+  <fieldset>
+    <legend>${label}</legend>
+
+    {{tmpl(children) "#question_base"}}
+  </fieldset>
+</script>
+
+<script id="question_text" type="text/x-jquery-tmpl">
+  <div>
+    {{if subtype}}
+      {{if subtype == 'monoline'}}
+        <strong>${label}</strong>&nbsp;:
+        <input type="text" name="qid[${qid}]" value="" />
+      {{else}}
+        <div><strong>${label}</strong></div>
+        <textarea name="qid[${qid}]" rows="4" cols="80"></textarea>
+      {{/if}}
+    {{else}}
+      <strong>${label}</strong>&nbsp;:
+      <input type="text" name="qid[${qid}]" value="" />
+    {{/if}}
+  </div>
+</script>
+
+<script id="question_multiple" type="text/x-jquery-tmpl">
+  <div>
+    <div><strong>${label}</strong></div>
+    {{each answers}}
+      <input type="${subtype}" name="qid[${qid}][answers][${$index}]" value="${$value}" /> ${$value}<br />
+    {{/each}}
+    {{if allow_other}}
+      <input type="${subtype}" name="qid[${qid}][answers][other]" value="other" /> Autre, préciser&nbsp;:
+      <input type="text" name="qid[${qid}][other]" />
+    {{/if}}
+  </div>
+</script>
+{/literal}
 
 {* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
similarity index 74%
rename from templates/skin/common.bandeau.head.tpl
rename to templates/survey/vote.tpl
index 1846e97..0a771da 100644 (file)
 {*                                                                        *}
 {**************************************************************************}
 
-<link rel="stylesheet" media="screen" type="text/css" href="css/bandeau.css"/>
+<h1>{$survey->title}</h1>
 
-{* vim:set et sw=2 sts=2 sws=2 enc=utf-8: *}
+<p>{$survey->description|miniwiki}</p>
+
+<form action="survey/vote/{$survey->shortname}" method="post">
+  <div id="questions">
+  </div>
+
+  <div class="center">
+    {xsrf_token_field}
+    <input type="submit" name="vote" value="Enregister mon vote" />
+  </div>
+</form>
+
+{include file="survey/vote.questions.tpl"}
+
+<script type="text/javascript">
+  //<![CDATA[
+  var questions = {$survey->exportQuestionsToJSON()|smarty:nodefaults};
+
+  $($("#questions").showQuestions(questions));
+  //]]>
+</script>
+
+{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
index 4e701f0..86a88ec 100644 (file)
@@ -30,7 +30,8 @@
     <link rel="apple-touch-icon" href="images/logo-xnet.png" type="image/png" />
 
     <link rel="stylesheet" type="text/css" href="css/xnet.css" media="screen" />
-    <link rel="stylesheet" type="text/css" href="css/base.css" media="screen" />
+    <link rel="stylesheet" type="text/css" href="css/base.css" media="all" />
+    <link rel="stylesheet" type="text/css" href="css/bandeau.css" />
 
     <link rel="bookmark" href="http://www.polytechnique.fr/"        title="| École polytechnique" />
     <link rel="bookmark" href="http://www.polytechnique.edu/"       title="| Institutionnal site" />
@@ -40,7 +41,6 @@
     <link rel="bookmark" href="http://www.polytechnique.fr/eleves/" title="| Site d'élèves" />
 
     {include core=plpage.header.tpl}
-    {include file=skin/common.bandeau.head.tpl}
   </head>
   <body>
     {include core=plpage.devel.tpl}
             <div>
               <select name="right" onchange="this.form.submit()" style="margin: 0; padding: 0">
                 {if hasPerm('admin') || ($suid && $smarty.session.suid.perms->hasFlag('admin'))}
-                <option value="admin" {if hasPerm('admin')}selected="selected"{/if}>Administrateur</option>
+                <option value="admin" {if hasPerm('admin') && !($suid && $smarty.session.suid.perms->hasFlag('admin'))}selected="selected"{/if}>Administrateur</option>
                 {/if}
-                <option value="anim" {if $is_admin && !hasPerm('admin')}selected="selected"{/if}>Animateur</option>
+                <option value="anim" {if $is_admin && !( hasPerm('admin') && !($suid && $smarty.session.suid.perms->hasFlag('admin')))}selected="selected"{/if}>Animateur</option>
                 <option value="member" {if !$is_admin && $is_member}selected="selected"{/if}>Membre</option>
                 <option value="logged" {if !$is_admin && !$is_member}selected="selected"{/if}>Non-membre</option>
               </select>
index 8b4fc34..99292bc 100644 (file)
@@ -123,6 +123,19 @@ function deadlineChange(box)
       </td>
     </tr>
     <tr>
+      <td class="titre">
+        Notifier lors d'une inscriptions&nbsp;:
+      </td>
+      <td>
+        <select name="subscription_notification">
+          <option value='creator' {if $evt.subscription_notification eq 'creator'}selected='selected'{/if}>le créateur de l'événement</option>
+          <option value='animator' {if $evt.subscription_notification eq 'animator'}selected='selected'{/if}>les animateurs du groupe</option>
+          <option value='both' {if $evt.subscription_notification eq 'both'}selected='selected'{/if}>le créateur de l'événement et les animateurs du groupe</option>
+          <option value='nobody' {if $evt.subscription_notification eq 'nobody'}selected='selected'{/if}>personne</option>
+        </select>
+      </td>
+    </tr>
+    <tr>
       <td class='titre'>
         Options&nbsp;:
       </td>
index e60d478..21940e7 100644 (file)
@@ -73,7 +73,7 @@
         modifier
         {icon name=date_edit title="Édition de l'événement"}</a>]
       &nbsp;
-      [<a href="javascript:dynpostkv('{$platal->pl_self()}?token={xsrf_token}',{if !$archive}'archive'{else}'unarchive'{/if},{$e.eid})">
+      [<a href="javascript:$.dynPost('{$platal->pl_self()}?token={xsrf_token}',{if !$archive}'archive'{else}'unarchive'{/if},{$e.eid})">
         {if !$archive}
           archiver
           {icon name=package_add title="Archivage"}</a>]
@@ -82,7 +82,7 @@
           {icon name=package_delete title="Désarchivage"}</a>]
         {/if}
       &nbsp;
-      [<a href="javascript:dynpostkv('{$platal->ns}events?token={xsrf_token}','del',{$e.eid})"
+      [<a href="javascript:$.dynPost('{$platal->ns}events?token={xsrf_token}','del',{$e.eid})"
         onclick="return confirm('Supprimer l\'événement effacera la liste des inscrits et des paiements.\n Es-tu sûr de vouloir supprimer l\'événement&nbsp;?')">
         supprimer
       {icon name=delete title='Suppression'}</a>]
similarity index 76%
rename from templates/survey/success.tpl
rename to templates/xnetevents/subscription-notif.mail.tpl
index 0d28ee2..e66d452 100644 (file)
 {*  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA               *}
 {*                                                                        *}
 {**************************************************************************}
-<h1>Sondages&nbsp;: succès</h1>
 
-{if $survey_message neq ""}
-  {$survey_message}
-{else}
-  Opération réussie
-{/if}
-<br/>
-<a href="{$survey_link}">Retour</a>
+{config_load file="mails.conf" section="xnet_notification"}
+{if $mail_part eq 'head'}
+{from full=#from#}
+{subject text="[`$group`] $event"}
+{elseif $mail_part eq 'wiki'}
+Chers organisateurs,
+
+{$name} a mis a jour son inscription à cet événement. En voici le détail :
+{foreach from=$subs item=count key=i}
+{assign var=j value=$i-1}
+* {$moments.$j.titre} : {$count} personne{if $count > 1}s{/if}
+{/foreach}
 
-{* vim:set et sw=2 sts=2 ts=8 enc=utf-8: *}
+{include file="include/signature.mail.tpl"}
+{/if}
+{* vim:set et sw=2 sts=2 sws=2: *}
index 08805e7..12dc248 100644 (file)
   </tr>
   {/if}
 
+  {if $asso->positions|count}
+  <tr>
+    <td class="titre">
+      Bureau&nbsp;:
+    </td>
+    <td>
+      {foreach from=$asso->positions item=position}
+      <em>&bull;&nbsp;{$position.position}&nbsp;:</em> {profile user=$position.uid promo=true}<br />
+      {/foreach}
+    </td>
+  </tr>
+  {/if}
+
   {if $asso->forum}
   <tr>
     <td class="titre">
@@ -82,7 +95,7 @@
   {if $asso->ax}
   <tr>
     <td class="titre center" colspan="2">
-      groupe agréé par l'AX
+      groupe agréé par l'AX {if $asso->axDate}le {$asso->axDate}{/if}
     </td>
   </tr>
   {/if}
index ae59280..e0c77d6 100644 (file)
@@ -79,7 +79,8 @@
     <tr>
       <td class="titre center" colspan="2">
         <label><input type="checkbox" value="1" name="ax" {if $asso->ax}checked="checked"{/if} />
-        groupe agréé par l'AX</label>
+        groupe agréé par l'AX</label> le <input type="text" size="10" maxlength="10" value="{$asso->axDate}" name="axDate" />
+        <small>(ex: 01/01/1970)</small>
       </td>
     </tr>
   </table>
     </tr>
 
     <tr>
+      <td class="titre">
+        Message de bienvenue&nbsp;:<br />
+        <em>envoyé à l'inscription</em>
+      </td>
+      <td>
+        <textarea cols='40' rows='8' name='welcome_msg'>{$asso->welcome_msg}</textarea>
+      </td>
+    </tr>
+
+    <tr>
       <td class="titre center" colspan="2">
         Diffusion de la liste des membres&nbsp;:
         <select name="pub">
index 52256fb..ca37807 100644 (file)
         </select>
       </td>
     </tr>
+    <tr class="pair">
+      <td class="titre">
+        Poste&nbsp;:
+      </td>
+      <td>
+        <select name="group_position">
+          <option value=""{if $user->group_position eq ''} selected="selected"{/if}></option>
+          {foreach from=$positions item=position}
+          <option value="{$position}"{if $user->group_position eq $position} selected="selected"{/if}>{$position}</option>
+          {/foreach}
+        </select>
+      </td>
+    </tr>
     {if !$user->profile()}
     <tr class="impair">
       <td class="titre">
diff --git a/upgrade/1.1.0/01_new_mail_schema.sql b/upgrade/1.1.0/01_new_mail_schema.sql
new file mode 100644 (file)
index 0000000..15756f7
--- /dev/null
@@ -0,0 +1,75 @@
+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,
+  PRIMARY KEY (hrmid, uid),
+  FOREIGN KEY (uid) REFERENCES accounts (uid) ON UPDATE CASCADE ON DELETE CASCADE
+) 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 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', 'inactive', 'broken', 'disabled') NOT NULL,
+  hash VARCHAR(32) DEFAULT NULL,
+  allow_rewrite TINYINT(1) DEFAULT 0,
+  PRIMARY KEY (uid, redirect),
+  KEY (uid),
+  KEY (redirect),
+  FOREIGN KEY (uid) REFERENCES accounts (uid) ON UPDATE CASCADE ON DELETE CASCADE
+) 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',
+  PRIMARY KEY (hrmid, redirect),
+  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',
+  PRIMARY KEY (email, domain, redirect),
+  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:
diff --git a/upgrade/1.1.0/02_new_mail_insertion.sql b/upgrade/1.1.0/02_new_mail_insertion.sql
new file mode 100644 (file)
index 0000000..effcbb1
--- /dev/null
@@ -0,0 +1,258 @@
+INSERT INTO  email_source_account (uid, email, type, flags, expire)
+     SELECT  uid, CONCAT(alias, '@polytechnique.org'), IF(type = 'a_vie', 'forlife', 'alias'), REPLACE(flags, 'epouse', 'marital'), expire
+       FROM  aliases
+      WHERE  type = 'a_vie' OR type = 'alias';
+INSERT INTO  email_source_account (uid, email, type, flags, expire)
+     SELECT  uid, CONCAT(alias, '@m4x.org'), IF(type = 'a_vie', 'forlife', 'alias'), REPLACE(flags, 'epouse', 'marital'), expire
+       FROM  aliases
+      WHERE  type = 'a_vie' OR 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.', alias), '.polytechnique.org'), CONCAT(alias, '@polytechnique.org'), 'homonym'
+       FROM  aliases
+      WHERE  type = 'homonyme'
+   GROUP BY  (alias);
+INSERT INTO  email_source_other (hrmid, email, type)
+     SELECT  CONCAT(CONCAT('h.', alias), '.polytechnique.org'), CONCAT(alias, '@m4x.org'), 'homonym'
+       FROM  aliases
+      WHERE  type = 'homonyme'
+   GROUP BY  (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_date, 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 = '', 'inactive', 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  hrmid, 'homonym', 'homonym'
+       FROM  email_source_other
+      WHERE  type = 'homonym'
+   GROUP BY  (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, type, redirect)
+     SELECT  CONCAT(alias, '@polytechnique.org'), 'list',
+             CONCAT('polytechnique.org_', REPLACE(REPLACE(REPLACE(CONCAT(alias, '+post@listes.polytechnique.org'),
+                                                                  '-admin+post', '+admin'),
+                                                          '-owner+post', '+owner'),
+                                                  '-bounces+post', '+bounces'))
+       FROM  aliases
+      WHERE  type = 'liste';
+INSERT INTO  email_virtual (email, type, redirect)
+     SELECT  CONCAT(alias, '@m4x.org'), 'list',
+             CONCAT('polytechnique.org_', REPLACE(REPLACE(REPLACE(CONCAT(alias, '+post@listes.polytechnique.org'),
+                                                                  '-admin+post', '+admin'),
+                                                          '-owner+post', '+owner'),
+                                                  '-bounces+post', '+bounces'))
+       FROM  aliases
+      WHERE  type = 'liste';
+INSERT INTO  email_virtual (email, redirect, type)
+     SELECT  v.alias, vr.redirect, '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  REPLACE(v.alias, '@melix.net', '@melix.org'), vr.redirect, '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');
+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'),
+             ('validation@polytechnique.org', 'hotliners@staff.polytechnique.org', 'admin'),
+             ('validation@m4x.org', 'validation@polytechnique.org', 'admin'),
+             ('listes+admin@polytechnique.org', 'br@staff.polytechnique.org', 'admin'),
+             ('listes+admin@m4x.org', 'listes+admin@polytechnique.org', 'admin'),
+             ('listes@polytechnique.org', 'otrs.platal+listes@polytechnique.org', 'admin'),
+             ('listes@m4x.org', 'listes@polytechnique.org', 'admin'),
+             ('gld@polytechnique.org', 'listes@polytechnique.org', 'admin'),
+             ('gld@m4x.org', 'gld@polytechnique.org', 'admin'),
+             ('support@polytechnique.org', 'otrs.platal+support@polytechnique.org', 'admin'),
+             ('support@m4x.org', 'support@polytechnique.org', 'admin'),
+             ('contact@polytechnique.org', 'otrs.platal+contact@polytechnique.org', 'admin'),
+             ('contact@m4x.org', 'contact@polytechnique.org', 'admin'),
+             ('register@polytechnique.org', 'otrs.platal+register@polytechnique.org', 'admin'),
+             ('register@m4x.org', 'register@polytechnique.org', 'admin'),
+             ('info@polytechnique.org', 'otrs.platal+info@polytechnique.org', 'admin'),
+             ('info@m4x.org', 'info@polytechnique.org', 'admin'),
+             ('bug@polytechnique.org', 'otrs.platal+bug@polytechnique.org', 'admin'),
+             ('bug@m4x.org', 'bug@polytechnique.org', 'admin'),
+             ('resetpass@polytechnique.org', 'otrs.platal+resetpass@polytechnique.org', 'admin'),
+             ('resetpass@m4x.org', 'resetpass@polytechnique.org', 'admin'),
+             ('association@polytechnique.org', 'otrs.platal+association@polytechnique.org', 'admin'),
+             ('association@m4x.org', 'association@polytechnique.org', 'admin'),
+             ('x-org@polytechnique.org', 'association@polytechnique.org', 'admin'),
+             ('x-org@m4x.org', 'x-org@polytechnique.org', 'admin'),
+             ('manageurs@polytechnique.org', 'otrs@support.manageurs.com', 'partner'),
+             ('manageurs@m4x.org', 'manageurs@polytechnique.org', 'partner'),
+             ('fondation@polytechnique.org', 'fondation@fondationx.org', 'partner'),
+             ('fondation@m4x.org', 'fondation@polytechnique.org', 'partner'),
+             ('ax@polytechnique.org', 'ax@wanadoo.fr', 'partner'),
+             ('ax@m4x.org', 'ax@polytechnique.org', 'partner'),
+             ('annuaire-ax@polytechnique.org', 'annuaire-ax@wanadoo.fr', 'partner'),
+             ('annuaire-ax@m4x.org', 'annuaire-ax@polytechnique.org', 'partner'),
+             ('ax-bdc@polytechnique.org', 'ax-bdc@wanadoo.fr', 'partner'),
+             ('ax-bdc@m4x.org', 'ax-bdc@polytechnique.org', 'partner'),
+             ('jaune@polytechnique.org', 'null@hruid.polytechnique.org', 'partner'),
+             ('jaune@m4x.org', 'jaune@polytechnique.org', 'partner'),
+             ('jaune+rouge@polytechnique.org', 'jaune_rouge@wanadoo.fr', 'partner'),
+             ('jaune+rouge@m4x.org', 'jaune+rouge@polytechnique.org', 'partner'),
+             ('xcourseaularge@polytechnique.org', 'info@xcourseaularge.polytechnique.org', 'partner'),
+             ('xcourseaularge@m4x.org', 'xcourseaularge@polytechnique.org', 'partner'),
+             ('xim@polytechnique.org', 'membres@x-internet.polytechnique.org', 'partner'),
+             ('xim@m4x.org', 'xim@polytechnique.org', 'partner'),
+             ('x-consult@polytechnique.org', 'info@x-consult.polytechnique.org', 'partner'),
+             ('x-consult@m4x.org', 'x-consult@polytechnique.org', 'partner'),
+             ('xmcb@polytechnique.org', 'xmcb@x-consult.polytechnique.org', 'partner'),
+             ('xmcb@m4x.org', 'xmcb@polytechnique.org', 'partner'),
+             ('x-maroc@polytechnique.org', 'allam@mtpnet.gov.ma', 'partner'),
+             ('x-maroc@m4x.org', 'x-maroc@polytechnique.org', 'partner'),
+             ('x-musique@polytechnique.org', 'xmusique@free.fr', 'partner'),
+             ('x-musique@m4x.org', 'x-musique@polytechnique.org', 'partner'),
+             ('x-resistance@polytechnique.org', 'info@xresistance.org', 'partner'),
+             ('x-resistance@m4x.org', 'x-resistance@polytechnique.org', 'partner'),
+             ('x-israel@polytechnique.org', 'info@x-israel.polytechnique.org', 'partner'),
+             ('x-israel@m4x.org', 'x-israel@polytechnique.org', 'partner'),
+             ('gpx@polytechnique.org', 'g.p.x@infonie.fr', 'partner'),
+             ('gpx@m4x.org', 'gpx@polytechnique.org', 'partner'),
+             ('g.p.x@polytechnique.org', 'gpx@polytechnique.org', 'partner'),
+             ('g.p.x@m4x.org', 'g.p.x@polytechnique.org', 'partner'),
+             ('pointgamma@polytechnique.org', 'gamma@frankiz.polytechnique.fr', 'partner'),
+             ('pointgamma@m4x.org', 'pointgamma@polytechnique.org', 'partner'),
+             ('xmpentrepreneur@polytechnique.org', 'xmp.entrepreneur@gmail.com', 'partner'),
+             ('xmpentrepreneur@m4x.org', 'xmpentrepreneur@polytechnique.org', 'partner'),
+             ('xmp-entrepreneur@polytechnique.org', 'xmp.entrepreneur@gmail.com', 'partner'),
+             ('xmp-entrepreneur@m4x.org', 'xmp-entrepreneur@polytechnique.org', 'partner'),
+             ('xmpangels@polytechnique.org', 'xmpangels@xmp-ba.m4x.org', 'partner'),
+             ('xmpangels@m4x.org', 'xmpangels@polytechnique.org', 'partner'),
+             ('xmp-angels@polytechnique.org', 'xmpangels@xmp-ba.m4x.org', 'partner'),
+             ('xmp-angels@m4x.org', 'xmp-angels@polytechnique.org', 'partner'),
+             ('relex@polytechnique.org', 'relex@staff.polytechnique.org', 'admin'),
+             ('relex@m4x.org', 'relex@polytechnique.org', 'admin'),
+             ('tresorier@polytechnique.org', 'tresorier@staff.polytechnique.org', 'admin'),
+             ('tresorier@m4x.org', 'tresorier@polytechnique.org', 'admin'),
+             ('aaege-sso@polytechnique.org', 'aaege-sso@staff.polytechnique.org', 'admin'),
+             ('aaege-sso@m4x.org', 'aaege-sso@polytechnique.org', 'admin'),
+             ('innovation@polytechnique.org', 'innovation@staff.polytechnique.org', 'admin'),
+             ('innovation@m4x.org', 'innovation@polytechnique.org', 'admin'),
+             ('groupes@polytechnique.org', 'groupes@staff.polytechnique.org', 'admin'),
+             ('groupes@m4x.org', 'groupes@polytechnique.org', 'admin'),
+             ('br@polytechnique.org', 'br@staff.polytechnique.org', 'admin'),
+             ('br@m4x.org', 'br@polytechnique.org', 'admin'),
+             ('ca@polytechnique.org', 'ca@staff.polytechnique.org', 'admin'),
+             ('ca@m4x.org', 'ca@polytechnique.org', 'admin'),
+             ('personnel@polytechnique.org', 'br@staff.polytechnique.org', 'admin'),
+             ('personnel@m4x.org', 'personnel@polytechnique.org', 'admin'),
+             ('cil@polytechnique.org', 'cil@staff.polytechnique.org', 'admin'),
+             ('cil@m4x.org', 'cil@polytechnique.org', 'admin'),
+             ('opensource@polytechnique.org', 'contact@polytechnique.org', 'admin'),
+             ('opensource@m4x.org', 'opensource@polytechnique.org', 'admin'),
+             ('forums@polytechnique.org', 'forums@staff.m4x.org', 'admin'),
+             ('forums@m4x.org', 'forums@polytechnique.org', 'admin'),
+             ('telepaiement@polytechnique.org', 'telepaiement@staff.m4x.org', 'admin'),
+             ('telepaiement@m4x.org', 'telepaiement@polytechnique.org', 'admin'),
+             ('hotliners@polytechnique.org', 'hotliners@staff.m4x.org', 'admin'),
+             ('hotliners@m4x.org', 'hotliners@polytechnique.org', 'admin'),
+             ('kes@polytechnique.org', 'kes@frankiz.polytechnique.fr', 'partner'),
+             ('kes@m4x.org', 'kes@polytechnique.org', 'partner'),
+             ('kes1999@polytechnique.org', 'cariokes@polytechnique.org', 'partner'),
+             ('kes1999@m4x.org', 'kes1999@polytechnique.org', 'partner'),
+             ('kes2000@polytechnique.org', 'kestinpowers@polytechnique.org', 'partner'),
+             ('kes2000@m4x.org', '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.nicolas.zarpas.polytechnique.org', 'AX-nicolas.zarpas@polytechnique.org', 'ax'),
+             ('ax.nicolas.zarpas.polytechnique.org', 'AX-nicolas.zarpas@m4x.org', 'ax'),
+             ('ax.carrieres.polytechnique.org', 'AX-carrieres@polytechnique.org', 'ax'),
+             ('ax.carrieres.polytechnique.org', 'AX-carrieres@m4x.org', 'ax'),
+             ('ax.info1.polytechnique.org', 'AX-info1@polytechnique.org', 'ax'),
+             ('ax.info1.polytechnique.org', 'AX-info1@m4x.org', 'ax'),
+             ('ax.info2.polytechnique.org', 'AX-info2@polytechnique.org', 'ax'),
+             ('ax.info2.polytechnique.org', 'AX-info2@m4x.org', 'ax'),
+             ('ax.bal.polytechnique.org', 'AX-bal@polytechnique.org', 'ax'),
+             ('ax.bal.polytechnique.org', 'AX-bal@m4x.org', 'ax'),
+             ('ax.annuaire.polytechnique.org', 'AX-annuaire@polytechnique.org', 'ax'),
+             ('ax.annuaire.polytechnique.org', 'AX-annuaire@m4x.org', 'ax'),
+             ('ax.jaune-rouge.polytechnique.org', 'AX-jaune-rouge@polytechnique.org', 'ax'),
+             ('ax.jaune-rouge.polytechnique.org', 'AX-jaune-rouge@m4x.org', '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.blah.1980@polytechnique.org', 'honeypot'),
+             ('honey.jean-pierre.bilah.1980.polytechnique.org', 'jean-pierre.blah.1980@m4x.org', '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';
+
+-- 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:
diff --git a/upgrade/1.1.0/04_xnetgrp.sql b/upgrade/1.1.0/04_xnetgrp.sql
new file mode 100644 (file)
index 0000000..377a21c
--- /dev/null
@@ -0,0 +1,5 @@
+ALTER TABLE groups ADD COLUMN axDate DATE DEFAULT NULL;
+ALTER TABLE group_members ADD COLUMN position ENUM('Président', 'Vice-président', 'Trésorier', 'Vice-trésorier', 'Secrétaire', 'Directeur', 'Délégué général', 'Secrétaire général', 'Membre du bureau') DEFAULT NULL;
+ALTER TABLE groups ADD COLUMN welcome_msg MEDIUMTEXT DEFAULT NULL;
+
+-- vim:set syntax=mysql:
diff --git a/upgrade/1.1.0/05_permissions.sql b/upgrade/1.1.0/05_permissions.sql
new file mode 100644 (file)
index 0000000..6a6615d
--- /dev/null
@@ -0,0 +1,9 @@
+ALTER TABLE accounts CHANGE COLUMN user_perms user_perms
+    SET('groups', 'mail', 'directory_ax', 'directory_private', 'edit_directory',
+        'forums', 'lists', 'payment', 'api_user_readonly') DEFAULT NULL;
+
+ALTER TABLE account_types CHANGE COLUMN perms perms
+    SET('groups', 'mail', 'directory_ax', 'directory_private', 'edit_directory',
+        'forums', 'lists', 'payment', 'api_user_readonly') NOT NULL;
+
+-- vim:set syntax=mysql:
diff --git a/upgrade/1.1.0/05_xnetevents.sql b/upgrade/1.1.0/05_xnetevents.sql
new file mode 100644 (file)
index 0000000..d67ad18
--- /dev/null
@@ -0,0 +1,3 @@
+ALTER TABLE group_events ADD COLUMN subscription_notification ENUM('nobody', 'creator', 'animator', 'both') NOT NULL DEFAULT 'nobody';
+
+-- vim:set syntax=mysql:
diff --git a/upgrade/1.1.0/06_language.sql b/upgrade/1.1.0/06_language.sql
new file mode 100644 (file)
index 0000000..85d6a29
--- /dev/null
@@ -0,0 +1,12 @@
+UPDATE profile_langskill_enum SET id = SUBSTRING(id, 1, 3);
+ALTER TABLE profile_langskills DROP FOREIGN KEY profile_langskills_ibfk_2;
+ALTER TABLE profile_langskill_enum CHANGE COLUMN id iso_639_2b CHAR(3) NOT NULL DEFAULT '';
+ALTER TABLE profile_langskills ADD FOREIGN KEY (lid) REFERENCES profile_langskill_enum (iso_639_2b) ON DELETE CASCADE ON UPDATE CASCADE;
+ALTER TABLE profile_langskill_enum ADD COLUMN iso_639_2t CHAR(3) NOT NULL DEFAULT '';
+ALTER TABLE profile_langskill_enum ADD COLUMN iso_639_1 CHAR(2) DEFAULT NULL;
+ALTER TABLE profile_langskill_enum CHANGE COLUMN langue_en language_en VARCHAR(255) NOT NULL DEFAULT '';
+ALTER TABLE profile_langskill_enum CHANGE COLUMN langue_fr language VARCHAR(255) NOT NULL DEFAULT '';
+ALTER TABLE profile_langskill_enum ADD KEY (iso_639_2t);
+ALTER TABLE profile_langskill_enum ADD KEY (iso_639_1);
+
+-- vim:set syntax=mysql:
diff --git a/upgrade/1.1.0/10_surveys.sql b/upgrade/1.1.0/10_surveys.sql
new file mode 100644 (file)
index 0000000..e6e5f47
--- /dev/null
@@ -0,0 +1,88 @@
+#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:
diff --git a/upgrade/1.1.0/connect.db.inc.php b/upgrade/1.1.0/connect.db.inc.php
new file mode 120000 (symlink)
index 0000000..442fab7
--- /dev/null
@@ -0,0 +1 @@
+../../bin/connect.db.inc.php
\ No newline at end of file
diff --git a/upgrade/1.1.0/languages.php b/upgrade/1.1.0/languages.php
new file mode 100755 (executable)
index 0000000..5736497
--- /dev/null
@@ -0,0 +1,34 @@
+#!/usr/bin/php5
+<?php
+
+require_once 'connect.db.inc.php';
+
+$globals->debug = 0; // Do not store backtraces.
+
+// First build the list provided by the iso codes.
+$list = array();
+exec('isoquery --iso=639', $list);
+
+foreach ($list as $key => $item) {
+    $array = explode("\t", $item);
+    unset($list[$key]);
+    $list[$array[0]] = array();
+    foreach (array('iso_639_2t', 'iso_639_1') as $i => $field) {
+        $list[$array[0]][$field] = $array[$i + 1];
+    }
+}
+
+$res = XDB::iterator('SELECT  iso_639_2b
+                        FROM  profile_langskill_enum
+                       WHERE  iso_639_2b IN {?}',
+                     array_keys($list));
+while ($item = $res->next()) {
+    $id = $item['iso_639_2b'];
+    XDB::execute('UPDATE  profile_langskill_enum
+                     SET  iso_639_2t = {?}, iso_639_1 = {?}
+                   WHERE  iso_639_2b = {?}',
+                 $list[$id]['iso_639_2t'], (($list[$id]['iso_639_1']) ? $list[$id]['iso_639_1'] : null), $id);
+}
+
+/* vim:set et sw=4 sts=4 ts=4: */
+?>
diff --git a/upgrade/1.1.0/new_mail_delete_old.sql.noauto b/upgrade/1.1.0/new_mail_delete_old.sql.noauto
new file mode 100644 (file)
index 0000000..00cccf4
--- /dev/null
@@ -0,0 +1,9 @@
+DROP TABLE aliases;
+DROP TABLE virtual;
+DROP TABLE virtual_redirect;
+DROP TABLE virtual_domains;
+DROP TABLE homonyms;
+DROP TABLE emails;
+DROP TABLE email_options;
+
+-- vim:set syntax=mysql:
diff --git a/upgrade/1.1.0/old_surveys.inc.php b/upgrade/1.1.0/old_surveys.inc.php
new file mode 100644 (file)
index 0000000..497a7f8
--- /dev/null
@@ -0,0 +1,823 @@
+<?php
+/***************************************************************************
+ *  Copyright (C) 2003-2011 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:
+?>
diff --git a/upgrade/1.1.0/update.sh b/upgrade/1.1.0/update.sh
new file mode 100755 (executable)
index 0000000..ac34396
--- /dev/null
@@ -0,0 +1,10 @@
+#!/bin/bash
+
+. ../inc/pervasive.sh
+
+###########################################################
+[ "$DATABASE" != "x4dat" ] || die "Cannot target x4dat"
+copy_db
+
+confirm "* Running database upgrade scripts"
+#mysql_run_directory .