Пример #1
1
 function handler_issues_promo($page, $action = '')
 {
     $page->changeTpl('fusionax/promo_issues.tpl');
     if ($action == 'edit') {
         S::assert_xsrf_token();
         $issues = XDB::rawIterRow('SELECT  p.pid, pd.directory_name, pd.promo, pm.entry_year_ax, pe.entry_year, pe.grad_year
                                      FROM  profile_merge_issues AS pm
                                INNER JOIN  profiles             AS p  ON (pm.pid = p.pid)
                                INNER JOIN  profile_display      AS pd ON (pd.pid = p.pid)
                                INNER JOIN  profile_education    AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
                                     WHERE  FIND_IN_SET(\'promo\', pm.issues)
                                  ORDER BY  pd.directory_name');
         while (list($pid, $name, $promo, $deathAX, $deathXorgEntry, $deathXorgGrad) = $issues->next()) {
             $choiceXorg = Post::has('XORG_' . $pid);
             if (!(Post::has('display_' . $pid) && Post::has('entry_' . $pid) && Post::has('grad_' . $pid))) {
                 continue;
             }
             $display = Post::i('display_' . $pid);
             $entry = Post::i('entry_' . $pid);
             $grad = Post::i('grad_' . $pid);
             if (!($grad <= $entry + 5 && $grad >= $entry + 3 && ($display >= $entry && $display <= $grad - 3))) {
                 $page->trigError("La promotion de {$name} n'a pas été corrigée.");
                 continue;
             }
             XDB::execute('UPDATE  profile_display
                              SET  promo = {?}
                            WHERE  pid = {?}', 'X' . $display, $pid);
             XDB::execute('UPDATE  profile_education
                              SET  entry_year = {?}, grad_year = {?}
                            WHERE  pid = {?} AND FIND_IN_SET(\'primary\', flags)', $entry, $grad, $pid);
             $page->trigSuccess("La promotion de {$name} a bien été corrigée.");
         }
     }
     $issues = XDB::rawFetchAllAssoc('SELECT  p.pid, p.hrpid, pd.directory_name, pd.promo, pm.entry_year_ax, pe.entry_year, pe.grad_year
                                        FROM  profile_merge_issues AS pm
                                  INNER JOIN  profiles             AS p  ON (pm.pid = p.pid)
                                  INNER JOIN  profile_display      AS pd ON (pd.pid = p.pid)
                                  INNER JOIN  profile_education    AS pe ON (pe.pid = p.pid AND FIND_IN_SET(\'primary\', pe.flags))
                                       WHERE  FIND_IN_SET(\'promo\', pm.issues)
                                    ORDER BY  pd.directory_name');
     $page->assign('issues', $issues);
     $page->assign('total', count($issues));
 }
Пример #2
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);
         }
     }
 }
Пример #3
0
 function handler_map_url($page)
 {
     pl_content_headers('text/plain');
     if (Post::has('text')) {
         $address = new Address(array('text' => Post::t('text')));
         $gmapsGeocoder = new GMapsGeocoder();
         $gmapsGeocoder->getGeocodedAddress($address);
         echo GMapsGeocoder::buildStaticMapURL($address->latitude, $address->longitude, Post::t('color'));
     }
     exit;
 }
Пример #4
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);
 }
Пример #5
0
function send_robot_homonym(PlUser $user, $email)
{
    $cc = "validation+homonyme@" . Platal::globals()->mail->domain;
    $from = "\"Support Polytechnique.org\" <{$cc}>";
    $body = Post::has('mailbody') ? Post::t('mailbody') : get_robot_mail_text($user, $email);
    $user = User::getSilentWithUID($user->id());
    $mymail = new PlMailer();
    $mymail->setFrom($from);
    $mymail->setSubject("Mise en place du robot {$email}@" . $user->mainEmailDomain());
    $mymail->addCc($cc);
    $mymail->setTxtBody($body);
    $mymail->sendTo($user);
}
Пример #6
0
 function handler_admin_url($page)
 {
     $page->changeTpl('urlshortener/admin.tpl');
     if (!Post::has('url')) {
         return;
     }
     $url = Post::t('url');
     $alias = Post::t('alias');
     $url_regex = '{^(https?|ftp)://[a-zA-Z0-9._%#+/?=&~-]+$}i';
     if (strlen($url) > 255 || !preg_match($url_regex, $url)) {
         $page->trigError("L'url donnée n'est pas valide.");
         return;
     }
     $page->assign('url', $url);
     if ($alias != '') {
         if (!preg_match('/^[a-zA-Z0-9\\-\\/]+$/i', $alias)) {
             $page->trigError("L'alias proposé n'est pas valide.");
             return;
         }
         if (preg_match('/^a\\//i', $alias)) {
             $page->trigError("L'alias commence par le préfixe 'a/' qui est réservé et donc non autorisé.");
             return;
         }
         $page->assign('alias', $alias);
         $used = XDB::fetchOneCell('SELECT  COUNT(*)
                                      FROM  url_shortener
                                     WHERE  alias = {?}', $alias);
         if ($used != 0) {
             $page->trigError("L'alias proposé est déjà utilisé.");
             return;
         }
     } else {
         do {
             $alias = 'a/' . rand_token(6);
             $used = XDB::fetchOneCell('SELECT  COUNT(*)
                                          FROM  url_shortener
                                         WHERE  alias = {?}', $alias);
         } while ($used != 0);
         $page->assign('alias', $alias);
     }
     XDB::execute('INSERT INTO  url_shortener (url, alias)
                        VALUES  ({?}, {?})', $url, $alias);
     $page->trigSuccess("L'url « " . $url . ' » est maintenant accessible depuis « http://u.w4x.org/' . $alias . ' ».');
 }
Пример #7
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());
 }
Пример #8
0
 public function handler_admin_nl_enable($page)
 {
     global $globals;
     $nl = $this->getNl();
     if ($nl) {
         return PL_FORBIDDEN;
     }
     if (Post::has('title')) {
         if (!S::has_xsrf_token()) {
             return PL_FORBIDDEN;
         }
         XDB::execute('INSERT INTO  newsletters
                               SET  group_id = {?}, name = {?}', $globals->asso('id'), Post::s('title'));
         $mailer = new PlMailer();
         $mailer->assign('group', $globals->asso('nom'));
         $mailer->assign('user', S::user());
         $mailer->send();
         $page->trigSuccessRedirect("La lettre d'informations du groupe " . $globals->asso('nom') . " a bien été créée", $globals->asso('shortname') . '/admin/nl');
     }
     $page->setTitle('Activation de la newsletter');
     $page->changeTpl('newsletter/enable.tpl');
 }
Пример #9
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&nbsp;: ' . $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é&nbsp;: ' . $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);
 }
Пример #10
0
 function handler_aaliases($page, $alias = null)
 {
     global $globals;
     require_once 'emails.inc.php';
     $page->setTitle('Administration - Aliases');
     if (Post::has('new_alias')) {
         pl_redirect('admin/aliases/' . Post::t('new_alias') . '@' . $globals->mail->domain);
     }
     // If no alias, list them all.
     if (is_null($alias)) {
         $page->changeTpl('lists/admin_aliases.tpl');
         $page->assign('aliases', array_merge(iterate_list_alias($globals->mail->domain), iterate_list_alias($globals->mail->domain2)));
         return;
     }
     list($local_part, $domain) = explode('@', $alias);
     if (!($globals->mail->domain == $domain || $globals->mail->domain2 == $domain) || !preg_match("/^[a-zA-Z0-9\\-\\.]*\$/", $local_part)) {
         $page->trigErrorRedirect('Le nom de l\'alias est erroné.', $globals->asso('diminutif') . 'admin/aliases');
     }
     // Now we can perform the action.
     if (Post::has('del_alias')) {
         S::assert_xsrf_token();
         delete_list_alias($local_part, $domain);
         $page->trigSuccessRedirect($alias . ' supprimé.', 'admin/aliases');
     }
     if (Post::has('add_member')) {
         S::assert_xsrf_token();
         if (add_to_list_alias(Post::t('add_member'), $local_part, $domain)) {
             $page->trigSuccess('Ajout réussit.');
         } else {
             $page->trigError('Ajout infructueux.');
         }
     }
     if (Get::has('del_member')) {
         S::assert_xsrf_token();
         if (delete_from_list_alias(Get::t('del_member'), $local_part, $domain)) {
             $page->trigSuccess('Suppression réussie.');
         } else {
             $page->trigError('Suppression infructueuse.');
         }
     }
     $page->changeTpl('lists/admin_edit_alias.tpl');
     $page->assign('members', list_alias_members($local_part, $domain));
     $page->assign('alias', $alias);
 }
Пример #11
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;
 }
Пример #12
0
                 foreach (Post::val('groupsIds', array()) as $key => $value) {
                     $dbStorage->InsertAddressGroupContact($addressBookRecord->IdAddress, $value);
                 }
             }
             if (isset($_SESSION[SARRAY][SEARCH_ARRAY])) {
                 unset($_SESSION[SARRAY][SEARCH_ARRAY]);
             }
             SetReport(ReportContactSuccessfulyAdded);
         } else {
             SetError(PROC_CANT_INS_NEW_CONT);
         }
     } else {
         if ($dbStorage->UpdateAddressBookRecord($addressBookRecord)) {
             if ($addressBookRecord->IdAddress) {
                 $dbStorage->DeleteAddressGroupsContactsByIdAddress($addressBookRecord->IdAddress);
                 if (Post::has('groupsIds') && count(Post::val('groupsIds', array())) > 0) {
                     foreach (Post::val('groupsIds', array()) as $key => $value) {
                         $dbStorage->InsertAddressGroupContact($addressBookRecord->IdAddress, $value);
                     }
                 }
                 SetReport(ReportContactUpdatedSuccessfuly);
             } else {
                 SetError(PROC_CANT_UPDATE_CONT);
             }
         } else {
             SetError(PROC_CANT_UPDATE_CONT . "<br />\r\n" . getGlobalError());
         }
     }
 } else {
     SetError(getGlobalError());
 }
Пример #13
0
 function handler_relance($page)
 {
     $page->changeTpl('marketing/relance.tpl');
     if (Post::has('relancer')) {
         global $globals;
         $nbdix = $globals->core->NbIns;
         $sent = array();
         $users = User::getBulkUsersWithUIDs($_POST['relance']);
         foreach ($users as $user) {
             if ($tmp = Marketing::relance($user, $nbdix)) {
                 $sent[] = $tmp . ' a été relancé.';
             }
         }
         $page->assign('sent', $sent);
     }
     $page->assign('relance', XDB::iterator('SELECT  r.date, r.relance, r.uid
                                               FROM  register_pending AS r
                                              WHERE  hash != \'INSCRIT\'
                                           ORDER BY  date DESC'));
 }
Пример #14
0
    // If someone used the 'show task' form, redirect them
    if (is_numeric($show_task)) {
        Flyspray::Redirect(CreateURL('details', $show_task));
    } else {
        Flyspray::Redirect($baseurl . '?string=' . $show_task);
    }
}
if (Flyspray::requestDuplicated()) {
    // Check that this page isn't being submitted twice
    Flyspray::show_error(3);
}
# handle all forms request that modify data
if (Req::has('action')) {
    # enforcing if the form sent the correct anti csrf token
    # only allow token by post
    if (!Post::has('csrftoken')) {
        die('missingtoken');
    } elseif (Post::val('csrftoken') == $_SESSION['csrftoken']) {
        require_once BASEDIR . '/includes/modify.inc.php';
    } else {
        die('wrongtoken');
    }
}
# start collecting infos for the answer page
if ($proj->id && $user->perms('manage_project')) {
    // Find out if there are any PM requests wanting attention
    $sql = $db->Query('SELECT COUNT(*) FROM {admin_requests} WHERE project_id = ? AND resolved_by = 0', array($proj->id));
    list($count) = $db->fetchRow($sql);
    $page->assign('pm_pendingreq_num', $count);
}
if ($user->perms('is_admin')) {
Пример #15
0
                     WHERE p.task_id = ? OR s.task_id = ?', array($task['task_id'], $task['task_id']));
 $check = $db->fetchRow($result);
 // if there are any subtasks or a parent, check that the project is not changed.
 if ($check && $check['sub_id']) {
     if ($check['project'] != Post::val('project_id')) {
         Flyspray::show_error(L('movingtodifferentproject'));
         break;
     }
 }
 $time = time();
 $result = $db->Query('SELECT * from {tasks} WHERE task_id = ?', array($task['task_id']));
 $defaults = $db->fetchRow($result);
 if (!Post::has('due_date')) {
     $due_date = $defaults['due_date'];
 }
 if (!Post::has('estimated_effort')) {
     $estimated_effort = $defaults['estimated_effort'];
 }
 $db->Query('UPDATE  {tasks}
                SET  project_id = ?, task_type = ?, item_summary = ?,
                     detailed_desc = ?, item_status = ?, mark_private = ?,
                     product_category = ?, closedby_version = ?, operating_system = ?,
                     task_severity = ?, task_priority = ?, last_edited_by = ?,
                     last_edited_time = ?, due_date = ?, percent_complete = ?, product_version = ?,
                     estimated_effort = ?
              WHERE  task_id = ?', array(Post::val('project_id', $defaults['project_id']), Post::val('task_type', $defaults['task_type']), Post::val('item_summary', $defaults['item_summary']), Post::val('detailed_desc', $defaults['detailed_desc']), Post::val('item_status', $defaults['item_status']), intval($user->can_change_private($task) && Post::val('mark_private', $defaults['mark_private'])), Post::val('product_category', $defaults['product_category']), Post::val('closedby_version', $defaults['closedby_version']), Post::val('operating_system', $defaults['operating_system']), Post::val('task_severity', $defaults['task_severity']), Post::val('task_priority', $defaults['task_priority']), intval($user->id), $time, intval($due_date), Post::val('percent_complete', $defaults['percent_complete']), Post::val('reportedver', $defaults['product_version']), intval($estimated_effort), $task['task_id']));
 // Update the list of users assigned this task
 $assignees = (array) Post::val('rassigned_to');
 $assignees_changed = count(array_diff($task['assigned_to'], $assignees)) + count(array_diff($assignees, $task['assigned_to']));
 if ($user->perms('edit_assignments') && $assignees_changed) {
     // Delete the current assignees for this task
Пример #16
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');
 }
Пример #17
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;
 }
Пример #18
0
    // Determine which project we want to see
    if (($project_id = Cookie::val('flyspray_project')) == '') {
        $project_id = $fs->prefs['default_project'];
    }
    $project_id = Req::val('project', Req::val('project_id', $project_id));
}
$proj = new Project($project_id);
// reset do for default project level entry page
if (!in_array($do, $modes)) {
    $do = $do ? Req::enum('do', $modes, $proj->prefs['default_entry']) : $proj->prefs['default_entry'];
}
$proj->setCookie();
$user = new User($uid = 0);
// verify and initiate user
$auth = new FlysprayAuth();
if (Post::val('user_name') && Post::has('password')) {
    $uid = $auth->checkLogin(Post::val('user_name'), Post::val('password'));
    if (is_array($uid)) {
        FlysprayDo::error($uid);
    }
} else {
    if (Cookie::val('flyspray_userid') && $auth->checkCookie(Cookie::val('flyspray_userid'), Cookie::val('flyspray_passhash'))) {
        $uid = Cookie::val('flyspray_userid');
    }
}
$user = new User($uid);
// Load translations
load_translations();
function debuglog($str)
{
    $file = fopen("debug.log", "a+");
Пример #19
0
 function handler_trust($page)
 {
     $this->load('openid.inc.php');
     $server = new OpenId();
     $user = S::user();
     // Initializes the OpenId environment from the request.
     if (!$server->Initialize() || !$server->IsAuthorizationRequest()) {
         $page->kill("Ta requête OpenID a échoué, merci de réessayer.");
     }
     // Prepares the SREG data, if any is required.
     $sreg_response = $server->GetSRegDataForRequest($user);
     // Asks the user about her trust level of the current request, if not
     // done yet.
     if (!Post::has('trust_accept') && !Post::has('trust_cancel')) {
         $page->changeTpl('openid/trust.tpl');
         $page->assign('openid_query', $server->GetQueryStringForRequest());
         $page->assign('relying_party', $server->GetEndpoint());
         $page->assign('sreg_data', $sreg_response->contents());
         return;
     }
     // Interprets the form results, and updates the user whitelist.
     S::assert_xsrf_token();
     $trusted = $server->UpdateEndpointTrust($user, Post::b('trust_accept') && !Post::b('trust_cancel'), Post::b('trust_always'));
     // Finally answers the request.
     if ($server->IsUserAuthorized($user) && $trusted) {
         $server->AnswerRequest(true, Post::b('trust_sreg') ? $sreg_response : null);
     } else {
         $server->AnswerRequest(false);
     }
 }
Пример #20
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);
     }
 }
Пример #21
0
 function handler_admin_name($page, $hruid = null)
 {
     $page->changeTpl('admin/admin_name.tpl');
     if (Post::has('id')) {
         $user = User::get(Post::t('id'));
         if (is_null($user)) {
             $page->trigError("L'identifiant donné ne correspond à personne ou est ambigu.");
             exit;
         }
         pl_redirect('admin/name/' . $user->hruid);
     }
     $user = User::getSilent($hruid);
     if (!is_null($user)) {
         require_once 'name.func.inc.php';
         if ($user->hasProfile()) {
             $name_types = array('lastname_main' => 'Nom patronymique', 'lastname_marital' => 'Nom marital', 'lastname_ordinary' => 'Nom usuel', 'firstname_main' => 'Prénom', 'firstname_ordinary' => 'Prénom usuel', 'pseudonym' => 'Pseudonyme');
             $names = XDB::fetchOneAssoc('SELECT  lastname_main, lastname_marital, lastname_ordinary,
                                                  firstname_main, firstname_ordinary, pseudonym
                                            FROM  profile_public_names
                                           WHERE  pid = {?}', $user->profile()->id());
         } else {
             $name_types = array('lastname' => 'Nom', 'firstname' => 'Prénom');
             $names = XDB::fetchOneAssoc('SELECT  lastname, firstname
                                            FROM  accounts
                                           WHERE  uid = {?}', $user->id());
         }
         if (Post::has('correct')) {
             $new_names = array();
             $update = true;
             foreach ($name_types as $key => $fullname) {
                 $new_names[$key] = Post::t($key);
                 if (mb_strtolower($new_names[$key]) != mb_strtolower($names[$key])) {
                     $update = false;
                 }
             }
             if ($update) {
                 if ($user->hasProfile()) {
                     update_public_names($user->profile()->id(), $new_names);
                     update_display_names($user->profile(), $new_names);
                 } else {
                     $new_names['full_name'] = build_full_name($new_names['firstname'], $new_names['lastname']);
                     $new_names['directory_name'] = build_directory_name($new_names['firstname'], $new_names['lastname']);
                     $new_names['sort_name'] = build_sort_name($new_names['firstname'], $new_names['lastname']);
                     XDB::execute('UPDATE  accounts
                                      SET  lastname = {?}, firstname = {?}, full_name = {?},
                                           directory_name = {?}, sort_name = {?}
                                    WHERE  uid = {?}', $new_names['lastname'], $new_names['firstname'], $new_names['full_name'], $new_names['directory_name'], $new_names['sort_name'], $user->id());
                 }
                 $page->trigSuccess('Mise à jour réussie.');
             } else {
                 $page->trigError('Seuls des changements de casse sont autorisés ici.');
             }
         }
         if ($user->hasProfile()) {
             $names = XDB::fetchOneAssoc('SELECT  lastname_main, lastname_marital, lastname_ordinary,
                                                  firstname_main, firstname_ordinary, pseudonym
                                            FROM  profile_public_names
                                           WHERE  pid = {?}', $user->profile()->id());
         } else {
             $names = XDB::fetchOneAssoc('SELECT  lastname, firstname
                                            FROM  accounts
                                           WHERE  uid = {?}', $user->id());
         }
         foreach ($names as $key => $name) {
             $names[$key] = array('value' => $name, 'standard' => capitalize_name($name));
             $names[$key]['different'] = $names[$key]['value'] != $names[$key]['standard'];
         }
         $page->assign('uid', $user->id());
         $page->assign('hruid', $user->hruid);
         $page->assign('names', $names);
         $page->assign('name_types', $name_types);
     }
 }
Пример #22
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);
     }
 }
Пример #23
0
 /** Check auth.
  */
 protected function doAuth($level)
 {
     global $globals;
     /* Cookie authentication
      */
     if ($level == AUTH_COOKIE && !S::has('auth_by_cookie')) {
         $this->tryCookie();
     }
     if ($level == AUTH_COOKIE && S::has('auth_by_cookie')) {
         if (!S::logged()) {
             S::set('auth', AUTH_COOKIE);
         }
         return User::getSilentWithUID(S::i('auth_by_cookie'));
     }
     /* We want to do auth... we must have infos from a form.
      */
     if (!Post::has('username') || !Post::has('response') || !S::has('challenge')) {
         return null;
     }
     /** We come from an authentication form.
      */
     if (S::suid()) {
         $login = S::suid('uid');
     } else {
         $login = Post::v('username');
     }
     $user = User::getSilent($login);
     if (is_null($user)) {
         Platal::page()->trigError(self::TEXT_INVALID_LOGIN);
         $success = false;
     } else {
         if (S::suid()) {
             $success = S::suid('uid') == $user->id();
         } else {
             $success = $this->checkPassword($login, $user, Post::v('response'));
         }
     }
     if ($success) {
         S::set('auth', AUTH_PASSWD);
         S::kill('challenge');
         S::logger($user->id())->log('auth_ok');
     }
     return $user;
 }
Пример #24
0
    exit;
}
if (isset($_SESSION['oauth_token'])) {
    $token = unserialize($_SESSION['oauth_token']);
    unset($_SESSION['oauth_token']);
} else {
    // Try to get an access token
    try {
        $token = $obj->getAccessToken('authorization_code', array('code' => $_GET['code']));
    } catch (\League\OAuth2\Client\Exception\IDPException $e) {
        throw new Exception($e->getMessage());
    }
}
$user_details = $obj->getUserDetails($token);
$uid = $user_details->uid;
if (Post::has('username')) {
    $username = Post::val('username');
} else {
    $username = $user_details->nickname;
}
// First time logging in
if (!Flyspray::checkForOauthUser($uid, $provider)) {
    if (!$user_details->email) {
        Flyspray::show_error(27);
    }
    $success = false;
    if ($username) {
        $group_in = $fs->prefs['anon_group'];
        $name = $user_details->name ?: $username;
        $success = Backend::create_user($username, null, $name, '', $user_details->email, 0, 0, $group_in, 1, $uid, $provider);
    }
Пример #25
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);
 }
Пример #26
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));
         }
     }
     // }}}
 }
Пример #27
0
    Flyspray::show_error($user->isAnon() ? 102 : 101, false);
} else {
    require_once BASEDIR . '/includes/events.inc.php';
    if ($proj->prefs['use_effort_tracking']) {
        require_once BASEDIR . '/includes/class.effort.php';
        $effort = new effort($task_id, $user->id);
        $effort->populateDetails();
        $page->assign('effort', $effort);
    }
    $page->uses('task_details');
    // Send user variables to the template
    $page->assign('assigned_users', $task_details['assigned_to']);
    $page->assign('old_assigned', implode(' ', $task_details['assigned_to']));
    $page->assign('tags', $task_details['tags']);
    $page->setTitle(sprintf('FS#%d : %s', $task_details['task_id'], $task_details['item_summary']));
    if ((Get::val('edit') || Post::has('item_summary') && !isset($_SESSION['SUCCESS'])) && $user->can_edit_task($task_details)) {
        $result = $db->Query('
			SELECT g.project_id, u.user_id, u.user_name, u.real_name, g.group_id, g.group_name
			FROM {users} u
			JOIN {users_in_groups} uig ON u.user_id = uig.user_id
			JOIN {groups} g ON g.group_id = uig.group_id
			WHERE (g.show_as_assignees = 1 OR g.is_admin = 1)
			AND (g.project_id = 0 OR g.project_id = ?)
			AND u.account_enabled = 1
			ORDER BY g.project_id ASC, g.group_name ASC, u.user_name ASC', $proj->id ? $proj->id : -1);
        // FIXME: -1 is a hack. when $proj->id is 0 the query fails
        $userlist = array();
        $userids = array();
        while ($row = $db->FetchRow($result)) {
            if (!in_array($row['user_id'], $userids)) {
                $userlist[$row['group_id']][] = array(0 => $row['user_id'], 1 => sprintf('%s (%s)', $row['user_name'], $row['real_name']), 2 => $row['project_id'], 3 => $row['group_name']);
Пример #28
0
 function handler_register_ext($page, $hash = null)
 {
     XDB::execute('DELETE FROM  register_pending_xnet
                         WHERE  DATE_SUB(NOW(), INTERVAL 1 MONTH) > date');
     $res = XDB::fetchOneAssoc('SELECT  uid, hruid, email
                                  FROM  register_pending_xnet
                                 WHERE  hash = {?}', $hash);
     if (is_null($hash) || is_null($res)) {
         $page->trigErrorRedirect('Cette adresse n\'existe pas ou n\'existe plus sur le serveur.', '');
     }
     if (Post::has('pwhash') && Post::t('pwhash')) {
         XDB::startTransaction();
         XDB::query('UPDATE  accounts
                        SET  password = {?}, state = \'active\', registration_date = NOW()
                      WHERE  uid = {?} AND state = \'pending\' AND type = \'xnet\'', Post::t('pwhash'), $res['uid']);
         XDB::query('DELETE FROM  register_pending_xnet
                           WHERE  uid = {?}', $res['uid']);
         XDB::commit();
         S::logger($res['uid'])->log('passwd', '');
         // 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.
         Post::kill('wait');
         Platal::session()->startAvailableAuth();
         $page->changeTpl('xnet/register.success.tpl');
         $page->assign('email', $res['email']);
     } else {
         $page->changeTpl('platal/password.tpl');
         $page->assign('xnet', true);
         $page->assign('hruid', $res['hruid']);
         $page->assign('do_auth', 1);
     }
 }
Пример #29
0
    /**
     * @param PageBuilder $pageBuilder
     * @return ContactsPanel
     */
    function CNewMessagePanel(&$pagebuilder)
    {
        $this->Type = Post::val('mtype', 'mes');
        $this->To = '';
        $this->_pagebuilder =& $pagebuilder;
        $this->_proc =& $pagebuilder->_proc;
        $this->From = $this->_getFromEmail();
        $this->_pagebuilder->_top->AddOnResize('ResizeElements(\'all\');');
        if ($this->_proc->account->AllowDhtmlEditor) {
            $editorResize = 'HTMLEditor.Resize(width - 1, height - 2);';
            $editorReplace = 'HTMLEditor.Replace();';
        } else {
            $editorResize = '
						plainEditor.style.height = (height - 1) + "px";
						plainEditor.style.width = (width - 2) + "px";
					';
            $editorReplace = '';
        }
        $this->inputs = '';
        $contacts = null;
        if (Post::has('contacts') && is_array(Post::val('contacts'))) {
            $contactsArray = array_keys(Post::val('contacts'));
            $contacts =& $this->_proc->db->LoadContactsById($contactsArray);
        }
        if (Post::has('groupid')) {
            $group =& $this->_proc->db->SelectGroupById(Post::val('groupid', -1));
            $contacts =& $this->_proc->db->SelectAddressGroupContacts(Post::val('groupid', -1));
        }
        if ($contacts) {
            foreach ($contacts->Instance() as $contact) {
                if (!$contact->Email) {
                    continue;
                }
                $this->To .= $contact->Name ? '"' . $contact->Name . '" <' . $contact->Email . '>, ' : $contact->Email . ',';
            }
            $this->To = trim(trim($this->To), ',');
        }
        if (Post::has('mailto')) {
            $this->To = Post::val('mailto', '');
        }
        if (Get::has('to')) {
            $this->To = (string) trim(Get::val('to', ''));
        }
        $message = null;
        $isHtml = $this->_proc->account->AllowDhtmlEditor;
        $this->attacmentsHtml = '';
        $this->_pagebuilder->AddJSText('
			
var bcc, bcc_mode, bcc_mode_switcher;

var plainCont = null;
var plainEditor = null;
var HTMLEditor = null;
var EditAreaUrl = "edit-area.php";
var prevWidth = 0;
var prevHeight = 0;
var rowIndex = 0;

function ResizeElements(mode) 
{
	var width = GetWidth();
	if (width < 684)
		width = 684;
	width = width - 40;
	var height = Math.ceil(width/3);
	
	if (prevWidth != width && prevHeight != height) {
		prevWidth = width;
		prevHeight = height;
		if (plainCont != null) {
			plainCont.style.height = height + "px";
			plainCont.style.width = width + "px";
			' . $editorResize . '
		}
	}
}

function WriteEmails(str, field)
{
	var mailInput;
	if (field == 2) {
		mailInput = document.getElementById("toCC");
	} else if (field == 3) {
		mailInput = document.getElementById("toBCC");
	} else {
		mailInput = document.getElementById("toemail");
	}
	if (mailInput) {
		mailInput.value = (mailInput.value == "") ? str : mailInput.value + ", " + str;
		mailInput.focus();
	}
}

function LoadAttachmentHandler(attachObj)
{
	var attachtable = document.getElementById("attachmentTable");
	if (attachObj)
	{
		var imageLink = GetFileParams(attachObj.FileName);
		var tr = attachtable.insertRow(rowIndex++);
		tr.id = "tr_" + attachObj.TempName;
		var td = tr.insertCell(0);
		td.className = "wm_attachment";
		var innerHtml = \'<img src="./images/icons/\' + imageLink.image + \'" />\';
		innerHtml += \'<input type="hidden" name="attachments[\' + attachObj.TempName + \']" value="\' + attachObj.FileName + \'">\';
		innerHtml += HtmlEncode(attachObj.FileName) + \' (\' + GetFriendlySize(attachObj.Size) + \') <a href="#" id="\' + attachObj.TempName + \'" onclick="return  DeleteAttach(this.id);">' . JS_LANG_Delete . '</a>\';
		td.innerHTML = innerHtml;
	}
}

function ChangeBCCMode()
{
	if (bcc_mode == "hide") {
		bcc_mode = "show";
		bcc.className = "";
		bcc_mode_switcher.innerHTML = Lang.HideBCC;
	} else {
		bcc_mode = "hide";
		bcc.className = "wm_hide";
		bcc_mode_switcher.innerHTML = Lang.ShowBCC;
	}
	' . $editorReplace . '
	return false;
}

function UpdateIdUid(id, uid)
{
	var idf = document.getElementById("m_id");
	var uidf = document.getElementById("m_uid");
	if (idf && uidf) {
		idf.value = id;
		uidf.value = uid;
	}
}

var Rep_m, Err_m;
var hiddensaveiframe;
var pop3Pr = ' . ($pagebuilder->_proc->account->MailProtocol == MAILPROTOCOL_POP3 ? 'true' : 'false') . ';
function DoSaveButton()
{
	if (pop3Pr)
	{ 
		if (!hiddensaveiframe) {
			hiddensaveiframe = CreateChildWithAttrs(document.body, "iframe", [["name", "hiddensaveiframe"], ["class", "wm_hide"]]);
		}
	}
	
	var form = document.getElementById("messageForm");
	form.action = "' . ACTIONFILE . '?action=save&req=message";
	form.target = (pop3Pr) ? "hiddensaveiframe" : "";

	if (submitSaveMessage()) {
		form.submit();
	}
}

function DoSendButton()
{
	var toemail = document.getElementById("toemail");
	var ccemail = document.getElementById("toCC");
	var bccemail = document.getElementById("toBCC");
	var subject = document.getElementById("subject");
	var mailIsCorrect = false;
	
	if ((toemail && toemail.value.length > 3) || (ccemail && ccemail.value.length > 3) || (bccemail && bccemail.value.length > 3)) { 
		mailIsCorrect = true;
	}
	
	if (mailIsCorrect) {
		if (subject && subject.value.length < 1 && !confirm(Lang.ConfirmEmptySubject)) {
			return false;
		}
		
		var form = document.getElementById("messageForm");
		form.action = "' . ACTIONFILE . '?action=send&req=message";
		form.target = "";
		if (submitSaveMessage()) {
			form.submit();
		}
	} else {
		alert(Lang.WarningToBlank);
	}
}

function DeleteAttach(idline)
{
	var trtable = document.getElementById("tr_" + idline);
	if (trtable)
	{
		trtable.className = "wm_hide";
		CleanNode(trtable);
	}
	return false;
}

function ShowPictures()
{
	var showPictureTable = document.getElementById("showpicturestable");

	if (HTMLEditor) {
		var temp = HTMLEditor.GetText().ReplaceStr("wmx_src", "src");
		temp = temp.ReplaceStr("wmx_background", "background");
		HTMLEditor.SetHtml(temp);
		if (showPictureTable) {
			showPictureTable.className = "wm_hide";
		}
		HTMLEditor.Replace();
	}
}

');
        $this->_pagebuilder->AddInitText('

bcc_mode = "hide";
bcc = document.getElementById("bcc");
bcc_mode_switcher = document.getElementById("bcc_mode_switcher");

plainEditor = document.getElementById("editor_area");
plainCont = document.getElementById("editor_cont");

Rep_m = new CReport("Rep_m");
Rep_m.Build();

Err_m = new CError("Err_m", "' . ConvertUtils::ClearJavaScriptString($this->_pagebuilder->SkinName(), '"') . '");
Err_m.Build();
');
        $m_id = -1;
        $m_uid = '';
        if (Post::has('m_id')) {
            $mes_id = Post::val('m_id');
            $mes_uid = Post::val('m_uid');
            $folder_id = Post::val('f_id');
            $folder_name = Post::val('f_name');
            $folder_name = 'defaultname';
            $mes_charset = Post::val('charset', -1);
            $message = new GetMessageBase($this->_proc->account, $mes_id, $mes_uid, $folder_id, $folder_name, $mes_charset);
            $m_id = (int) $mes_id;
            $m_uid = $mes_uid;
        }
        $this->inputs = '<input type="hidden" id="m_id" name="m_id" value="' . ConvertUtils::AttributeQuote($m_id) . '"><input type="hidden" id="m_uid" name="m_uid" value="' . ConvertUtils::AttributeQuote($m_uid) . '">';
        $withSignature = false;
        switch ($this->_proc->account->SignatureOptions) {
            case SIGNATURE_OPTION_AddToAll:
                $withSignature = true;
                break;
            case SIGNATURE_OPTION_AddToNewOnly:
                $withSignature = $this->Type == 'mes';
                break;
            default:
            case SIGNATURE_OPTION_DontAdd:
                $withSignature = false;
                break;
        }
        if ($message) {
            if ($this->Type != 'forward' && $this->Type != 'reply' && $this->Type != 'replytoall') {
                $withSignature = false;
            }
            $this->_pagebuilder->AddInitText('SetPriority(' . $message->msg->GetPriorityStatus() . ');');
            switch ($this->Type) {
                default:
                    $this->To = $message->PrintTo(true);
                    $this->CC = $message->PrintCC(true);
                    $this->BCC = '';
                    $this->Subject = $message->PrintSubject(true);
                    break;
                case 'forward':
                    $this->To = '';
                    $this->CC = '';
                    $this->BCC = '';
                    $this->Subject = JS_LANG_Fwd . ': ' . $message->PrintSubject(true);
                    break;
                case 'reply':
                    $replyto = trim($message->PrintReplyTo(true));
                    $this->To = strlen($replyto) > 0 ? $replyto : $message->PrintFrom(true);
                    $this->CC = '';
                    $this->BCC = '';
                    $this->Subject = JS_LANG_Re . ': ' . $message->PrintSubject(true);
                    break;
                case 'replytoall':
                    $emailCollection =& $message->msg->GetAllRecipients(false, true);
                    $temp = '';
                    if ($emailCollection) {
                        foreach ($emailCollection->Instance() as $value) {
                            $email =& $value;
                            if ($email->Email != $this->_proc->account->Email) {
                                $temp .= $email->Email . ', ';
                            }
                        }
                    }
                    $this->To = trim(trim($temp), ',');
                    $this->CC = '';
                    $this->BCC = '';
                    $this->Subject = JS_LANG_Re . ': ' . $message->PrintSubject(true);
                    break;
            }
            if ($this->_proc->account->AllowDhtmlEditor) {
                switch ($this->Type) {
                    case 'forward':
                    case 'reply':
                    case 'replytoall':
                        if ($message->account->ViewMode == VIEW_MODE_PREVIEW_PANE_NO_IMG || $message->account->ViewMode == VIEW_MODE_WITHOUT_PREVIEW_PANE_NO_IMG) {
                            $isHtml = true;
                            $this->Body = ConvertUtils::HtmlBodyWithoutImages($message->msg->GetRelpyAsHtml(true));
                            if (isset($GLOBALS[GL_WITHIMG]) && $GLOBALS[GL_WITHIMG]) {
                                $GLOBALS[GL_WITHIMG] = false;
                                $this->isSafety = false;
                            }
                        } else {
                            $isHtml = true;
                            $this->Body = ConvertUtils::HtmlBodyWithoutImages($message->msg->GetRelpyAsHtml(true));
                        }
                        break;
                    default:
                        if ($message->account->ViewMode == VIEW_MODE_PREVIEW_PANE_NO_IMG || $message->account->ViewMode == VIEW_MODE_WITHOUT_PREVIEW_PANE_NO_IMG) {
                            if ($message->msg->HasHtmlText()) {
                                $isHtml = true;
                                $this->Body = ConvertUtils::HtmlBodyWithoutImages($message->msg->GetCensoredHtmlWithImageLinks(true));
                                if (isset($GLOBALS[GL_WITHIMG]) && $GLOBALS[GL_WITHIMG]) {
                                    $GLOBALS[GL_WITHIMG] = false;
                                    $this->isSafety = false;
                                }
                            } elseif ($message->msg->HasPlainText()) {
                                $isHtml = false;
                                $this->Body = $message->msg->GetNotCensoredTextBody(true);
                            }
                        } else {
                            if ($message->msg->HasHtmlText()) {
                                $isHtml = true;
                                $this->Body = $message->msg->GetCensoredHtmlWithImageLinks(true);
                            } elseif ($message->msg->HasPlainText()) {
                                $isHtml = false;
                                $this->Body = $message->msg->GetNotCensoredTextBody(true);
                            }
                        }
                        break;
                }
            } else {
                $isHtml = false;
                switch ($this->Type) {
                    case 'forward':
                    case 'reply':
                    case 'replytoall':
                        $this->Body = $message->msg->GetRelpyAsPlain(true);
                        break;
                    default:
                        $this->Body = $message->msg->GetNotCensoredTextBody(true);
                        break;
                }
            }
            if ($message->HasAttachments() && $this->Type != 'reply' && $this->Type != 'replytoall') {
                $attachments =& $message->msg->Attachments;
                if ($attachments != null && $attachments->Count() > 0) {
                    foreach (array_keys($attachments->Instance()) as $key) {
                        $attachment =& $attachments->Get($key);
                        $tempname = $message->msg->IdMsg . '-' . $key . '_' . $attachment->GetTempName();
                        //$filename = ConvertUtils::ConvertEncoding($attachment->GetFilenameFromMime(), $GLOBALS[MailInputCharset], $message->account->GetUserCharset());
                        $filename = ConvertUtils::WMHtmlSpecialChars($attachment->GetFilenameFromMime());
                        $filesize = GetFriendlySize(strlen($attachment->MimePart->GetBinaryBody()));
                        $fs =& new FileSystem(INI_DIR . '/temp', $message->account->Email, $message->account->Id);
                        $attfolder =& new Folder($message->account->Id, -1, Session::val('attachtempdir', md5(session_id())));
                        $fs->SaveAttach($attachment, $attfolder, $tempname);
                        $this->attacmentsHtml .= '
<tr id="tr_' . ConvertUtils::AttributeQuote($tempname) . '"><td class="wm_attachment"><img src="./images/icons/' . GetAttachImg($filename) . '" />
<input type="hidden" name="attachments[' . ConvertUtils::AttributeQuote($tempname) . ']" value="' . ConvertUtils::AttributeQuote($filename) . '"> ' . $filename . '
 (' . $filesize . ') 						
<a href="#" id="' . ConvertUtils::AttributeQuote($tempname) . '" onClick="return  DeleteAttach(this.id);">' . JS_LANG_Delete . '</a></td></tr>';
                    }
                }
            }
        } else {
            $this->_pagebuilder->AddInitText('SetPriority(3);');
        }
        $signature = '';
        if ($withSignature) {
            if ($this->_proc->account->AllowDhtmlEditor) {
                $signature = $this->_proc->account->SignatureType == 0 ? nl2br($this->_proc->account->Signature) : $this->_proc->account->Signature;
                $signature = $isHtml ? $signature : strip_tags(nl2br($signature));
            } else {
                $signature = $this->_proc->account->SignatureType == 0 ? strip_tags($this->_proc->account->Signature) : strip_tags($this->_proc->account->Signature);
            }
        }
        $this->Body = $signature . $this->Body;
        if ($this->_proc->account->AllowDhtmlEditor) {
            $this->_pagebuilder->AddJSFile('class.html-editor.js');
            $setText = $isHtml ? 'HTMLEditor.SetHtml(mess);' : 'HTMLEditor.SetText(mess);';
            $this->_pagebuilder->AddJSText('
		function submitSaveMessage()
		{
			var hiddenkey = document.getElementById("ishtml");
			
			if (HTMLEditor._htmlMode) {
				plainEditor.value = HTMLEditor.GetText();
				hiddenkey.value = "1";
			} else {
				hiddenkey.value = "0";
			}
			if (bcc_mode == "hide")
			{
				document.getElementById("toBCC").value = "";
			}
			return true;
		}
		
		function EditAreaLoadHandler() { HTMLEditor.LoadEditArea();	}
		function CreateLinkHandler(url) { HTMLEditor.CreateLinkFromWindow(url); }
		function DesignModeOnHandler(rer) {
			HTMLEditor.Show();
			var mess = "' . ConvertUtils::ReBuildStringToJavaScript($this->Body, '"') . '";
			if (mess.length == 0) {
				mess = "<br />";
			}
			' . $setText . '
		}
				');
            $this->_pagebuilder->AddInitText('
		HTMLEditor = new CHtmlEditorField(true);
		HTMLEditor.SetPlainEditor(plainEditor, document.getElementById("mode_switcher"));
		HTMLEditor.Show();');
        } else {
            $this->_pagebuilder->AddJSText('
		function submitSaveMessage()
		{
			var hiddenkey = document.getElementById("ishtml");
			hiddenkey.value = "0";
			if (bcc_mode == "hide") {
				document.getElementById("toBCC").value = "";
			}
			return true;
		}
				');
        }
    }
Пример #30
0
 function val($key, $default = null)
 {
     return Post::has($key) ? $_POST[$key] : $default;
 }