Example #1
0
function get_all_redirects($membres, $mls, $client)
{
    global $globals;
    $tos = array();
    // TODO: add more filters to choose users
    if (!empty($membres)) {
        $uf = new UserFilter(new UFC_Group($globals->asso('id')));
        $tos = $uf->getUsers();
    }
    foreach ($mls as $ml) {
        // $list_members is a (list_details, members, list_owners) array, where
        // members is an array of (0 => name, 1 => email) arrays.
        $list_members = $client->get_members($ml);
        if ($list_members) {
            foreach ($list_members[1] as $mem) {
                $uf = new UserFilter(new UFC_Email($mem[1]));
                $user = $uf->getUser();
                if ($user) {
                    $tos[] = $user;
                } else {
                    $tos[] = $mem[1];
                }
            }
        }
    }
    return $tos;
}
Example #2
0
function weakCheckId($subState)
{
    $uf = new UserFilter(new PFC_And(new PFC_Not(new UFC_Dead()), new UFC_Promo('=', $subState->s('edu_type'), $subState->s('yearpromo')), new PFC_Not(new UFC_Registered(true))));
    if ($it = $uf->iterProfiles()) {
        while ($profile = $it->next()) {
            if ($profile->compareNames($subState->s('firstname'), $subState->s('lastname'))) {
                $subState->set('lastname', $profile->lastName());
                $subState->set('firstname', $profile->firstName());
                $subState->set('uid', $profile->owner()->id());
                $subState->set('watch', $profile->owner()->watch);
                $subState->set('comment', $profile->owner()->comment);
                $subState->set('birthdateRef', $profile->__get('birthdate_ref'));
                $subState->set('xorgid', $profile->__get('xorg_id'));
                return true;
            }
        }
    }
    $uf = new UserFilter(new PFC_And(new PFC_Not(new UFC_Dead()), new UFC_Promo('=', $subState->s('edu_type'), $subState->s('yearpromo')), new UFC_Registered(true)));
    if ($it = $uf->iterProfiles()) {
        while ($profile = $it->next()) {
            if ($profile->compareNames($subState->s('firstname'), $subState->s('lastname'))) {
                $subState->set('uid', $profile->owner()->id());
                $subState->set('watch', $profile->owner()->watch);
                $subState->set('comment', $profile->owner()->comment);
                $subState->set('birthdateRef', $profile->__get('birthdate_ref'));
                $subState->set('xorgid', $profile->__get('xorg_id'));
                return 'Tu es vraisemblablement déjà inscrit !';
            }
        }
    }
    return 'Nous n\'avons pas les mêmes informations (promo, accents…) que toi ! Tu peux vérifier en cherchant ta fiche sur l\'annuaire public, si ça ne fonctionne toujours pas tu peux nous envoyer un email à support@polytechnique.org';
}
Example #3
0
function list_sort_owners($emails, $tri_promo = true)
{
    global $globals;
    // $membres' structure is the following: $sortKey => $key => $listMember
    $membres = array();
    $seen = array();
    $members = array();
    $uf = new UserFilter(new UFC_Email($emails));
    $it = $uf->iterUsers();
    while ($u = $it->next()) {
        $members[$u->uid] = array('user' => $u, 'profile' => null, 'email' => $u->forlifeEmail());
        $seen[] = strtolower($u->forlifeEmail());
    }
    $pf = new ProfileFilter(new UFC_Email($emails));
    $it = $pf->iterProfiles();
    if ($it) {
        while ($p = $it->next()) {
            $members[$p->owner_id]['user']->setPrefetchedProfile($p);
            $members[$p->owner_id]['profile'] = $p;
        }
    }
    foreach ($emails as $email) {
        $email = strtolower($email);
        if (!in_array($email, $seen)) {
            $seen[] = $email;
            $members[$email] = array('user' => null, 'profile' => null, 'email' => $email);
        }
    }
    // $members is now an array of uid => {'user': User or null, 'email': $email}
    // $sorted_members is an array of $sortKey1 => $sortKey2 => {User, email}
    $sorted_members = array();
    foreach ($members as $member) {
        if (is_null($member['user'])) {
            $category = 'AAAAA';
            $name = $member['email'];
        } else {
            $category = $member['user']->category();
            $name = $member['user']->sortName();
        }
        if (empty($category)) {
            $category = "AAAAA";
        }
        $main_sort_key = $tri_promo ? $category : strtoupper($name[0]);
        $alt_sort_key = $name . $member['email'];
        if (!array_key_exists($main_sort_key, $sorted_members)) {
            $sorted_members[$main_sort_key] = array();
        }
        $sorted_members[$main_sort_key][$alt_sort_key] = $member;
    }
    uksort($sorted_members, 'strcasecmp');
    foreach ($sorted_members as &$subsorted_members) {
        uksort($subsorted_members, 'strcasecmp');
    }
    return $sorted_members;
}
 function afterSave($created)
 {
     if ($created) {
         $datas = array();
         $viewer_id = $this->getInsertID();
         $opts['conditions'] = array('Viewer.id' => $viewer_id);
         $datas = $this->find('first', $opts);
         App::import('Model', 'UserFilter');
         $userFilter = new UserFilter();
         $userFilter->updateTable($datas);
         $this->updateAll(array('Viewer.unskipped' => true), array('Viewer.id' => $viewer_id));
     }
 }
Example #5
0
 public function update($id, $data = [])
 {
     try {
         //fetch the entity
         $entity = $this->gateway->findByPk($id);
         if (!$entity) {
             return $this->payload->notFound(['id' => $id]);
         }
         //set data in the entity; do not overwrite existing $id
         unset($data['id']);
         $entity->setData($data);
         // validate the entity
         if (!$this->filter->forUpdate($entity)) {
             return $this->payload->notValid([$this->entityName => $entity, 'messages' => $this->filter->getMessages()]);
         }
         // update the entity
         if (!$this->gateway->update($entity)) {
             return $this->payload->notUpdated([$this->entityName => $entity]);
         }
         //success
         return $this->payload->updated([$this->entityName => $entity]);
     } catch (\Exception $e) {
         return $this->payload->error(['exception' => $e, 'id' => $id, 'data' => $data]);
     }
 }
Example #6
0
 /**
  * @param $page      The page
  * @param $login     The hruid of the user
  * @param $token     The hash_rss for identification
  */
 public function run(FrankizPage $page, $login, $token)
 {
     $uf = new UserFilter(new UFC_Hruid($login));
     $user = $uf->get(true);
     if (!$user) {
         return PL_FORBIDDEN;
     }
     $user->select(UserSelect::feed());
     if ($user->hash_rss() != $token) {
         return PL_FORBIDDEN;
     }
     $page->assign('rss_hash', $token);
     pl_content_headers("application/rss+xml");
     $this->iterator = $this->fetch($user);
     $page->coreTpl('feed.rss2.tpl', NO_SKIN);
     $page->assign_by_ref('feed', $this);
     $page->run();
 }
Example #7
0
 public function run()
 {
     $promos = S::user()->castes()->groups()->filter('ns', Group::NS_PROMO);
     $promos->add(Group::from('on_platal'));
     $uf = new UserFilter(new PFC_And(new UFC_Birthday('=', new FrankizDateTime()), new UFC_Group($promos)));
     $us = $uf->get();
     $us->select(UserSelect::birthday());
     $formations = array();
     $users = array();
     foreach ($us as $u) {
         $study = $u->studies();
         $first = array_shift($study);
         $formations[$first->formation()->abbrev()] = $first->formation();
         $users[$first->formation()->abbrev()][$first->promo()][] = $u;
     }
     $this->assign('formations', $formations);
     $this->assign('users', $users);
 }
Example #8
0
 public static function nextEvent(PlIterator $it, PlUser $user)
 {
     while ($body = $it->next()) {
         $uf = UserFilter::getLegacy($body['promo_min'], $body['promo_max']);
         if ($uf->checkUser($user)) {
             return $body;
         }
     }
     return null;
 }
Example #9
0
 protected function getSortTokens(PlFilter $uf)
 {
     if (UserFilter::isGrade($this->grade)) {
         $sub = $uf->addEducationFilter(true, $this->grade);
         return 'pe' . $sub . '.' . UserFilter::promoYear($this->grade);
     } else {
         $sub = $uf->addDisplayFilter();
         return 'pd' . $sub . '.promo';
     }
 }
Example #10
0
 function handler_chat_avatar($page, $hruid)
 {
     global $globals;
     $filter = new UFC_Hruid($hruid);
     $uf = new UserFilter($filter);
     $user = $uf->get(true);
     //add boolean
     if (!$user) {
         header($_SERVER['SERVER_PROTOCOL'] . '404 Not Found');
         $image = new StaticImage($globals->images->man);
         // for some reason mime isn't picked up: for valid images mime == null is enough to be displayed correctly
         // for $globals->images->man neither 1 nor null does the trick
     } else {
         $user->select(UserSelect::login());
         $image = $user->image();
     }
     $image->send("micro");
     exit;
 }
Example #11
0
 public function next()
 {
     while ($n = $this->it->next()) {
         $uf = UserFilter::getLegacy($n['promo_min'], $n['promo_max']);
         if ($uf->checkUser($this->user)) {
             return $n;
         }
     }
     return null;
 }
Example #12
0
 function handler_bulkmail(PlPage $page, PlUser $authUser, $payload)
 {
     require_once 'partnersharing.inc.php';
     $partner = PartnerSharing::fetchByAPIUser($authUser);
     if ($partner == null || !$partner->has_bulkmail) {
         return PL_FORBIDDEN;
     }
     if (!isset($payload['uids'])) {
         $page->trigError('Malformed query.');
         return PL_BAD_REQUEST;
     }
     $uids = $payload['uids'];
     $pf = new UserFilter(new PFC_And(new UFC_PartnerSharingID($partner->id, $uids), new UFC_HasValidEmail(), new UFC_PartnerSharingEmail($partner->id)));
     $contexts = array();
     foreach ($pf->iterUsers() as $user) {
         $contexts[] = array('name' => $user->fullName(), 'email' => $user->bestEmail(), 'gender' => $user->isFemale() ? 'woman' : 'man');
     }
     $page->jsonAssign('contexts', $contexts);
     return PL_JSON;
 }
Example #13
0
function test_userfilters($grouptext, $rights, $db_caste, $expected_condition = null)
{
    $castetext = $rights . " userfilter (caste " . $db_caste->id() . ")";
    $db_userfilter = $db_caste->userfilter();
    if (is_null($expected_condition)) {
        if ($db_userfilter) {
            echo "Info: group " . $grouptext . " has unexpected " . $castetext . " " . json_encode($db_userfilter->export()) . "\n";
        }
    } else {
        $expected_userfilter = new UserFilter($expected_condition);
        $expected_json = json_encode($expected_userfilter->export());
        if (!$db_userfilter) {
            echo "Error: group " . $grouptext . " does not have a " . $castetext . ", " . "expected was " . $expected_json . "\n";
        } else {
            $db_json = json_encode($db_userfilter->export());
            if ($db_json != $expected_json) {
                echo "Error: group " . $grouptext . " has invalid " . $castetext . "\n" . "    Expected: " . $expected_json . "\n" . "    Database: " . $db_json . "\n";
            }
        }
    }
}
Example #14
0
 public function run()
 {
     // Total Users
     $f = new UserFilter(null);
     $users = $f->getTotalCount();
     $this->assign('users', $users);
     // Total Groups
     $f = new GroupFilter(null);
     $groups = $f->getTotalCount();
     $this->assign('groups', $groups);
     // Total Castes
     $f = new CasteFilter(null);
     $castes = $f->getTotalCount();
     $this->assign('castes', $castes);
     // Total News
     $f = new NewsFilter(null);
     $news = $f->getTotalCount();
     $this->assign('news', $news);
     // Total Images
     $f = new ImageFilter(null);
     $images = $f->getTotalCount();
     $this->assign('images', $images);
     $this->assign('user', S::user());
 }
 public function testGetsAllUsers()
 {
     $userId = 123232;
     $userItemView = new UserItemView();
     $userItemView->Id = $userId;
     $userItemView->DateCreated = Date::Now();
     $userItemView->LastLogin = Date::Now();
     $userList = array($userItemView);
     $users = new PageableData($userList);
     $attributes = array(new FakeCustomAttribute(1), new FakeCustomAttribute(2));
     $username = '******';
     $position = 'position';
     $att1 = 'att1';
     $this->server->SetQueryString(WebServiceQueryStringKeys::USERNAME, $username);
     $this->server->SetQueryString(WebServiceQueryStringKeys::POSITION, $position);
     $this->server->SetQueryString('att1', $att1);
     $expectedFilter = new UserFilter($username, null, null, null, null, null, $position, array(new Attribute($attributes[0], $att1)));
     $this->userRepositoryFactory->expects($this->once())->method('Create')->with($this->equalTo($this->server->GetSession()))->will($this->returnValue($this->userRepository));
     $this->userRepository->expects($this->once())->method('GetList')->with($this->isNull(), $this->isNull(), $this->isNull(), $this->isNull(), $expectedFilter->GetFilter(), AccountStatus::ACTIVE)->will($this->returnValue($users));
     $this->attributeService->expects($this->once())->method('GetByCategory')->with($this->equalTo(CustomAttributeCategory::USER))->will($this->returnValue($attributes));
     $expectedResponse = new UsersResponse($this->server, $userList, array(1 => 'fakeCustomAttribute1', 2 => 'fakeCustomAttribute2'));
     $this->service->GetUsers();
     $this->assertEquals($expectedResponse, $this->server->_LastResponse);
 }
Example #16
0
function get_event_participants(&$evt, $item_id, array $tri = array(), $limit = null, $offset = 0)
{
    global $globals;
    $eid = $evt['eid'];
    $money = $evt['money'] && function_exists('may_update') && may_update();
    $pay_id = $evt['paiement_id'];
    $append = $item_id ? XDB::format(' AND ep.item_id = {?}', $item_id) : '';
    $query = XDB::fetchAllAssoc('uid', 'SELECT  ep.uid, SUM(ep.paid) AS paid, SUM(ep.nb) AS nb,
                                                FIND_IN_SET(\'notify_payment\', ep.flags) AS notify_payment
                                          FROM  group_event_participants AS ep
                                         WHERE  ep.eid = {?} AND nb > 0 ' . $append . '
                                      GROUP BY  ep.uid', $eid);
    $uf = new UserFilter(new PFC_True(), $tri);
    $users = User::getBulkUsersWithUIDs($uf->filter(array_keys($query), new PlLimit($limit, $offset)));
    $tab = array();
    foreach ($users as $user) {
        $uid = $user->id();
        $tab[$uid] = $query[$uid];
        $tab[$uid]['user'] = $user;
    }
    if ($item_id) {
        return $tab;
    }
    $evt['adminpaid'] = 0;
    $evt['telepaid'] = 0;
    $evt['topay'] = 0;
    $evt['paid'] = 0;
    foreach ($tab as $uid => &$u) {
        $u['adminpaid'] = (double) $u['paid'];
        $u['montant'] = 0;
        if ($money && $pay_id) {
            $montant = XDB::fetchOneCell('SELECT  SUM(amount)
                                            FROM  payment_transactions AS t
                                           WHERE  status = "confirmed" AND ref = {?} AND uid = {?}', $pay_id, $uid);
            $u['paid'] += $montant;
        }
        $u['telepayment'] = $u['paid'] - $u['adminpaid'];
        $res_ = XDB::iterator('SELECT  ep.nb, ep.item_id, ei.montant
                                 FROM  group_event_participants AS ep
                           INNER JOIN  group_event_items AS ei ON (ei.eid = ep.eid AND ei.item_id = ep.item_id)
                                WHERE  ep.eid = {?} AND ep.uid = {?}', $eid, $uid);
        while ($i = $res_->next()) {
            $u[$i['item_id']] = $i['nb'];
            $u['montant'] += $i['montant'] * $i['nb'];
        }
        $evt['telepaid'] += $u['telepayment'];
        $evt['adminpaid'] += $u['adminpaid'];
        $evt['paid'] += $u['paid'];
        $evt['topay'] += $u['montant'];
    }
    return $tab;
}
Example #17
0
$res = XDB::query('SELECT  id, target, writer, writername, title, body, ishtml
                     FROM  mails
                    WHERE  processed IS NULL')->fetchAllRow();
$ids = array();
if (count($res) == 0) {
    exit;
}
foreach ($res as $r) {
    $ids[] = $r[0];
}
XDB::execute('UPDATE  mails
                 SET  processed = NOW()
               WHERE  id IN {?}', $ids);
XDB::commit();
foreach ($res as $r) {
    $uf = new UserFilter($r[1]);
    $users = $uf->get();
    $users->select(UserSelect::base());
    foreach ($users as $user) {
        $mail = new FrankizMailer();
        $mail->addAddress($user->bestEmail(), $user->fullName());
        $mail->SetFrom($r[2], $r[3]);
        $mail->subject($r[4]);
        $mail->body($r[5]);
        $mail->send($r[6]);
    }
    XDB::execute('UPDATE  mails
                     SET  done = NOW()
                   WHERE  id = {?}', $r[0]);
}
// vim:set et sw=4 sts=4 sws=4 foldmethod=marker enc=utf-8:
Example #18
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);
 }
Example #19
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');
 }
Example #20
0
    return $str;
}
function conv_name($str)
{
    $str = str_replace(array('É'), 'e', $str);
    $str = strtolower(conv($str));
    $str = str_replace(array('é', 'è', 'ë', 'ê'), 'e', $str);
    $str = str_replace(array('à', 'ä', 'â'), 'a', $str);
    $str = str_replace(array('î', 'ï'), 'i', $str);
    $str = str_replace(array('ç'), 'c', $str);
    return preg_replace("/[^a-z0-9_-]/", "", $str);
}
$gf = new GroupFilter(new GFC_Name('tol'));
$group = $gf->get(true)->select(GroupSelect::castes());
$tol_caste = $group->caste(Rights::everybody());
$uf = new UserFilter(new PFC_And(new UFC_Study(new Formation(1)), new UFC_Promo(2010)));
$us = $uf->get()->select(UserSelect::tol());
$nf = new GroupFilter(new GFC_Name('sport_judo'));
$n = $nf->get(true);
$n->select(GroupSelect::castes());
/*
XDB::execute('DELETE FROM users_minimodules WHERE uid = 0 AND col = "COL_FLOAT"');
XDB::execute('INSERT INTO users_minimodules (uid,name,col,row) VALUES
                          (0, "activate_account",  "COL_FLOAT",  0 )');
XDB::execute('INSERT INTO users_minimodules (uid,name,col,row) VALUES
                          (0, "quicksearch",       "COL_FLOAT",  1 )');
XDB::execute('INSERT INTO users_minimodules (uid,name,col,row) VALUES
                          (0, "links",             "COL_FLOAT",  2 )');
*/
$users = $us->count();
$k = 0;
Example #21
0
 function handler_tol_ajax_sheet($page, $uid)
 {
     $f = new UserFilter(new UFC_Uid($uid));
     $u = $f->get(true);
     if ($u) {
         $u->select(UserSelect::tol());
     }
     $page->assign('user', S::user());
     $page->assign('result', $u);
     try {
         $sheet = $page->filteredFetch(FrankizPage::getTplPath('tol/sheet.tpl'));
     } catch (Exception $e) {
         $sheet = "La fiche de l'utilisateur comporte des erreurs";
         XDB::execute('INSERT INTO tol_errors SET error = {?}', $u->id());
     }
     $page->jsonAssign('sheet', $sheet);
     $page->jsonAssign('success', true);
     return PL_JSON;
 }
Example #22
0
 function buildCourseset($course, $grouped)
 {
     $db = DBManager::get();
     $cs = new CourseSet();
     $rule = new ParticipantRestrictedAdmission();
     // Loszeitpunkt übernehmen.
     $rule->setDistributionTime($course['admission_type'] == 1 ? $course['admission_endtime'] : 0);
     $cs->addAdmissionRule($rule);
     // Beschränkung 1 aus n, falls erforderlich
     if ($grouped) {
         $rule = new LimitedAdmission();
         $rule->setMaxNumber(1);
         $cs->addAdmissionRule($rule);
     }
     // Falls Anmeldezeitraum eingestellt, diesen übernehmen.
     if ($course['admission_starttime'] != -1 || $course['admission_endtime_sem'] != -1) {
         $rule = new TimedAdmission();
         if ($course['admission_starttime'] != -1) {
             $rule->setStartTime($course['admission_starttime']);
         }
         if ($course['admission_endtime_sem'] != -1) {
             $rule->setEndTime($course['admission_endtime_sem']);
         }
         $cs->addAdmissionRule($rule);
     }
     // Studiengänge eintragen
     $stmt = $db->prepare('SELECT studiengang_id FROM admission_seminar_studiengang WHERE seminar_id = ?');
     $stmt->execute(array($course['seminar_id']));
     $subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
     if (!in_array('all', $subjects) && $subjects) {
         $rule = new ConditionalAdmission();
         foreach ($subjects as $subject) {
             $condition = new UserFilter();
             $subject_field = new SubjectCondition();
             $subject_field->setCompareOperator('=');
             $subject_field->setValue($subject);
             $condition->addField($subject_field);
             $rule->addCondition($condition);
         }
         $cs->addAdmissionRule($rule);
     }
     return $cs;
 }
Example #23
0
 function getEmails($aliases)
 {
     if (!is_array($aliases)) {
         return null;
     }
     $uf = new UserFilter(new UFC_Hrpid($aliases));
     $users = $uf->iterUsers();
     $ret = array();
     while ($user = $users->next()) {
         $ret[] = $user->forlife;
     }
     return join(', ', $ret);
 }
 /**
  * Declares an association between this object and a UserFilter object.
  *
  * @param      UserFilter $v
  * @return     UserFilterMissionTypes The current object (for fluent API support)
  * @throws     PropelException
  */
 public function setUserFilter(UserFilter $v = null)
 {
     if ($v === null) {
         $this->setUserFilterId(NULL);
     } else {
         $this->setUserFilterId($v->getId());
     }
     $this->aUserFilter = $v;
     // Add binding for other direction of this n:n relationship.
     // If this object has already been added to the UserFilter object, it will not be re-added.
     if ($v !== null) {
         $v->addUserFilterMissionTypes($this);
     }
     return $this;
 }
Example #25
0
 function handler_week($page, $sorting = 'per_promo')
 {
     $page->changeTpl('marketing/this_week.tpl');
     $sort = $sorting == 'per_promo' ? new UFO_Promo() : new UFO_Registration();
     $uf = new UserFilter(new UFC_Registered(false, '>', strtotime('1 week ago')), $sort);
     $page->assign('users', $uf->getUsers());
 }
 /**
  * Helper function for storing data to DB.
  */
 public function store()
 {
     // Store rule data.
     $stmt = DBManager::get()->prepare("INSERT INTO `conditionaladmissions`\n            (`rule_id`, `message`, `start_time`, `end_time`, `mkdate`, `chdate`)\n            VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE\n            `message`=VALUES(`message`),\n            `start_time`=VALUES(`start_time`),\n            `end_time`=VALUES(`end_time`),\n            `chdate`=VALUES(`chdate`)");
     $stmt->execute(array($this->id, $this->message, (int) $this->startTime, (int) $this->endTime, time(), time()));
     // Delete removed conditions from DB.
     $stmt = DBManager::get()->prepare("SELECT `filter_id` FROM\n            `admission_condition` WHERE `rule_id`=? AND `filter_id` NOT IN ('" . implode("', '", array_keys($this->conditions)) . "')");
     $stmt->execute(array($this->id));
     foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $entry) {
         $current = new UserFilter($entry['filter_id']);
         $current->delete();
     }
     DBManager::get()->exec("DELETE FROM `admission_condition`\n            WHERE `rule_id`='" . $this->id . "' AND `filter_id` NOT IN ('" . implode("', '", array_keys($this->conditions)) . "')");
     // Store all conditions.
     $queries = array();
     $parameters = array();
     foreach ($this->conditions as $condition) {
         // Store each condition...
         $condition->store();
         $queries[] = "(?, ?, ?)";
         $parameters[] = $this->id;
         $parameters[] = $condition->getId();
         $parameters[] = time();
     }
     // Store all assignments between rule and condition.
     $stmt = DBManager::get()->prepare("INSERT INTO `admission_condition`\n            (`rule_id`, `filter_id`, `mkdate`)\n            VALUES " . implode(",", $queries) . " ON DUPLICATE KEY UPDATE\n            `filter_id`=VALUES(`filter_id`)");
     $stmt->execute($parameters);
     return $this;
 }
Example #27
0
 public function iterToNotify()
 {
     if ($this->data['notify_all']) {
         $condition = UFC_Group::BOTH;
     } else {
         $condition = UFC_Group::NOTIFIED;
     }
     $uf = new UserFilter(new UFC_Group($this->id, true, $condition));
     return $uf->iterUsers();
 }
Example #28
0
 /** Sent this issue to all valid recipients
  * @return Number of issues sent
  */
 public function sendToAll()
 {
     $this->fetchArticles();
     XDB::execute('UPDATE  newsletter_issues
                      SET  state = \'sent\', date=CURDATE()
                    WHERE  id = {?}', $this->id);
     // Every minute, select BATCH_SIZE users who:
     // * are subscribed to the newsletter
     // * have not yet been mailed this issue of the newsletter
     // * have a valid email address
     // ... and send them the current issue.
     // Once a mail is sent, newsletter_ins is updated to prevent selecting again the same user a minute later.
     $ufc = new PFC_And($this->getRecipientsUFC(), new UFC_NLSubscribed($this->nl->id, $this->id), new UFC_HasValidEmail());
     $uf = new UserFilter($ufc, array(new UFO_IsAdmin(true), new UFO_Uid()));
     $limit = new PlLimit(self::BATCH_SIZE);
     $global_sent = array();
     while (true) {
         $sent = array();
         $users = $uf->getUsers($limit);
         if (count($users) == 0) {
             break;
         }
         foreach ($users as $user) {
             if (array_key_exists($user->id(), $global_sent)) {
                 // Such a condition may happen if an user:
                 // 1. was mailed the issue,
                 // 2. unsubscribed the newsletter,
                 // 3. subscribed again before the sending was done.
                 // Such a case is reported by mail to people who monitor the website.
                 // If you are reading this comment because of such a mail and the lines above explain what happened,
                 // you only need to reset the state of the issue to "pending".
                 // A cron script will then restart the mailing from where it stopped and only the problematic user will reveive the issue twice.
                 Platal::page()->kill('Sending the same newsletter issue ' . $this->id . ' to user ' . $user->id() . ' twice, something must be wrong.');
             }
             $sent[] = $user->id();
             $global_sent[$user->id()] = true;
             $this->sendTo($user, $hash);
         }
         XDB::execute("UPDATE  newsletter_ins\n                             SET  last = {?}\n                           WHERE  nlid = {?} AND uid IN {?}", $this->id, $this->nl->id, $sent);
         sleep(60);
     }
     return count($global_sent);
 }
Example #29
0
 *  http://br.binets.fr/                                                   *
 *                                                                         *
 *  This program is free software; you can redistribute it and/or modify   *
 *  it under the terms of the GNU General Public License as published by   *
 *  the Free Software Foundation; either version 2 of the License, or      *
 *  (at your option) any later version.                                    *
 *                                                                         *
 *  This program is distributed in the hope that it will be useful,        *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *  GNU General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program; if not, write to the Free Software            *
 *  Foundation, Inc.,                                                      *
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
 ***************************************************************************/
/**
/**
* Force a skin to every user in groupe on_platal
*/
require_once dirname(__FILE__) . '/../connect.db.inc.php';
// Get all users
$userfilter = new UserFilter(new UFC_Group(Group::from('on_platal')));
$users = $userfilter->get();
$users->select(UserSelect::base());
$skin = empty($argv[1]) ? 'default' : $argv[1];
foreach ($users as $u) {
    echo 'Forcing skin to ' . $u->login() . PHP_EOL;
    $u->skin($skin);
}
Example #30
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();
     }
 }