diff options
Diffstat (limited to 'modules/gallery')
83 files changed, 1928 insertions, 821 deletions
diff --git a/modules/gallery/config/cache.php b/modules/gallery/config/cache.php index cc3ac87d..d9a27c96 100644 --- a/modules/gallery/config/cache.php +++ b/modules/gallery/config/cache.php @@ -45,5 +45,6 @@ $config["default"] = array ( "driver" => "database", "params" => null, "lifetime" => 84600, - "requests" => 1000 + "requests" => 1000, + "prefix" => null, ); diff --git a/modules/gallery/config/log_file.php b/modules/gallery/config/log_file.php new file mode 100644 index 00000000..827a5d80 --- /dev/null +++ b/modules/gallery/config/log_file.php @@ -0,0 +1,29 @@ +<?php defined("SYSPATH") or die("No direct script access."); +/** + * Gallery - a web based photo album viewer and editor + * Copyright (C) 2000-2009 Bharat Mediratta + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. + */ + +/** + * Message logging directory. + */ +$config['log_directory'] = VARPATH.'logs'; + +/** + * Permissions of the log file + */ +$config['posix_permissions'] = 0644;
\ No newline at end of file diff --git a/modules/gallery/controllers/admin.php b/modules/gallery/controllers/admin.php index 98cac557..e4216991 100644 --- a/modules/gallery/controllers/admin.php +++ b/modules/gallery/controllers/admin.php @@ -44,7 +44,7 @@ class Admin_Controller extends Controller { } if (!method_exists($controller_name, $method)) { - return kohana::show_404(); + throw new Kohana_404_Exception(); } call_user_func_array(array(new $controller_name, $method), $args); diff --git a/modules/gallery/controllers/admin_advanced_settings.php b/modules/gallery/controllers/admin_advanced_settings.php index 79bc1183..391d2598 100644 --- a/modules/gallery/controllers/admin_advanced_settings.php +++ b/modules/gallery/controllers/admin_advanced_settings.php @@ -22,7 +22,8 @@ class Admin_Advanced_Settings_Controller extends Admin_Controller { $view = new Admin_View("admin.html"); $view->content = new View("admin_advanced_settings.html"); $view->content->vars = ORM::factory("var") - ->orderby("module_name", "name") + ->order_by("module_name") + ->order_by("name") ->find_all(); print $view; } diff --git a/modules/gallery/controllers/admin_dashboard.php b/modules/gallery/controllers/admin_dashboard.php index 7e28f625..5f2cb41d 100644 --- a/modules/gallery/controllers/admin_dashboard.php +++ b/modules/gallery/controllers/admin_dashboard.php @@ -86,7 +86,7 @@ class Admin_Dashboard_Controller extends Admin_Controller { foreach (array("dashboard_sidebar", "dashboard_center") as $location) { $new_blocks = array(); - foreach ($this->input->get($location, array()) as $id) { + foreach (Input::instance()->get($location, array()) as $id) { $new_blocks[$id] = $active_set[$id]; } block_manager::set_active($location, $new_blocks); diff --git a/modules/gallery/controllers/admin_identity.php b/modules/gallery/controllers/admin_identity.php index acf71665..354e6c0c 100644 --- a/modules/gallery/controllers/admin_identity.php +++ b/modules/gallery/controllers/admin_identity.php @@ -30,7 +30,7 @@ class Admin_Identity_Controller extends Admin_Controller { access::verify_csrf(); $v = new View("admin_identity_confirm.html"); - $v->new_provider = $this->input->post("provider"); + $v->new_provider = Input::instance()->post("provider"); print $v; } @@ -40,7 +40,7 @@ class Admin_Identity_Controller extends Admin_Controller { $active_provider = module::get_var("gallery", "identity_provider", "user"); $providers = identity::providers(); - $new_provider = $this->input->post("provider"); + $new_provider = Input::instance()->post("provider"); if ($new_provider != $active_provider) { diff --git a/modules/gallery/controllers/admin_languages.php b/modules/gallery/controllers/admin_languages.php index 27537c7f..41523023 100644 --- a/modules/gallery/controllers/admin_languages.php +++ b/modules/gallery/controllers/admin_languages.php @@ -36,10 +36,11 @@ class Admin_Languages_Controller extends Admin_Controller { public function save() { access::verify_csrf(); - locales::update_installed($this->input->post("installed_locales")); + $input = Input::instance(); + locales::update_installed($input->post("installed_locales")); $installed_locales = array_keys(locales::installed()); - $new_default_locale = $this->input->post("default_locale"); + $new_default_locale = $input->post("default_locale"); if (!in_array($new_default_locale, $installed_locales)) { if (!empty($installed_locales)) { $new_default_locale = $installed_locales[0]; @@ -61,7 +62,7 @@ class Admin_Languages_Controller extends Admin_Controller { return $this->index($form); } - if ($this->input->post("share")) { + if (Input::instance()->post("share")) { l10n_client::submit_translations(); message::success(t("Translations submitted")); } else { diff --git a/modules/gallery/controllers/admin_maintenance.php b/modules/gallery/controllers/admin_maintenance.php index 66bcce55..213e4fe2 100644 --- a/modules/gallery/controllers/admin_maintenance.php +++ b/modules/gallery/controllers/admin_maintenance.php @@ -22,11 +22,13 @@ class Admin_Maintenance_Controller extends Admin_Controller { * Show a list of all available, running and finished tasks. */ public function index() { - $query = Database::instance()->query( - "UPDATE {tasks} SET `state` = 'stalled' " . - "WHERE done = 0 " . - "AND state <> 'stalled' " . - "AND unix_timestamp(now()) - updated > 15"); + $query = db::build() + ->update("tasks") + ->set("state", "stalled") + ->where("done", "=", 0) + ->where("state", "<>", "stalled") + ->where(new Database_Expression("UNIX_TIMESTAMP(NOW()) - `updated` > 15")) + ->execute(); $stalled_count = $query->count(); if ($stalled_count) { log::warning("tasks", @@ -41,9 +43,9 @@ class Admin_Maintenance_Controller extends Admin_Controller { $view->content = new View("admin_maintenance.html"); $view->content->task_definitions = task::get_definitions(); $view->content->running_tasks = ORM::factory("task") - ->where("done", 0)->orderby("updated", "DESC")->find_all(); + ->where("done", "=", 0)->order_by("updated", "DESC")->find_all(); $view->content->finished_tasks = ORM::factory("task") - ->where("done", 1)->orderby("updated", "DESC")->find_all(); + ->where("done", "=", 1)->order_by("updated", "DESC")->find_all(); print $view; } @@ -75,7 +77,7 @@ class Admin_Maintenance_Controller extends Admin_Controller { access::verify_csrf(); $task = ORM::factory("task", $task_id); - if (!$task->loaded) { + if (!$task->loaded()) { throw new Exception("@todo MISSING_TASK"); } $view = new View("admin_maintenance_task.html"); @@ -97,7 +99,7 @@ class Admin_Maintenance_Controller extends Admin_Controller { access::verify_csrf(); $task = ORM::factory("task", $task_id); - if (!$task->loaded) { + if (!$task->loaded()) { throw new Exception("@todo MISSING_TASK"); } $view = new View("admin_maintenance_show_log.html"); @@ -114,7 +116,7 @@ class Admin_Maintenance_Controller extends Admin_Controller { access::verify_csrf(); $task = ORM::factory("task", $task_id); - if (!$task->loaded) { + if (!$task->loaded()) { throw new Exception("@todo MISSING_TASK"); } @@ -138,10 +140,12 @@ class Admin_Maintenance_Controller extends Admin_Controller { public function cancel_running_tasks() { access::verify_csrf(); - Database::instance()->update( - "tasks", - array("done" => 1, "state" => "cancelled"), - array("done" => 0)); + db::build() + ->update("tasks") + ->set("done", 1) + ->set("state", "cancelled") + ->where("done", "=", 0) + ->execute(); message::success(t("All running tasks cancelled")); url::redirect("admin/maintenance"); } @@ -164,7 +168,7 @@ class Admin_Maintenance_Controller extends Admin_Controller { // Do it the long way so we can call delete and remove the cache. $finished = ORM::factory("task") - ->where(array("done" => 1)) + ->where("done", "=", 1) ->find_all(); foreach ($finished as $task) { task::remove($task->id); @@ -184,7 +188,7 @@ class Admin_Maintenance_Controller extends Admin_Controller { try { $task = task::run($task_id); } catch (Exception $e) { - Kohana::log( + Kohana_Log::add( "error", sprintf( "%s in %s at line %s:\n%s", $e->getMessage(), $e->getFile(), diff --git a/modules/gallery/controllers/admin_modules.php b/modules/gallery/controllers/admin_modules.php index af6dbbdc..549718e7 100644 --- a/modules/gallery/controllers/admin_modules.php +++ b/modules/gallery/controllers/admin_modules.php @@ -37,7 +37,7 @@ class Admin_Modules_Controller extends Admin_Controller { continue; } - $desired = $this->input->post($module_name) == 1; + $desired = Input::instance()->post($module_name) == 1; if ($info->active && !$desired && module::is_active($module_name)) { $changes->deactivate[] = $module_name; $deactivated_names[] = t($info->name); diff --git a/modules/gallery/controllers/admin_sidebar.php b/modules/gallery/controllers/admin_sidebar.php index 77e83bc2..4c55bf89 100644 --- a/modules/gallery/controllers/admin_sidebar.php +++ b/modules/gallery/controllers/admin_sidebar.php @@ -34,7 +34,7 @@ class Admin_Sidebar_Controller extends Admin_Controller { $available_blocks = block_manager::get_available_site_blocks(); $active_blocks = array(); - foreach ($this->input->get("block", array()) as $block_id) { + foreach (Input::instance()->get("block", array()) as $block_id) { $active_blocks[md5($block_id)] = explode(":", (string) $block_id); } block_manager::set_active("site_sidebar", $active_blocks); diff --git a/modules/gallery/controllers/albums.php b/modules/gallery/controllers/albums.php index 3c1a0adf..2eeefdf1 100644 --- a/modules/gallery/controllers/albums.php +++ b/modules/gallery/controllers/albums.php @@ -42,7 +42,8 @@ class Albums_Controller extends Items_Controller { } } - $show = $this->input->get("show"); + $input = Input::instance(); + $show = $input->get("show"); if ($show) { $child = ORM::factory("item", $show); @@ -57,7 +58,7 @@ class Albums_Controller extends Items_Controller { } } - $page = $this->input->get("page", "1"); + $page = $input->get("page", "1"); $children_count = $album->viewable()->children_count(); $offset = ($page - 1) * $page_size; $max_pages = max(ceil($children_count / $page_size), 1); @@ -71,6 +72,7 @@ class Albums_Controller extends Items_Controller { $template = new Theme_View("page.html", "collection", "album"); $template->set_global("page", $page); + $template->set_global("page_title", null); $template->set_global("max_pages", $max_pages); $template->set_global("page_size", $page_size); $template->set_global("item", $album); @@ -81,7 +83,7 @@ class Albums_Controller extends Items_Controller { // We can't use math in ORM or the query builder, so do this by hand. It's important // that we do this with math, otherwise concurrent accesses will damage accuracy. - Database::instance()->query( + db::query( "UPDATE {items} SET `view_count` = `view_count` + 1 WHERE `id` = $album->id"); print $template; @@ -93,15 +95,16 @@ class Albums_Controller extends Items_Controller { access::required("view", $album); access::required("add", $album); + $input = Input::instance(); $form = album::get_add_form($album); if ($form->validate()) { $new_album = album::create( $album, - $this->input->post("name"), - $this->input->post("title", $this->input->post("name")), - $this->input->post("description"), + $input->post("name"), + $input->post("title", $input->post("name")), + $input->post("description"), identity::active_user()->id, - $this->input->post("slug")); + $input->post("slug")); log::success("content", "Created an album", html::anchor("albums/$new_album->id", "view album")); @@ -131,16 +134,16 @@ class Albums_Controller extends Items_Controller { $form->edit_item->dirname->value != $album->name || $form->edit_item->slug->value != $album->slug) { // Make sure that there's not a conflict - if ($row = Database::instance() + if ($row = db::build() ->select(array("name", "slug")) ->from("items") - ->where("parent_id", $album->parent_id) - ->where("id <>", $album->id) - ->open_paren() - ->where("name", $form->edit_item->dirname->value) - ->orwhere("slug", $form->edit_item->slug->value) - ->close_paren() - ->get() + ->where("parent_id", "=", $album->parent_id) + ->where("id", "<>", $album->id) + ->and_open() + ->where("name", "=", $form->edit_item->dirname->value) + ->or_where("slug", "=", $form->edit_item->slug->value) + ->close() + ->execute() ->current()) { if ($row->name == $form->edit_item->dirname->value) { $form->edit_item->dirname->add_error("name_conflict", 1); @@ -154,8 +157,6 @@ class Albums_Controller extends Items_Controller { } if ($valid) { - $watching_album = $album->url() != ($location = parse_url(request::referrer(), PHP_URL_PATH)); - $album->title = $form->edit_item->title->value; $album->description = $form->edit_item->description->value; $album->sort_column = $form->edit_item->sort_order->column->value; @@ -171,9 +172,13 @@ class Albums_Controller extends Items_Controller { message::success(t("Saved album %album_title", array("album_title" => html::purify($album->title)))); - print json_encode( - array("result" => "success", - "location" => $watching_album ? $location : $album->url())); + if ($form->from_id->value == $album->id) { + // Use the new url; it might have changed. + print json_encode(array("result" => "success", "location" => $album->url())); + } else { + // Stay on the same page + print json_encode(array("result" => "success")); + } } else { print json_encode( array("result" => "error", diff --git a/modules/gallery/controllers/combined.php b/modules/gallery/controllers/combined.php index c1f42bfe..e90a2f1a 100644 --- a/modules/gallery/controllers/combined.php +++ b/modules/gallery/controllers/combined.php @@ -22,7 +22,6 @@ class Combined_Controller extends Controller { * Return the combined Javascript bundle associated with the given key. */ public function javascript($key) { - $key = substr($key, 0, strlen($key) - 3); // strip off the trailing .js return $this->_emit("javascript", $key); } @@ -30,7 +29,6 @@ class Combined_Controller extends Controller { * Return the combined CSS bundle associated with the given key. */ public function css($key) { - $key = substr($key, 0, strlen($key) - 4); // strip off the trailing .css return $this->_emit("css", $key); } @@ -56,7 +54,7 @@ class Combined_Controller extends Controller { } if (empty($key)) { - Kohana::show_404(); + throw new Kohana_404_Exception(); } $cache = Cache::instance(); @@ -71,7 +69,7 @@ class Combined_Controller extends Controller { $content = $cache->get($key); } if (empty($content)) { - Kohana::show_404(); + throw new Kohana_404_Exception(); } // $type is either 'javascript' or 'css' diff --git a/modules/gallery/controllers/file_proxy.php b/modules/gallery/controllers/file_proxy.php index 8fde1132..72c4e104 100644 --- a/modules/gallery/controllers/file_proxy.php +++ b/modules/gallery/controllers/file_proxy.php @@ -29,7 +29,7 @@ class File_Proxy_Controller extends Controller { public function __call($function, $args) { // request_uri: http://example.com/gallery3/var/trunk/albums/foo/bar.jpg - $request_uri = $this->input->server("REQUEST_URI"); + $request_uri = Input::instance()->server("REQUEST_URI"); $request_uri = preg_replace("/\?.*/", "", $request_uri); // var_uri: http://example.com/gallery3/var/ @@ -38,27 +38,27 @@ class File_Proxy_Controller extends Controller { // Make sure that the request is for a file inside var $offset = strpos($request_uri, $var_uri); if ($offset === false) { - kohana::show_404(); + throw new Kohana_404_Exception(); } $file_uri = substr($request_uri, strlen($var_uri)); // Make sure that we don't leave the var dir if (strpos($file_uri, "..") !== false) { - kohana::show_404(); + throw new Kohana_404_Exception(); } list ($type, $path) = explode("/", $file_uri, 2); if ($type != "resizes" && $type != "albums" && $type != "thumbs") { - kohana::show_404(); + throw new Kohana_404_Exception(); } // If the last element is .album.jpg, pop that off since it's not a real item $path = preg_replace("|/.album.jpg$|", "", $path); // We now have the relative path to the item. Search for it in the path cache - $item = ORM::factory("item")->where("relative_path_cache", $path)->find(); - if (!$item->loaded) { + $item = ORM::factory("item")->where("relative_path_cache", "=", $path)->find(); + if (!$item->loaded()) { // We didn't turn it up. It's possible that the relative_path_cache is out of date here. // There was fallback code, but bharat deleted it in 8f1bca74. If it turns out to be // necessary, it's easily resurrected. @@ -69,16 +69,16 @@ class File_Proxy_Controller extends Controller { if (preg_match('/.jpg$/', $path)) { foreach (array("flv", "mp4") as $ext) { $movie_path = preg_replace('/.jpg$/', ".$ext", $path); - $item = ORM::factory("item")->where("relative_path_cache", $movie_path)->find(); - if ($item->loaded) { + $item = ORM::factory("item")->where("relative_path_cache", "=", $movie_path)->find(); + if ($item->loaded()) { break; } } } } - if (!$item->loaded) { - kohana::show_404(); + if (!$item->loaded()) { + throw new Kohana_404_Exception(); } if ($type == "albums") { @@ -91,26 +91,34 @@ class File_Proxy_Controller extends Controller { // Make sure we have access to the item if (!access::can("view", $item)) { - kohana::show_404(); + throw new Kohana_404_Exception(); } // Make sure we have view_full access to the original if ($type == "albums" && !access::can("view_full", $item)) { - kohana::show_404(); + throw new Kohana_404_Exception(); + } + + // Check that the content hasn't expired or it wasn't changed since cached + if (($last_modified = expires::get()) !== false && + $item->updated < $last_modified) { + expires::check(2592000); } // Don't try to load a directory if ($type == "albums" && $item->is_album()) { - kohana::show_404(); + throw new Kohana_404_Exception(); } if (!file_exists($file)) { - kohana::show_404(); + throw new Kohana_404_Exception(); } // We don't need to save the session for this request Session::abort_save(); + expires::set(2592000); // 30 days + // Dump out the image. If the item is a movie, then its thumbnail will be a JPG. if ($item->is_movie() && $type != "albums") { header("Content-type: image/jpeg"); diff --git a/modules/gallery/controllers/items.php b/modules/gallery/controllers/items.php index b350c5a2..f261e3a9 100644 --- a/modules/gallery/controllers/items.php +++ b/modules/gallery/controllers/items.php @@ -20,8 +20,8 @@ class Items_Controller extends Controller { public function __call($function, $args) { $item = ORM::factory("item", (int)$function); - if (!$item->loaded) { - return Kohana::show_404(); + if (!$item->loaded()) { + throw new Kohana_404_Exception(); } // Redirect to the more specific resource type, since it will render diff --git a/modules/gallery/controllers/l10n_client.php b/modules/gallery/controllers/l10n_client.php index 6db67d3b..71df1cf1 100644 --- a/modules/gallery/controllers/l10n_client.php +++ b/modules/gallery/controllers/l10n_client.php @@ -24,7 +24,7 @@ class L10n_Client_Controller extends Controller { access::forbidden(); } - $locale = I18n::instance()->locale(); + $locale = Gallery_I18n::instance()->locale(); $input = Input::instance(); $key = $input->post("l10n-message-key"); @@ -33,10 +33,10 @@ class L10n_Client_Controller extends Controller { "locale" => "root")) ->find(); - if (!$root_message->loaded) { + if (!$root_message->loaded()) { throw new Exception("@todo bad request data / illegal state"); } - $is_plural = I18n::is_plural_message(unserialize($root_message->message)); + $is_plural = Gallery_I18n::is_plural_message(unserialize($root_message->message)); if ($is_plural) { $plural_forms = l10n_client::plural_forms($locale); @@ -60,7 +60,7 @@ class L10n_Client_Controller extends Controller { "locale" => $locale)) ->find(); - if (!$entry->loaded) { + if (!$entry->loaded()) { $entry->key = $key; $entry->locale = $locale; $entry->message = $root_message->message; @@ -74,7 +74,7 @@ class L10n_Client_Controller extends Controller { "locale" => $locale)) ->find(); - if (!$entry_from_incoming->loaded) { + if (!$entry_from_incoming->loaded()) { $entry->base_revision = $entry_from_incoming->revision; } @@ -113,36 +113,33 @@ class L10n_Client_Controller extends Controller { public static function l10n_form() { if (Input::instance()->get("show_all_l10n_messages")) { $calls = array(); - foreach (Database::instance() + foreach (db::build() ->select("key", "message") ->from("incoming_translations") - ->where(array("locale" => 'root')) - ->get() - ->as_array() as $row) { + ->where("locale", "=", "root") + ->execute() as $row) { $calls[$row->key] = array(unserialize($row->message), array()); } } else { - $calls = I18n::instance()->call_log(); + $calls = Gallery_I18n::instance()->call_log(); } - $locale = I18n::instance()->locale(); + $locale = Gallery_I18n::instance()->locale(); if ($calls) { $translations = array(); - foreach (Database::instance() + foreach (db::build() ->select("key", "translation") ->from("incoming_translations") - ->where(array("locale" => $locale)) - ->get() - ->as_array() as $row) { + ->where("locale", "=", $locale) + ->execute() as $row) { $translations[$row->key] = unserialize($row->translation); } // Override incoming with outgoing... - foreach (Database::instance() + foreach (db::build() ->select("key", "translation") ->from("outgoing_translations") - ->where(array("locale" => $locale)) - ->get() - ->as_array() as $row) { + ->where("locale", "=", $locale) + ->execute() as $row) { $translations[$row->key] = unserialize($row->translation); } diff --git a/modules/gallery/controllers/logout.php b/modules/gallery/controllers/logout.php index 2b93655d..fe9c48ba 100644 --- a/modules/gallery/controllers/logout.php +++ b/modules/gallery/controllers/logout.php @@ -20,7 +20,7 @@ class Logout_Controller extends Controller { public function index() { auth::logout(); - if ($continue_url = $this->input->get("continue")) { + if ($continue_url = Input::instance()->get("continue")) { $item = url::get_item_from_uri($continue_url); if (access::can("view", $item)) { // Don't use url::redirect() because it'll call url::site() and munge the continue url. diff --git a/modules/gallery/controllers/move.php b/modules/gallery/controllers/move.php index 87b73436..14513fdc 100644 --- a/modules/gallery/controllers/move.php +++ b/modules/gallery/controllers/move.php @@ -32,7 +32,7 @@ class Move_Controller extends Controller { public function save($source_id) { access::verify_csrf(); $source = ORM::factory("item", $source_id); - $target = ORM::factory("item", $this->input->post("target_id")); + $target = ORM::factory("item", Input::instance()->post("target_id")); access::required("view", $source); access::required("edit", $source); @@ -64,8 +64,8 @@ class Move_Controller extends Controller { $view->parent = $target; $view->children = ORM::factory("item") ->viewable() - ->where("type", "album") - ->where("parent_id", $target->id) + ->where("type", "=", "album") + ->where("parent_id", "=", $target->id) ->find_all(); return $view; } diff --git a/modules/gallery/controllers/movies.php b/modules/gallery/controllers/movies.php index 575b2b60..7a8e4d2a 100644 --- a/modules/gallery/controllers/movies.php +++ b/modules/gallery/controllers/movies.php @@ -26,7 +26,7 @@ class Movies_Controller extends Items_Controller { } access::required("view", $movie); - $where = array("type != " => "album"); + $where = array(array("type", "!=", "album")); $position = $movie->parent()->get_position($movie, $where); if ($position > 1) { list ($previous_item, $ignore, $next_item) = @@ -76,16 +76,16 @@ class Movies_Controller extends Items_Controller { if ($form->edit_item->filename->value != $movie->name || $form->edit_item->slug->value != $movie->slug) { // Make sure that there's not a name or slug conflict - if ($row = Database::instance() + if ($row = db::build() ->select(array("name", "slug")) ->from("items") - ->where("parent_id", $movie->parent_id) - ->where("id <>", $movie->id) - ->open_paren() - ->where("name", $form->edit_item->filename->value) - ->orwhere("slug", $form->edit_item->slug->value) - ->close_paren() - ->get() + ->where("parent_id", "=", $movie->parent_id) + ->where("id", "<>", $movie->id) + ->and_open() + ->where("name", "=", $form->edit_item->filename->value) + ->or_where("slug", "=", $form->edit_item->slug->value) + ->close() + ->execute() ->current()) { if ($row->name == $form->edit_item->filename->value) { $form->edit_item->filename->add_error("name_conflict", 1); @@ -110,8 +110,13 @@ class Movies_Controller extends Items_Controller { message::success( t("Saved movie %movie_title", array("movie_title" => $movie->title))); - print json_encode( - array("result" => "success")); + if ($form->from_id->value == $movie->id) { + // Use the new url; it might have changed. + print json_encode(array("result" => "success", "location" => $movie->url())); + } else { + // Stay on the same page + print json_encode(array("result" => "success")); + } } else { print json_encode( array("result" => "error", @@ -123,6 +128,7 @@ class Movies_Controller extends Items_Controller { $movie = ORM::factory("item", $movie_id); access::required("view", $movie); access::required("edit", $movie); + print movie::get_edit_form($movie); } } diff --git a/modules/gallery/controllers/packager.php b/modules/gallery/controllers/packager.php index 1354a01b..cb64f1bf 100644 --- a/modules/gallery/controllers/packager.php +++ b/modules/gallery/controllers/packager.php @@ -30,7 +30,7 @@ class Packager_Controller extends Controller { $this->_dump_database(); // Dump the database $this->_dump_var(); // Dump the var directory } catch (Exception $e) { - print $e->getTraceAsString(); + print $e->getMessage() . "\n" . $e->getTraceAsString(); return; } @@ -38,11 +38,9 @@ class Packager_Controller extends Controller { } private function _reset() { - $db = Database::instance(); - // Drop all tables - foreach ($db->list_tables() as $table) { - $db->query("DROP TABLE IF EXISTS `$table`"); + foreach (Database::instance()->list_tables() as $table) { + Database::instance()->query("DROP TABLE IF EXISTS {{$table}}"); } // Clean out data @@ -53,7 +51,7 @@ class Packager_Controller extends Controller { dir::unlink(VARPATH . "modules"); dir::unlink(VARPATH . "tmp"); - $db->clear_cache(); + Database::instance()->clear_cache(); module::$modules = array(); module::$active = array(); @@ -84,12 +82,17 @@ class Packager_Controller extends Controller { module::set_var("gallery", "blocks_{$key}", serialize($blocks)); } - $db = Database::instance(); - $db->query("TRUNCATE {sessions}"); - $db->query("TRUNCATE {logs}"); - $db->query("DELETE FROM {vars} WHERE `module_name` = 'gallery' AND `name` = '_cache'"); - $db->update("users", array("password" => ""), array("id" => 1)); - $db->update("users", array("password" => ""), array("id" => 2)); + Database::instance()->query("TRUNCATE {sessions}"); + Database::instance()->query("TRUNCATE {logs}"); + db::build() + ->delete("vars") + ->where("module_name", "=", "gallery") + ->where("name", "=", "_cache") + ->execute(); + db::build()->update("users") + ->set(array("password" => "")) + ->where("id", "in", array(1, 2)) + ->execute(); $dbconfig = Kohana::config('database.default'); $conn = $dbconfig["connection"]; diff --git a/modules/gallery/controllers/permissions.php b/modules/gallery/controllers/permissions.php index 99943fbb..e03f41a9 100644 --- a/modules/gallery/controllers/permissions.php +++ b/modules/gallery/controllers/permissions.php @@ -57,7 +57,7 @@ class Permissions_Controller extends Controller { access::required("view", $item); access::required("edit", $item); - if (!empty($group) && $perm->loaded && $item->loaded) { + if (!empty($group) && $perm->loaded() && $item->loaded()) { switch($command) { case "allow": access::allow($group, $perm->name, $item); diff --git a/modules/gallery/controllers/photos.php b/modules/gallery/controllers/photos.php index ba4cfb83..56b454ce 100644 --- a/modules/gallery/controllers/photos.php +++ b/modules/gallery/controllers/photos.php @@ -26,7 +26,7 @@ class Photos_Controller extends Items_Controller { } access::required("view", $photo); - $where = array("type != " => "album"); + $where = array(array("type", "!=", "album")); $position = $photo->parent()->get_position($photo, $where); if ($position > 1) { list ($previous_item, $ignore, $next_item) = @@ -76,16 +76,16 @@ class Photos_Controller extends Items_Controller { if ($form->edit_item->filename->value != $photo->name || $form->edit_item->slug->value != $photo->slug) { // Make sure that there's not a name or slug conflict - if ($row = Database::instance() + if ($row = db::build() ->select(array("name", "slug")) ->from("items") - ->where("parent_id", $photo->parent_id) - ->where("id <>", $photo->id) - ->open_paren() - ->where("name", $form->edit_item->filename->value) - ->orwhere("slug", $form->edit_item->slug->value) - ->close_paren() - ->get() + ->where("parent_id", "=", $photo->parent_id) + ->where("id", "<>", $photo->id) + ->and_open() + ->where("name", "=", $form->edit_item->filename->value) + ->or_where("slug", "=", $form->edit_item->slug->value) + ->close() + ->execute() ->current()) { if ($row->name == $form->edit_item->filename->value) { $form->edit_item->filename->add_error("name_conflict", 1); @@ -99,8 +99,6 @@ class Photos_Controller extends Items_Controller { } if ($valid) { - $watching_album = $photo->url() != ($location = parse_url(request::referrer(), PHP_URL_PATH)); - $photo->title = $form->edit_item->title->value; $photo->description = $form->edit_item->description->value; $photo->slug = $form->edit_item->slug->value; @@ -110,12 +108,15 @@ class Photos_Controller extends Items_Controller { log::success("content", "Updated photo", "<a href=\"{$photo->url()}\">view</a>"); message::success( - t("Saved photo %photo_title", - array("photo_title" => html::purify($photo->title)))); + t("Saved photo %photo_title", array("photo_title" => html::purify($photo->title)))); - print json_encode( - array("result" => "success", - "location" => $watching_album ? $location : $photo->url())); + if ($form->from_id->value == $photo->id) { + // Use the new url; it might have changed. + print json_encode(array("result" => "success", "location" => $photo->url())); + } else { + // Stay on the same page + print json_encode(array("result" => "success")); + } } else { print json_encode( array("result" => "error", diff --git a/modules/gallery/controllers/quick.php b/modules/gallery/controllers/quick.php index 7f1ad43b..7f9a9826 100644 --- a/modules/gallery/controllers/quick.php +++ b/modules/gallery/controllers/quick.php @@ -133,13 +133,21 @@ class Quick_Controller extends Controller { switch ($item->type) { case "album": - return print album::get_edit_form($item); + $form = album::get_edit_form($item); + break; case "photo": - return print photo::get_edit_form($item); + $form = photo::get_edit_form($item); + break; case "movie": - return print movie::get_edit_form($item); + $form = movie::get_edit_form($item); + break; } + + // Pass on the source item where this form was generated, so we have an idea where to return to. + $form->hidden("from_id")->value((int)Input::instance()->get("from_id", 0)); + + print $form; } } diff --git a/modules/gallery/controllers/simple_uploader.php b/modules/gallery/controllers/simple_uploader.php index 37753ff3..5d32e35f 100644 --- a/modules/gallery/controllers/simple_uploader.php +++ b/modules/gallery/controllers/simple_uploader.php @@ -72,7 +72,7 @@ class Simple_Uploader_Controller extends Controller { module::event("add_photos_form_completed", $item, $form); } } catch (Exception $e) { - Kohana::log("alert", $e->__toString()); + Kohana_Log::add("alert", $e->__toString()); if (file_exists($temp_filename)) { unlink($temp_filename); } diff --git a/modules/gallery/helpers/MY_url.php b/modules/gallery/helpers/MY_url.php index 139aec21..74284951 100644 --- a/modules/gallery/helpers/MY_url.php +++ b/modules/gallery/helpers/MY_url.php @@ -32,7 +32,7 @@ class url extends url_Core { } $item = self::get_item_from_uri(Router::$current_uri); - if ($item && $item->loaded) { + if ($item && $item->loaded()) { Router::$controller = "{$item->type}s"; Router::$controller_path = MODPATH . "gallery/controllers/{$item->type}s.php"; Router::$method = "show"; @@ -51,12 +51,12 @@ class url extends url_Core { // In most cases, we'll have an exact match in the relative_url_cache item field. // but failing that, walk down the tree until we find it. The fallback code will fix caches // as it goes, so it'll never be run frequently. - $item = ORM::factory("item")->where("relative_url_cache", $current_uri)->find(); - if (!$item->loaded) { + $item = ORM::factory("item")->where("relative_url_cache", "=", $current_uri)->find(); + if (!$item->loaded()) { $count = count(Router::$segments); foreach (ORM::factory("item") - ->where("slug", html_entity_decode(Router::$segments[$count - 1], ENT_QUOTES)) - ->where("level", $count + 1) + ->where("slug", "=", html_entity_decode(Router::$segments[$count - 1], ENT_QUOTES)) + ->where("level", "=", $count + 1) ->find_all() as $match) { if ($match->relative_url() == $current_uri) { $item = $match; diff --git a/modules/gallery/helpers/access.php b/modules/gallery/helpers/access.php index 88a02ce2..8ce7e436 100644 --- a/modules/gallery/helpers/access.php +++ b/modules/gallery/helpers/access.php @@ -91,7 +91,7 @@ class access_Core { * @return boolean */ static function user_can($user, $perm_name, $item) { - if (!$item->loaded) { + if (!$item->loaded()) { return false; } @@ -101,7 +101,7 @@ class access_Core { $resource = $perm_name == "view" ? $item : model_cache::get("access_cache", $item->id, "item_id"); - foreach ($user->groups as $group) { + foreach ($user->groups() as $group) { if ($resource->__get("{$perm_name}_{$group->id}") === self::ALLOW) { return true; } @@ -166,16 +166,16 @@ class access_Core { // For view permissions, if any parent is self::DENY, then those parents lock this one. // Return $lock = ORM::factory("item") - ->where("`left_ptr` <= $item->left_ptr") - ->where("`right_ptr` >= $item->right_ptr") - ->where("items.id <> $item->id") + ->where("left_ptr", "<=", $item->left_ptr) + ->where("right_ptr", ">=", $item->right_ptr) + ->where("items.id", "<>", $item->id) ->join("access_intents", "items.id", "access_intents.item_id") - ->where("access_intents.view_$group->id", self::DENY) - ->orderby("level", "DESC") + ->where("access_intents.view_$group->id", "=", self::DENY) + ->order_by("level", "DESC") ->limit(1) ->find(); - if ($lock->loaded) { + if ($lock->loaded()) { return $lock; } else { return null; @@ -201,7 +201,7 @@ class access_Core { if (!($group instanceof Group_Definition)) { throw new Exception("@todo PERMISSIONS_ONLY_WORK_ON_GROUPS"); } - if (!$album->loaded) { + if (!$album->loaded()) { throw new Exception("@todo INVALID_ALBUM $album->id"); } if (!$album->is_album()) { @@ -282,7 +282,7 @@ class access_Core { */ static function register_permission($name, $display_name) { $permission = ORM::factory("permission", $name); - if ($permission->loaded) { + if ($permission->loaded()) { throw new Exception("@todo PERMISSION_ALREADY_EXISTS $name"); } $permission->name = $name; @@ -304,8 +304,8 @@ class access_Core { foreach (self::_get_all_groups() as $group) { self::_drop_columns($name, $group); } - $permission = ORM::factory("permission")->where("name", $name)->find(); - if ($permission->loaded) { + $permission = ORM::factory("permission")->where("name", "=", $name)->find(); + if ($permission->loaded()) { $permission->delete(); } } @@ -342,7 +342,7 @@ class access_Core { */ static function add_item($item) { $access_intent = ORM::factory("access_intent", $item->id); - if ($access_intent->loaded) { + if ($access_intent->loaded()) { throw new Exception("@todo ITEM_ALREADY_ADDED $item->id"); } $access_intent = ORM::factory("access_intent"); @@ -354,7 +354,7 @@ class access_Core { $access_cache->item_id = $item->id; if ($item->id != 1) { $parent_access_cache = - ORM::factory("access_cache")->where("item_id", $item->parent()->id)->find(); + ORM::factory("access_cache")->where("item_id", "=", $item->parent()->id)->find(); foreach (self::_get_all_groups() as $group) { foreach (ORM::factory("permission")->find_all() as $perm) { $field = "{$perm->name}_{$group->id}"; @@ -377,8 +377,8 @@ class access_Core { * @return void */ static function delete_item($item) { - ORM::factory("access_intent")->where("item_id", $item->id)->find()->delete(); - ORM::factory("access_cache")->where("item_id", $item->id)->find()->delete(); + ORM::factory("access_intent")->where("item_id", "=", $item->id)->find()->delete(); + ORM::factory("access_cache")->where("item_id", "=", $item->id)->find()->delete(); } /** @@ -419,8 +419,8 @@ class access_Core { * @return ORM_Iterator */ private static function _get_all_groups() { - // When we build the gallery package, it's possible that there is no identity provider installed yet. - // This is ok at packaging time, so work around it. + // When we build the gallery package, it's possible that there is no identity provider + // installed yet. This is ok at packaging time, so work around it. if (module::is_active(module::get_var("gallery", "identity_provider", "user"))) { return identity::groups(); } else { @@ -436,11 +436,10 @@ class access_Core { * @return void */ private static function _drop_columns($perm_name, $group) { - $db = Database::instance(); $field = "{$perm_name}_{$group->id}"; $cache_table = $perm_name == "view" ? "items" : "access_caches"; - $db->query("ALTER TABLE {{$cache_table}} DROP `$field`"); - $db->query("ALTER TABLE {access_intents} DROP `$field`"); + Database::instance()->query("ALTER TABLE {{$cache_table}} DROP `$field`"); + Database::instance()->query("ALTER TABLE {access_intents} DROP `$field`"); model_cache::clear(); ORM::factory("access_intent")->clear_cache(); } @@ -453,13 +452,18 @@ class access_Core { * @return void */ private static function _add_columns($perm_name, $group) { - $db = Database::instance(); $field = "{$perm_name}_{$group->id}"; $cache_table = $perm_name == "view" ? "items" : "access_caches"; $not_null = $cache_table == "items" ? "" : "NOT NULL"; - $db->query("ALTER TABLE {{$cache_table}} ADD `$field` BINARY $not_null DEFAULT FALSE"); - $db->query("ALTER TABLE {access_intents} ADD `$field` BINARY DEFAULT NULL"); - $db->update("access_intents", array($field => self::DENY), array("item_id" => 1)); + Database::instance()->query( + "ALTER TABLE {{$cache_table}} ADD `$field` BINARY $not_null DEFAULT FALSE"); + Database::instance()->query( + "ALTER TABLE {access_intents} ADD `$field` BINARY DEFAULT NULL"); + db::build() + ->update("access_intents") + ->set($field, self::DENY) + ->where("item_id", "=", 1) + ->execute(); model_cache::clear(); ORM::factory("access_intent")->clear_cache(); } @@ -475,9 +479,7 @@ class access_Core { * @return void */ private static function _update_access_view_cache($group, $item) { - $access = ORM::factory("access_intent")->where("item_id", $item->id)->find(); - - $db = Database::instance(); + $access = ORM::factory("access_intent")->where("item_id", "=", $item->id)->find(); $field = "view_{$group->id}"; // With view permissions, deny values in the parent can override allow values in the child, @@ -490,14 +492,14 @@ class access_Core { // item, then its safe to propagate from here. if ($access->$field !== self::DENY) { $tmp_item = ORM::factory("item") - ->where("left_ptr <", $item->left_ptr) - ->where("right_ptr >", $item->right_ptr) + ->where("left_ptr", "<", $item->left_ptr) + ->where("right_ptr", ">", $item->right_ptr) ->join("access_intents", "access_intents.item_id", "items.id") - ->where("access_intents.$field", self::DENY) - ->orderby("left_ptr", "DESC") + ->where("access_intents.$field", "=", self::DENY) + ->order_by("left_ptr", "DESC") ->limit(1) ->find(); - if ($tmp_item->loaded) { + if ($tmp_item->loaded()) { $item = $tmp_item; } } @@ -506,35 +508,53 @@ class access_Core { // access_caches table will already contain DENY values and we won't be able to overwrite // them according the rule above. So mark every permission below this level as UNKNOWN so // that we can tell which permissions have been changed, and which ones need to be updated. - $db->update("items", array($field => self::UNKNOWN), - array("left_ptr >=" => $item->left_ptr, "right_ptr <=" => $item->right_ptr)); + db::build() + ->update("items") + ->set($field, self::UNKNOWN) + ->where("left_ptr", ">=", $item->left_ptr) + ->where("right_ptr", "<=", $item->right_ptr) + ->execute(); $query = ORM::factory("access_intent") ->select(array("access_intents.$field", "items.left_ptr", "items.right_ptr", "items.id")) ->join("items", "items.id", "access_intents.item_id") - ->where("left_ptr >=", $item->left_ptr) - ->where("right_ptr <=", $item->right_ptr) - ->where("type", "album") - ->where("access_intents.$field IS NOT", self::INHERIT) - ->orderby("level", "DESC") + ->where("left_ptr", ">=", $item->left_ptr) + ->where("right_ptr", "<=", $item->right_ptr) + ->where("type", "=", "album") + ->where("access_intents.$field", "IS NOT", self::INHERIT) + ->order_by("level", "DESC") ->find_all(); foreach ($query as $row) { if ($row->$field == self::ALLOW) { // Propagate ALLOW for any row that is still UNKNOWN. - $db->update("items", array($field => $row->$field), - array($field => self::UNKNOWN, "left_ptr >=" => $row->left_ptr, "right_ptr <=" => $row->right_ptr)); + db::build() + ->update("items") + ->set($field, $row->$field) + ->where($field, "IS", self::UNKNOWN) // UNKNOWN is NULL so we have to use IS + ->where("left_ptr", ">=", $row->left_ptr) + ->where("right_ptr", "<=", $row->right_ptr) + ->execute(); } else if ($row->$field == self::DENY) { // DENY overwrites everything below it - $db->update("items", array($field => $row->$field), - array("left_ptr >=" => $row->left_ptr, "right_ptr <=" => $row->right_ptr)); + db::build() + ->update("items") + ->set($field, $row->$field) + ->where("left_ptr", ">=", $row->left_ptr) + ->where("right_ptr", "<=", $row->right_ptr) + ->execute(); } } // Finally, if our intent is DEFAULT at this point it means that we were unable to find a // DENY parent in the hierarchy to propagate from. So we'll still have a UNKNOWN values in // the hierarchy, and all of those are safe to change to ALLOW. - $db->update("items", array($field => self::ALLOW), - array($field => self::UNKNOWN, "left_ptr >=" => $item->left_ptr, "right_ptr <=" => $item->right_ptr)); + db::build() + ->update("items") + ->set($field, self::ALLOW) + ->where($field, "IS", self::UNKNOWN) // UNKNOWN is NULL so we have to use IS + ->where("left_ptr", ">=", $item->left_ptr) + ->where("right_ptr", "<=", $item->right_ptr) + ->execute(); } /** @@ -549,9 +569,8 @@ class access_Core { * @return void */ private static function _update_access_non_view_cache($group, $perm_name, $item) { - $access = ORM::factory("access_intent")->where("item_id", $item->id)->find(); + $access = ORM::factory("access_intent")->where("item_id", "=", $item->id)->find(); - $db = Database::instance(); $field = "{$perm_name}_{$group->id}"; // If the item's intent is DEFAULT, then we need to back up the chain to find the nearest @@ -562,13 +581,13 @@ class access_Core { if ($access->$field === self::INHERIT) { $tmp_item = ORM::factory("item") ->join("access_intents", "items.id", "access_intents.item_id") - ->where("left_ptr <", $item->left_ptr) - ->where("right_ptr >", $item->right_ptr) - ->where("$field IS NOT", self::UNKNOWN) - ->orderby("left_ptr", "DESC") + ->where("left_ptr", "<", $item->left_ptr) + ->where("right_ptr", ">", $item->right_ptr) + ->where($field, "IS NOT", self::UNKNOWN) // UNKNOWN is NULL so we have to use IS NOT + ->order_by("left_ptr", "DESC") ->limit(1) ->find(); - if ($tmp_item->loaded) { + if ($tmp_item->loaded()) { $item = $tmp_item; } } @@ -578,19 +597,23 @@ class access_Core { $query = ORM::factory("access_intent") ->select(array("access_intents.$field", "items.left_ptr", "items.right_ptr")) ->join("items", "items.id", "access_intents.item_id") - ->where("left_ptr >=", $item->left_ptr) - ->where("right_ptr <=", $item->right_ptr) - ->where("$field IS NOT", self::INHERIT) - ->orderby("level", "ASC") + ->where("left_ptr", ">=", $item->left_ptr) + ->where("right_ptr", "<=", $item->right_ptr) + ->where($field, "IS NOT", self::INHERIT) + ->order_by("level", "ASC") ->find_all(); - foreach ($query as $row) { - $value = ($row->$field === self::ALLOW) ? "TRUE" : "FALSE"; - $db->query( - "UPDATE {access_caches} SET `$field` = $value " . - "WHERE `item_id` IN " . - " (SELECT `id` FROM {items} " . - " WHERE `left_ptr` >= $row->left_ptr " . - " AND `right_ptr` <= $row->right_ptr)"); + foreach ($query as $row) { + $value = ($row->$field === self::ALLOW) ? true : false; + db::build() + ->update("access_caches") + ->set($field, $value) + ->where("item_id", "IN", + db::build() + ->select("id") + ->from("items") + ->where("left_ptr", ">=", $row->left_ptr) + ->where("right_ptr", "<=", $row->right_ptr)) + ->execute(); } } diff --git a/modules/gallery/helpers/album.php b/modules/gallery/helpers/album.php index cc631be4..feaf74cc 100644 --- a/modules/gallery/helpers/album.php +++ b/modules/gallery/helpers/album.php @@ -34,7 +34,7 @@ class album_Core { * @return Item_Model */ static function create($parent, $name, $title, $description=null, $owner_id=null, $slug=null) { - if (!$parent->loaded || !$parent->is_album()) { + if (!$parent->loaded() || !$parent->is_album()) { throw new Exception("@todo INVALID_PARENT"); } @@ -68,11 +68,11 @@ class album_Core { // Randomize the name or slug if there's a conflict // @todo Improve this. Random numbers are not user friendly while (ORM::factory("item") - ->where("parent_id", $parent->id) - ->open_paren() - ->where("name", $album->name) - ->orwhere("slug", $album->slug) - ->close_paren() + ->where("parent_id", "=", $parent->id) + ->and_open() + ->where("name", "=", $album->name) + ->or_where("slug", "=", $album->slug) + ->close() ->find()->id) { $rand = rand(); $album->name = "{$name}-$rand"; @@ -115,6 +115,7 @@ class album_Core { static function get_edit_form($parent) { $form = new Forge("albums/update/{$parent->id}", "", "post", array("id" => "g-edit-album-form")); + $form->hidden("from_id"); $group = $form->group("edit_item")->label(t("Edit Album")); $group->input("title")->label(t("Title"))->value($parent->title); diff --git a/modules/gallery/helpers/auth.php b/modules/gallery/helpers/auth.php index 9c69cecd..21a39bfb 100644 --- a/modules/gallery/helpers/auth.php +++ b/modules/gallery/helpers/auth.php @@ -46,7 +46,7 @@ class auth_Core { try { Session::instance()->destroy(); } catch (Exception $e) { - Kohana::log("error", $e); + Kohana_Log::add("error", $e); } module::event("user_logout", $user); } diff --git a/modules/gallery/helpers/gallery_block.php b/modules/gallery/helpers/gallery_block.php index b5c32ad2..9d4e81b6 100644 --- a/modules/gallery/helpers/gallery_block.php +++ b/modules/gallery/helpers/gallery_block.php @@ -34,7 +34,7 @@ class gallery_block_Core { static function get($block_id) { $block = new Block(); - switch($block_id) { + switch ($block_id) { case "welcome": $block->css_id = "g-welcome"; $block->title = t("Welcome to Gallery 3"); @@ -45,8 +45,8 @@ class gallery_block_Core { $block->css_id = "g-photo-stream"; $block->title = t("Photo stream"); $block->content = new View("admin_block_photo_stream.html"); - $block->content->photos = - ORM::factory("item")->where("type", "photo")->orderby("created", "DESC")->find_all(10); + $block->content->photos = ORM::factory("item") + ->where("type", "=", "photo")->order_by("created", "DESC")->find_all(10); break; case "log_entries": @@ -54,7 +54,7 @@ class gallery_block_Core { $block->title = t("Log entries"); $block->content = new View("admin_block_log_entries.html"); $block->content->entries = ORM::factory("log") - ->orderby(array("timestamp" => "DESC", "id" => "DESC"))->find_all(5); + ->order_by(array("timestamp" => "DESC", "id" => "DESC"))->find_all(5); break; case "stats": @@ -62,8 +62,8 @@ class gallery_block_Core { $block->title = t("Gallery stats"); $block->content = new View("admin_block_stats.html"); $block->content->album_count = - ORM::factory("item")->where("type", "album")->where("id <>", 1)->count_all(); - $block->content->photo_count = ORM::factory("item")->where("type", "photo")->count_all(); + ORM::factory("item")->where("type", "=", "album")->where("id", "<>", 1)->count_all(); + $block->content->photo_count = ORM::factory("item")->where("type", "=", "photo")->count_all(); break; case "platform_info": @@ -101,8 +101,7 @@ class gallery_block_Core { $block->css_id = "g-user-language-block"; $block->title = t("Language preference"); $block->content = new View("user_languages_block.html"); - $block->content->installed_locales = - array_merge(array("" => t("« none »")), $locales); + $block->content->installed_locales = array_merge(array("" => t("« none »")), $locales); $block->content->selected = (string) locales::cookie_locale(); } else { $block = ""; diff --git a/modules/gallery/helpers/gallery_event.php b/modules/gallery/helpers/gallery_event.php index 02bfdf28..5565850d 100644 --- a/modules/gallery/helpers/gallery_event.php +++ b/modules/gallery/helpers/gallery_event.php @@ -30,36 +30,37 @@ class gallery_event_Core { static function user_deleted($user) { $admin = identity::admin_user(); - $db = Database::instance(); - $db->from("tasks") - ->set(array("owner_id" => $admin->id)) - ->where(array("owner_id" => $user->id)) - ->update(); - $db->from("items") - ->set(array("owner_id" => $admin->id)) - ->where(array("owner_id" => $user->id)) - ->update(); - $db->from("logs") - ->set(array("user_id" => $admin->id)) - ->where(array("user_id" => $user->id)) - ->update(); + db::build() + ->update("tasks") + ->set("owner_id", $admin->id) + ->where("owner_id", "=", $user->id) + ->execute(); + db::build() + ->update("items") + ->set("owner_id", $admin->id) + ->where("owner_id", "=", $user->id) + ->execute(); + db::build() + ->update("logs") + ->set("user_id", $admin->id) + ->where("user_id", "=", $user->id) + ->execute(); } static function identity_provider_changed($old_provider, $new_provider) { $admin = identity::admin_user(); - $db = Database::instance(); - $db->from("tasks") - ->set(array("owner_id" => $admin->id)) - ->where("1 = 1") - ->update(); - $db->from("items") - ->set(array("owner_id" => $admin->id)) - ->where("1 = 1") - ->update(); - $db->from("logs") - ->set(array("user_id" => $admin->id)) - ->where("1 = 1") - ->update(); + db::build() + ->update("tasks") + ->set("owner_id", $admin->id) + ->execute(); + db::build() + ->update("items") + ->set("owner_id", $admin->id) + ->execute(); + db::build() + ->update("logs") + ->set("user_id", $admin->id) + ->execute(); } static function group_created($group) { @@ -108,6 +109,7 @@ class gallery_event_Core { ->label(t("Login"))); } else { $csrf = access::csrf_token(); + $item = $theme->item(); $menu->append(Menu::factory("dialog") ->id("user_menu_edit_profile") ->css_id("g-user-profile-link") @@ -118,7 +120,7 @@ class gallery_event_Core { ->id("user_menu_logout") ->css_id("g-logout-link") ->url(url::site("logout?csrf=$csrf&continue=" . - urlencode(url::current(true)))) + urlencode($item->url()))) ->label(t("Logout"))); } } @@ -270,8 +272,6 @@ class gallery_event_Core { ->css_class("ui-icon-carat-1-n")); if (access::can("edit", $item)) { - $page_type = $theme->page_type(); - $page_subtype = $theme->page_subtype(); switch ($item->type) { case "movie": $edit_title = t("Edit this movie"); @@ -293,11 +293,12 @@ class gallery_event_Core { $csrf = access::csrf_token(); + $theme_item = $theme->item(); $options_menu->append(Menu::factory("dialog") ->id("edit") ->label($edit_title) ->css_class("ui-icon-pencil") - ->url(url::site("quick/form_edit/$item->id?page_type=$page_type"))); + ->url(url::site("quick/form_edit/$item->id?from_id=$theme_item->id"))); if ($item->is_photo() && graphics::can("rotate")) { $options_menu @@ -308,7 +309,7 @@ class gallery_event_Core { ->css_class("ui-icon-rotate-ccw") ->ajax_handler("function(data) { " . "\$.gallery_replace_image(data, \$('$thumb_css_selector')) }") - ->url(url::site("quick/rotate/$item->id/ccw?csrf=$csrf&page_type=$page_type"))) + ->url(url::site("quick/rotate/$item->id/ccw?csrf=$csrf&from_id=$theme_item->id"))) ->append( Menu::factory("ajax_link") ->id("rotate_cw") @@ -316,12 +317,12 @@ class gallery_event_Core { ->css_class("ui-icon-rotate-cw") ->ajax_handler("function(data) { " . "\$.gallery_replace_image(data, \$('$thumb_css_selector')) }") - ->url(url::site("quick/rotate/$item->id/cw?csrf=$csrf&page_type=$page_type"))); + ->url(url::site("quick/rotate/$item->id/cw?csrf=$csrf&from_id=$theme_item->id"))); } // @todo Don't move photos from the photo page; we don't yet have a good way of redirecting // after move - if ($page_subtype == "album") { + if ($theme->page_subtype() == "album") { $options_menu ->append(Menu::factory("dialog") ->id("move") @@ -356,7 +357,7 @@ class gallery_event_Core { ->label($delete_title) ->css_class("ui-icon-trash") ->css_id("g-quick-delete") - ->url(url::site("quick/form_delete/$item->id?csrf=$csrf&page_type=$page_type"))); + ->url(url::site("quick/form_delete/$item->id?csrf=$csrf&from_id=$theme_item->id"))); } if ($item->is_album()) { diff --git a/modules/gallery/helpers/gallery_graphics.php b/modules/gallery/helpers/gallery_graphics.php index c24d2bde..ce08bbd7 100644 --- a/modules/gallery/helpers/gallery_graphics.php +++ b/modules/gallery/helpers/gallery_graphics.php @@ -123,7 +123,7 @@ class gallery_graphics_Core { module::event("graphics_composite_completed", $input_file, $output_file, $options); } catch (ErrorException $e) { - Kohana::log("error", $e->get_message()); + Kohana_Log::add("error", $e->get_message()); } } } diff --git a/modules/gallery/helpers/gallery_rest.php b/modules/gallery/helpers/gallery_rest.php new file mode 100644 index 00000000..a87ebb4e --- /dev/null +++ b/modules/gallery/helpers/gallery_rest.php @@ -0,0 +1,248 @@ +<?php defined("SYSPATH") or die("No direct script access."); +/** + * Gallery - a web based photo album viewer and editor + * Copyright (C) 2000-2009 Bharat Mediratta + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. + */ +class gallery_rest_Core { + static function get($request) { + $path = implode("/", $request->arguments); + + $item = gallery_rest::_get_item($path); + + $parent = $item->parent(); + $response_data = array("type" => $item->type, + "name" => $item->name, + "path" => $item->relative_url(), + "parent_path" => empty($parent) ? null : $parent->relative_url(), + "title" => $item->title, + "thumb_url" => $item->thumb_url(true), + "thumb_size" => array("height" => $item->thumb_height, + "width" => $item->thumb_width), + "resize_url" => $item->resize_url(true), + "resize_size" => array("height" => (int)$item->resize_height, + "width" => (int)$item->resize_width), + "url" => $item->file_url(true), + "size" => array("height" => $item->height, + "width" => $item->width), + "description" => $item->description, + "slug" => $item->slug); + + $children = self::_get_children($item, $request); + if (!empty($children) || $item->is_album()) { + $response_data["children"] = $children; + } + return rest::success(array("resource" => $response_data)); + } + + static function put($request) { + if (empty($request->arguments)) { + throw new Rest_Exception(400, "Bad request"); + } + $path = implode("/", $request->arguments); + $item = gallery_rest::_get_item($path, "edit"); + + // Validate the request data + $new_values = gallery_rest::_validate($request, $item->parent_id, $item->id); + $errors = $new_values->errors(); + if (empty($errors)) { + $item->title = $new_values->title; + $item->description = $new_values->description; + if ($item->id != 1) { + $item->rename($new_values->name); + } + $item->slug = $new_values->slug; + $item->save(); + + log::success("content", "Updated $item->type", + "<a href=\"{$item->type}s/$item->id\">view</a>"); + + return rest::success(); + } else { + return rest::validation_error($errors); + } + } + + static function post($request) { + if (empty($request->arguments)) { + throw new Rest_Exception(400, "Bad request"); + } + + $components = $request->arguments; + $name = urldecode(array_pop($components)); + + $parent = gallery_rest::_get_item(implode("/", $components), "edit"); + + // Validate the request data + $request->name = $name; + $new_values = gallery_rest::_validate($request, $parent->id); + $errors = $new_values->errors(); + if (!empty($errors)) { + return rest::validation_error($errors); + } + + if (empty($new_values["image"])) { + $new_item = album::create( + $parent, + $name, + empty($new_values["title"]) ? $name : $new_values["title"], + empty($new_values["description"]) ? null : $new_values["description"], + identity::active_user()->id, + empty($new_values["slug"]) ? $name : $new_values["slug"]); + $log_message = t("Added an album"); + } else { + $temp_filename = upload::save("image"); + $path_info = @pathinfo($temp_filename); + if (array_key_exists("extension", $path_info) && + in_array(strtolower($path_info["extension"]), array("flv", "mp4"))) { + $new_item = + movie::create($parent, $temp_filename, $new_values["name"], $new_values["title"]); + $log_message = t("Added a movie"); + } else { + $new_item = + photo::create($parent, $temp_filename, $new_values["name"], $new_values["title"]); + $log_message = t("Added a photo"); + } + } + + log::success("content", $log_message, "<a href=\"{$new_item->type}s/$new_item->id\">view</a>"); + + return rest::success(array("path" => $new_item->relative_url())); + } + + static function delete($request) { + if (empty($request->arguments)) { + throw new Rest_Exception(400, "Bad request"); + } + $path = implode("/", $request->arguments); + + $item = gallery_rest::_get_item($path, "edit"); + + if ($item->id == 1) { + throw new Rest_Exception(400, "Bad request"); + } + + $parent = $item->parent(); + $item->delete(); + + if ($item->is_album()) { + $msg = t("Deleted album <b>%title</b>", array("title" => html::purify($item->title))); + } else { + $msg = t("Deleted photo <b>%title</b>", array("title" => html::purify($item->title))); + } + log::success("content", $msg); + + return rest::success(array("resource" => array("parent_path" => $parent->relative_url()))); + } + + private static function _get_item($path, $permission="view") { + $item = url::get_item_from_uri($path); + + if (!$item->loaded()) { + throw new Kohana_404_Exception(); + } + + if (!access::can($permission, $item)) { + throw new Kohana_404_Exception(); + } + + return $item; + } + + private static function _get_children($item, $request) { + $children = array(); + $limit = empty($request->limit) ? null : $request->limit; + $offset = empty($request->offset) ? null : $request->offset; + $where = empty($request->filter) ? array() : array("type" => $request->filter); + foreach ($item->viewable()->children($limit, $offset, $where) as $child) { + $children[] = array("type" => $child->type, + "has_children" => $child->children_count() > 0, + "path" => $child->relative_url(), + "thumb_url" => $child->thumb_url(true), + "thumb_dimensions" => array("width" => $child->thumb_width, + "height" => $child->thumb_height), + "has_thumb" => $child->has_thumb(), + "title" => $child->title); + } + + return $children; + } + + private static function _validate($request, $parent_id, $item_id=0) { + $item = ORM::factory("item", $item_id); + + // Normalize the inputs so all fields have a value + $new_values = Validation::factory(array()); + foreach ($item->form_rules as $field => $rule_set) { + if (isset($request->$field)) { + $new_values[$field] = $request->$field; + } else if (isset($item->$field)) { + $new_values[$field] = $item->$field; + } + foreach (explode("|", $rule_set) as $rule) { + $new_values->add_rules($field, $rule); + } + } + $name = $new_values["name"]; + $new_values["title"] = empty($new_values["title"]) ? $name : $new_values["title"]; + $new_values["description"] = + empty($new_values["description"]) ? null : $new_values["description"]; + $new_values["slug"] = empty($new_values["slug"]) ? $name : $new_values["slug"]; + + if (!empty($request->image)) { + $new_values["image"] = $request->image; + $new_values->add_rules( + "image", "upload::valid", "upload::required", "upload::type[gif,jpg,jpeg,png,flv,mp4]"); + } + + if ($new_values->validate() && $item_id != 1) { + $errors = gallery_rest::_check_for_conflicts($parent_id, $item_id, + $new_values["name"], $new_values["slug"]); + if (!empty($errors)) { + !empty($errors["name_conflict"]) OR $new_values->add_error("name", "Duplicate name"); + !empty($errors["slug_conflict"]) OR + $new_values->add_error("slug", "Duplicate Internet address"); + } + } + + return $new_values; + } + + private static function _check_for_conflicts($parent_id, $item_id, $new_name, $new_slug) { + $errors = array(); + + if ($row = db::build() + ->select(array("name", "slug")) + ->from("items") + ->where("parent_id", "=", $parent_id) + ->where("id", "<>", $item_id) + ->and_open() + ->where("name", "=", $new_name) + ->or_where("slug", "=", $new_slug) + ->close() + ->execute() + ->current()) { + if ($row->name == $new_name) { + $errors["name_conflict"] = 1; + } + if ($row->slug == $new_slug) { + $errors["slug_conflict"] = 1; + } + } + + return $errors; + } +} diff --git a/modules/gallery/helpers/gallery_rss.php b/modules/gallery/helpers/gallery_rss.php index 155edfb5..d422636f 100644 --- a/modules/gallery/helpers/gallery_rss.php +++ b/modules/gallery/helpers/gallery_rss.php @@ -29,14 +29,14 @@ class gallery_rss_Core { case "latest": $feed->children = ORM::factory("item") ->viewable() - ->where("type !=", "album") - ->orderby("created", "DESC") + ->where("type", "<>", "album") + ->order_by("created", "DESC") ->find_all($limit, $offset); $all_children = ORM::factory("item") ->viewable() - ->where("type !=", "album") - ->orderby("created", "DESC"); + ->where("type", "<>", "album") + ->order_by("created", "DESC"); $feed->max_pages = ceil($all_children->find_all()->count() / $limit); $feed->title = t("Recent updates"); @@ -49,9 +49,9 @@ class gallery_rss_Core { $feed->children = $item ->viewable() - ->descendants($limit, $offset, array("type" => "photo")); + ->descendants($limit, $offset, array(array("type", "=", "photo"))); $feed->max_pages = ceil( - $item->viewable()->descendants_count(array("type" => "photo")) / $limit); + $item->viewable()->descendants_count(array(array("type", "=", "photo"))) / $limit); $feed->title = html::purify($item->title); $feed->description = nl2br(html::purify($item->description)); diff --git a/modules/gallery/helpers/gallery_task.php b/modules/gallery/helpers/gallery_task.php index e0b03682..3a705027 100644 --- a/modules/gallery/helpers/gallery_task.php +++ b/modules/gallery/helpers/gallery_task.php @@ -19,7 +19,7 @@ */ class gallery_task_Core { static function available_tasks() { - $dirty_count = graphics::find_dirty_images_query()->count(); + $dirty_count = graphics::find_dirty_images_query()->count_records(); $tasks = array(); $tasks[] = Task_Definition::factory() ->callback("gallery_task::rebuild_dirty_images") @@ -47,7 +47,7 @@ class gallery_task_Core { static function rebuild_dirty_images($task) { $errors = array(); try { - $result = graphics::find_dirty_images_query(); + $result = graphics::find_dirty_images_query()->select("id")->execute(); $total_count = $task->get("total_count", $result->count()); $mode = $task->get("mode", "init"); if ($mode == "init") { @@ -66,7 +66,7 @@ class gallery_task_Core { } $item = ORM::factory("item", $row->id); - if ($item->loaded) { + if ($item->loaded()) { try { graphics::generate($item); $completed++; diff --git a/modules/gallery/helpers/graphics.php b/modules/gallery/helpers/graphics.php index d6a2f00c..7577d7ac 100644 --- a/modules/gallery/helpers/graphics.php +++ b/modules/gallery/helpers/graphics.php @@ -61,9 +61,9 @@ class graphics_Core { */ static function remove_rule($module_name, $target, $operation) { ORM::factory("graphics_rule") - ->where("module_name", $module_name) - ->where("target", $target) - ->where("operation", $operation) + ->where("module_name", "=", $module_name) + ->where("target", "=", $target) + ->where("operation", "=", $operation) ->delete_all(); self::mark_dirty($target == "thumb", $target == "resize"); @@ -74,7 +74,10 @@ class graphics_Core { * @param string $module_name */ static function remove_rules($module_name) { - $status = Database::instance()->delete("graphics_rules", array("module_name" => $module_name)); + $status = db::build() + ->delete("graphics_rules") + ->where("module_name", "=", $module_name) + ->execute(); if (count($status)) { self::mark_dirty(true, true); } @@ -86,8 +89,11 @@ class graphics_Core { * module it won't cause all of your images to suddenly require a rebuild. */ static function activate_rules($module_name) { - Database::instance() - ->update("graphics_rules",array("active" => true), array("module_name" => $module_name)); + db::build() + ->update("graphics_rules") + ->set("active", true) + ->where("module_name", "=", $module_name) + ->execute(); } /** @@ -96,8 +102,11 @@ class graphics_Core { * module it won't cause all of your images to suddenly require a rebuild. */ static function deactivate_rules($module_name) { - Database::instance() - ->update("graphics_rules",array("active" => false), array("module_name" => $module_name)); + db::build() + ->update("graphics_rules") + ->set("active", false) + ->where("module_name", "=", $module_name) + ->execute(); } /** @@ -171,7 +180,7 @@ class graphics_Core { } catch (Exception $e) { // Something went wrong rebuilding the image. Leave it dirty and move on. // @todo we should handle this better. - Kohana::log("error", "Caught exception rebuilding image: {$item->title}\n" . + Kohana_Log::add("error", "Caught exception rebuilding image: {$item->title}\n" . $e->getMessage() . "\n" . $e->getTraceAsString()); throw $e; } @@ -181,9 +190,9 @@ class graphics_Core { if (empty(self::$_rules_cache[$target])) { $rules = array(); foreach (ORM::factory("graphics_rule") - ->where("target", $target) - ->where("active", true) - ->orderby("priority", "asc") + ->where("target", "=", $target) + ->where("active", "=", true) + ->order_by("priority", "asc") ->find_all() as $rule) { $rules[] = (object)$rule->as_array(); } @@ -197,11 +206,22 @@ class graphics_Core { * @return Database_Result Query result */ static function find_dirty_images_query() { - return Database::instance()->query( - "SELECT `id` FROM {items} " . - "WHERE ((`thumb_dirty` = 1 AND (`type` <> 'album' OR `album_cover_item_id` IS NOT NULL))" . - " OR (`resize_dirty` = 1 AND `type` = 'photo')) " . - " AND `id` != 1"); + return db::build() + ->from("items") + ->and_open() + ->and_open() + ->where("thumb_dirty", "=", 1) + ->and_open() + ->where("type", "<>", "album") + ->or_where("album_cover_item_id", "IS NOT", null) + ->close() + ->or_open() + ->where("resize_dirty", "=", 1) + ->where("type", "=", "photo") + ->close() + ->close() + ->where("id", "<>", 1) + ->close(); } /** @@ -209,18 +229,18 @@ class graphics_Core { */ static function mark_dirty($thumbs, $resizes) { if ($thumbs || $resizes) { - $db = Database::instance(); - $fields = array(); + $db = db::build() + ->update("items"); if ($thumbs) { - $fields["thumb_dirty"] = 1; + $db->set("thumb_dirty", 1); } if ($resizes) { - $fields["resize_dirty"] = 1; + $db->set("resize_dirty", 1); } - $db->update("items", $fields, true); + $db->execute(); } - $count = self::find_dirty_images_query()->count(); + $count = self::find_dirty_images_query()->count_records(); if ($count) { site_status::warning( t2("One of your photos is out of date. <a %attrs>Click here to fix it</a>", @@ -371,18 +391,18 @@ class graphics_Core { } switch(module::get_var("gallery", "graphics_toolkit")) { case "gd": - Kohana::config_set("image.driver", "GD"); + Kohana_Config::instance()->set("image.driver", "GD"); break; case "imagemagick": - Kohana::config_set("image.driver", "ImageMagick"); - Kohana::config_set( + Kohana_Config::instance()->set("image.driver", "ImageMagick"); + Kohana_Config::instance()->set( "image.params.directory", module::get_var("gallery", "graphics_toolkit_path")); break; case "graphicsmagick": - Kohana::config_set("image.driver", "GraphicsMagick"); - Kohana::config_set( + Kohana_Config::instance()->set("image.driver", "GraphicsMagick"); + Kohana_Config::instance()->set( "image.params.directory", module::get_var("gallery", "graphics_toolkit_path")); break; } diff --git a/modules/gallery/helpers/identity.php b/modules/gallery/helpers/identity.php index 83ba9e1e..eae0ea3e 100644 --- a/modules/gallery/helpers/identity.php +++ b/modules/gallery/helpers/identity.php @@ -75,15 +75,15 @@ class identity_Core { if (!$session->get("group_ids")) { $ids = array(); - foreach ($user->groups as $group) { + 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("error", "Load_user Exception: " . - $e->getMessage() . "\n" . $e->getTraceAsString()); + Kohana_Log::add("error", "Load_user Exception: " . + $e->getMessage() . "\n" . $e->getTraceAsString()); try { Session::instance()->destroy(); } catch (Exception $e) { diff --git a/modules/gallery/helpers/item.php b/modules/gallery/helpers/item.php index f8e6534e..f6181f8a 100644 --- a/modules/gallery/helpers/item.php +++ b/modules/gallery/helpers/item.php @@ -139,10 +139,10 @@ class item_Core { // Guard against an empty result when we create the first item. It's unfortunate that we // have to check this every time. // @todo: figure out a better way to bootstrap the weight. - $result = Database::instance() + $result = db::build() ->select("weight")->from("items") - ->orderby("weight", "desc")->limit(1) - ->get()->current(); + ->order_by("weight", "desc")->limit(1) + ->execute()->current(); return ($result ? $result->weight : 0) + 1; } @@ -155,29 +155,12 @@ class item_Core { $view_restrictions = array(); if (!identity::active_user()->admin) { foreach (identity::group_ids_for_active_user() as $id) { - // Separate the first restriction from the rest to make it easier for us to formulate - // our where clause below - if (empty($view_restrictions)) { - $view_restrictions[0] = "items.view_$id"; - } else { - $view_restrictions[1]["items.view_$id"] = access::ALLOW; - } + $view_restrictions[] = array("items.view_$id", "=", access::ALLOW); } } - switch (count($view_restrictions)) { - case 0: - break; - - case 1: - $model->where($view_restrictions[0], access::ALLOW); - break; - - default: - $model->open_paren(); - $model->where($view_restrictions[0], access::ALLOW); - $model->orwhere($view_restrictions[1]); - $model->close_paren(); - break; + + if (count($view_restrictions)) { + $model->and_open()->merge_or_where($view_restrictions)->close(); } return $model; diff --git a/modules/gallery/helpers/l10n_client.php b/modules/gallery/helpers/l10n_client.php index 3460cc65..fe70933d 100644 --- a/modules/gallery/helpers/l10n_client.php +++ b/modules/gallery/helpers/l10n_client.php @@ -80,11 +80,10 @@ class l10n_client_Core { } // @todo Batch requests (max request size) - foreach (Database::instance() + foreach (db::build() ->select("key", "locale", "revision", "translation") ->from("incoming_translations") - ->get() - ->as_array() as $row) { + ->execute() as $row) { if (!isset($request->messages->{$row->key})) { $request->messages->{$row->key} = 1; } @@ -134,12 +133,14 @@ class l10n_client_Core { // incoming_translations.message to be NULL? $locale = $message_data->locale; $entry = ORM::factory("incoming_translation") - ->where(array("key" => $key, "locale" => $locale)) + ->where("key", "=", $key) + ->where("locale", "=", $locale) ->find(); - if (!$entry->loaded) { + if (!$entry->loaded()) { // @todo Load a message key -> message (text) dict into memory outside of this loop $root_entry = ORM::factory("incoming_translation") - ->where(array("key" => $key, "locale" => "root")) + ->where("key", "=", $key) + ->where("locale", "=", "root") ->find(); $entry->key = $key; $entry->message = $root_entry->message; @@ -166,10 +167,10 @@ class l10n_client_Core { // @todo Batch requests (max request size) // @todo include base_revision in submission / how to handle resubmissions / edit fights? - foreach (Database::instance() + foreach (db::build() ->select("key", "message", "locale", "base_revision", "translation") ->from("outgoing_translations") - ->get() as $row) { + ->execute() as $row) { $key = $row->key; if (!isset($request->{$key})) { $request->{$key}->message = json_encode(unserialize($row->message)); diff --git a/modules/gallery/helpers/l10n_scanner.php b/modules/gallery/helpers/l10n_scanner.php index a8059b3a..bb7cb449 100644 --- a/modules/gallery/helpers/l10n_scanner.php +++ b/modules/gallery/helpers/l10n_scanner.php @@ -28,22 +28,22 @@ class l10n_scanner_Core { static function process_message($message, &$cache) { if (empty($cache)) { - foreach (Database::instance() + foreach (db::build() ->select("key") ->from("incoming_translations") - ->where("locale", "root") - ->get() as $row) { + ->where("locale", "=", "root") + ->execute() as $row) { $cache[$row->key] = true; } } - $key = I18n::get_message_key($message); + $key = Gallery_I18n::get_message_key($message); if (array_key_exists($key, $cache)) { return $cache[$key]; } - $entry = ORM::factory("incoming_translation", array("key" => $key)); - if (!$entry->loaded) { + $entry = ORM::factory("incoming_translation")->where("key", "=", $key)->find(); + if (!$entry->loaded()) { $entry->key = $key; $entry->message = serialize($message); $entry->locale = "root"; diff --git a/modules/gallery/helpers/locales.php b/modules/gallery/helpers/locales.php index 2de029ff..8d76e333 100644 --- a/modules/gallery/helpers/locales.php +++ b/modules/gallery/helpers/locales.php @@ -125,13 +125,13 @@ class locales_Core { if (empty(self::$locales)) { self::_init_language_data(); } - $locale or $locale = I18n::instance()->locale(); + $locale or $locale = Gallery_I18n::instance()->locale(); return self::$locales["$locale"]; } static function is_rtl($locale=null) { - $locale or $locale = I18n::instance()->locale(); + $locale or $locale = Gallery_I18n::instance()->locale(); list ($language, $territory) = explode('_', $locale . "_"); return in_array($language, array("he", "fa", "ar")); } @@ -233,7 +233,7 @@ class locales_Core { } // If we have any preference, override the site's default locale if ($locale) { - I18n::instance()->locale($locale); + Gallery_I18n::instance()->locale($locale); } } diff --git a/modules/gallery/helpers/model_cache.php b/modules/gallery/helpers/model_cache.php index a3e09862..302e42d9 100644 --- a/modules/gallery/helpers/model_cache.php +++ b/modules/gallery/helpers/model_cache.php @@ -22,8 +22,8 @@ class model_cache_Core { static function get($model_name, $id, $field_name="id") { if (TEST_MODE || empty(self::$cache->$model_name->$field_name->$id)) { - $model = ORM::factory($model_name)->where($field_name, $id)->find(); - if (!$model->loaded) { + $model = ORM::factory($model_name)->where($field_name, "=", $id)->find(); + if (!$model->loaded()) { throw new Exception("@todo MISSING_MODEL $model_name:$id"); } self::$cache->$model_name->$field_name->$id = $model; diff --git a/modules/gallery/helpers/module.php b/modules/gallery/helpers/module.php index 50abdaae..6c7078a3 100644 --- a/modules/gallery/helpers/module.php +++ b/modules/gallery/helpers/module.php @@ -36,13 +36,13 @@ class module_Core { */ static function set_version($module_name, $version) { $module = self::get($module_name); - if (!$module->loaded) { + if (!$module->loaded()) { $module->name = $module_name; $module->active = $module_name == "gallery"; // only gallery is active by default } $module->version = $version; $module->save(); - Kohana::log("debug", "$module_name: version is now $version"); + Kohana_Log::add("debug", "$module_name: version is now $version"); } /** @@ -51,7 +51,7 @@ class module_Core { */ static function get($module_name) { if (empty(self::$modules[$module_name])) { - return ORM::factory("module", array("name" => $module_name)); + return ORM::factory("module")->where("name", "=", $module_name)->find(); } return self::$modules[$module_name]; } @@ -126,9 +126,10 @@ class module_Core { * @param string $module_name */ static function install($module_name) { - $kohana_modules = Kohana::config("core.modules"); + $config = Kohana_Config::instance(); + $kohana_modules = $config->get("core.modules"); array_unshift($kohana_modules, MODPATH . $module_name); - Kohana::config_set("core.modules", $kohana_modules); + $config->set("core.modules", $kohana_modules); // Rebuild the include path so the module installer can benefit from auto loading Kohana::include_paths(true); @@ -142,7 +143,7 @@ class module_Core { // Now the module is installed but inactive, so don't leave it in the active path array_shift($kohana_modules); - Kohana::config_set("core.modules", $kohana_modules); + $config->set("core.modules", $kohana_modules); log::success( "module", t("Installed module %module_name", array("module_name" => $module_name))); @@ -193,9 +194,10 @@ class module_Core { * @param string $module_name */ static function activate($module_name) { - $kohana_modules = Kohana::config("core.modules"); + $config = Kohana_Config::instance(); + $kohana_modules = $config->get("core.modules"); array_unshift($kohana_modules, MODPATH . $module_name); - Kohana::config_set("core.modules", $kohana_modules); + $config->set("core.modules", $kohana_modules); $installer_class = "{$module_name}_installer"; if (method_exists($installer_class, "activate")) { @@ -203,7 +205,7 @@ class module_Core { } $module = self::get($module_name); - if ($module->loaded) { + if ($module->loaded()) { $module->active = true; $module->save(); } @@ -230,7 +232,7 @@ class module_Core { } $module = self::get($module_name); - if ($module->loaded) { + if ($module->loaded()) { $module->active = false; $module->save(); } @@ -257,7 +259,7 @@ class module_Core { graphics::remove_rules($module_name); $module = self::get($module_name); - if ($module->loaded) { + if ($module->loaded()) { $module->delete(); } module::load_modules(); @@ -290,8 +292,9 @@ class module_Core { } } self::$active[] = $gallery; // put gallery last in the module list to match core.modules - Kohana::config_set( - "core.modules", array_merge($kohana_modules, Kohana::config("core.modules"))); + $config = Kohana_Config::instance(); + $config->set( + "core.modules", array_merge($kohana_modules, $config->get("core.modules"))); } /** @@ -363,21 +366,23 @@ class module_Core { // We cache all vars in gallery._cache so that we can load all vars at once for // performance. if (empty(self::$var_cache)) { - $row = Database::instance() + $row = db::build() ->select("value") ->from("vars") - ->where(array("module_name" => "gallery", "name" => "_cache")) - ->get() + ->where("module_name", "=", "gallery") + ->where("name", "=", "_cache") + ->execute() ->current(); if ($row) { self::$var_cache = unserialize($row->value); } else { // gallery._cache doesn't exist. Create it now. - foreach (Database::instance() + foreach (db::build() ->select("module_name", "name", "value") ->from("vars") - ->orderby("module_name", "name") - ->get() as $row) { + ->order_by("module_name") + ->order_by("name") + ->execute() as $row) { if ($row->module_name == "gallery" && $row->name == "_cache") { // This could happen if there's a race condition continue; @@ -407,33 +412,50 @@ class module_Core { */ static function set_var($module_name, $name, $value) { $var = ORM::factory("var") - ->where("module_name", $module_name) - ->where("name", $name) + ->where("module_name", "=", $module_name) + ->where("name", "=", $name) ->find(); - if (!$var->loaded) { + if (!$var->loaded()) { $var->module_name = $module_name; $var->name = $name; } $var->value = $value; $var->save(); - Database::instance()->delete("vars", array("module_name" => "gallery", "name" => "_cache")); + db::build() + ->delete("vars") + ->where("module_name", "=", "gallery") + ->where("name", "=", "_cache") + ->execute(); self::$var_cache = null; } /** * Increment the value of a variable for this module + * + * Note: Frequently updating counters is very inefficient because it invalidates the cache value + * which has to be rebuilt every time we make a change. + * + * @todo Get rid of this and find an alternate approach for all callers (currently only Akismet) + * + * @deprecated * @param string $module_name * @param string $name * @param string $increment (optional, default is 1) */ static function incr_var($module_name, $name, $increment=1) { - Database::instance()->query( - "UPDATE {vars} SET `value` = `value` + $increment " . - "WHERE `module_name` = '$module_name' " . - "AND `name` = '$name'"); - - Database::instance()->delete("vars", array("module_name" => "gallery", "name" => "_cache")); + db::build() + ->update("vars") + ->set("value", new Database_Expression("`value` + $increment")) + ->where("module_name", "=", $module_name) + ->where("name", "=", $name) + ->execute(); + + db::build() + ->delete("vars") + ->where("module_name", "=", "gallery") + ->where("name", "=", "_cache") + ->execute(); self::$var_cache = null; } @@ -444,14 +466,18 @@ class module_Core { */ static function clear_var($module_name, $name) { $var = ORM::factory("var") - ->where("module_name", $module_name) - ->where("name", $name) + ->where("module_name", "=", $module_name) + ->where("name", "=", $name) ->find(); - if ($var->loaded) { + if ($var->loaded()) { $var->delete(); } - Database::instance()->delete("vars", array("module_name" => "gallery", "name" => "_cache")); + db::build() + ->delete("vars") + ->where("module_name", "=", "gallery") + ->where("name", "=", "_cache") + ->execute(); self::$var_cache = null; } diff --git a/modules/gallery/helpers/movie.php b/modules/gallery/helpers/movie.php index 20ac8592..01859924 100644 --- a/modules/gallery/helpers/movie.php +++ b/modules/gallery/helpers/movie.php @@ -36,7 +36,7 @@ class movie_Core { */ static function create($parent, $filename, $name, $title, $description=null, $owner_id=null, $slug=null) { - if (!$parent->loaded || !$parent->is_album()) { + if (!$parent->loaded() || !$parent->is_album()) { throw new Exception("@todo INVALID_PARENT"); } @@ -90,11 +90,11 @@ class movie_Core { // Randomize the name if there's a conflict // @todo Improve this. Random numbers are not user friendly while (ORM::factory("item") - ->where("parent_id", $parent->id) - ->open_paren() - ->where("name", $movie->name) - ->orwhere("slug", $movie->slug) - ->close_paren() + ->where("parent_id", "=", $parent->id) + ->and_open() + ->where("name", "=", $movie->name) + ->or_where("slug", "=", $movie->slug) + ->close() ->find()->id) { $rand = rand(); $movie->name = "{$name}.$rand.{$pi['extension']}"; @@ -130,6 +130,7 @@ class movie_Core { static function get_edit_form($movie) { $form = new Forge("movies/update/$movie->id", "", "post", array("id" => "g-edit-movie-form")); + $form->hidden("from_id"); $group = $form->group("edit_item")->label(t("Edit Movie")); $group->input("title")->label(t("Title"))->value($movie->title); $group->textarea("description")->label(t("Description"))->value($movie->description); diff --git a/modules/gallery/helpers/photo.php b/modules/gallery/helpers/photo.php index dab98436..4e20e610 100644 --- a/modules/gallery/helpers/photo.php +++ b/modules/gallery/helpers/photo.php @@ -36,7 +36,7 @@ class photo_Core { */ static function create($parent, $filename, $name, $title, $description=null, $owner_id=null, $slug=null) { - if (!$parent->loaded || !$parent->is_album()) { + if (!$parent->loaded() || !$parent->is_album()) { throw new Exception("@todo INVALID_PARENT"); } @@ -89,11 +89,11 @@ class photo_Core { // Randomize the name or slug if there's a conflict // @todo Improve this. Random numbers are not user friendly while (ORM::factory("item") - ->where("parent_id", $parent->id) - ->open_paren() - ->where("name", $photo->name) - ->orwhere("slug", $photo->slug) - ->close_paren() + ->where("parent_id", "=", $parent->id) + ->and_open() + ->where("name", "=", $photo->name) + ->or_where("slug", "=", $photo->slug) + ->close() ->find()->id) { $rand = rand(); $photo->name = "{$name}.$rand.{$pi['extension']}"; @@ -139,6 +139,7 @@ class photo_Core { static function get_edit_form($photo) { $form = new Forge("photos/update/$photo->id", "", "post", array("id" => "g-edit-photo-form")); + $form->hidden("from_id"); $group = $form->group("edit_item")->label(t("Edit Photo")); $group->input("title")->label(t("Title"))->value($photo->title); $group->textarea("description")->label(t("Description"))->value($photo->description); diff --git a/modules/gallery/helpers/site_status.php b/modules/gallery/helpers/site_status.php index 2b090776..04316fff 100644 --- a/modules/gallery/helpers/site_status.php +++ b/modules/gallery/helpers/site_status.php @@ -67,9 +67,9 @@ class site_status_Core { */ private static function _add($msg, $severity, $permanent_key) { $message = ORM::factory("message") - ->where("key", $permanent_key) + ->where("key", "=", $permanent_key) ->find(); - if (!$message->loaded) { + if (!$message->loaded()) { $message->key = $permanent_key; } $message->severity = $severity; @@ -82,8 +82,8 @@ class site_status_Core { * @param string $permanent_key */ static function clear($permanent_key) { - $message = ORM::factory("message")->where("key", $permanent_key)->find(); - if ($message->loaded) { + $message = ORM::factory("message")->where("key", "=", $permanent_key)->find(); + if ($message->loaded()) { $message->delete(); } } diff --git a/modules/gallery/helpers/task.php b/modules/gallery/helpers/task.php index dac5f9d3..4aa95f33 100644 --- a/modules/gallery/helpers/task.php +++ b/modules/gallery/helpers/task.php @@ -51,7 +51,7 @@ class task_Core { static function cancel($task_id) { $task = ORM::factory("task", $task_id); - if (!$task->loaded) { + if (!$task->loaded()) { throw new Exception("@todo MISSING_TASK"); } $task->done = 1; @@ -65,14 +65,14 @@ class task_Core { static function remove($task_id) { $task = ORM::factory("task", $task_id); - if ($task->loaded) { + if ($task->loaded()) { $task->delete(); } } static function run($task_id) { $task = ORM::factory("task", $task_id); - if (!$task->loaded) { + if (!$task->loaded()) { throw new Exception("@todo MISSING_TASK"); } @@ -84,7 +84,7 @@ class task_Core { } $task->save(); } catch (Exception $e) { - Kohana::log("error", $e->__toString()); + Kohana_Log::add("error", $e->__toString()); $task->log($e->__toString()); $task->state = "error"; $task->done = true; diff --git a/modules/gallery/helpers/theme.php b/modules/gallery/helpers/theme.php index 247aa5c4..b836292f 100644 --- a/modules/gallery/helpers/theme.php +++ b/modules/gallery/helpers/theme.php @@ -39,7 +39,8 @@ class theme_Core { $path = "/" . $input->get("kohana_uri"); } - $modules = Kohana::config("core.modules"); + $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) { @@ -58,13 +59,13 @@ class theme_Core { if (file_exists(THEMEPATH . $override)) { self::$site_theme_name = $override; } else { - Kohana::log("error", "Missing override theme: '$override'"); + Kohana_Log::add("error", "Missing override theme: '$override'"); } } array_unshift($modules, THEMEPATH . self::$site_theme_name); } - Kohana::config_set("core.modules", $modules); + $config->set("core.modules", $modules); } static function get_edit_form_admin() { diff --git a/modules/gallery/hooks/init_gallery.php b/modules/gallery/hooks/init_gallery.php index b2d9c4de..c7355260 100644 --- a/modules/gallery/hooks/init_gallery.php +++ b/modules/gallery/hooks/init_gallery.php @@ -24,7 +24,7 @@ if (!file_exists(VARPATH . "database.php")) { url::redirect(url::abs_file("installer")); } -Event::add("system.ready", array("I18n", "instance")); +Event::add("system.ready", array("Gallery_I18n", "instance")); Event::add("system.ready", array("module", "load_modules")); Event::add("system.ready", array("gallery", "ready")); Event::add("system.post_routing", array("url", "parse_url")); @@ -42,5 +42,5 @@ if ($g3sid = $input->post("g3sid", $input->get("g3sid"))) { } if ($user_agent = $input->post("user_agent", $input->get("user_agent"))) { - Kohana::$user_agent = $user_agent; + $_SERVER["HTTP_USER_AGENT"] = $user_agent; } diff --git a/modules/gallery/libraries/I18n.php b/modules/gallery/libraries/Gallery_I18n.php index c3336052..4e0c1f82 100644 --- a/modules/gallery/libraries/I18n.php +++ b/modules/gallery/libraries/Gallery_I18n.php @@ -27,7 +27,7 @@ * @return String The translated message string. */ function t($message, $options=array()) { - return I18n::instance()->translate($message, $options); + return Gallery_I18n::instance()->translate($message, $options); } /** @@ -43,11 +43,11 @@ function t($message, $options=array()) { * @return String The translated message string. */ function t2($singular, $plural, $count, $options=array()) { - return I18n::instance()->translate(array("one" => $singular, "other" => $plural), + return Gallery_I18n::instance()->translate(array("one" => $singular, "other" => $plural), array_merge($options, array("count" => $count))); } -class I18n_Core { +class Gallery_I18n_Core { private static $_instance; private $_config = array(); private $_call_log = array(); @@ -64,7 +64,7 @@ class I18n_Core { if (empty($config['default_locale'])) { $config['default_locale'] = module::get_var('gallery', 'default_locale'); } - self::$_instance = new I18n_Core($config); + self::$_instance = new Gallery_I18n_Core($config); } return self::$_instance; @@ -128,22 +128,20 @@ class I18n_Core { if (!isset($this->_cache[$locale])) { $this->_cache[$locale] = array(); // TODO: Load data from locale file instead of the DB. - foreach (Database::instance() + foreach (db::build() ->select("key", "translation") ->from("incoming_translations") - ->where(array("locale" => $locale)) - ->get() - ->as_array() as $row) { + ->where("locale", "=", $locale) + ->execute() as $row) { $this->_cache[$locale][$row->key] = unserialize($row->translation); } // Override incoming with outgoing... - foreach (Database::instance() + foreach (db::build() ->select("key", "translation") ->from("outgoing_translations") - ->where(array("locale" => $locale)) - ->get() - ->as_array() as $row) { + ->where("locale", "=", $locale) + ->execute() as $row) { $this->_cache[$locale][$row->key] = unserialize($row->translation); } } diff --git a/modules/gallery/libraries/Gallery_View.php b/modules/gallery/libraries/Gallery_View.php index 3bf56d0f..940c5321 100644 --- a/modules/gallery/libraries/Gallery_View.php +++ b/modules/gallery/libraries/Gallery_View.php @@ -32,7 +32,7 @@ class Gallery_View_Core extends View { if (($path = gallery::find_file("js", $file, false))) { $this->scripts[$path] = 1; } else { - Kohana::log("error", "Can't find script file: $file"); + Kohana_Log::add("error", "Can't find script file: $file"); } } @@ -55,7 +55,7 @@ class Gallery_View_Core extends View { if (($path = gallery::find_file("css", $file, false))) { $this->css[$path] = 1; } else { - Kohana::log("error", "Can't find css file: $file"); + Kohana_Log::add("error", "Can't find css file: $file"); } } @@ -130,7 +130,7 @@ class Gallery_View_Core extends View { $search[] = $match[0]; $replace[] = "url('" . url::abs_file($relative) . "')"; } else { - Kohana::log("error", "Missing URL reference '{$match[1]}' in CSS file '$css_file'"); + Kohana_Log::add("error", "Missing URL reference '{$match[1]}' in CSS file '$css_file'"); } } $replace = str_replace(DIRECTORY_SEPARATOR, "/", $replace); diff --git a/modules/gallery/libraries/IdentityProvider.php b/modules/gallery/libraries/IdentityProvider.php index e213ae97..bcb3056a 100644 --- a/modules/gallery/libraries/IdentityProvider.php +++ b/modules/gallery/libraries/IdentityProvider.php @@ -54,7 +54,7 @@ class IdentityProvider_Core { */ static function reset() { self::$instance = null; - Kohana::config_clear("identity"); + Kohana_Config::instance()->clear("identity"); } /** @@ -90,7 +90,7 @@ class IdentityProvider_Core { get_class($this), "IdentityProvider_Driver"); } - Kohana::log("debug", "Identity Library initialized"); + Kohana_Log::add("debug", "Identity Library initialized"); } /** diff --git a/modules/gallery/libraries/MY_Database.php b/modules/gallery/libraries/MY_Database.php index c56f16e8..61f23fb0 100644 --- a/modules/gallery/libraries/MY_Database.php +++ b/modules/gallery/libraries/MY_Database.php @@ -17,32 +17,21 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ -class Database extends Database_Core { +abstract class Database extends Database_Core { protected $_table_names; - public function open_paren() { - $this->where[] = "("; - return $this; - } - - public function close_paren() { - // Search backwards for the last opening paren and resolve it - $i = count($this->where) - 1; - $this->where[$i] .= ")"; - while (--$i >= 0) { - if ($this->where[$i] == "(") { - // Remove the paren from the where clauses, and add it to the right of the operator of the - // next where clause. If removing the paren makes the next where clause the first element - // in the where list, then the operator shouldn't be there. It's there because we - // calculate whether or not we need an operator based on the number of where clauses, and - // the open paren seems like a where clause even though it isn't. - array_splice($this->where, $i, 1); - $this->where[$i] = preg_replace("/^(AND|OR) /", $i ? "\\1 (" : "(", $this->where[$i]); - return $this; - } + /** + * Kohana 2.4 introduces a new connection parameter. If it's not specified, make sure that we + * define it here to avoid an error later on. + * + * @todo: add an upgrade path to modify var/database.php so that we can avoid doing this at + * runtime. + */ + protected function __construct(array $config) { + if (!isset($config["connection"]["params"])) { + $config["connection"]["params"] = null; } - - throw new Kohana_Database_Exception('database.missing_open_paren'); + parent::__construct($config); } /** @@ -74,19 +63,19 @@ class Database extends Database_Core { if (!isset($this->_table_names)) { // This should only run once on the first query - $this->_table_names =array(); - $len = strlen($prefix); + $this->_table_names = array(); foreach($this->list_tables() as $table_name) { - if ($len > 0) { - $naked_name = strpos($table_name, $prefix) !== 0 ? - $table_name : substr($table_name, $len); - } else { - $naked_name = $table_name; - } - $this->_table_names["{{$naked_name}}"] = $table_name; + $this->_table_names["{{$table_name}}"] = $prefix . $table_name; } } - return empty($this->_table_names) ? $sql : strtr($sql, $this->_table_names); + return strtr($sql, $this->_table_names); + } + + /** + * This is used by the unit test code to switch the active database connection. + */ + static function set_default_instance($db) { + self::$instances["default"] = $db; } }
\ No newline at end of file diff --git a/modules/gallery/libraries/MY_Forge.php b/modules/gallery/libraries/MY_Forge.php index b40d067d..9564f941 100644 --- a/modules/gallery/libraries/MY_Forge.php +++ b/modules/gallery/libraries/MY_Forge.php @@ -24,14 +24,13 @@ class Forge extends Forge_Core { */ public function __construct($action=null, $title='', $method=null, $attr=array()) { parent::__construct($action, $title, $method, $attr); - $this->hidden("csrf")->value(""); + $this->hidden("csrf")->value(access::csrf_token()); } /** * Use our own template */ public function render($template="form.html", $custom=false) { - $this->hidden["csrf"]->value(access::csrf_token()); return parent::render($template, $custom); } @@ -43,8 +42,8 @@ class Forge extends Forge_Core { if (isset($input->inputs)) { $input->add_rules_from($model); } - if (isset($model->rules[$name])) { - $input->rules($model->rules[$name]); + if (isset($model->form_rules[$name])) { + $input->rules($model->form_rules[$name]); } } } diff --git a/modules/gallery/libraries/MY_Kohana_Exception.php b/modules/gallery/libraries/MY_Kohana_Exception.php new file mode 100644 index 00000000..dd5998a1 --- /dev/null +++ b/modules/gallery/libraries/MY_Kohana_Exception.php @@ -0,0 +1,31 @@ +<?php defined("SYSPATH") or die("No direct script access."); +/** + * Gallery - a web based photo album viewer and editor + * Copyright (C) 2000-2009 Bharat Mediratta + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. + */ +class Kohana_Exception extends Kohana_Exception_Core { + /** + * Dump out the full stack trace as part of the text representation of the exception. + */ + public static function text($e) { + return sprintf( + "%s [ %s ]: %s\n%s [ %s ]\n%s", + get_class($e), $e->getCode(), strip_tags($e->getMessage()), + $e->getFile(), $e->getLine(), + $e->getTraceAsString()); + } +}
\ No newline at end of file diff --git a/modules/gallery/libraries/MY_ORM.php b/modules/gallery/libraries/MY_ORM.php index 2c9ad1d7..56c776aa 100644 --- a/modules/gallery/libraries/MY_ORM.php +++ b/modules/gallery/libraries/MY_ORM.php @@ -21,16 +21,6 @@ class ORM extends ORM_Core { // Track the original value of this ORM so that we can look it up in ORM::original() protected $original = null; - public function open_paren() { - $this->db->open_paren(); - return $this; - } - - public function close_paren() { - $this->db->close_paren(); - return $this; - } - public function save() { model_cache::clear(); $result = parent::save(); diff --git a/modules/gallery/libraries/MY_View.php b/modules/gallery/libraries/MY_View.php index eb55aca6..cec59ec1 100644 --- a/modules/gallery/libraries/MY_View.php +++ b/modules/gallery/libraries/MY_View.php @@ -18,6 +18,35 @@ * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ class View extends View_Core { + static $global_data = array(); + + /** + * Reimplement Kohana 2.3's View::set_global() functionality. + */ + public function set_global($key, $value) { + View::$global_data[$key] = $value; + } + + public function is_set($key) { + return parent::is_set($key) ? true : array_key_exists($key, View::$global_data); + } + + /** + * Completely replace View_Core::__get() so that local data trumps global data, trumps members. + * This simulates the Kohana 2.3 behavior. + */ + public function &__get($key) { + if (isset($this->kohana_local_data[$key])) { + return $this->kohana_local_data[$key]; + } else if (isset(View::$global_data[$key])) { + return View::$global_data[$key]; + } else if (isset($this->$key)) { + return $this->$key; + } else { + throw new Kohana_Exception('Undefined view variable: :var', array(':var' => $key)); + } + } + /** * Override View_Core::__construct so that we can set the csrf value into all views. * @@ -34,11 +63,12 @@ class View extends View_Core { * * @see View_Core::render */ - public function render($print=false, $renderer=false) { + public function render($print=false, $renderer=false, $modifier=false) { try { - return parent::render($print, $renderer); + $this->kohana_local_data = array_merge(View::$global_data, $this->kohana_local_data); + return parent::render($print, $renderer, $modifier); } catch (Exception $e) { - Kohana::Log("error", $e->getMessage() . "\n" . $e->getTraceAsString()); + Kohana_Log::add("error", $e->getMessage() . "\n" . $e->getTraceAsString()); return ""; } } diff --git a/modules/gallery/libraries/ORM_MPTT.php b/modules/gallery/libraries/ORM_MPTT.php index ebd7abc2..0ea519c9 100644 --- a/modules/gallery/libraries/ORM_MPTT.php +++ b/modules/gallery/libraries/ORM_MPTT.php @@ -52,10 +52,16 @@ class ORM_MPTT_Core extends ORM { try { // Make a hole in the parent for this new item - $this->db->query( - "UPDATE {{$this->table_name}} SET `left_ptr` = `left_ptr` + 2 WHERE `left_ptr` >= {$parent->right_ptr}"); - $this->db->query( - "UPDATE {{$this->table_name}} SET `right_ptr` = `right_ptr` + 2 WHERE `right_ptr` >= {$parent->right_ptr}"); + $this->db_builder + ->update($this->table_name) + ->set("left_ptr", new Database_Expression("`left_ptr` + 2")) + ->where("left_ptr", ">=", $parent->right_ptr) + ->execute(); + $this->db_builder + ->update($this->table_name) + ->set("right_ptr", new Database_Expression("`right_ptr` + 2")) + ->where("right_ptr", ">=", $parent->right_ptr) + ->execute(); $parent->right_ptr += 2; // Insert this item into the hole @@ -94,10 +100,16 @@ class ORM_MPTT_Core extends ORM { $this->lock(); $this->reload(); // Assume that the prior lock holder may have changed this entry try { - $this->db->query( - "UPDATE {{$this->table_name}} SET `left_ptr` = `left_ptr` - 2 WHERE `left_ptr` > {$this->right_ptr}"); - $this->db->query( - "UPDATE {{$this->table_name}} SET `right_ptr` = `right_ptr` - 2 WHERE `right_ptr` > {$this->right_ptr}"); + $this->db_builder + ->update($this->table_name) + ->set("left_ptr", new Database_Expression("`left_ptr` - 2")) + ->where("left_ptr", ">", $this->right_ptr) + ->execute(); + $this->db_builder + ->update($this->table_name) + ->set("right_ptr", new Database_Expression("`right_ptr` - 2")) + ->where("right_ptr", ">", $this->right_ptr) + ->execute(); } catch (Exception $e) { $this->unlock(); throw $e; @@ -135,10 +147,10 @@ class ORM_MPTT_Core extends ORM { */ function parents() { return $this - ->where("`left_ptr` <= {$this->left_ptr}") - ->where("`right_ptr` >= {$this->right_ptr}") - ->where("id <> {$this->id}") - ->orderby("left_ptr", "ASC") + ->where("left_ptr", "<=", $this->left_ptr) + ->where("right_ptr", ">=", $this->right_ptr) + ->where("id", "<>", $this->id) + ->order_by("left_ptr", "ASC") ->find_all(); } @@ -149,14 +161,17 @@ class ORM_MPTT_Core extends ORM { * @param integer SQL limit * @param integer SQL offset * @param array additional where clauses - * @param array orderby + * @param array order_by * @return array ORM */ - function children($limit=null, $offset=0, $where=array(), $orderby=array("id" => "ASC")) { + function children($limit=null, $offset=null, $where=null, $order_by=array("id" => "ASC")) { + if ($where) { + $this->merge_where($where); + } + return $this - ->where("parent_id", $this->id) - ->where($where) - ->orderby($orderby) + ->where("parent_id", "=", $this->id) + ->order_by($order_by) ->find_all($limit, $offset); } @@ -167,10 +182,13 @@ class ORM_MPTT_Core extends ORM { * @param array additional where clauses * @return array ORM */ - function children_count($where=array()) { + function children_count($where=null) { + if ($where) { + $this->merge_where($where); + } + return $this - ->where($where) - ->where("parent_id", $this->id) + ->where("parent_id", "=", $this->id) ->count_all(); } @@ -180,15 +198,18 @@ class ORM_MPTT_Core extends ORM { * @param integer SQL limit * @param integer SQL offset * @param array additional where clauses - * @param array orderby + * @param array order_by * @return object ORM_Iterator */ - function descendants($limit=null, $offset=0, $where=array(), $orderby=array("id" => "ASC")) { + function descendants($limit=null, $offset=null, $where=null, $order_by=array("id" => "ASC")) { + if ($where) { + $this->merge_where($where); + } + return $this - ->where("left_ptr >", $this->left_ptr) - ->where("right_ptr <=", $this->right_ptr) - ->where($where) - ->orderby($orderby) + ->where("left_ptr", ">", $this->left_ptr) + ->where("right_ptr", "<=", $this->right_ptr) + ->order_by($order_by) ->find_all($limit, $offset); } @@ -198,11 +219,14 @@ class ORM_MPTT_Core extends ORM { * @param array additional where clauses * @return integer child count */ - function descendants_count($where=array()) { + function descendants_count($where=null) { + if ($where) { + $this->merge_where($where); + } + return $this - ->where("left_ptr >", $this->left_ptr) - ->where("right_ptr <=", $this->right_ptr) - ->where($where) + ->where("left_ptr", ">", $this->left_ptr) + ->where("right_ptr", "<=", $this->right_ptr) ->count_all(); } @@ -231,23 +255,32 @@ class ORM_MPTT_Core extends ORM { try { if ($level_delta) { // Update the levels for the to-be-moved items - $this->db->query( - "UPDATE {{$this->table_name}} SET `level` = `level` + $level_delta" . - " WHERE `left_ptr` >= $original_left_ptr AND `right_ptr` <= $original_right_ptr"); + $this->db_builder + ->update($this->table_name) + ->set("level", new Database_Expression("`level` + $level_delta")) + ->where("left_ptr", ">=", $original_left_ptr) + ->where("right_ptr", "<=", $original_right_ptr) + ->execute(); } // Make a hole in the target for the move - $target->db->query( - "UPDATE {{$this->table_name}} SET `left_ptr` = `left_ptr` + $size_of_hole" . - " WHERE `left_ptr` >= $target_right_ptr"); - $target->db->query( - "UPDATE {{$this->table_name}} SET `right_ptr` = `right_ptr` + $size_of_hole" . - " WHERE `right_ptr` >= $target_right_ptr"); + $target->db_builder + ->update($this->table_name) + ->set("left_ptr", new Database_Expression("`left_ptr` + $size_of_hole")) + ->where("left_ptr", ">=", $target_right_ptr) + ->execute(); + $target->db_builder + ->update($this->table_name) + ->set("right_ptr", new Database_Expression("`right_ptr` + $size_of_hole")) + ->where("right_ptr", ">=", $target_right_ptr) + ->execute(); // Change the parent. - $this->db->query( - "UPDATE {{$this->table_name}} SET `parent_id` = {$target->id}" . - " WHERE `id` = {$this->id}"); + $this->db_builder + ->update($this->table_name) + ->set("parent_id", $target->id) + ->where("id", "=", $this->id) + ->execute(); // If the source is to the right of the target then we just adjusted its left_ptr and right_ptr above. $left_ptr = $original_left_ptr; @@ -258,20 +291,25 @@ class ORM_MPTT_Core extends ORM { } $new_offset = $target->right_ptr - $left_ptr; - $this->db->query( - "UPDATE {{$this->table_name}}" . - " SET `left_ptr` = `left_ptr` + $new_offset," . - " `right_ptr` = `right_ptr` + $new_offset" . - " WHERE `left_ptr` >= $left_ptr" . - " AND `right_ptr` <= $right_ptr"); + $this->db_builder + ->update($this->table_name) + ->set("left_ptr", new Database_Expression("`left_ptr` + $new_offset")) + ->set("right_ptr", new Database_Expression("`right_ptr` + $new_offset")) + ->where("left_ptr", ">=", $left_ptr) + ->where("right_ptr", "<=", $right_ptr) + ->execute(); // Close the hole in the source's parent after the move - $this->db->query( - "UPDATE {{$this->table_name}} SET `left_ptr` = `left_ptr` - $size_of_hole" . - " WHERE `left_ptr` > $right_ptr"); - $this->db->query( - "UPDATE {{$this->table_name}} SET `right_ptr` = `right_ptr` - $size_of_hole" . - " WHERE `right_ptr` > $right_ptr"); + $this->db_builder + ->update($this->table_name) + ->set("left_ptr", new Database_Expression("`left_ptr` - $size_of_hole")) + ->where("left_ptr", ">", $right_ptr) + ->execute(); + $this->db_builder + ->update($this->table_name) + ->set("right_ptr", new Database_Expression("`right_ptr` - $size_of_hole")) + ->where("right_ptr", ">", $right_ptr) + ->execute(); } catch (Exception $e) { $this->unlock(); throw $e; diff --git a/modules/gallery/libraries/SafeString.php b/modules/gallery/libraries/SafeString.php index ba3a8ffd..cc63f3a7 100644 --- a/modules/gallery/libraries/SafeString.php +++ b/modules/gallery/libraries/SafeString.php @@ -146,7 +146,7 @@ class SafeString_Core { * Escape special HTML chars ("<", ">", "&", etc.) to HTML entities. */ private static function _escape_for_html($dirty_html) { - return html::specialchars($dirty_html); + return html::chars($dirty_html); } /** diff --git a/modules/gallery/libraries/Sendmail.php b/modules/gallery/libraries/Sendmail.php index 7bc21a67..aa2b51a9 100644 --- a/modules/gallery/libraries/Sendmail.php +++ b/modules/gallery/libraries/Sendmail.php @@ -52,7 +52,7 @@ class Sendmail_Core { break; case "header": if (count($value) != 2) { - Kohana::log("error", wordwrap("Invalid header parameters\n" . Kohana::debug($value))); + Kohana_Log::add("error", wordwrap("Invalid header parameters\n" . Kohana::debug($value))); throw new Exception("@todo INVALID_HEADER_PARAMETERS"); } $this->headers[$value[0]] = $value[1]; @@ -71,7 +71,7 @@ class Sendmail_Core { public function send() { if (empty($this->to)) { - Kohana::log("error", wordwrap("Sending mail failed:\nNo to address specified")); + Kohana_Log::add("error", wordwrap("Sending mail failed:\nNo to address specified")); throw new Exception("@todo TO_IS_REQUIRED_FOR_MAIL"); } $to = implode(", ", $this->to); diff --git a/modules/gallery/libraries/drivers/Cache/Database.php b/modules/gallery/libraries/drivers/Cache/Database.php index 7e2aeabc..82a09ab9 100644 --- a/modules/gallery/libraries/drivers/Cache/Database.php +++ b/modules/gallery/libraries/drivers/Cache/Database.php @@ -20,43 +20,33 @@ /* * Based on the Cache_Sqlite_Driver developed by the Kohana Team */ -class Cache_Database_Driver implements Cache_Driver { +class Cache_Database_Driver extends Cache_Driver { // Kohana database instance protected $db; /** - * Tests that the storage location is a directory and is writable. - */ - public function __construct() { - // Open up an instance of the database - $this->db = Database::instance(); - - if (!$this->db->table_exists("caches")) { - throw new Exception("@todo Cache table is not defined"); - } - } - - /** * Checks if a cache id is already set. * * @param string cache id * @return boolean */ public function exists($id) { - $count = $this->db->count_records("caches", array("key" => $id, "expiration >=" => time())); + $count = db::build() + ->where("key", "=", $id) + ->where("expiration", ">=", time()) + ->count_records("caches"); return $count > 0; } /** * Sets a cache item to the given data, tags, and lifetime. * - * @param string cache id to set - * @param string data in the cache + * @param array assoc array of key => value pairs * @param array cache tags * @param integer lifetime * @return bool */ - public function set($id, $data, array $tags = NULL, $lifetime) { + public function set($items, $tags=null, $lifetime=null) { if (!empty($tags)) { // Escape the tags, adding brackets so the tag can be explicitly matched $tags = "<" . implode(">,<", $tags) . ">"; @@ -69,46 +59,53 @@ class Cache_Database_Driver implements Cache_Driver { $lifetime += time(); } - if ($this->exists($id)) { - $status = $this->db->update( - "caches", - array("tags" => $tags, "expiration" => $lifetime, "cache" => serialize($data)), array("key" => $id)); - } else { - $status = $this->db->insert( - "caches", - array("key" => $id, "tags" => $tags, "expiration" => $lifetime, "cache" => serialize($data))); + foreach ($items as $id => $data) { + if ($this->exists($id)) { + $status = db::build() + ->update("caches") + ->set("tags", $tags) + ->set("expiration", $lifetime) + ->set("cache", serialize($data)) + ->where("key", "=", $id) + ->execute(); + } else { + $status = db::build() + ->insert("caches") + ->columns("key", "tags", "expiration", "cache") + ->values($id, $tags, $lifetime, serialize($data)) + ->execute(); + } } - return count($status) > 0; + return true; } /** - * Finds an array of ids for a given tag. - * - * @param string tag name - * @return array of ids that match the tag + * Get cache items by tag + * @param array cache tags + * @return array cached data */ - public function find($tag) { - $db_result = $this->db->from("caches") - ->like("tags", "<$tag>") - ->get() - ->result(true); + public function get_tag($tags) { + $db = db::build() + ->select() + ->from("caches"); + foreach ($tags as $tag) { + $db->where("tags", "LIKE", "%<$tag>%"); + } + $db_result = $db->execute(); // An array will always be returned $result = array(); + // Disable notices for unserializing + $ER = error_reporting(~E_NOTICE); if ($db_result->count() > 0) { - // Disable notices for unserializing - $ER = error_reporting(~E_NOTICE); - foreach ($db_result as $row) { // Add each cache to the array $result[$row->key] = unserialize($row->cache); } - - // Turn notices back on - error_reporting($ER); } + error_reporting($ER); return $result; } @@ -120,9 +117,13 @@ class Cache_Database_Driver implements Cache_Driver { * @param string cache id * @return mixed|NULL */ - public function get($id) { + public function get($keys, $single=false) { $data = null; - $result = $this->db->getwhere("caches", array("key" => $id)); + $result = db::build() + ->select() + ->from("caches") + ->where("key", "IN", $keys) + ->execute(); if (count($result) > 0) { $cache = $result->current(); @@ -152,32 +153,47 @@ class Cache_Database_Driver implements Cache_Driver { * @param bool delete a tag * @return bool */ - public function delete($id, $tag = false) { - $this->db->from("caches"); + public function delete($id, $tag=false) { + $db = db::build() + ->delete("caches"); if ($id === true) { - $this->db->where(1); // Delete all caches } else if ($tag === true) { - $this->db->like("tags", "<$id>"); + $db->where("tags", "LIKE", "%<$id>%"); } else { - $this->db->where("key", $id); + $db->where("key", "=", $id); } - $status = $this->db->delete(); + $status = $db->execute(); return count($status) > 0; } /** + * Delete cache items by tag + */ + public function delete_tag($tags) { + return $this->delete($tags, true); + } + + /** * Deletes all cache files that are older than the current time. */ public function delete_expired() { // Delete all expired caches - $status = $this->db->from("caches") - ->where(array("expiration !=" => 0, "expiration <=" => time())) - ->delete(); + $status = db::build() + ->delete("caches") + ->where("expiration", "<>", 0) + ->where("expiration", "<=", time()) + ->execute(); return count($status) > 0; } -} // End Cache Database Driver
\ No newline at end of file + /** + * Empty the cache + */ + public function delete_all() { + Database::instance()->query("TRUNCATE {caches}"); + } +}
\ No newline at end of file diff --git a/modules/gallery/models/item.php b/modules/gallery/models/item.php index 96415b3d..414181d9 100644 --- a/modules/gallery/models/item.php +++ b/modules/gallery/models/item.php @@ -21,7 +21,7 @@ class Item_Model extends ORM_MPTT { protected $children = 'items'; protected $sorting = array(); - var $rules = array( + var $form_rules = array( "name" => "required|length[0,255]", "title" => "required|length[0,255]", "description" => "length[0,65535]", @@ -76,9 +76,18 @@ class Item_Model extends ORM_MPTT { parent::delete(); if (is_dir($path)) { + // Take some precautions against accidentally deleting way too much + $delete_resize_path = dirname($resize_path); + $delete_thumb_path = dirname($thumb_path); + if ($delete_resize_path == VARPATH . "resizes" || + $delete_thumb_path == VARPATH . "thumbs" || + $path == VARPATH . "albums") { + throw new Exception( + "@todo DELETING_TOO_MUCH ($delete_resize_path, $delete_thumb_path, $path)"); + } @dir::unlink($path); - @dir::unlink(dirname($resize_path)); - @dir::unlink(dirname($thumb_path)); + @dir::unlink($delete_resize_path); + @dir::unlink($delete_thumb_path); } else { @unlink($path); @unlink($resize_path); @@ -120,11 +129,13 @@ class Item_Model extends ORM_MPTT { if ($this->is_album()) { @rename(dirname($original_resize_path), dirname($this->resize_path())); @rename(dirname($original_thumb_path), dirname($this->thumb_path())); - Database::instance() - ->update("items", - array("relative_path_cache" => null, - "relative_url_cache" => null), - array("left_ptr >" => $this->left_ptr, "right_ptr <" => $this->right_ptr)); + db::build() + ->update("items") + ->set("relative_path_cache", null) + ->set("relative_url_cache", null) + ->where("left_ptr", ">", $this->left_ptr) + ->where("right_ptr", "<", $this->right_ptr) + ->execute(); } else { @rename($original_resize_path, $this->resize_path()); @rename($original_thumb_path, $this->thumb_path()); @@ -170,11 +181,13 @@ class Item_Model extends ORM_MPTT { $this->name = $new_name; if ($this->is_album()) { - Database::instance() - ->update("items", - array("relative_path_cache" => null, - "relative_url_cache" => null), - array("left_ptr >" => $this->left_ptr, "right_ptr <" => $this->right_ptr)); + db::build() + ->update("items") + ->set("relative_url_cache", null) + ->set("relative_path_cache", null) + ->where("left_ptr", ">", $this->left_ptr) + ->where("right_ptr", "<", $this->right_ptr) + ->execute(); } return $this; @@ -224,7 +237,8 @@ class Item_Model extends ORM_MPTT { */ public function file_url($full_uri=false) { $relative_path = "var/albums/" . $this->relative_path(); - return $full_uri ? url::abs_file($relative_path) : url::file($relative_path); + return ($full_uri ? url::abs_file($relative_path) : url::file($relative_path)) + . "?m={$this->updated}"; } /** @@ -255,7 +269,7 @@ class Item_Model extends ORM_MPTT { * photo: http://example.com/gallery3/var/albums/album1/photo.thumb.jpg */ public function thumb_url($full_uri=false) { - $cache_buster = "?m=" . $this->updated; + $cache_buster = "?m={$this->updated}"; $relative_path = "var/thumbs/" . $this->relative_path(); $base = ($full_uri ? url::abs_file($relative_path) : url::file($relative_path)); if ($this->is_photo()) { @@ -285,7 +299,8 @@ class Item_Model extends ORM_MPTT { public function resize_url($full_uri=false) { $relative_path = "var/resizes/" . $this->relative_path(); return ($full_uri ? url::abs_file($relative_path) : url::file($relative_path)) . - ($this->is_album() ? "/.album.jpg" : ""); + ($this->is_album() ? "/.album.jpg" : "") + . "?m={$this->updated}"; } /** @@ -294,14 +309,14 @@ class Item_Model extends ORM_MPTT { private function _build_relative_caches() { $names = array(); $slugs = array(); - foreach (Database::instance() + foreach (db::build() ->select(array("name", "slug")) ->from("items") - ->where("left_ptr <=", $this->left_ptr) - ->where("right_ptr >=", $this->right_ptr) - ->where("id <>", 1) - ->orderby("left_ptr", "ASC") - ->get() as $row) { + ->where("left_ptr", "<=", $this->left_ptr) + ->where("right_ptr", ">=", $this->right_ptr) + ->where("id", "<>", 1) + ->order_by("left_ptr", "ASC") + ->execute() as $row) { // Don't encode the names segment $names[] = rawurlencode($row->name); $slugs[] = rawurlencode($row->slug); @@ -318,7 +333,7 @@ class Item_Model extends ORM_MPTT { * @return string */ public function relative_path() { - if (!$this->loaded) { + if (!$this->loaded()) { return; } @@ -333,7 +348,7 @@ class Item_Model extends ORM_MPTT { * @return string */ public function relative_url() { - if (!$this->loaded) { + if (!$this->loaded()) { return; } @@ -371,10 +386,12 @@ class Item_Model extends ORM_MPTT { // Clear the relative url cache for this item and all children $this->relative_url_cache = null; if ($this->is_album()) { - Database::instance() - ->update("items", - array("relative_url_cache" => null), - array("left_ptr >" => $this->left_ptr, "right_ptr <" => $this->right_ptr)); + db::build() + ->update("items") + ->set("relative_url_cache", null) + ->where("left_ptr", ">", $this->left_ptr) + ->where("right_ptr", "<", $this->right_ptr) + ->execute(); } } } @@ -392,7 +409,7 @@ class Item_Model extends ORM_MPTT { if (!empty($this->changed) && $significant_changes) { $this->updated = time(); - if (!$this->loaded) { + if (!$this->loaded()) { $this->created = $this->updated; $this->weight = item::get_max_weight(); } else { @@ -437,14 +454,14 @@ class Item_Model extends ORM_MPTT { } else { $comp = "<"; } - $db = Database::instance(); + $db = db::build(); // If the comparison column has NULLs in it, we can't use comparators on it and will have to // deal with it the hard way. $count = $db->from("items") - ->where("parent_id", $this->id) - ->where($this->sort_column, NULL) - ->where($where) + ->where("parent_id", "=", $this->id) + ->where($this->sort_column, "=", NULL) + ->merge_where($where) ->count_records(); if (empty($count)) { @@ -452,9 +469,9 @@ class Item_Model extends ORM_MPTT { $sort_column = $this->sort_column; $position = $db->from("items") - ->where("parent_id", $this->id) - ->where("$sort_column $comp ", $child->$sort_column) - ->where($where) + ->where("parent_id", "=", $this->id) + ->where($sort_column, $comp, $child->$sort_column) + ->merge_where($where) ->count_records(); // We stopped short of our target value in the sort (notice that we're using a < comparator @@ -465,12 +482,14 @@ class Item_Model extends ORM_MPTT { // // Fix this by doing a 2nd query where we iterate over the equivalent columns and add them to // our base value. - foreach ($db->from("items") - ->where("parent_id", $this->id) - ->where($sort_column, $child->$sort_column) - ->where($where) - ->orderby(array("id" => "ASC")) - ->get() as $row) { + foreach ($db + ->select("id") + ->from("items") + ->where("parent_id", "=", $this->id) + ->where($sort_column, "=", $child->$sort_column) + ->merge_where($where) + ->order_by(array("id" => "ASC")) + ->execute() as $row) { $position++; if ($row->id == $child->id) { break; @@ -484,19 +503,19 @@ class Item_Model extends ORM_MPTT { // // Reproduce the children() functionality here using Database directly to avoid loading the // whole ORM for each row. - $orderby = array($this->sort_column => $this->sort_order); + $order_by = array($this->sort_column => $this->sort_order); // Use id as a tie breaker if ($this->sort_column != "id") { - $orderby["id"] = "ASC"; + $order_by["id"] = "ASC"; } $position = 0; foreach ($db->select("id") ->from("items") - ->where("parent_id", $this->id) - ->where($where) - ->orderby($orderby) - ->get() as $row) { + ->where("parent_id", "=", $this->id) + ->merge_where($where) + ->order_by($order_by) + ->execute() as $row) { $position++; if ($row->id == $child->id) { break; @@ -601,18 +620,18 @@ class Item_Model extends ORM_MPTT { * @param integer SQL limit * @param integer SQL offset * @param array additional where clauses - * @param array orderby + * @param array order_by * @return array ORM */ - function children($limit=null, $offset=0, $where=array(), $orderby=null) { - if (empty($orderby)) { - $orderby = array($this->sort_column => $this->sort_order); + function children($limit=null, $offset=null, $where=array(), $order_by=null) { + if (empty($order_by)) { + $order_by = array($this->sort_column => $this->sort_order); // Use id as a tie breaker if ($this->sort_column != "id") { - $orderby["id"] = "ASC"; + $order_by["id"] = "ASC"; } } - return parent::children($limit, $offset, $where, $orderby); + return parent::children($limit, $offset, $where, $order_by); } /** @@ -626,14 +645,14 @@ class Item_Model extends ORM_MPTT { * @param array additional where clauses * @return object ORM_Iterator */ - function descendants($limit=null, $offset=0, $where=array(), $orderby=null) { - if (empty($orderby)) { - $orderby = array($this->sort_column => $this->sort_order); + function descendants($limit=null, $offset=null, $where=array(), $order_by=null) { + if (empty($order_by)) { + $order_by = array($this->sort_column => $this->sort_order); // Use id as a tie breaker if ($this->sort_column != "id") { - $orderby["id"] = "ASC"; + $order_by["id"] = "ASC"; } } - return parent::descendants($limit, $offset, $where, $orderby); + return parent::descendants($limit, $offset, $where, $order_by); } } diff --git a/modules/gallery/models/log.php b/modules/gallery/models/log.php index c816a4a7..a2044325 100644 --- a/modules/gallery/models/log.php +++ b/modules/gallery/models/log.php @@ -28,7 +28,7 @@ class Log_Model extends ORM { try { return identity::lookup_user($this->user_id); } catch (Exception $e) { - Kohana::log("alert", "Unable to load user with id $this->user_id"); + Kohana_Log::add("alert", "Unable to load user with id $this->user_id"); return null; } } else { diff --git a/modules/gallery/tests/Access_Helper_Test.php b/modules/gallery/tests/Access_Helper_Test.php index e9e5cb26..084bfb47 100644 --- a/modules/gallery/tests/Access_Helper_Test.php +++ b/modules/gallery/tests/Access_Helper_Test.php @@ -76,7 +76,7 @@ class Access_Helper_Test extends Unit_Test_Case { access::deny(identity::registered_users(), "view", $item); $user = identity::create_user("access_test", "Access Test", ""); - foreach ($user->groups as $group) { + foreach ($user->groups() as $group) { $user->remove($group); } $user->add($access_test); @@ -93,7 +93,7 @@ class Access_Helper_Test extends Unit_Test_Case { access::deny(identity::registered_users(), "view", $item); $user = identity::create_user("access_test", "Access Test", ""); - foreach ($user->groups as $group) { + foreach ($user->groups() as $group) { $user->remove($group); } $user->save(); @@ -106,15 +106,15 @@ class Access_Helper_Test extends Unit_Test_Case { $item = album::create($root, rand(), "test album"); // New rows exist - $this->assert_true(ORM::factory("access_cache")->where("item_id", $item->id)->find()->loaded); - $this->assert_true(ORM::factory("access_intent")->where("item_id", $item->id)->find()->loaded); + $this->assert_true(ORM::factory("access_cache")->where("item_id", "=", $item->id)->find()->loaded()); + $this->assert_true(ORM::factory("access_intent")->where("item_id", "=", $item->id)->find()->loaded()); // Delete the item $item->delete(); // Rows are gone - $this->assert_false(ORM::factory("access_cache")->where("item_id", $item->id)->find()->loaded); - $this->assert_false(ORM::factory("access_intent")->where("item_id", $item->id)->find()->loaded); + $this->assert_false(ORM::factory("access_cache")->where("item_id", "=", $item->id)->find()->loaded()); + $this->assert_false(ORM::factory("access_intent")->where("item_id", "=", $item->id)->find()->loaded()); } public function new_photos_inherit_parent_permissions_test() { @@ -131,7 +131,7 @@ class Access_Helper_Test extends Unit_Test_Case { public function can_allow_deny_and_reset_intent_test() { $root = ORM::factory("item", 1); $album = album::create($root, rand(), "test album"); - $intent = ORM::factory("access_intent")->where("item_id", $album)->find(); + $intent = ORM::factory("access_intent")->where("item_id", "=", $album->id)->find(); // Allow access::allow(identity::everybody(), "view", $album); @@ -141,19 +141,19 @@ class Access_Helper_Test extends Unit_Test_Case { access::deny(identity::everybody(), "view", $album); $this->assert_same( access::DENY, - ORM::factory("access_intent")->where("item_id", $album)->find()->view_1); + ORM::factory("access_intent")->where("item_id", "=", $album->id)->find()->view_1); // Allow again. If the initial value was allow, then the first Allow clause above may not // have actually changed any values. access::allow(identity::everybody(), "view", $album); $this->assert_same( access::ALLOW, - ORM::factory("access_intent")->where("item_id", $album)->find()->view_1); + ORM::factory("access_intent")->where("item_id", "=", $album->id)->find()->view_1); access::reset(identity::everybody(), "view", $album); $this->assert_same( null, - ORM::factory("access_intent")->where("item_id", $album)->find()->view_1); + ORM::factory("access_intent")->where("item_id", "=", $album->id)->find()->view_1); } public function cant_reset_root_item_test() { @@ -288,7 +288,7 @@ class Access_Helper_Test extends Unit_Test_Case { public function i_can_edit_test() { // Create a new user that belongs to no groups $user = identity::create_user("access_test", "Access Test", ""); - foreach ($user->groups as $group) { + foreach ($user->groups() as $group) { $user->remove($group); } $user->save(); diff --git a/modules/gallery/tests/Album_Helper_Test.php b/modules/gallery/tests/Album_Helper_Test.php index 2080ef30..1284b8cc 100644 --- a/modules/gallery/tests/Album_Helper_Test.php +++ b/modules/gallery/tests/Album_Helper_Test.php @@ -57,7 +57,7 @@ class Album_Helper_Test extends Unit_Test_Case { $rand = rand(); $root = ORM::factory("item", 1); $album = album::create($root, $rand, $rand, $rand); - $this->assert_equal("http://./var/resizes/$rand/.album.jpg", $album->resize_url()); + $this->assert_equal("http://./var/resizes/$rand/.album.jpg?m={$album->updated}", $album->resize_url()); } public function create_album_shouldnt_allow_names_with_slash_test() { diff --git a/modules/gallery/tests/Albums_Controller_Test.php b/modules/gallery/tests/Albums_Controller_Test.php index 5f23f821..4d8935cd 100644 --- a/modules/gallery/tests/Albums_Controller_Test.php +++ b/modules/gallery/tests/Albums_Controller_Test.php @@ -20,7 +20,6 @@ class Albums_Controller_Test extends Unit_Test_Case { public function setup() { $this->_save = array($_POST, $_SERVER); - $_SERVER["HTTP_REFERER"] = "HTTP_REFERER"; } public function teardown() { @@ -36,8 +35,10 @@ class Albums_Controller_Test extends Unit_Test_Case { $this->_album = album::create($root, "test", "test", "test"); $orig_name = $this->_album->name; - $_POST["dirname"] = "test"; - $_POST["name"] = "new name"; + // Randomize to avoid conflicts. + $new_dirname = "new_name_" . rand(); + + $_POST["dirname"] = $new_dirname; $_POST["title"] = "new title"; $_POST["description"] = "new description"; $_POST["column"] = "weight"; @@ -53,13 +54,11 @@ class Albums_Controller_Test extends Unit_Test_Case { ob_end_clean(); $this->assert_equal( - json_encode(array("result" => "success", "location" => "HTTP_REFERER")), + json_encode(array("result" => "success")), $results); + $this->assert_equal($new_dirname, $this->_album->name); $this->assert_equal("new title", $this->_album->title); $this->assert_equal("new description", $this->_album->description); - - // We don't change the name, yet. - $this->assert_equal($orig_name, $this->_album->name); } public function change_album_no_csrf_fails_test() { diff --git a/modules/gallery/tests/Cache_Test.php b/modules/gallery/tests/Cache_Test.php index 6b525265..d5bf37cc 100644 --- a/modules/gallery/tests/Cache_Test.php +++ b/modules/gallery/tests/Cache_Test.php @@ -20,88 +20,83 @@ class Cache_Test extends Unit_Test_Case { private $_driver; public function setup() { - Database::instance()->from("caches")->where(1)->delete(); + db::build()->delete("caches")->execute(); $this->_driver = new Cache_Database_Driver(); } public function cache_exists_test() { - $db = Database::instance(); - $this->assert_false($this->_driver->exists("test_key"), "test_key should not be defined"); $id = md5(rand()); - $db->insert("caches", array("key" => $id, "tags" => "<tag1>, <tag2>", - "expiration" => 84600 + time(), - "cache" => serialize("some test data"))); + db::build() + ->insert("caches") + ->columns("key", "tags", "expiration", "cache") + ->values($id, "<tag1>, <tag2>", 84600 + time(), serialize("some test data")) + ->execute(); $this->assert_true($this->_driver->exists($id), "test_key should be defined"); } public function cache_get_test() { - $db = Database::instance(); - $id = md5(rand()); - $db->insert("caches", array("key" => $id, "tags" => "<tag1>, <tag2>", - "expiration" => 84600 + time(), - "cache" => serialize("some test data"))); - $data = $this->_driver->get($id); + db::build() + ->insert("caches") + ->columns("key", "tags", "expiration", "cache") + ->values($id, "<tag1>, <tag2>", 84600 + time(), serialize("some test data")) + ->execute(); + + $data = $this->_driver->get(array($id)); $this->assert_equal("some test data", $data, "cached data should match"); - $data = $this->_driver->get(""); + $data = $this->_driver->get(array("")); $this->assert_equal(null, $data, "cached data should not be found"); } public function cache_set_test() { - $db = Database::instance(); - $id = md5(rand()); $original_data = array("field1" => "value1", "field2" => "value2"); - $this->_driver->set($id, $original_data, array("tag1", "tag2"), 84600); + $this->_driver->set(array($id => $original_data), array("tag1", "tag2"), 84600); - $data = $this->_driver->get($id); + $data = $this->_driver->get(array($id)); $this->assert_equal($original_data, $data, "cached data should match"); } - public function cache_find_test() { - $db = Database::instance(); - + public function cache_get_tag_test() { $id1 = md5(rand()); $value1 = array("field1" => "value1", "field2" => "value2"); - $this->_driver->set($id1, $value1, array("tag1", "tag2"), 84600); + $this->_driver->set(array($id1 => $value1), array("tag1", "tag2"), 84600); $id2 = md5(rand()); $value2 = array("field3" => "value3", "field4" => "value4"); - $this->_driver->set($id2, $value2, array("tag2", "tag3"), 84600); + $this->_driver->set(array($id2 => $value2), array("tag2", "tag3"), 84600); $id3 = md5(rand()); $value3 = array("field5" => "value5", "field6" => "value6"); - $this->_driver->set($id3, $value3, array("tag3", "tag4"), 84600); + $this->_driver->set(array($id3 => $value3), array("tag3", "tag4"), 84600); - $data = $this->_driver->find("tag2"); + $data = $this->_driver->get_tag(array("tag2")); $expected = array($id1 => $value1, $id2 => $value2); ksort($expected); $this->assert_equal($expected, $data, "Expected id1 & id2"); - $data = $this->_driver->find("tag4"); + $data = $this->_driver->get_tag(array("tag4")); $this->assert_equal(array($id3 => $value3), $data, "Expected id3"); } public function cache_delete_expired_test() { - $db = Database::instance(); - $id1 = md5(rand()); $value1 = array("field1" => "value1", "field2" => "value2"); - $this->_driver->set($id1, $value1, array("tag1", "tag2"), -84600); + $this->_driver->set(array($id1 => $value1), array("tag1", "tag2"), -84600); $id2 = md5(rand()); $value2 = array("field3" => "value3", "field4" => "value4"); - $this->_driver->set($id2, $value2, array("tag2", "tag3"), -846000); + $this->_driver->set(array($id2 => $value2), array("tag2", "tag3"), -846000); $id3 = md5(rand()); $value3 = array("field5" => "value5", "field6" => "value6"); - $this->_driver->set($id3, $value3, array("tag3", "tag4"), -84600); + $this->_driver->set(array($id3 => $value3), array("tag3", "tag4"), -84600); $data = $this->_driver->delete_expired(); @@ -111,19 +106,17 @@ class Cache_Test extends Unit_Test_Case { } public function cache_delete_id_test() { - $db = Database::instance(); - $id1 = md5(rand()); $value1 = array("field1" => "value1", "field2" => "value2"); - $this->_driver->set($id1, $value1, array("tag1", "tag2"), 84600); + $this->_driver->set(array($id1 => $value1), array("tag1", "tag2"), 84600); $id2 = md5(rand()); $value2 = array("field3" => "value3", "field4" => "value4"); - $this->_driver->set($id2, $value2, array("tag2", "tag3"), 846000); + $this->_driver->set(array($id2 => $value2), array("tag2", "tag3"), 846000); $id3 = md5(rand()); $value3 = array("field5" => "value5", "field6" => "value6"); - $this->_driver->set($id3, $value3, array("tag3", "tag4"), 84600); + $this->_driver->set(array($id3 => $value3), array("tag3", "tag4"), 84600); $this->_driver->delete($id1); @@ -133,19 +126,17 @@ class Cache_Test extends Unit_Test_Case { } public function cache_delete_tag_test() { - $db = Database::instance(); - $id1 = md5(rand()); $value1 = array("field1" => "value1", "field2" => "value2"); - $this->_driver->set($id1, $value1, array("tag1", "tag2"), 84600); + $this->_driver->set(array($id1 => $value1), array("tag1", "tag2"), 84600); $id2 = md5(rand()); $value2 = array("field3" => "value3", "field4" => "value4"); - $this->_driver->set($id2, $value2, array("tag2", "tag3"), 846000); + $this->_driver->set(array($id2 => $value2), array("tag2", "tag3"), 846000); $id3 = md5(rand()); $value3 = array("field5" => "value5", "field6" => "value6"); - $this->_driver->set($id3, $value3, array("tag3", "tag4"), 84600); + $this->_driver->set(array($id3 => $value3), array("tag3", "tag4"), 84600); $data = $this->_driver->delete("tag3", true); @@ -155,19 +146,17 @@ class Cache_Test extends Unit_Test_Case { } public function cache_delete_all_test() { - $db = Database::instance(); - $id1 = md5(rand()); $value1 = array("field1" => "value1", "field2" => "value2"); - $this->_driver->set($id1, $value1, array("tag1", "tag2"), 84600); + $this->_driver->set(array($id1 => $value1), array("tag1", "tag2"), 84600); $id2 = md5(rand()); $value2 = array("field3" => "value3", "field4" => "value4"); - $this->_driver->set($id2, $value2, array("tag2", "tag3"), 846000); + $this->_driver->set(array($id2 => $value2), array("tag2", "tag3"), 846000); $id3 = md5(rand()); $value3 = array("field5" => "value5", "field6" => "value6"); - $this->_driver->set($id3, $value3, array("tag3", "tag4"), 84600); + $this->_driver->set(array($id3 => $value3), array("tag3", "tag4"), 84600); $data = $this->_driver->delete(true); diff --git a/modules/gallery/tests/Database_Test.php b/modules/gallery/tests/Database_Test.php index 98bd4046..6aa186e5 100644 --- a/modules/gallery/tests/Database_Test.php +++ b/modules/gallery/tests/Database_Test.php @@ -18,81 +18,95 @@ * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ class Database_Test extends Unit_Test_Case { + function setup() { + $config = Kohana_Config::instance(); + $config->set("database.mock.connection.type", "mock"); + $config->set("database.mock.cache", false); + $config->set("database.mock.table_prefix", "g_"); + } + function simple_where_test() { - $sql = Database::instance() - ->where("a", 1) - ->where("b", 2) + $sql = db::build("mock") + ->select("some_column") + ->from("some_table") + ->where("a", "=", 1) + ->where("b", "=", 2) ->compile(); $sql = str_replace("\n", " ", $sql); - $this->assert_same("SELECT * WHERE `a` = 1 AND `b` = 2", $sql); + $this->assert_same("SELECT [some_column] FROM [some_table] WHERE [a] = [1] AND [b] = [2]", $sql); } function compound_where_test() { - $sql = Database::instance() - ->where("outer1", 1) - ->open_paren() - ->where("inner1", 1) - ->orwhere("inner2", 2) - ->close_paren() - ->where("outer2", 2) + $sql = db::build("mock") + ->select() + ->where("outer1", "=", 1) + ->and_open() + ->where("inner1", "=", 1) + ->or_where("inner2", "=", 2) + ->close() + ->where("outer2", "=", 2) ->compile(); $sql = str_replace("\n", " ", $sql); $this->assert_same( - "SELECT * WHERE `outer1` = 1 AND (`inner1` = 1 OR `inner2` = 2) AND `outer2` = 2", + "SELECT [*] WHERE [outer1] = [1] AND ([inner1] = [1] OR [inner2] = [2]) AND [outer2] = [2]", $sql); } function group_first_test() { - $sql = Database::instance() - ->open_paren() - ->where("inner1", 1) - ->orwhere("inner2", 2) - ->close_paren() - ->where("outer1", 1) - ->where("outer2", 2) + $sql = db::build("mock") + ->select() + ->and_open() + ->where("inner1", "=", 1) + ->or_where("inner2", "=", 2) + ->close() + ->where("outer1", "=", 1) + ->where("outer2", "=", 2) ->compile(); $sql = str_replace("\n", " ", $sql); $this->assert_same( - "SELECT * WHERE (`inner1` = 1 OR `inner2` = 2) AND `outer1` = 1 AND `outer2` = 2", + "SELECT [*] WHERE ([inner1] = [1] OR [inner2] = [2]) AND [outer1] = [1] AND [outer2] = [2]", $sql); } function where_array_test() { - $sql = Database::instance() - ->where("outer1", 1) - ->open_paren() - ->where("inner1", 1) - ->orwhere(array("inner2" => 2, "inner3" => 3)) - ->close_paren() + $sql = db::build("mock") + ->select() + ->where("outer1", "=", 1) + ->and_open() + ->where("inner1", "=", 1) + ->or_where("inner2", "=", 2) + ->or_where("inner3", "=", 3) + ->close() ->compile(); $sql = str_replace("\n", " ", $sql); $this->assert_same( - "SELECT * WHERE `outer1` = 1 AND (`inner1` = 1 OR `inner2` = 2 OR `inner3` = 3)", + "SELECT [*] WHERE [outer1] = [1] AND ([inner1] = [1] OR [inner2] = [2] OR [inner3] = [3])", $sql); } function notlike_test() { - $sql = Database::instance() - ->where("outer1", 1) - ->open_paren() - ->ornotlike("inner1", 1) - ->close_paren() + $sql = db::build("mock") + ->select() + ->where("outer1", "=", 1) + ->or_open() + ->where("inner1", "NOT LIKE", "%1%") + ->close() ->compile(); $sql = str_replace("\n", " ", $sql); $this->assert_same( - "SELECT * WHERE `outer1` = 1 OR ( `inner1` NOT LIKE '%1%')", + "SELECT [*] WHERE [outer1] = [1] OR ([inner1] NOT LIKE [%1%])", $sql); } function prefix_replacement_test() { - $db = Database_For_Test::instance(); - $converted = $db->add_table_prefixes("CREATE TABLE IF NOT EXISTS {test_tables} ( + $db = Database::instance("mock"); + $converted = $db->add_table_prefixes("CREATE TABLE IF NOT EXISTS {test} ( `id` int(9) NOT NULL auto_increment, `name` varchar(32) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY(`name`)) ENGINE=InnoDB DEFAULT CHARSET=utf8"); - $expected = "CREATE TABLE IF NOT EXISTS g3test_test_tables ( + $expected = "CREATE TABLE IF NOT EXISTS g_test ( `id` int(9) NOT NULL auto_increment, `name` varchar(32) NOT NULL, PRIMARY KEY (`id`), @@ -100,16 +114,16 @@ class Database_Test extends Unit_Test_Case { ENGINE=InnoDB DEFAULT CHARSET=utf8"; $this->assert_same($expected, $converted); - $sql = "UPDATE {test_tables} SET `name` = '{test string}' " . + $sql = "UPDATE {test} SET `name` = '{test string}' " . "WHERE `item_id` IN " . - " (SELECT `id` FROM {items} " . + " (SELECT `id` FROM {test} " . " WHERE `left_ptr` >= 1 " . " AND `right_ptr` <= 6)"; $sql = $db->add_table_prefixes($sql); - $expected = "UPDATE g3test_test_tables SET `name` = '{test string}' " . + $expected = "UPDATE g_test SET `name` = '{test string}' " . "WHERE `item_id` IN " . - " (SELECT `id` FROM g3test_items " . + " (SELECT `id` FROM g_test " . " WHERE `left_ptr` >= 1 " . " AND `right_ptr` <= 6)"; @@ -117,29 +131,52 @@ class Database_Test extends Unit_Test_Case { } function prefix_no_replacement_test() { - $update = Database_For_Test::instance()->from("test_tables") - ->where("1 = 1") + $sql = db::build("mock") + ->from("test_tables") + ->where("1", "=", "1") ->set(array("name" => "Test Name")) - ->update(); + ->update() + ->compile(); + $sql = str_replace("\n", " ", $sql); + $this->assert_same("UPDATE [test_tables] SET [name] = [Test Name] WHERE [1] = [1]", $sql); + } +} - $expected = "UPDATE `g3test_test_tables` SET `name` = 'Test Name' WHERE 1 = 1"; +class Database_Mock extends Database { + public function connect() { + } - $this->assert_same($expected, $update); + public function disconnect() { } -} -class Database_For_Test extends Database { - static function instance() { - $db = new Database_For_Test(); - $db->_table_names["{items}"] = "g3test_items"; - $db->config["table_prefix"] = "g3test_"; - return $db; + public function set_charset($charset) { } - public function query($sql = '') { - if (!empty($sql)) { - $sql = $this->add_table_prefixes($sql); - } - return $sql; + public function query_execute($sql) { } -} + + public function escape($val) { + } + + public function list_constraints($table) { + } + + public function list_fields($table) { + } + + public function list_tables() { + return array("test"); + } + + public function quote_column($val) { + return "[$val]"; + } + + public function quote_table($val) { + return "[$val]"; + } + + public function quote($val) { + return "[$val]"; + } +}
\ No newline at end of file diff --git a/modules/gallery/tests/DrawForm_Test.php b/modules/gallery/tests/DrawForm_Test.php index 7ee80ca2..da8a6b04 100644 --- a/modules/gallery/tests/DrawForm_Test.php +++ b/modules/gallery/tests/DrawForm_Test.php @@ -23,28 +23,28 @@ class DrawForm_Test extends Unit_Test_Case { $form->input("title")->label(t("Title")); $form->textarea("description")->label(t("Text Area")); $form->submit("")->value(t("Submit")); - $rendered = $form->__toString(); + $csrf = access::csrf_token(); $expected = "<form action=\"http://./index.php/test/controller\" method=\"post\" " . "id=\"g-test-group-form\">\n" . - "<input type=\"hidden\" name=\"csrf\" value=\"" . access::csrf_token() . "\" />\n" . + "<input type=\"hidden\" name=\"csrf\" value=\"$csrf\" />" . " <ul>\n" . " <li>\n" . " <label for=\"title\" >Title</label>\n" . - " <input type=\"text\" id=\"title\" name=\"title\" value=\"\" " . + " <input type=\"text\" name=\"title\" value=\"\" " . "class=\"textbox\" />\n" . " </li>\n" . " <li>\n" . " <label for=\"description\" >Text Area</label>\n" . - " <textarea id=\"description\" name=\"description\" " . + " <textarea name=\"description\" rows=\"\" cols=\"\" " . "class=\"textarea\" ></textarea>\n" . " </li>\n" . " <li>\n" . " <input type=\"submit\" value=\"Submit\" class=\"submit\" />\n" . " </li>\n" . " </ul>\n" . - "</form>\n"; - $this->assert_same($expected, $rendered); + "</form>"; + $this->assert_same($expected, (string) $form); } function group_test() { @@ -53,22 +53,22 @@ class DrawForm_Test extends Unit_Test_Case { $group->input("title")->label(t("Title")); $group->textarea("description")->label(t("Text Area")); $group->submit("")->value(t("Submit")); - $rendered = $form->__toString(); + $csrf = access::csrf_token(); $expected = "<form action=\"http://./index.php/test/controller\" method=\"post\" " . "id=\"g-test-group-form\">\n" . - "<input type=\"hidden\" name=\"csrf\" value=\"" . access::csrf_token() . "\" />\n" . + "<input type=\"hidden\" name=\"csrf\" value=\"$csrf\" />" . " <fieldset>\n" . " <legend>Test Group</legend>\n" . " <ul>\n" . " <li>\n" . " <label for=\"title\" >Title</label>\n" . - " <input type=\"text\" id=\"title\" name=\"title\" value=\"\" " . + " <input type=\"text\" name=\"title\" value=\"\" " . "class=\"textbox\" />\n" . " </li>\n" . " <li>\n" . " <label for=\"description\" >Text Area</label>\n" . - " <textarea id=\"description\" name=\"description\" " . + " <textarea name=\"description\" rows=\"\" cols=\"\" " . "class=\"textarea\" ></textarea>\n" . " </li>\n" . " <li>\n" . @@ -76,8 +76,8 @@ class DrawForm_Test extends Unit_Test_Case { " </li>\n" . " </ul>\n" . " </fieldset>\n" . - "</form>\n"; - $this->assert_same($expected, $rendered); + "</form>"; + $this->assert_same($expected, (string) $form); } function form_script_test() { @@ -89,22 +89,22 @@ class DrawForm_Test extends Unit_Test_Case { ->url(url::file("test.js")) ->text("alert('Test Javascript');"); $group->submit("")->value(t("Submit")); - $rendered = $form->__toString(); + $csrf = access::csrf_token(); $expected = "<form action=\"http://./index.php/test/controller\" method=\"post\" " . "id=\"g-test-group-form\">\n" . - "<input type=\"hidden\" name=\"csrf\" value=\"" . access::csrf_token() . "\" />\n" . + "<input type=\"hidden\" name=\"csrf\" value=\"$csrf\" />" . " <fieldset>\n" . " <legend>Test Group</legend>\n" . " <ul>\n" . " <li>\n" . " <label for=\"title\" >Title</label>\n" . - " <input type=\"text\" id=\"title\" name=\"title\" value=\"\" " . + " <input type=\"text\" name=\"title\" value=\"\" " . "class=\"textbox\" />\n" . " </li>\n" . " <li>\n" . " <label for=\"description\" >Text Area</label>\n" . - " <textarea id=\"description\" name=\"description\" " . + " <textarea name=\"description\" rows=\"\" cols=\"\" " . "class=\"textarea\" ></textarea>\n" . " </li>\n" . " <li>\n" . @@ -116,8 +116,22 @@ class DrawForm_Test extends Unit_Test_Case { "<script type=\"text/javascript\">\n" . "alert('Test Javascript');\n" . "</script>\n" . - "</form>\n"; - $this->assert_same($expected, $rendered); + "</form>"; + $this->assert_same($expected, (string) $form); + } + + function two_hiddens_test() { + $form = new Forge("test/controller", "", "post"); + $form->hidden("HIDDEN_NAME")->value("HIDDEN_VALUE"); + + $csrf = access::csrf_token(); + $expected = "<form action=\"http://./index.php/test/controller\" method=\"post\" class=\"form\">\n" . + "<input type=\"hidden\" name=\"csrf\" value=\"$csrf\" />" . + "<input type=\"hidden\" name=\"HIDDEN_NAME\" value=\"HIDDEN_VALUE\" />" . + " <ul>\n" . + " </ul>\n" . + "</form>"; + $this->assert_same($expected, (string) $form); } } diff --git a/modules/gallery/tests/File_Structure_Test.php b/modules/gallery/tests/File_Structure_Test.php index 36342fda..b5026188 100644 --- a/modules/gallery/tests/File_Structure_Test.php +++ b/modules/gallery/tests/File_Structure_Test.php @@ -36,6 +36,10 @@ class File_Structure_Test extends Unit_Test_Case { $dir = new GalleryCodeFilterIterator( new RecursiveIteratorIterator(new RecursiveDirectoryIterator(DOCROOT))); foreach ($dir as $file) { + if (strpos($file, "modules/gallery/views/kohana/error.php")) { + continue; + } + if (strpos($file, "views")) { $this->assert_true( preg_match("#/views/.*?(\.html|mrss|txt)\.php$#", $file->getPathname()), @@ -57,10 +61,12 @@ class File_Structure_Test extends Unit_Test_Case { } private function _check_view_preamble($path, &$errors) { + $expected_2 = null; // The preamble for views is a single line that prevents direct script access if (strpos($path, SYSPATH) === 0) { // Kohana preamble $expected = "<?php defined('SYSPATH') OR die('No direct access allowed.'); ?>\n"; + $expected_2 = "<?php defined('SYSPATH') OR die('No direct access allowed.');\n"; // error.php } else { // Gallery preamble // @todo use the same preamble for both! @@ -71,26 +77,32 @@ class File_Structure_Test extends Unit_Test_Case { $actual = fgets($fp); fclose($fp); - if ($expected != $actual) { + if ($expected != $actual && $expected_2 != $actual) { $errors[] = "$path:1\n expected:\n\t$expected\n actual:\n\t$actual"; } } private function _check_php_preamble($path, &$errors) { + $expected_2 = null; $expected_3 = null; $expected_4 = null; if (strpos($path, SYSPATH) === 0 || strpos($path, MODPATH . "unit_test") === 0) { // Kohana: we only care about the first line $fp = fopen($path, "r"); $actual = array(fgets($fp)); fclose($fp); - $expected = array("<?php defined('SYSPATH') OR die('No direct access allowed.');\n"); + $expected = array("<?php defined('SYSPATH') OR die('No direct script access.');\n"); + $expected_2 = array("<?php defined('SYSPATH') OR die('No direct access allowed.');\n"); + $expected_3 = array("<?php defined('SYSPATH') or die('No direct access allowed.');\n"); + $expected_4 = array("<?php defined('SYSPATH') or die('No direct script access.');\n"); } else if (strpos($path, MODPATH . "forge") === 0 || strpos($path, MODPATH . "exif/lib") === 0 || strpos($path, MODPATH . "gallery/lib/HTMLPurifier") === 0 || $path == MODPATH . "user/lib/PasswordHash.php" || $path == DOCROOT . "var/database.php") { // 3rd party module security-only preambles, similar to Gallery's - $expected = array("<?php defined(\"SYSPATH\") or die(\"No direct script access.\");\n"); + $expected = array("<?php defined(\"SYSPATH\") or die(\"No direct access allowed.\");\n"); + $expected_2 = array("<?php defined('SYSPATH') OR die('No direct access allowed.');\n"); + $expected_3 = array("<?php defined(\"SYSPATH\") or die(\"No direct script access.\");\n"); $fp = fopen($path, "r"); $actual = array(fgets($fp)); fclose($fp); @@ -131,7 +143,7 @@ class File_Structure_Test extends Unit_Test_Case { " */", ); } - if ($expected != $actual) { + if ($expected != $actual && $expected_2 != $actual && $expected_3 != $actual && $expected_4 != $actual) { $errors[] = "$path:1\n expected\n\t" . join("\n\t", $expected) . "\n actual:\n\t" . join("\n\t", $actual); } diff --git a/modules/gallery/tests/I18n_Test.php b/modules/gallery/tests/Gallery_I18n_Test.php index 9010606a..895e3051 100644 --- a/modules/gallery/tests/I18n_Test.php +++ b/modules/gallery/tests/Gallery_I18n_Test.php @@ -18,7 +18,7 @@ * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */ -class I18n_Test extends Unit_Test_Case { +class Gallery_I18n_Test extends Unit_Test_Case { private $i18n; public function setup() { @@ -26,10 +26,10 @@ class I18n_Test extends Unit_Test_Case { 'root_locale' => 'en', 'default_locale' => 'te_ST', 'locale_dir' => VARPATH . 'locale/'); - $this->i18n = I18n::instance($config); + $this->i18n = Gallery_I18n::instance($config); ORM::factory("incoming_translation") - ->where("locale", "te_ST") + ->where("locale", "=", "te_ST") ->delete_all(); $messages_te_ST = array( @@ -43,7 +43,7 @@ class I18n_Test extends Unit_Test_Case { foreach ($messages_te_ST as $data) { list ($message, $translation) = $data; $entry = ORM::factory("incoming_translation"); - $entry->key = I18n::get_message_key($message); + $entry->key = Gallery_I18n::get_message_key($message); $entry->message = serialize($message); $entry->translation = serialize($translation); $entry->locale = 'te_ST'; @@ -62,7 +62,7 @@ class I18n_Test extends Unit_Test_Case { $locale = $this->i18n->locale(); $this->assert_equal("de_DE", $locale); } - + public function translate_simple_test() { $result = $this->i18n->translate('Hello world'); $this->assert_equal('Hallo Welt', $result); diff --git a/modules/gallery/tests/Gallery_Installer_Test.php b/modules/gallery/tests/Gallery_Installer_Test.php index 36ced2bb..43399fb4 100644 --- a/modules/gallery/tests/Gallery_Installer_Test.php +++ b/modules/gallery/tests/Gallery_Installer_Test.php @@ -29,13 +29,13 @@ class Gallery_Installer_Test extends Unit_Test_Case { } public function install_registers_gallery_module_test() { - $gallery = ORM::factory("module")->where("name", "gallery")->find(); + $gallery = ORM::factory("module")->where("name", "=", "gallery")->find(); $this->assert_equal("gallery", $gallery->name); } public function install_creates_root_item_test() { $max_right_ptr = ORM::factory("item") - ->select("MAX(`right_ptr`) AS `right_ptr`") + ->select(new Database_Expression("MAX(`right_ptr`) AS `right_ptr`")) ->find()->right_ptr; $root = ORM::factory('item')->find(1); $this->assert_equal("Gallery", $root->title); diff --git a/modules/gallery/tests/Gallery_Rest_Helper_Test.php b/modules/gallery/tests/Gallery_Rest_Helper_Test.php new file mode 100644 index 00000000..cd0aabae --- /dev/null +++ b/modules/gallery/tests/Gallery_Rest_Helper_Test.php @@ -0,0 +1,277 @@ +<?php defined("SYSPATH") or die("No direct script access."); +/** + * Gallery - a web based photo album viewer and editor + * Copyright (C) 2000-2009 Bharat Mediratta + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or (at + * your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. + */ +class Gallery_Rest_Helper_Test extends Unit_Test_Case { + public function setup() { + $this->_save = array($_GET, $_POST, $_SERVER, $_FILES); + $this->_saved_active_user = identity::active_user(); + } + + public function teardown() { + list($_GET, $_POST, $_SERVER, $_FILES) = $this->_save; + identity::set_active_user($this->_saved_active_user); + if (!empty($this->_user)) { + try { + $this->_user->delete(); + } catch (Exception $e) { } + } + } + + private function _create_user() { + if (empty($this->_user)) { + $this->_user = identity::create_user("access_test" . rand(), "Access Test", "password"); + $key = ORM::factory("user_access_token"); + $key->access_key = md5($this->_user->name . rand()); + $key->user_id = $this->_user->id; + $key->save(); + identity::set_active_user($this->_user); + } + return $this->_user; + } + + private function _create_album($parent=null) { + $album_name = "rest_album_" . rand(); + if (empty($parent)) { + $parent = ORM::factory("item", 1); + } + return album::create($parent, $album_name, $album_name, $album_name); + } + + private function _create_image($parent=null) { + $filename = MODPATH . "gallery/tests/test.jpg"; + $image_name = "rest_image_" . rand(); + if (empty($parent)) { + $parent = ORM::factory("item", 1); + } + return photo::create($parent, $filename, "$image_name.jpg", $image_name); + } + + public function gallery_rest_get_album_test() { + $album = $this->_create_album(); + $child = $this->_create_album($album); + $photo = $this->_create_image($child); + $child->reload(); + $request = (object)array("arguments" => explode("/", $child->relative_url())); + + $this->assert_equal( + json_encode(array("status" => "OK", + "resource" => + array("type" => $child->type, + "name" => $child->name, + "path" => $child->relative_url(), + "parent_path" => $album->relative_url(), + "title" => $child->title, + "thumb_url" => $child->thumb_url(), + "thumb_size" => array("height" => $child->thumb_height, + "width" => $child->thumb_width), + "resize_url" => $child->resize_url(), + "resize_size" => array("height" => 0, + "width" => 0), + "url" => $child->file_url(), + "size" => array("height" => $child->height, + "width" => $child->width), + "description" => $child->description, + "slug" => $child->slug, + "children" => array(array( + "type" => "photo", + "has_children" => false, + "path" => $photo->relative_url(), + "thumb_url" => $photo->thumb_url(), + "thumb_dimensions" => array( + "width" => $photo->thumb_width, + "height" => $photo->thumb_height), + "has_thumb" => true, + "title" => $photo->title))))), + gallery_rest::get($request)); + } + + public function gallery_rest_get_photo_test() { + $child = $this->_create_album(); + $photo = $this->_create_image($child); + $request = (object)array("arguments" => explode("/", $photo->relative_url())); + + $this->assert_equal( + json_encode(array("status" => "OK", + "resource" => + array("type" => $photo->type, + "name" => $photo->name, + "path" => $photo->relative_url(), + "parent_path" => $child->relative_url(), + "title" => $photo->title, + "thumb_url" => $photo->thumb_url(), + "thumb_size" => array("height" => $photo->thumb_height, + "width" => $photo->thumb_width), + "resize_url" => $photo->resize_url(), + "resize_size" => array("height" => $photo->resize_height, + "width" => $photo->resize_width), + "url" => $photo->file_url(), + "size" => array("height" => $photo->height, + "width" => $photo->width), + "description" => $photo->description, + "slug" => $photo->slug))), + gallery_rest::get($request)); + } + + public function gallery_rest_put_album_no_path_test() { + $request = (object)array("description" => "Updated description", + "title" => "Updated Title", + "name" => "new name"); + + try { + gallery_rest::put($request); + } catch (Rest_Exception $e) { + $this->assert_equal("400 Bad request", $e->getMessage()); + } catch (Exception $e) { + $this->assert_false(true, $e->__toString()); + } + } + + public function gallery_rest_put_album_not_found_test() { + $photo = $this->_create_image(); + $request = (object)array("arguments" => explode("/", $photo->relative_url() . rand()), + "description" => "Updated description", + "title" => "Updated Title", + "name" => "new name"); + + try { + gallery_rest::put($request); + } catch (Kohana_404_Exception $k404) { + } catch (Exception $e) { + $this->assert_false(true, $e->__toString()); + } + } + + public function gallery_rest_put_album_no_edit_permission_test() { + $child = $this->_create_album(); + $this->_create_user(); + $request = (object)array("arguments" => explode("/", $child->relative_url()), + "description" => "Updated description", + "title" => "Updated Title", + "name" => "new name"); + + try { + gallery_rest::put($request); + } catch (Kohana_404_Exception $k404) { + } catch (Exception $e) { + $this->assert_false(true, $e->__toString()); + } + } + + public function gallery_rest_put_album_rename_conflict_test() { + $child = $this->_create_album(); + $sibling = $this->_create_image(); + $this->_create_user(); + access::allow(identity::registered_users(), "edit", $child); + $request = (object)array("arguments" => explode("/", $child->relative_url()), + "description" => "Updated description", + "title" => "Updated Title", + "name" => $sibling->name); + + $this->assert_equal( + json_encode(array("status" => "VALIDATE_ERROR", + "fields" => array("slug" => "Duplicate Internet address"))), + gallery_rest::put($request)); + } + + public function gallery_rest_put_album_test() { + $child = $this->_create_album(); + $sibling = $this->_create_image(); + $this->_create_user(); + access::allow(identity::registered_users(), "edit", $child); + + $new_name = "new_album_name" . rand(); + $request = (object)array("arguments" => explode("/", $child->relative_url()), + "description" => "Updated description", + "title" => "Updated Title", + "name" => $new_name); + + $this->assert_equal(json_encode(array("status" => "OK")), gallery_rest::put($request)); + $child->reload(); + $this->assert_equal("Updated description", $child->description); + $this->assert_equal("Updated Title", $child->title); + $this->assert_equal($new_name, $child->name); + } + + public function gallery_rest_put_photo_test() { + $child = $this->_create_album(); + $photo = $this->_create_image($child); + $this->_create_user(); + access::allow(identity::registered_users(), "edit", $child); + + $request = (object)array("arguments" => explode("/", $photo->relative_url()), + "description" => "Updated description", + "title" => "Updated Title", + "name" => "new name"); + + $this->assert_equal(json_encode(array("status" => "OK")), gallery_rest::put($request)); + $photo->reload(); + $this->assert_equal("Updated description", $photo->description); + $this->assert_equal("Updated Title", $photo->title); + $this->assert_equal("new name", $photo->name); + } + + public function gallery_rest_delete_album_test() { + $album = $this->_create_album(); + $child = $this->_create_album($album); + $this->_create_user(); + access::allow(identity::registered_users(), "edit", $album); + + $request = (object)array("arguments" => explode("/", $child->relative_url())); + + $this->assert_equal(json_encode(array("status" => "OK", + "resource" => array( + "parent_path" => $album->relative_url()))), + gallery_rest::delete($request)); + $child->reload(); + $this->assert_false($child->loaded()); + } + + public function gallery_rest_delete_photo_test() { + $album = $this->_create_album(); + $photo = $this->_create_image($album); + $this->_create_user(); + access::allow(identity::registered_users(), "edit", $album); + + $request = (object)array("arguments" => explode("/", $photo->relative_url())); + + $this->assert_equal(json_encode(array("status" => "OK", + "resource" => array( + "parent_path" => $album->relative_url()))), + gallery_rest::delete($request)); + $photo->reload(); + $this->assert_false($photo->loaded()); + } + + public function gallery_rest_post_album_test() { + $album = $this->_create_album(); + $this->_create_user(); + access::allow(identity::registered_users(), "edit", $album); + + $new_path = $album->relative_url() . "/new%20child"; + $request = (object)array("arguments" => explode("/", $new_path)); + + $this->assert_equal(json_encode(array("status" => "OK", "path" => $new_path)), + gallery_rest::post($request)); + $album = ORM::factory("item") + ->where("relative_url_cache", "=", $new_path) + ->find(); + $this->assert_true($album->loaded()); + $this->assert_equal("new child", $album->slug); + } +} diff --git a/modules/gallery/tests/Item_Helper_Test.php b/modules/gallery/tests/Item_Helper_Test.php index a364423a..f0c653c0 100644 --- a/modules/gallery/tests/Item_Helper_Test.php +++ b/modules/gallery/tests/Item_Helper_Test.php @@ -29,13 +29,13 @@ class Item_Helper_Test extends Unit_Test_Case { access::allow(identity::everybody(), "view", $album); $this->assert_equal( 1, - ORM::factory("item")->viewable()->where("id", $item->id)->count_all()); + ORM::factory("item")->viewable()->where("id", "=", $item->id)->count_all()); // We can't see the item when permissions are denied access::deny(identity::everybody(), "view", $album); $this->assert_equal( 0, - ORM::factory("item")->viewable()->where("id", $item->id)->count_all()); + ORM::factory("item")->viewable()->where("id", "=", $item->id)->count_all()); } public function validate_url_safe_test() { diff --git a/modules/gallery/tests/Item_Model_Test.php b/modules/gallery/tests/Item_Model_Test.php index e7dce893..bf5fca1a 100644 --- a/modules/gallery/tests/Item_Model_Test.php +++ b/modules/gallery/tests/Item_Model_Test.php @@ -35,8 +35,12 @@ class Item_Model_Test extends Unit_Test_Case { $item = self::_create_random_item(); // Force the creation date to something well known - $db = Database::instance(); - $db->update("items", array("created" => 0, "updated" => 0), array("id" => $item->id)); + db::build() + ->update("items") + ->set("created", 0) + ->set("updated", 0) + ->where("id", "=", $item->id) + ->execute(); $item->reload(); $item->title = "foo"; // force a change $item->save(); @@ -51,8 +55,11 @@ class Item_Model_Test extends Unit_Test_Case { $this->assert_same(0, $item->view_count); // Force the updated date to something well known - $db = Database::instance(); - $db->update("items", array("updated" => 0), array("id" => $item->id)); + db::build() + ->update("items") + ->set("updated", 0) + ->where("id", "=", $item->id) + ->execute(); $item->reload(); $item->view_count++; $item->save(); diff --git a/modules/gallery/tests/ORM_MPTT_Test.php b/modules/gallery/tests/ORM_MPTT_Test.php index a749542b..69b6bea9 100644 --- a/modules/gallery/tests/ORM_MPTT_Test.php +++ b/modules/gallery/tests/ORM_MPTT_Test.php @@ -190,8 +190,8 @@ class ORM_MPTT_Test extends Unit_Test_Case { $parent->reload(); $this->assert_equal(3, $parent->descendants()->count()); - $this->assert_equal(2, $parent->descendants(null, 0, array("type" => "photo"))->count()); - $this->assert_equal(1, $parent->descendants(null, 0, array("type" => "album"))->count()); + $this->assert_equal(2, $parent->descendants(null, null, array(array("type", "=", "photo")))->count()); + $this->assert_equal(1, $parent->descendants(null, null, array(array("type", "=", "album")))->count()); } public function descendant_limit_test() { @@ -228,7 +228,7 @@ class ORM_MPTT_Test extends Unit_Test_Case { $parent->reload(); $this->assert_equal(3, $parent->descendants_count()); - $this->assert_equal(2, $parent->descendants_count(array("type" => "photo"))); - $this->assert_equal(1, $parent->descendants_count(array("type" => "album"))); + $this->assert_equal(2, $parent->descendants_count(array(array("type", "=", "photo")))); + $this->assert_equal(1, $parent->descendants_count(array(array("type", "=", "album")))); } } diff --git a/modules/gallery/tests/Photo_Helper_Test.php b/modules/gallery/tests/Photo_Helper_Test.php index da455bf8..97923f90 100644 --- a/modules/gallery/tests/Photo_Helper_Test.php +++ b/modules/gallery/tests/Photo_Helper_Test.php @@ -78,7 +78,18 @@ class Photo_Helper_Test extends Unit_Test_Case { $album = album::create($root, $rand, $rand, $rand); $photo = photo::create($album, MODPATH . "gallery/tests/test.jpg", "$rand.jpg", $rand, $rand); - $this->assert_equal("http://./var/resizes/{$rand}/{$rand}.jpg", $photo->resize_url()); + $this->assert_equal( + "http://./var/resizes/{$rand}/{$rand}.jpg?m={$photo->updated}", $photo->resize_url()); + } + + public function file_url_test() { + $rand = rand(); + $root = ORM::factory("item", 1); + $album = album::create($root, $rand, $rand, $rand); + $photo = photo::create($album, MODPATH . "gallery/tests/test.jpg", "$rand.jpg", $rand, $rand); + + $this->assert_equal( + "http://./var/albums/{$rand}/{$rand}.jpg?m={$photo->updated}", $photo->file_url()); } public function create_photo_creates_reasonable_slug_test() { diff --git a/modules/gallery/tests/Photos_Controller_Test.php b/modules/gallery/tests/Photos_Controller_Test.php index fa4f101a..b6c6df47 100644 --- a/modules/gallery/tests/Photos_Controller_Test.php +++ b/modules/gallery/tests/Photos_Controller_Test.php @@ -49,8 +49,7 @@ class Photos_Controller_Test extends Unit_Test_Case { $results = ob_get_contents(); ob_end_clean(); - $this->assert_equal( - json_encode(array("result" => "success", "location" => "HTTP_REFERER")), $results); + $this->assert_equal(json_encode(array("result" => "success")), $results); $this->assert_equal("new-slug", $photo->slug); $this->assert_equal("new title", $photo->title); $this->assert_equal("new description", $photo->description); diff --git a/modules/gallery/tests/Sendmail_Test.php b/modules/gallery/tests/Sendmail_Test.php index 64c1fff0..f3a8d897 100644 --- a/modules/gallery/tests/Sendmail_Test.php +++ b/modules/gallery/tests/Sendmail_Test.php @@ -19,9 +19,7 @@ */ class Sendmail_Test extends Unit_Test_Case { public function setup() { - $config = Kohana::config("sendmail"); - $config["from"] = "from@gallery3.com"; - Kohana::config_set("sendmail", $config); + Kohana_Config::instance()->set("sendmail.from", "from@gallery3.com"); } public function sendmail_test() { diff --git a/modules/gallery/tests/controller_auth_data.txt b/modules/gallery/tests/controller_auth_data.txt index 1fe29ffb..c1fffe6a 100644 --- a/modules/gallery/tests/controller_auth_data.txt +++ b/modules/gallery/tests/controller_auth_data.txt @@ -2,8 +2,10 @@ modules/comment/controllers/admin_comments.php queue modules/comment/helpers/comment_rss.php feed DIRTY_AUTH modules/digibug/controllers/digibug.php print_proxy DIRTY_CSRF|DIRTY_AUTH modules/digibug/controllers/digibug.php close_window DIRTY_AUTH +modules/g2_import/controllers/g2.php map DIRTY_CSRF modules/gallery/controllers/admin.php __call DIRTY_AUTH -modules/gallery/controllers/albums.php _show DIRTY_CSRF +modules/gallery/controllers/albums.php index DIRTY_AUTH +modules/gallery/controllers/albums.php show DIRTY_CSRF modules/gallery/controllers/combined.php javascript DIRTY_AUTH modules/gallery/controllers/combined.php css DIRTY_AUTH modules/gallery/controllers/file_proxy.php __call DIRTY_CSRF|DIRTY_AUTH @@ -13,10 +15,13 @@ modules/gallery/controllers/login.php html modules/gallery/controllers/login.php auth_html DIRTY_AUTH modules/gallery/controllers/logout.php index DIRTY_CSRF|DIRTY_AUTH modules/gallery/controllers/maintenance.php index DIRTY_AUTH +modules/gallery/controllers/quick.php form_edit DIRTY_CSRF modules/gallery/controllers/simple_uploader.php start DIRTY_AUTH modules/gallery/controllers/simple_uploader.php finish DIRTY_AUTH modules/gallery/controllers/upgrader.php index DIRTY_AUTH modules/gallery/controllers/welcome_message.php index DIRTY_AUTH +modules/rest/controllers/rest.php access_key DIRTY_CSRF|DIRTY_AUTH +modules/rest/controllers/rest.php __call DIRTY_AUTH modules/rss/controllers/rss.php feed DIRTY_CSRF|DIRTY_AUTH modules/search/controllers/search.php index DIRTY_CSRF|DIRTY_AUTH modules/server_add/controllers/admin_server_add.php autocomplete DIRTY_CSRF diff --git a/modules/gallery/tests/xss_data.txt b/modules/gallery/tests/xss_data.txt index 3708bc6d..a264286c 100644 --- a/modules/gallery/tests/xss_data.txt +++ b/modules/gallery/tests/xss_data.txt @@ -39,7 +39,7 @@ modules/digibug/views/digibug_form.html.php 5 DIRTY form:: modules/digibug/views/digibug_form.html.php 6 DIRTY form::close() modules/exif/views/exif_dialog.html.php 14 DIRTY $details[$i]["caption"] modules/exif/views/exif_dialog.html.php 21 DIRTY $details[$i]["caption"] -modules/g2_import/views/admin_g2_import.html.php 29 DIRTY $form +modules/g2_import/views/admin_g2_import.html.php 30 DIRTY $form modules/gallery/views/admin_advanced_settings.html.php 21 DIRTY_ATTR text::alternate("g-odd","g-even") modules/gallery/views/admin_advanced_settings.html.php 22 DIRTY $var->module_name modules/gallery/views/admin_block_log_entries.html.php 4 DIRTY_ATTR log::severity_class($entry->severity) @@ -118,10 +118,11 @@ modules/gallery/views/admin_themes.html.php 62 DIRTY $theme modules/gallery/views/admin_themes.html.php 76 DIRTY $info->name modules/gallery/views/admin_themes.html.php 78 DIRTY $info->description modules/gallery/views/admin_themes_preview.html.php 7 DIRTY_ATTR $url -modules/gallery/views/form_uploadify.html.php 20 DIRTY_JS url::file("lib/uploadify/uploadify.swf") -modules/gallery/views/form_uploadify.html.php 21 DIRTY_JS url::site("simple_uploader/add_photo/{$album->id}") -modules/gallery/views/form_uploadify.html.php 25 DIRTY_JS url::file("lib/uploadify/cancel.png") -modules/gallery/views/form_uploadify.html.php 52 DIRTY_JS t("Completed") +modules/gallery/views/form_uploadify.html.php 24 DIRTY_JS url::file("lib/uploadify/uploadify.swf") +modules/gallery/views/form_uploadify.html.php 25 DIRTY_JS url::site("simple_uploader/add_photo/{$album->id}") +modules/gallery/views/form_uploadify.html.php 29 DIRTY_JS url::file("lib/uploadify/cancel.png") +modules/gallery/views/form_uploadify.html.php 30 DIRTY_JS $simultaneous_upload_limit +modules/gallery/views/form_uploadify.html.php 55 DIRTY_JS t("Completed") modules/gallery/views/in_place_edit.html.php 2 DIRTY form::open($action,array("method"=>"post","id"=>"g-in-place-edit-form","class"=>"g-short-form"),$hidden) modules/gallery/views/in_place_edit.html.php 5 DIRTY form::input("input",$form["input"]," class=\"textbox\"") modules/gallery/views/in_place_edit.html.php 12 DIRTY form::close() @@ -244,7 +245,7 @@ modules/organize/views/organize_thumb_grid.html.php 7 DIRTY $child modules/organize/views/organize_thumb_grid.html.php 15 DIRTY_JS url::site("organize/album/$album->id/".($offset+25)) modules/organize/views/organize_tree.html.php 2 DIRTY_ATTR access::can("edit",$album)?"":"g-view-only" modules/organize/views/organize_tree.html.php 3 DIRTY_ATTR $album->id -modules/organize/views/organize_tree.html.php 6 DIRTY_ATTR $selected&&$album->id==$selected->id?"selected":"" +modules/organize/views/organize_tree.html.php 6 DIRTY_ATTR $selected&&$album->id==$selected->id?"ui-state-focus":"" modules/organize/views/organize_tree.html.php 7 DIRTY_ATTR $album->id modules/organize/views/organize_tree.html.php 13 DIRTY View::factory("organize_tree.html",array("selected"=>$selected,"album"=>$child)); modules/organize/views/organize_tree.html.php 15 DIRTY_ATTR access::can("edit",$child)?"":"g-view-only" @@ -274,11 +275,11 @@ modules/rss/views/feed.mrss.php 55 DIRTY_ATTR @fil modules/rss/views/feed.mrss.php 56 DIRTY_ATTR $child->mime_type modules/rss/views/feed.mrss.php 57 DIRTY_ATTR $child->resize_height modules/rss/views/feed.mrss.php 58 DIRTY_ATTR $child->resize_width -modules/rss/views/feed.mrss.php 62 DIRTY_ATTR $child->file_url(true) -modules/rss/views/feed.mrss.php 63 DIRTY_ATTR @filesize($child->file_path()) -modules/rss/views/feed.mrss.php 64 DIRTY_ATTR $child->mime_type -modules/rss/views/feed.mrss.php 65 DIRTY_ATTR $child->height -modules/rss/views/feed.mrss.php 66 DIRTY_ATTR $child->width +modules/rss/views/feed.mrss.php 61 DIRTY_ATTR $child->file_url(true) +modules/rss/views/feed.mrss.php 62 DIRTY_ATTR @filesize($child->file_path()) +modules/rss/views/feed.mrss.php 63 DIRTY_ATTR $child->mime_type +modules/rss/views/feed.mrss.php 64 DIRTY_ATTR $child->height +modules/rss/views/feed.mrss.php 65 DIRTY_ATTR $child->width modules/rss/views/feed.mrss.php 70 DIRTY_ATTR $child->file_url(true) modules/rss/views/feed.mrss.php 71 DIRTY_ATTR @filesize($child->file_path()) modules/rss/views/feed.mrss.php 72 DIRTY_ATTR $child->height diff --git a/modules/gallery/views/admin_advanced_settings.html.php b/modules/gallery/views/admin_advanced_settings.html.php index ff4843ab..2d4b11a1 100644 --- a/modules/gallery/views/admin_advanced_settings.html.php +++ b/modules/gallery/views/admin_advanced_settings.html.php @@ -25,7 +25,7 @@ <a href="<?= url::site("admin/advanced_settings/edit/$var->module_name/" . html::clean($var->name)) ?>" class="g-dialog-link" title="<?= t("Edit %var (%module_name)", array("var" => $var->name, "module_name" => $var->module_name))->for_html_attr() ?>"> - <? if ($var->value): ?> + <? if (isset($var->value)): ?> <?= html::clean($var->value) ?> <? else: ?> <i> <?= t("empty") ?> </i> diff --git a/modules/gallery/views/form_uploadify.html.php b/modules/gallery/views/form_uploadify.html.php index d856c464..f3b9c883 100644 --- a/modules/gallery/views/form_uploadify.html.php +++ b/modules/gallery/views/form_uploadify.html.php @@ -1,15 +1,19 @@ <?php defined("SYSPATH") or die("No direct script access.") ?> <style> #g-add-photos-canvas object { - left: -50px; + height: 33px; + left: -60px; position: relative; z-index: 100; } #g-add-photos-button { - left: 55px; + float: left; + left: 175px; + padding-bottom: .5em; + padding-top: .5em; position: relative; - top: -15px; - z-index: -1; + width: 110px; + z-index: 1; } </style> <script type="text/javascript" src="<?= url::file("lib/swfobject.js") ?>"></script> @@ -23,7 +27,6 @@ fileExt: "*.gif;*.jpg;*.jpeg;*.png;*.flv;*.mp4;*.GIF;*.JPG;*.JPEG;*.PNG;*.FLV;*.MP4", fileDesc: <?= t("Photos and movies")->for_js() ?>, cancelImg: "<?= url::file("lib/uploadify/cancel.png") ?>", - buttonText: <?= t("Select photos...")->for_js() ?>, simUploadLimit: <?= $simultaneous_upload_limit ?>, wmode: "transparent", hideButton: true, /* should be true */ @@ -77,7 +80,6 @@ $("#g-add-photos-status ul").append( "<li class=\"g-error\">" + fileObj.name + msg + "</li>"); $("#g-uploadify" + queueID).remove(); - //return false; }, onSelect: function(event) { if ($("#g-upload-cancel-all").hasClass("ui-state-disabled")) { @@ -113,8 +115,8 @@ </ul> </div> -<div id="g-add-photos-canvas" style="text-align: center;"> - <a id="g-add-photos-button" class="ui-corner-all" style="padding-bottom: 1em;" href="#"><?= t("Select photos...") ?></a> +<div id="g-add-photos-canvas" style="text-align: center;clear: both"> + <a id="g-add-photos-button" class="ui-corner-all" href="#"><?= t("Select photos...") ?></a> <span id="g-uploadify"></span> </div> <div id="g-add-photos-status" style="text-align: center;"> diff --git a/modules/gallery/views/kohana/error.php b/modules/gallery/views/kohana/error.php new file mode 100644 index 00000000..7271db14 --- /dev/null +++ b/modules/gallery/views/kohana/error.php @@ -0,0 +1,279 @@ +<?php defined("SYSPATH") or die("No direct script access.") ?> +<? $error_id = uniqid("error") ?> +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> + <head> + <style type="text/css"> + body { + background: #fff; + font-size: 14px; + line-height: 130%; + } + + div.big_box { + padding: 10px; + background: #eee; + border: solid 1px #ccc; + font-family: sans-serif; + color: #111; + width: 60em; + margin: 20px auto; + } + + div#framework_error { + text-align: center; + } + + div#error_details { + text-align: left; + } + + code { + font-family: monospace; + font-size: 12px; + margin: 20px 20px 20px 0px; + color: #333; + white-space: pre-wrap; + white-space: -moz-pre-wrap; + word-wrap: break-word; + } + + code .line { + padding-left: 10px; + } + + h3 { + font-family: sans-serif; + margin: 2px 0px 0px 0px; + padding: 8px 0px 0px 0px; + border-top: 1px solid #ddd; + } + + p { + padding: 0px; + margin: 0px 0px 10px 0px; + } + + li, pre { + padding: 0px; + margin: 0px; + } + + .collapsed { + display: none; + } + + .highlight { + font-weight: bold; + color: darkred; + } + + #kohana_error .message { + display: block; + padding-bottom: 10px; + } + + .source { + border: solid 1px #ccc; + background: #efe; + margin-bottom: 5px; + } + + table { + width: 100%; + display: block; + margin: 0 0 0.4em; + padding: 0; + border-collapse: collapse; + background: #efe; + } + + table td { + border: solid 1px #ddd; + text-align: left; + vertical-align: top; + padding: 0.4em; + } + + .args table td.key { + width: 200px; + } + + .number { + padding-right: 1em; + } + </style> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> + <title><?= t("Something went wrong!") ?></title> + + <script type="text/javascript"> + function koggle(elem) { + elem = document.getElementById(elem); + if (elem.style && elem.style["display"]) { + // Only works with the "style" attr + var disp = elem.style["display"]; + } else { + if (elem.currentStyle) { + // For MSIE, naturally + var disp = elem.currentStyle["display"]; + } else { + if (window.getComputedStyle) { + // For most other browsers + var disp = document.defaultView.getComputedStyle(elem, null).getPropertyValue('display'); + } + } + } + + // Toggle the state of the "display" style + elem.style.display = disp == 'block' ? 'none' : 'block'; + return false; + } + </script> + </head> + <body> + <? try { $user = identity::active_user(); } catch (Exception $e) { } ?> + <? $admin = php_sapi_name() == "cli" || isset($user) && $user->admin ?> + <div class="big_box" id="framework_error"> + <h1> + <?= t("Dang... Something went wrong!") ?> + </h1> + <h2> + <?= t("We tried really hard, but it's broken.") ?> + </h2> + <? if (!$admin): ?> + <p> + <?= t("Talk to your Gallery administrator for help fixing this!") ?> + </p> + <? endif ?> + </div> + <? if ($admin): ?> + <div class="big_box" id="error_details"> + <h2> + <?= t("Hey wait, you're an admin! We can tell you stuff.") ?> + </h2> + <div id="kohana_error"> + <h3> + <span class="type"> + <?= $type?> [ <?= $code ?> ]: + </span> + <span class="message"> + <?= $message?> + </span> + </h3> + <div id="<?= $error_id ?>" class="content"> + <ol class="trace"> + <li class="snippet"> + <p> + <span class="file"> + <?= Kohana_Exception::debug_path($file)?>[ <?= $line?> ] + </span> + </p> + + <div class="source"> + <? if (Kohana_Exception::$source_output and $source_code = Kohana_Exception::debug_source($file, $line)): ?><code><? foreach ($source_code as $num => $row): ?><span class="line <?= ($num == $line) ? "highlight" : ""?>"><span class="number"><?= $num ?></span><?= htmlspecialchars($row, ENT_NOQUOTES, Kohana::CHARSET) ?></span><? endforeach ?></code> + <? endif ?> + </div> + </li> + + <? if (Kohana_Exception::$trace_output): ?> + <? foreach (Kohana_Exception::trace($trace) as $i => $step): ?> + <li class="snippet"> + <p> + <span class="file"> + <? if ($step["file"]): $source_id = "$error_id.source.$i" ?> + <? if (Kohana_Exception::$source_output and $step["source"]): ?> + <a href="#<?= $source_id ?>" onclick="return koggle('<?= $source_id ?>')"><?= Kohana_Exception::debug_path($step["file"])?>[ <?= $step["line"]?> ]</a> + <? else: ?> + <span class="file"><?= Kohana_Exception::debug_path($step["file"])?>[ <?= $step["line"]?> ]</span> + <? endif ?> + <? else: ?> + {<?= t("PHP internal call")?>} + <? endif?> + </span> + » + <?= $step["function"]?>(<? if ($step["args"]): $args_id = "$error_id.args.$i" ?> + <a href="#<?= $args_id ?>" onclick="return koggle('<?= $args_id ?>')"><?= t("arguments")?></a> + <? endif?>) + </p> + <? if (isset($args_id)): ?> + <div id="<?= $args_id ?>" class="args collapsed"> + <table cellspacing="0"> + <? foreach ($step["args"] as $name => $arg): ?> + <tr> + <td class="key"> + <pre><?= $name?></pre> + </td> + <td class="value"> + <pre><?= Kohana_Exception::dump($arg) ?></pre> + </td> + </tr> + <? endforeach?> + </table> + </div> + <? endif?> + <? if (Kohana_Exception::$source_output and $step["source"] and isset($source_id)): ?> + <pre id="<?= $source_id ?>" class="source collapsed"><code><? foreach ($step["source"] as $num => $row): ?><span class="line <?= ($num == $step["line"]) ? "highlight" : "" ?>"><span class="number"><?= $num ?></span><?= htmlspecialchars($row, ENT_NOQUOTES, Kohana::CHARSET) ?></span><? endforeach ?></code></pre> + <? endif?> + </li> + <? unset($args_id, $source_id) ?> + <? endforeach?> + </ol> + <? endif ?> + + </div> + <h2> + <a href="#<?= $env_id = $error_id."environment" ?>" onclick="return koggle('<?= $env_id ?>')"><?= t("Environment")?></a> + </h2> + <div id="<?= $env_id ?>" class="content collapsed"> + <? $included = get_included_files()?> + <h3><a href="#<?= $env_id = $error_id."environment_included" ?>" onclick="return koggle('<?= $env_id ?>')"><?= t("Included files")?></a>(<?= count($included)?>)</h3> + <div id="<?= $env_id ?>" class="collapsed"> + <table cellspacing="0"> + <? foreach ($included as $file): ?> + <tr> + <td> + <pre><?= Kohana_Exception::debug_path($file)?></pre> + </td> + </tr> + <? endforeach?> + </table> + </div> + <? $included = get_loaded_extensions()?> + <h3><a href="#<?= $env_id = $error_id."environment_loaded" ?>" onclick="return koggle('<?= $env_id ?>')"><?= t("Loaded extensions")?></a>(<?= count($included)?>)</h3> + <div id="<?= $env_id ?>" class="collapsed"> + <table cellspacing="0"> + <? foreach ($included as $file): ?> + <tr> + <td> + <pre><?= Kohana_Exception::debug_path($file)?></pre> + </td> + </tr> + <? endforeach?> + </table> + </div> + <? foreach (array("_SESSION", "_GET", "_POST", "_FILES", "_COOKIE", "_SERVER") as $var): ?> + <? if ( empty($GLOBALS[$var]) OR ! is_array($GLOBALS[$var])) continue ?> + <h3><a href="#<?= $env_id = "$error_id.environment" . strtolower($var) ?>" + onclick="return koggle('<?= $env_id ?>')">$<?= $var?></a></h3> + <div id="<?= $env_id ?>" class="collapsed"> + <table cellspacing="0"> + <? foreach ($GLOBALS[$var] as $key => $value): ?> + <tr> + <td class="key"> + <code> + <?= $key?> + </code> + </td> + <td class="value"> + <pre><?= Kohana_Exception::dump($value) ?></pre> + </td> + </tr> + <? endforeach?> + </table> + </div> + <? endforeach?> + </div> + </div> + </div> + <? endif ?> + </body> +</html> diff --git a/modules/gallery/views/kohana_error_page.php b/modules/gallery/views/kohana_error_page.php index 0d8801e5..b9fdcc19 100644 --- a/modules/gallery/views/kohana_error_page.php +++ b/modules/gallery/views/kohana_error_page.php @@ -120,7 +120,7 @@ <? else: ?> <? $trace = $PHP_ERROR ? array_slice(debug_backtrace(), 1) : $exception->getTraceAsString(); ?> <? if (!empty($trace)): ?> - <? Kohana::Log("error", print_r($trace, 1)); ?> + <? Kohana_Log::add("error", print_r($trace, 1)); ?> <? endif ?> <? endif ?> </body> |