/**
  * startup
  * called after Controller::beforeFilter()
  * 
  * @param object $controller instance of controller
  * @return void
  * @access public
  */
 public function startup(Controller $controller)
 {
     // Maintenance mode OFF but on offline page -> redirect to root url
     if (!$this->isOn() && strpos($controller->here, Configure::read('Maintenance.site_offline_url')) !== false) {
         $controller->redirect(Router::url('/', true));
         return;
     }
     // Maintenance mode ON user logoout allowed
     if ($this->isOn() && strpos($controller->here, 'users/logout') !== false) {
         return;
     }
     // Maintenance mode ON but not in offline page requested - > redirect to offline page
     if ($this->isOn() && strpos($controller->here, Configure::read('Maintenance.site_offline_url')) === false) {
         // All users auto logged off if setting is true
         if (Configure::read('Maintenance.offline_destroy_session')) {
             $this->Session->destroy();
         }
         $controller->redirect(Router::url(Configure::read('Maintenance.site_offline_url'), true));
         return;
     }
     // Maintenance mode scheduled show message!!
     if ($this->hasSchedule()) {
         $this->Flash->maintenance(__('This application will be on maintenance mode at  %s ', Configure::read('Maintenance.start')));
     }
 }
 function onLaunch()
 {
     // Check the user has an appropriate role
     if ($this->user->isLearner() || $this->user->isStaff()) {
         $user_id = $this->user->getId();
         $consumer_key = $this->consumer->getKey();
         // Initialise the user session
         $model = new LTILoginer();
         $model->consumer_key = $consumer_key;
         $model->user_id = $user_id;
         // validate user and redirect if valid
         if ($model->validate() && $model->login()) {
             $returnUrl = Yii::app()->user->returnUrl;
             if (!is_null($returnUrl)) {
                 $returnUrl = array('site/index');
             }
             $this->controller->redirect($returnUrl);
         } else {
             // TODO: some error message
         }
         /*$_SESSION['consumer_key'] = $this->consumer->getKey();
           $_SESSION['resource_id'] = $this->resource_link->getId();
           $_SESSION['user_consumer_key'] = $this->user->getResourceLink()
               ->getConsumer()
               ->getKey();
           $_SESSION['user_id'] = $this->user->getId();
           $_SESSION['isStudent'] = $this->user->isLearner();
           $_SESSION['isContentItem'] = FALSE;*/
         // Redirect the user to display the list of items for the resource link
         /*$this->redirectURL = getAppUrl();*/
     } else {
         $this->reason = 'Invalid role.';
         $this->isOK = FALSE;
     }
 }
Example #3
0
 /**
  * Convenience method to check for selection count and redirect request
  *
  * @param bool $condition True will redirect request to $options['redirect']
  * @param array $options Options array as passed to process()
  * @return bool True if selection is valid
  */
 protected function _validateSelection($condition, $options, $messageName)
 {
     $messageMap = $options['messageMap'];
     $message = $messageMap[$messageName];
     if ($condition === true) {
         $this->Session->setFlash($message, 'flash', array('class' => 'error'));
         $this->_controller->redirect($options['redirect']);
     }
     return !$condition;
 }
 /**
  * Login 
  * 
  * @return void
  */
 public function login()
 {
     if ($this->Controller->request->is('post')) {
         $user_id = $this->Controller->request->data['User']['id'];
         $result = $this->Controller->User->find('first', array('conditions' => array('User.id' => $user_id), 'recursive' => -1));
         if ($result) {
             $this->Auth->login($result['User']);
             $this->Controller->redirect($this->Auth->redirect());
         } else {
             $this->Session->setFlash(__('User does not exist'));
         }
     }
 }
Example #5
0
 /**
  * Redirect to url stored in Data.referer or default $url
  *
  * @param mixed the url to redirect to
  * @param integer http status code, default is null
  * @param boolean calling php exit or not after redirect, default is true
  * @return mixed
  */
 public function redirect($url, $status = null, $exit = true)
 {
     if (isset($this->Controller->data['Data']['referer'])) {
         $referer = $this->Controller->request->data['Data']['referer'];
     } else {
         $referer = $this->Controller->request->referer();
     }
     if (strlen($referer) == 0 || $referer == '/') {
         $this->Controller->redirect($url, $status, $exit);
     } else {
         $this->Controller->redirect($referer, $status, $exit);
     }
 }
 public static function checkPermissionForProtectedHomeDirs($strFile)
 {
     $strUuid = \Config::get('protectedHomeDirRoot');
     if (!$strFile) {
         return;
     }
     if ($strUuid && ($strProtectedHomeDirRootPath = \HeimrichHannot\HastePlus\Files::getPathFromUuid($strUuid)) !== null) {
         // check only if path inside the protected root dir
         if (StringUtil::startsWith($strFile, $strProtectedHomeDirRootPath)) {
             if (FE_USER_LOGGED_IN) {
                 if (($objFrontendUser = \FrontendUser::getInstance()) !== null) {
                     if (\Config::get('allowAccessByMemberId') && $objFrontendUser->assignProtectedDir && $objFrontendUser->protectedHomeDir) {
                         $strProtectedHomeDirMemberRootPath = Files::getPathFromUuid($objFrontendUser->protectedHomeDir);
                         // fe user id = dir owner member id
                         if (StringUtil::startsWith($strFile, $strProtectedHomeDirMemberRootPath)) {
                             return;
                         }
                     }
                     if (\Config::get('allowAccessByMemberGroups')) {
                         $arrAllowedGroups = deserialize(\Config::get('allowedMemberGroups'), true);
                         if (array_intersect(deserialize($objFrontendUser->groups, true), $arrAllowedGroups)) {
                             return;
                         }
                     }
                 }
             }
             $intNoAccessPage = \Config::get('jumpToNoAccess');
             if ($intNoAccessPage && ($objPageJumpTo = \PageModel::findByPk($intNoAccessPage)) !== null) {
                 \Controller::redirect(\Controller::generateFrontendUrl($objPageJumpTo->row()));
             } else {
                 die($GLOBALS['TL_LANG']['MSC']['noAccessDownload']);
             }
         }
     }
 }
	public function deletePosition($params){
		//Check session user
		parent::userInfoAndSession();
		
		if($this->db->deletePosition($params)) parent::redirect('cms'.DS.'carriere'.DS.'position', 'success');
		else parent::redirect('cms'.DS.'carriere'.DS.'position', 'error');
	}
 /**
  * Check permissions to edit table.
  */
 public function checkPermission()
 {
     if (!\BackendUser::getInstance()->isAdmin) {
         \System::log('Not enough permissions to access leads export ID "' . \Input::get('id') . '"', __METHOD__, TL_ERROR);
         \Controller::redirect('contao/main.php?act=error');
     }
 }
 protected function runAction()
 {
     global $objPage;
     switch (\Input::get('act')) {
         case WATCHLIST_ACT_DELETE:
             Watchlist::getInstance()->deleteItem(\Input::get('id'));
             break;
         case WATCHLIST_ACT_ADD:
             $objItem = new WatchlistItemModel();
             $objItem->pid = Watchlist::getInstance()->getId();
             $objItem->uuid = \Input::get('id');
             $objItem->pageID = $objPage->id;
             $objItem->cid = \Input::get('cid');
             $objItem->type = \Input::get('type');
             $objItem->title = \Input::get('title');
             $objItem->tstamp = time();
             Watchlist::getInstance()->addItem($objItem);
             break;
         case WATCHLIST_ACT_DELETE_ALL:
             Watchlist::getInstance()->deleteAll();
             break;
         case WATCHLIST_ACT_DOWNLOAD_ALL:
             Watchlist::getInstance()->downloadAll();
             break;
     }
     // if ajax -> return the content of the watchlist
     if (\Environment::get('isAjaxRequest')) {
         die(json_encode(array('action' => \Input::get('act'), 'watchlist' => Watchlist::getInstance()->generate(), 'notification' => Watchlist::getInstance()->generateNotifications(), 'count' => Watchlist::getInstance()->count(), 'cssClass' => Watchlist::getInstance()->count() > 0 ? 'not-empty' : 'empty')));
     }
     // no js support -- redirect and remove GET parameters
     \Controller::redirect(\Controller::generateFrontendUrl($objPage->row()));
 }
 public function redirect($url, $status = null, $exit = true)
 {
     if (!isset($url['language']) && $this->Session->check('Config.language')) {
         $url['language'] = $this->Session->read('Config.language');
     }
     parent::redirect($url, $status, $exit);
 }
 public function startup(Controller $controller)
 {
     if (isset($controller->request->params['prefix']) && $controller->request->params['prefix'] == 'admin' && !$this->isLoggedIn()) {
         $this->Session->setFlash(__d('micro_auth', 'You need to login to access this page'));
         $controller->redirect($this->config['loginAction']);
     }
 }
 /**
  * Returns the appropriate response up the controller chain
  * if {@link validate()} fails (which is checked prior to executing any form actions).
  * By default, returns different views for ajax/non-ajax request, and
  * handles 'application/json' requests with a JSON object containing the error messages.
  * Behaviour can be influenced by setting {@link $redirectToFormOnValidationError}.
  *
  * @return SS_HTTPResponse|string
  */
 protected function getValidationErrorResponse()
 {
     $request = $this->getRequest();
     if ($request->isAjax()) {
         // Special case for legacy Validator.js implementation
         // (assumes eval'ed javascript collected through FormResponse)
         $acceptType = $request->getHeader('Accept');
         if (strpos($acceptType, 'application/json') !== FALSE) {
             // Send validation errors back as JSON with a flag at the start
             $response = new SS_HTTPResponse(Convert::array2json($this->validator->getErrors()));
             $response->addHeader('Content-Type', 'application/json');
         } else {
             $this->setupFormErrors();
             // Send the newly rendered form tag as HTML
             $response = new SS_HTTPResponse($this->forTemplate());
             $response->addHeader('Content-Type', 'text/html');
         }
         return $response;
     } else {
         if ($this->getRedirectToFormOnValidationError()) {
             if ($pageURL = $request->getHeader('Referer')) {
                 if (Director::is_site_url($pageURL)) {
                     // Remove existing pragmas
                     $pageURL = preg_replace('/(#.*)/', '', $pageURL);
                     $pageURL = Director::absoluteURL($pageURL, true);
                     return $this->controller->redirect($pageURL . '#' . $this->FormName());
                 }
             }
         }
         return $this->controller->redirectBack();
     }
 }
 function init()
 {
     parent::init();
     if ($this->Children()->Count()) {
         Controller::redirect($this->Children()->First()->AbsoluteLink());
     }
 }
Example #14
0
 public function action_authorized()
 {
     $auth_t = array_key_exists('OAuthAuthToken', $_SESSION) ? $_SESSION['OAuthAuthToken'] : false;
     if ($auth_t) {
         $access_t = $this->oauth->getAccessToken($auth_t);
         if ($access_t) {
             Backend::addSuccess('Sucessfully logged into Twitter');
             $data = array('screen_name' => $access_t['screen_name'], 'twitter_id' => $access_t['user_id'], 'oauth_token' => $access_t['oauth_token'], 'oauth_secret' => $access_t['oauth_token_secret'], 'active' => 1);
             $twit = new TwitterObj();
             if ($twit->replace($data)) {
             } else {
                 Backend::addError('Could not record Twitter Auth information');
             }
             if (!empty($_SESSION['TwitterRedirect'])) {
                 $url = $_SESSION['TwitterRedirect'];
                 unset($_SESSION['TwitterRedirect']);
                 Controller::redirect($url);
             }
         } else {
             Backend::addError('Could not get Access Token');
         }
     } else {
         Backend::addError('No Authentication Token');
     }
     return true;
 }
Example #15
0
 public function update($id)
 {
     if (parent::auth()) {
         if ($_SESSION['id'] == $id) {
             $user = User::find($id);
             if ($_POST) {
                 if ($_FILES['picture']) {
                     parent::uploadImage($_FILES['picture'], 'user');
                 }
                 try {
                     $user->update_attributes($_POST);
                     $_SESSION['username'] = $_POST['username'];
                     parent::redirect('site/index');
                 } catch (Exception $e) {
                     if (strstr($e->getMessage(), 'Duplicate entry') == true) {
                         $error = 'Username or Email Has Been Previously Registered';
                     }
                 }
             }
             parent::setHeader('default');
             parent::render('user/update', array('user' => $user, 'error' => isset($error) ? $error : ''));
             parent::setFooter('default');
         } else {
             parent::redirect('site/index');
         }
     } else {
         parent::redirect('site/index');
     }
 }
Example #16
0
 public function action_logout()
 {
     if (Auth::instance()->logout()) {
         $this->session->destroy();
         Controller::redirect();
     }
 }
 public function reset($email, $requestKey)
 {
     // Redirect if user is already logged in
     if ($this->Controller->authUser) {
         $this->Controller->Flash->error(__d('users', 'Your account could not be activated.'));
         return $this->Controller->redirect($this->Controller->Auth->config('loginAction'));
     }
     // If the email and key doesn't match
     if (!$this->Controller->Users->validateRequestKey($email, $requestKey)) {
         $this->Controller->Flash->error(__d('users', 'Your account could not be activated.'));
         return $this->Controller->redirect($this->Controller->Auth->config('loginAction'));
     }
     // If we passed and the POST isset
     if ($this->Controller->request->is('post')) {
         $user = $this->Controller->Users->find()->where(['email' => $email, 'request_key' => $requestKey])->first();
         if ($user) {
             $user = $this->Controller->Users->patchEntity($user, $this->Controller->request->data);
             $user->set('active', 1);
             $user->set('request_key', null);
             if ($this->Controller->Users->save($user)) {
                 $this->Controller->Flash->success(__d('users', 'Your password has been changed.'));
                 return $this->Controller->redirect($this->Controller->Auth->config('loginAction'));
             }
         }
         $this->Controller->Flash->error(__d('users', 'Your account could not be activated.'));
     }
 }
Example #18
0
 /**
  * start login
  */
 public function action_login()
 {
     $username = Arr::get($_POST, 'username', '');
     $password = Arr::get($_POST, 'password', '');
     if (!$username || !$password) {
         return Prompt::warningView('用户名密码不能为空', 'author');
     }
     try {
         $account = Model::factory('Account')->getAccountByName($username)->getArray();
         if (!$account[0]) {
             //日志
             return Prompt::errorView('用户名不存在', 'author');
         }
     } catch (Exception $e) {
         //日志
         echo $e->getMessage();
         exit;
         return Prompt::errorView('登录失败', 'author');
     }
     if ($account[0]['password'] && $account[0]['password'] === md5($password)) {
         //保存 seesion 信息
         Session::instance()->set('author', $account[0]);
         return Controller::redirect('/');
     } else {
         return Prompt::errorView('登录失败', 'author');
     }
 }
 protected function compile()
 {
     $strAction = \Input::get('act');
     // at first check for the correct request token to be set
     if ($strAction && !\RequestToken::validate(\Input::get('token')) && !$this->deactivateTokens) {
         StatusMessage::addError(sprintf($GLOBALS['TL_LANG']['frontendedit']['requestTokenExpired'], Environment::getUrl(true, true, false)), $this->id, 'requestTokenExpired');
         return;
     }
     if ($strAction == FRONTENDEDIT_ACT_DELETE && ($intId = \Input::get('id'))) {
         if ($this->checkPermission($intId)) {
             $this->deleteItem($intId);
             // return to the list
             \Controller::redirect(Url::removeQueryString(array('act', 'id', 'token'), Environment::getUrl()));
         } else {
             StatusMessage::addError($GLOBALS['TL_LANG']['formhybrid_list']['noPermission'], $this->id);
             return;
         }
     }
     if ($strAction == FRONTENDEDIT_ACT_PUBLISH && ($intId = \Input::get('id'))) {
         if ($this->checkPermission($intId)) {
             $this->publishItem($intId);
             // return to the list
             \Controller::redirect(Url::removeQueryString(array('act', 'id'), Environment::getUrl()));
         } else {
             StatusMessage::addError($GLOBALS['TL_LANG']['formhybrid_list']['noPermission'], $this->id);
             return;
         }
     }
     parent::compile();
 }
	public function position($params){
		//Check session user
		parent::userInfoAndSession();
		
		if($this->db->setPosition($params)) parent::redirect('cms'.DS.'contact', '');
		else parent::redirect('cms'.DS.'contact', 'error');
	}
Example #21
0
 /**
  * Check permissions for that entry
  * @return void
  */
 public static function check()
 {
     $session = \Session::getInstance()->getData();
     if (\Input::get('act') == 'delete' && in_array(\Input::get('id'), static::getUndeletableIds())) {
         \System::log('Product type ID ' . \Input::get('id') . ' is used in an order and can\'t be deleted', __METHOD__, TL_ERROR);
         \Controller::redirect('contao/main.php?act=error');
     } elseif (\Input::get('act') == 'deleteAll' && is_array($session['CURRENT']['IDS'])) {
         $arrDeletable = array_diff($session['CURRENT']['IDS'], static::getUndeletableIds());
         if (count($arrDeletable) != count($session['CURRENT']['IDS'])) {
             $session['CURRENT']['IDS'] = array_values($arrDeletable);
             \Session::getInstance()->setData($session);
             \Message::addInfo($GLOBALS['TL_LANG']['MSC']['undeletableRecords']);
         }
     }
     // Disable variants if no such attributes are available
     \Controller::loadDataContainer('tl_iso_product');
     $blnVariants = false;
     foreach ($GLOBALS['TL_DCA']['tl_iso_product']['fields'] as $strName => $arrConfig) {
         $objAttribute = $GLOBALS['TL_DCA']['tl_iso_product']['attributes'][$strName];
         if (null !== $objAttribute && $objAttribute->isVariantOption()) {
             $blnVariants = true;
             break;
         }
     }
     if (!$blnVariants) {
         \System::loadLanguageFile('explain');
         unset($GLOBALS['TL_DCA']['tl_iso_producttype']['subpalettes']['variants']);
         $GLOBALS['TL_DCA']['tl_iso_producttype']['fields']['variants']['input_field_callback'] = function ($dc) {
             // Make sure variants are disabled in this product type (see #1114)
             \Database::getInstance()->prepare("UPDATE " . $dc->table . " SET variants='' WHERE id=?")->execute($dc->id);
             return '<br><p class="tl_info">' . $GLOBALS['TL_LANG']['XPL']['noVariantAttributes'] . '</p>';
         };
     }
 }
 public static function executeListSubscribe()
 {
     if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
         Controller::redirect('/get');
     }
     $email = $_POST['email'];
     if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
         Session::set('list_error', $email ? __('Please provide a valid email address.') : __('Please provide an email address.'));
     } elseif (!$_POST['listId']) {
         Session::set('list_error', __('List not provided.'));
     } else {
         $mcApi = new Mailchimp();
         $mcListId = $_POST['listId'];
         $mergeFields = isset($_POST['mergeFields']) ? unserialize($_POST['mergeFields']) : [];
         $success = $mcApi->listSubscribe($mcListId, $email, $mergeFields, 'html', false);
         if ($success) {
             Session::set(Session::KEY_MAILCHIMP_LIST_IDS, array_merge(Session::get(Session::KEY_MAILCHIMP_LIST_IDS, []), [$mcListId]));
             Session::set(Session::KEY_LIST_SUB_SUCCESS, __('Great success! Welcome to LBRY.'));
         } else {
             $error = $mcApi->errorMessage ?: __('Something went wrong adding you to the list.');
             Session::set('list_error', $error);
         }
     }
     Controller::redirect(isset($_POST['return_url']) && $_POST['return_url'] ? $_POST['return_url'] : '/get');
 }
Example #23
0
 /**
  * Display a wildcard in the back end
  * @return string
  */
 public function generate()
 {
     if (TL_MODE == 'BE') {
         $objTemplate = new \BackendTemplate('be_wildcard');
         $objTemplate->wildcard = '### ISOTOPE ECOMMERCE: STORE CONFIG SWICHER ###';
         $objTemplate->title = $this->headline;
         $objTemplate->id = $this->id;
         $objTemplate->link = $this->name;
         $objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;
         return $objTemplate->parse();
     }
     $this->iso_config_ids = deserialize($this->iso_config_ids);
     if (!is_array($this->iso_config_ids) || !count($this->iso_config_ids)) {
         // Can't use empty() because its an object property (using __get)
         return '';
     }
     if (\Input::get('config') != '') {
         if (in_array(\Input::get('config'), $this->iso_config_ids)) {
             Isotope::getCart()->config_id = \Input::get('config');
             Isotope::getCart()->save();
         }
         \Controller::redirect(preg_replace('@[?|&]config=' . \Input::get('config') . '@', '', \Environment::get('request')));
     }
     return parent::generate();
 }
Example #24
0
 function execute(&$controller, &$request, &$user)
 {
     $member = $user->getAttribute('member', GLU_NS);
     $user->setAttribute('member', $member, GLU_NS);
     $custom = $request->hasParameter('custom_design_submit') ? $request->getParameter('custom_design_submit') : null;
     if ($custom) {
         $ct = DB_DataObject::factory('custom_template');
         $ct->member_id = $member->id;
         if ($ct->count() > 0) {
             $ct->get('member_id', $member->id);
             $ct->template = $request->getParameter('css');
             $ct->update();
         } else {
             $ct->member_id = $member->id;
             $ct->template = $request->getParameter('css');
             $ct->insert();
         }
         Controller::redirect(SCRIPT_PATH . 'setting/design/changed_custom');
     } else {
         $member->design_id = $request->getParameter('design_id');
         $member->update();
         Controller::redirect(SCRIPT_PATH . 'setting/design/changed');
     }
     return VIEW_NONE;
 }
Example #25
0
 /**
  * Performs a delete on given scaffolded Model.
  *
  * @param array $params Parameters for scaffolding
  * @return mixed Success on delete, error if delete fails
  * @access private
  */
 function __scaffoldDelete($params = array())
 {
     if ($this->controller->_beforeScaffold('delete')) {
         if (isset($params['pass'][0])) {
             $id = $params['pass'][0];
         } elseif ($this->_validSession) {
             $this->controller->Session->setFlash(sprintf(__("No id set for %s::delete()", true), Inflector::humanize($this->modelKey)));
             $this->controller->redirect($this->redirect);
         } else {
             return $this->controller->flash(sprintf(__("No id set for %s::delete()", true), Inflector::humanize($this->modelKey)), '/' . Inflector::underscore($this->controller->viewPath));
         }
         if ($this->ScaffoldModel->delete($id)) {
             if ($this->_validSession) {
                 $this->controller->Session->setFlash(sprintf(__('The %1$s with id: %2$d has been deleted.', true), Inflector::humanize($this->modelClass), $id));
                 $this->controller->redirect($this->redirect);
             } else {
                 return $this->controller->flash(sprintf(__('The %1$s with id: %2$d has been deleted.', true), Inflector::humanize($this->modelClass), $id), '/' . $this->viewPath);
             }
         } else {
             if ($this->_validSession) {
                 $this->controller->Session->setFlash(sprintf(__('There was an error deleting the %1$s with id: %2$d', true), Inflector::humanize($this->modelClass), $id));
                 $this->controller->redirect($this->redirect);
             } else {
                 return $this->controller->flash(sprintf(__('There was an error deleting the %1$s with id: %2$d', true), Inflector::humanize($this->modelClass), $id), '/' . $this->viewPath);
             }
         }
     } elseif ($this->controller->_scaffoldError('delete') === false) {
         return $this->__scaffoldError();
     }
 }
Example #26
0
 /**
  * Authorize the user to see the account, or take
  * appropriate action if they're not authorized.
  *
  * @param \Page $page
  * @param \Template $tpl
  *
  * @return bool
  */
 public static function authorize($page, $tpl)
 {
     $conf = self::conf();
     $www = $conf['App Settings']['include_www'] ? "www." : "";
     // Send non-customer requests to the main site
     $customer = self::customer();
     if (!$customer) {
         if (strpos($_SERVER['REQUEST_URI'], '/saasy/') === 0) {
             self::$controller->redirect('/');
         }
         $url = $_SERVER['REQUEST_URI'] === '/' ? 'admin/page' : 'admin/page' . $_SERVER['REQUEST_URI'];
         echo self::$controller->run($url);
         return false;
     }
     // Require user to be logged in
     if (!\User::is_valid()) {
         $page->title = __('Members');
         echo self::$controller->run('user/login');
         return false;
     }
     // Does this user belong to the company?
     $acct = self::acct();
     if (!$acct || $acct->customer !== $customer->id || $acct->enabled == 0) {
         \User::logout();
         $page->title = __('Unauthorized');
         echo $tpl->render('saasy/unauthorized');
         return false;
     }
     return true;
 }
Example #27
0
 /**
  * Получение access token для авторизации
  * @return bool
  * @throws Kohana_Exception
  */
 private function get_access_token()
 {
     $params = Arr::get($_SERVER, 'QUERY_STRING');
     parse_str($params, $params);
     if (empty($params['code'])) {
         Controller::redirect($this->login_query());
     }
     if (!$params) {
         # TODO: Throw custom Exception for GitHub
         throw new Kohana_Exception('NO QUERY PARAMS');
     }
     if (isset($params['error'])) {
         # TODO: Throw custom Exception for GitHub
         throw new Kohana_Exception('Error: ' . $params['error'] . ' Description: ' . $params['error_description']);
     }
     $params = array('client_id' => self::$config['APP_ID'], 'code' => $params['code'], 'client_secret' => self::$config['APP_SECRET'], 'redirect_uri' => self::$config['REDIRECT_URI']);
     $resp = Request::factory(self::$config['GET_TOKEN_URI'])->method(Request::GET)->query($params)->execute();
     parse_str($resp);
     if (!isset($access_token)) {
         # TODO: Throw custom Exception for GitHub
         throw new Kohana_Exception('Error: ' . $resp->error . ' Description: ' . $resp->error_description);
     }
     $this->token = $access_token;
     //Session::instance()->set('gh_token', $access_token); #TODO: Why is it commented?
     return true;
 }
Example #28
0
 public function redirect($url, $status = null, $exit = true)
 {
     if ($url == null && $status == 403 && $this->request->is('ajax')) {
         $url = $this->Auth->loginAction;
     }
     parent::redirect($url, $status, $exit);
 }
Example #29
0
 public function action_index()
 {
     $data_pages = ORM::factory('Page')->where('title_en', '=', 'contacts')->find()->as_array();
     $id = $data_pages['id'];
     $data_contacts = ORM::factory('Setting', 1)->as_array();
     if (isset($_POST['submit'])) {
         $data_pages = Arr::extract($_POST, array('seo_snippet', 'keywords', 'title_head'));
         $data_contacts = Arr::extract($_POST, array('main_adress', 'branch_adress'));
         try {
             $page = ORM::factory('Page', $id);
             $page->values($data_pages);
             $page->save();
             $contacts = ORM::factory('Setting', 1);
             $contacts->values($data_contacts);
             $contacts->save();
             Controller::redirect('admin/contacts');
         } catch (ORM_Validation_Exception $e) {
             $errors = $e->errors('validation');
         }
     }
     $content = View::factory('admin/contacts/v_contacts_edit');
     $content->bind('errors', $errors);
     $content->bind('data_pages', $data_pages);
     $content->bind('data_contacts', $data_contacts);
     $this->template->page_title = 'Контакты';
     $this->template->block_center = array($content);
 }
Example #30
0
 /**
  * Получение access token для авторизации
  * @return bool
  * @throws Kohana_Exception
  */
 private function get_access_token()
 {
     $params = Arr::get($_SERVER, 'QUERY_STRING');
     parse_str($params, $params);
     if (empty($params['code'])) {
         Controller::redirect($this->login_query());
     }
     if (!$params) {
         # TODO: Throw custom Exception for VK
         throw new Kohana_Exception('NO QUERY PARAMS');
     }
     if (isset($error)) {
         # TODO: Throw custom Exception for VK
         throw new Kohana_Exception('Error: ' . $error . ' Description: ' . $error_description);
     }
     $params = array('client_id' => self::$config['APP_ID'], 'code' => $params['code'], 'client_secret' => self::$config['APP_SECRET'], 'redirect_uri' => self::$config['REDIRECT_URI']);
     $resp = Request::factory(self::$config['GET_TOKEN_URI'])->method('GET')->query($params)->execute();
     $resp = json_decode($resp);
     if (empty($resp->access_token)) {
         # TODO: Throw custom Exception for VK
         throw new Kohana_Exception('Error: ' . $resp->error . ' Description: ' . $resp->error_description);
     }
     Session::instance()->set('vk_token', $resp->access_token);
     Session::instance()->set('vk_user_id', $resp->user_id);
     return true;
 }