Example #1
0
 public function save_has_many($name, $exist_ids)
 {
     $affected_ids = array();
     $post_ids = Request::current()->post($name);
     if ($post_ids === NULL) {
         $post_ids = array();
     }
     $post_ids = array_filter($post_ids, array($this, '_repeat_filter'));
     if (is_array($post_ids)) {
         if (!empty($post_ids)) {
             $post_ids = array_unique($post_ids);
         } else {
             $post_ids = array();
         }
         $del_ids = array_diff($exist_ids, $post_ids);
         $add_ids = array_diff($post_ids, $exist_ids);
         if (!empty($del_ids)) {
             $this->remove($name, $del_ids);
         }
         if (!empty($add_ids)) {
             $this->add($name, $add_ids);
         }
         $affected_ids = array_diff($exist_ids, $del_ids);
         $affected_ids = $affected_ids + $add_ids;
     }
     if (!empty($affected_ids)) {
         $affected_ids = array_combine($affected_ids, $affected_ids);
     }
     return $affected_ids;
 }
Example #2
0
 /**
  * Class constructor
  *
  * @param   array  $options  Associative array of options
  * @return  void
  */
 public function __construct($options = array())
 {
     parent::__construct($options);
     // Set document type
     $this->type = 'opensearch';
     // Set mime type
     $this->mime = 'application/opensearchdescription+xml';
     // Add the URL for self updating
     $update = new Url();
     $update->type = 'application/opensearchdescription+xml';
     $update->rel = 'self';
     $update->template = Route::url(\Request::current());
     $this->addUrl($update);
     // Add the favicon as the default image
     // Try to find a favicon by checking the template and root folder
     $dirs = array(App::get('template')->path, PATH_ROOT);
     foreach ($dirs as $dir) {
         if (file_exists($dir . DS . 'favicon.ico')) {
             $path = str_replace(PATH_ROOT . DS, '', $dir);
             $path = str_replace('\\', '/', $path);
             $favicon = new Image();
             $favicon->data = \Request::root() . $path . '/favicon.ico';
             $favicon->height = '16';
             $favicon->width = '16';
             $favicon->type = 'image/vnd.microsoft.icon';
             $this->addImage($favicon);
             break;
         }
     }
 }
Example #3
0
 public function action_get_index_collection()
 {
     // Get the post query
     $posts_query = $this->_build_query();
     // Get the count of ALL records
     $count_query = clone $posts_query;
     $total_records = (int) $count_query->select(array(DB::expr('COUNT(DISTINCT `post`.`id`)'), 'records_found'))->limit(NULL)->offset(NULL)->find_all()->get('records_found');
     // Fetch posts from db
     $posts = $posts_query->find_all();
     // Get query count
     $post_query_sql = $posts_query->last_query();
     // Generate filename using hashed query params and ids
     $filename = 'export-' . hash('sha256', implode('-', $this->request->query()) . '~' . '-' . $this->request->param('id')) . '.csv';
     // Get existing tsv file
     $tsv_file = Kohana::$config->load('media.media_upload_dir') . $filename;
     // Only generate a new if the file doesn't exist
     if (!file_exists($tsv_file)) {
         // Supported headers for the TSV file
         $tsv_headers = array("ID", "PARENT", "USER", "FORM", "TITLE", "CONTENT", "TYPE", "STATUS", "SLUG", "LOCALE", "CREATED", "UPDATED", "TAGS", "SETS");
         // Generate tab separated values (tsv)
         $tsv_text = $this->_generate_tsv($tsv_headers, $posts);
         // Write tsv to file
         $this->_write_tsv_to_file($tsv_text, $filename);
     }
     // Relative path
     $relative_path = str_replace(APPPATH . 'media' . DIRECTORY_SEPARATOR, '', Kohana::$config->load('media.media_upload_dir'));
     // Build download link
     $download_link = URL::site(Media::uri($relative_path . $filename), Request::current());
     // Respond with download link and record count
     $this->_response_payload = array('total_count' => $total_records, 'link' => $download_link);
 }
Example #4
0
 /**
  * Initializes the dropbox connection
  *
  * @param   array   $params  Any connection params needed
  * @return  \League\Flysystem\Dropbox\DropboxAdapter
  **/
 public static function init($params = [])
 {
     // Get the params
     $pparams = Plugin::params('filesystem', 'dropbox');
     if (isset($params['app_token'])) {
         $accessToken = $params['app_token'];
     } else {
         $info = ['key' => isset($params['app_key']) ? $params['app_key'] : $pparams->get('app_key'), 'secret' => isset($params['app_secret']) ? $params['app_secret'] : $pparams->get('app_secret')];
         \Session::set('dropbox.app_key', $info['key']);
         \Session::set('dropbox.app_secret', $info['secret']);
         \Session::set('dropbox.connection_to_set_up', Request::getVar('connection', 0));
         $appInfo = \Dropbox\AppInfo::loadFromJson($info);
         $clientIdentifier = 'hubzero-cms/2.0';
         $redirectUri = trim(Request::root(), '/') . '/developer/callback/dropboxAuthorize';
         $csrfTokenStore = new \Dropbox\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
         $oauth = new \Dropbox\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore);
         // Redirect to dropbox
         // We hide the return url in the state field...that's not exactly what
         // it was intended for, but it does the trick
         $return = Request::getVar('return') ? Request::getVar('return') : Request::current(true);
         $return = base64_encode($return);
         App::redirect($oauth->start($return));
     }
     $app_secret = isset($params['app_secret']) ? $params['app_secret'] : $pparams->get('app_secret');
     // Create the client
     $client = new \Dropbox\Client($accessToken, $app_secret);
     // Return the adapter
     return new \League\Flysystem\Dropbox\DropboxAdapter($client, isset($params['subdir']) ? $params['subdir'] : null);
 }
Example #5
0
File: report.php Project: anqh/anqh
    /**
     * Render view.
     *
     * @return  string
     */
    public function content()
    {
        ob_start();
        $gallery = $this->image->gallery();
        echo Form::open(Route::url('gallery_image', array('gallery_id' => Route::model_id($gallery), 'id' => $this->image->id, 'action' => 'report')), array('class' => Request::current()->is_ajax() ? 'ajaxify' : ''));
        ?>

<fieldset>

	<?php 
        echo Form::control_group(Form::input('reason', null, array('class' => 'input-block-level')), array('name' => __('Reason')), null, __('You can enter an optional reason for reporting this image, e.g. why it should be removed'));
        ?>

</fieldset>

<fieldset class="form-actions">
	<?php 
        echo Form::button('save', __('Report'), array('type' => 'submit', 'class' => 'btn btn-danger btn-large'));
        ?>
	<?php 
        echo Request::current()->is_ajax() ? '' : HTML::anchor(Route::url('gallery_image', array('gallery_id' => Route::model_id($gallery), 'id' => $this->image->id, 'action' => '')), __('Cancel'), array('class' => 'cancel'));
        ?>

	<?php 
        echo Form::csrf();
        ?>
</fieldset>

<?php 
        return ob_get_clean();
    }
Example #6
0
 /**
  *
  */
 public function before()
 {
     $is_guest = \Registry::getCurrentUser()->isGuest();
     // Дополнительные функции
     $this->InitEnvironment();
     if (!Request::current()->is_ajax()) {
         // Add Google Font
         Assets::css('Google_Font', 'https://fonts.googleapis.com/css?family=Open+Sans:400,300,300italic,400italic,600,600italic,700,700italic&subset=latin,cyrillic-ext,cyrillic');
         /*ADD google maps JS*/
         Assets::js('google_maps_api', 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=drawing&places&geometry');
         Assets::js('jQuery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js');
         Assets::css('bootstrap', 'http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css', ['media' => 'screen']);
         Assets::js('bootstrap', 'http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js');
         //GMAP Plugin js
         Assets::js('cluster', base_UI . 'js/plugins/gmap/marker.js');
         Assets::js('gmap', base_UI . 'js/plugins/gmap/gmaps.js');
         /*Базовые стили шаблона*/
         //Global Assets
         Assets::js('globalJS', base_UI . 'js/pages/global.js');
         Assets::css('awesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css');
         Assets::css('stl', base_UI . 'css/style.css');
         /*BootBox Js file*/
         Assets::js('BootBox', base_UI . 'libs/BootBox/bootbox.js');
         /*Login Js file*/
         Assets::js('LoginJs', base_UI . 'js/Auth/login.js');
         /*Register Js file*/
         Assets::js('RegisterJs', base_UI . 'js/Auth/register.js');
         //Zopim Helper js
         Assets::js('zopim', base_UI . 'js/index/zopim.js');
         //MAP js
         Assets::js('map1', base_UI . 'js/map/map.js');
         Assets::js('map2', base_UI . 'js/pages/map.js');
         Assets::js('map3', base_UI . 'js/map/catalog.js');
         $this->template = \smarty\View::init();
         $this->renderULogin();
         if (!$is_guest) {
             $access = new \Auth\Access(\Registry::getCurrentUser()->access_level);
             $user_id = \Registry::getCurrentUser()->iduser;
             $this->template->assign(['current_user' => \Registry::getCurrentUser(), 'isAdmin' => $access->get(\Auth\Access::User_Is_Admin), 'isModerator' => $access->get(\Auth\Access::User_Is_Moderator)]);
         } else {
             $this->template->assign(['current_user' => \Registry::getCurrentUser()]);
         }
         $this->template->assign(['localis' => $this->localis, 'local' => $this->i18n]);
     } else {
         $this->setJSONHeader();
         // Mobile API
         if (!isset($_POST)) {
             $error = array('status' => 'error', 'message' => 'No Data', 'code' => '2');
             echo json_encode($error);
             return;
         }
         /** @var $dbSession UserSession */
         if ($_POST['token']) {
             $condition = (new \DBCriteria())->addColumnCondition(['token' => $_POST['token']])->addCondition('`expired`>=UNIX_TIMESTAMP(NOW())');
             /** @var $dbSession UserSession */
             $sessionData = UserSession::model()->with('user')->find($condition);
             \Registry::setCurrentUser($sessionData->user);
         }
     }
 }
Example #7
0
 /**
  * CRUD controller: UPDATE
  */
 public function action_update()
 {
     $this->template->title = __('Update') . ' ' . __($this->_orm_model) . ' ' . $this->request->param('id');
     $form = new FormOrm($this->_orm_model, $this->request->param('id'));
     if ($this->request->post()) {
         if ($success = $form->submit()) {
             if (Valid::email($form->object->email, TRUE)) {
                 //check we have this email in the DB
                 $user = new Model_User();
                 $user = $user->where('email', '=', Kohana::$_POST_ORIG['formorm']['email'])->where('id_user', '!=', $this->request->param('id'))->limit(1)->find();
                 if ($user->loaded()) {
                     Alert::set(Alert::ERROR, __('A user with the email you specified already exists'));
                 } else {
                     $form->save_object();
                     Alert::set(Alert::SUCCESS, __('Item updated') . '. ' . __('Please to see the changes delete the cache') . '<br><a class="btn btn-primary btn-mini ajax-load" href="' . Route::url('oc-panel', array('controller' => 'tools', 'action' => 'cache')) . '?force=1" title="' . __('Delete cache') . '">' . __('Delete cache') . '</a>');
                     $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller())));
                 }
             } else {
                 Alert::set(Alert::ERROR, __('Invalid Email'));
             }
         } else {
             Alert::set(Alert::ERROR, __('Check form for errors'));
         }
     }
     return $this->render('oc-panel/pages/user/update', array('form' => $form));
 }
Example #8
0
 public function on_page_load()
 {
     $email_ctx_id = $this->get('email_id_ctx', 'email');
     $email = $this->_ctx->get($email_ctx_id);
     $referrer_page = Request::current()->referrer();
     $next_page = $this->get('next_url', Request::current()->referrer());
     if (!Valid::email($email)) {
         Messages::errors(__('Use a valid e-mail address.'));
         HTTP::redirect($referrer_page);
     }
     $user = ORM::factory('user', array('email' => $email));
     if (!$user->loaded()) {
         Messages::errors(__('No user found!'));
         HTTP::redirect($referrer_page);
     }
     $reflink = ORM::factory('user_reflink')->generate($user, 'forgot', array('next_url' => URL::site($this->next_url, TRUE)));
     if (!$reflink) {
         Messages::errors(__('Reflink generate error'));
         HTTP::redirect($referrer_page);
     }
     Observer::notify('admin_login_forgot_before', $user);
     try {
         Email_Type::get('user_request_password')->send(array('username' => $user->username, 'email' => $user->email, 'reflink' => Route::url('reflink', array('code' => $reflink)), 'code' => $reflink));
         Messages::success(__('Email with reflink send to address set in your profile'));
     } catch (Exception $e) {
         Messages::error(__('Something went wrong'));
     }
     HTTP::redirect($next_page);
 }
Example #9
0
 public static function topdf($data, $download = FALSE)
 {
     $bin = Kohana::config('wkhtml.paths.bin');
     if (!file_exists($bin)) {
         throw new Kohana_Exception('wkhtml binary does not exist at: ' . $bin);
     }
     // Create unique temporary file
     $uuid = uniqid('wkhtml_temp_', TRUE);
     // Store working files in cache
     $folder = Kohana::config('wkhtml.paths.temp');
     $file_in = $folder . $uuid . '.html';
     $file_out = $folder . $uuid . '.pdf';
     // Write temporary file
     file_put_contents($file_in, $data);
     // Build command
     $cmd = $bin . ' ' . escapeshellarg($file_in) . ' ' . escapeshellarg($file_out);
     // Convert file
     passthru($cmd);
     // Delete HTML file
     unlink($file_in);
     // Handle any errors
     if (!file_exists($file_out)) {
         throw new Kohana_Exception('Unknown wkhtmltopdf error.');
     }
     // Force PDF download or return cache ID
     if ($download) {
         $filename = is_string($download) ? $download : 'print.pdf';
         Request::current()->response()->send_file($file_out, $filename);
     }
     return $file_out;
 }
Example #10
0
 public function action_list()
 {
     $data = array();
     $filter = Session::instance()->get('userlistFilter', array());
     $user = ORM::factory('user');
     if ($this->isPressed('btnFilter')) {
         $filter['FIO'] = trim(Arr::get($_POST, 'FIO'));
         $filter['role'] = trim(Arr::get($_POST, 'role'));
         $filter['isActive'] = trim(Arr::get($_POST, 'isActive'));
         $filter['note'] = trim(Arr::get($_POST, 'note'));
         foreach ($filter as $key => $value) {
             if ($value == '') {
                 unset($filter[$key]);
             }
         }
         Session::instance()->set('userlistFilter', $filter);
     }
     if ($this->isPressed('btnDelete')) {
         $idList = Arr::get($_POST, 'cb', array());
         foreach ($idList as $id => $value) {
             $user = ORM::factory('user', $id);
             $user->delete();
         }
     }
     $user = ORM::factory('user');
     $data['notes'] = $user->getDistinctNotes();
     $data['filter'] = $filter;
     // получаем общее количество пользователей
     $count = ORM::factory('user')->getUserList($filter)->count();
     // передаем значение количества пользователей в модуль pagination и формируем ссылки
     $pagination = Pagination::factory(array('total_items' => $count))->route_params(array('controller' => Request::current()->controller(), 'action' => Request::current()->action()));
     $data['users'] = $user->getUserList($filter, $pagination);
     $data['pagination'] = $pagination;
     $this->tpl->content = View::factory('admin/userlist', $data);
 }
Example #11
0
 /**
  * Initializes the github connection
  *
  * @param   array   $params  Any connection params needed
  * @return  object
  **/
 public static function init($params = [])
 {
     // Get the params
     $pparams = Plugin::params('filesystem', 'github');
     $app_key = isset($params['app_key']) ? $params['app_key'] : $pparams['app_key'];
     $app_secret = isset($params['app_secret']) ? $params['app_secret'] : $pparams['app_secret'];
     \Session::set('github.app_key', $app_key);
     \Session::set('github.app_secret', $app_secret);
     $repository = isset($params['repository']) ? $params['repository'] : $pparams['repository'];
     $credentials = [];
     if (isset($params['username']) && isset($params['password'])) {
         $credentials = [Settings::AUTHENTICATE_USING_PASSWORD, $params['username'], $params['password']];
     } else {
         $accessToken = Session::get('github.token', false);
         if (!$accessToken) {
             $base = 'https://github.com/login/oauth/authorize';
             $params = '?client_id=' . $app_key;
             $scope = '&scope=user,repo';
             $return = Request::getVar('return') ? Request::getVar('return') : Request::current(true);
             $return = base64_encode($return);
             $state = '&state=' . $return;
             Session::set('github.state', $return);
             App::redirect($base . $params . $scope . $state);
         }
         $credentials = [Settings::AUTHENTICATE_USING_TOKEN, $accessToken];
     }
     $settings = new Settings($params['repository'], $credentials);
     $api = new Api(new \Github\Client(), $settings);
     // Return the adapter
     return new GithubAdapter($api);
 }
Example #12
0
 /**
  * CRUD controller: UPDATE
  */
 public function action_update()
 {
     $id_role = $this->request->param('id');
     //we do not allow modify the admin
     if ($id_role == Model_Role::ROLE_ADMIN) {
         Alert::set(Alert::WARNING, __('Admin Role can not be modified!'));
         $this->redirect(Route::url('oc-panel', array('controller' => 'role')));
     }
     $this->template->title = __('Update') . ' ' . __($this->_orm_model) . ' ' . $id_role;
     $role = new Model_Role($id_role);
     if ($this->request->post() and $role->loaded()) {
         //delete all the access
         DB::delete('access')->where('id_role', '=', $role->id_role)->execute();
         //set all the access where post = on
         foreach ($_POST as $key => $value) {
             if ($value == 'on') {
                 DB::insert('access', array('id_role', 'access'))->values(array($role->id_role, str_replace('|', '.', $key)))->execute();
             }
         }
         //saving the role params
         $role->name = core::post('name');
         $role->description = core::post('description');
         $role->save();
         Alert::set(Alert::SUCCESS, __('Item updated'));
         $this->redirect(Route::get($this->_route_name)->uri(array('controller' => Request::current()->controller())));
     }
     //getting controllers actions
     $controllers = Model_Access::list_controllers();
     //get all the access this user has
     $query = DB::select('access')->from('access')->where('id_role', '=', $id_role)->execute();
     $access_in_use = array_keys($query->as_array('access'));
     // d(in_array('access_index',$access_in_use));
     //d($access_in_use);
     return $this->render('oc-panel/pages/role/update', array('role' => $role, 'controllers' => $controllers, 'access_in_use' => $access_in_use));
 }
Example #13
0
 public function action_categories()
 {
     // Get the category model
     $categories = Jelly::select('category');
     /*
      * If the route is something like this: categories/alias-of-category/2, 
      *	 then we know that we're accessing the children of "alias-of-category" but display is limited to 2 levels only
      */
     $category = $this->request->param('category', NULL);
     $category = Jelly::select('category', $category);
     $limit = $this->request->param('limit', $this->params->get('maxLevel', -1));
     if ($category->loaded()) {
         // Get the children of the category
         $categories->where('parent_id', '=', $category->id);
     } else {
         // Just get all the 1st Level Categories
         $categories->where('level', '=', 1);
     }
     // Set the result in the View
     $items = View::factory('categories/list')->set('categories', $categories->execute())->set('limit', $limit)->set('level', 1)->render();
     // If this is an internal HMVC call, then we don't need to display the template which displays the headings
     if (Request::instance() !== Request::current()) {
         $this->request->response = $items;
         return;
     }
     // Combine the 2 views, this view loads the Title and Description, then inserts the previous view "items" above
     $this->request->response = View::factory('categories/template')->set('items', $items)->set('page_heading', $this->params->get('page_title'))->render();
 }
Example #14
0
    function walkTree($nodes, $level = 0)
    {
        static $i = 1;
        foreach ($nodes as $key => $value) {
            if ($value['start'] == 1) {
                echo '<tr>
									<td>' . $i . '</td>
									<td>' . $value['display_name'] . '</td>
									<td>' . $value['dir'] . '</td>
									<td>' . $value['date_create'] . '</td>
									<td>
										<a href="' . URL::site(Request::current()->param('language') . '/admin/folders/edit/' . $value['id']) . '">Edit</a> 
										| 
										<a href="' . URL::site(Request::current()->param('language') . '/admin/folders/delete/' . $value['id']) . '">Delete</a>
									</td>
								  </tr>' . "\n";
            } else {
                echo '<tr>
    								<td>' . $i . '</td>
    								<td>' . str_repeat('---', $level) . $value['display_name'] . '</td>
    								<td>' . $value['dir'] . '</td>
    								<td>' . $value['date_create'] . '</td>
    								<td>
										<a href="' . URL::site(Request::current()->param('language') . '/admin/folders/edit/' . $value['id']) . '">Edit</a> 
										| 
										<a href="' . URL::site(Request::current()->param('language') . '/admin/folders/delete/' . $value['id']) . '">Delete</a>
									</td>
    							  </tr>' . "\n";
            }
            $i++;
            if ($value['children']) {
                walkTree($value['children'], $level + 1);
            }
        }
    }
Example #15
0
 public static function is_backend()
 {
     if (Request::current()->directory() == 'Admin') {
         return true;
     }
     return false;
 }
Example #16
0
 public function before()
 {
     parent::before();
     if (Request::current()->is_initial()) {
         $this->auto_render = FALSE;
     }
 }
Example #17
0
	/**
	 * Generates an opening HTML form tag.
	 *
	 *     // Form will submit back to the current page using POST
	 *     echo Form::open();
	 *
	 *     // Form will submit to 'search' using GET
	 *     echo Form::open('search', array('method' => 'get'));
	 *
	 *     // When "file" inputs are present, you must include the "enctype"
	 *     echo Form::open(NULL, array('enctype' => 'multipart/form-data'));
	 *
	 * @param   string  form action, defaults to the current request URI
	 * @param   array   html attributes
	 * @return  string
	 * @uses    Request::instance
	 * @uses    URL::site
	 * @uses    HTML::attributes
	 */
	public static function open($action = NULL, array $attributes = NULL)
	{
		if ($action === NULL)
		{
			// Use the current URI
			$action = Request::current()->uri;
		}

		if ($action === '')
		{
			// Use only the base URI
			$action = Kohana::$base_url;
		}
		elseif (strpos($action, '://') === FALSE)
		{
			// Make the URI absolute
			$action = URL::site($action);
		}

		// Add the form action to the attributes
		$attributes['action'] = $action;

		// Only accept the default character set
		$attributes['accept-charset'] = Kohana::$charset;

		if ( ! isset($attributes['method']))
		{
			// Use POST method
			$attributes['method'] = 'post';
		}

		return '<form'.HTML::attributes($attributes).'>';
	}
Example #18
0
 public function before()
 {
     $this->navigation = Navigation::instance('sitemap');
     // Ищем текущую страницу в карте сайта по текущему URL
     $this->page = $this->navigation->pages()->findOneByUri(Request::current()->uri());
     // Если найдена, то рендерим шаблон для нее
     if ($this->page) {
         $this->auto_render = TRUE;
         // Указываем, нужна ли авторизация и для каких ролей доступен
         // контроллер
         $this->auth_required = $this->page->getRoles();
     }
     parent::before();
     if (!$this->page and $this->request->is_ajax() === TRUE) {
         return;
     }
     if ($this->page) {
         if (!isset($this->page->title)) {
             $this->page->title = $this->page->label;
         }
         if (!isset($this->page->meta_keywords)) {
             $this->page->meta_keywords = $this->config['view']['keywords'];
         }
         if (!isset($this->page->meta_description)) {
             $this->page->meta_description = $this->config['view']['description'];
         }
     }
     if ($this->auto_render === TRUE) {
         $this->template->content = View::factory($this->_get_uri());
     }
 }
Example #19
0
 public function action_index()
 {
     $auth = Auth::instance();
     //si el usuario esta logeado entocnes mostramos el menu
     if ($auth->logged_in()) {
         //View::set_global('pass', $auth->hash_password('admin'));
         $user = ORM::factory('users')->where('id', '=', $auth->get_user())->find();
         $session = Session::instance();
         $session->set('nombreUsuario', $user->nombre);
     } else {
         $this->request->redirect(URL::base() . 'login');
         if (isset($_POST['submit'])) {
             $validate = Validation::factory($this->request->post());
             $validate->rule('usuario', 'not_empty')->rule('password', 'not_empty');
             if ($validate->check()) {
                 $user = $auth->login(Arr::get($_POST, 'usuario'), Arr::get($_POST, 'password'));
                 if ($user) {
                     $this->request->redirect('index');
                 } else {
                     Request::current()->redirect('login');
                 }
             }
         }
         $this->template->title = 'Login';
         //$this->template->header  =  View::factory ('templates/menu');
         $this->template->content = View::factory('admin/login');
     }
 }
Example #20
0
 /**
  * Initializes the Google Drive connection
  *
  * @param   array   $params  Any connection params needed
  * @return  object
  **/
 public static function init($params = [])
 {
     // Get the params
     $pparams = Plugin::params('filesystem', 'googledrive');
     $app_id = isset($params['app_id']) && $params['app_id'] != '' ? $params['app_id'] : $pparams->get('app_id');
     $app_secret = isset($params['app_secret']) && $params['app_secret'] != '' ? $params['app_secret'] : $pparams->get('app_secret');
     $client = new \Google_Client();
     $client->setClientId($app_id);
     $client->setClientSecret($app_secret);
     $client->addScope(Google_Service_Drive::DRIVE);
     $client->setAccessType('offline');
     $client->setApprovalPrompt('force');
     $client->setIncludeGrantedScopes(true);
     if (isset($params['app_token'])) {
         $accessToken = $params['app_token'];
         // json encode turned our array into an object, we need to undo that
         $accessToken = (array) $accessToken;
     } else {
         \Session::set('googledrive.app_id', $app_id);
         \Session::set('googledrive.app_secret', $app_secret);
         \Session::set('googledrive.connection_to_set_up', Request::getVar('connection', 0));
         // Set upp a return and redirect to Google for auth
         $return = Request::getVar('return') ? Request::getVar('return') : Request::current(true);
         $return = base64_encode($return);
         $redirectUri = trim(Request::root(), '/') . '/developer/callback/googledriveAuthorize';
         $client->setRedirectUri($redirectUri);
         Session::set('googledrive.state', $return);
         App::redirect($client->createAuthUrl());
     }
     $client->setAccessToken($accessToken);
     $service = new \Google_Service_Drive($client);
     $adapter = new \Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter($service, 'root');
     return $adapter;
 }
Example #21
0
 public function before()
 {
     parent::before();
     if (Request::current()->is_initial()) {
         $this->request->action(404);
     }
 }
 /**
  * get param from request or session
  * used to easily get params and store them 
  * 
  * $sourceOrValueOrRetain
  * 'request' or null :get param from request ans store it in session
  * true : get value from session and leave it there
  * int/string : get value from session and replace it with given value
  *
  * @param string $name
  * @param mixed $valueOrGetFromRequest
  * @param boolean $storeValue
  * @return int
  */
 protected function param($name, $valueOrGetFromRequest = TRUE, $storeValue = TRUE)
 {
     // create key for param
     $key = 'active.' . $name;
     if ($valueOrGetFromRequest === TRUE) {
         // get value from get
         $value = Request::current()->param($name, FALSE);
         // store it
         if ($storeValue === TRUE) {
             $this->_state->set($key, $value);
         }
         // return it
         return $value;
     } elseif ($valueOrGetFromRequest === FALSE) {
         // get id from active, leave it there
         $value = $this->_state->get($key);
         //return it
         return $value;
     } else {
         // get value from session
         $value = $this->_state->get($key);
         // set value to value
         $this->_state->set($key, $valueOrGetFromRequest);
         //return it
         return $value;
     }
 }
Example #23
0
 public function on_page_load()
 {
     $username = Auth::get_username();
     Auth::instance()->logout(TRUE);
     Observer::notify('admin_after_logout', $username);
     HTTP::redirect($this->get('next_url', Request::current()->referrer()));
 }
Example #24
0
 public function __invoke($entities)
 {
     if (!is_array($entities)) {
         throw new FormatterException('Collection formatter requries an array of entities');
     }
     $output = ['type' => 'FeatureCollection', 'features' => []];
     foreach ($entities as $entity) {
         $geometries = [];
         foreach ($entity->values as $attribute => $values) {
             foreach ($values as $value) {
                 if ($geometry = $this->valueToGeometry($value)) {
                     $geometries[] = $geometry;
                 }
             }
         }
         if (!empty($geometries)) {
             $output['features'][] = ['type' => 'Feature', 'geometry' => ['type' => 'GeometryCollection', 'geometries' => $geometries], 'properties' => ['title' => $entity->title, 'description' => $entity->content, 'id' => $entity->id, 'url' => URL::site(Ushahidi_Rest::url($entity->getResource(), $entity->id), Request::current())]];
         }
     }
     if ($this->search->bbox) {
         if (is_array($this->search->bbox)) {
             $bbox = $this->search->bbox;
         } else {
             $bbox = explode(',', $this->search->bbox);
         }
         $output['bbox'] = $bbox;
     }
     return $output;
 }
Example #25
0
 public function action_logout()
 {
     // log user out
     Auth::instance()->logout();
     // redirect to login page
     Request::current()->redirect('');
 }
 /**
  * Query parameters setter
  * 
  * @param	array	Query parameters to set
  * @return	$this	Chainable as setter
  */
 public function query_params($params = NULL)
 {
     if (!empty($params)) {
         Request::current()->query($params);
     }
     return $this;
 }
Example #27
0
 /**
  * Hook for after parsing route
  *
  * @return void
  */
 public function onAfterRoute()
 {
     // First, check for presence of subject dn, which is the minimum required field
     if (!isset($_SERVER['SSL_CLIENT_S_DN']) || !$_SERVER['SSL_CLIENT_S_DN']) {
         \App::redirect($this->params->get('failure_location', '/invalidcert.php'));
         return;
     }
     if (\User::isGuest()) {
         // If so, redirect to login
         Request::setVar('option', 'com_users');
         Request::setVar('task', 'user.login');
         Request::setVar('authenticator', 'certificate');
         Request::setVar('return', base64_encode(\Request::current()));
         return;
     }
     // Check if user is registered and if current session is linked to cert identity
     $hzad = \Hubzero\Auth\Domain::getInstance('authentication', 'certificate', $_SERVER['SSL_CLIENT_I_DN_CN']);
     if ($link = \Hubzero\Auth\Link::getInstance($hzad->id, $_SERVER['SSL_CLIENT_S_DN_CN'])) {
         if ($link->user_id == \User::get('id')) {
             // All clear...return nothing
             return;
         }
     }
     // Otherwise, we have a cert-based user that doesn't match the current user
     Request::setVar('option', 'com_users');
     Request::setVar('task', 'user.logout');
     $this->event->stop();
 }
Example #28
0
 public function action_topic()
 {
     // init
     $topic_id = intval($this->request->param('id'));
     if ($topic_id == NULL) {
         $this->action_index();
     }
     $topic = Model_Topic::find_by_id($topic_id);
     if (!$topic) {
         throw new Exception_Page(__('common.discuss_not_found'));
     }
     $cu = $this->get_current_user();
     if ($this->request->is_post()) {
         if ($cu->submit < 1) {
             throw new Exception_Page(__('common.submit_before_topic'));
         }
         $reply = new Model_Reply();
         $reply->author_id = $cu->user_id;
         $reply->topic_id = $topic_id;
         $reply->content = $this->get_raw_post('content');
         $reply->save();
         $this->redirect(Request::current()->uri());
     }
     $relies = $topic->replies();
     $this->template_data['the_topic'] = $topic;
     $this->template_data['relies'] = $relies;
     $this->template_data['title'] = $topic->title;
 }
Example #29
0
 public function before()
 {
     parent::before();
     // Borrowed from userguide
     if (isset($_GET['lang'])) {
         $lang = $_GET['lang'];
         // Make sure the translations is valid
         $translations = Kohana::message('langify', 'translations');
         if (in_array($lang, array_keys($translations))) {
             // Set the language cookie
             Cookie::set('langify_language', $lang, Date::YEAR);
         }
         // Reload the page
         $this->request->redirect($this->request->uri());
     }
     // Set the translation language
     I18n::$lang = Cookie::get('langify_language', Kohana::config('langify')->lang);
     // Borrowed from Vendo
     // Automaticly load a view class based on action.
     $view_name = $this->view_prefix . Request::current()->action();
     if (Kohana::find_file('classes', strtolower(str_replace('_', '/', $view_name)))) {
         $this->view = new $view_name();
         $this->view->set('version', $this->version);
     }
 }
Example #30
0
 /**
  * Validation rule for checking a valid token
  *
  * @param   string  $namespace - the token string to check for
  * @return  bool
  */
 public static function valid($namespace = NULL)
 {
     if ($namespace === NULL) {
         $namespace = URL::title(Request::current()->uri());
     }
     return Request::$current->post('csrf_' . $namespace) === self::token($namespace);
 }