Example #1
0
 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";
 }
Example #2
0
 public function create_movie_creates_reasonable_slug_test()
 {
     $rand = rand();
     $root = ORM::factory("item", 1);
     $album = album::create($root, $rand, $rand, $rand);
     $movie = movie::create($album, MODPATH . "gallery/tests/test.flv", "This (is) my file%name.flv", $rand, $rand);
     $this->assert_equal("This-is-my-file-name", $movie->slug);
 }
Example #3
0
 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"];
 }
Example #4
0
 public function create_movie_shouldnt_allow_names_with_trailing_periods_test()
 {
     $rand = rand();
     $root = ORM::factory("item", 1);
     try {
         $movie = movie::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 movie with trailing . in the name");
 }
Example #5
0
 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");
     }
 }
Example #6
0
 /**
  * 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('&amp;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;
 }
Example #7
0
 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));
 }
Example #8
0
 /**
  * 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")));
     }
 }