예제 #1
0
 public static function getCurrentUser()
 {
     if (self::checkIfAuthenticated()) {
         $query = new UserQuery();
         $user = $query->findPk($_SESSION[self::$SESSION_USER_ID]);
         return $user;
     } else {
         return null;
     }
 }
예제 #2
0
파일: User.php 프로젝트: dapepe/tymio
 /**
  * Returns a subordinate user by ID.
  *
  * @param string|int $userId The subordinate user's ID or full login name.
  * @param PropelPDO $con Optional. The database connection to use.
  *     Default is NULL.
  * @throws Exception
  * @return User
  */
 public function getSubordinate($userId, PropelPDO $con = null)
 {
     $query = new UserQuery();
     $user = is_numeric($userId) ? $query->findOneById($userId, $con) : $query->findOneByFQN($userId, $con);
     if ($user === null) {
         throw new Exception('Invalid user ID ' . $userId . '.');
     }
     $thisAccountId = (string) $this->getAccountId();
     if ($thisAccountId === '' or (string) $user->getAccountId() !== $thisAccountId or !$this->isAdmin() and (string) $user->getDomainId() !== (string) $this->getManagerOf()) {
         throw new Exception('The selected user #' . $userId . ' (account #' . $user->getAccountId() . ') is not assigned to user "' . $this->getFQN($con) . '" (account #' . $thisAccountId . ').');
     }
     return $user;
 }
예제 #3
0
 /**
  * Returns a new UserQuery object.
  *
  * @param     string $modelAlias The alias of a model in the query
  * @param     UserQuery|Criteria $criteria Optional Criteria to build the query from
  *
  * @return UserQuery
  */
 public static function create($modelAlias = null, $criteria = null)
 {
     if ($criteria instanceof UserQuery) {
         return $criteria;
     }
     $query = new UserQuery();
     if (null !== $modelAlias) {
         $query->setModelAlias($modelAlias);
     }
     if ($criteria instanceof Criteria) {
         $query->mergeWith($criteria);
     }
     return $query;
 }
예제 #4
0
 protected function setUser($reddit_id, $name)
 {
     $query = new UserQuery();
     $users = $query->findByRedditID($reddit_id);
     $user = null;
     if ($users->count() == 0) {
         $user = new User();
         $user->setUsername($name);
         $user->setRedditID($reddit_id);
         $user->save();
     } else {
         $user = $users->getFirst();
     }
     $_SESSION[Auth::$SESSION_USER_ID] = $user->getId();
 }
예제 #5
0
 public static function getUser()
 {
     if (isset($_SESSION['user']) && $_SESSION['user'] != '' && ($user = UserQuery::create()->findOneByUUID($_SESSION['user']))) {
         return $user;
     }
     return null;
 }
예제 #6
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->output = $output;
     $project_service = $this->getProjectService();
     if ($user_name = $input->getOption('user-name')) {
         if (!($user = UserQuery::create()->findOneByUsername($user_name))) {
             $this->logError('Пользователь с именем ' . $user_name . ' не найден');
             die;
         } else {
             $project_list = $project_service->getProjectList($user, true, false, true);
         }
     } else {
         $project_list = $project_service->getProjectsAll(true, false, true);
     }
     if (count($project_list)) {
         foreach ($project_list as $project) {
             /** @var Project $project */
             $this->log($project->getTitle());
             $project_bad_links = $project->getLinks(true, true);
             //TODO: далее собираем плохие ссылки в одну кучу и отправляем письмо
             if (count($project_bad_links)) {
             }
         }
     } else {
         $this->log('со всеми проектами всё ок');
     }
 }
예제 #7
0
 function getQuery($user)
 {
     global $app;
     $sort = $app->request()->params('sort', '');
     $query = UserQuery::create()->leftJoin('User.Chart')->withColumn('COUNT(Chart.Id)', 'NbCharts')->groupBy('User.Id')->filterByDeleted(false);
     $q = $app->request()->params('q');
     if ($q) {
         $query->where('email LIKE "%' . $q . '%" OR name LIKE "%' . $q . '%"');
     }
     if (!$user->isSysAdmin()) {
         $query->filterByRole('sysadmin', Criteria::NOT_EQUAL);
     }
     switch ($sort) {
         case 'name':
             $query->orderByName('asc');
             break;
         case 'email':
             $query->orderByEmail('asc');
             break;
         case 'charts':
             $query->orderBy('NbCharts', 'desc');
             break;
         case 'created_at':
             $query->orderBy('createdAt', 'desc');
             break;
     }
     return $query;
 }
예제 #8
0
 /**
  * Authenticates this user and signs them in, if the API key or session is valid
  * 
  * Overridden because currently sfAltumoPlugin's version is specific to ApiUser.
  * @todo that behavior needs to be changed and updated on applications that rely on it.
  * 
  * @param sfActions $action
  * @return void
  * @throws Exception if validation fails.
  */
 public function authenticate()
 {
     //require SSL, if applicable
     $this->assertSslApiRequest();
     //authenticate via the API key, if provided
     $api_key = $this->getHttpRequestHeader('Authorization', null);
     if (!is_null($api_key)) {
         if (preg_match('/\\s*Basic\\s+(.*?)\\s*$/im', $api_key, $regs)) {
             $api_key = $regs[1];
             $user = \UserQuery::create()->filterByActive(true)->filterByApiKey($api_key)->findOne();
             if (!$user) {
                 throw new \Exception('Unknown or inactive user.');
             }
             $sf_guard_user = $user->getsfGuardUser();
             if ($sf_guard_user->getIsActive()) {
                 \sfContext::getInstance()->getUser()->signIn($sf_guard_user, false);
                 return;
             } else {
                 throw new \Exception('Unknown or inactive user.');
             }
         } else {
             throw new \Exception('API key format not recognized');
         }
     }
     //try to authenticate via the session, if the api key was not provided
     if (is_null($api_key)) {
         $sf_user = sfContext::getInstance()->getUser();
         if (!$sf_user || !$sf_user->isAuthenticated()) {
             throw new \Exception('Your session is not valid for API usage.');
         }
     } else {
         throw new \Exception('Please provide either a valid session or valid API key.');
     }
 }
예제 #9
0
 static function getInstance()
 {
     if (!self::$instance) {
         self::$instance = new GameQuery();
     }
     return self::$instance;
 }
예제 #10
0
 public function executeDelete(sfWebRequest $request)
 {
     $request->checkCSRFProtection();
     $User = UserQuery::create()->findPk($request->getParameter('id'));
     $this->forward404Unless($User, sprintf('Object User does not exist (%s).', $request->getParameter('id')));
     $User->delete();
     $this->redirect('user/index');
 }
예제 #11
0
 public function emailExists()
 {
     $user = UserQuery::create()->findOneByEmail($this->getEmail());
     if ($user) {
         return true;
     }
     return false;
 }
예제 #12
0
 protected function getNewEntityForm()
 {
     $form = new Curry_Form(array('action' => url('', $_GET), 'method' => 'post', 'elements' => array('path' => array('filebrowser', array('label' => 'File/Folder path', 'required' => true, 'description' => 'If you want to specify a folder, type the public path without a trailing slash (e.g. images/site).', 'filebrowserOptions' => array('local' => false))), 'owner_id' => array('select', array('label' => 'Owner', 'multiOptions' => UserQuery::create()->find()->toKeyValue('UserId', 'Name'), 'value' => User::getUser()->getUserRoleId(), 'required' => true)), 'oread' => array('checkbox', array('label' => 'Read', 'value' => true)), 'owrite' => array('checkbox', array('label' => 'Write', 'value' => true)), 'rread' => array('checkbox', array('label' => 'Read', 'value' => true)), 'rwrite' => array('checkbox', array('label' => 'Write', 'value' => true)), 'wread' => array('checkbox', array('label' => 'Read', 'value' => true)), 'wwrite' => array('checkbox', array('label' => 'Write', 'value' => true)))));
     $form->addDisplayGroup(array('oread', 'owrite'), 'grpOwner', array('legend' => 'Owner permissions', 'class' => 'advanced'));
     $form->addDisplayGroup(array('rread', 'rwrite'), 'grpRole', array('legend' => 'Role permissions', 'class' => 'advanced'));
     $form->addDisplayGroup(array('wread', 'wwrite'), 'grpWorld', array('legend' => 'World permissions', 'class' => 'advanced'));
     $form->addElement('submit', 'save', array('label' => 'Save'));
     return $form;
 }
예제 #13
0
 /**
  * Determines whether the provided $email_address is available to be used. 
  * This is a case-insensitive match.
  * 
  * @param string $email_address
  * @throws \Exception                    //if email address format is invalid
  * @return boolean
  */
 public static function testAvailableEmailAddress($email_address, $exception_message = null)
 {
     $email_address = \Altumo\Validation\Emails::assertEmailAddress($email_address, $exception_message);
     $email_address = strtolower($email_address);
     $count = UserQuery::create()->usesfGuardUserQuery()->filterByUsername($email_address)->endUse()->count();
     if ($count === 0) {
         return true;
     } else {
         return false;
     }
 }
예제 #14
0
 public function dashboard($app, $page)
 {
     // returns a CSV from a MySQL resultset
     function res2csv($rs)
     {
         $csv = "";
         $keys = array();
         $results = array();
         foreach ($rs as $r) {
             if (count($keys) == 0) {
                 foreach ($r as $key => $val) {
                     if (is_string($key)) {
                         $keys[] = $key;
                     }
                 }
                 $csv = implode(";", $keys) . "\\n";
             }
             $results[] = $r;
         }
         $results = array_reverse($results);
         foreach ($results as $r) {
             $values = array();
             foreach ($keys as $key) {
                 $values[] = $r[$key];
             }
             $csv .= implode(";", $values) . "\\n";
         }
         return $csv;
     }
     $con = Propel::getConnection();
     $data = array();
     $publised_sql = 'SELECT DATE_FORMAT(published_at, \'%Y-%m-%d\') pub_date, COUNT(*) pub_count FROM `chart` WHERE last_edit_step = 5 GROUP BY pub_date ORDER BY `pub_date` DESC LIMIT 1,90';
     $publised_week_sql = 'SELECT DATE_FORMAT(published_at, \'%Y-w%u\') pub_date, COUNT(*) pub_count FROM `chart` WHERE last_edit_step = 5 GROUP BY pub_date ORDER BY `pub_date` DESC LIMIT 1,26';
     $user_signups_sql = 'SELECT DATE_FORMAT(created_at, \'%Y-%m-%d\') create_date, COUNT(*) user_count FROM `user` GROUP BY create_date ORDER BY `create_date` DESC LIMIT 1,90';
     $numUsers = UserQuery::create()->filterByDeleted(false)->count();
     $numUsersPending = UserQuery::create()->filterByDeleted(false)->filterByRole(UserPeer::ROLE_PENDING)->count();
     $numUsersActivated = UserQuery::create()->filterByDeleted(false)->filterByRole(UserPeer::ROLE_EDITOR)->count();
     $numUsersDeleted = UserQuery::create()->filterByDeleted(true)->count();
     $users_csv = "Type;Count\\nPending;{$numUsersPending}\\nActivated;{$numUsersActivated}\\nDeleted;{$numUsersDeleted}";
     $numCharts = ChartQuery::create()->filterByDeleted(false)->count();
     $numChartsUpload = ChartQuery::create()->filterByLastEditStep(array('max' => 1))->filterByDeleted(false)->count();
     $numChartsDescribe = ChartQuery::create()->filterByLastEditStep(2)->filterByDeleted(false)->count();
     $numChartsVisualize = ChartQuery::create()->filterByLastEditStep(3)->filterByDeleted(false)->count();
     $numChartsPublished = ChartQuery::create()->filterByLastEditStep(array('min' => 4))->filterByDeleted(false)->count();
     $charts_csv = "LastEditStep;Count\\nUpload;{$numChartsUpload}\\nDescribe;{$numChartsDescribe}\\nVisualize;{$numChartsVisualize}\\nPublish;{$numChartsPublished}\\n";
     $charts_by_type_csv = res2csv($con->query('SELECT type, COUNT(*) FROM chart WHERE deleted = 0 GROUP BY type;'));
     $charts_by_type_csv = str_replace('-chart', '', $charts_by_type_csv);
     $page = array_merge($page, array('num_users' => $numUsers, 'num_users_activated' => $numUsersActivated, 'num_charts' => $numCharts, 'num_charts_published' => $numChartsPublished, 'published_csv' => res2csv($con->query($publised_sql)), 'published_week_csv' => res2csv($con->query($publised_week_sql)), 'users_csv' => $users_csv, 'charts_edit_step_csv' => $charts_csv, 'charts_by_type_csv' => $charts_by_type_csv, 'created_csv' => res2csv($con->query('SELECT DATE_FORMAT(created_at, \'%Y-%m-%d\') pub_date, COUNT(*) pub_count FROM `chart` GROUP BY pub_date ORDER BY `pub_date` DESC LIMIT 1,90')), 'created_weekly_csv' => res2csv($con->query('SELECT DATE_FORMAT(created_at, \'%Y-w%u\') pub_date, COUNT(*) pub_count FROM `chart` GROUP BY pub_date ORDER BY `pub_date` DESC LIMIT 1,26')), 'user_signups_csv' => res2csv($con->query($user_signups_sql)), 'linechart' => DatawrapperVisualization::get('line-chart'), 'columnchart' => DatawrapperVisualization::get('column-chart'), 'donutchart' => DatawrapperVisualization::get('donut-chart'), 'chartLocale' => 'en-US'));
     $app->render('plugins/admin-dashboard/admin-dashboard.twig', $page);
 }
예제 #15
0
 public function index()
 {
     $user = UserQuery::create();
     $this->usuarios = $user->find();
     // Initialize Propel with the runtime configuration
     Session::set('myDbName', 'dokeos_0001');
     Propel::init(APP_PATH . 'config/propel/dokeos-conf.php');
     $foro = ForumForumQuery::create();
     $this->foros = $foro->find();
     Session::set('myDbName', 'dokeos_main');
     Propel::init(APP_PATH . 'config/propel/dokeos-conf.php');
     $user = UserQuery::create();
     $this->usuarios2 = $user->find();
 }
예제 #16
0
function _checkInviteTokenAndExec($token, $func)
{
    if (!empty($token)) {
        $user = UserQuery::create()->findOneByActivateToken($token);
        if ($user && $user->getRole() != 'pending') {
            $func($user);
        } else {
            // this is not a valid token!
            $page['alert'] = array('type' => 'error', 'message' => __('The invitation token is invalid.'));
            global $app;
            $app->redirect('/');
        }
    }
}
예제 #17
0
 public function resetRequest($sUserNameOrPassword, $bForce)
 {
     if ($sUserNameOrPassword === '') {
         throw new LocalizedException('flash.login.username_or_email_required');
     }
     $oUser = UserQuery::create()->filterByUsername($sUserNameOrPassword)->findOne();
     $bShowUserName = false;
     if ($oUser === null) {
         $oUser = UserQuery::create()->filterByEmail($sUserNameOrPassword)->findOne();
         $bShowUserName = true;
     }
     if ($oUser) {
         LoginManager::sendResetMail($oUser, $bShowUserName, null, $bForce);
     }
 }
예제 #18
0
 protected function setUser($reddit_id, $name)
 {
     $query = new UserQuery();
     $users = $query->findByRedditID($reddit_id);
     $user = null;
     if ($users->count() == 0) {
         $user = new User();
         $user->setUsername($name);
         $user->setRedditID($reddit_id);
         $user->save();
     } else {
         $user = $users->getFirst();
     }
     if ($user->getBanned()) {
         // We block banned users by just not letting them log in
         session_destroy();
         return null;
     } else {
         $_SESSION[Auth::$SESSION_USER_ID] = $user->getId();
         //Record login
         UserAccess::addUserEvent($user, $_SERVER['REMOTE_ADDR'], UserAccessType::login);
         return $user;
     }
 }
예제 #19
0
 /**
  * initializes a new user or creates a guest user if not logged in
  */
 protected function initUser()
 {
     if (isset($_SESSION['dw-user-id']) && (isset($_SESSION['persistent']) || isset($_SESSION['last_action_time']))) {
         if (isset($_SESSION['persistent']) && $_SESSION['persistent'] || isset($_SESSION['last_action_time']) && time() - $_SESSION['last_action_time'] < 1800) {
             $this->user = UserQuery::create()->limit(1)->findPK($_SESSION['dw-user-id']);
             $_SESSION['last_action_time'] = time();
         }
     }
     if (empty($this->user)) {
         // create temporary guest user for this session
         $user = new User();
         $user->setEmail('*****@*****.**');
         $user->setRole('guest');
         $user->setLanguage(self::getBrowserLocale());
         $this->user = $user;
     }
 }
예제 #20
0
 /**
  * @param $suspensionInDays
  * @param $softDelete
  * @param $userId
  * @return bool
  */
 public static function setAccountSuspensionAndDeletionStatus($suspensionInDays, $softDelete, $userId)
 {
     if ($suspensionInDays > 0) {
         $suspensionTime = time() + $suspensionInDays * 60 * 60 * 24;
     } else {
         $suspensionTime = null;
     }
     // FYI "on" is what a checkbox delivers by default when submitted. Didn't know that for a long time :)
     $delete = $softDelete == "on" ? 1 : 0;
     $user = UserQuery::create()->findPk($userId);
     $user->setUserSuspensionTimestamp($suspensionTime);
     $user->setUserDeleted($delete);
     $user->save();
     if ($user) {
         Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_SUSPENSION_DELETION_STATUS'));
         return true;
     }
     return true;
 }
예제 #21
0
 private static function initializeRootPage()
 {
     $oRootPage = new Page();
     $oRootPage->makeRoot();
     $oRootPage->setName('root');
     $oRootPage->setIsInactive(false);
     $oRootPage->setPageType('default');
     $oRootPage->setTemplateName(null);
     $oFirstUser = UserQuery::create()->findOne();
     $oFirstUserId = $oFirstUser !== null ? $oFirstUser->getId() : 0;
     $oRootPage->setCreatedBy($oFirstUserId);
     $oRootPage->setUpdatedBy($oFirstUserId);
     $sPageString = new PageString();
     $sPageString->setLanguageId(Settings::getSetting("session_default", Session::SESSION_LANGUAGE_KEY, 'de'));
     $sPageString->setPageTitle('Home');
     $sPageString->setIsInactive(false);
     $oRootPage->addPageString($sPageString);
     $oRootPage->save();
     return $oRootPage;
 }
예제 #22
0
 public static function getQueryConditionById($queryId)
 {
     $resultInfo = array();
     $queryInfo = UserQuery::model()->findByPk($queryId);
     if ($queryInfo == null) {
         $resultInfo['status'] = CommonService::$ApiResult['FAIL'];
         $resultInfo['detail']['id'] = 'query not existed';
         return $resultInfo;
     } else {
         $userAccessableProductIdArr = Yii::app()->user->getState('visit_product_id');
         if (!in_array($queryInfo['product_id'], $userAccessableProductIdArr)) {
             $resultInfo['status'] = CommonService::$ApiResult['FAIL'];
             $resultInfo['detail']['id'] = 'has not visit right';
             return $resultInfo;
         }
     }
     $parsedQueryInfo = array();
     $parsedQueryInfo['product_id'] = $queryInfo['product_id'];
     $parsedQueryInfo['query_type'] = $queryInfo['query_type'];
     $parsedQueryInfo['title'] = $queryInfo['title'];
     $searchArr['leftParenthesesName'] = unserialize($queryInfo->left_parentheses);
     $searchArr['field'] = unserialize($queryInfo->fieldlist);
     $searchArr['operator'] = unserialize($queryInfo->operatorlist);
     $searchArr['value'] = unserialize($queryInfo->valuelist);
     $searchArr['rightParenthesesName'] = unserialize($queryInfo->right_parentheses);
     $searchArr['andor'] = unserialize($queryInfo->andorlist);
     $returnArr = array();
     $fieldCount = count($searchArr['field']);
     $keyArr = array('leftParenthesesName', 'field', 'operator', 'value', 'rightParenthesesName', 'andor');
     for ($i = 0; $i < $fieldCount; $i++) {
         $rowArr = array();
         foreach ($keyArr as $key) {
             $rowArr[$key] = $searchArr[$key][$i];
         }
         $returnArr[] = $rowArr;
     }
     $parsedQueryInfo['search_condition'] = $returnArr;
     $resultInfo['status'] = CommonService::$ApiResult['SUCCESS'];
     $resultInfo['detail'] = $parsedQueryInfo;
     return $resultInfo;
 }
예제 #23
0
 public function testSerialize()
 {
     $group = new Group();
     $group->setName('Developers');
     $user = new User();
     $user->setEmail('*****@*****.**');
     $user->setPassword('123456');
     $user->addGroup($group);
     $user->save();
     $userId = $user->getId();
     $this->assertInternalType('int', $userId);
     $serialized = serialize($user);
     UserPeer::clearInstancePool();
     $this->assertCount(0, UserPeer::$instances);
     $unserialized = unserialize($serialized);
     $fetchedUser = UserQuery::create()->findOneById($userId);
     $this->assertInstanceOf('FOS\\UserBundle\\Propel\\User', $unserialized);
     $this->assertCount(1, UserPeer::$instances);
     $this->assertTrue($fetchedUser->equals($unserialized));
     $this->assertCount(1, $unserialized->getGroups());
 }
예제 #24
0
 public static function initializeFirstUserIfEmpty($sUsername = null, $sPassword = null)
 {
     if (UserQuery::create()->count() > 0) {
         return false;
     }
     $sUsername = $sUsername !== null ? $sUsername : ADMIN_USERNAME;
     $sPassword = $sPassword !== null ? $sPassword : ADMIN_PASSWORD;
     $oUser = new User();
     $oUser->setPassword($sPassword);
     $oUser->setFirstName($sUsername);
     $oUser->setUsername($sUsername);
     $oUser->setIsAdmin(true);
     $oUser->setLanguageId(Settings::getSetting("session_default", Session::SESSION_LANGUAGE_KEY, 'en'));
     UserPeer::ignoreRights(true);
     $oUser->save();
     UserPeer::ignoreRights(false);
     // make sure that this first language exists and is the content language too
     AdminManager::createLanguageIfNoneExist(Session::language(), $oUser);
     AdminManager::setContentLanguage(Session::language());
     return true;
 }
예제 #25
0
 public function addUsersFromArray($users = array())
 {
     foreach ($users as $user) {
         $u = UserQuery::create()->findOneByUsername($user["username"]);
         if ($u) {
             if ($u == $this->data["loggedUser"]) {
                 $response["messages"][] = "You can not add yourself to group.";
                 continue;
             }
             $userGroup = UserGroupQuery::create()->filterByUser($u)->filterByGroup($this->data["group"])->findOne();
             if ($userGroup) {
                 $response["messages"][] = "User " . $user["username"] . " is already in this group.";
                 continue;
             }
             $userGroup = new UserGroup();
             $userGroup->setUser($u);
             $userGroup->setGroup($this->data["group"]);
             $userGroup->save();
         } else {
             $response["messages"][] = "User " . $user["username"] . " does not exist.";
         }
     }
 }
예제 #26
0
function user_charts($app, $user, $key, $val)
{
    $curPage = $app->request()->params('page');
    $q = $app->request()->params('q');
    if (empty($curPage)) {
        $curPage = 0;
    }
    $perPage = 12;
    $filter = !empty($key) ? array($key => $val) : array();
    if (!empty($q)) {
        $filter['q'] = $q;
    }
    $charts = ChartQuery::create()->getPublicChartsByUser($user, $filter, $curPage * $perPage, $perPage);
    $total = ChartQuery::create()->countPublicChartsByUser($user, $filter);
    $page = array('charts' => $charts, 'bymonth' => nbChartsByMonth($user), 'byvis' => nbChartsByType($user), 'bylayout' => nbChartsByLayout($user), 'bystatus' => nbChartsByStatus($user), 'key' => $key, 'val' => $val, 'search_query' => empty($q) ? '' : $q, 'mycharts_base' => '/mycharts');
    if (DatawrapperSession::getUser()->isAdmin() && $user != DatawrapperSession::getUser()) {
        $page['user2'] = $user;
        $page['mycharts_base'] = '/admin/charts/' . $user->getId();
        $page['all_users'] = UserQuery::create()->filterByDeleted(false)->orderByEmail()->find();
    }
    add_header_vars($page, 'mycharts');
    add_pagination_vars($page, $total, $curPage, $perPage, empty($q) ? '' : '&q=' . $q);
    $app->render('mycharts.twig', $page);
}
예제 #27
0
        $name = $user->getEmail();
        include '../../lib/templates/invitation-email.php';
        $from = $GLOBALS['dw_config']['email']['invite'];
        dw_send_support_email($user->getEmail(), __('You have been invited to Datawrapper!'), $invitation_mail, array('name' => $user->guessName(), 'invitation_link' => $invitationLink));
        ok(__('You should soon receive an email with further instructions.'));
    } else {
        error('login-email-unknown', __('The email is not registered yet.'));
    }
});
/*
 * endpoint for validating an invitation. The user sends his new password
 */
$app->post('/account/invitation/:token', function ($token) use($app) {
    $data = json_decode($app->request()->getBody());
    if (!empty($token)) {
        $users = UserQuery::create()->filterByActivateToken($token)->find();
        if (count($users) != 1) {
            error("token-invalid", __("This activation token is invalid. Your email address is probably already activated."));
        } elseif (empty($data->pwd1)) {
            error("password-missing", __("You must enter a password."));
        } elseif ($data->pwd1 != $data->pwd2) {
            error("password-mismatch", __("Both passwords must be the same."));
        } else {
            $user = $users[0];
            $user->setActivateToken('');
            $user->setPwd($data->pwd1);
            $user->save();
            // NOTE: we don't need a confirmation.
            # send confirmation email
            // $name   = $user->getEmail();
            // $domain = $GLOBALS['dw_config']['domain'];
<?php

include __DIR__ . '/vendor/autoload.php';
include __DIR__ . '/../../bootstrap.php';
$debugbarRenderer->setBaseUrl('../../../src/DebugBar/Resources');
use DebugBar\Bridge\PropelCollector;
$debugbar->addCollector(new PropelCollector());
Propel::init('build/conf/demo-conf.php');
set_include_path("build/classes" . PATH_SEPARATOR . get_include_path());
PropelCollector::enablePropelProfiling();
$user = new User();
$user->setName('foo');
$user->save();
$firstUser = UserQuery::create()->findPK(1);
render_demo_page();
예제 #29
0
 public function calcClockings(&$list, $userid, $start, $end)
 {
     $this->employee = UserQuery::create()->filterById($userid)->findOne();
     $domain = $this->employee->getDomain();
     $vacationDays = HolidayQuery::create()->filterByDomain($domain)->filterByDate($start, Criteria::GREATER_EQUAL)->filterByDate($end, Criteria::LESS_EQUAL)->find();
     $this->holidays = array();
     foreach ($vacationDays as $day) {
         $key = dayKey($day->getDate());
         $this->holidays[$key] = $day;
     }
     // Get flexitime
     $this->flexitime = ClockingQuery::create()->filterByUserId($userid)->filterByStart($start, Criteria::LESS_THAN)->filterByVisibility(0)->withColumn('SUM(flexitime)', 'flexitimeSum')->findOne()->getFlexitimeSum();
     $this->holidaysWeeks = Holiday::getCountPerWeek($domain, $start, $end);
     // Calculate weektime for first item
     $first = $list->getFirst();
     if ($first == null) {
         // No items at all, stop here
         return;
     }
     $weekday = date('N', $first->getStart());
     $currentWeek = date('W', $first->getStart());
     $currentYear = date('Y', $first->getStart());
     // Count any holiday as 'work done'
     $weekKey = $currentWeek . '-' . $currentYear;
     if (!array_key_exists($weekKey, $this->holidaysWeeks)) {
         $this->holidaysWeeks[$weekKey] = 0;
     }
     $this->worktime = $this->holidaysWeeks[$weekKey] * $this->employee->getDailyTime();
     if ($weekday > 1) {
         $weekstart = createDate($first->getStart());
         $weekstart->modify('midnight this week');
         $weekend = createDate($first->getStart());
         $weekend->modify('midnight this week +7 days');
         $week = ClockingQuery::create()->filterByStart($weekstart->getTimestamp(), Criteria::GREATER_THAN)->filterByStart($weekend->getTimestamp(), Criteria::LESS_THAN)->filterByUser($this->employee)->filterByVisibility(0)->find();
         $this->calcList($week);
     }
     $connection = Propel::getConnection(ClockingPeer::DATABASE_NAME);
     $connection->beginTransaction();
     try {
         $this->calcList($list);
         $connection->commit();
     } catch (Exception $e) {
         $connection->rollBack();
         throw $e;
     }
 }
예제 #30
0
});
//GET route
$app->get('/setup', function () use($app) {
    disable_cache($app);
    if (DatawrapperSession::getUser()->isLoggedIn() || UserQuery::create()->filterByRole(array('admin', 'sysadmin'))->count() > 0) {
        $app->redirect('/');
    }
    $page = array('title' => 'Datawrapper', 'pageClass' => 'setup', 'noHeader' => true, 'noFooter' => true, 'noSignup' => true, 'auth_salt' => DW_AUTH_SALT);
    add_header_vars($page, '');
    $app->render('setup.twig', $page);
});
/*
 * endpoint for final setup script
 */
$app->post('/setup', function () use($app) {
    $data = json_decode($app->request()->getBody());
    // check that there is no admin user yet (only true right after setup)
    if (UserQuery::create()->count() == 0) {
        $user = new User();
        $user->setCreatedAt(time());
        $user->setEmail($data->email);
        $user->setRole('admin');
        $user->setPwd(secure_password($data->pwd));
        $user->setLanguage(DatawrapperSession::getLanguage());
        $user->save();
        DatawrapperSession::login($user);
        $app->redirect('/');
    } else {
        print json_encode(array('status' => 'fail'));
    }
});