Ejemplo n.º 1
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.');
     }
 }
Ejemplo n.º 2
0
 public static function getUser()
 {
     if (isset($_SESSION['user']) && $_SESSION['user'] != '' && ($user = UserQuery::create()->findOneByUUID($_SESSION['user']))) {
         return $user;
     }
     return null;
 }
Ejemplo n.º 3
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;
 }
Ejemplo n.º 4
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('со всеми проектами всё ок');
     }
 }
Ejemplo n.º 5
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');
 }
Ejemplo n.º 6
0
 public function emailExists()
 {
     $user = UserQuery::create()->findOneByEmail($this->getEmail());
     if ($user) {
         return true;
     }
     return false;
 }
Ejemplo n.º 7
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;
 }
Ejemplo n.º 8
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;
     }
 }
Ejemplo n.º 9
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('/');
        }
    }
}
Ejemplo n.º 10
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();
 }
Ejemplo n.º 11
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);
 }
Ejemplo n.º 12
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);
     }
 }
Ejemplo n.º 13
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;
     }
 }
Ejemplo n.º 14
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;
 }
Ejemplo n.º 15
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;
 }
Ejemplo n.º 16
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());
 }
Ejemplo n.º 17
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;
 }
Ejemplo n.º 18
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.";
         }
     }
 }
Ejemplo n.º 19
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);
}
Ejemplo n.º 20
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'];
Ejemplo n.º 21
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;
     }
 }
<?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();
Ejemplo n.º 23
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'));
    }
});
Ejemplo n.º 24
0
 /**
  * Get the associated User object
  *
  * @param PropelPDO $con Optional Connection object.
  * @param $doQuery Executes a query to get the object if required
  * @return User The associated User object.
  * @throws PropelException
  */
 public function getUserRelatedByUpdatedBy(PropelPDO $con = null, $doQuery = true)
 {
     if ($this->aUserRelatedByUpdatedBy === null && $this->updated_by !== null && $doQuery) {
         $this->aUserRelatedByUpdatedBy = UserQuery::create()->findPk($this->updated_by, $con);
         /* The following can be used additionally to
               guarantee the related object contains a reference
               to this object.  This level of coupling may, however, be
               undesirable since it could result in an only partially populated collection
               in the referenced object.
               $this->aUserRelatedByUpdatedBy->addRightsRelatedByUpdatedBy($this);
            */
     }
     return $this->aUserRelatedByUpdatedBy;
 }
Ejemplo n.º 25
0
    if ($user->isLoggedIn()) {
        return;
    }
    // allow access if this is a public installation
    if (empty($dw_config['prevent_guest_access'])) {
        return;
    }
    // allow access if a proper secret is given (required for publishing charts
    // (see download()) in private installations)
    $requiredKey = sha1(isset($dw_config['secure_auth_key']) ? $dw_config['secure_auth_key'] : '');
    $givenKey = isset($_REQUEST['seckey']) ? $_REQUEST['seckey'] : null;
    if ($requiredKey === $givenKey) {
        return;
    }
    $req = $app->request();
    if (UserQuery::create()->filterByRole(array('admin', 'sysadmin'))->count() > 0) {
        if ($req->getResourceUri() != '/login' && strncmp($req->getResourceUri(), '/account/invite/', 16) && strncmp($req->getResourceUri(), '/account/reset-password/', 24)) {
            // and doesn't start with '/account/reset-password/'
            $app->redirect('/login');
        }
    } else {
        if ($req->getResourceUri() != '/setup') {
            $app->redirect('/setup');
        }
    }
});
/**
 * Step 4: Run the Slim application
 *
 * This method should be called last. This is responsible for executing
 * the Slim application using the settings and routes defined above.
Ejemplo n.º 26
0
 private function import()
 {
     session_write_close();
     $SOURCE_DB = 'groupion_new';
     $USERNAME = '******';
     $PASSWORD = '';
     set_time_limit(0);
     $status = new Status();
     print '<br><br><br><br><br><div style="margin-left: 3em">';
     print '<p>Starting database migration</p>';
     flush();
     try {
         $con = Propel::getConnection();
         $status->start('Connecting to database');
         $dbh = new PDO('mysql:host=localhost;dbname=' . $SOURCE_DB, $USERNAME, $PASSWORD);
         $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $dbh->exec('SET NAMES utf8');
         $status->done();
         $debugUser = UserQuery::create()->findOneByFQN('cms/test', $con);
         if ($debugUser === null) {
             throw new Exception('Could not find debug user "cms/test".');
         }
         $status->start('Clearing tables');
         // Mark transactions created by old system as deleted
         TransactionQuery::create()->filterByCreatorId(null, Criteria::NOT_EQUAL)->filterById(5814, Criteria::LESS_EQUAL)->filterByCreationdate(1347446069, Criteria::LESS_EQUAL)->update(array('Deleted' => 1), $con);
         // Clockings created by old system => max. clocking ID = 365913
         // Transactions created by new system with old clockings
         // SELECT distinct min(tc.clocking_id) FROM transaction t join transaction_clocking tc on t.id=tc.transaction_id where tc.clocking_id<=365913 and ;
         // => min clocking ID
         /*
         			// Delete clockings without new system transactions
         			ClockingQuery::create()
         				->joinTransactionClocking()
         				->join('TransactionClocking.Transaction')
         				->filterByCreatorId(null, Criteria::NOT_EQUAL)
         				->add(TransactionPeer::ID, 5814, Criteria::LESS_EQUAL)
         				->add(TransactionPeer::CREATOR_ID, null, Criteria::NOT_EQUAL)
         				->update(array('Deleted' => 1), $con);
         */
         // Mark clockings with new system transactions as deleted
         ClockingQuery::create()->filterById(365913, Criteria::LESS_EQUAL)->filterByCreatorId(null)->update(array('Deleted' => 1), $con);
         /*
         			TransactionClockingQuery::create()->deleteAll($con);
         			TransactionQuery::create()->deleteAll($con);
         
         			ClockingQuery::create()
         				->filterByUserRelatedByUserId($debugUser, Criteria::NOT_EQUAL)
         				->delete($con);
         			HolidayQuery::create()->deleteAll($con);
         			UserQuery::create()
         				->filterByName('test', Criteria::NOT_EQUAL)
         				->delete($con);
         */
         /*
         			TransactionClockingQuery::create()->deleteAll();
         			TransactionQuery::create()->deleteAll();
         			ClockingQuery::create()->deleteAll();
         			DomainQuery::create()->deleteAll();
         			AccountQuery::create()->deleteAll();
         
         			$status->done();
         
         			$status->start('Create default Account');
         
         			$account = new Account();
         			$account->setName('Default account');
         			$account->save();
         
         			$status->done();
         
         			$status->start('Create default domain');
         
         			$domain = new Domain();
         			$domain->setName('default');
         			$domain->setDescription('Default domain created while migrating to the new system.');
         			$domain->setAccount($account);
         			$domain->save();
         
         			$status->done();
         */
         $account = AccountQuery::create()->findOneByIdentifier('cms', $con);
         $domain = DomainQuery::create();
         /*
         			$status->start('Create holidays');
         
         			$holidaysUrl = \Xily\Config::get('migration.holidays_url', 'string', 'http://10.10.10.5/groupion/data/holidays');
         
         			$filenames = array('Bayern2009', 'Bayern2010', 'Bayern2011', 'Bayern2012', 'Bayern2013', 'Bayern2014');
         			foreach ($filenames as $filename) {
         				$file = fopen($holidaysUrl.'/'.$filename.'.csv', 'r');
         				if ( !is_resource($file) )
         					throw new Exception('Could not open file');
         
         				while ( is_array($row = fgetcsv($file, 1000, ';')) ) {
         					$date  = strtotime($row[0]);
         					$name  = $row[1];
         					$state = $row[2];
         					if ( $date ) {
         						$holidayDomain = new HolidayDomain();
         						$holidayDomain->setDomain($domain);
         
         						$holiday = new Holiday();
         						$holiday
         							->setAccount($account)
         							->setDate($date)
         							->setName(trim($name))
         							->addHolidayDomain($holidayDomain)
         							->save();
         					}
         				}
         			}
         
         			$status->done();
         
         			$status->start('Migrating Users');
         			$this->importUsers($status, $account, $domain, $dbh, $con);
         			$status->done();
         */
         $usersByName = $this->getUsers($account, $con);
         $clockingTypeMap = $this->getClockingTypes($account, $con);
         $status->start('Migrating Clockings');
         $clockingDataByOldID = $this->importClockings($status, $clockingTypeMap, $usersByName, $dbh, $con);
         $status->done();
         $bookingTypesByIdentifier = $this->getBookingTypes($account, $con);
         $status->start('Migrating Transactions');
         $this->importTransactions($status, $clockingTypeMap, $bookingTypesByIdentifier, $usersByName, $clockingDataByOldID, $dbh, $con);
         $status->done();
         echo '#INCONSISTENCIES: ' . $this->inconsistencies;
         $dbh = null;
     } catch (Exception $e) {
         echo 'Error: ' . nl2br(htmlspecialchars($e->getMessage())) . '<br/>';
         $status->showNotes($e->getMessage());
         die;
     }
     print '<p>Finished migration!</p></div>';
     $status->showNotes();
 }
Ejemplo n.º 27
0
function email_exists($email)
{
    $r = UserQuery::create()->findOneByEmail($email);
    return isset($r);
}
Ejemplo n.º 28
0
 /**
  * Get the associated User object
  *
  * @param      PropelPDO Optional Connection object.
  * @return     User The associated User object.
  * @throws     PropelException
  */
 public function getUser(PropelPDO $con = null)
 {
     if ($this->aUser === null && $this->user_id !== null) {
         $this->aUser = UserQuery::create()->findPk($this->user_id, $con);
         /* The following can be used additionally to
         			guarantee the related object contains a reference
         			to this object.  This level of coupling may, however, be
         			undesirable since it could result in an only partially populated collection
         			in the referenced object.
         			$this->aUser->addJobs($this);
         		 */
     }
     return $this->aUser;
 }
Ejemplo n.º 29
0
function all_users()
{
    return UserQuery::create()->find();
}
Ejemplo n.º 30
0
 /**
  * checks the email/verification code combination and set the user's activation status to true in the database
  *
  * @param int $user_id user id
  * @param string $user_activation_verification_code verification token
  *
  * @return bool success status
  */
 public static function verifyNewUser($user_id, $user_activation_verification_code)
 {
     $user = UserQuery::create()->findPk($user_id);
     $user->setUserActive(1);
     $user->setUserActivationHash('NULL');
     if ($user) {
         Session::add('feedback_positive', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_SUCCESSFUL'));
         return true;
     }
     Session::add('feedback_negative', Text::get('FEEDBACK_ACCOUNT_ACTIVATION_FAILED'));
     return false;
 }