Example #1
0
 /**
  * Displays all feeds.
  */
 public function index()
 {
     $this->template->header->this_page = Kohana::lang('ui_admin.feeds');
     $this->template->content = new View('feed/feeds');
     // Pagination
     $pagination = new Pagination(array('query_string' => 'page', 'items_per_page' => (int) Kohana::config('settings.items_per_page'), 'total_items' => ORM::factory('feed_item')->count_all()));
     $feeds = ORM::factory('feed_item')->orderby('item_date', 'desc')->find_all((int) Kohana::config('settings.items_per_page'), $pagination->sql_offset);
     $this->template->content->feeds = $feeds;
     //Set default as not showing pagination. Will change below if necessary.
     $this->template->content->pagination = '';
     // Pagination and Total Num of Report Stats
     $plural = $pagination->total_items == 1 ? '' : 's';
     if ($pagination->total_items > 0) {
         $current_page = $pagination->sql_offset / (int) Kohana::config('settings.items_per_page') + 1;
         $total_pages = ceil($pagination->total_items / (int) Kohana::config('settings.items_per_page'));
         if ($total_pages > 1) {
             // Paginate results
             $pagination_stats = Kohana::lang('ui_admin.showing_page') . ' ' . $current_page . ' ' . Kohana::lang('ui_admin.of') . ' ' . $total_pages . ' ' . Kohana::lang('ui_admin.pages');
             $this->template->content->pagination_stats = $pagination_stats;
             $this->template->content->pagination = $pagination;
         } else {
             // No pagination
             $this->template->content->pagination_stats = $pagination->total_items . ' ' . Kohana::lang('ui_admin.feeds');
         }
     } else {
         $this->template->content->pagination_stats = $pagination->total_items . ' ' . Kohana::lang('ui_admin.feeds');
     }
 }
Example #2
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 #3
0
 public static function instance()
 {
     if (!Kotwig::$instance) {
         Kotwig::$instance = new static();
         // Load Twig configuration
         Kotwig::$instance->config = Kohana::$config->load('kotwig');
         // Create the the loader
         $views = Kohana::include_paths();
         $look_in = array();
         foreach ($views as $key => $view) {
             $dir = $view . Kotwig::$instance->config->templates;
             if (is_dir($dir)) {
                 $look_in[] = $dir;
             }
         }
         $loader = new Twig_Loader_Filesystem($look_in);
         // Set up Twig
         Kotwig::$instance->twig = new Twig_Environment($loader, Kotwig::$instance->config->environment);
         foreach (Kotwig::$instance->config->extensions as $extension) {
             // Load extensions
             Kotwig::$instance->twig->addExtension(new $extension());
         }
         foreach (Kotwig::$instance->config->globals as $global => $object) {
             // Load globals
             Kotwig::$instance->twig->addGlobal($global, $object);
         }
         foreach (Kotwig::$instance->config->filters as $filter => $object) {
             // Load filters
             Kotwig::$instance->twig->addFilter($filter, $object);
         }
     }
     return Kotwig::$instance;
 }
Example #4
0
 public function execute($address)
 {
     Geocode_Yahoo::$_cacheKey = Geocode_Yahoo::CACHE_PREFIX . md5($address);
     $data = Kohana::cache(Geocode_Yahoo::$_cacheKey);
     if ($data === NULL) {
         try {
             $request = Geocode_Yahoo::API_URL . '?q=' . urlencode($address) . '&appid=' . $this->api_key . '&flags=' . $this->flags . '&locale=' . $this->locale;
             $sData = Request::factory($request)->execute()->body();
             $data = unserialize($sData);
             if ($data['ResultSet']['Error'] === 0 && $data['ResultSet']['Found'] > 0) {
                 $resultsArray = array();
                 foreach ($data['ResultSet']['Result'] as $k => $result) {
                     $resultsArray[] = array('lat' => (double) $result['latitude'], 'lng' => (double) $result['longitude'], 'zip' => (string) $result['postal'], 'city' => (string) $result['city'], 'state' => (string) $result['state'], 'country' => (string) $result['countrycode'], 'street_house' => (string) $result['street'] . ' ' . $result['house']);
                 }
                 $data = array('dataCount' => $data['ResultSet']['Found'], 'dataArray' => $resultsArray);
                 Kohana::cache(Geocode_Yahoo::$_cacheKey, $data, Geocode_Yahoo::CACHE_TIME);
             } else {
                 return FALSE;
             }
         } catch (Exception $e) {
             return FALSE;
         }
     }
     return $data;
 }
 public static function add($controller_name, $method_name, $parameters = array(), $priority = 5, $application_path = '')
 {
     if ($priority < 1 or $priority > 10) {
         Kohana::log('error', 'The priority of the task was out of range!');
         return FALSE;
     }
     $application_path = empty($application_path) ? APPPATH : $application_path;
     $old_module_list = Kohana::config('core.modules');
     Kohana::config_set('core.modules', array_merge($old_module_list, array($application_path)));
     // Make sure the controller name and method are valid
     if (Kohana::auto_load($controller_name)) {
         // Only add it to the queue if the controller method exists
         if (Kohana::config('queue.validate_methods') and !method_exists($controller_name, $method_name)) {
             Kohana::log('error', 'The method ' . $controller_name . '::' . $method_name . ' does not exist.');
             return FALSE;
         }
         // Add the action to the run queue with the priority
         $task = new Task_Model();
         $task->set_fields(array('application' => $application_path, 'class' => $controller_name, 'method' => $method_name, 'params' => serialize($parameters), 'priority' => $priority));
         $task->save();
         // Restore the module list
         Kohana::config_set('core.modules', $old_module_list);
         return TRUE;
     }
     Kohana::log('error', 'The class ' . $controller_name . ' does not exist.');
     return FALSE;
 }
Example #6
0
 /**
  * Loads encryption configuration and validates the data.
  *
  * @param   array|string      custom configuration or config group name
  * @throws  Kohana_Exception
  */
 public function __construct($config = FALSE)
 {
     if (!defined('MCRYPT_ENCRYPT')) {
         throw new Kohana_Exception('encrypt.requires_mcrypt');
     }
     if (is_string($config)) {
         $name = $config;
         // Test the config group name
         if (($config = Kohana::config('encryption.' . $config)) === NULL) {
             throw new Kohana_Exception('encrypt.undefined_group', $name);
         }
     }
     if (is_array($config)) {
         // Append the default configuration options
         $config += Kohana::config('encryption.default');
     } else {
         // Load the default group
         $config = Kohana::config('encryption.default');
     }
     if (empty($config['key'])) {
         throw new Kohana_Exception('encrypt.no_encryption_key');
     }
     // Find the max length of the key, based on cipher and mode
     $size = mcrypt_get_key_size($config['cipher'], $config['mode']);
     if (strlen($config['key']) > $size) {
         // Shorten the key to the maximum size
         $config['key'] = substr($config['key'], 0, $size);
     }
     // Find the initialization vector size
     $config['iv_size'] = mcrypt_get_iv_size($config['cipher'], $config['mode']);
     // Cache the config in the object
     $this->config = $config;
     Kohana::log('debug', 'Encrypt Library initialized');
 }
 /**
  * Sets the config for the class.
  *
  * @param : array  - config passed from the payment library constructor
  */
 public function __construct($config)
 {
     $this->test_mode = $config['test_mode'];
     if ($this->test_mode) {
         $this->fields['USER'] = $config['SANDBOX_USER'];
         $this->fields['PWD'] = $config['SANDBOX_PWD'];
         $this->fields['SIGNATURE'] = $config['SANDBOX_SIGNATURE'];
         $this->fields['ENDPOINT'] = $config['SANDBOX_ENDPOINT'];
     } else {
         $this->fields['USER'] = $config['USER'];
         $this->fields['PWD'] = $config['PWD'];
         $this->fields['SIGNATURE'] = $config['SIGNATURE'];
         $this->fields['ENDPOINT'] = $config['ENDPOINT'];
     }
     $this->fields['VERSION'] = $config['VERSION'];
     $this->fields['CURRENCYCODE'] = $config['CURRENCYCODE'];
     $this->required_fields['USER'] = !empty($config['USER']);
     $this->required_fields['PWD'] = !empty($config['PWD']);
     $this->required_fields['SIGNATURE'] = !empty($config['SIGNATURE']);
     $this->required_fields['ENDPOINT'] = !empty($config['ENDPOINT']);
     $this->required_fields['VERSION'] = !empty($config['VERSION']);
     $this->required_fields['CURRENCYCODE'] = !empty($config['CURRENCYCODE']);
     $this->curl_config = $config['curl_config'];
     Kohana::log('debug', 'Paypalpro Payment Driver Initialized');
 }
Example #8
0
File: upload.php Project: azuya/Wi3
 /**
  * Save an uploaded file to a new location. If no filename is provided,
  * the original filename will be used, with a unique prefix added.
  *
  * This method should be used after validating the $_FILES array:
  *
  *     if ($array->check())
  *     {
  *         // Upload is valid, save it
  *         Upload::save($_FILES['file']);
  *     }
  *
  * @param   array    uploaded file data
  * @param   string   new filename
  * @param   string   new directory
  * @param   integer  chmod mask
  * @return  string   on success, full path to new file
  * @return  FALSE    on failure
  */
 public static function save(array $file, $filename = NULL, $directory = NULL, $chmod = 0644)
 {
     if (!isset($file['tmp_name']) or !is_uploaded_file($file['tmp_name'])) {
         // Ignore corrupted uploads
         return FALSE;
     }
     if ($filename === NULL) {
         // Use the default filename, with a timestamp pre-pended
         $filename = uniqid() . $file['name'];
     }
     if (Upload::$remove_spaces === TRUE) {
         // Remove spaces from the filename
         $filename = preg_replace('/\\s+/', '_', $filename);
     }
     if ($directory === NULL) {
         // Use the pre-configured upload directory
         $directory = Upload::$default_directory;
     }
     if (!is_dir($directory) or !is_writable(realpath($directory))) {
         throw new Kohana_Exception('Directory :dir must be writable', array(':dir' => Kohana::debug_path($directory)));
     }
     // Make the filename into a complete path
     $filename = realpath($directory) . DIRECTORY_SEPARATOR . $filename;
     if (move_uploaded_file($file['tmp_name'], $filename)) {
         if ($chmod !== FALSE) {
             // Set permissions on filename
             chmod($filename, $chmod);
         }
         // Return new file path
         return $filename;
     }
     return FALSE;
 }
Example #9
0
 /**
  * 用户登陆
  * @method POST
  */
 public function login()
 {
     $post = $this->get_data();
     $mobile = trim($post['mobile']);
     $zone_code = $post['zone_code'] ? trim($post['zone_code']) : ($post['zonecode'] ? trim($post['zonecode']) : '86');
     $zone_code = str_replace('+', '', $zone_code);
     $password = trim($post['password']);
     if (empty($mobile)) {
         $this->send_response(400, NULL, '40001:手机号为空');
     }
     if (!international::check_is_valid($zone_code, $mobile)) {
         $this->send_response(400, NULL, '40002:手机号码格式不对');
     }
     if ($password == "") {
         $this->send_response(400, NULL, '40003:密码为空');
     }
     $user = $this->model->get_user_by_mobile($zone_code, $mobile);
     if (!$user) {
         $this->send_response(400, NULL, Kohana::lang('user.mobile_not_register'));
     }
     if (!password_verify($password, $user['password'])) {
         $this->send_response(400, NULL, Kohana::lang('user.username_password_not_match'));
     }
     $token = $this->model->create_token(3600, TRUE, array('zone_code' => $user['zone_code'], 'mobile' => $user['mobile'], 'id' => (int) $user['id']));
     $this->send_response(200, array('id' => (int) $user['uid'], 'name' => $user['username'], 'avatar' => sns::getavatar($user['uid']), 'access_token' => $token['access_token'], 'refresh_token' => $token['refresh_token'], 'expires_in' => $token['expires_in']));
 }
Example #10
0
 /**
  * Generates a help list for all tasks
  *
  * @return null
  */
 protected function _execute(array $params)
 {
     $tasks = $this->_compile_task_list(Kohana::list_files('classes/task'));
     $view = new View('minion/help/list');
     $view->tasks = $tasks;
     echo $view;
 }
Example #11
0
 /**
  * Application initialization
  *     - Loads the plugins
  *     - Sets the cookie configuration
  */
 public static function init()
 {
     // Set defaule cache configuration
     Cache::$default = Kohana::$config->load('site')->get('default_cache');
     try {
         $cache = Cache::instance()->get('dummy' . rand(0, 99));
     } catch (Exception $e) {
         // Use the dummy driver
         Cache::$default = 'dummy';
     }
     // Load the plugins
     Swiftriver_Plugins::load();
     // Add the current default theme to the list of modules
     $theme = Swiftriver::get_setting('site_theme');
     if (isset($theme) and $theme != "default") {
         Kohana::modules(array_merge(array('themes/' . $theme->value => THEMEPATH . $theme->value), Kohana::modules()));
     }
     // Clean up
     unset($active_plugins, $theme);
     // Load the cookie configuration
     $cookie_config = Kohana::$config->load('cookie');
     Cookie::$httponly = TRUE;
     Cookie::$salt = $cookie_config->get('salt', Swiftriver::DEFAULT_COOKIE_SALT);
     Cookie::$domain = $cookie_config->get('domain') or '';
     Cookie::$secure = $cookie_config->get('secure') or FALSE;
     Cookie::$expiration = $cookie_config->get('expiration') or 0;
     // Set the default site locale
     I18n::$lang = Swiftriver::get_setting('site_locale');
 }
 public function __construct($group = 'default')
 {
     $this->config = Kohana::config('migrations');
     $this->group = $group;
     $this->config['path'] = $this->config['path'][$group];
     $this->config['info'] = $this->config['path'] . $this->config['info'] . '/';
 }
Example #13
0
File: i18n.php Project: ascseb/core
 /**
  * Returns the translation table for a given language.
  *
  * @param   string   language to load
  * @return  array
  */
 public static function load($lang)
 {
     if (!isset(I18n::$_cache[$lang])) {
         // Separate the language and locale
         list($language, $locale) = explode('-', strtolower($lang), 2);
         // Start a new translation table
         $table = array();
         // Add the non-specific language strings
         if ($files = Kohana::find_file('i18n', $language)) {
             foreach ($files as $file) {
                 // Merge the language strings into the translation table
                 $table = array_merge($table, require $file);
             }
         }
         // Add the locale-specific language strings
         if ($files = Kohana::find_file('i18n', $language . '/' . $locale)) {
             foreach ($files as $file) {
                 // Merge the locale strings into the translation table
                 $table = array_merge($table, require $file);
             }
         }
         // Cache the translation table locally
         I18n::$_cache[$lang] = $table;
     }
     return I18n::$_cache[$lang];
 }
Example #14
0
 public function index()
 {
     role::check('user_charge_orders');
     /* 初始化默认查询条件 */
     $user_query_struct = array('where' => array(), 'like' => array(), 'orderby' => array('id' => "DESC"), 'limit' => array('per_page' => 20, 'offset' => 0));
     /* 用户列表模板 */
     $this->template->content = new View("user/user_charge_orders");
     /* 搜索功能 */
     $search_arr = array('order_num');
     $search_value = $this->input->get('search_value');
     $where_view = array();
     $user_query_struct['like']['order_num'] = $search_value;
     //$user_query_struct['like']['ret_order_num'] = $search_value;
     $where_view['search_value'] = $search_value;
     /* 每页显示条数 */
     $per_page = controller_tool::per_page();
     $user_query_struct['limit']['per_page'] = $per_page;
     /* 调用分页 */
     $this->pagination = new Pagination(array('total_items' => User_chargeService::get_instance()->query_count($user_query_struct), 'items_per_page' => $per_page));
     //d($this->pagination->sql_offset);
     $user_query_struct['limit']['offset'] = $this->pagination->sql_offset;
     $users = User_chargeService::get_instance()->lists($user_query_struct);
     $userobj = user::get_instance();
     foreach ($users as $key => $rowuser) {
         $users[$key]['userinfo'] = $userobj->get($rowuser['user_id']);
     }
     /* 调用列表 */
     $this->template->content->user_list = $users;
     $this->template->content->where = $where_view;
     $this->template->content->pay_banks = Kohana::config('pay_banks');
 }
Example #15
0
 public function print_proxy($site_key, $file_id)
 {
     // This function retrieves the full-sized image for fotomoto.
     //   As this function by-passes normal Gallery security, a private
     //   site-key is used to try and prevent people other then fotomoto
     //   from finding the URL.
     // If the site key doesn't match, display a 404 error.
     if ($site_key != module::get_var("fotomotorw", "fotomoto_private_key")) {
         throw new Kohana_404_Exception();
     }
     // Load the photo from the provided id.  If the id# is invalid, display a 404 error.
     $item = ORM::factory("item", $file_id);
     if (!$item->loaded()) {
         throw new Kohana_404_Exception();
     }
     // If the image file doesn't exist for some reason, display a 404 error.
     if (!file_exists($item->file_path())) {
         throw new Kohana_404_Exception();
     }
     // Display the image.
     header("Content-Type: {$item->mime_type}");
     Kohana::close_buffers(false);
     $fd = fopen($item->file_path(), "rb");
     fpassthru($fd);
     fclose($fd);
 }
    /**
     * Creates the required database tables for the smssync plugin
     */
    public function run_install()
    {
        // Create the database tables.
        // Also include table_prefix in name
        $this->db->query('CREATE TABLE IF NOT EXISTS `' . Kohana::config('database.default.table_prefix') . 'densitymap_geometry` (
				  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
				  `category_id` int(11) NOT NULL,
				  `kml_file` varchar(200) default NULL,
				  `label_lat` double NOT NULL DEFAULT \'0\',
  				  `label_lon` double NOT NULL DEFAULT \'0\',
				  PRIMARY KEY (`id`)
				) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1');
        //check and see if the densitymap_geometry table already has the label_lat and label_lon columns. If not make it
        $result = $this->db->query('DESCRIBE `' . Kohana::config('database.default.table_prefix') . 'densitymap_geometry`');
        $has_lat = false;
        $has_lon = false;
        foreach ($result as $row) {
            if ($row->Field == "label_lat") {
                $has_lat = true;
            }
            if ($row->Field == "label_lon") {
                $has_lon = true;
            }
        }
        if (!$has_lat) {
            $this->db->query('ALTER TABLE `' . Kohana::config('database.default.table_prefix') . 'densitymap_geometry` ADD `label_lat` double NOT NULL DEFAULT \'0\'');
        }
        if (!$has_lon) {
            $this->db->query('ALTER TABLE `' . Kohana::config('database.default.table_prefix') . 'densitymap_geometry` ADD `label_lon` double NOT NULL DEFAULT \'0\'');
        }
    }
Example #17
0
 /**
  * Delete image
  * @return void
  * @param integer id of item
  * @param integer id of picture
  * @param string dir with images
  */
 public function delete_image($id, $image, $dir)
 {
     // Check for user permission
     if (user::is_got()) {
         // Page settings
         $this->set_title(Kohana::lang('gallery.delete_image'));
         $this->add_breadcrumb(Kohana::lang('gallery.delete_image'), url::current());
         // Set redirect URL
         if (isset($_POST['redirect'])) {
             $redirect = $_POST['redirect'];
         } else {
             $redirect = request::referrer();
         }
         $form = array('redirect' => $redirect);
         if ($_POST) {
             if (isset($_POST['yes'])) {
                 // Clicked on yes = delete image
                 unlink('./data/' . $dir . '/' . $id . '_' . $image . '.jpg');
                 unlink('./data/' . $dir . '/' . $id . '_' . $image . '_m.jpg');
                 url::redirect($form['redirect']);
             } else {
                 url::redirect($form['redirect']);
             }
         }
         // View
         $this->template->content = new View('admin/delete_image');
         $this->template->content->form = $form;
     }
 }
 /** 
  * Upload function for a JNCC style designations spreadsheet.
  */
 public function upload_csv()
 {
     try {
         // We will be using a POST array to send data, and presumably a FILES array for the
         // media.
         // Upload size
         $ups = Kohana::config('indicia.maxUploadSize');
         $_FILES = Validation::factory($_FILES)->add_rules('csv_upload', 'upload::valid', 'upload::required', 'upload::type[csv]', "upload::size[{$ups}]");
         if (count($_FILES) === 0) {
             echo "No file was uploaded.";
         } elseif ($_FILES->validate()) {
             if (array_key_exists('name_is_guid', $_POST) && $_POST['name_is_guid'] == 'true') {
                 $finalName = strtolower($_FILES['csv_upload']['name']);
             } else {
                 $finalName = time() . strtolower($_FILES['csv_upload']['name']);
             }
             $fTmp = upload::save('csv_upload', $finalName);
             url::redirect('taxon_designation/import_progress?file=' . urlencode(basename($fTmp)));
         } else {
             kohana::log('error', 'Validation errors uploading file ' . $_FILES['csv_upload']['name']);
             kohana::log('error', print_r($_FILES->errors('form_error_messages'), true));
             throw new ValidationError('Validation error', 2004, $_FILES->errors('form_error_messages'));
         }
     } catch (Exception $e) {
         $this->handle_error($e);
     }
 }
Example #19
0
 public function show($movie)
 {
     if (!is_object($movie)) {
         // show() must be public because we route to it in url::parse_url(), so make
         // sure that we're actually receiving an object
         Kohana::show_404();
     }
     access::required("view", $movie);
     $where = array(array("type", "!=", "album"));
     $position = $movie->parent()->get_position($movie, $where);
     if ($position > 1) {
         list($previous_item, $ignore, $next_item) = $movie->parent()->children(3, $position - 2, $where);
     } else {
         $previous_item = null;
         list($next_item) = $movie->parent()->viewable()->children(1, $position, $where);
     }
     $template = new Theme_View("page.html", "item", "movie");
     $template->set_global("item", $movie);
     $template->set_global("children", array());
     $template->set_global("children_count", 0);
     $template->set_global("parents", $movie->parents());
     $template->set_global("next_item", $next_item);
     $template->set_global("previous_item", $previous_item);
     $template->set_global("sibling_count", $movie->parent()->viewable()->children_count($where));
     $template->set_global("position", $position);
     $template->content = new View("movie.html");
     $movie->view_count++;
     $movie->save();
     print $template;
 }
function error_404()
{
    if (Kohana::$instance == NULL) {
        Kohana::$instance = new Errors_Controller();
    }
    Kohana::show_404(null, 'common/error_404');
}
Example #21
0
 /**
  * Tests that the storage location is a directory and is writable.
  */
 public function __construct($filename)
 {
     // Get the directory name
     $directory = str_replace('\\', '/', realpath(pathinfo($filename, PATHINFO_DIRNAME))) . '/';
     // Set the filename from the real directory path
     $filename = $directory . basename($filename);
     // Make sure the cache directory is writable
     if (!is_dir($directory) or !is_writable($directory)) {
         throw new Kohana_Exception('cache.unwritable', $directory);
     }
     // Make sure the cache database is writable
     if (is_file($filename) and !is_writable($filename)) {
         throw new Kohana_Exception('cache.unwritable', $filename);
     }
     // Open up an instance of the database
     $this->db = new SQLiteDatabase($filename, '0666', $error);
     // Throw an exception if there's an error
     if (!empty($error)) {
         throw new Kohana_Exception('cache.driver_error', sqlite_error_string($error));
     }
     $query = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'caches'";
     $tables = $this->db->query($query, SQLITE_BOTH, $error);
     // Throw an exception if there's an error
     if (!empty($error)) {
         throw new Kohana_Exception('cache.driver_error', sqlite_error_string($error));
     }
     if ($tables->numRows() == 0) {
         Kohana::log('error', 'Cache: Initializing new SQLite cache database');
         // Issue a CREATE TABLE command
         $this->db->unbufferedQuery(Kohana::config('cache_sqlite.schema'));
     }
 }
Example #22
0
 /**
  * Processes incoming text
  */
 public function action_index()
 {
     $this->request->headers['Content-type'] = 'image/png';
     // Grab text and styles
     $text = arr::get($_GET, 'text');
     $styles = $_GET;
     $hover = FALSE;
     try {
         // Create image
         $img = new PNGText($text, $styles);
         foreach ($styles as $key => $value) {
             if (substr($key, 0, 6) == 'hover-') {
                 // Grab hover associated styles and override existing styles
                 $hover = TRUE;
                 $styles[substr($key, 6)] = $value;
             }
         }
         if ($hover) {
             // Create new hover image and stack it
             $hover = new PNGText($text, $styles);
             $img->stack($hover);
         }
         echo $img->draw();
     } catch (Exception $e) {
         if (Kohana::config('pngtext.debug')) {
             // Dump error message in an image form
             $img = imagecreatetruecolor(strlen($e->getMessage()) * 6, 16);
             imagefill($img, 0, 0, imagecolorallocate($img, 255, 255, 255));
             imagestring($img, 2, 0, 0, $e->getMessage(), imagecolorallocate($img, 0, 0, 0));
             echo imagepng($img);
         }
     }
 }
 /**
  * Loads ushahidi themes
  */
 public function register()
 {
     // Array to hold all the CSS files
     $theme_css = array();
     // 1. Load the default theme
     Kohana::config_set('core.modules', array_merge(array(THEMEPATH . "default"), Kohana::config("core.modules")));
     $css_url = Kohana::config("cache.cdn_css") ? Kohana::config("cache.cdn_css") : url::base();
     // HACK: don't include the default style.css if using the ccnz theme
     if (Kohana::config("settings.site_style") != "ccnz") {
         $theme_css[] = $css_url . "themes/default/css/style.css";
     }
     // 2. Extend the default theme
     if (Kohana::config("settings.site_style") != "default") {
         $theme = THEMEPATH . Kohana::config("settings.site_style");
         Kohana::config_set('core.modules', array_merge(array($theme), Kohana::config("core.modules")));
         if (is_dir($theme . '/css')) {
             $css = dir($theme . '/css');
             // Load all the themes css files
             while (($css_file = $css->read()) !== FALSE) {
                 if (preg_match('/\\.css/i', $css_file)) {
                     $theme_css[] = url::base() . "themes/" . Kohana::config("settings.site_style") . "/css/" . $css_file;
                 }
             }
         }
     }
     Kohana::config_set('settings.site_style_css', $theme_css);
 }
Example #24
0
 /**
  * Returns the singleton instance of HTML Purifier. If no instance has
  * been created, a new instance will be created. Configuration options
  * for HTML Purifier can be set in `APPPATH/config/purifier.php` in the
  * "settings" key.
  *
  *     $purifier = Security::htmlpurifier();
  *
  * @return  HTMLPurifier
  */
 public static function htmlpurifier()
 {
     if (!Security::$htmlpurifier) {
         if (!class_exists('HTMLPurifier_Config', FALSE)) {
             if (kohana::$config->load('purifier')->get('preload')) {
                 // Load the all of HTML Purifier right now.
                 // This increases performance with a slight hit to memory usage.
                 require Kohana::find_file('vendor', 'htmlpurifier/library/HTMLPurifier.includes');
             }
             // Load the HTML Purifier auto loader
             require Kohana::find_file('vendor', 'htmlpurifier/library/HTMLPurifier.auto');
         }
         // Create a new configuration object
         $config = HTMLPurifier_Config::createDefault();
         if (!kohana::$config->load('purifier')->get('finalize')) {
             // Allow configuration to be modified
             $config->autoFinalize = FALSE;
         }
         // Use the same character set as Kohana
         $config->set('Core.Encoding', Kohana::$charset);
         if (is_array($settings = kohana::$config->load('purifier')->get('settings'))) {
             // Load the settings
             $config->loadArray($settings);
         }
         // Configure additional options
         $config = Security::configure($config);
         // Create the purifier instance
         Security::$htmlpurifier = new HTMLPurifier($config);
     }
     return Security::$htmlpurifier;
 }
Example #25
0
 /**
  * 改变状态
  */
 function do_active($id)
 {
     //权限验证
     role::check('user_charge');
     if (!$id) {
         remind::set(Kohana::lang('o_global.bad_request'), 'user/user_charge');
     }
     $db = Database::instance();
     $data = array_shift($db->query('SELECT * FROM user_charge_order WHERE id=' . $id)->result_array(false));
     if ($data['id'] <= 0 || $data['status'] > 0) {
         remind::set(Kohana::lang('o_global.bad_request'), 'user/user_charge');
     }
     $logodata = array();
     $logodata['manager_id'] = $this->manager_id;
     $logodata['ip'] = tool::get_str_ip();
     $logodata['user_log_type'] = 27;
     $logodata['method'] = __CLASS__ . '::' . __METHOD__ . '()';
     $logodata['memo'] = "充值订单号:" . $data['order_num'] . ", 购买拍点数:" . $data['price'] . ", 充值金额:" . $data['money'];
     $sql = "UPDATE user_charge_order SET status=1 WHERE id='" . $id . "' ";
     if ($db->query($sql)) {
         //充值用户Money
         $sql_reward = "UPDATE users \r\n                            SET user_money = user_money+" . $data['price'] . "\r\n                            WHERE id='" . $data['user_id'] . "'\r\n                          ";
         $db->query($sql_reward);
         //操作log
         ulog::add($logodata);
         remind::set(Kohana::lang('o_global.update_success'), 'user/user_charge', 'success');
     } else {
         //操作log
         ulog::add($logodata, 1);
         remind::set(Kohana::lang('o_global.update_error'), 'user/user_charge', 'error');
     }
 }
Example #26
0
 public function activate($validation_key)
 {
     if (!IN_PRODUCTION) {
         $profiler = new Profiler();
     }
     // TODO: Figure out where to store magic constants.
     if ($validation_key && strlen($validation_key) == 32) {
         $db = Database::instance();
         $email_users_set = $db->select('email_users.email', 'email_users.is_validated', 'user_details.public_api_key', 'user_details.private_api_key')->from('email_users')->join('user_details', array('email_users.user_id' => 'user_details.id'))->where('validation_key', $validation_key)->limit(1)->get();
         if (count($email_users_set)) {
             $email_user_row = null;
             foreach ($email_users_set as $row) {
                 $email_user_row = $row;
                 break;
             }
             if (!$email_user_row->is_validated) {
                 $db->from('email_users')->set('is_validated', '1')->set('validation_key', 'NULL', $disable_escaping = true)->where('email', $email_user_row->email)->update();
             }
             if ($email_user_row->public_api_key) {
                 $this->render_activation_succeeded_view(Kohana::lang('account_messages.activation.success_with_api_keys'));
             } else {
                 $this->render_activation_succeeded_view(Kohana::lang('account_messages.activation.success_without_api_keys'));
             }
         } else {
             $this->render_activation_failed_view(Kohana::lang('account_messages.activation.key_not_found'));
         }
     } else {
         $this->render_activation_failed_view(Kohana::lang('account_messages.activation.key_not_found'));
     }
 }
Example #27
0
 /**
  * Attempts to load a view and pre-load view data.
  *
  * @throws  Kohana_Exception  if the requested view cannot be found
  * @param   string  $name view name
  * @param   string  $page_type page type: album, photo, tags, etc
  * @param   string  $theme_name view name
  * @return  void
  */
 public function __construct($name, $page_type)
 {
     $theme_name = module::get_var("gallery", "active_site_theme");
     if (!file_exists("themes/{$theme_name}")) {
         module::set_var("gallery", "active_site_theme", "default");
         theme::load_themes();
         Kohana::log("error", "Unable to locate theme '{$theme_name}', switching to default theme.");
     }
     parent::__construct($name);
     $this->theme_name = module::get_var("gallery", "active_site_theme");
     if (user::active()->admin) {
         $this->theme_name = Input::instance()->get("theme", $this->theme_name);
     }
     $this->item = null;
     $this->tag = null;
     $this->set_global("theme", $this);
     $this->set_global("user", user::active());
     $this->set_global("page_type", $page_type);
     $this->set_global("page_title", null);
     if ($page_type == "album") {
         $this->set_global("thumb_proportion", $this->thumb_proportion());
     }
     $maintenance_mode = Kohana::config("core.maintenance_mode", false, false);
     if ($maintenance_mode) {
         message::warning(t("This site is currently in maintenance mode"));
     }
 }
Example #28
0
 private function _dump_database()
 {
     // We now have a clean install with just the packages that we want.  Make sure that the
     // database is clean too.
     $i = 1;
     foreach (array("dashboard_sidebar", "dashboard_center", "site_sidebar") as $key) {
         $blocks = array();
         foreach (unserialize(module::get_var("gallery", "blocks_{$key}")) as $rnd => $value) {
             $blocks[++$i] = $value;
         }
         module::set_var("gallery", "blocks_{$key}", serialize($blocks));
     }
     Database::instance()->query("TRUNCATE {caches}");
     Database::instance()->query("TRUNCATE {sessions}");
     Database::instance()->query("TRUNCATE {logs}");
     db::build()->update("users")->set(array("password" => ""))->where("id", "in", array(1, 2))->execute();
     $dbconfig = Kohana::config('database.default');
     $conn = $dbconfig["connection"];
     $sql_file = DOCROOT . "installer/install.sql";
     if (!is_writable($sql_file)) {
         print "{$sql_file} is not writeable";
         return;
     }
     $command = sprintf("mysqldump --compact --skip-extended-insert --add-drop-table %s %s %s %s > {$sql_file}", escapeshellarg("-h{$conn['host']}"), escapeshellarg("-u{$conn['user']}"), $conn['pass'] ? escapeshellarg("-p{$conn['pass']}") : "", escapeshellarg($conn['database']));
     exec($command, $output, $status);
     if ($status) {
         print "<pre>";
         print "{$command}\n";
         print "Failed to dump database\n";
         print implode("\n", $output);
         return;
     }
     // Post-process the sql file
     $buf = "";
     $root = ORM::factory("item", 1);
     $root_created_timestamp = $root->created;
     $root_updated_timestamp = $root->updated;
     $table_name = "";
     foreach (file($sql_file) as $line) {
         // Prefix tables
         $line = preg_replace("/(CREATE TABLE|IF EXISTS|INSERT INTO) `{$dbconfig['table_prefix']}(\\w+)`/", "\\1 {\\2}", $line);
         if (preg_match("/CREATE TABLE {(\\w+)}/", $line, $matches)) {
             $table_name = $matches[1];
         }
         // Normalize dates
         $line = preg_replace("/,{$root_created_timestamp},/", ",UNIX_TIMESTAMP(),", $line);
         $line = preg_replace("/,{$root_updated_timestamp},/", ",UNIX_TIMESTAMP(),", $line);
         // Remove ENGINE= specifications execpt for search records, it always needs to be MyISAM
         if ($table_name != "search_records") {
             $line = preg_replace("/ENGINE=\\S+ /", "", $line);
         }
         // Null out ids in the vars table since it's an auto_increment table and this will result in
         // more stable values so we'll have less churn in install.sql.
         $line = preg_replace("/^INSERT INTO {vars} VALUES \\(\\d+/", "INSERT INTO {vars} VALUES (NULL", $line);
         $buf .= $line;
     }
     $fd = fopen($sql_file, "wb");
     fwrite($fd, $buf);
     fclose($fd);
 }
Example #29
0
 public static function include_vendor()
 {
     require_once Kohana::find_file('vendor', 'hybridauth/hybridauth/Hybrid/Auth', 'php');
     require_once Kohana::find_file('vendor', 'hybridauth/hybridauth/Hybrid/Endpoint', 'php');
     require_once Kohana::find_file('vendor', 'hybridauth/hybridauth/Hybrid/Logger', 'php');
     require_once Kohana::find_file('vendor', 'hybridauth/hybridauth/Hybrid/Exception', 'php');
 }
Example #30
0
 /**
  * Show latest PER_PAGE news on page
  * @return void
  */
 public function index($module = NULL, $page = 1)
 {
     $this->set_title(Kohana::lang('search.search'));
     if ($page == 1) {
         $this->add_breadcrumb(Kohana::lang('search.the_best_results'), url::current());
     } else {
         $this->add_breadcrumb(Kohana::lang('search.page_no') . ' ' . $page, url::current());
     }
     // Default values
     $form = array('value' => '');
     $errors = array();
     if ($_POST) {
         $post = new Validation($_POST);
         // Some filters
         $post->pre_filter('trim', TRUE);
         // Rules
         $post->add_rules('value', 'required');
         if ($post->validate()) {
             $form = arr::overwrite($form, $post->as_array());
         } else {
             // Repopulate form with error and original values
             $form = arr::overwrite($form, $post->as_array());
             $errors = $post->errors('search_errors');
         }
     }
     $this->template->content = new View('search');
     $data = $this->products->search($post['value']);
     $data2 = $this->page->search($post['value']);
     $data3 = $this->news->search($post['value']);
     $this->template->content->data = $data;
     $this->template->content->data2 = $data2;
     $this->template->content->data3 = $data3;
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
 }