示例#1
0
 public function anyEdit($id = null)
 {
     Auth::getUser()->hasPermissionOr401(Config::get("permissions.mediaItems"), 1);
     $mediaItem = null;
     $editing = false;
     if (!is_null($id)) {
         $mediaItem = MediaItem::with("coverFile", "sideBannerFile", "videoItem", "liveStreamItem", "liveStreamItem.liveStream", "liveStreamItem.stateDefinition", "relatedItems")->find($id);
         if (is_null($mediaItem)) {
             App::abort(404);
             return;
         }
         $editing = true;
     }
     $formSubmitted = isset($_POST['form-submitted']) && $_POST['form-submitted'] === "1";
     // has id 1
     // populate $formData with default values or received values
     $formData = FormHelpers::getFormData(array(array("enabled", ObjectHelpers::getProp(true, $mediaItem, "enabled") ? "y" : ""), array("promoted", ObjectHelpers::getProp(false, $mediaItem, "promoted") ? "y" : ""), array("name", ObjectHelpers::getProp("", $mediaItem, "name")), array("description", ObjectHelpers::getProp("", $mediaItem, "description")), array("email-notifications-enabled", ObjectHelpers::getProp(true, $mediaItem, "email_notifications_enabled") ? "y" : ""), array("likes-enabled", ObjectHelpers::getProp(true, $mediaItem, "likes_enabled") ? "y" : ""), array("comments-enabled", ObjectHelpers::getProp(true, $mediaItem, "comments_enabled") ? "y" : ""), array("cover-image-id", ObjectHelpers::getProp("", $mediaItem, "coverFile", "id")), array("cover-art-id", ObjectHelpers::getProp("", $mediaItem, "coverArtFile", "id")), array("side-banners-image-id", ObjectHelpers::getProp("", $mediaItem, "sideBannerFile", "id")), array("side-banners-fill-image-id", ObjectHelpers::getProp("", $mediaItem, "sideBannerFillFile", "id")), array("publish-time", ObjectHelpers::getProp("", $mediaItem, "scheduled_publish_time_for_input")), array("vod-added", !is_null(ObjectHelpers::getProp(null, $mediaItem, "videoItem")) ? "1" : "0"), array("vod-enabled", ObjectHelpers::getProp(true, $mediaItem, "videoItem", "enabled") ? "y" : ""), array("vod-video-id", ObjectHelpers::getProp("", $mediaItem, "videoItem", "sourceFile", "id")), array("vod-time-recorded", ObjectHelpers::getProp("", $mediaItem, "videoItem", "time_recorded_for_input")), array("vod-chapters", json_encode(array())), array("stream-added", !is_null(ObjectHelpers::getProp(null, $mediaItem, "liveStreamItem")) ? "1" : "0"), array("stream-enabled", ObjectHelpers::getProp(true, $mediaItem, "liveStreamItem", "enabled") ? "y" : ""), array("stream-state", ObjectHelpers::getProp(LiveStreamStateDefinition::first()->id, $mediaItem, "liveStreamItem", "stateDefinition", "id")), array("stream-being-recorded", ObjectHelpers::getProp(false, $mediaItem, "liveStreamItem", "being_recorded") ? "y" : ""), array("stream-info-msg", ObjectHelpers::getProp("", $mediaItem, "liveStreamItem", "information_msg")), array("stream-stream-id", ObjectHelpers::getProp("", $mediaItem, "liveStreamItem", "liveStream", "id")), array("stream-external-stream-url", ObjectHelpers::getProp("", $mediaItem, "liveStreamItem", "external_stream_url")), array("credits", json_encode(array())), array("related-items", json_encode(array()))), !$formSubmitted);
     // this will contain any additional data which does not get saved anywhere
     $additionalFormData = array("coverImageFile" => FormHelpers::getFileInfo($formData['cover-image-id']), "sideBannersImageFile" => FormHelpers::getFileInfo($formData['side-banners-image-id']), "sideBannersFillImageFile" => FormHelpers::getFileInfo($formData['side-banners-fill-image-id']), "coverArtFile" => FormHelpers::getFileInfo($formData['cover-art-id']), "vodVideoFile" => FormHelpers::getFileInfo($formData['vod-video-id']), "vodChaptersInput" => null, "vodChaptersInitialData" => null, "creditsInput" => null, "creditsInputInitialData" => null, "relatedItemsInput" => null, "relatedItemsInitialData" => null);
     if (!$formSubmitted) {
         $additionalFormData['creditsInput'] = ObjectHelpers::getProp(json_encode(array()), $mediaItem, "credits_for_input");
         $additionalFormData['creditsInitialData'] = ObjectHelpers::getProp(json_encode(array()), $mediaItem, "credits_for_reorderable_list");
         $additionalFormData['relatedItemsInput'] = ObjectHelpers::getProp(json_encode(array()), $mediaItem, "related_items_for_input");
         $additionalFormData['relatedItemsInitialData'] = ObjectHelpers::getProp(json_encode(array()), $mediaItem, "related_items_for_reorderable_list");
     } else {
         $additionalFormData['creditsInput'] = MediaItem::generateInputValueForMediaItemCreditsReorderableList(JsonHelpers::jsonDecodeOrNull($formData['credits'], true));
         $additionalFormData['creditsInitialData'] = MediaItem::generateInitialDataForMediaItemCreditsReorderableList(JsonHelpers::jsonDecodeOrNull($formData['credits'], true));
         $additionalFormData['relatedItemsInput'] = MediaItem::generateInputValueForAjaxSelectReorderableList(JsonHelpers::jsonDecodeOrNull($formData['related-items'], true));
         $additionalFormData['relatedItemsInitialData'] = MediaItem::generateInitialDataForAjaxSelectReorderableList(JsonHelpers::jsonDecodeOrNull($formData['related-items'], true));
     }
     if (!$formSubmitted && !is_null($mediaItem) && !is_null($mediaItem->videoItem)) {
         $additionalFormData['vodChaptersInput'] = ObjectHelpers::getProp(json_encode(array()), $mediaItem, "videoItem", "chapters_for_input");
         $additionalFormData['vodChaptersInitialData'] = ObjectHelpers::getProp(json_encode(array()), $mediaItem, "videoItem", "chapters_for_reorderable_list");
     } else {
         $additionalFormData['vodChaptersInput'] = MediaItemVideo::generateInputValueForChaptersReorderableList(JsonHelpers::jsonDecodeOrNull($formData['vod-chapters'], true));
         $additionalFormData['vodChaptersInitialData'] = MediaItemVideo::generateInitialDataForChaptersReorderableList(JsonHelpers::jsonDecodeOrNull($formData['vod-chapters'], true));
     }
     $liveStreamStateDefinitions = LiveStreamStateDefinition::orderBy("id", "asc")->get();
     $additionalFormData['streamStateButtonsData'] = array();
     foreach ($liveStreamStateDefinitions as $a) {
         $additionalFormData['streamStateButtonsData'][] = array("id" => intval($a->id), "text" => $a->name);
     }
     $errors = null;
     if ($formSubmitted) {
         // validate input
         Validator::extend('valid_file_id', FormHelpers::getValidFileValidatorFunction());
         Validator::extend('valid_stream_id', FormHelpers::getValidStreamValidatorFunction());
         Validator::extend('my_date', FormHelpers::getValidDateValidatorFunction());
         Validator::extend('valid_credits', function ($attribute, $value, $parameters) {
             return MediaItem::isValidDataFromMediaItemCreditsReorderableList(JsonHelpers::jsonDecodeOrNull($value, true));
         });
         Validator::extend('valid_related_items', function ($attribute, $value, $parameters) {
             return MediaItem::isValidIdsFromAjaxSelectReorderableList(JsonHelpers::jsonDecodeOrNull($value, true));
         });
         Validator::extend('valid_vod_chapters', function ($attribute, $value, $parameters) {
             return MediaItemVideo::isValidDataFromChaptersReorderableList(JsonHelpers::jsonDecodeOrNull($value, true));
         });
         Validator::extend('valid_stream_state_id', function ($attribute, $value, $parameters) {
             return !is_null(LiveStreamStateDefinition::find(intval($value)));
         });
         Validator::extend('not_specified', function ($attribute, $value, $parameters) {
             return false;
         });
         $modelCreated = DB::transaction(function () use(&$formData, &$mediaItem, &$errors) {
             $validator = Validator::make($formData, array('name' => array('required', 'max:50'), 'description' => array('max:500'), 'cover-image-id' => array('valid_file_id'), 'side-banners-image-id' => array('valid_file_id'), 'side-banners-fill-image-id' => array('valid_file_id'), 'cover-art-id' => array('valid_file_id'), 'publish-time' => array('my_date'), 'vod-video-id' => array('required_if:vod-added,1', 'valid_file_id'), 'vod-time-recorded' => array('my_date'), 'vod-chapters' => array('required', 'valid_vod_chapters'), 'stream-state' => array('required', 'valid_stream_state_id'), 'stream-info-msg' => array('max:500'), 'stream-stream-id' => array('valid_stream_id'), 'stream-external-stream-url' => array('url'), 'credits' => array('required', 'valid_credits'), 'related-items' => array('required', 'valid_related_items')), array('name.required' => FormHelpers::getRequiredMsg(), 'name.max' => FormHelpers::getLessThanCharactersMsg(50), 'description.max' => FormHelpers::getLessThanCharactersMsg(500), 'cover-image-id.valid_file_id' => FormHelpers::getInvalidFileMsg(), 'side-banners-image-id.valid_file_id' => FormHelpers::getInvalidFileMsg(), 'side-banners-fill-image-id.valid_file_id' => FormHelpers::getInvalidFileMsg(), 'cover-art-id.valid_file_id' => FormHelpers::getInvalidFileMsg(), 'publish-time.my_date' => FormHelpers::getInvalidTimeMsg(), 'vod-video-id.required_if' => FormHelpers::getRequiredMsg(), 'vod-video-id.valid_file_id' => FormHelpers::getInvalidFileMsg(), 'vod-time-recorded.my_date' => FormHelpers::getInvalidTimeMsg(), 'vod-time-recorded.not_specified' => "This cannot be set if this is a recording of a live stream. The time will be inferred from the scheduled live time.", 'vod-chapters.required' => FormHelpers::getGenericInvalidMsg(), 'vod-chapters.valid_vod_chapters' => FormHelpers::getGenericInvalidMsg(), 'stream-state.required' => FormHelpers::getRequiredMsg(), 'stream-state.valid_stream_state_id' => FormHelpers::getGenericInvalidMsg(), 'stream-info-msg.max' => FormHelpers::getLessThanCharactersMsg(500), 'stream-stream-id.valid_stream_id' => FormHelpers::getInvalidStreamMsg(), 'stream-external-stream-url.url' => "This is not a valid url.", 'credits.required' => FormHelpers::getGenericInvalidMsg(), 'credits.valid_credits' => FormHelpers::getGenericInvalidMsg(), 'related-items.required' => FormHelpers::getGenericInvalidMsg(), 'related-items.valid_related_items' => FormHelpers::getGenericInvalidMsg()));
             $validator->sometimes("vod-time-recorded", "not_specified", function ($input) use(&$formData) {
                 return $formData['stream-added'] === "1" && $formData['vod-added'] === "1";
             });
             if (!$validator->fails()) {
                 // everything is good. save/create model
                 if (is_null($mediaItem)) {
                     $mediaItem = new MediaItem();
                 }
                 $mediaItem->name = $formData['name'];
                 $mediaItem->description = FormHelpers::nullIfEmpty($formData['description']);
                 $mediaItem->enabled = FormHelpers::toBoolean($formData['enabled']);
                 $mediaItem->promoted = FormHelpers::toBoolean($formData['promoted']);
                 // if the scheduled publish time is empty and this item is enabled, set it to the current time.
                 // an enabled media item should always have a published time.
                 $scheduledPublishTime = FormHelpers::nullIfEmpty(strtotime($formData['publish-time']));
                 $mediaItem->scheduled_publish_time = !is_null($scheduledPublishTime) ? $scheduledPublishTime : Carbon::now();
                 $mediaItem->email_notifications_enabled = FormHelpers::toBoolean($formData['email-notifications-enabled']);
                 $mediaItem->likes_enabled = FormHelpers::toBoolean($formData['likes-enabled']);
                 // if comments are being disabled then remove any existing comments.
                 $commentsEnabled = FormHelpers::toBoolean($formData['comments-enabled']);
                 $currentCommentsEnabled = (bool) $mediaItem->comments_enabled;
                 $mediaItem->comments_enabled = $commentsEnabled;
                 if ($currentCommentsEnabled !== $commentsEnabled) {
                     // remove when changing from enabled to disabled and vice versa
                     // I think it might be possible for someone to make a comment during this transaction when going from enabled to disable.
                     // deleting when going from disabled to enabled should always catch any that this happens to
                     $mediaItem->comments()->delete();
                 }
                 $coverImageId = FormHelpers::nullIfEmpty($formData['cover-image-id']);
                 $file = Upload::register(Config::get("uploadPoints.coverImage"), $coverImageId, $mediaItem->coverFile);
                 EloquentHelpers::associateOrNull($mediaItem->coverFile(), $file);
                 $sideBannerFileId = FormHelpers::nullIfEmpty($formData['side-banners-image-id']);
                 $file = Upload::register(Config::get("uploadPoints.sideBannersImage"), $sideBannerFileId, $mediaItem->sideBannerFile);
                 EloquentHelpers::associateOrNull($mediaItem->sideBannerFile(), $file);
                 $sideBannerFillFileId = FormHelpers::nullIfEmpty($formData['side-banners-fill-image-id']);
                 $file = Upload::register(Config::get("uploadPoints.sideBannersFillImage"), $sideBannerFillFileId, $mediaItem->sideBannerFillFile);
                 EloquentHelpers::associateOrNull($mediaItem->sideBannerFillFile(), $file);
                 $coverArtId = FormHelpers::nullIfEmpty($formData['cover-art-id']);
                 $file = Upload::register(Config::get("uploadPoints.coverArt"), $coverArtId, $mediaItem->coverArtFile);
                 EloquentHelpers::associateOrNull($mediaItem->coverArtFile(), $file);
                 // vod
                 $mediaItemVideo = null;
                 if ($formData['vod-added'] === "1") {
                     // create MediaItemVideo if doesn't exist, otherwise retrieve it
                     if (!is_null($mediaItem->videoItem)) {
                         $mediaItemVideo = $mediaItem->videoItem;
                     } else {
                         $mediaItemVideo = new MediaItemVideo();
                     }
                     $mediaItemVideo->time_recorded = FormHelpers::nullIfEmpty(strtotime($formData['vod-time-recorded']));
                     $mediaItemVideo->enabled = FormHelpers::toBoolean($formData['vod-enabled']);
                     $vodVideoId = FormHelpers::nullIfEmpty($formData['vod-video-id']);
                     $file = Upload::register(Config::get("uploadPoints.vodVideo"), $vodVideoId, $mediaItemVideo->sourceFile);
                     EloquentHelpers::associateOrNull($mediaItemVideo->sourceFile(), $file);
                     if ($mediaItemVideo->chapters()->count() > 0) {
                         if (!$mediaItemVideo->chapters()->delete()) {
                             // remove all chapters
                             throw new Exception("Error deleting MediaItemVideo chapters.");
                         }
                     }
                     // now add the chapters again
                     $chapterData = json_decode($formData['vod-chapters'], true);
                     foreach ($chapterData as $chapter) {
                         $chapterModel = new MediaItemVideoChapter(array("title" => trim($chapter['title']), "time" => $chapter['time']));
                         $mediaItemVideo->chapters()->save($chapterModel);
                     }
                 } else {
                     // remove video model if there is one
                     if (!is_null($mediaItem->videoItem)) {
                         // remove source file and cover art file (if there is one)
                         Upload::delete($mediaItem->videoItem->sourceFile);
                         Upload::delete($mediaItem->videoItem->coverArtFile);
                         if ($mediaItem->videoItem->delete() === false) {
                             throw new Exception("Error deleting MediaItemVideo.");
                         }
                     }
                 }
                 // stream
                 $mediaItemLiveStream = null;
                 if ($formData['stream-added'] === "1") {
                     // create MediaItemLiveStream if doesn't exist, otherwise retrieve it
                     if (!is_null($mediaItem->liveStreamItem)) {
                         $mediaItemLiveStream = $mediaItem->liveStreamItem;
                     } else {
                         $mediaItemLiveStream = new MediaItemLiveStream();
                     }
                     $mediaItemLiveStream->information_msg = FormHelpers::nullIfEmpty($formData['stream-info-msg']);
                     $mediaItemLiveStream->being_recorded = FormHelpers::toBoolean($formData['stream-being-recorded']);
                     $mediaItemLiveStream->enabled = FormHelpers::toBoolean($formData['stream-enabled']);
                     $mediaItemLiveStream->stateDefinition()->associate(LiveStreamStateDefinition::find($formData['stream-state']));
                     if (!is_null(FormHelpers::nullIfEmpty($formData['stream-stream-id']))) {
                         $liveStream = LiveStream::find(intval($formData['stream-stream-id'], 10));
                         if (is_null($liveStream)) {
                             throw new Exception("Live stream no longer exists in transaction.");
                         }
                         $mediaItemLiveStream->liveStream()->associate($liveStream);
                     } else {
                         EloquentHelpers::setForeignKeyNull($mediaItemLiveStream->liveStream());
                     }
                     $mediaItemLiveStream->external_stream_url = FormHelpers::nullIfEmpty($formData['stream-external-stream-url']);
                 } else {
                     // remove livestream model if there is one
                     if (!is_null($mediaItem->liveStreamItem)) {
                         if ($mediaItem->liveStreamItem->delete() === false) {
                             throw new Exception("Error deleting MediaItemLiveStream.");
                         }
                     }
                 }
                 if ($mediaItem->save() === false) {
                     throw new Exception("Error saving MediaItem.");
                 }
                 if (!is_null($mediaItemVideo)) {
                     if ($mediaItem->videoItem()->save($mediaItemVideo) === false) {
                         throw new Exception("Error creating MediaItemVideo.");
                     }
                 }
                 if (!is_null($mediaItemLiveStream)) {
                     if ($mediaItem->liveStreamItem()->save($mediaItemLiveStream) === false) {
                         throw new Exception("Error creating MediaItemLiveStream.");
                     }
                 }
                 // update credits
                 if ($mediaItem->credits()->count() > 0) {
                     if (!$mediaItem->credits()->delete()) {
                         // remove all chapters
                         throw new Exception("Error deleting MediaItem credits.");
                     }
                 }
                 $creditsData = json_decode($formData['credits'], true);
                 foreach ($creditsData as $credit) {
                     $creditModel = new Credit(array("name_override" => $credit["nameOverride"]));
                     $productionRole = ProductionRoleMediaItem::find($credit["productionRoleId"]);
                     $creditModel->productionRole()->associate($productionRole);
                     if (!is_null($credit["siteUserId"])) {
                         $siteUser = SiteUser::find($credit["siteUserId"]);
                         if (is_null($siteUser)) {
                             // given the credits data has been validated earlier, it shouldn't have passed if the SiteUser didn't exist
                             throw new Exception("Was expecting the SiteUser to exist.");
                         }
                         $creditModel->siteUser()->associate($siteUser);
                     }
                     $mediaItem->credits()->save($creditModel);
                 }
                 $mediaItem->relatedItems()->detach();
                 // detaches all
                 $ids = json_decode($formData['related-items'], true);
                 if (count($ids) > 0) {
                     $mediaItems = MediaItem::whereIn("id", $ids)->get();
                     foreach ($mediaItems as $a) {
                         $mediaItem->relatedItems()->attach($a, array("position" => array_search(intval($a->id), $ids, true)));
                     }
                 }
                 // the transaction callback result is returned out of the transaction function
                 return true;
             } else {
                 $errors = $validator->messages();
                 return false;
             }
         });
         if ($modelCreated) {
             return Redirect::to(Config::get("custom.admin_base_url") . "/media");
         }
         // if not valid then return form again with errors
     }
     $liveStreams = LiveStream::orderBy("name", "asc")->orderBy("description", "asc")->get();
     $streamOptions = array();
     $streamOptions[] = array("id" => "", "name" => "[None]");
     foreach ($liveStreams as $a) {
         $name = $a->name;
         if (!$a->enabled) {
             $name .= " [Disabled]";
         }
         $streamOptions[] = array("id" => $a->id, "name" => $name);
     }
     $hasDvrRecording = false;
     $liveStreamItem = !is_null($mediaItem) ? $mediaItem->liveStreamItem : null;
     if (!is_null($liveStreamItem)) {
         $hasDvrRecording = $liveStreamItem->dvrLiveStreamUris()->count() > 0;
     }
     $view = View::make('home.admin.media.edit');
     $view->editing = $editing;
     $view->streamOptions = $streamOptions;
     $view->form = $formData;
     $view->additionalForm = $additionalFormData;
     $view->hasDvrRecording = $hasDvrRecording;
     if ($hasDvrRecording) {
         $view->dvrRecordingRemoveUri = Config::get("custom.admin_base_url") . "/media/remove-dvr-recording/" . $liveStreamItem->id;
     }
     $view->formErrors = $errors;
     // used to uniquely identify these file upload points on the site. Must not be duplicated for different upload points.
     $view->coverImageUploadPointId = Config::get("uploadPoints.coverImage");
     $view->sideBannersImageUploadPointId = Config::get("uploadPoints.sideBannersImage");
     $view->sideBannersFillImageUploadPointId = Config::get("uploadPoints.sideBannersFillImage");
     $view->coverArtUploadPointId = Config::get("uploadPoints.coverArt");
     $view->vodVideoUploadPointId = Config::get("uploadPoints.vodVideo");
     $view->cancelUri = Config::get("custom.admin_base_url") . "/media";
     $this->setContent($view, "media", "media-edit");
 }