Exemplo n.º 1
0
 public function handler_licenses_final($page, $no_reason = false)
 {
     $softwares = License::getSoftwares();
     $keys = array();
     if (Post::has('disagree') || !$no_reason && !Post::has('resend') && (!Post::has('reason') || Post::v('reason') == "") || !Post::has('software') || !in_array(Post::v('software'), array_keys($softwares))) {
         $this->handler_licenses($page);
     } else {
         $page->changeTpl('licenses/licenses_final.tpl');
         $page->assign('title', "Demande de licence pour {$softwares[Post::v('software')]}");
         $page->assign('software', Post::s('software'));
         $page->assign('software_name', $softwares[Post::s('software')]);
         if (($key = License::adminKey(Post::s('software'))) && License::hasRights(S::user())) {
             $key->give(S::user());
             $page->assign('direct', true);
         } elseif (Post::has('resend')) {
             $l = License::fetch(array('id' => Post::i('id')));
             if ($l[0]->uid() == S::user()->id()) {
                 License::send($l);
             } else {
                 die("La license n'appartient pas à l'utilisateur courant");
             }
             $page->assign('direct', true);
         } else {
             $lv = new LicensesValidate(Post::s('software'), Post::s('reason'));
             $v = new Validate(array('writer' => S::user(), 'group' => Group::from('licenses'), 'item' => $lv, 'type' => 'licenses'));
             $v->insert();
             $page->assign('direct', false);
         }
     }
 }
Exemplo n.º 2
0
 function handler_banana($page, $group = null, $action = null, $artid = null)
 {
     $page->changeTpl('banana/index.tpl');
     $page->setTitle('Forums & PA');
     $get = array();
     if (Post::has('updateall')) {
         $get['updateall'] = Post::v('updateall');
     }
     require_once 'banana/forum.inc.php';
     get_banana_params($get, $group, $action, $artid);
     run_banana($page, 'ForumsBanana', $get);
 }
Exemplo n.º 3
0
 protected function handle_editor()
 {
     $data = Post::v('valid');
     if (isset($data['text']) && $data['text'] != $this->toy_text && $data['text'] != $this->given_text) {
         $this->toy_text = $data['text'];
         $address = new Address(array('changed' => 1, 'text' => $this->toy_text));
         $address->format();
         $this->address = $address->toFormArray();
     }
     $this->modified = isset($data['modified']);
     return true;
 }
Exemplo n.º 4
0
 function handler_coml_submit($page)
 {
     $page->changeTpl('comletter/submit.tpl');
     $nl = $this->getNl();
     if (!$nl) {
         return PL_NOT_FOUND;
     }
     $wp = new PlWikiPage('Xorg.LettreCommunaute');
     $wp->buildCache();
     if (Post::has('see') || Post::has('valid') && (!trim(Post::v('title')) || !trim(Post::v('body')))) {
         if (!Post::has('see')) {
             $page->trigError("L'article doit avoir un titre et un contenu");
         }
         $art = new ComLArticle(Post::v('title'), Post::v('body'), Post::v('append'));
         $page->assign('art', $art);
     } elseif (Post::has('valid')) {
         $art = new ComLReq(S::user(), Post::v('title'), Post::v('body'), Post::v('append'));
         $art->submit();
         $page->assign('submited', true);
     }
     $page->addCssLink($nl->cssFile());
 }
Exemplo n.º 5
0
 public function HandleAction($action)
 {
     switch ($action) {
         case 'suscribe':
             S::assert_xsrf_token();
             $subs = array_keys(Post::v('sub_ml'));
             $res = XDB::iterRow("SELECT  sub, domain\n                                   FROM  register_subs\n                                  WHERE  uid = {?} AND type = 'list'\n                               ORDER BY  domain", S::i('uid'));
             while (list($sub, $domain) = $res->next()) {
                 if (array_shift($subs) == "{$sub}@{$domain}") {
                     MailingList::subscribeTo($sub, $domain);
                 }
             }
             $this->UpdateOnYes();
             pl_redirect('lists');
             break;
         case 'dismiss':
             $this->UpdateOnDismiss();
             break;
         case 'no':
             $this->UpdateOnNo();
             break;
     }
 }
Exemplo n.º 6
0
 function handler_deceased($page, $action = '')
 {
     if ($action == 'updateXorg') {
         XDB::execute('UPDATE  fusionax_deceased
                          SET  deces_xorg = deces_ax
                        WHERE  deces_xorg IS NULL');
     }
     if ($action == 'updateAX') {
         XDB::execute('UPDATE  fusionax_deceased
                          SET  deces_ax = deces_xorg
                        WHERE  deces_ax = "0000-00-00"');
     }
     if ($action == 'update') {
         if (Post::has('pid') && Post::has('date')) {
             XDB::execute('UPDATE  fusionax_deceased
                              SET  deces_ax = {?}, deces_xorg = {?}
                            WHERE  pid = {?}', Post::v('date'), Post::v('date'), Post::i('pid'));
         }
     }
     $page->changeTpl('fusionax/deceased.tpl');
     // deceased
     $deceasedErrorsSql = XDB::query('SELECT COUNT(*) FROM fusionax_deceased');
     $page->assign('deceasedErrors', $deceasedErrorsSql->fetchOneCell());
     $res = XDB::iterator('SELECT  pid, ax_id, promo, private_name, deces_ax
                             FROM  fusionax_deceased
                            WHERE  deces_xorg IS NULL
                            LIMIT  10');
     $page->assign('nbDeceasedMissingInXorg', $res->total());
     $page->assign('deceasedMissingInXorg', $res);
     $res = XDB::iterator('SELECT  pid, ax_id, promo, private_name, deces_xorg
                             FROM  fusionax_deceased
                            WHERE  deces_ax = "0000-00-00"
                            LIMIT  10');
     $page->assign('nbDeceasedMissingInAX', $res->total());
     $page->assign('deceasedMissingInAX', $res);
     $res = XDB::iterator('SELECT  pid, ax_id, promo, private_name, deces_xorg, deces_ax
                             FROM  fusionax_deceased
                            WHERE  deces_xorg != "0000-00-00" AND deces_ax != "0000-00-00"');
     $page->assign('nbDeceasedDifferent', $res->total());
     $page->assign('deceasedDifferent', $res);
 }
Exemplo n.º 7
0
 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,\n                                                    elle est en attente de validation par un administrateur du site.", 'survey');
                 } else {
                     $this->show_error($page, '', 'survey');
                 }
             }
             $this->clear_session();
         } else {
             // asks for a confirmation if it has not been sent
             $survey = unserialize(S::v('survey'));
             $errors = $survey->checkSyntax();
             if (!is_null($errors)) {
                 $this->show_error($page, "", 'survey/edit', $errors);
             } else {
                 if (S::has('survey_id')) {
                     $this->show_confirm($page, "Veuillez confirmer l'enregistrement des modifications apportées à ce sondage.", 'edit', array('action' => 'valid'));
                 } else {
                     $this->show_confirm($page, "Veuillez confirmer l'envoi de cette proposition de sondage.", 'edit', array('action' => 'valid'));
                 }
             }
         }
         // }}}
     } elseif ($action == 'cancel') {
         // {{{ cancels the creation/modification of a survey
         if (Post::has('survey_submit')) {
             // needs a confirmation
             if (S::has('survey_id')) {
                 // only possible when modifying a survey in admin mode
                 if (S::has('survey_validate')) {
                     // if a link has been supplied, uses it
                     $this->clear_session();
                     return $this->show_success($page, "Les modifications effectuées ont été annulées", 'admin/validate');
                 } else {
                     // else shows the admin index
                     $this->clear_session();
                     return $this->handler_admin($page);
                 }
             } else {
                 $this->clear_session();
                 return $this->handler_index($page);
                 // else shows the 'normal' index
             }
         } else {
             // asks for a confirmation if it has not been sent
             $this->show_confirm($page, "Êtes-vous certain de vouloir annuler totalement l'édition de ce sondage ? Attention, " . "toutes les données éditées jusque là seront définitivement perdues.", 'edit', array('action' => $action));
         }
     }
     // }}}
 }
Exemplo n.º 8
0
 function handler_add_secondary_edu($page)
 {
     $page->changeTpl('admin/add_secondary_edu.tpl');
     if (!(Post::has('verify') || Post::has('add'))) {
         return;
     } elseif (!Post::has('people')) {
         $page->trigWarning("Aucune information n'a été fournie.");
         return;
     }
     require_once 'name.func.inc.php';
     $lines = explode("\n", Post::t('people'));
     $separator = Post::t('separator');
     $degree = Post::v('degree');
     $promotion = Post::i('promotion');
     $schoolsList = array_flip(DirEnum::getOptions(DirEnum::EDUSCHOOLS));
     $degreesList = array_flip(DirEnum::getOptions(DirEnum::EDUDEGREES));
     $edu_id = $schoolsList[Profile::EDU_X];
     $degree_id = $degreesList[$degree];
     $res = array('incomplete' => array(), 'empty' => array(), 'multiple' => array(), 'already' => array(), 'new' => array());
     $old_pids = array();
     $new_pids = array();
     foreach ($lines as $line) {
         $line = trim($line);
         $line_array = explode($separator, $line);
         array_walk($line_array, 'trim');
         if (count($line_array) != 3) {
             $page->trigError("La ligne « {$line} » est incomplète.");
             $res['incomplete'][] = $line;
             continue;
         }
         $cond = new PFC_And(new UFC_NameTokens(split_name_for_search($line_array[0]), array(), false, false, Profile::LASTNAME));
         $cond->addChild(new UFC_NameTokens(split_name_for_search($line_array[1]), array(), false, false, Profile::FIRSTNAME));
         $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, $line_array[2]));
         $uf = new UserFilter($cond);
         $pid = $uf->getPIDs();
         $count = count($pid);
         if ($count == 0) {
             $page->trigError("La ligne « {$line} » ne correspond à aucun profil existant.");
             $res['empty'][] = $line;
             continue;
         } elseif ($count > 1) {
             $page->trigError("La ligne « {$line} » correspond à plusieurs profils existant.");
             $res['multiple'][] = $line;
             continue;
         } else {
             $count = XDB::fetchOneCell('SELECT  COUNT(*) AS count
                                           FROM  profile_education
                                          WHERE  pid = {?} AND eduid = {?} AND degreeid = {?}', $pid, $edu_id, $degree_id);
             if ($count == 1) {
                 $res['already'][] = $line;
                 $old_pids[] = $pid[0];
             } else {
                 $res['new'][] = $line;
                 $new_pids[] = $pid[0];
             }
         }
     }
     $display = array();
     foreach ($res as $type => $res_type) {
         if (count($res_type) > 0) {
             $display = array_merge($display, array('--------------------' . $type . ':'), $res_type);
         }
     }
     $page->assign('people', implode("\n", $display));
     $page->assign('promotion', $promotion);
     $page->assign('degree', $degree);
     if (Post::has('add')) {
         $entry_year = $promotion - Profile::educationDuration($degree);
         if (Post::b('force_addition')) {
             $pids = array_unique(array_merge($old_pids, $new_pids));
         } else {
             $pids = array_unique($new_pids);
             // Updates years.
             if (count($old_pids)) {
                 XDB::execute('UPDATE  profile_education
                                  SET  entry_year = {?}, grad_year = {?}, promo_year = {?}
                                WHERE  pid IN {?} AND eduid = {?} AND degreeid = {?}', $entry_year, $promotion, $promotion, $old_pids, $edu_id, $degree_id);
             }
         }
         // Precomputes values common to all users.
         $select = XDB::format('MAX(id) + 1, pid, {?}, {?}, {?}, {?}, {?}, \'secondary\'', $edu_id, $degree_id, $entry_year, $promotion, $promotion);
         XDB::startTransaction();
         foreach ($pids as $pid) {
             XDB::execute('INSERT INTO  profile_education (id, pid, eduid, degreeid, entry_year, grad_year, promo_year, flags)
                                SELECT  ' . $select . '
                                  FROM  profile_education
                                 WHERE  pid = {?}
                              GROUP BY  pid', $pid);
         }
         XDB::commit();
     }
 }
Exemplo n.º 9
0
 function handler_admin_user($page, $user = null)
 {
     require_once 'emails.inc.php';
     require_once 'googleapps.inc.php';
     $page->changeTpl('googleapps/admin.user.tpl');
     $page->setTitle('Administration Google Apps');
     $page->assign('googleapps_admin', GoogleAppsAccount::is_administrator(S::v('uid')));
     if (!$user && Post::has('login')) {
         $user = Post::v('login');
     }
     $user = User::get($user);
     if ($user) {
         $account = new GoogleAppsAccount($user);
         // Apply requested actions.
         if (Post::has('suspend') && $account->active() && !$account->pending_update_suspension) {
             S::assert_xsrf_token();
             $account->suspend();
             $page->trigSuccess('Le compte est en cours de suspension.');
         } else {
             if (Post::has('unsuspend') && $account->suspended() && !$account->pending_update_suspension) {
                 S::assert_xsrf_token();
                 $account->do_unsuspend();
                 $page->trigSuccess('Le compte est en cours de réactivation.');
             } else {
                 if (Post::has('forcesync') && $account->active() && $account->sync_password) {
                     $account->set_password($user->password());
                     $page->trigSuccess('Le mot de passe est en cours de synchronisation.');
                 } else {
                     if (Post::has('sync') && $account->active()) {
                         $account->set_password($user->password());
                         $account->set_password_sync(true);
                     } else {
                         if (Post::has('nosync') && $account->active()) {
                             $account->set_password_sync(false);
                         }
                     }
                 }
             }
         }
         // Displays basic account information.
         $page->assign('account', $account);
         $page->assign('admin_account', GoogleAppsAccount::is_administrator($user->id()));
         $page->assign('googleapps_storage', Email::is_active_storage($user, 'googleapps'));
         $page->assign('user', $user->id());
         // Retrieves user's pending requests.
         $res = XDB::iterator("SELECT  q_id, q_recipient_id, p_status, j_type, UNIX_TIMESTAMP(p_entry_date) AS p_entry_date\n                   FROM  gapps_queue\n                  WHERE  q_recipient_id = {?}\n               ORDER BY  p_entry_date DESC", $user->id());
         $page->assign('requests', $res);
     }
 }
Exemplo n.º 10
0
 function handler_batch($page)
 {
     $page->changeTpl('carnet/batch.tpl');
     $errors = false;
     $incomplete = array();
     if (Post::has('add')) {
         S::assert_xsrf_token();
         require_once 'userset.inc.php';
         require_once 'emails.inc.php';
         require_once 'marketing.inc.php';
         $list = explode("\n", Post::v('list'));
         $origin = Post::v('origin');
         foreach ($list as $item) {
             if ($item = trim($item)) {
                 $elements = preg_split("/\\s/", $item);
                 $email = array_pop($elements);
                 if (!isvalid_email($email)) {
                     $page->trigError('Email invalide : ' . $email);
                     $incomplete[] = $item;
                     $errors = true;
                     continue;
                 }
                 $user = User::getSilent($email);
                 if (is_null($user)) {
                     $details = implode(' ', $elements);
                     $promo = trim(array_pop($elements));
                     $cond = new PFC_And();
                     if (preg_match('/^[MDX]\\d{4}$/', $promo)) {
                         $cond->addChild(new UFC_Promo('=', UserFilter::DISPLAY, $promo));
                     } else {
                         $cond->addChild(new UFC_NameTokens($promo));
                     }
                     foreach ($elements as $element) {
                         $cond->addChild(new UFC_NameTokens($element));
                     }
                     $uf = new UserFilter($cond);
                     $count = $uf->getTotalCount();
                     if ($count == 0) {
                         $page->trigError('Les informations : « ' . $item . ' » ne correspondent à aucun camarade.');
                         $incomplete[] = $item;
                         $errors = true;
                         continue;
                     } elseif ($count > 1) {
                         $page->trigError('Les informations : « ' . $item . ' » sont ambigues et correspondent à plusieurs camarades.');
                         $incomplete[] = $item;
                         $errors = true;
                         continue;
                     } else {
                         $user = $uf->getUser();
                     }
                 }
                 if ($user->state == 'active') {
                     $this->addRegistered($page, $user->profile());
                 } else {
                     if (!User::isForeignEmailAddress($email)) {
                         $page->trigError('Email pas encore attribué : ' . $email);
                         $incomplete[] = $item;
                         $errors = true;
                     } else {
                         $this->addNonRegistered($page, $user);
                         if (!Marketing::get($user->id(), $email, true)) {
                             check_email($email, "Une adresse surveillée est proposée au marketing par " . S::user()->login());
                             $market = new Marketing($user->id(), $email, 'default', null, $origin, S::v('uid'), null);
                             $market->add();
                         }
                     }
                 }
             }
         }
     }
     $page->assign('errors', $errors);
     $page->assign('incomplete', $incomplete);
 }
Exemplo n.º 11
0
 function handler_admin($page, $eid = null, $item_id = null)
 {
     global $globals;
     $this->load('xnetevents.inc.php');
     $evt = get_event_detail($eid, $item_id);
     if (!$evt) {
         return PL_NOT_FOUND;
     }
     $page->changeTpl('xnetevents/admin.tpl');
     if (!$evt['show_participants'] && !may_update()) {
         return PL_FORBIDDEN;
     }
     if (may_update() && Post::v('adm')) {
         S::assert_xsrf_token();
         $member = User::getSilent(Post::v('mail'));
         if (!$member) {
             $page->trigError("Membre introuvable");
         }
         // change the price paid by a participant
         if (Env::v('adm') == 'prix' && $member) {
             $amount = strtr(Env::v('montant'), ',', '.');
             XDB::execute("UPDATE group_event_participants\n                                 SET paid = paid + {?}\n                               WHERE uid = {?} AND eid = {?} AND nb > 0\n                            ORDER BY item_id ASC\n                               LIMIT 1", $amount, $member->uid, $evt['eid']);
             subscribe_lists_event($member->uid, $evt['short_name'], 1, $amount);
         }
         // change the number of personns coming with a participant
         if (Env::v('adm') == 'nbs' && $member) {
             $res = XDB::query("SELECT SUM(paid)\n                                     FROM group_event_participants\n                                    WHERE uid = {?} AND eid = {?}", $member->uid, $evt['eid']);
             $paid = $res->fetchOneCell();
             // Ensure we have an integer
             if ($paid == null) {
                 $paid = 0;
             }
             $nbs = Post::v('nb', array());
             $paid_inserted = false;
             foreach ($nbs as $id => $nb) {
                 $nb = max(intval($nb), 0);
                 if (!$paid_inserted && $nb > 0) {
                     $item_paid = $paid;
                     $paid_inserted = true;
                 } else {
                     $item_paid = 0;
                 }
                 XDB::execute('INSERT INTO  group_event_participants (eid, uid, item_id, nb, flags, paid)
                                    VALUES  ({?}, {?}, {?}, {?}, {?}, {?})
                   ON DUPLICATE KEY UPDATE  nb = VALUES(nb), flags = VALUES(flags), paid = VALUES(paid)', $evt['eid'], $member->uid, $id, $nb, '', $item_paid);
             }
             $res = XDB::query('SELECT  COUNT(uid) AS cnt, SUM(nb) AS nb
                                  FROM  group_event_participants
                                 WHERE  uid = {?} AND eid = {?}
                              GROUP BY  uid', $member->uid, $evt['eid']);
             $u = $res->fetchOneAssoc();
             if ($paid == 0 && Post::v('cancel')) {
                 XDB::execute("DELETE FROM group_event_participants\n                                        WHERE uid = {?} AND eid = {?}", $member->uid, $evt['eid']);
                 $u = 0;
                 subscribe_lists_event($member->uid, $evt['short_name'], -1, $paid);
             } else {
                 $u = $u['cnt'] ? $u['nb'] : null;
                 subscribe_lists_event($member->uid, $evt['short_name'], $u > 0 ? 1 : 0, $paid);
             }
         }
         $evt = get_event_detail($eid, $item_id);
     }
     $page->assign_by_ref('evt', $evt);
     $page->assign('tout', is_null($item_id));
     if (count($evt['moments'])) {
         $page->assign('moments', $evt['moments']);
     }
     if ($evt['paiement_id']) {
         $infos = User::getBulkUsersWithUIDs(XDB::fetchAllAssoc('SELECT  t.uid, t.amount
                                               FROM  payment_transactions AS t
                                          LEFT JOIN  group_event_participants AS ep ON(ep.uid = t.uid AND ep.eid = {?})
                                              WHERE  t.status = "confirmed" AND t.ref = {?} AND ep.uid IS NULL', $evt['eid'], $evt['paiement_id']), 'uid', 'user');
         $page->assign('oublis', count($infos));
         $page->assign('oubliinscription', $infos);
     }
     $absents = User::getBulkUsersFromDB('SELECT  p.uid
                                            FROM  group_event_participants AS p
                                       LEFT JOIN  group_event_participants AS p2 ON (p2.uid = p.uid
                                                                                            AND p2.eid = p.eid
                                                                                            AND p2.nb != 0)
                                           WHERE  p.eid = {?} AND p2.eid IS NULL
                                        GROUP BY  p.uid', $evt['eid']);
     $ofs = Env::i('offset');
     $part = get_event_participants($evt, $item_id, UserFilter::sortByName(), NB_PER_PAGE, $ofs * NB_PER_PAGE);
     $nbp = ceil($evt['user_count'] / NB_PER_PAGE);
     if ($nbp > 1) {
         $links = array();
         if ($ofs) {
             $links['précédent'] = $ofs - 1;
         }
         for ($i = 1; $i <= $nbp; $i++) {
             $links[(string) $i] = $i - 1;
         }
         if ($ofs < $nbp - 1) {
             $links['suivant'] = $ofs + 1;
         }
         $page->assign('links', $links);
     }
     $page->assign('absents', $absents);
     $page->assign('participants', $part);
 }
Exemplo n.º 12
0
 /** Start a session as user $user
  */
 protected function startSessionAs($user, $level)
 {
     /* Session data and required data mismatch */
     if (!is_null(S::v('user')) && S::v('user')->id() != $user->id() || S::has('uid') && S::i('uid') != $user->id()) {
         return false;
     } else {
         if (S::has('uid')) {
             return true;
         }
     }
     /* If we want to do a SUID */
     if ($level == AUTH_SUID) {
         S::set('auth', AUTH_MDP);
     }
     S::set('user', $user);
     S::set('uid', $user->id());
     if (!isSmartphone()) {
         S::set('skin', $user->skin());
     }
     if (!S::suid()) {
         if (Post::v('remember', 'false') == 'on') {
             $this->setAccessCookie(false);
         }
         S::logger()->saveLastSession();
     } else {
         S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
     }
     // Set session perms from User perms
     S::set('perms', $user->perms());
     /* Clean temp var 'cookie_uid' */
     S::kill('cookie_uid');
     return true;
 }
Exemplo n.º 13
0
 function handler_delete($page, $liste = null)
 {
     global $globals;
     if (is_null($liste)) {
         return PL_NOT_FOUND;
     }
     $mlist = $this->prepare_list($liste);
     if (!$this->is_group_admin($page)) {
         $this->verify_list_owner($page, $mlist);
     }
     $page->changeTpl('lists/delete.tpl');
     if (Post::v('valid') == 'OUI') {
         S::assert_xsrf_token();
         if ($mlist->delete(Post::b('del_archive'))) {
             require_once 'emails.inc.php';
             delete_list($mlist->mbox, $mlist->domain);
             $page->assign('deleted', true);
             $page->trigSuccess('La liste a été détruite&nbsp;!');
         } else {
             $page->kill('Une erreur est survenue lors de la suppression de la liste.<br />' . 'Contact les administrateurs du site pour régler le problème : ' . '<a href="mailto:support@polytechnique.org">support@polytechnique.org</a>.');
         }
     } elseif (list($details, $options) = $mlist->getOwnerOptions()) {
         if (!$details['own']) {
             $page->trigWarning('Tu n\'es pas administrateur de la liste, mais du site.');
         }
         $page->assign_by_ref('details', $details);
         $page->assign_by_ref('options', $options);
         $page->assign('bogo_level', $mlist->getBogoLevel());
     } else {
         $page->kill("La liste n'existe pas ou tu n'as pas le droit de l'administrer.");
     }
 }
Exemplo n.º 14
0
 function handler_end($page, $hash = null)
 {
     global $globals;
     $_SESSION['subState'] = array('step' => 5);
     // Reject registration requests from unsafe IP addresses (and remove the
     // registration information from the database, to prevent IP changes).
     if (check_ip('unsafe')) {
         send_warning_mail('Une IP surveillée a tenté de finaliser son inscription.');
         XDB::execute("DELETE FROM  register_pending\n                                WHERE  hash = {?} AND hash != 'INSCRIT'", $hash);
         return PL_FORBIDDEN;
     }
     // Retrieve the pre-registration information using the url-provided
     // authentication token.
     $res = XDB::query("SELECT  r.uid, p.pid, r.forlife, r.bestalias, r.mailorg2,\n                                   r.password, r.email, r.services, r.naissance,\n                                   ppn.lastname_initial, ppn.firstname_initial, pe.promo_year,\n                                   pd.promo, p.sex, p.birthdate_ref, a.type, a.email AS old_account_email\n                             FROM  register_pending AS r\n                       INNER JOIN  accounts         AS a   ON (r.uid = a.uid)\n                       INNER JOIN  account_profiles AS ap  ON (a.uid = ap.uid AND FIND_IN_SET('owner', ap.perms))\n                       INNER JOIN  profiles         AS p   ON (p.pid = ap.pid)\n                       INNER JOIN  profile_public_names AS ppn ON (ppn.pid = p.pid)\n                       INNER JOIN  profile_display  AS pd  ON (p.pid = pd.pid)\n                       INNER JOIN  profile_education AS pe ON (pe.pid = p.pid AND FIND_IN_SET('primary', pe.flags))\n                            WHERE  hash = {?} AND hash != 'INSCRIT' AND a.state = 'pending'", $hash);
     if (!$hash || $res->numRows() == 0) {
         $page->kill("<p>Cette adresse n'existe pas, ou plus, sur le serveur.</p>\n                         <p>Causes probables&nbsp;:</p>\n                         <ol>\n                           <li>Vérifie que tu visites l'adresse du dernier\n                               email reçu s'il y en a eu plusieurs.</li>\n                           <li>Tu as peut-être mal copié l'adresse reçue par\n                               email, vérifie-la à la main.</li>\n                           <li>Tu as peut-être attendu trop longtemps pour\n                               confirmer. Les pré-inscriptions sont annulées\n                               tous les 30 jours.</li>\n                           <li>Tu es en fait déjà inscrit.</li>\n                        </ol>");
     }
     list($uid, $pid, $forlife, $bestalias, $emailXorg2, $password, $email, $services, $birthdate, $lastname, $firstname, $yearpromo, $promo, $sex, $birthdate_ref, $type, $old_account_email) = $res->fetchOneRow();
     $isX = $type == 'x';
     $mail_domain = User::$sub_mail_domains[$type] . $globals->mail->domain;
     // Prepare the template for display.
     $page->changeTpl('register/end.tpl');
     $page->assign('forlife', $forlife);
     $page->assign('firstname', $firstname);
     // Check if the user did enter a valid password; if not (or if none is found),
     // get her an information page.
     if (Post::has('response')) {
         $expected_response = sha1("{$forlife}:{$password}:" . S::v('challenge'));
         if (Post::v('response') != $expected_response) {
             $page->trigError("Mot de passe invalide.");
             S::logger($uid)->log('auth_fail', 'bad password (register/end)');
             return;
         }
     } else {
         return;
     }
     //
     // Create the user account.
     //
     XDB::startTransaction();
     XDB::execute("UPDATE  accounts\n                         SET  password = {?}, state = 'active',\n                              registration_date = NOW(), email = NULL\n                       WHERE  uid = {?}", $password, $uid);
     XDB::execute("UPDATE  profiles\n                         SET  birthdate = {?}, last_change = NOW()\n                       WHERE  pid = {?}", $birthdate, $pid);
     XDB::execute('INSERT INTO  email_source_account (email, uid, type, flags, domain)
                        SELECT  {?}, {?}, \'forlife\', \'\', id
                          FROM  email_virtual_domains
                         WHERE  name = {?}', $forlife, $uid, $mail_domain);
     XDB::execute('INSERT INTO  email_source_account (email, uid, type, flags, domain)
                        SELECT  {?}, {?}, \'alias\', \'bestalias\', id
                          FROM  email_virtual_domains
                         WHERE  name = {?}', $bestalias, $uid, $mail_domain);
     if ($emailXorg2) {
         XDB::execute('INSERT INTO  email_source_account (email, uid, type, flags, domain)
                            SELECT  {?}, {?}, \'alias\', \'\', id
                              FROM  email_virtual_domains
                             WHERE  name = {?}', $emailXorg2, $uid, $mail_domain);
     }
     XDB::commit();
     // 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.
     Platal::session()->start(AUTH_PASSWD);
     // Add the registration email address as first and only redirection.
     require_once 'emails.inc.php';
     $user = User::getSilentWithUID($uid);
     $redirect = new Redirect($user);
     $redirect->add_email($email);
     fix_bestalias($user);
     // If the user was registered to some aliases and MLs, we must change
     // the subscription to her forlife email.
     if ($old_account_email) {
         $listClient = new MMList($user);
         $listClient->change_user_email($old_account_email, $user->forlifeEmail());
         update_alias_user($old_account_email, $user->forlifeEmail());
     }
     // Subscribe the user to the services she did request at registration time.
     require_once 'newsletter.inc.php';
     foreach (explode(',', $services) as $service) {
         switch ($service) {
             case 'ax_letter':
                 /* This option is deprecated by 'com_letters' */
                 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
                 break;
             case 'com_letters':
                 NewsLetter::forGroup(NewsLetter::GROUP_AX)->subscribe($user);
                 NewsLetter::forGroup(NewsLetter::GROUP_EP)->subscribe($user);
                 NewsLetter::forGroup(NewsLetter::GROUP_FX)->subscribe($user);
                 break;
             case 'nl':
                 NewsLetter::forGroup(NewsLetter::GROUP_XORG)->subscribe($user);
                 break;
             case 'imap':
                 Email::activate_storage($user, 'imap', Bogo::IMAP_DEFAULT);
                 break;
             case 'ml_promo':
                 if ($isX) {
                     $r = XDB::query('SELECT id FROM groups WHERE diminutif = {?}', $yearpromo);
                     if ($r->numRows()) {
                         $asso_id = $r->fetchOneCell();
                         XDB::execute('INSERT IGNORE INTO  group_members (uid, asso_id)
                                                   VALUES  ({?}, {?})', $uid, $asso_id);
                         try {
                             MailingList::subscribePromo($yearpromo, $user);
                         } catch (Exception $e) {
                             PlErrorReport::report($e);
                             $page->trigError("L'inscription à la liste promo" . $yearpromo . " a échouée.");
                         }
                     }
                 }
                 break;
         }
     }
     // Log the registration in the user session.
     S::logger($uid)->log('inscription', $email);
     XDB::execute("UPDATE  register_pending\n                         SET  hash = 'INSCRIT'\n                       WHERE  uid = {?}", $uid);
     // Congratulate our newly registered user by email.
     $mymail = new PlMailer('register/success.mail.tpl');
     $mymail->addTo("\"{$user->fullName()}\" <{$user->forlifeEmail()}>");
     if ($isX) {
         $mymail->setSubject('Bienvenue parmi les X sur le web !');
     } else {
         $mymail->setSubject('Bienvenue sur Polytechnique.org !');
     }
     $mymail->assign('forlife', $forlife);
     $mymail->assign('firstname', $firstname);
     $mymail->send();
     // Index the user, to allow her to appear in searches.
     Profile::rebuildSearchTokens($pid);
     // Notify other users which were watching for her arrival.
     XDB::execute('INSERT INTO  contacts (uid, contact)
                        SELECT  uid, {?}
                          FROM  watch_nonins
                         WHERE  ni_id = {?}', $pid, $uid);
     XDB::execute('DELETE FROM  watch_nonins
                         WHERE  ni_id = {?}', $uid);
     Platal::session()->updateNbNotifs();
     // Forcibly register the new user on default forums.
     $registeredForums = array('xorg.general', 'xorg.pa.divers', 'xorg.pa.logements');
     if ($isX) {
         $promoForum = 'xorg.promo.' . strtolower($promo);
         $exists = XDB::fetchOneCell('SELECT  COUNT(*)
                                        FROM  forums
                                       WHERE  name = {?}', $promoForum);
         if ($exists == 0) {
             // Notify the newsgroup admin of the promotion forum needs be created.
             $promoFull = new UserFilter(new UFC_Promo('=', UserFilter::DISPLAY, $promo));
             $promoRegistered = new UserFilter(new PFC_And(new UFC_Promo('=', UserFilter::DISPLAY, $promo), new UFC_Registered(true), new PFC_Not(new UFC_Dead())));
             if ($promoRegistered->getTotalCount() > 0.2 * $promoFull->getTotalCount()) {
                 $mymail = new PlMailer('admin/forums-promo.mail.tpl');
                 $mymail->assign('promo', $promo);
                 $mymail->send();
             }
         } else {
             $registeredForums[] = $promoForum;
         }
     }
     foreach ($registeredForums as $forum) {
         XDB::execute("INSERT INTO  forum_subs (fid, uid)\n                               SELECT  fid, {?}\n                                 FROM  forums\n                                WHERE  name = {?}", $uid, $val);
     }
     // Update the global registration count stats.
     $globals->updateNbIns();
     //
     // Update collateral data sources, and inform watchers by email.
     //
     // Email the referrer(s) of this new user.
     $res = XDB::iterRow("SELECT  sender, GROUP_CONCAT(email SEPARATOR ', ') AS mails, MAX(last) AS lastDate\n                               FROM  register_marketing\n                              WHERE  uid = {?}\n                           GROUP BY  sender\n                           ORDER BY  lastDate DESC", $uid);
     XDB::execute("UPDATE  register_mstats\n                         SET  success = NOW()\n                       WHERE  uid = {?}", $uid);
     $market = array();
     while (list($senderid, $maketingEmails, $lastDate) = $res->next()) {
         $sender = User::getWithUID($senderid);
         $market[] = " - par {$sender->fullName()} sur {$maketingEmails} (le plus récemment le {$lastDate})";
         $mymail = new PlMailer('register/marketer.mail.tpl');
         $mymail->setSubject("{$firstname} {$lastname} s'est inscrit à Polytechnique.org !");
         $mymail->setTo($sender);
         $mymail->assign('sender', $sender);
         $mymail->assign('firstname', $firstname);
         $mymail->assign('lastname', $lastname);
         $mymail->assign('promo', $promo);
         $mymail->assign('sex', $sex);
         $mymail->setTxtBody(wordwrap($msg, 72));
         $mymail->send();
     }
     // Email the plat/al administrators about the registration.
     if ($globals->register->notif) {
         $mymail = new PlMailer('register/registration.mail.tpl');
         $mymail->setSubject("Inscription de {$firstname} {$lastname} ({$promo})");
         $mymail->assign('firstname', $firstname);
         $mymail->assign('lastname', $lastname);
         $mymail->assign('promo', $promo);
         $mymail->assign('sex', $sex);
         $mymail->assign('birthdate', $birthdate);
         $mymail->assign('birthdate_ref', $birthdate_ref);
         $mymail->assign('forlife', $forlife);
         $mymail->assign('email', $email);
         $mymail->assign('logger', S::logger());
         if (count($market) > 0) {
             $mymail->assign('market', implode("\n", $market));
         }
         $mymail->setTxtBody($msg);
         $mymail->send();
     }
     // Remove old pending marketing requests for the new user.
     Marketing::clear($uid);
     pl_redirect('profile/edit');
 }
Exemplo n.º 15
0
 function handler_admin($page)
 {
     $page->changeTpl('xnet/admin.tpl');
     if (Get::has('del')) {
         $res = XDB::query('SELECT id, nom, mail_domain
                                        FROM groups WHERE diminutif={?}', Get::v('del'));
         list($id, $nom, $domain) = $res->fetchOneRow();
         $page->assign('nom', $nom);
         if ($id && Post::has('del')) {
             S::assert_xsrf_token();
             XDB::query('DELETE FROM group_members WHERE asso_id={?}', $id);
             $page->trigSuccess('membres supprimés');
             if ($domain) {
                 XDB::execute('DELETE  v
                                 FROM  email_virtual         AS v
                           INNER JOIN  email_virtual_domains AS d ON (v.domain = d.id)
                                WHERE  d.name = {?}', $domain);
                 XDB::execute('DELETE FROM  email_virtual_domains
                                     WHERE  name = {?}', $domain);
                 $page->trigSuccess('suppression des alias mails');
                 $mmlist = new MMList(S::v('uid'), S::v('password'), $domain);
                 if ($listes = $mmlist->get_lists()) {
                     foreach ($listes as $l) {
                         $mmlist->delete_list($l['list'], true);
                     }
                     $page->trigSuccess('mail lists surpprimées');
                 }
             }
             XDB::query('DELETE FROM groups WHERE id={?}', $id);
             $page->trigSuccess("Groupe {$nom} supprimé");
             Get::kill('del');
         }
         if (!$id) {
             Get::kill('del');
         }
     }
     if (Post::has('diminutif') && Post::v('diminutif') != "") {
         S::assert_xsrf_token();
         $res = XDB::query('SELECT  COUNT(*)
                              FROM  groups
                             WHERE  diminutif = {?}', Post::v('diminutif'));
         if ($res->fetchOneCell() == 0) {
             XDB::execute('INSERT INTO  groups (id, diminutif)
                                VALUES  (NULL, {?})', Post::v('diminutif'));
             pl_redirect(Post::v('diminutif') . '/edit');
         } else {
             $page->trigError('Le diminutif demandé est déjà pris.');
         }
     }
     $res = XDB::query('SELECT  nom, diminutif
                          FROM  groups
                      ORDER BY  nom');
     $page->assign('assos', $res->fetchAllAssoc());
 }
Exemplo n.º 16
0
 public function process(&$global_success)
 {
     $global_success = true;
     $this->fetchData();
     foreach ($this->settings as $field => &$setting) {
         $success = false;
         if (!is_null($setting)) {
             $this->values[$field] = $setting->value($this, $field, Post::v($field, ''), $success);
         } else {
             $success = true;
             $this->values[$field] = Post::v($field, '');
         }
         $this->errors[$field] = !$success;
         $global_success = $global_success && $success;
     }
     if ($global_success) {
         if ($this->checkChanges()) {
             /* Save changes atomically to avoid inconsistent state
              * in case of error.
              */
             if (!XDB::runTransaction(array($this, 'saveData'))) {
                 $global_success = false;
                 return PlWizard::CURRENT_PAGE;
             }
             $this->markChange();
         }
         // XXX: removes this code once all merge related issues have been fixed.
         static $issues = array(0 => array('name', 'promo', 'phone', 'education'), 1 => array('address'), 2 => array('job'));
         if (isset($issues[Post::i('valid_page')])) {
             foreach ($issues[Post::i('valid_page')] as $issue) {
                 XDB::execute("UPDATE  profile_merge_issues\n                                     SET  issues = REPLACE(issues, {?}, '')\n                                   WHERE  pid = {?}", $issue, $this->pid());
             }
         }
         return Post::has('next_page') ? PlWizard::NEXT_PAGE : PlWizard::CURRENT_PAGE;
     }
     $text = "Certains champs n'ont pas pu être validés, merci de corriger les informations " . (S::user()->isMe($this->owner) ? "de ton profil et de revalider ta demande." : "du profil et de revalider ta demande.");
     Platal::page()->trigError($text);
     return PlWizard::CURRENT_PAGE;
 }
Exemplo n.º 17
0
 function handler_edit_announce($page, $aid = null)
 {
     global $globals, $platal;
     $page->changeTpl('xnetgrp/announce-edit.tpl');
     $page->assign('new', is_null($aid));
     $art = array();
     if (Post::v('valid') == 'Visualiser' || Post::v('valid') == 'Enregistrer' || Post::v('valid') == 'Supprimer l\'image' || Post::v('valid') == 'Pas d\'image') {
         S::assert_xsrf_token();
         if (!is_null($aid)) {
             $art['id'] = $aid;
         }
         $art['titre'] = Post::v('titre');
         $art['texte'] = Post::v('texte');
         $art['contacts'] = Post::v('contacts');
         $art['promo_min'] = Post::i('promo_min');
         $art['promo_max'] = Post::i('promo_max');
         $art['nom'] = S::v('nom');
         $art['prenom'] = S::v('prenom');
         $art['promo'] = S::v('promo');
         $art['hruid'] = S::user()->login();
         $art['uid'] = S::user()->id();
         $art['expiration'] = Post::v('expiration');
         $art['public'] = Post::has('public');
         $art['xorg'] = Post::has('xorg');
         $art['nl'] = Post::has('nl');
         $art['event'] = Post::v('event');
         $upload = new PlUpload(S::user()->login(), 'xnetannounce');
         $this->upload_image($page, $upload);
         $art['contact_html'] = $art['contacts'];
         if ($art['event']) {
             $art['contact_html'] .= "\n{$globals->baseurl}/{$platal->ns}events/sub/{$art['event']}";
         }
         if (!$art['public'] && ($art['promo_min'] > $art['promo_max'] && $art['promo_max'] != 0 || $art['promo_min'] != 0 && ($art['promo_min'] <= 1900 || $art['promo_min'] >= 2020) || $art['promo_max'] != 0 && ($art['promo_max'] <= 1900 || $art['promo_max'] >= 2020))) {
             $page->trigError("L'intervalle de promotions est invalide.");
             Post::kill('valid');
         }
         if (!trim($art['titre']) || !trim($art['texte'])) {
             $page->trigError("L'article doit avoir un titre et un contenu.");
             Post::kill('valid');
         }
         if (Post::v('valid') == 'Supprimer l\'image') {
             $upload->rm();
             Post::kill('valid');
         }
         $art['photo'] = $upload->exists() || Post::i('photo');
         if (Post::v('valid') == 'Pas d\'image' && !is_null($aid)) {
             XDB::query('DELETE FROM  group_announces_photo
                               WHERE  eid = {?}', $aid);
             $upload->rm();
             Post::kill('valid');
             $art['photo'] = false;
         }
     }
     if (Post::v('valid') == 'Enregistrer') {
         $promo_min = $art['public'] ? 0 : $art['promo_min'];
         $promo_max = $art['public'] ? 0 : $art['promo_max'];
         $flags = new PlFlagSet();
         if ($art['public']) {
             $flags->addFlag('public');
         }
         if ($art['photo']) {
             $flags->addFlag('photo');
         }
         if (is_null($aid)) {
             $fulltext = $art['texte'];
             if (!empty($art['contact_html'])) {
                 $fulltext .= "\n\n'''Contacts :'''\\\\\n" . $art['contact_html'];
             }
             $post = null;
             if ($globals->asso('forum')) {
                 require_once 'banana/forum.inc.php';
                 $banana = new ForumsBanana(S::user());
                 $post = $banana->post($globals->asso('forum'), null, $art['titre'], MiniWiki::wikiToText($fulltext, false, 0, 80));
             }
             XDB::query('INSERT INTO  group_announces (uid, asso_id, create_date, titre, texte, contacts,
                                                       expiration, promo_min, promo_max, flags, post_id)
                              VALUES  ({?}, {?}, NOW(), {?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})', S::i('uid'), $globals->asso('id'), $art['titre'], $art['texte'], $art['contact_html'], $art['expiration'], $promo_min, $promo_max, $flags, $post);
             $aid = XDB::insertId();
             if ($art['photo']) {
                 list($imgx, $imgy, $imgtype) = $upload->imageInfo();
                 XDB::execute('INSERT INTO  group_announces_photo
                                       SET  eid = {?}, attachmime = {?}, x = {?}, y = {?}, attach = {?}', $aid, $imgtype, $imgx, $imgy, $upload->getContents());
             }
             if ($art['xorg']) {
                 $article = new EvtReq("[{$globals->asso('nom')}] " . $art['titre'], $fulltext, $art['promo_min'], $art['promo_max'], $art['expiration'], "", S::user(), $upload);
                 $article->submit();
                 $page->trigWarning("L'affichage sur la page d'accueil de Polytechnique.org est en attente de validation.");
             } else {
                 if ($upload && $upload->exists()) {
                     $upload->rm();
                 }
             }
             if ($art['nl']) {
                 $article = new NLReq(S::user(), $globals->asso('nom') . " : " . $art['titre'], $art['texte'], $art['contact_html']);
                 $article->submit();
                 $page->trigWarning("La parution dans la Lettre Mensuelle est en attente de validation.");
             }
         } else {
             XDB::query('UPDATE  group_announces
                            SET  titre = {?}, texte = {?}, contacts = {?}, expiration = {?},
                                 promo_min = {?}, promo_max = {?}, flags = {?}
                          WHERE  id = {?} AND asso_id = {?}', $art['titre'], $art['texte'], $art['contacts'], $art['expiration'], $promo_min, $promo_max, $flags, $art['id'], $globals->asso('id'));
             if ($art['photo'] && $upload->exists()) {
                 list($imgx, $imgy, $imgtype) = $upload->imageInfo();
                 XDB::execute('INSERT INTO  group_announces_photo (eid, attachmime, attach, x, y)
                                    VALUES  ({?}, {?}, {?}, {?}, {?})
                   ON DUPLICATE KEY UPDATE  attachmime = VALUES(attachmime), attach = VALUES(attach), x = VALUES(x), y = VALUES(y)', $aid, $imgtype, $upload->getContents(), $imgx, $imgy);
                 $upload->rm();
             }
         }
     }
     if (Post::v('valid') == 'Enregistrer' || Post::v('valid') == 'Annuler') {
         pl_redirect("");
     }
     if (empty($art) && !is_null($aid)) {
         $res = XDB::query("SELECT  *, FIND_IN_SET('public', flags) AS public,\n                                       FIND_IN_SET('photo', flags) AS photo\n                                 FROM  group_announces\n                                WHERE  asso_id = {?} AND id = {?}", $globals->asso('id'), $aid);
         if ($res->numRows()) {
             $art = $res->fetchOneAssoc();
             $art['contact_html'] = $art['contacts'];
         } else {
             $page->kill("Aucun article correspond à l'identifiant indiqué.");
         }
     }
     if (is_null($aid)) {
         $events = XDB::iterator("SELECT *\n                                      FROM group_events\n                                     WHERE asso_id = {?} AND archive = 0", $globals->asso('id'));
         if ($events->total()) {
             $page->assign('events', $events);
         }
     }
     $art['contact_html'] = @MiniWiki::WikiToHTML($art['contact_html']);
     $page->assign('art', $art);
     $page->assign_by_ref('upload', $upload);
 }
Exemplo n.º 18
0
 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\n                             SET  recongroup_id = {?}, status = 'closed'\n                           WHERE  id IN {?}", $recongp_id, $recon_ids);
         // create 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)
                             WHERE  t.recon_id IN {?} AND t.status = "confirmed"
                          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.');
         $this->handler_adm_reconcile($page);
     } elseif ($action == 'delgroup') {
         S::assert_xsrf_token();
         XDB::execute("UPDATE  payment_reconcilations\n                             SET  status = 'transfering', recongroup_id = NULL\n                           WHERE  recongroup_id = {?}", $id);
         XDB::execute("DELETE FROM  payment_transfers\n                                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();
         $account_id = XDB::fetchOneCell('SELECT  rib_id
                                            FROM  payments          AS p 
                                       LEFT JOIN  payment_transfers AS t ON (t.payment_id = p.id)
                                           WHERE  t.id = {?}', $id);
         XDB::execute('UPDATE  payment_transfers
                          SET  date = NOW(), account_id = {?}
                        WHERE  id = {?}', $account_id, $id);
         $page->trigSuccess('Virement ' . $id . ' confirmé.');
         $this->handler_adm_reconcile($page);
     } else {
         pl_redirect('admin/reconcile');
     }
 }
Exemplo n.º 19
0
 function handler_prefs_email($page)
 {
     $page->changeTpl('platal/email_preferences.tpl');
     if (Post::has('submit')) {
         S::assert_xsrf_token();
         $from_email = Post::t('from_email');
         $from_format = Post::v('from_format');
         // Checks email.
         $email_regex = '/^[a-z0-9.\\-+_\\$]+@([\\-.+_]?[a-z0-9])+$/i';
         if (!preg_match($email_regex, $from_email)) {
             $full_regex = '/^[^<]*<[a-z0-9.\\-+_\\$]+@([\\-.+_]?[a-z0-9])+>$/i';
             if (!preg_match($full_regex, $from_email)) {
                 $page->trigError("L'adresse email est erronée.");
                 $error = true;
                 $page->assign('from_email', $from_email);
                 $page->assign('from_format', $from_format);
                 $page->assign('error', true);
                 return;
             }
         }
         // Saves data.
         XDB::execute('UPDATE  accounts
                          SET  from_email = {?}, from_format = {?}
                        WHERE  uid = {?}', $from_email, $from_format == 'html' ? 'html' : 'text', S::user()->id());
         $page->trigSuccess('Données enregistrées.');
     }
     $data = XDB::fetchOneAssoc('SELECT  from_email, from_format
                                   FROM  accounts
                                  WHERE  uid = {?}', S::user()->id());
     $page->assign('from_email', $data['from_email']);
     $page->assign('from_format', $data['from_format']);
     $page->assign('error', false);
 }
Exemplo n.º 20
0
 function handler_admin_nl_edit($page, $nid = 'last', $aid = null, $action = 'edit')
 {
     $page->changeTpl('newsletter/edit.tpl');
     $page->addCssLink('nl.Polytechnique.org.css');
     $page->setTitle('Administration - Newsletter : Édition');
     $nl = $this->getNl();
     if (!$nl) {
         return PL_NOT_FOUND;
     }
     try {
         $issue = $nl->getIssue($nid, false);
     } catch (MailNotFound $e) {
         return PL_NOT_FOUND;
     }
     $ufb = $nl->getSubscribersUFB();
     $ufb_keepenv = false;
     // Will be set to True if there were invalid modification to the UFB.
     // Convert NLIssue error messages to human-readable errors
     $error_msgs = array(NLIssue::ERROR_INVALID_REPLY_TO => "L'adresse de réponse est invalide.", NLIssue::ERROR_INVALID_SHORTNAME => "Le nom court est invalide ou vide.", NLIssue::ERROR_INVALID_UFC => "Le filtre des destinataires est invalide.", NLIssue::ERROR_TOO_LONG_UFC => "Le nombre de matricules AX renseigné est trop élevé.", NLIssue::ERROR_SQL_SAVE => "Une erreur est survenue en tentant de sauvegarder la lettre, merci de réessayer.");
     // Update the current issue
     if ($aid == 'update' && Post::has('submit')) {
         // Save common fields
         $issue->title = Post::s('title');
         $issue->title_mail = Post::s('title_mail');
         $issue->head = Post::s('head');
         $issue->signature = Post::s('signature');
         $issue->reply_to = Post::s('reply_to');
         if ($issue->isEditable()) {
             // Date and shortname may only be modified for pending NLs, otherwise all links get broken.
             $issue->date = Post::s('date');
             $issue->shortname = strlen(Post::blank('shortname')) ? null : Post::s('shortname');
             $issue->sufb->updateFromEnv($ufb->getEnv());
             if ($nl->automaticMailingEnabled()) {
                 $issue->send_before = preg_replace('/^(\\d\\d\\d\\d)(\\d\\d)(\\d\\d)$/', '\\1-\\2-\\3', Post::v('send_before_date')) . ' ' . Post::i('send_before_time_Hour') . ':00:00';
             }
         }
         $errors = $issue->save();
         if (count($errors)) {
             foreach ($errors as $error_code) {
                 $page->trigError($error_msgs[$error_code]);
             }
         }
     }
     // Delete an article
     if ($action == 'delete') {
         $issue->delArticle($aid);
         pl_redirect($nl->adminPrefix(true, false) . "/edit/{$nid}");
     }
     // Save an article
     if (Post::v('save')) {
         $art = new NLArticle(Post::v('title'), Post::v('body'), Post::v('append'), $aid, Post::v('cid'), Post::v('pos'));
         $issue->saveArticle($art);
         pl_redirect($nl->adminPrefix(true, false) . "/edit/{$nid}");
     }
     // Edit an article
     if ($action == 'edit' && $aid != 'update') {
         $eaid = $aid;
         if (Post::has('title')) {
             $art = new NLArticle(Post::v('title'), Post::v('body'), Post::v('append'), $eaid, Post::v('cid'), Post::v('pos'));
         } else {
             $art = $eaid == 'new' ? new NLArticle() : $issue->getArt($eaid);
         }
         if ($art && !$art->check()) {
             $page->trigError("Cet article est trop long.");
         }
         $page->assign('art', $art);
     }
     // Check blacklisted IPs
     if ($aid == 'blacklist_check') {
         global $globals;
         $ips_to_check = array();
         $blacklist_host_resolution_count = 0;
         foreach ($issue->arts as $key => $articles) {
             foreach ($articles as $article) {
                 $article_ips = $article->getLinkIps($blacklist_host_resolution_count);
                 if (!empty($article_ips)) {
                     $ips_to_check[$article->title()] = $article_ips;
                 }
             }
         }
         $page->assign('ips_to_check', $ips_to_check);
         if ($blacklist_host_resolution_count >= $globals->mail->blacklist_host_resolution_limit) {
             $page->trigError("Toutes les url et adresses emails de la lettre" . " n'ont pas été prises en compte car la" . " limite du nombre de résolutions DNS" . " autorisée a été atteinte.");
         }
     }
     if ($issue->state == NLIssue::STATE_SENT) {
         $page->trigWarning("Cette lettre a déjà été envoyée ; il est recommandé de limiter les modifications au maximum (orthographe, adresses web et mail).");
     }
     $ufb->setEnv($issue->sufb->getEnv());
     $page->assign_by_ref('nl', $nl);
     $page->assign_by_ref('issue', $issue);
 }
Exemplo n.º 21
0
 function handler_public($page, $hruid = null)
 {
     $page->changeTpl('marketing/public.tpl');
     // Retrieves the user info, and checks the user is not yet registered.
     $user = User::getSilent($hruid);
     if (!$user || !$user->hasProfile()) {
         return PL_NOT_FOUND;
     }
     if ($user->state != 'pending') {
         $page->kill('Cet utilisateur est déjà inscrit');
     }
     // Displays the page, and handles the eventual user actions.
     $page->assign('full_name', $user->fullName());
     $page->assign('promo', $user->promo());
     if (Post::has('valide')) {
         S::assert_xsrf_token();
         $email = trim(Post::v('mail'));
         require_once 'emails.inc.php';
         if (!isvalid_email_redirection($email, $user)) {
             $page->trigError('Email invalide&nbsp;!');
         } else {
             // On cherche les marketings précédents sur cette adresse
             // email, en se restreignant au dernier mois
             if (Marketing::get($user->id(), $email, true)) {
                 $page->assign('already', true);
             } else {
                 $page->assign('ok', true);
                 check_email($email, "Une adresse surveillée est proposée au marketing par " . S::user()->login());
                 $market = new Marketing($user->id(), $email, 'default', null, Post::v('origine'), S::v('uid'), Post::v('origine') == 'user' ? Post::v('personal_notes') : null);
                 $market->add();
             }
         }
     } else {
         global $globals;
         require_once 'marketing.inc.php';
         $sender = User::getSilent(S::v('uid'));
         $perso_signature = 'Cordialement,<br />-- <br />' . $sender->fullName();
         $market = new AnnuaireMarketing(null, true);
         $text = $market->getText(array('sexe' => $user->isFemale(), 'forlife_email' => $user->hruid . "@" . $user->mainEmailDomain(), 'forlife_email2' => $user->hruid . "@" . $user->alternateEmailDomain()));
         $text = str_replace('%%hash%%', '', $text);
         $text = str_replace('%%personal_notes%%', '<em id="personal_notes_display"></em>', $text);
         $text = str_replace('%%sender%%', '<span id="sender">' . $perso_signature . '</span>', $text);
         $page->assign('text', nl2br($text));
         $page->assign('perso_signature', $perso_signature);
         $page->assign('mail_part', 'escaped_html');
     }
 }
Exemplo n.º 22
0
 function handler_acreate($page)
 {
     if (!$this->get_lists_domain()) {
         return PL_NOT_FOUND;
     }
     $page->changeTpl('xnetlists/alias-create.tpl');
     if (!Post::has('submit')) {
         return;
     } else {
         S::assert_xsrf_token();
     }
     if (!Post::has('liste')) {
         $page->trigError('Le champs «&nbsp;adresse souhaitée&nbsp;» est vide.');
         return;
     }
     $list = Post::v('liste');
     if (!preg_match("/^[a-zA-Z0-9\\-\\.]*\$/", $list)) {
         $page->trigError('Le nom de l\'alias ne doit contenir que des lettres,' . ' chiffres, tirets et points.');
         return;
     }
     require_once 'emails.inc.php';
     $lists_domain = $this->get_lists_domain();
     if (list_exist($list, $lists_domain)) {
         $page->trigError('Cet alias est déjà pris.');
         return;
     }
     add_to_list_alias(S::i('uid'), $list, $lists_domain);
     pl_redirect('alias/admin/' . $list . '@' . $lists_domain);
 }
Exemplo n.º 23
0
 protected function action_updateProfile()
 {
     global $globals;
     $page =& Platal::page();
     $colors = glob(dirname(__FILE__) . '/../../htdocs/images/banana/m2*.gif');
     foreach ($colors as $key => $path) {
         $path = basename($path, '.gif');
         $colors[$key] = substr($path, 2);
     }
     $page->assign('colors', $colors);
     if (Post::has('action') && Post::v('action') == 'Enregistrer') {
         S::assert_xsrf_token();
         $flags = new PlFlagSet();
         if (Post::b('bananadisplay')) {
             $flags->addFlag('threads');
         }
         if (Post::b('bananaupdate')) {
             $flags->addFlag('automaj');
         }
         if (Post::b('bananaxface')) {
             $flags->addFlag('xface');
         }
         $unread = Post::s('unread');
         $read = Post::s('read');
         if (!in_array($unread, $colors) || !in_array($read, $colors)) {
             $page->trigError('Le choix de type pour l\'arborescence est invalide');
         } else {
             $last_seen = XDB::query('SELECT  last_seen
                                        FROM  forum_profiles
                                       WHERE  uid = {?}', $this->user->id());
             if ($last_seen->numRows() > 0) {
                 $last_seen = $last_seen->fetchOneCell();
             } else {
                 $last_seen = '0000-00-00';
             }
             XDB::execute('INSERT INTO  forum_profiles (uid, sig, mail, name, flags, tree_unread, tree_read, last_seen)
                                VALUES  ({?}, {?}, {?}, {?}, {?}, {?}, {?}, {?})
               ON DUPLICATE KEY UPDATE  sig = VALUES(sig), mail = VALUES(mail), name = VALUES(name), flags = VALUES(flags),
                                        tree_unread = VALUES(tree_unread), tree_read = VALUES(tree_read), last_seen = VALUES(last_seen)', $this->user->id(), Post::v('bananasig'), Post::v('bananamail'), Post::v('banananame'), $flags, $unread, $read, $last_seen);
             $page->trigSuccess('Ton profil a été mis à jour');
         }
     }
     $infos = $this->fetchProfile();
     $page->assign('nom', $infos['name']);
     $page->assign('mail', $infos['mail']);
     $page->assign('sig', $infos['sig']);
     $page->assign('disp', $infos['threads']);
     $page->assign('maj', $infos['maj']);
     $page->assign('xface', $infos['xface']);
     $page->assign('unread', $infos['tree_unread']);
     $page->assign('read', $infos['tree_read']);
     return null;
 }
Exemplo n.º 24
0
 function handler_duplicated($page, $action = 'list', $email = null)
 {
     $page->changeTpl('emails/duplicated.tpl');
     $states = array('pending' => 'En attente...', 'safe' => 'Pas d\'inquiétude', 'unsafe' => 'Recherches en cours', 'dangerous' => 'Usurpations par cette adresse');
     $page->assign('states', $states);
     if (Post::has('action')) {
         S::assert_xsrf_token();
     }
     switch (Post::v('action')) {
         case 'create':
             if (trim(Post::v('emailN')) != '') {
                 Xdb::execute('INSERT IGNORE INTO email_watch (email, state, detection, last, uid, description)
                                       VALUES ({?}, {?}, CURDATE(), NOW(), {?}, {?})', trim(Post::v('emailN')), Post::v('stateN'), S::i('uid'), Post::v('descriptionN'));
             }
             break;
         case 'edit':
             Xdb::execute('UPDATE email_watch
                          SET state = {?}, last = NOW(), uid = {?}, description = {?}
                        WHERE email = {?}', Post::v('stateN'), S::i('uid'), Post::v('descriptionN'), Post::v('emailN'));
             break;
         default:
             if ($action == 'delete' && !is_null($email)) {
                 Xdb::execute('DELETE FROM email_watch WHERE email = {?}', $email);
             }
     }
     if ($action != 'create' && $action != 'edit') {
         $action = 'list';
     }
     $page->assign('action', $action);
     if ($action == 'list') {
         $it = XDB::iterRow('SELECT  w.email, w.detection, w.state, s.email AS forlife
                               FROM  email_watch            AS w
                         INNER JOIN  email_redirect_account AS r ON (w.email = r.redirect)
                         INNER JOIN  email_source_account   AS s ON (s.uid = r.uid AND s.type = \'forlife\')
                           ORDER BY  w.state, w.email, s.email');
         $table = array();
         $props = array();
         while (list($email, $date, $state, $forlife) = $it->next()) {
             if (count($props) == 0 || $props['mail'] != $email) {
                 if (count($props) > 0) {
                     $table[] = $props;
                 }
                 $props = array('mail' => $email, 'detection' => $date, 'state' => $state, 'users' => array($forlife));
             } else {
                 $props['users'][] = $forlife;
             }
         }
         if (count($props) > 0) {
             $table[] = $props;
         }
         $page->assign('table', $table);
     } elseif ($action == 'edit') {
         $it = XDB::iterRow('SELECT  w.detection, w.state, w.last, w.description,
                                     a.hruid AS edit, s.email AS forlife
                               FROM  email_watch            AS w
                         INNER JOIN  email_redirect_account AS r ON (w.email = r.redirect)
                         INNER JOIN  email_source_account   AS s ON (s.uid = r.uid AND s.type = \'forlife\')
                          LEFT JOIN  accounts               AS a ON (w.uid = a.uid)
                              WHERE  w.email = {?}
                           ORDER BY  s.email', $email);
         $props = array();
         while (list($detection, $state, $last, $description, $edit, $forlife) = $it->next()) {
             if (count($props) == 0) {
                 $props = array('mail' => $email, 'detection' => $detection, 'state' => $state, 'last' => $last, 'description' => $description, 'edit' => $edit, 'users' => array($forlife));
             } else {
                 $props['users'][] = $forlife;
             }
         }
         $page->assign('doublon', $props);
     }
 }
Exemplo n.º 25
0
 protected function startSessionAs($user, $level)
 {
     if (!is_null(S::user()) && S::user()->id() != $user->id() || S::has('uid') && S::i('uid') != $user->id()) {
         return false;
     } else {
         if (S::has('uid')) {
             return true;
         }
     }
     if ($level == AUTH_SUID) {
         S::set('auth', AUTH_PASSWD);
     }
     // Loads uid and hruid into the session for developement conveniance.
     $_SESSION = array_merge($_SESSION, array('uid' => $user->id(), 'hruid' => $user->hruid, 'token' => $user->token, 'user' => $user));
     // Starts the session's logger, and sets up the permanent cookie.
     if (S::suid()) {
         S::logger()->log("suid_start", S::v('hruid') . ' by ' . S::suid('hruid'));
     } else {
         S::logger()->saveLastSession();
         Cookie::set('uid', $user->id(), 300);
         if (S::i('auth_by_cookie') == $user->id() || Post::v('remember', 'false') == 'true') {
             $this->setAccessCookie(false, S::i('auth_by_cookie') != $user->id());
         } else {
             $this->killAccessCookie();
             // If login for an external website and not activating cookie,
             // mark that we want to disconnect once external auth checks
             // have been performed.
             if (Post::b('external_auth')) {
                 S::set('external_auth_exit', true);
             }
         }
     }
     // Finalizes the session setup.
     $this->makePerms($user->perms, $user->is_admin);
     $this->securityChecks();
     $this->setSkin();
     $this->updateNbNotifs();
     // Only check email redirection for 'internal' users.
     if ($user->checkPerms(PERMS_USER)) {
         check_redirect();
     }
     // We should not have to use this private data anymore
     S::kill('auth_by_cookie');
     return true;
 }
Exemplo n.º 26
0
 public static function send($keys, $user = null)
 {
     if ($user == null) {
         $user = S::user();
     }
     $mail = new FrankizMailer('licenses/licenses_key.mail.tpl');
     $mail->assign('keys', $keys);
     $mail->assign('multiple', count($keys) > 1);
     $mail->assign('pub_domain', in_array(Post::v('software'), License::getDomainSoftwares()));
     $mail->Subject = '[Frankiz] Ta licence MSDNAA';
     $mail->SetFrom('*****@*****.**', 'admin@windows');
     $mail->AddAddress($user->bestEmail(), $user->displayName());
     $mail->AddCC('*****@*****.**', 'admin@windows');
     $mail->Send(false);
 }
Exemplo n.º 27
0
 function handler_admin_events($page, $action = 'list', $eid = null)
 {
     $page->changeTpl('events/admin.tpl');
     $page->setTitle('Administration - Evenements');
     $page->register_modifier('hde', 'html_entity_decode');
     $arch = $action == 'archives';
     $page->assign('action', $action);
     $upload = new PlUpload(S::user()->login(), 'event');
     if ((Env::has('preview') || Post::v('action') == "Proposer") && $eid) {
         $action = 'edit';
         $this->upload_image($page, $upload);
     }
     if (Post::v('action') == 'Pas d\'image' && $eid) {
         S::assert_xsrf_token();
         $upload->rm();
         XDB::execute("DELETE FROM announce_photos WHERE eid = {?}", $eid);
         $action = 'edit';
     } elseif (Post::v('action') == 'Supprimer l\'image' && $eid) {
         S::assert_xsrf_token();
         $upload->rm();
         $action = 'edit';
     } elseif (Post::v('action') == "Proposer" && $eid) {
         S::assert_xsrf_token();
         $promo_min = Post::i('promo_min');
         $promo_max = Post::i('promo_max');
         if ($promo_min != 0 && ($promo_min <= 1900 || $promo_min >= 2020) || $promo_max != 0 && ($promo_max <= 1900 || $promo_max >= 2020 || $promo_max < $promo_min)) {
             $page->trigError("L'intervalle de promotions {$promo_min} -> {$promo_max} n'est pas valide");
             $action = 'edit';
         } else {
             $res = XDB::query('SELECT flags FROM announces WHERE id = {?}', $eid);
             $flags = new PlFlagSet($res->fetchOneCell());
             $flags->addFlag('wiki');
             if (Post::v('important')) {
                 $flags->addFlag('important');
             } else {
                 $flags->rmFlag('important');
             }
             XDB::execute('UPDATE announces
                              SET creation_date = creation_date,
                                  titre={?}, texte={?}, expiration={?}, promo_min={?}, promo_max={?},
                                  flags = {?}
                            WHERE id = {?}', Post::v('titre'), Post::v('texte'), Post::v('expiration'), Post::v('promo_min'), Post::v('promo_max'), $flags, $eid);
             if ($upload->exists() && (list($x, $y, $type) = $upload->imageInfo())) {
                 XDB::execute('INSERT INTO  announce_photos (eid, attachmime, attach, x, y)
                                    VALUES  ({?}, {?}, {?}, {?}, {?})
                   ON DUPLICATE KEY UPDATE  attachmime = VALUES(attachmime), attach = VALUES(attach), x = VALUES(x), y = VALUES(y)', $eid, $type, $upload->getContents(), $x, $y);
                 $upload->rm();
             }
         }
     }
     if ($action == 'edit') {
         $res = XDB::query('SELECT titre, texte, expiration, promo_min, promo_max, FIND_IN_SET(\'important\', flags),
                                   attach IS NOT NULL
                              FROM announces       AS e
                         LEFT JOIN announce_photos AS p ON(e.id = p.eid)
                             WHERE id={?}', $eid);
         list($titre, $texte, $expiration, $promo_min, $promo_max, $important, $img) = $res->fetchOneRow();
         $page->assign('titre', $titre);
         $page->assign('texte', $texte);
         $page->assign('promo_min', $promo_min);
         $page->assign('promo_max', $promo_max);
         $page->assign('expiration', $expiration);
         $page->assign('important', $important);
         $page->assign('eid', $eid);
         $page->assign('img', $img);
         $page->assign_by_ref('upload', $upload);
         $select = "";
         for ($i = 1; $i < 30; $i++) {
             $p_stamp = date("Ymd", time() + 3600 * 24 * $i);
             $year = substr($p_stamp, 0, 4);
             $month = substr($p_stamp, 4, 2);
             $day = substr($p_stamp, 6, 2);
             $select .= "<option value=\"{$p_stamp}\"" . ($p_stamp == strtr($expiration, array("-" => "")) ? " selected" : "") . "> {$day} / {$month} / {$year}</option>\n";
         }
         $page->assign('select', $select);
     } else {
         switch ($action) {
             case 'delete':
                 S::assert_xsrf_token();
                 XDB::execute('DELETE from announces
                                WHERE id = {?}', $eid);
                 break;
             case "archive":
                 S::assert_xsrf_token();
                 XDB::execute('UPDATE announces
                                  SET creation_date = creation_date, flags = CONCAT(flags,",archive")
                                WHERE id = {?}', $eid);
                 break;
             case "unarchive":
                 S::assert_xsrf_token();
                 XDB::execute('UPDATE announces
                                  SET creation_date = creation_date, flags = REPLACE(flags,"archive","")
                                WHERE id = {?}', $eid);
                 $action = 'archives';
                 $arch = true;
                 break;
             case "valid":
                 S::assert_xsrf_token();
                 XDB::execute('UPDATE announces
                                  SET creation_date = creation_date, flags = CONCAT(flags,",valide")
                                WHERE id = {?}', $eid);
                 break;
             case "unvalid":
                 S::assert_xsrf_token();
                 XDB::execute('UPDATE announces
                                  SET creation_date = creation_date, flags = REPLACE(flags,"valide", "")
                                WHERE id = {?}', $eid);
                 break;
         }
         $pid = $eid && $action == 'preview' ? $eid : -1;
         $sql = "SELECT  e.id, e.titre, e.texte,e.id = {$pid} AS preview, e.uid,\n                            DATE_FORMAT(e.creation_date,'%d/%m/%Y %T') AS creation_date,\n                            DATE_FORMAT(e.expiration,'%d/%m/%Y') AS expiration,\n                            e.promo_min, e.promo_max,\n                            FIND_IN_SET('valide', e.flags) AS fvalide,\n                            FIND_IN_SET('archive', e.flags) AS farch,\n                            FIND_IN_SET('wiki', e.flags) AS wiki\n                      FROM  announces    AS e\n                     WHERE  " . ($arch ? "" : "!") . "FIND_IN_SET('archive',e.flags)\n                  ORDER BY  FIND_IN_SET('valide',e.flags), e.expiration DESC";
         $page->assign('evs', XDB::iterator($sql));
     }
     $page->assign('arch', $arch);
     $page->assign('admin_evts', true);
 }
Exemplo n.º 28
0
 function handler_admin_medals($page, $action = 'list', $id = null)
 {
     $page->setTitle('Administration - Distinctions');
     $page->assign('title', 'Gestion des Distinctions');
     $table_editor = new PLTableEditor('admin/medals', 'profile_medal_enum', 'id');
     $table_editor->describe('text', 'intitulé', true);
     $table_editor->describe('img', 'nom de l\'image', false, true);
     $table_editor->describe('flags', 'valider', true);
     $table_editor->apply($page, $action, $id);
     if ($id && $action == 'edit') {
         $page->changeTpl('profile/admin_decos.tpl');
         $mid = $id;
         if (Post::v('act') == 'del') {
             XDB::execute('DELETE FROM  profile_medal_grade_enum
                                 WHERE  mid={?} AND gid={?}', $mid, Post::i('gid'));
         } else {
             foreach (Post::v('grades', array()) as $gid => $text) {
                 if ($gid === 0) {
                     if (!empty($text)) {
                         $res = XDB::query('SELECT  MAX(gid)
                                              FROM  profile_medal_grade_enum
                                             WHERE  mid = {?}', $mid);
                         $gid = $res->fetchOneCell() + 1;
                         XDB::execute('INSERT INTO  profile_medal_grade_enum (mid, gid, text, pos)
                                            VALUES  ({?}, {?}, {?}, {?})', $mid, $gid, $text, $_POST['pos']['0']);
                     }
                 } else {
                     XDB::execute('UPDATE  profile_medal_grade_enum
                                      SET  pos={?}, text={?}
                                    WHERE  gid={?} AND mid={?}', $_POST['pos'][$gid], $text, $gid, $mid);
                 }
             }
         }
         $res = XDB::iterator('SELECT gid, text, pos FROM profile_medal_grade_enum WHERE mid={?} ORDER BY pos', $mid);
         $page->assign('grades', $res);
     }
 }