function add_albums_and_photos($count, $desired_type = null) { srand(time()); $parents = ORM::factory("item")->where("type", "album")->find_all()->as_array(); $owner_id = user::active()->id; $test_images = glob(MODPATH . "gallery/tests/images/*.[Jj][Pp][Gg]"); batch::start(); $album_count = $photo_count = 0; for ($i = 0; $i < $count; $i++) { set_time_limit(30); $parent = $parents[array_rand($parents)]; $parent->reload(); $type = $desired_type; if (!$type) { $type = rand(0, 10) ? "photo" : "album"; } if ($type == "album") { $thumb_size = module::get_var("gallery", "thumb_size"); $parents[] = album::create($parent, "rnd_" . rand(), "Rnd {$i}", "random album {$i}", $owner_id)->save(); $album_count++; } else { $photo_index = rand(0, count($test_images) - 1); photo::create($parent, $test_images[$photo_index], basename($test_images[$photo_index]), "rnd_" . rand(), "sample thumb", $owner_id); $photo_count++; } } batch::stop(); if ($photo_count > 0) { log::success("content", "(scaffold) Added {$photo_count} photos"); } if ($album_count > 0) { log::success("content", "(scaffold) Added {$album_count} albums"); } url::redirect("scaffold"); }
private static function _create_random_item($root = null, $rand = null) { $root = $root ? $root : ORM::factory("item", 1); $rand = $rand ? $rand : rand(); $item = photo::create($root, MODPATH . "gallery/tests/test.jpg", "{$rand}.jpg", $rand, $rand); return $item; }
public function add_photo($id) { $album = ORM::factory("item", $id); access::required("view", $album); access::required("add", $album); access::verify_csrf(); $file_validation = new Validation($_FILES); $file_validation->add_rules("Filedata", "upload::valid", "upload::type[gif,jpg,png,flv,mp4]"); if ($file_validation->validate()) { // SimpleUploader.swf does not yet call /start directly, so simulate it here for now. if (!batch::in_progress()) { batch::start(); } $temp_filename = upload::save("Filedata"); try { $name = substr(basename($temp_filename), 10); // Skip unique identifier Kohana adds $title = item::convert_filename_to_title($name); $path_info = pathinfo($temp_filename); if (array_key_exists("extension", $path_info) && in_array(strtolower($path_info["extension"]), array("flv", "mp4"))) { $movie = movie::create($album, $temp_filename, $name, $title); log::success("content", t("Added a movie"), html::anchor("movies/{$movie->id}", t("view movie"))); } else { $photo = photo::create($album, $temp_filename, $name, $title); log::success("content", t("Added a photo"), html::anchor("photos/{$photo->id}", t("view photo"))); } } catch (Exception $e) { unlink($temp_filename); throw $e; } unlink($temp_filename); } print "File Received"; }
public function exif_extract_test() { $rand = rand(); $root = ORM::factory("item", 1); $photo = photo::create($root, MODPATH . "exif/tests/data/image.jpg", "{$rand}.jpg", $rand, $rand); $expected = array(array("caption" => "Camera Maker", "value" => "Pentax Corporation"), array("caption" => "Camera Model", "value" => "PENTAX K10D"), array("caption" => "Aperture", "value" => "f/2.8"), array("caption" => "Color Space", "value" => "Uncalibrated"), array("caption" => "Exposure Value", "value" => "4294.67 EV"), array("caption" => "Exposure Program", "value" => "Program"), array("caption" => "Exposure Time", "value" => "1/60 sec"), array("caption" => "Flash", "value" => "No Flash"), array("caption" => "Focal Length", "value" => "50 mm"), array("caption" => "ISO", "value" => "6553700"), array("caption" => "Metering Mode", "value" => "Multi-Segment"), array("caption" => "Date/Time", "value" => "2008:03:17 17:41:25"), array("caption" => "Copyright", "value" => "(C) 2008 - T. Almdal"), array("caption" => "Orientation", "value" => "1: Normal (0 deg)"), array("caption" => "Resolution Unit", "value" => "Inch"), array("caption" => "X Resolution", "value" => "240 dots per ResolutionUnit"), array("caption" => "Y Resolution", "value" => "240 dots per ResolutionUnit"), array("caption" => "Brightness Value", "value" => "0"), array("caption" => "Scene Type", "value" => "0"), array("caption" => "Subject Distance", "value" => "0")); $this->assert_equal($expected, exif::get($photo)); }
static function add_from_server($task) { $context = unserialize($task->context); try { $paths = array_keys(unserialize(module::get_var("server_add", "authorized_paths"))); $path = $paths[$context["next_path"]]; if (!empty($context["files"][$path])) { $file = $context["files"][$path][$context["position"]]; $parent = ORM::factory("item", $file["parent_id"]); access::required("server_add", $parent); access::required("add", $parent); if (!$parent->is_album()) { throw new Exception("@todo BAD_ALBUM"); } $name = $file["name"]; if ($file["type"] == "album") { $album = ORM::factory("item")->where("name", $name)->where("parent_id", $parent->id)->find(); if (!$album->loaded) { $album = album::create($parent, $name, $name, null, user::active()->id); } // Now that we have a new album. Go through the remaining files to import and change the // parent_id of any file that has the same relative path as this album's path. $album_path = "{$file['path']}/{$name}"; for ($idx = $context["position"] + 1; $idx < count($context["files"][$path]); $idx++) { if (strpos($context["files"][$path][$idx]["path"], $album_path) === 0) { $context["files"][$path][$idx]["parent_id"] = $album->id; } } } else { $extension = strtolower(substr(strrchr($name, '.'), 1)); $source_path = "{$path}{$file['path']}/{$name}"; if (in_array($extension, array("flv", "mp4"))) { $movie = movie::create($parent, $source_path, $name, $name, null, user::active()->id); } else { $photo = photo::create($parent, $source_path, $name, $name, null, user::active()->id); } } $context["counter"]++; if (++$context["position"] >= count($context["files"][$path])) { $context["next_path"]++; $context["position"] = 0; } } else { $context["next_path"]++; } } catch (Exception $e) { $context["errors"][$path] = $e->getMessage(); } $task->context = serialize($context); $task->state = "success"; $task->percent_complete = $context["counter"] / (double) $context["total"] * 100; $task->done = $context["counter"] == (double) $context["total"]; }
public function setup() { $this->_server = $_SERVER; $root = ORM::factory("item", 1); $this->_album = album::create($root, rand(), "test album"); access::deny(identity::everybody(), "view_full", $this->_album); access::deny(identity::registered_users(), "view_full", $this->_album); $rand = rand(); $this->_item = photo::create($this->_album, MODPATH . "gallery/tests/test.jpg", "{$rand}.jpg", $rand, $rand); $this->_proxy = ORM::factory("digibug_proxy"); $this->_proxy->uuid = md5(rand()); $this->_proxy->item_id = $this->_item->id; $this->_proxy->save(); }
public function add_photo($id) { $album = ORM::factory("item", $id); access::required("view", $album); access::required("add", $album); access::verify_csrf(); $file_validation = new Validation($_FILES); $file_validation->add_rules("Filedata", "upload::valid", "upload::required", "upload::type[gif,jpg,jpeg,png,flv,mp4]"); if ($file_validation->validate()) { // SimpleUploader.swf does not yet call /start directly, so simulate it here for now. if (!batch::in_progress()) { batch::start(); } $temp_filename = upload::save("Filedata"); try { $name = substr(basename($temp_filename), 10); // Skip unique identifier Kohana adds $title = item::convert_filename_to_title($name); $path_info = @pathinfo($temp_filename); if (array_key_exists("extension", $path_info) && in_array(strtolower($path_info["extension"]), array("flv", "mp4"))) { $item = movie::create($album, $temp_filename, $name, $title); log::success("content", t("Added a movie"), html::anchor("movies/{$item->id}", t("view movie"))); } else { $item = photo::create($album, $temp_filename, $name, $title); log::success("content", t("Added a photo"), html::anchor("photos/{$item->id}", t("view photo"))); } // We currently have no way of showing errors if validation fails, so only call our event // handlers if validation passes. $form = $this->_get_add_form($album); if ($form->validate()) { module::event("add_photos_form_completed", $item, $form); } } catch (Exception $e) { Kohana_Log::add("alert", $e->__toString()); if (file_exists($temp_filename)) { unlink($temp_filename); } header("HTTP/1.1 500 Internal Server Error"); print "ERROR: " . $e->getMessage(); return; } unlink($temp_filename); print "FILEID: {$item->id}"; } else { header("HTTP/1.1 400 Bad Request"); print "ERROR: " . t("Invalid Upload"); } }
public function change_photo_no_csrf_fails_test() { $controller = new Photos_Controller(); $root = ORM::factory("item", 1); $this->_photo = photo::create($root, MODPATH . "gallery/tests/test.jpg", "test", "test", "test"); $_POST["name"] = "new name"; $_POST["title"] = "new title"; $_POST["description"] = "new description"; access::allow(group::everybody(), "edit", $root); try { $controller->_update($this->_photo); $this->assert_true(false, "This should fail"); } catch (Exception $e) { // pass } }
/** * Import a single photo or movie. */ static function import_item(&$queue) { $g2_item_id = array_shift($queue); if (self::map($g2_item_id)) { return t("Item with id: %id already imported, skipping", array("id" => $g2_item_id)); } try { self::$current_g2_item = $g2_item = g2(GalleryCoreApi::loadEntitiesById($g2_item_id)); $g2_path = g2($g2_item->fetchPath()); } catch (Exception $e) { return t("Failed to import Gallery 2 item with id: %id\n%exception", array("id" => $g2_item_id, "exception" => $e->__toString())); } $parent = ORM::factory("item", self::map($g2_item->getParentId())); $g2_type = $g2_item->getEntityType(); $corrupt = 0; if (!file_exists($g2_path)) { // If the Gallery 2 source image isn't available, this operation is going to fail. That can // happen in cases where there's corruption in the source Gallery 2. In that case, fall // back on using a broken image. It's important that we import *something* otherwise // anything that refers to this item in Gallery 2 will have a dangling pointer in Gallery 3 // // Note that this will change movies to be photos, if there's a broken movie. Hopefully // this case is rare enough that we don't need to take any heroic action here. g2_import::log(t("%path missing in import; replacing it with a placeholder", array("path" => $g2_path))); $g2_path = MODPATH . "g2_import/data/broken-image.gif"; $g2_type = "GalleryPhotoItem"; $corrupt = 1; } $message = array(); switch ($g2_type) { case "GalleryPhotoItem": if (!in_array($g2_item->getMimeType(), array("image/jpeg", "image/gif", "image/png"))) { Kohana::log("alert", "{$g2_path} is an unsupported image type; using a placeholder gif"); $message[] = t("'%path' is an unsupported image type, using a placeholder", array("path" => $g2_path)); $g2_path = MODPATH . "g2_import/data/broken-image.gif"; $corrupt = 1; } try { $item = photo::create($parent, $g2_path, $g2_item->getPathComponent(), self::_decode_html_special_chars($g2_item->getTitle()), self::_decode_html_special_chars(self::extract_description($g2_item)), self::map($g2_item->getOwnerId())); } catch (Exception $e) { Kohana::log("alert", "Corrupt image {$g2_path}\n" . $e->__toString()); $message[] = t("Corrupt image '%path'", array("path" => $g2_path)); $message[] = $e->__toString(); $corrupt = 1; } break; case "GalleryMovieItem": // @todo we should transcode other types into FLV if (in_array($g2_item->getMimeType(), array("video/mp4", "video/x-flv"))) { try { $item = movie::create($parent, $g2_path, $g2_item->getPathComponent(), self::_decode_html_special_chars($g2_item->getTitle()), self::_decode_html_special_chars(self::extract_description($g2_item)), self::map($g2_item->getOwnerId())); } catch (Exception $e) { Kohana::log("alert", "Corrupt movie {$g2_path}\n" . $e->__toString()); $message[] = t("Corrupt movie '%path'", array("path" => $g2_path)); $message[] = $e->__toString(); $corrupt = 1; } } else { Kohana::log("alert", "{$g2_path} is an unsupported movie type"); $message[] = t("'%path' is an unsupported movie type", array("path" => $g2_path)); $corrupt = 1; } break; default: // Ignore break; } if (!empty($item)) { self::import_keywords_as_tags($g2_item->getKeywords(), $item); } if (isset($item)) { self::set_map($g2_item_id, $item->id); $item->view_count = g2(GalleryCoreApi::fetchItemViewCount($g2_item_id)); $item->save(); } if ($corrupt) { $url_generator = $GLOBALS["gallery"]->getUrlGenerator(); // @todo we need a more persistent warning $g2_item_url = $url_generator->generateUrl(array("itemId" => $g2_item->getId())); // Why oh why did I ever approve the session id placeholder idea in G2? $g2_item_url = str_replace('&g2_GALLERYSID=TMP_SESSION_ID_DI_NOISSES_PMT', '', $g2_item_url); if (!empty($item)) { $message[] = t("<a href=\"%g2_url\">%title</a> from Gallery 2 could not be processed; " . "(imported as <a href=\"%g3_url\">%title</a>)", array("g2_url" => $g2_item_url, "g3_url" => $item->url(), "title" => $g2_item->getTitle())); } else { $message[] = t("<a href=\"%g2_url\">%title</a> from Gallery 2 could not be processed", array("g2_url" => $g2_item_url, "title" => $g2_item->getTitle())); } } self::$current_g2_item = null; return $message; }
private static function _add_album_or_photo($desired_type = null) { srand(time()); $parents = ORM::factory("item")->where("type", "album")->find_all()->as_array(); $owner_id = user::active()->id; $test_images = glob(dirname(dirname(__FILE__)) . "/data/*.[Jj][Pp][Gg]"); $parent = $parents[array_rand($parents)]; $parent->reload(); $type = $desired_type; if (!$type) { $type = rand(0, 10) ? "photo" : "album"; } if ($type == "album") { $thumb_size = module::get_var("core", "thumb_size"); $rand = rand(); $parents[] = album::create($parent, "rnd_{$rand}", "Rnd {$rand}", "random album {$rand}", $owner_id)->save(); } else { $photo_index = rand(0, count($test_images) - 1); photo::create($parent, $test_images[$photo_index], basename($test_images[$photo_index]), "rnd_" . rand(), "sample thumb", $owner_id); } }
public function moved_items_inherit_new_permissions_test() { user::set_active(user::lookup_by_name("admin")); $root = ORM::factory("item", 1); $public_album = album::create($root, rand(), "public album"); $public_photo = photo::create($public_album, MODPATH . "gallery/images/gallery.png", "", ""); access::allow(group::everybody(), "view", $public_album); $root->reload(); // Account for MPTT changes $private_album = album::create($root, rand(), "private album"); access::deny(group::everybody(), "view", $private_album); $private_photo = photo::create($private_album, MODPATH . "gallery/images/gallery.png", "", ""); // Make sure that we now have a public photo and private photo. $this->assert_true(access::group_can(group::everybody(), "view", $public_photo)); $this->assert_false(access::group_can(group::everybody(), "view", $private_photo)); // Swap the photos item::move($public_photo, $private_album); $private_album->reload(); // Reload to get new MPTT pointers and cached perms. $public_album->reload(); $private_photo->reload(); $public_photo->reload(); item::move($private_photo, $public_album); $private_album->reload(); // Reload to get new MPTT pointers and cached perms. $public_album->reload(); $private_photo->reload(); $public_photo->reload(); // Make sure that the public_photo is now private, and the private_photo is now public. $this->assert_false(access::group_can(group::everybody(), "view", $public_photo)); $this->assert_true(access::group_can(group::everybody(), "view", $private_photo)); }
private function _create_photo($album) { access::required("view", $album); access::required("add", $album); // If we set the content type as JSON, it triggers saving the result as // a document in the browser (well, in Chrome at least). // @todo figure out why and fix this. $form = photo::get_add_form($album); if ($form->validate()) { $photo = photo::create($album, $this->input->post("file"), $_FILES["file"]["name"], $this->input->post("title", $this->input->post("name")), $this->input->post("description"), user::active()->id); log::success("content", "Added a photo", html::anchor("photos/{$photo->id}", "view photo")); message::success(t("Added photo %photo_title", array("photo_title" => $photo->title))); print json_encode(array("result" => "success", "resource" => url::site("photos/{$photo->id}"), "location" => url::site("photos/{$photo->id}"))); } else { print json_encode(array("result" => "error", "form" => $form->__toString())); } }
public function add_photo($id) { access::verify_csrf(); $album = ORM::factory("item", $id); access::required("view", $album); access::required("add", $album); try { $name = $_REQUEST["filename"]; $body = @file_get_contents('php://input'); //$stream = http_get_request_body(); $directory = Kohana::config('upload.directory', TRUE); // Make sure the directory ends with a slash $directory = str_replace('\\', '/', $directory); $directory = rtrim($directory, '/') . '/'; if (!is_dir($directory) and Kohana::config('upload.create_directories') === TRUE) { // Create the upload directory mkdir($directory, 0777, TRUE); } if (!is_writable($directory)) { throw new Kohana_Exception('upload.not_writable', $directory); } $temp_filename = $directory . $name; $file = fopen($temp_filename, 'w'); fwrite($file, $body); fclose($file); $title = item::convert_filename_to_title($name); $path_info = @pathinfo($temp_filename); if (array_key_exists("extension", $path_info) && in_array(strtolower($path_info["extension"]), array("flv", "mp4"))) { $item = movie::create($album, $temp_filename, $name, $title); log::success("content", t("Added a movie"), html::anchor("movies/{$item->id}", t("view movie"))); } else { $item = photo::create($album, $temp_filename, $name, $title); log::success("content", t("Added a photo"), html::anchor("photos/{$item->id}", t("view photo"))); } } catch (Exception $e) { Kohana::log("alert", $e->__toString()); if (file_exists($temp_filename)) { unlink($temp_filename); } header("HTTP/1.1 500 Internal Server Error"); print "ERROR: " . $e->getMessage(); return; } unlink($temp_filename); print json_encode(self::child_json_encode($item)); }
/** * This is the task code that adds photos and albums. It first examines all the target files * and creates a set of Server_Add_File_Models, then runs through the list of models and adds * them one at a time. */ static function add($task) { $mode = $task->get("mode", "init"); $start = microtime(true); switch ($mode) { case "init": $task->set("mode", "build-file-list"); $task->percent_complete = 0; $task->status = t("Starting up"); batch::start(); break; case "build-file-list": // 0% to 10% // We can't fit an arbitrary number of paths in a task, so store them in a separate table. // Don't use an iterator here because we can't get enough control over it when we're dealing // with a deep hierarchy and we don't want to go over our time quota. The queue is in the // form [path, parent_id] where the parent_id refers to another Server_Add_File_Model. We // have this extra level of abstraction because we don't know its Item_Model id yet. $queue = $task->get("queue"); while ($queue && microtime(true) - $start < 0.5) { list($file, $parent_entry_id) = array_shift($queue); $entry = ORM::factory("server_add_file"); $entry->task_id = $task->id; $entry->file = $file; $entry->parent_id = $parent_entry_id; $entry->save(); foreach (glob("{$file}/*") as $child) { if (is_dir($child)) { $queue[] = array($child, $entry->id); } else { $ext = strtolower(pathinfo($child, PATHINFO_EXTENSION)); if (in_array($ext, array("gif", "jpeg", "jpg", "png", "flv", "mp4"))) { $child_entry = ORM::factory("server_add_file"); $child_entry->task_id = $task->id; $child_entry->file = $child; $child_entry->parent_id = $entry->id; $child_entry->save(); } } } } // We have no idea how long this can take because we have no idea how deep the tree // hierarchy rabbit hole goes. Leave ourselves room here for 100 iterations and don't go // over 10% in percent_complete. $task->set("queue", $queue); $task->percent_complete = min($task->percent_complete + 0.1, 10); $task->status = t2("Found one file", "Found %count files", Database::instance()->where("task_id", $task->id)->count_records("server_add_files")); if (!$queue) { $task->set("mode", "add-files"); $task->set("total_files", database::instance()->count_records("server_add_files", array("task_id" => $task->id))); $task->percent_complete = 10; } break; case "add-files": // 10% to 100% $completed_files = $task->get("completed_files", 0); $total_files = $task->get("total_files"); // Ordering by id ensures that we add them in the order that we created the entries, which // will create albums first. Ignore entries which already have an Item_Model attached, // they're done. $entries = ORM::factory("server_add_file")->where("task_id", $task->id)->where("item_id", null)->orderby("id", "ASC")->limit(10)->find_all(); if ($entries->count() == 0) { // Out of entries, we're done. $task->set("mode", "done"); } $owner_id = user::active()->id; foreach ($entries as $entry) { if (microtime(true) - $start > 0.5) { break; } // Look up the parent item for this entry. By now it should exist, but if none was // specified, then this belongs as a child of the current item. $parent_entry = ORM::factory("server_add_file", $entry->parent_id); if (!$parent_entry->loaded) { $parent = ORM::factory("item", $task->get("item_id")); } else { $parent = ORM::factory("item", $parent_entry->item_id); } $name = basename($entry->file); $title = item::convert_filename_to_title($name); if (is_dir($entry->file)) { $album = album::create($parent, $name, $title, null, $owner_id); $entry->item_id = $album->id; } else { $extension = strtolower(pathinfo($name, PATHINFO_EXTENSION)); if (in_array($extension, array("gif", "png", "jpg", "jpeg"))) { $photo = photo::create($parent, $entry->file, $name, $title, null, $owner_id); $entry->item_id = $photo->id; } else { if (in_array($extension, array("flv", "mp4"))) { $movie = movie::create($parent, $entry->file, $name, $title, null, $owner_id); $entry->item_id = $movie->id; } else { // This should never happen, because we don't add stuff to the list that we can't // process. But just in, case.. set this to a non-null value so that we skip this // entry. $entry->item_id = 0; $task->log("Skipping unknown file type: {$entry->file}"); } } } $completed_files++; $entry->save(); } $task->set("completed_files", $completed_files); $task->status = t("Adding photos and albums (%completed of %total)", array("completed" => $completed_files, "total" => $total_files)); $task->percent_complete = 10 + 100 * ($completed_files / $total_files); break; case "done": batch::stop(); $task->done = true; $task->state = "success"; $task->percent_complete = 100; ORM::factory("server_add_file")->where("task_id", $task->id)->delete_all(); message::info(t2("Successfully added one photo", "Successfully added %count photos and albums", $task->get("completed_files"))); } }
public function create_photo_silently_trims_trailing_periods_test() { $rand = rand(); $root = ORM::factory("item", 1); try { $photo = photo::create($root, MODPATH . "gallery/tests/test.jpg", "{$rand}.jpg.", $rand, $rand); } catch (Exception $e) { $this->assert_equal("@todo NAME_CANNOT_END_IN_PERIOD", $e->getMessage()); return; } $this->assert_true(false, "Shouldn't create a photo with trailing . in the name"); }