/**
  * generate xml for a form from a table
  *
  * @param object $setup 
  * @return string
  * @author Andy Bennett
  */
 function get_form_xml($setup)
 {
     $file_name = $setup->form_name;
     $dir = DATAPATH . '/xml/forms/';
     $path = $dir . $file_name . '.xml';
     if (file_exists($path)) {
         return file_get_contents($path);
     }
     if (!isset($setup->model) || !is_object($setup->model)) {
         $config = Kohana::config('controls.controllers');
         $name = Kohana::instance()->uri->segment(1);
         if (!isset($config->{$name})) {
             throw new Exception("No controller set up");
         }
         $this->set_table($config->{$name}['table']);
     } else {
         $this->set_table($setup->model->get_table());
         $name = $setup->form_name;
     }
     $field_data = $this->db->field_data($this->table);
     // print_r($field_data);
     $view = new View('xml/form');
     $view->field_data = $field_data;
     $view->name = Kohana::instance()->uri->segment(1);
     $view->action = Kohana::instance()->uri->segment(2);
     $data = $view->render();
     if (file_exists($dir)) {
         file_put_contents($path, $data);
     }
     return $data;
 }
示例#2
0
 /**
  * Twitter class constructor
  *
  * @param  string  $username	Twitter username
  * @param  string  $password	Twitter password for username
  * @param  string  $application	Twitter application name
  * @param  string  $format		Encoding format
  */
 function __construct($username, $password, $application = FALSE, $format = FALSE)
 {
     $this->login = "******";
     $this->application = $application ? $application : Kohana::config('twitter.application');
     $this->application = urlencode($this->application);
     $this->format = $format ? $format : Kohana::config('twitter.format');
 }
示例#3
0
文件: base.php 项目: Hinton/langify
 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);
     }
 }
 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;
 }
示例#5
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'));
     }
 }
示例#6
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);
 }
示例#7
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);
         }
     }
 }
    /**
     * 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\'');
        }
    }
示例#9
0
 /**
  * Creates a new request cache decorator of the type defined. If no decorator type
  * is supplied, the `vitesse.default_decorator` configuration setting will be used.
  * 
  *     // Create a new memcache decorator
  *     $decorator = Request_Cache_Decorator::instance('Memcache');
  *
  *     // Create a new default decorator
  *     $default_decorator = Request_Cache_Decorator::instance();
  *
  * @param   string   decorator class name
  * @return  Request_Cache_Adaptor
  * @throws  Kohana_Request_Exception
  */
 public static function instance($decorator = NULL)
 {
     // Load the vitesse config
     $config = Kohana::config('vitesse');
     // If the adaptor isn't defined
     if ($decorator === NULL) {
         // Set it to the default adaptor
         $decorator = Request_Cache_Decorator::$default;
     }
     // Create the full adaptor class name
     $decorator_class = 'Request_Cache_Decorator_' . $decorator;
     // If an instance already exists
     if (isset(Request_Cache_Decorator::$_instances[$decorator_class])) {
         // Return the instance
         return Request_Cache_Decorator::$_instances[$decorator_class];
     }
     // Create a new decorator class
     $decorator = new $decorator_class($config->cache_configuration_groups);
     // If the decorator is not of the correct type
     if (!$decorator instanceof Request_Cache_Decorator) {
         // Throw an exception
         throw new Kohana_Request_Exception('Decorator supplied is not an instance of Request_Cache_Decorator : :class', array(':class' => get_class($decorator)));
     }
     // Set the instance to the class
     Request_Cache_Decorator::$_instances[$decorator_class] = $decorator;
     // Return the decorator
     return $decorator;
 }
示例#10
0
 public function index($feedtype = 'rss2')
 {
     if (!Kohana::config('settings.allow_feed')) {
         throw new Kohana_404_Exception();
     }
     if ($feedtype != 'atom' and $feedtype != 'rss2') {
         throw new Kohana_404_Exception();
     }
     $feedpath = $feedtype == 'atom' ? 'feed/atom/' : 'feed/';
     $site_url = url::base();
     $incidents = ORM::factory('incident')->where('incident_active', '1')->orderby('incident_date', 'desc')->limit(20)->find_all();
     $items = array();
     foreach ($incidents as $incident) {
         $item = array();
         $item['title'] = $incident->incident_title;
         $item['link'] = $site_url . 'reports/view/' . $incident->id;
         $item['description'] = $incident->incident_description;
         $item['date'] = $incident->incident_date;
         if ($incident->location_id != 0 and $incident->location->longitude and $incident->location->latitude) {
             $item['point'] = array($incident->location->latitude, $incident->location->longitude);
             $items[] = $item;
         }
     }
     header("Content-Type: text/xml; charset=utf-8");
     $view = new View('feed_' . $feedtype);
     $view->feed_title = htmlspecialchars(Kohana::config('settings.site_name'));
     $view->site_url = $site_url;
     $view->georss = 1;
     // this adds georss namespace in the feed
     $view->feed_url = $site_url . $feedpath;
     $view->feed_date = gmdate("D, d M Y H:i:s T", time());
     $view->feed_description = 'Incident feed for ' . Kohana::config('settings.site_name');
     $view->items = $items;
     $view->render(TRUE);
 }
示例#11
0
文件: Remote.php 项目: swk/bluebox
 public static function queryRepositories($repos = NULL)
 {
     if (is_null($repos)) {
         $repos = Kohana::config('core.repositories');
     }
     if (!is_array($repos)) {
         $repos = array($repos);
     }
     if (empty($repos)) {
         return array();
     }
     $remoteCatalogs = array();
     foreach ($repos as $repo) {
         if (!($repoXMLCatalog = self::fetch($repo))) {
             continue;
         }
         $remoteCatalog = self::fromXML($repoXMLCatalog);
         foreach ($remoteCatalog as $package) {
             Package_Catalog_Standardize::packageData($package, NULL);
             Package_Catalog_Standardize::navigation($package);
             if (empty($package['identifier'])) {
                 Package_Message::log('alert', 'Remote repo ' . $repo . ' provided an invalid package, ignoring!');
                 continue;
             }
             if (array_key_exists($package['identifier'], Package_Catalog::getCatalog())) {
                 Package_Message::log('debug', 'Remote repo ' . $repo . ' provided existing package ' . $package['packageName'] . ' version ' . $package['version'] . ', ignoring');
                 continue;
             }
             Package_Message::log('debug', 'Remote repo ' . $repo . ' provided new package ' . $package['packageName'] . ' version ' . $package['version']);
             $package['status'] = Package_Manager::STATUS_UNINSTALLED;
             $remoteCatalogs[$package['identifier']] = $package;
         }
     }
     return $remoteCatalogs;
 }
示例#12
0
文件: mq.php 项目: momoim/momo-api
 public static function connect()
 {
     if (!is_object(self::$cnn)) {
         self::$cnn = new AMQPConnect(Kohana::config('uap.rabbitmq'));
     }
     return self::$cnn;
 }
示例#13
0
 public function before()
 {
     if ($this->request->action === 'media') {
         // Do not template media files
         $this->auto_render = FALSE;
     } else {
         // Grab the necessary routes
         $this->media = Route::get('docs/media');
         $this->api = Route::get('docs/api');
         $this->guide = Route::get('docs/guide');
         if (isset($_GET['lang'])) {
             $lang = $_GET['lang'];
             // Load the accepted language list
             $translations = array_keys(Kohana::message('userguide', 'translations'));
             if (in_array($lang, $translations)) {
                 // Set the language cookie
                 Cookie::set('userguide_language', $lang, Date::YEAR);
             }
             // Reload the page
             $this->request->redirect($this->request->uri);
         }
         // Set the translation language
         I18n::$lang = Cookie::get('userguide_language', Kohana::config('userguide')->lang);
         // Use customized Markdown parser
         define('MARKDOWN_PARSER_CLASS', 'Kodoc_Markdown');
         // Load Markdown support
         require Kohana::find_file('vendor', 'markdown/markdown');
         // Set the base URL for links and images
         Kodoc_Markdown::$base_url = URL::site($this->guide->uri()) . '/';
         Kodoc_Markdown::$image_url = URL::site($this->media->uri()) . '/';
     }
     parent::before();
 }
示例#14
0
    public function __construct($api_service)    
    {    
        $this->db = new Database();
        
        $this->api_settings = new Api_Settings_Model(1);

        // Set the list limit
        $this->list_limit = ((int) $this->api_settings->default_record_limit > 0)
            ? $this->api_settings->default_record_limit
            : (int) Kohana::config('settings.items_per_api_request');
        
        $this->domain = url::base();
        $this->record_count = 1;
        $this->table_prefix = Kohana::config('database.default.table_prefix');
        $this->api_service = $api_service;
        
        // Check if the response type for the API service has already been set
        if ( ! is_null($api_service->get_response_type()))
        {
            $this->request = $api_service->get_request();
            $this->response_type = $api_service->get_response_type();
        }
        else
        {
            $this->set_request($api_service->get_request());
        }
    }
示例#15
0
 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'] . '/';
 }
示例#16
0
文件: deal.php 项目: momoim/momo-api
 public function __construct()
 {
     parent::__construct();
     $mg_instance = new MongoClient(Kohana::config('uap.mongodb'));
     $mongo = $mg_instance->selectDB(MONGO_DB_FEED);
     $this->mongo_deal = $mongo->selectCollection('deals');
 }
示例#17
0
 public function __construct($file = null, array $data = null)
 {
     $token = Kohana::$profiling ? Profiler::start('renderer', 'new kohana view') : false;
     $this->_config = Kohana::config('render');
     parent::__construct($file, $data);
     $token ? Profiler::stop($token) : null;
 }
示例#18
0
 /**
  * Displays all reports.
  */
 public function index()
 {
     $this->template->header->this_page = 'feeds';
     $this->template->content = new View('feeds');
     // Pagination
     /** #########  Apala required changes ########## DB Call below. ::factory('feed_item')*/
     $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()));
     /** #########  Apala required changes ########## DB Call below.  ::factory('feed_item')*/
     $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
     if ($pagination->total_items == 1) {
         $plural = '';
     } else {
         $plural = '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) {
             // If we want to show pagination
             $this->template->content->pagination_stats = '(Showing ' . $current_page . ' of ' . $total_pages . ' pages of ' . $pagination->total_items . ' feeds' . $plural . ')';
             $this->template->content->pagination = $pagination;
         } else {
             // If we don't want to show pagination
             $this->template->content->pagination_stats = '(' . $pagination->total_items . ' feed' . $plural . ')';
         }
     } else {
         $this->template->content->pagination_stats = '(' . $pagination->total_items . ' feed' . $plural . ')';
     }
 }
 /** 
  * 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);
     }
 }
 public function index($id = NULL)
 {
     $this->template->content = new View('analysis/main');
     // Get all active top level categories
     $parent_categories = array();
     foreach (ORM::factory('category')->where('category_visible', '1')->where('parent_id', '0')->orderby('category_title', 'ASC')->find_all() as $category) {
         // Get The Children
         $children = array();
         foreach ($category->children as $child) {
             $children[$child->id] = array($child->category_title);
         }
         sort($children);
         // Put it all together
         $parent_categories[$category->id] = array($category->category_title, $children);
     }
     $this->template->content->categories = $parent_categories;
     $this->template->content->date_picker_js = $this->_date_picker_js();
     $this->template->content->latitude = Kohana::config('settings.default_lat');
     $this->template->content->longitude = Kohana::config('settings.default_lon');
     // Javascript
     $this->template->map_enabled = TRUE;
     $this->template->js = new View('analysis/main_js');
     $this->template->js->default_map = Kohana::config('settings.default_map');
     $this->template->js->default_zoom = Kohana::config('settings.default_zoom');
     $this->template->js->latitude = Kohana::config('settings.default_lat');
     $this->template->js->longitude = Kohana::config('settings.default_lon');
 }
示例#21
0
 /**
  * Render the profiler. Output is added to the bottom of the page by default.
  *
  * @param   boolean  return the output if TRUE
  * @return  void|string
  */
 public function render($return = FALSE)
 {
     $start = microtime(TRUE);
     $get = isset($_GET['profiler']) ? explode(',', $_GET['profiler']) : array();
     $this->show = empty($get) ? Kohana::config('profiler.show') : $get;
     Event::run('profiler.run', $this);
     $styles = '';
     foreach ($this->profiles as $profile) {
         $styles .= $profile->styles();
     }
     // Don't display if there's no profiles
     if (empty($this->profiles)) {
         return;
     }
     // Load the profiler view
     $data = array('profiles' => $this->profiles, 'styles' => $styles, 'execution_time' => microtime(TRUE) - $start);
     $view = new View('kohana_profiler', $data);
     // Return rendered view if $return is TRUE
     if ($return == TRUE) {
         return $view->render();
     }
     // Add profiler data to the output
     if (stripos(Kohana::$output, '</body>') !== FALSE) {
         // Closing body tag was found, insert the profiler data before it
         Kohana::$output = str_ireplace('</body>', $view->render() . '</body>', Kohana::$output);
     } else {
         // Append the profiler data to the output
         Kohana::$output .= $view->render();
     }
 }
示例#22
0
 public function index()
 {
     // Create new session
     $this->session->create();
     $this->template->header->this_page = 'alerts';
     $this->template->content = new View('alerts');
     // Display news feeds?
     $this->template->content->allow_feed = Kohana::config('settings.allow_feed');
     // Retrieve default country, latitude, longitude
     $default_country = Kohana::config('settings.default_country');
     // Retrieve Country Cities
     $this->template->content->cities = $this->_get_cities($default_country);
     // Setup and initialize form field names
     $form = array('alert_mobile' => '', 'alert_mobile_yes' => '', 'alert_email' => '', 'alert_email_yes' => '', 'alert_lat' => '', 'alert_lon' => '', 'alert_radius' => '');
     // Copy the form as errors, so the errors will be stored with keys
     // corresponding to the form field names
     $errors = $form;
     $form_error = FALSE;
     $form_saved = FALSE;
     // If there is a post and $_POST is not empty
     if ($post = $this->input->post()) {
         // Create a new alert
         $alert = ORM::factory('alert');
         // Test to see if things passed the rule checks
         if ($alert->validate($post)) {
             // Yes! everything is valid
             // Save alert and send out confirmation code
             if (!empty($post->alert_mobile)) {
                 $this->_send_mobile_alert($post->alert_mobile, $post->alert_lon, $post->alert_lat, $post->alert_radius);
             }
             if (!empty($post->alert_email)) {
                 $this->_send_email_alert($post->alert_email, $post->alert_lon, $post->alert_lat, $post->alert_radius);
             }
             $this->session->set('alert_mobile', $post->alert_mobile);
             $this->session->set('alert_email', $post->alert_email);
             url::redirect('alerts/confirm');
         } else {
             // repopulate the form fields
             $form = arr::overwrite($form, $post->as_array());
             // populate the error fields, if any
             $errors = arr::overwrite($errors, $post->errors('alerts'));
             $form_error = TRUE;
         }
     } else {
         $form['alert_lat'] = Kohana::config('settings.default_lat');
         $form['alert_lon'] = Kohana::config('settings.default_lon');
         $form['alert_radius'] = 20;
     }
     $this->template->content->form = $form;
     $this->template->content->errors = $errors;
     $this->template->content->form_error = $form_error;
     $this->template->content->form_saved = $form_saved;
     // Javascript Header
     $this->template->header->map_enabled = TRUE;
     $this->template->header->js = new View('alerts_js');
     $this->template->header->js->default_map = Kohana::config('settings.default_map');
     $this->template->header->js->default_zoom = Kohana::config('settings.default_zoom');
     $this->template->header->js->latitude = $form['alert_lat'];
     $this->template->header->js->longitude = $form['alert_lon'];
 }
示例#23
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');
 }
示例#24
0
 /**
  * Add a new message to the log.
  *
  * @param   string  type of message
  * @param   string  message text
  * @return  void
  */
 public static function add($type, $message)
 {
     // Make sure the drivers and config are loaded
     if (!is_array(Kohana_Log::$config)) {
         Kohana_Log::$config = Kohana::config('log');
     }
     if (!is_array(Kohana_Log::$drivers)) {
         foreach ((array) Kohana::config('log.drivers') as $driver_name) {
             // Set driver name
             $driver = 'Log_' . ucfirst($driver_name) . '_Driver';
             // Load the driver
             if (!Kohana::auto_load($driver)) {
                 throw new Kohana_Exception('Log Driver Not Found: %driver%', array('%driver%' => $driver));
             }
             // Initialize the driver
             $driver = new $driver(array_merge(Kohana::config('log'), Kohana::config('log_' . $driver_name)));
             // Validate the driver
             if (!$driver instanceof Log_Driver) {
                 throw new Kohana_Exception('%driver% does not implement the Log_Driver interface', array('%driver%' => $driver));
             }
             Kohana_Log::$drivers[] = $driver;
         }
         // Always save logs on shutdown
         Event::add('system.shutdown', array('Kohana_Log', 'save'));
     }
     Kohana_Log::$messages[] = array('date' => time(), 'type' => $type, 'message' => $message);
 }
示例#25
0
 /**
  * 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);
 }
示例#26
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');
     }
 }
示例#27
0
 private function handleStatic($filenames, $type)
 {
     /* Fix to prevent debug bar from rendering on this page */
     $config = Kohana::config('debug_toolbar');
     if ($config) {
         $config->set('auto_render', false);
     }
     /* end fix */
     if ($filenames === null) {
         $this->response = "/* No {$type} TO BE FOUND */";
         return;
     }
     if (Kohana_Core::$environment != Kohana::DEVELOPMENT && self::check(300) === FALSE) {
         self::set(300);
     }
     $this->response->headers('Content-Type', File::mime_by_ext($type));
     $body = "";
     $filenames = preg_replace("/\\.{$type}\$/", '', $filenames);
     foreach (explode(',', $filenames) as $key) {
         $key = basename($key, ".{$type}");
         $file = Kohana::find_file('views/' . $type, $key, $type);
         if (!$file) {
             $body .= "/* No such file or directory ({$key}.{$type}) */\n";
             continue;
         }
         $body .= implode('', array('/* (', str_replace(DOCROOT, '', $file), ") */\n"));
         $body .= file_get_contents($file);
     }
     /* Play nice with minify module if its enabled */
     if (Kohana::config('minify.enabled', false) && class_exists('Minify')) {
         $body = Minify::factory($type)->set($body)->min();
     }
     $this->response->body($body);
 }
示例#28
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');
 }
示例#29
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"));
     }
 }
示例#30
0
 public function index()
 {
     define('DEBUG', true);
     // an array of file extensions to accept
     $accepted_extensions = array("png", "jpg", "gif");
     // http://your-web-site.domain/base/url
     $base_url = url::base() . Kohana::config('upload.relative_directory', TRUE) . "jwysiwyg";
     // the root path of the upload directory on the server
     $uploads_dir = Kohana::config('upload.directory', TRUE) . "jwysiwyg";
     // the root path that the files are available from the webserver
     $uploads_access_dir = Kohana::config('upload.directory', TRUE) . "jwysiwyg";
     if (!file_exists($uploads_access_dir)) {
         mkdir($uploads_access_dir, 0775);
     }
     if (DEBUG) {
         if (!file_exists($uploads_access_dir)) {
             $error = 'Folder "' . $uploads_access_dir . '" doesn\'t exists.';
             header('Content-type: text/html; charset=UTF-8');
             print '{"error":"config.php: ' . htmlentities($error) . '","success":false}';
             exit;
         }
     }
     $capabilities = array("move" => false, "rename" => true, "remove" => true, "mkdir" => false, "upload" => true);
     if (extension_loaded('mbstring')) {
         mb_internal_encoding('UTF-8');
         mb_regex_encoding('UTF-8');
     }
     require_once Kohana::find_file('libraries/jwysiwyg', 'common', TRUE);
     require_once Kohana::find_file('libraries/jwysiwyg', 'handlers', TRUE);
     ResponseRouter::getInstance()->run();
 }