/** * When we call detach() we expect the specified log writer to be removed * * @test * @covers Kohana_Log::detach */ public function test_detach_removes_log_writer_and_returns_this() { $logger = new Kohana_Log(); $writer = $this->getMockForAbstractClass('Kohana_Log_Writer'); $logger->attach($writer); $this->assertSame($logger, $logger->detach($writer)); $this->assertAttributeSame(array(), '_writers', $logger); }
public function __construct() { include Kohana::find_file('vendor', 'facebook/src/facebook'); // class setup $this->_facebook = new Facebook(array('appId' => Kohana::config('facebook')->app_id, 'secret' => Kohana::config('facebook')->secret, 'cookie' => true)); $this->canvasUrl = Kohana::config('facebook')->canvas_url; $this->scope = Kohana::config('facebook')->scope; try { $this->uid = $this->getUser(); if (Kohana::$profiling === TRUE) { $benchmark = Profiler::start('Kohana_Facebook', 'facebook->api(/me)'); } $this->_me = $this->_facebook->api('/me'); if (isset($benchmark)) { // Stop the benchmark Profiler::stop($benchmark); } } catch (FacebookApiException $e) { $log = Kohana_Log::instance(); $log->write($e); var_dump($e); $this->redirectToLogin(); exit; } }
/** * Make sure that we have a session and group_ids cached in the session. */ static function load_user() { try { // Call IdentityProvider::instance() now to force the load of the user interface classes. // We are about to load the active user from the session and which needs the user definition // class, which can't be reached by Kohana's heiracrchical lookup. IdentityProvider::instance(); $session = Session::instance(); if (!($user = $session->get("user"))) { self::set_active_user($user = self::guest()); } // The installer cannot set a user into the session, so it just sets an id which we should // upconvert into a user. // @todo set the user name into the session instead of 2 and then use it to get the user object if ($user === 2) { auth::login(IdentityProvider::instance()->admin_user()); } if (!$session->get("group_ids")) { $ids = array(); foreach ($user->groups() as $group) { $ids[] = $group->id; } $session->set("group_ids", $ids); } } catch (Exception $e) { // Log it, so we at least have so notification that we swallowed the exception. Kohana_Log::add("error", "load_user Exception: " . $e->getMessage() . "\n" . $e->getTraceAsString()); try { Session::instance()->destroy(); } catch (Exception $e) { // We don't care if there was a problem destroying the session. } url::redirect(item::root()->abs_url()); } }
/** * Shows a themed error page. * @see Kohana_Exception::handle */ private static function _show_themed_error_page(Exception $e) { // Create a text version of the exception $error = Kohana_Exception::text($e); // Add this exception to the log Kohana_Log::add('error', $error); // Manually save logs after exceptions Kohana_Log::save(); if (!headers_sent()) { if ($e instanceof Kohana_Exception) { $e->sendHeaders(); } else { header("HTTP/1.1 500 Internal Server Error"); } } $view = new Theme_View("page.html", "other", "error"); if ($e instanceof Kohana_404_Exception) { $view->page_title = t("Dang... Page not found!"); $view->content = new View("error_404.html"); $user = identity::active_user(); $view->content->is_guest = $user && $user->guest; if ($view->content->is_guest) { $view->content->login_form = new View("login_ajax.html"); $view->content->login_form->form = auth::get_login_form("login/auth_html"); // Avoid anti-phishing protection by passing the url as session variable. Session::instance()->set("continue_url", url::current(true)); } } else { $view->page_title = t("Dang... Something went wrong!"); $view->content = new View("error.html"); } print $view; }
/** * 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('To use the Encrypt library, mcrypt must be enabled in your PHP installation'); } if (is_string($config)) { $name = $config; // Test the config group name if (($config = Kohana::config('encryption.' . $config)) === NULL) { throw new Kohana_Exception('The :name: group is not defined in your configuration.', array(':name:' => $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('To use the Encrypt library, you must set an encryption key in your config file'); } // 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::add('debug', 'Encrypt Library initialized'); }
public function saveprefs() { // Save user preferences to the database. // Prevent Cross Site Request Forgery access::verify_csrf(); // Make sure the user filled out the form properly. $form = $this->_get_admin_form(); if ($form->validate()) { Kohana_Log::add("error", print_r($form, 1)); // Save settings to Gallery's database. foreach (iptc::keys() as $keyword => $iptcvar) { $checkbox = false; for ($i = 0; $i < count($form->Global->{$keyword}); $i++) { if ($form->Global->{$keyword}->value[$i] == $keyword) { $checkbox = true; } } module::set_var("iptc", "show_" . $keyword, $checkbox); } // Display a success message and redirect back to the TagsMap admin page. message::success(t("Your settings have been saved.")); url::redirect("admin/iptc"); } // Else show the page with errors $view = new Admin_View("admin.html"); $view->content = new View("admin_iptc.html"); $view->content->iptc_form = $form; print $view; }
/** * On first session instance creation, sets up the driver and creates session. * * @param string Force a specific session_id */ protected function __construct($session_id = NULL) { $this->input = Input::instance(); // This part only needs to be run once if (Session::$instance === NULL) { // Load config Session::$config = Kohana::config('session'); // Makes a mirrored array, eg: foo=foo Session::$protect = array_combine(Session::$protect, Session::$protect); // Configure garbage collection ini_set('session.gc_probability', (int) Session::$config['gc_probability']); ini_set('session.gc_divisor', 100); ini_set('session.gc_maxlifetime', Session::$config['expiration'] == 0 ? 86400 : Session::$config['expiration']); // Create a new session $this->create(NULL, $session_id); if (Session::$config['regenerate'] > 0 and $_SESSION['total_hits'] % Session::$config['regenerate'] === 0) { // Regenerate session id and update session cookie $this->regenerate(); } else { // Always update session cookie to keep the session alive cookie::set(Session::$config['name'], $_SESSION['session_id'], Session::$config['expiration']); } // Close the session on system shutdown (run before sending the headers), so that // the session cookie(s) can be written. Event::add('system.shutdown', array($this, 'write_close')); // Singleton instance Session::$instance = $this; } Kohana_Log::add('debug', 'Session Library initialized'); }
/** * Handle the creation of a new photo. * @todo Get tags from the XMP and/or IPTC data in the image * * @param Item_Model $photo */ static function item_created($photo) { $tags = array(); if ($photo->is_photo()) { $path = $photo->file_path(); $size = getimagesize($photo->file_path(), $info); if (is_array($info) && !empty($info["APP13"])) { $iptc = iptcparse($info["APP13"]); if (!empty($iptc["2#025"])) { foreach ($iptc["2#025"] as $tag) { $tag = str_replace("", "", $tag); foreach (explode(",", $tag) as $word) { $word = trim($word); if (function_exists("mb_detect_encoding") && mb_detect_encoding($word) != "UTF-8") { $word = utf8_encode($word); } $tags[$word] = 1; } } } } } // @todo figure out how to read the keywords from xmp foreach (array_keys($tags) as $tag) { try { tag::add($photo, $tag); } catch (Exception $e) { Kohana_Log::add("error", "Error adding tag: {$tag}\n" . $e->getMessage() . "\n" . $e->getTraceAsString()); } } return; }
public function login() { $form = $errors = array("user" => "", "password" => ""); $post = new Validation($_POST); $post->add_rules("user", "required"); $post->add_rules("password", "required"); if ($valid = $post->validate()) { try { $token = G3Remote::instance()->get_access_token($post["user"], $post["password"]); Session::instance()->set("g3_client_access_token", $token); $response = G3Remote::instance()->get_resource("gallery"); $valid = true; $content = $this->_get_main_view($response->resource); } catch (Exception $e) { Kohana_Log::add("error", Kohana_Exception::text($e)); $valid = false; } } if (!$valid) { $content = new View('login.html'); $content->form = arr::overwrite($form, $post->as_array()); $content->errors = arr::overwrite($errors, $post->errors()); } $this->auto_render = false; print json_encode(array("status" => $valid ? "ok" : "error", "content" => (string) $content)); }
/** * Rotate an image. Valid options are degrees * * @param string $input_file * @param string $output_file * @param array $options */ static function rotate($input_file, $output_file, $options) { graphics::init_toolkit(); module::event("graphics_rotate", $input_file, $output_file, $options); // BEGIN mod to original function $image_info = getimagesize($input_file); // [0]=w, [1]=h, [2]=type (1=GIF, 2=JPG, 3=PNG) if (module::get_var("image_optimizer", "rotate_jpg") || $image_info[2] == 2) { // rotate_jpg enabled, the file is a jpg. get args $path = module::get_var("image_optimizer", "path_jpg"); $exec_args = " -rotate "; $exec_args .= $options["degrees"] > 0 ? $options["degrees"] : $options["degrees"] + 360; $exec_args .= " -copy all -optimize -outfile "; // run it - from input_file to tmp_file $tmp_file = image_optimizer::make_temp_name($output_file); exec(escapeshellcmd($path) . $exec_args . escapeshellarg($tmp_file) . " " . escapeshellarg($input_file), $exec_output, $exec_status); if ($exec_status || !filesize($tmp_file)) { // either a blank/nonexistant file or an error - log an error and pass to normal function Kohana_Log::add("error", "image_optimizer rotation failed on " . $output_file); unlink($tmp_file); } else { // worked - move temp to output rename($tmp_file, $output_file); $status = true; } } if (!$status) { // we got here if we weren't supposed to use jpegtran or if jpegtran failed // END mod to original function Image::factory($input_file)->quality(module::get_var("gallery", "image_quality"))->rotate($options["degrees"])->save($output_file); // BEGIN mod to original function } // END mod to original function module::event("graphics_rotate_completed", $input_file, $output_file, $options); }
/** * At this point, the output has been sent to the browser, so we can take some time * to run a schedule task. */ static function gallery_shutdown() { try { $schedule = ORM::factory("schedule")->where("next_run_datetime", "<=", time())->where("busy", "!=", 1)->order_by("next_run_datetime")->find_all(1); if ($schedule->count()) { $schedule = $schedule->current(); $schedule->busy = true; $schedule->save(); try { if (empty($schedule->task_id)) { $task = task::start($schedule->task_callback); $schedule->task_id = $task->id; } $task = task::run($schedule->task_id); if ($task->done) { $schedule->next_run_datetime += $schedule->interval; $schedule->task_id = null; } $schedule->busy = false; $schedule->save(); } catch (Exception $e) { $schedule->busy = false; $schedule->save(); throw $e; } } } catch (Exception $e) { Kohana_Log::add("error", (string) $e); } }
/** * Load the active theme. This is called at bootstrap time. We will only ever have one theme * active for any given request. */ static function load_themes() { $input = Input::instance(); $path = $input->server("PATH_INFO"); if (empty($path)) { $path = "/" . $input->get("kohana_uri"); } $config = Kohana_Config::instance(); $modules = $config->get("core.modules"); self::$is_admin = $path == "/admin" || !strncmp($path, "/admin/", 7); self::$site_theme_name = module::get_var("gallery", "active_site_theme"); if (self::$is_admin) { // Load the admin theme self::$admin_theme_name = module::get_var("gallery", "active_admin_theme"); array_unshift($modules, THEMEPATH . self::$admin_theme_name); // If the site theme has an admin subdir, load that as a module so that // themes can provide their own code. if (file_exists(THEMEPATH . self::$site_theme_name . "/admin")) { array_unshift($modules, THEMEPATH . self::$site_theme_name . "/admin"); } } else { // Admins can override the site theme, temporarily. This lets us preview themes. if (identity::active_user()->admin && ($override = $input->get("theme"))) { if (file_exists(THEMEPATH . $override)) { self::$site_theme_name = $override; } else { Kohana_Log::add("error", "Missing override theme: '{$override}'"); } } array_unshift($modules, THEMEPATH . self::$site_theme_name); } $config->set("core.modules", $modules); }
static function scan_php_file($file, &$cache) { $code = file_get_contents($file); $raw_tokens = token_get_all($code); unset($code); $tokens = array(); $func_token_list = array("t" => array(), "t2" => array()); $token_number = 0; // Filter out HTML / whitespace, and build a lookup for global function calls. foreach ($raw_tokens as $token) { if (!is_array($token) || $token[0] != T_WHITESPACE && $token[0] != T_INLINE_HTML) { if (is_array($token)) { if ($token[0] == T_STRING && in_array($token[1], array("t", "t2"))) { $func_token_list[$token[1]][] = $token_number; } } $tokens[] = $token; $token_number++; } } unset($raw_tokens); if (!empty($func_token_list["t"])) { $errors = l10n_scanner::_parse_t_calls($tokens, $func_token_list["t"], $cache); foreach ($errors as $line => $error) { Kohana_Log::add("error", "Translation scanner error. " . "file: " . substr($file, strlen(DOCROOT)) . ", line: {$line}, context: {$error}"); } } if (!empty($func_token_list["t2"])) { $errors = l10n_scanner::_parse_plural_calls($tokens, $func_token_list["t2"], $cache); foreach ($errors as $line => $error) { Kohana_Log::add("error", "Translation scanner error. " . "file: " . substr($file, strlen(DOCROOT)) . ", line: {$line}, context: {$error}"); } } }
/** * @param resource from pg_query() or pg_get_result() * @param string SQL used to create this result * @param resource from pg_connect() or pg_pconnect() * @param boolean|string * @return void */ public function __construct($result, $sql, $link, $return_objects) { // PGSQL_COMMAND_OK <- SET client_encoding = 'utf8' // PGSQL_TUPLES_OK <- SELECT table_name FROM information_schema.tables // PGSQL_COMMAND_OK <- INSERT INTO pages (name) VALUES ('gone soon') // PGSQL_COMMAND_OK <- DELETE FROM pages WHERE id = 2 // PGSQL_COMMAND_OK <- UPDATE pb_users SET company_id = 1 // PGSQL_FATAL_ERROR <- SELECT FROM pages switch (pg_result_status($result)) { case PGSQL_EMPTY_QUERY: $this->total_rows = 0; break; case PGSQL_COMMAND_OK: $this->total_rows = pg_affected_rows($result); break; case PGSQL_TUPLES_OK: $this->total_rows = pg_num_rows($result); break; case PGSQL_COPY_OUT: case PGSQL_COPY_IN: Kohana_Log::add('debug', 'PostgreSQL COPY operations not supported'); break; case PGSQL_BAD_RESPONSE: case PGSQL_NONFATAL_ERROR: case PGSQL_FATAL_ERROR: throw new Database_Exception(':error [ :query ]', array(':error' => pg_result_error($result), ':query' => $sql)); } $this->link = $link; $this->result = $result; $this->return_objects = $return_objects; $this->sql = $sql; }
/** * Loads the configured driver and validates it. * * @param array|string custom configuration or config group name * @return void */ public function __construct($config = FALSE) { if (is_string($config)) { $name = $config; // Test the config group name if (($config = Kohana::config('cache.' . $config)) === NULL) { throw new Cache_Exception('The :group: group is not defined in your configuration.', array(':group:' => $name)); } } if (is_array($config)) { // Append the default configuration options $config += Kohana::config('cache.default'); } else { // Load the default group $config = Kohana::config('cache.default'); } // Cache the config in the object $this->config = $config; // Set driver name $driver = 'Cache_' . ucfirst($this->config['driver']) . '_Driver'; // Load the driver if (!Kohana::auto_load($driver)) { throw new Cache_Exception('The :driver: driver for the :class: library could not be found', array(':driver:' => $this->config['driver'], ':class:' => get_class($this))); } // Initialize the driver $this->driver = new $driver($this->config['params']); // Validate the driver if (!$this->driver instanceof Cache_Driver) { throw new Cache_Exception('The :driver: driver for the :library: library must implement the :interface: interface', array(':driver:' => $this->config['driver'], ':library:' => get_class($this), ':interface:' => 'Cache_Driver')); } Kohana_Log::add('debug', 'Cache Library initialized'); }
public function saveprefs() { // Prevent Cross Site Request Forgery access::verify_csrf(); $form = $this->_get_admin_form(); if ($form->validate()) { Kohana_Log::add("error", print_r($form, 1)); module::set_var("tag_albums", "tag_page_title", $form->Tag_Albums_Tag_Sort->tag_page_title->value); module::set_var("tag_albums", "tag_index", $form->Tag_Albums_Tag_Sort->tag_index->value); module::set_var("tag_albums", "tag_index_scope", count($form->Tag_Albums_Tag_Sort->tag_index_scope->value)); module::set_var("tag_albums", "tag_index_filter_top", count($form->Tag_Albums_Tag_Sort->tag_index_filter_top->value)); module::set_var("tag_albums", "tag_index_filter_bottom", count($form->Tag_Albums_Tag_Sort->tag_index_filter_bottom->value)); module::set_var("tag_albums", "tag_sort_by", $form->Tag_Albums_Tag_Sort->tag_sort_by->value); module::set_var("tag_albums", "tag_sort_direction", $form->Tag_Albums_Tag_Sort->tag_sort_direction->value); module::set_var("tag_albums", "subalbum_sort_by", $form->Tag_Albums_Tag_Item_Sort->subalbum_sort_by->value); module::set_var("tag_albums", "subalbum_sort_direction", $form->Tag_Albums_Tag_Item_Sort->subalbum_sort_direction->value); message::success(t("Your settings have been saved.")); url::redirect("admin/tag_albums"); } // Else show the page with errors $view = new Admin_View("admin.html"); $view->content = new View("admin_tag_albums.html"); $view->content->tag_albums_form = $form; print $view; }
public function __construct() { // Load Encrypt library if (Kohana::config('session.encryption')) { $this->encrypt = new Encrypt(); } Kohana_Log::add('debug', 'Session Cache Driver Initialized'); }
/** * Validate the item name. It can't conflict with other names, can't contain slashes or * trailing periods. */ public function valid_name(Validation $v, $field) { Kohana_Log::add("error", print_r("valid_name!", 1)); $product = ORM::factory("product")->where("name", "=", $this->name)->find(); if ($product->loaded() && $product->id != $this->id) { $v->add_error("name", "in_use"); } }
static function update_overlays($task) { $errors = array(); try { $mode = $task->get('mode', 'init'); switch ($mode) { case 'init': $q = emboss::find_dirty(); foreach ($q as $item) { $ids[] = array('id' => $item->id, 'image_id' => $item->image_id, 'overlay_id' => $item->best_overlay_id); } $count = count($ids); if ($count > 0) { $task->set('ids', $ids); $task->set('count', $count); $task->set('current', 0); $task->set('mode', 'continue'); } else { $task->done = true; $task->state = 'success'; $task->percent_complete = 100; site_status::clear('emboss_dirty'); return; } break; case 'continue': $ids = $task->get('ids'); $count = $task->get('count'); $current = $task->get('current'); break; } $i = 1 * $current; $id = $ids[$i]; $current++; $task->set('current', $current); emboss_task::do_embossing($id['id'], $id['image_id'], $id['overlay_id']); if ($current >= $count) { $task->done = true; $task->state = 'success'; $task->percent_complete = 100; $task->status = 'Complete'; site_status::clear('emboss_dirty'); } else { $task->percent_complete = $current / $count * 100; $task->status = t("Reembossed {$current} of {$count} photos"); } } catch (Exception $e) { Kohana_Log::add('error', (string) $e); $task->done = true; $task->state = 'error'; $task->status = $e->getMessage(); $errors[] = (string) $e; } if ($errors) { $task->log($errors); } }
/** * Loads Session and configuration options. * * @return void */ public function __construct($config = array()) { // Clean up the salt pattern and split it into an array $config['salt_pattern'] = preg_split('/,\\s*/', Kohana::config('auth')->get('salt_pattern')); // Save the config in the object $this->config = $config; $this->session = Session::instance(); Kohana_Log::instance()->add('debug', 'Auth Library loaded'); }
/** * Load the active theme. This is called at bootstrap time. We will only ever have one theme * active for any given request. */ static function load_themes() { $input = Input::instance(); $path = $input->server("PATH_INFO"); if (empty($path)) { $path = "/" . $input->get("kohana_uri"); } $config = Kohana_Config::instance(); $modules = $config->get("core.modules"); // Normally Router::find_uri() strips off the url suffix for us, but we're working off of the // PATH_INFO here so we need to strip it off manually if ($suffix = Kohana::config("core.url_suffix")) { $path = preg_replace("#" . preg_quote($suffix) . "\$#u", "", $path); } self::$is_admin = $path == "/admin" || !strncmp($path, "/admin/", 7); self::$site_theme_name = module::get_var("gallery", "active_site_theme"); // If the site theme doesn't exist, fall back to wind. if (!file_exists(THEMEPATH . self::$site_theme_name . "/theme.info")) { site_status::error(t("Theme '%name' is missing. Falling back to the Wind theme.", array("name" => self::$site_theme_name)), "missing_site_theme"); module::set_var("gallery", "active_site_theme", self::$site_theme_name = "wind"); } if (self::$is_admin) { // Load the admin theme self::$admin_theme_name = module::get_var("gallery", "active_admin_theme"); // If the admin theme doesn't exist, fall back to admin_wind. if (!file_exists(THEMEPATH . self::$admin_theme_name . "/theme.info")) { site_status::error(t("Admin theme '%name' is missing! Falling back to the Wind theme.", array("name" => self::$admin_theme_name)), "missing_admin_theme"); module::set_var("gallery", "active_admin_theme", self::$admin_theme_name = "admin_wind"); } array_unshift($modules, THEMEPATH . self::$admin_theme_name); // If the site theme has an admin subdir, load that as a module so that // themes can provide their own code. if (file_exists(THEMEPATH . self::$site_theme_name . "/admin")) { array_unshift($modules, THEMEPATH . self::$site_theme_name . "/admin"); } // Admins can override the site theme, temporarily. This lets us preview themes. if (identity::active_user()->admin && ($override = $input->get("theme"))) { if (file_exists(THEMEPATH . $override)) { self::$admin_theme_name = $override; array_unshift($modules, THEMEPATH . self::$admin_theme_name); } else { Kohana_Log::add("error", "Missing override admin theme: '{$override}'"); } } } else { // Admins can override the site theme, temporarily. This lets us preview themes. if (identity::active_user()->admin && ($override = $input->get("theme"))) { if (file_exists(THEMEPATH . $override)) { self::$site_theme_name = $override; } else { Kohana_Log::add("error", "Missing override site theme: '{$override}'"); } } array_unshift($modules, THEMEPATH . self::$site_theme_name); } $config->set("core.modules", $modules); }
static function item_created($item) { try { autorotate::rotate_item($item); } catch (Exception $e) { Kohana_Log::add("error", "@todo autorotate_event::item_created() failed"); Kohana_Log::add("error", $e->getMessage() . "\n" . $e->getTraceAsString()); } }
/** * Fix up tag counts and delete any tags that have no associated items. * @param Task_Model the task */ static function clean_up_tags($task) { $errors = array(); try { $start = microtime(true); $last_tag_id = $task->get("last_tag_id", null); $current = 0; $total = 0; switch ($task->get("mode", "init")) { case "init": $task->set("total", ORM::factory("tag")->count_all()); $task->set("mode", "clean_up_tags"); $task->set("completed", 0); $task->set("last_tag_id", 0); case "clean_up_tags": $completed = $task->get("completed"); $total = $task->get("total"); $last_tag_id = $task->get("last_tag_id"); $tags = ORM::factory("tag")->where("id", ">", $last_tag_id)->find_all(25); Kohana_Log::add("error", print_r(Database::instance()->last_query(), 1)); while ($current < $total && microtime(true) - $start < 1 && ($tag = $tags->current())) { $last_tag_id = $tag->id; $real_count = $tag->items_count(); if ($tag->count != $real_count) { $tag->count = $real_count; if ($tag->count) { $task->log("Fixing count for tag {$tag->name} (id: {$tag->id}, new count: {$tag->count})"); $tag->save(); } else { $task->log("Deleting empty tag {$tag->name} ({$tag->id})"); $tag->delete(); } } $completed++; $tags->next(); } $task->percent_complete = $completed / $total * 100; $task->set("completed", $completed); $task->set("last_tag_id", $last_tag_id); } $task->status = t2("Examined %count tag", "Examined %count tags", $completed); if ($completed == $total) { $task->done = true; $task->state = "success"; $task->percent_complete = 100; } } catch (Exception $e) { Kohana_Log::add("error", (string) $e); $task->done = true; $task->state = "error"; $task->status = $e->getMessage(); $errors[] = (string) $e; } if ($errors) { $task->log($errors); } }
public function add_photo($id) { $album = ORM::factory("item", $id); access::required("view", $album); access::required("add", $album); access::verify_csrf(); // The Flash uploader not call /start directly, so simulate it here for now. if (!batch::in_progress()) { batch::start(); } $form = $this->_get_add_form($album); // Uploadify adds its own field to the form, so validate that separately. $file_validation = new Validation($_FILES); $file_validation->add_rules("Filedata", "upload::valid", "upload::required", "upload::type[" . implode(",", legal_file::get_extensions()) . "]"); if ($form->validate() && $file_validation->validate()) { $temp_filename = upload::save("Filedata"); Event::add("system.shutdown", create_function("", "unlink(\"{$temp_filename}\");")); try { $item = ORM::factory("item"); $item->name = substr(basename($temp_filename), 10); // Skip unique identifier Kohana adds $item->title = item::convert_filename_to_title($item->name); $item->parent_id = $album->id; $item->set_data_file($temp_filename); // Remove double extensions from the filename - they'll be disallowed in the model but if // we don't do it here then it'll result in a failed upload. $item->name = legal_file::smash_extensions($item->name); $path_info = @pathinfo($temp_filename); if (array_key_exists("extension", $path_info) && in_array(strtolower($path_info["extension"]), legal_file::get_movie_extensions())) { $item->type = "movie"; $item->save(); log::success("content", t("Added a movie"), html::anchor("movies/{$item->id}", t("view movie"))); } else { $item->type = "photo"; $item->save(); log::success("content", t("Added a photo"), html::anchor("photos/{$item->id}", t("view photo"))); } module::event("add_photos_form_completed", $item, $form); } catch (Exception $e) { // The Flash uploader has no good way of reporting complex errors, so just keep it simple. Kohana_Log::add("error", $e->getMessage() . "\n" . $e->getTraceAsString()); // Ugh. I hate to use instanceof, But this beats catching the exception separately since // we mostly want to treat it the same way as all other exceptions if ($e instanceof ORM_Validation_Exception) { Kohana_Log::add("error", "Validation errors: " . print_r($e->validation->errors(), 1)); } header("HTTP/1.1 500 Internal Server Error"); print "ERROR: " . $e->getMessage(); return; } print "FILEID: {$item->id}"; } else { header("HTTP/1.1 400 Bad Request"); print "ERROR: " . t("Invalid upload"); } }
/** * Get the singleton instance of this class and enable writing at shutdown. * * @return Kohana_Log */ public static function instance() { if (self::$_instance === NULL) { // Create a new instance self::$_instance = new self(); // Write the logs at shutdown register_shutdown_function(array(self::$_instance, 'write')); } return self::$_instance; }
/** * Override View_Core::render so that we trap errors stemming from bad PHP includes and show a * visible stack trace to help developers. * * @see View_Core::render */ public function render($print = false, $renderer = false, $modifier = false) { try { $this->kohana_local_data = array_merge(View::$global_data, $this->kohana_local_data); return parent::render($print, $renderer, $modifier); } catch (Exception $e) { Kohana_Log::add("error", $e->getMessage() . "\n" . $e->getTraceAsString()); return ""; } }
/** * Loads Session and configuration options. * * @param array $config */ public function __construct($config = array()) { // Load Session $this->session = Session::instance(); // Append default visitor configuration $config += Kohana::config('visitor'); // Save the config in the object $this->config = $config; Kohana_Log::add('debug', 'Visitor Library loaded'); }
public static function debug($message) { if (is_array($message)) { $message = print_r($message, true); } if (is_bool($message)) { $message = $message ? "true" : "false"; } Kohana_Log::add("error", $message); }
/** * Constructs a new Pagination object. * * @param array configuration settings * @return void */ public function __construct($config = array()) { // No custom group name given if (!isset($config['group'])) { $config['group'] = 'default'; } // Pagination setup $this->initialize($config); Kohana_Log::add('debug', 'Pagination Library initialized'); }
static function extract($item) { $keys = array(); // Only try to extract IPTC from photos if ($item->is_photo() && $item->mime_type == "image/jpeg") { $info = getJpegHeader($item->file_path()); if ($info !== FALSE) { $iptcBlock = getIptcBlock($info); if ($iptcBlock !== FALSE) { $iptc = iptcparse($iptcBlock); } else { $iptc = array(); } $xmp = getXmpDom($info); foreach (self::keys() as $keyword => $iptcvar) { $iptc_key = $iptcvar[0]; $xpath = $iptcvar[2]; $value = null; if ($xpath != null) { $value = getXmpValue($xmp, $xpath); } if ($value == null) { if (!empty($iptc[$iptc_key])) { $value = implode(";", $iptc[$iptc_key]); if (function_exists("mb_detect_encoding") && mb_detect_encoding($value) != "UTF-8") { $value = utf8_encode($value); } } } if ($value != null) { $keys[$keyword] = Input::clean($value); } } } } $record = ORM::factory("iptc_record")->where("item_id", "=", $item->id)->find(); if (!$record->loaded()) { $record->item_id = $item->id; } $record->data = serialize($keys); $record->key_count = count($keys); $record->dirty = 0; $record->save(); if (array_key_exists('Keywords', $keys)) { $tags = explode(';', $keys['Keywords']); foreach ($tags as $tag) { try { tag::add($item, $tag); } catch (Exception $e) { Kohana_Log::add("error", "Error adding tag: {$tag}\n" . $e->getMessage() . "\n" . $e->getTraceAsString()); } } } }