diff --git a/airtime_mvc/application/common/DateHelper.php b/airtime_mvc/application/common/DateHelper.php index 5d40e9b5f..bbac8abc1 100644 --- a/airtime_mvc/application/common/DateHelper.php +++ b/airtime_mvc/application/common/DateHelper.php @@ -266,7 +266,7 @@ class Application_Common_DateHelper public static function ConvertToLocalDateTime($p_dateString){ $dateTime = new DateTime($p_dateString, new DateTimeZone("UTC")); - $dateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); + $dateTime->setTimezone(new DateTimeZone(Application_Model_Preference::GetTimezone())); return $dateTime; } diff --git a/airtime_mvc/application/controllers/ApiController.php b/airtime_mvc/application/controllers/ApiController.php index b2280b0b4..1e4789747 100644 --- a/airtime_mvc/application/controllers/ApiController.php +++ b/airtime_mvc/application/controllers/ApiController.php @@ -64,14 +64,8 @@ class ApiController extends Zend_Controller_Action public function versionAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - - $jsonStr = json_encode( array( + $this->_helper->json->sendJson( array( "version" => Application_Model_Preference::GetAirtimeVersion())); - echo $jsonStr; - die(); } /** @@ -80,9 +74,6 @@ class ApiController extends Zend_Controller_Action */ public function calendarInitAction() { - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - if (is_null(Zend_Auth::getInstance()->getStorage()->read())) { header('HTTP/1.0 401 Unauthorized'); print _('You are not allowed to access this resource.'); @@ -97,6 +88,8 @@ class ApiController extends Zend_Controller_Action "timeInterval" => Application_Model_Preference::GetCalendarTimeInterval(), "weekStartDay" => Application_Model_Preference::GetWeekStartDay() ); + + $this->_helper->json->sendJson(array()); } /** @@ -107,10 +100,6 @@ class ApiController extends Zend_Controller_Action */ public function getMediaAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $fileId = $this->_getParam("file"); $media = Application_Model_StoredFile::RecallById($fileId); @@ -151,7 +140,7 @@ class ApiController extends Zend_Controller_Action } } - return; + $this->_helper->json->sendJson(array()); } /** @@ -359,22 +348,15 @@ class ApiController extends Zend_Controller_Action public function scheduleAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $data = Application_Model_Schedule::getSchedule(); header("Content-Type: application/json"); + echo json_encode($data, JSON_FORCE_OBJECT); - die(); + $this->_helper->json->sendJson($data, false, true); } public function notifyMediaItemStartPlayAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $media_id = $this->_getParam("media_id"); Logging::debug("Received notification of new media item start: $media_id"); Application_Model_Schedule::UpdateMediaPlayedStatus($media_id); @@ -404,8 +386,7 @@ class ApiController extends Zend_Controller_Action Logging::info($e); } - echo json_encode(array("status"=>1, "message"=>"")); - die(); + $this->_helper->json->sendJson(array("status"=>1, "message"=>"")); } public function recordedShowsAction() @@ -493,10 +474,6 @@ class ApiController extends Zend_Controller_Action public function mediaMonitorSetupAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $this->view->stor = Application_Model_MusicDir::getStorDir()->getDirectory(); $watchedDirs = Application_Model_MusicDir::getWatchedDirs(); @@ -612,8 +589,6 @@ class ApiController extends Zend_Controller_Action if ( !preg_match('/^md\d+$/', $k) ) { continue; } $info_json = json_decode($raw_json, $assoc = true); - Logging::info($info_json); - // Log invalid requests if ( !array_key_exists('mode', $info_json) ) { Logging::info("Received bad request(key=$k), no 'mode' parameter. Bad request is:"); @@ -940,38 +915,24 @@ class ApiController extends Zend_Controller_Action * out a message to pypo that a potential change has been made. */ public function getFilesWithoutReplayGainAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $dir_id = $this->_getParam('dir_id'); //connect to db and get get sql $rows = Application_Model_StoredFile::listAllFiles2($dir_id, 100); - echo json_encode($rows); - die(); + $this->_helper->json->sendJson($rows); } public function getFilesWithoutSilanValueAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - //connect to db and get get sql $rows = Application_Model_StoredFile::getAllFilesWithoutSilan(); - echo json_encode($rows); - die(); + $this->_helper->json->sendJson($rows); } public function updateReplayGainValueAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $request = $this->getRequest(); $data = json_decode($request->getParam('data')); @@ -983,16 +944,11 @@ class ApiController extends Zend_Controller_Action $file->save(); } - echo json_encode(array()); - die(); + $this->_helper->json->sendJson(array()); } public function updateCueValuesBySilanAction() { - // disable the view and the layout - $this->view->layout()->disableLayout(); - $this->_helper->viewRenderer->setNoRender(true); - $request = $this->getRequest(); $data = json_decode($request->getParam('data'), $assoc = true); @@ -1024,8 +980,7 @@ class ApiController extends Zend_Controller_Action $file->save(); } - echo json_encode(array()); - die(); + $this->_helper->json->sendJson(array()); } public function notifyWebstreamDataAction() @@ -1094,5 +1049,4 @@ class ApiController extends Zend_Controller_Action Application_Model_StreamSetting::SetListenerStatError($k, $v); } } - } diff --git a/airtime_mvc/application/controllers/PreferenceController.php b/airtime_mvc/application/controllers/PreferenceController.php index 77f615528..0ccb348a3 100644 --- a/airtime_mvc/application/controllers/PreferenceController.php +++ b/airtime_mvc/application/controllers/PreferenceController.php @@ -164,16 +164,25 @@ class PreferenceController extends Zend_Controller_Action foreach ($temp as $t) { $setting[$t['keyname']] = $t['value']; } + + $name_map = array('ogg' => 'Ogg Vorbis', + 'aacplus' => 'AAC+', + 'aac' => 'AAC', + 'opus' => 'Opus', + 'mp3' => 'MP3' + ); + // get predefined type and bitrate from pref table $temp_types = Application_Model_Preference::GetStreamType(); $stream_types = array(); foreach ($temp_types as $type) { - if (trim($type) == "ogg") { - $temp = "OGG/VORBIS"; + $type = strtolower(trim($type)); + if (isset($name_map[$type])) { + $name = $name_map[$type]; } else { - $temp = strtoupper(trim($type)); + $name = $type; } - $stream_types[trim($type)] = $temp; + $stream_types[$type] = $name; } $temp_bitrate = Application_Model_Preference::GetStreamBitrate(); diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 6ccc58e3f..f2fb9ff70 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -16,21 +16,21 @@ class ScheduleController extends Zend_Controller_Action ->addActionContext('edit-show', 'json') ->addActionContext('move-show', 'json') ->addActionContext('resize-show', 'json') - ->addActionContext('delete-show', 'json') + ->addActionContext('delete-show-instance', 'json') ->addActionContext('show-content-dialog', 'json') ->addActionContext('clear-show', 'json') ->addActionContext('get-current-playlist', 'json') ->addActionContext('remove-group', 'json') ->addActionContext('populate-show-form', 'json') - ->addActionContext('populate-show-instance-form', 'json') - ->addActionContext('cancel-show', 'json') + ->addActionContext('populate-repeating-show-instance-form', 'json') + ->addActionContext('delete-show', 'json') ->addActionContext('cancel-current-show', 'json') ->addActionContext('get-form', 'json') ->addActionContext('upload-to-sound-cloud', 'json') ->addActionContext('content-context-menu', 'json') ->addActionContext('set-time-scale', 'json') ->addActionContext('set-time-interval', 'json') - ->addActionContext('edit-show-instance', 'json') + ->addActionContext('edit-repeating-show-instance', 'json') ->addActionContext('dj-edit-show', 'json') ->addActionContext('calculate-duration', 'json') ->addActionContext('get-current-show', 'json') @@ -90,13 +90,14 @@ class ScheduleController extends Zend_Controller_Action $this->view->headLink()->appendStylesheet($baseUrl.'css/showbuilder.css?'.$CC_CONFIG['airtime_version']); //End Show builder JS/CSS requirements + $this->createShowFormAction(true); - Application_Model_Schedule::createNewFormSections($this->view); $user = Application_Model_User::getCurrentUser(); if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { $this->view->preloadShowForm = true; } + $this->view->addNewShow = true; $this->view->headScript()->appendScript( "var calendarPref = {};\n". "calendarPref.weekStart = ".Application_Model_Preference::GetWeekStartDay().";\n". @@ -111,16 +112,17 @@ class ScheduleController extends Zend_Controller_Action public function eventFeedAction() { + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); + $start = new DateTime($this->_getParam('start', null)); $start->setTimezone(new DateTimeZone("UTC")); $end = new DateTime($this->_getParam('end', null)); $end->setTimezone(new DateTimeZone("UTC")); - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - $editable = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); + $events = &Application_Model_Show::getFullCalendarEvents($start, $end, + $currentUser->isAdminOrPM()); - $events = &Application_Model_Show::getFullCalendarEvents($start, $end, $editable); $this->view->events = $events; } @@ -161,22 +163,16 @@ class ScheduleController extends Zend_Controller_Action { $deltaDay = $this->_getParam('day'); $deltaMin = $this->_getParam('min'); - $showInstanceId = $this->_getParam('showInstanceId'); - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - try { - $showInstance = new Application_Model_ShowInstance($showInstanceId); - } catch (Exception $e) { - $this->view->show_error = true; - - return false; - } - $error = $showInstance->moveShow($deltaDay, $deltaMin); + try { + $service_calendar = new Application_Service_CalendarService( + $this->_getParam('showInstanceId')); + } catch (Exception $e) { + $this->view->show_error = true; + return false; } + $error = $service_calendar->moveShow($deltaDay, $deltaMin); if (isset($error)) { $this->view->error = $error; } @@ -207,28 +203,17 @@ class ScheduleController extends Zend_Controller_Action } } - public function deleteShowAction() + public function deleteShowInstanceAction() { - $showInstanceId = $this->_getParam('id'); + $instanceId = $this->_getParam('id'); - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); + $service_show = new Application_Service_ShowService(); + $showId = $service_show->deleteShow($instanceId, true); - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - - try { - $showInstance = new Application_Model_ShowInstance($showInstanceId); - } catch (Exception $e) { - Logging::info($e->getMessage()); - $this->view->show_error = true; - - return false; - } - - $showInstance->delete(); - - $this->view->show_id = $showInstance->getShowId(); + if (!$showId) { + $this->view->show_error = true; } + $this->view->show_id = $showId; } public function uploadToSoundCloudAction() @@ -251,107 +236,11 @@ class ScheduleController extends Zend_Controller_Action public function makeContextMenuAction() { - $id = $this->_getParam('id'); - $menu = array(); - $epochNow = time(); - $baseUrl = Application_Common_OsPath::getBaseDir(); + $instanceId = $this->_getParam('instanceId'); - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - try { - $instance = new Application_Model_ShowInstance($id); - } catch (Exception $e) { - $this->view->show_error = true; + $service_calendar = new Application_Service_CalendarService($instanceId); - return false; - } - - $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - $isDJ = $user->isHostOfShow($instance->getShowId()); - - $showStartLocalDT = Application_Common_DateHelper::ConvertToLocalDateTime($instance->getShowInstanceStart()); - $showEndLocalDT = Application_Common_DateHelper::ConvertToLocalDateTime($instance->getShowInstanceEnd()); - - if ($instance->isRecorded() && $epochNow > $showEndLocalDT->getTimestamp()) { - - $file = $instance->getRecordedFile(); - $fileId = $file->getId(); - - $menu["view_recorded"] = array("name" => _("View Recorded File Metadata"), "icon" => "overview", - "url" => $baseUrl."library/edit-file-md/id/".$fileId); - } - - if ($epochNow < $showStartLocalDT->getTimestamp()) { - if ( ($isAdminOrPM || $isDJ) - && !$instance->isRecorded() - && !$instance->isRebroadcast()) { - - $menu["schedule"] = array("name"=> _("Add / Remove Content"), "icon" => "add-remove-content", - "url" => $baseUrl."showbuilder/builder-dialog/"); - - $menu["clear"] = array("name"=> _("Remove All Content"), "icon" => "remove-all-content", - "url" => $baseUrl."schedule/clear-show"); - } - } - - if (!$instance->isRecorded()) { - - $menu["content"] = array("name"=> _("Show Content"), "icon" => "overview", "url" => $baseUrl."schedule/show-content-dialog"); - } - - if ($showEndLocalDT->getTimestamp() <= $epochNow - && $instance->isRecorded() - && Application_Model_Preference::GetUploadToSoundcloudOption()) { - - $file = $instance->getRecordedFile(); - $fileId = $file->getId(); - $scid = $instance->getSoundCloudFileId(); - - if ($scid > 0) { - $url = $file->getSoundCloudLinkToFile(); - $menu["soundcloud_view"] = array("name" => _("View on Soundcloud"), "icon" => "soundcloud", "url" => $url); - } - - $text = is_null($scid) ? _('Upload to SoundCloud') : _('Re-upload to SoundCloud'); - $menu["soundcloud_upload"] = array("name"=> $text, "icon" => "soundcloud"); - } - - if ($showStartLocalDT->getTimestamp() <= $epochNow && - $epochNow < $showEndLocalDT->getTimestamp() && $isAdminOrPM) { - - if ($instance->isRecorded()) { - $menu["cancel_recorded"] = array("name"=> _("Cancel Current Show"), "icon" => "delete"); - } else { - - if (!$instance->isRebroadcast()) { - $menu["edit"] = array("name"=> _("Edit Show"), "icon" => "edit", "_type"=>"all", "url" => $baseUrl."Schedule/populate-show-form"); - } - - $menu["cancel"] = array("name"=> _("Cancel Current Show"), "icon" => "delete"); - } - } - - if ($epochNow < $showStartLocalDT->getTimestamp()) { - - if (!$instance->isRebroadcast() && $isAdminOrPM) { - $menu["edit"] = array("name"=> _("Edit Show"), "icon" => "edit", "_type"=>"all", "url" => $baseUrl."Schedule/populate-show-form"); - } - - if ($instance->getShow()->isRepeating() && $isAdminOrPM) { - - //create delete sub menu. - $menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "items" => array()); - - $menu["del"]["items"]["single"] = array("name"=> _("Delete This Instance"), "icon" => "delete", "url" => $baseUrl."schedule/delete-show"); - - $menu["del"]["items"]["following"] = array("name"=> _("Delete This Instance and All Following"), "icon" => "delete", "url" => $baseUrl."schedule/cancel-show"); - } elseif ($isAdminOrPM) { - - $menu["del"] = array("name"=> _("Delete"), "icon" => "delete", "url" => $baseUrl."schedule/delete-show"); - } - } - - $this->view->items = $menu; + $this->view->items = $service_calendar->makeContextMenu(); } public function clearShowAction() @@ -416,32 +305,6 @@ class ScheduleController extends Zend_Controller_Action $this->view->show_name = isset($show[0])?$show[0]["name"]:""; } - public function removeGroupAction() - { - $showInstanceId = $this->sched_sess->showInstanceId; - $group_id = $this->_getParam('groupId'); - - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - try { - $show = new Application_Model_ShowInstance($showInstanceId); - } catch (Exception $e) { - $this->view->show_error = true; - - return false; - } - - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)) || $user->isHostOfShow($show->getShowId())) { - $show->removeGroupFromShow($group_id); - } - - $this->view->showContent = $show->getShowContent(); - $this->view->timeFilled = $show->getTimeScheduled(); - $this->view->percentFilled = $show->getPercentScheduled(); - $this->view->chosen = $this->view->render('schedule/scheduled-content.phtml'); - unset($this->view->showContent); - } - public function showContentDialogAction() { $showInstanceId = $this->_getParam('id'); @@ -484,256 +347,66 @@ class ScheduleController extends Zend_Controller_Action unset($this->view->showContent); } - // we removed edit show instance option in menu item - // this feature is disabled in 2.1 and should be back in 2.2 - /*public function populateShowInstanceFormAction(){ - $formWhat = new Application_Form_AddShowWhat(); - $formWho = new Application_Form_AddShowWho(); - $formWhen = new Application_Form_AddShowWhen(); - $formRepeats = new Application_Form_AddShowRepeats(); - $formStyle = new Application_Form_AddShowStyle(); - $formLive = new Application_Form_AddShowLiveStream(); + public function populateRepeatingShowInstanceFormAction() + { + $showId = $this->_getParam('showId'); + $instanceId = $this->_getParam('instanceId'); + $service_showForm = new Application_Service_ShowFormService($showId, $instanceId); - $formWhat->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); + $forms = $this->createShowFormAction(); + + $service_showForm->delegateShowInstanceFormPopulation($forms); - $this->view->what = $formWhat; - $this->view->when = $formWhen; - $this->view->repeats = $formRepeats; - $this->view->who = $formWho; - $this->view->style = $formStyle; - $this->view->live = $formLive; $this->view->addNewShow = false; - - $showInstanceId = $this->_getParam('id'); - - $show_instance = CcShowInstancesQuery::create()->findPK($showInstanceId); - $show = new Application_Model_Show($show_instance->getDbShowId()); - - $starts_string = $show_instance->getDbStarts(); - $ends_string = $show_instance->getDbEnds(); - - $starts_datetime = new DateTime($starts_string, new DateTimeZone("UTC")); - $ends_datetime = new DateTime($ends_string, new DateTimeZone("UTC")); - - $starts_datetime->setTimezone(new DateTimeZone(date_default_timezone_get())); - $ends_datetime->setTimezone(new DateTimeZone(date_default_timezone_get())); - - $instance_duration = $starts_datetime->diff($ends_datetime); - - $formWhat->populate(array('add_show_id' => $show->getId(), - 'add_show_instance_id' => $showInstanceId, - 'add_show_name' => $show->getName(), - 'add_show_url' => $show->getUrl(), - 'add_show_genre' => $show->getGenre(), - 'add_show_description' => $show->getDescription())); - - $formWhen->populate(array('add_show_start_date' => $starts_datetime->format("Y-m-d"), - 'add_show_start_time' => $starts_datetime->format("H:i"), - 'add_show_end_date_no_repeat' => $ends_datetime->format("Y-m-d"), - 'add_show_end_time' => $ends_datetime->format("H:i"), - 'add_show_duration' => $instance_duration->format("%h"))); - - $formWhat->disable(); - $formWho->disable(); - $formWhen->disableRepeatCheckbox(); - $formRepeats->disable(); - $formStyle->disable(); - - //$formRecord->disable(); - //$formAbsoluteRebroadcast->disable(); - //$formRebroadcast->disable(); - - $this->view->action = "edit-show-instance"; + $this->view->action = "edit-repeating-show-instance"; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); - }*/ + } public function populateShowFormAction() { - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); - $showInstanceId = $this->_getParam('id'); - - $this->view->action = "edit-show"; - try { - $showInstance = new Application_Model_ShowInstance($showInstanceId); - } catch (Exception $e) { - $this->view->show_error = true; - - return false; - } - - $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - $isDJ = $user->isHostOfShow($showInstance->getShowId()); - - if (!($isAdminOrPM || $isDJ)) { - return; - } + $showId = $this->_getParam('showId'); + $instanceId = $this->_getParam('instanceId'); + $service_showForm = new Application_Service_ShowFormService($showId, $instanceId); + $isAdminOrPM = $currentUser->isAdminOrPM(); + /*$isHostOfShow = $currentUser->isHostOfShow($showId); // in case a user was once a dj and had been assigned to a show // but was then changed to an admin user we need to allow // the user to edit the show as an admin (CC-4925) - if ($isDJ && !$isAdminOrPM) { + if ($isHostOfShow && !$isAdminOrPM) { $this->view->action = "dj-edit-show"; - } + }*/ - $formWhat = new Application_Form_AddShowWhat(); - $formWho = new Application_Form_AddShowWho(); - $formWhen = new Application_Form_AddShowWhen(); - $formRepeats = new Application_Form_AddShowRepeats(); - $formStyle = new Application_Form_AddShowStyle(); - $formLive = new Application_Form_AddShowLiveStream(); + $forms = $this->createShowFormAction(); - $formWhat->removeDecorator('DtDdWrapper'); - $formWho->removeDecorator('DtDdWrapper'); - $formWhen->removeDecorator('DtDdWrapper'); - $formRepeats->removeDecorator('DtDdWrapper'); - $formStyle->removeDecorator('DtDdWrapper'); - - $this->view->what = $formWhat; - $this->view->when = $formWhen; - $this->view->repeats = $formRepeats; - $this->view->who = $formWho; - $this->view->style = $formStyle; - $this->view->live = $formLive; - $this->view->addNewShow = false; - - $show = new Application_Model_Show($showInstance->getShowId()); - - $formWhat->populate(array('add_show_id' => $show->getId(), - 'add_show_instance_id' => $showInstanceId, - 'add_show_name' => $show->getName(), - 'add_show_url' => $show->getUrl(), - 'add_show_genre' => $show->getGenre(), - 'add_show_description' => $show->getDescription())); - - $startsDateTime = new DateTime($show->getStartDate()." ".$show->getStartTime(), new DateTimeZone("UTC")); - $endsDateTime = new DateTime($show->getEndDate()." ".$show->getEndTime(), new DateTimeZone("UTC")); - - $startsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); - $endsDateTime->setTimezone(new DateTimeZone(date_default_timezone_get())); - - $formWhen->populate(array('add_show_start_date' => $startsDateTime->format("Y-m-d"), - 'add_show_start_time' => $startsDateTime->format("H:i"), - 'add_show_end_date_no_repeat' => $endsDateTime->format("Y-m-d"), - 'add_show_end_time' => $endsDateTime->format("H:i"), - 'add_show_duration' => $show->getDuration(true), - 'add_show_repeats' => $show->isRepeating() ? 1 : 0)); - - if ($show->isStartDateTimeInPast()) { - // for a non-repeating show, we should never allow user to change the start time. - // for the repeating show, we should allow because the form works as repeating template form - if (!$showInstance->getShow()->isRepeating()) { - $formWhen->disableStartDateAndTime(); - } else { - $nextFutureRepeatShow = $show->getNextFutureRepeatShowTime(); - $formWhen->getElement('add_show_start_date')->setValue($nextFutureRepeatShow["starts"]->format("Y-m-d")); - $formWhen->getElement('add_show_start_time')->setValue($nextFutureRepeatShow["starts"]->format("H:i")); - $formWhen->getElement('add_show_end_date_no_repeat')->setValue($nextFutureRepeatShow["ends"]->format("Y-m-d")); - $formWhen->getElement('add_show_end_time')->setValue($nextFutureRepeatShow["ends"]->format("H:i")); - } - } - - //need to get the days of the week in the php timezone (for the front end). - $days = array(); - $showDays = CcShowDaysQuery::create()->filterByDbShowId($showInstance->getShowId())->find(); - foreach ($showDays as $showDay) { - $showStartDay = new DateTime($showDay->getDbFirstShow(), new DateTimeZone($showDay->getDbTimezone())); - $showStartDay->setTimezone(new DateTimeZone(date_default_timezone_get())); - array_push($days, $showStartDay->format('w')); - } - - $displayedEndDate = new DateTime($show->getRepeatingEndDate(), new DateTimeZone($showDays[0]->getDbTimezone())); - $displayedEndDate->sub(new DateInterval("P1D"));//end dates are stored non-inclusively. - $displayedEndDate->setTimezone(new DateTimeZone(date_default_timezone_get())); - - $formRepeats->populate(array('add_show_repeat_type' => $show->getRepeatType(), - 'add_show_day_check' => $days, - 'add_show_end_date' => $displayedEndDate->format("Y-m-d"), - 'add_show_no_end' => ($show->getRepeatingEndDate() == ''))); - - $hosts = array(); - $showHosts = CcShowHostsQuery::create()->filterByDbShow($showInstance->getShowId())->find(); - foreach ($showHosts as $showHost) { - array_push($hosts, $showHost->getDbHost()); - } - $formWho->populate(array('add_show_hosts' => $hosts)); - $formStyle->populate(array('add_show_background_color' => $show->getBackgroundColor(), - 'add_show_color' => $show->getColor())); - - $formLive->populate($show->getLiveStreamInfo()); - - $formRecord = new Application_Form_AddShowRR(); - $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); - $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); - - $formRecord->removeDecorator('DtDdWrapper'); - $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); - $formRebroadcast->removeDecorator('DtDdWrapper'); - - $this->view->rr = $formRecord; - $this->view->absoluteRebroadcast = $formAbsoluteRebroadcast; - $this->view->rebroadcast = $formRebroadcast; - - $formRecord->populate(array('add_show_record' => $show->isRecorded(), - 'add_show_rebroadcast' => $show->isRebroadcast())); - - $formRecord->getElement('add_show_record')->setOptions(array('disabled' => true)); - - - - $rebroadcastsRelative = $show->getRebroadcastsRelative(); - $rebroadcastFormValues = array(); - $i = 1; - foreach ($rebroadcastsRelative as $rebroadcast) { - $rebroadcastFormValues["add_show_rebroadcast_date_$i"] = $rebroadcast['day_offset']; - $rebroadcastFormValues["add_show_rebroadcast_time_$i"] = Application_Common_DateHelper::removeSecondsFromTime($rebroadcast['start_time']); - $i++; - } - $formRebroadcast->populate($rebroadcastFormValues); - - $rebroadcastsAbsolute = $show->getRebroadcastsAbsolute(); - $rebroadcastAbsoluteFormValues = array(); - $i = 1; - foreach ($rebroadcastsAbsolute as $rebroadcast) { - $rebroadcastAbsoluteFormValues["add_show_rebroadcast_date_absolute_$i"] = $rebroadcast['start_date']; - $rebroadcastAbsoluteFormValues["add_show_rebroadcast_time_absolute_$i"] = $rebroadcast['start_time']; - $i++; - } - $formAbsoluteRebroadcast->populate($rebroadcastAbsoluteFormValues); - if (!$isAdminOrPM) { - $formRecord->disable(); - $formAbsoluteRebroadcast->disable(); - $formRebroadcast->disable(); - } + $service_showForm->delegateShowFormPopulation($forms); if (!$isAdminOrPM) { - $formWhat->disable(); - $formWho->disable(); - $formWhen->disable(); - $formRepeats->disable(); - $formStyle->disable(); + foreach ($forms as $form) { + $form->disable(); + } } + $this->view->action = "edit-show"; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->view->entries = 5; } public function getFormAction() { - $user = Application_Model_User::getCurrentUser(); + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - Application_Model_Schedule::createNewFormSections($this->view); + if ($currentUser->isAdminOrPM()) { + $this->createShowFormAction(true); $this->view->form = $this->view->render('schedule/add-show-form.phtml'); } } - public function djEditShowAction() + /*public function djEditShowAction() { $js = $this->_getParam('data'); $data = array(); @@ -751,30 +424,9 @@ class ScheduleController extends Zend_Controller_Action $show->setCustomPassword($data["custom_password"]); $this->view->edit = true; - } - - /*public function editShowInstanceAction(){ - $js = $this->_getParam('data'); - $data = array(); - - //need to convert from serialized jQuery array. - foreach ($js as $j) { - $data[$j["name"]] = $j["value"]; - } - - $success = Application_Model_Schedule::updateShowInstance($data, $this); - if ($success) { - $this->view->addNewShow = true; - $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); - } else { - $this->view->addNewShow = false; - $this->view->form = $this->view->render('schedule/add-show-form.phtml'); - } }*/ - public function editShowAction() - { - //1) Get add_show_start_date since it might not have been sent + public function editRepeatingShowInstanceAction(){ $js = $this->_getParam('data'); $data = array(); @@ -783,6 +435,53 @@ class ScheduleController extends Zend_Controller_Action $data[$j["name"]] = $j["value"]; } + $data['add_show_hosts'] = $this->_getParam('hosts'); + + $service_showForm = new Application_Service_ShowFormService( + $data["add_show_id"], $data["add_show_instance_id"]); + $service_show = new Application_Service_ShowService(null, $data); + + $forms = $this->createShowFormAction(); + + list($data, $validateStartDate, $validateStartTime, $originalShowStartDateTime) = + $service_showForm->preEditShowValidationCheck($data); + + if ($service_showForm->validateShowForms($forms, $data, $validateStartDate, + $originalShowStartDateTime, true, $data["add_show_instance_id"])) { + + $service_show->createShowFromRepeatingInstance($data); + + $this->view->addNewShow = true; + $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); + } else { + if (!$validateStartDate) { + $this->view->when->getElement('add_show_start_date')->setOptions(array('disabled' => true)); + } + if (!$validateStartTime) { + $this->view->when->getElement('add_show_start_time')->setOptions(array('disabled' => true)); + } + $this->view->rr->getElement('add_show_record')->setOptions(array('disabled' => true)); + $this->view->addNewShow = false; + $this->view->action = "edit-show"; + $this->view->form = $this->view->render('schedule/add-show-form.phtml'); + } + } + + public function editShowAction() + { + $js = $this->_getParam('data'); + $data = array(); + + //need to convert from serialized jQuery array. + foreach ($js as $j) { + $data[$j["name"]] = $j["value"]; + } + + $service_showForm = new Application_Service_ShowFormService( + $data["add_show_id"]); + $service_show = new Application_Service_ShowService(null, $data, true); + + //TODO: move this to js $data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_day_check'] = $this->_getParam('days'); @@ -790,43 +489,16 @@ class ScheduleController extends Zend_Controller_Action $data['add_show_day_check'] = null; } - $show = new Application_Model_Show($data['add_show_id']); + $forms = $this->createShowFormAction(); - $validateStartDate = true; - $validateStartTime = true; - if (!array_key_exists('add_show_start_date', $data)) { - //Changing the start date was disabled, since the - //array key does not exist. We need to repopulate this entry from the db. - //The start date will be returned in UTC time, so lets convert it to local time. - $dt = Application_Common_DateHelper::ConvertToLocalDateTime($show->getStartDateAndTime()); - $data['add_show_start_date'] = $dt->format("Y-m-d"); + list($data, $validateStartDate, $validateStartTime, $originalShowStartDateTime) = + $service_showForm->preEditShowValidationCheck($data); - if (!array_key_exists('add_show_start_time', $data)) { - $data['add_show_start_time'] = $dt->format("H:i"); - $validateStartTime = false; - } - $validateStartDate = false; - } - $data['add_show_record'] = $show->isRecorded(); + if ($service_showForm->validateShowForms($forms, $data, $validateStartDate, + $originalShowStartDateTime, true, $data["add_show_instance_id"])) { - if ($show->isRepeating()) { - $nextFutureRepeatShow = $show->getNextFutureRepeatShowTime(); - $originalShowStartDateTime = $nextFutureRepeatShow["starts"]; - } else { - $originalShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime( - $show->getStartDateAndTime()); - } + $service_show->addUpdateShow($data); - $success = Application_Model_Schedule::addUpdateShow($data, $this, - $validateStartDate, $originalShowStartDateTime, true, - $data['add_show_instance_id']); - - if ($success) { - $scheduler = new Application_Model_Scheduler(); - $showInstances = CcShowInstancesQuery::create()->filterByDbShowId($data['add_show_id'])->find(); - foreach ($showInstances as $si) { - $scheduler->removeGaps($si->getDbId()); - } $this->view->addNewShow = true; $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); } else { @@ -845,6 +517,9 @@ class ScheduleController extends Zend_Controller_Action public function addShowAction() { + $service_showForm = new Application_Service_ShowFormService(null); + //$service_show = new Application_Service_ShowService(); + $js = $this->_getParam('data'); $data = array(); @@ -853,6 +528,9 @@ class ScheduleController extends Zend_Controller_Action $data[$j["name"]] = $j["value"]; } + $service_show = new Application_Service_ShowService(null, $data); + + // TODO: move this to js $data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_day_check'] = $this->_getParam('days'); @@ -860,42 +538,60 @@ class ScheduleController extends Zend_Controller_Action $data['add_show_day_check'] = null; } - $validateStartDate = true; - $success = Application_Model_Schedule::addUpdateShow($data, $this, - $validateStartDate); + $forms = $this->createShowFormAction(); + + $this->view->addNewShow = true; + + if ($service_showForm->validateShowForms($forms, $data)) { + $service_show->addUpdateShow($data); + + $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); + //send new show forms to the user + $this->createShowFormAction(true); - if ($success) { - $this->view->addNewShow = true; - $this->view->newForm = $this->view->render( - 'schedule/add-show-form.phtml'); Logging::debug("Show creation succeeded"); } else { - $this->view->addNewShow = true; - $this->view->form = $this->view->render( - 'schedule/add-show-form.phtml'); + $this->view->form = $this->view->render('schedule/add-show-form.phtml'); Logging::debug("Show creation failed"); } } - public function cancelShowAction() + public function createShowFormAction($populateDefaults=false) { - $user = Application_Model_User::getCurrentUser(); + $service_showForm = new Application_Service_ShowFormService(); - if ($user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER))) { - $showInstanceId = $this->_getParam('id'); + $forms = $service_showForm->createShowForms(); - try { - $showInstance = new Application_Model_ShowInstance($showInstanceId); - } catch (Exception $e) { - $this->view->show_error = true; - - return false; - } - $show = new Application_Model_Show($showInstance->getShowId()); - - $show->cancelShow($showInstance->getShowInstanceStart()); - $this->view->show_id = $showInstance->getShowId(); + // populate forms with default values + if ($populateDefaults) { + $service_showForm->populateNewShowForms( + $forms["what"], $forms["when"], $forms["repeats"]); } + + $this->view->what = $forms["what"]; + $this->view->when = $forms["when"]; + $this->view->repeats = $forms["repeats"]; + $this->view->live = $forms["live"]; + $this->view->rr = $forms["record"]; + $this->view->absoluteRebroadcast = $forms["abs_rebroadcast"]; + $this->view->rebroadcast = $forms["rebroadcast"]; + $this->view->who = $forms["who"]; + $this->view->style = $forms["style"]; + + return $forms; + } + + public function deleteShowAction() + { + $instanceId = $this->_getParam('id'); + + $service_show = new Application_Service_ShowService(); + $showId = $service_show->deleteShow($instanceId); + + if (!$showId) { + $this->view->show_error = true; + } + $this->view->show_id = $showId; } public function cancelCurrentShowAction() @@ -962,32 +658,9 @@ class ScheduleController extends Zend_Controller_Action public function calculateDurationAction() { - $startParam = $this->_getParam('startTime'); - $endParam = $this->_getParam('endTime'); - - try { - $startDateTime = new DateTime($startParam); - $endDateTime = new DateTime($endParam); - - $UTCStartDateTime = $startDateTime->setTimezone(new DateTimeZone('UTC')); - $UTCEndDateTime = $endDateTime->setTimezone(new DateTimeZone('UTC')); - - $duration = $UTCEndDateTime->diff($UTCStartDateTime); - - $day = intval($duration->format('%d')); - if ($day > 0) { - $hour = intval($duration->format('%h')); - $min = intval($duration->format('%i')); - $hour += $day * 24; - $hour = min($hour, 99); - $sign = $duration->format('%r'); - $result = sprintf('%s%02dh %02dm', $sign, $hour, $min); - } else { - $result = $duration->format('%r%Hh %Im'); - } - } catch (Exception $e) { - $result = "Invalid Date"; - } + $service_showForm = new Application_Service_ShowFormService(); + $result = $service_showForm->calculateDuration($this->_getParam('startTime'), + $this->_getParam('endTime')); echo Zend_Json::encode($result); exit(); diff --git a/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php b/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php index a2f5b5cf3..4c43000c0 100644 --- a/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php +++ b/airtime_mvc/application/forms/AddShowAbsoluteRebroadcastDates.php @@ -40,6 +40,14 @@ class Application_Form_AddShowAbsoluteRebroadcastDates extends Zend_Form_SubForm } } + public function isValid($formData) { + if (parent::isValid($formData)) { + return $this->checkReliantFields($formData); + } else { + return false; + } + } + public function checkReliantFields($formData) { $noError = true; diff --git a/airtime_mvc/application/forms/AddShowRebroadcastDates.php b/airtime_mvc/application/forms/AddShowRebroadcastDates.php index 74725c98c..58d6af872 100644 --- a/airtime_mvc/application/forms/AddShowRebroadcastDates.php +++ b/airtime_mvc/application/forms/AddShowRebroadcastDates.php @@ -45,6 +45,14 @@ class Application_Form_AddShowRebroadcastDates extends Zend_Form_SubForm } } + public function isValid($formData) { + if (parent::isValid($formData)) { + return $this->checkReliantFields($formData); + } else { + return false; + } + } + public function checkReliantFields($formData) { $noError = true; diff --git a/airtime_mvc/application/forms/AddShowRepeats.php b/airtime_mvc/application/forms/AddShowRepeats.php index f0c2609e2..d09b5284a 100644 --- a/airtime_mvc/application/forms/AddShowRepeats.php +++ b/airtime_mvc/application/forms/AddShowRepeats.php @@ -5,6 +5,11 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm public function init() { + + $linked = new Zend_Form_Element_Checkbox("add_show_linked"); + $linked->setLabel(_("Link:")); + $this->addElement($linked); + //Add type select $this->addElement('select', 'add_show_repeat_type', array( 'required' => true, @@ -35,6 +40,15 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm ), )); + $repeatMonthlyType = new Zend_Form_Element_Radio("add_show_monthly_repeat_type"); + $repeatMonthlyType + ->setLabel(_("Repeat By:")) + ->setRequired(true) + ->setMultiOptions( + array(2 => _("day of the month"), 3 => _("day of the week"))) + ->setValue(2); + $this->addElement($repeatMonthlyType); + // Add end date element $this->addElement('text', 'add_show_end_date', array( 'label' => _('Date End:'), @@ -66,6 +80,14 @@ class Application_Form_AddShowRepeats extends Zend_Form_SubForm } } + public function isValid($formData) { + if (parent::isValid($formData)) { + return $this->checkReliantFields($formData); + } else { + return false; + } + } + public function checkReliantFields($formData) { if (!$formData['add_show_no_end']) { diff --git a/airtime_mvc/application/forms/AddShowWhen.php b/airtime_mvc/application/forms/AddShowWhen.php index 92873f153..007852ba4 100644 --- a/airtime_mvc/application/forms/AddShowWhen.php +++ b/airtime_mvc/application/forms/AddShowWhen.php @@ -87,6 +87,16 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm } + public function isWhenFormValid($formData, $validateStartDate, $originalStartDate, + $update, $instanceId) { + if (parent::isValid($formData)) { + return self::checkReliantFields($formData, $validateStartDate, + $originalStartDate, $update, $instanceId); + } else { + return false; + } + } + public function checkReliantFields($formData, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null) { $valid = true; @@ -285,7 +295,8 @@ class Application_Form_AddShowWhen extends Zend_Form_SubForm $rebroadcastShowStart->setTimezone(new DateTimeZone('UTC')); $rebroadcastShowEnd = clone $rebroadcastShowStart; $rebroadcastShowEnd->add(new DateInterval($durationToAdd)); - $overlapping = Application_Model_Schedule::checkOverlappingShows($rebroadcastShowStart, $rebroadcastShowEnd, $update, $instanceId); + $overlapping = Application_Model_Schedule::checkOverlappingShows($rebroadcastShowStart, + $rebroadcastShowEnd, $update, null, $formData["add_show_id"]); if ($overlapping) { $valid = false; $this->getElement('add_show_duration')->setErrors(array(_('Cannot schedule overlapping shows'))); diff --git a/airtime_mvc/application/models/Schedule.php b/airtime_mvc/application/models/Schedule.php index c3a2822ad..b6cb20600 100644 --- a/airtime_mvc/application/models/Schedule.php +++ b/airtime_mvc/application/models/Schedule.php @@ -385,6 +385,7 @@ SELECT showt.name AS show_name, showt.color AS show_color, showt.background_color AS show_background_color, showt.id AS show_id, + showt.linked AS linked, si.starts AS si_starts, si.ends AS si_ends, si.time_filled AS si_time_filled, @@ -961,7 +962,7 @@ SQL; Application_Common_Database::prepareAndExecute($sql, array(':file_id'=>$fileId), 'execute'); } - public static function createNewFormSections($p_view) + /*public static function createNewFormSections($p_view) { $formWhat = new Application_Form_AddShowWhat(); $formWho = new Application_Form_AddShowWho(); @@ -1006,7 +1007,7 @@ SQL; $p_view->absoluteRebroadcast = $formAbsoluteRebroadcast; $p_view->rebroadcast = $formRebroadcast; $p_view->addNewShow = true; - } + }*/ /* This function is responsible for handling the case where an individual * show instance in a repeating show was edited (via the context menu in the Calendar). @@ -1089,7 +1090,7 @@ SQL; * Another clean-up is to move all the form manipulation to the proper form class..... * -Martin */ - public static function addUpdateShow($data, $controller, $validateStartDate, + /*public static function addUpdateShow($data, $controller, $validateStartDate, $originalStartDate=null, $update=false, $instanceId=null) { $userInfo = Zend_Auth::getInstance()->getStorage()->read(); @@ -1141,13 +1142,13 @@ SQL; $data["add_show_duration"] = $hValue.":".$mValue; - $formRecord = new Application_Form_AddShowRR(); - $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); - $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); - $formRecord->removeDecorator('DtDdWrapper'); - $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); - $formRebroadcast->removeDecorator('DtDdWrapper'); + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); $record = $formRecord->isValid($data); @@ -1157,18 +1158,18 @@ SQL; if ($repeats) { $repeats = $formRepeats->checkReliantFields($data); } - $formAbsoluteRebroadcast->reset(); - //make it valid, results don't matter anyways. - $rebroadAb = 1; + $formAbsoluteRebroadcast->reset(); + //make it valid, results don't matter anyways. + $rebroadAb = 1; - if ($data["add_show_rebroadcast"]) { - $rebroad = $formRebroadcast->isValid($data); - if ($rebroad) { - $rebroad = $formRebroadcast->checkReliantFields($data); - } - } else { - $rebroad = 1; + if ($data["add_show_rebroadcast"]) { + $rebroad = $formRebroadcast->isValid($data); + if ($rebroad) { + $rebroad = $formRebroadcast->checkReliantFields($data); } + } else { + $rebroad = 1; + } } else { $repeats = 1; $formRebroadcast->reset(); @@ -1221,15 +1222,14 @@ SQL; $controller->view->who = $formWho; $controller->view->style = $formStyle; $controller->view->live = $formLive; - - $controller->view->rr = $formRecord; - $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; - $controller->view->rebroadcast = $formRebroadcast; + $controller->view->rr = $formRecord; + $controller->view->absoluteRebroadcast = $formAbsoluteRebroadcast; + $controller->view->rebroadcast = $formRebroadcast; //$controller->view->addNewShow = !$editShow; //$controller->view->form = $controller->view->render('schedule/add-show-form.phtml'); return false; } - } + }*/ public static function checkOverlappingShows($show_start, $show_end, $update=false, $instanceId=null, $showId=null) @@ -1258,19 +1258,19 @@ WHERE (ends <= :show_end1 AND date(starts) >= (date(:show_end3) - INTERVAL '2 days') AND modified_instance = FALSE SQL; - if (is_null($showId)) { - $sql .= <<checkUserPermissions = $value; } + private function validateItemMove($itemsToMove, $destination) + { + $destinationInstanceId = $destination["instance"]; + $destinationCcShowInstance = CcShowInstancesQuery::create() + ->findPk($destinationInstanceId); + $isDestinationLinked = $destinationCcShowInstance->getCcShow()->isLinked(); + + foreach ($itemsToMove as $itemToMove) { + $sourceInstanceId = $itemToMove["instance"]; + $ccShowInstance = CcShowInstancesQuery::create() + ->findPk($sourceInstanceId); + + //does the item being moved belong to a linked show + $isSourceLinked = $ccShowInstance->getCcShow()->isLinked(); + + if ($isDestinationLinked && !$isSourceLinked) { + throw new Exception("Cannot move items into linked shows"); + } elseif (!$isDestinationLinked && $isSourceLinked) { + throw new Exception("Cannot move items out of linked shows"); + } elseif ($isSourceLinked && $sourceInstanceId != $destinationInstanceId) { + throw new Exception(_("Cannot move items out of linked shows")); + } + } + } + /* * make sure any incoming requests for scheduling are ligit. * * @param array $items, an array containing pks of cc_schedule items. */ - private function validateRequest($items) + private function validateRequest($items, $addAction=false) { + //$items is where tracks get inserted (they are schedule locations) + $nowEpoch = floatval($this->nowDT->format("U.u")); for ($i = 0; $i < count($items); $i++) { @@ -59,9 +86,11 @@ class Application_Model_Scheduler //could be added to the beginning of a show, which sends id = 0; if ($id > 0) { + //schedule_id of where we are inserting after? $schedInfo[$id] = $items[$i]["instance"]; } + //format is instance_id => timestamp $instanceInfo[$items[$i]["instance"]] = $items[$i]["timestamp"]; } @@ -104,7 +133,7 @@ class Application_Model_Scheduler if ($this->checkUserPermissions && $this->user->canSchedule($show->getDbId()) === false) { throw new Exception(sprintf(_("You are not allowed to schedule show %s."), $show->getDbName())); } - + if ($instance->getDbRecord()) { throw new Exception(_("You cannot add files to recording shows.")); } @@ -121,6 +150,28 @@ class Application_Model_Scheduler Logging::info("ts {$ts} last sched {$lastSchedTs}"); throw new OutDatedScheduleException(sprintf(_("The show %s has been previously updated!"), $show->getDbName())); } + + /* + * Does the afterItem belong to a show that is linked AND + * currently playing? + * If yes, throw an exception + */ + if ($addAction) { + $ccShow = $instance->getCcShow(); + if ($ccShow->isLinked()) { + //get all the linked shows instances and check if + //any of them are currently playing + $ccShowInstances = $ccShow->getCcShowInstancess(); + $timeNowUTC = gmdate("Y-m-d H:i:s"); + foreach ($ccShowInstances as $ccShowInstance) { + + if ($ccShowInstance->getDbStarts() <= $timeNowUTC && + $ccShowInstance->getDbEnds() > $timeNowUTC) { + throw new Exception(_("Content in linked shows must be scheduled before or after any one is broadcasted")); + } + } + } + } } } @@ -380,135 +431,227 @@ class Application_Model_Scheduler $schedule->save($this->con); } - /* - * @param array $scheduledIds - * @param array $fileIds - * @param array $playlistIds + /** + * + * Enter description here ... + * @param $scheduleItems + * cc_schedule items, where the items get inserted after + * @param $filesToInsert + * array of schedule item info, what gets inserted into cc_schedule + * @param $adjustSched */ - private function insertAfter($scheduleItems, $schedFiles, $adjustSched = true, $mediaItems = null) + private function insertAfter($scheduleItems, $mediaItems, $filesToInsert=null, $adjustSched=true, $moveAction=false) { try { $affectedShowInstances = array(); - - //dont want to recalculate times for moved items. + + //dont want to recalculate times for moved items + //only moved items have a sched_id $excludeIds = array(); - foreach ($schedFiles as $file) { - if (isset($file["sched_id"])) { - $excludeIds[] = intval($file["sched_id"]); - } - } $startProfile = microtime(true); + $temp = array(); + $instance = null; + /* Items in shows are ordered by position number. We need to know + * the position when adding/moving items in linked shows so they are + * added or moved in the correct position + */ + $pos = 0; + foreach ($scheduleItems as $schedule) { $id = intval($schedule["id"]); - - // if mediaItmes is passed in, we want to create contents - // at the time of insert. This is for dyanmic blocks or - // playlist that contains dynamic blocks - if ($mediaItems != null) { - $schedFiles = array(); - foreach ($mediaItems as $media) { - $schedFiles = array_merge($schedFiles, $this->retrieveMediaFiles($media["id"], $media["type"])); + + /* Find out if the show where the cursor position (where an item will + * be inserted) is located is linked or not. If the show is linked, + * we need to make sure there isn't another cursor selection in one of it's + * linked shows. If there is that will cause a duplication, in the least, + * of inserted items + */ + if ($id != 0) { + $ccSchedule = CcScheduleQuery::create()->findPk($schedule["id"]); + $ccShowInstance = CcShowInstancesQuery::create()->findPk($ccSchedule->getDbInstanceId()); + $ccShow = $ccShowInstance->getCcShow(); + if ($ccShow->isLinked()) { + $unique = $ccShow->getDbId() . $ccSchedule->getDbPosition(); + if (!in_array($unique, $temp)) { + $temp[] = $unique; + } else { + continue; + } + } + } else { + $ccShowInstance = CcShowInstancesQuery::create()->findPk($schedule["instance"]); + $ccShow = $ccShowInstance->getccShow(); + if ($ccShow->isLinked()) { + $unique = $ccShow->getDbId() . "a"; + if (!in_array($unique, $temp)) { + $temp[] = $unique; + } else { + continue; + } } } - - if ($id !== 0) { - $schedItem = CcScheduleQuery::create()->findPK($id, $this->con); - $instance = $schedItem->getCcShowInstances($this->con); - $schedItemEndDT = $schedItem->getDbEnds(null); - $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); - } - //selected empty row to add after - else { + /* If the show where the cursor position is located is linked + * we need to insert the items for each linked instance belonging + * to that show + */ + $instances = $this->getInstances($schedule["instance"]); + foreach($instances as $instance) { + if ($id !== 0) { + $schedItem = CcScheduleQuery::create()->findPK($id, $this->con); + /* We use the selected cursor's position to find the same + * positions in every other linked instance + */ + $pos = $schedItem->getDbPosition(); - $instance = CcShowInstancesQuery::create()->findPK($schedule["instance"], $this->con); + $ccSchedule = CcScheduleQuery::create() + ->filterByDbInstanceId($instance->getDbId()) + ->filterByDbPosition($pos) + ->findOne(); - $showStartDT = $instance->getDbStarts(null); - $nextStartDT = $this->findNextStartTime($showStartDT, $instance); - } + //$schedItemEndDT = $schedItem->getDbEnds(null); + $schedItemEndDT = $ccSchedule->getDbEnds(null); + $nextStartDT = $this->findNextStartTime($schedItemEndDT, $instance); - if (!in_array($instance->getDbId(), $affectedShowInstances)) { - $affectedShowInstances[] = $instance->getDbId(); - } + $pos++; + } + //selected empty row to add after + else { + $showStartDT = $instance->getDbStarts(null); + $nextStartDT = $this->findNextStartTime($showStartDT, $instance); - if ($adjustSched === true) { - - $pstart = microtime(true); - - $followingSchedItems = CcScheduleQuery::create() - ->filterByDBStarts($nextStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL) - ->filterByDbInstanceId($instance->getDbId()) - ->filterByDbId($excludeIds, Criteria::NOT_IN) - ->orderByDbStarts() - ->find($this->con); - - $pend = microtime(true); - Logging::debug("finding all following items."); - Logging::debug(floatval($pend) - floatval($pstart)); - } - - foreach ($schedFiles as $file) { - $endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']); - - //item existed previously and is being moved. - //need to keep same id for resources if we want REST. - if (isset($file['sched_id'])) { - $sched = CcScheduleQuery::create()->findPK($file['sched_id'], $this->con); - } else { - $sched = new CcSchedule(); + //show is empty so start position counter at 0 + $pos = 0; } - // default fades are in seconds - // we need to convert to '00:00:00' format - $file['fadein'] = Application_Common_DateHelper::secondsToPlaylistTime($file['fadein']); - $file['fadeout'] = Application_Common_DateHelper::secondsToPlaylistTime($file['fadeout']); - - $sched->setDbStarts($nextStartDT) - ->setDbEnds($endTimeDT) - ->setDbCueIn($file['cuein']) - ->setDbCueOut($file['cueout']) - ->setDbFadeIn($file['fadein']) - ->setDbFadeOut($file['fadeout']) - ->setDbClipLength($file['cliplength']) - ->setDbInstanceId($instance->getDbId()); - - switch ($file["type"]) { - case 0: - $sched->setDbFileId($file['id']); - break; - case 1: - $sched->setDbStreamId($file['id']); - break; - default: break; + if (!in_array($instance->getDbId(), $affectedShowInstances)) { + $affectedShowInstances[] = $instance->getDbId(); } - $sched->save($this->con); + /* + * $adjustSched is true if there are schedule items + * following the item just inserted, per show instance + */ + if ($adjustSched === true) { - $nextStartDT = $endTimeDT; - } + $pstart = microtime(true); - if ($adjustSched === true) { + $initalStartDT = clone $nextStartDT; - $pstart = microtime(true); + $pend = microtime(true); + Logging::debug("finding all following items."); + Logging::debug(floatval($pend) - floatval($pstart)); + } - //recalculate the start/end times after the inserted items. - foreach ($followingSchedItems as $item) { + if (is_null($filesToInsert)) { + $filesToInsert = array(); + foreach ($mediaItems as $media) { + $filesToInsert = array_merge($filesToInsert, $this->retrieveMediaFiles($media["id"], $media["type"])); + } + } + foreach ($filesToInsert as $file) { + //item existed previously and is being moved. + //need to keep same id for resources if we want REST. + if (isset($file['sched_id'])) { + $sched = CcScheduleQuery::create()->findPk($file["sched_id"]); - $endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength()); + $excludeIds[] = intval($sched->getDbId()); + + $file["cliplength"] = $sched->getDbClipLength(); + $file["cuein"] = $sched->getDbCueIn(); + $file["cueout"] = $sched->getDbCueOut(); + $file["fadein"] = $sched->getDbFadeIn(); + $file["fadeout"] = $sched->getDbFadeOut(); + } else { + $sched = new CcSchedule(); + } + + $endTimeDT = $this->findEndTime($nextStartDT, $file['cliplength']); + // default fades are in seconds + // we need to convert to '00:00:00' format + $file['fadein'] = Application_Common_DateHelper::secondsToPlaylistTime($file['fadein']); + $file['fadeout'] = Application_Common_DateHelper::secondsToPlaylistTime($file['fadeout']); + + $sched->setDbStarts($nextStartDT) + ->setDbEnds($endTimeDT) + ->setDbCueIn($file['cuein']) + ->setDbCueOut($file['cueout']) + ->setDbFadeIn($file['fadein']) + ->setDbFadeOut($file['fadeout']) + ->setDbClipLength($file['cliplength']) + ->setDbPosition($pos); + //->setDbInstanceId($instance->getDbId()); + if (!$moveAction) { + $sched->setDbInstanceId($instance->getDbId()); + } + + switch ($file["type"]) { + case 0: + $sched->setDbFileId($file['id']); + break; + case 1: + $sched->setDbStreamId($file['id']); + break; + default: break; + } + + $sched->save($this->con); - $item->setDbStarts($nextStartDT); - $item->setDbEnds($endTimeDT); - $item->save($this->con); $nextStartDT = $endTimeDT; + $pos++; + + }//all files have been inserted/moved + + // update is_scheduled flag for each cc_file + foreach ($filesToInsert as $file) { + $db_file = CcFilesQuery::create()->findPk($file['id'], $this->con); + $db_file->setDbIsScheduled(true); + $db_file->save($this->con); + } + /* Reset files to insert so we can get a new set of files. We have + * to do this in case we are inserting a dynamic block + */ + if (!$moveAction) { + $filesToInsert = null; } - $pend = microtime(true); - Logging::debug("adjusting all following items."); - Logging::debug(floatval($pend) - floatval($pstart)); - } - } + /* If we are adjusting start and end times for items + * after the insert location, we need to exclude the + * schedule item we just inserted because it has correct + * start and end times*/ + $excludeIds[] = $sched->getDbId(); + + if ($adjustSched === true) { + $followingSchedItems = CcScheduleQuery::create() + ->filterByDBStarts($initalStartDT->format("Y-m-d H:i:s.u"), Criteria::GREATER_EQUAL) + ->filterByDbInstanceId($instance->getDbId()) + ->filterByDbId($excludeIds, Criteria::NOT_IN) + ->orderByDbStarts() + ->find($this->con); + + $pstart = microtime(true); + + //recalculate the start/end times after the inserted items. + foreach ($followingSchedItems as $item) { + $endTimeDT = $this->findEndTime($nextStartDT, $item->getDbClipLength()); + + $item->setDbStarts($nextStartDT); + $item->setDbEnds($endTimeDT); + $item->setDbPosition($pos); + $item->save($this->con); + $nextStartDT = $endTimeDT; + $pos++; + } + + $pend = microtime(true); + Logging::debug("adjusting all following items."); + Logging::debug(floatval($pend) - floatval($pstart)); + } + }//for each instance + + }//for each schedule location $endProfile = microtime(true); Logging::debug("finished adding scheduled items."); @@ -525,13 +668,6 @@ class Application_Model_Scheduler $instance->updateScheduleStatus($this->con); } - // update is_scheduled flag for each cc_file - foreach ($schedFiles as $file) { - $db_file = CcFilesQuery::create()->findPk($file['id'], $this->con); - $db_file->setDbIsScheduled(true); - $db_file->save($this->con); - } - $endProfile = microtime(true); Logging::debug("updating show instances status."); Logging::debug(floatval($endProfile) - floatval($startProfile)); @@ -552,46 +688,53 @@ class Application_Model_Scheduler } } + private function getInstances($instanceId) + { + $ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); + $ccShow = $ccShowInstance->getCcShow(); + if ($ccShow->isLinked()) { + return $ccShow->getCcShowInstancess(); + } else { + return array($ccShowInstance); + } + } + /* - * @param array $scheduleItems - * @param array $mediaItems + * @param array $scheduleItems (schedule_id and instance_id it belongs to) + * @param array $mediaItems (file|block|playlist|webstream) */ public function scheduleAfter($scheduleItems, $mediaItems, $adjustSched = true) { $this->con->beginTransaction(); - $schedFiles = array(); - try { + $this->validateRequest($scheduleItems, true); - $this->validateRequest($scheduleItems); - - $requireDynamicContentCreation = false; - - foreach ($mediaItems as $media) { - if ($media['type'] == "playlist") { - $pl = new Application_Model_Playlist($media['id']); - if ($pl->hasDynamicBlock()) { - $requireDynamicContentCreation = true; - break; - } - } else if ($media['type'] == "block") { - $bl = new Application_Model_Block($media['id']); - if (!$bl->isStatic()) { - $requireDynamicContentCreation = true; - break; - } - } - } - - if ($requireDynamicContentCreation) { - $this->insertAfter($scheduleItems, $schedFiles, $adjustSched, $mediaItems); - } else { - foreach ($mediaItems as $media) { - $schedFiles = array_merge($schedFiles, $this->retrieveMediaFiles($media["id"], $media["type"])); - } - $this->insertAfter($scheduleItems, $schedFiles, $adjustSched); - } + /* + * create array of arrays + * array of schedule item info + * (sched_id is the cc_schedule id and is set if an item is being + * moved because it is already in cc_schedule) + * [0] = Array( + * id => 1, + * cliplength => 00:04:32, + * cuein => 00:00:00, + * cueout => 00:04:32, + * fadein => 00.5, + * fadeout => 00.5, + * sched_id => , + * type => 0) + * [1] = Array( + * id => 2, + * cliplength => 00:05:07, + * cuein => 00:00:00, + * cueout => 00:05:07, + * fadein => 00.5, + * fadeout => 00.5, + * sched_id => , + * type => 0) + */ + $this->insertAfter($scheduleItems, $mediaItems, null, $adjustSched); $this->con->commit(); @@ -615,6 +758,7 @@ class Application_Model_Scheduler try { + $this->validateItemMove($selectedItems, $afterItems[0]); $this->validateRequest($selectedItems); $this->validateRequest($afterItems); @@ -668,7 +812,7 @@ class Application_Model_Scheduler $startProfile = microtime(true); - $this->insertAfter($afterItems, $movedData, $adjustSched); + $this->insertAfter($afterItems, null, $movedData, $adjustSched, true); $endProfile = microtime(true); Logging::debug("inserting after removing gaps."); @@ -692,7 +836,7 @@ class Application_Model_Scheduler } } - public function removeItems($scheduledItems, $adjustSched = true) + public function removeItems($scheduledItems, $adjustSched = true, $cancelShow=false) { $showInstances = array(); $this->con->beginTransaction(); @@ -713,6 +857,31 @@ class Application_Model_Scheduler $instance = $removedItem->getCcShowInstances($this->con); + //check if instance is linked and if so get the schedule items + //for all linked instances so we can delete them too + if (!$cancelShow && $instance->getCcShow()->isLinked()) { + //returns all linked instances if linked + $ccShowInstances = $this->getInstances($instance->getDbId()); + $instanceIds = array(); + foreach ($ccShowInstances as $ccShowInstance) { + $instanceIds[] = $ccShowInstance->getDbId(); + } + /* + * Find all the schedule items that are in the same position + * as the selected item by the user. + * The position of each track is the same across each linked instance + */ + $itemsToDelete = CcScheduleQuery::create() + ->filterByDbPosition($removedItem->getDbPosition()) + ->filterByDbInstanceId($instanceIds, Criteria::IN) + ->find(); + foreach ($itemsToDelete as $item) { + if (!$removedItems->contains($item)) { + $removedItems->append($item); + } + } + } + //check to truncate the currently playing item instead of deleting it. if ($removedItem->isCurrentItem($this->epochNow)) { @@ -816,7 +985,7 @@ class Application_Model_Scheduler $remove[$i]["id"] = $items[$i]->getDbId(); } - $this->removeItems($remove, false); + $this->removeItems($remove, false, true); } } else { $rebroadcasts = $instance->getCcShowInstancessRelatedByDbId(null, $this->con); diff --git a/airtime_mvc/application/models/Show.php b/airtime_mvc/application/models/Show.php index f485e41bc..186603f97 100644 --- a/airtime_mvc/application/models/Show.php +++ b/airtime_mvc/application/models/Show.php @@ -1113,11 +1113,13 @@ SQL; */ public static function create($data) { - $startDateTime = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time']); - $utcStartDateTime = clone $startDateTime; - $utcStartDateTime->setTimezone(new DateTimeZone('UTC')); + /*$startDateTime = new DateTime($data['add_show_start_date']." ".$data['add_show_start_time']);*/ + + // these are not used + /*$utcStartDateTime = clone $startDateTime; + $utcStartDateTime->setTimezone(new DateTimeZone('UTC'));*/ - if ($data['add_show_no_end']) { + /*if ($data['add_show_no_end']) { $endDate = NULL; } elseif ($data['add_show_repeats']) { $endDateTime = new DateTime($data['add_show_end_date']); @@ -1129,28 +1131,29 @@ SQL; //$endDateTime->setTimezone(new DateTimeZone('UTC')); $endDateTime->add(new DateInterval("P1D")); $endDate = $endDateTime->format("Y-m-d"); - } + }*/ //What we are doing here is checking if the show repeats or if //any repeating days have been checked. If not, then by default //the "selected" DOW is the initial day. //DOW in local time. - $startDow = date("w", $startDateTime->getTimestamp()); + /*$startDow = date("w", $startDateTime->getTimestamp()); if (!$data['add_show_repeats']) { $data['add_show_day_check'] = array($startDow); } elseif ($data['add_show_repeats'] && $data['add_show_day_check'] == "") { $data['add_show_day_check'] = array($startDow); - } + }*/ //find repeat type or set to a non repeating show. - $repeatType = ($data['add_show_repeats']) ? $data['add_show_repeat_type'] : -1; + /*$repeatType = ($data['add_show_repeats']) ? $data['add_show_repeat_type'] : -1;*/ - if ($data['add_show_id'] == -1) { + /*if ($data['add_show_id'] == -1) { $ccShow = new CcShow(); } else { $ccShow = CcShowQuery::create()->findPK($data['add_show_id']); - } - $ccShow->setDbName($data['add_show_name']); + }*/ + + /*$ccShow->setDbName($data['add_show_name']); $ccShow->setDbDescription($data['add_show_description']); $ccShow->setDbUrl($data['add_show_url']); $ccShow->setDbGenre($data['add_show_genre']); @@ -1160,25 +1163,26 @@ SQL; $ccShow->setDbLiveStreamUsingCustomAuth($data['cb_custom_auth'] == 1); $ccShow->setDbLiveStreamUser($data['custom_username']); $ccShow->setDbLiveStreamPass($data['custom_password']); - $ccShow->save(); + $ccShow->save();*/ - $showId = $ccShow->getDbId(); + /*$showId = $ccShow->getDbId();*/ - $isRecorded = (isset($data['add_show_record']) && $data['add_show_record']) ? 1 : 0; + /*$isRecorded = (isset($data['add_show_record']) && $data['add_show_record']) ? 1 : 0;*/ - if ($data['add_show_id'] != -1) { + /*if ($data['add_show_id'] != -1) { $show = new Application_Model_Show($showId); + //CC-4150 CULPRIT $show->deletePossiblyInvalidInstances($data, $endDate, $isRecorded, $repeatType); - } + }*/ //check if we are adding or updating a show, and if updating //erase all the show's show_days information first. - if ($data['add_show_id'] != -1) { + /*if ($data['add_show_id'] != -1) { CcShowDaysQuery::create()->filterByDbShowId($data['add_show_id'])->delete(); - } + }*/ //don't set day for monthly repeat type, it's invalid. - if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2) { + /*if ($data['add_show_repeats'] && $data['add_show_repeat_type'] == 2) { $showDay = new CcShowDays(); $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); $showDay->setDbLastShow($endDate); @@ -1215,19 +1219,19 @@ SQL; $showDay->save(); } } - } + }*/ //check if we are adding or updating a show, and if updating //erase all the show's future show_rebroadcast information first. - if (($data['add_show_id'] != -1) && isset($data['add_show_rebroadcast']) && $data['add_show_rebroadcast']) { + /*if (($data['add_show_id'] != -1) && isset($data['add_show_rebroadcast']) && $data['add_show_rebroadcast']) { CcShowRebroadcastQuery::create() ->filterByDbShowId($data['add_show_id']) ->delete(); - } + }*/ //adding rows to cc_show_rebroadcast /* TODO: Document magic constant 10 and define it properly somewhere --RG */ - if (($isRecorded && $data['add_show_rebroadcast']) && ($repeatType != -1)) { + /*if (($isRecorded && $data['add_show_rebroadcast']) && ($repeatType != -1)) { for ($i=1; $i<=10; $i++) { if ($data['add_show_rebroadcast_date_'.$i]) { $showRebroad = new CcShowRebroadcast(); @@ -1264,14 +1268,14 @@ SQL; $showRebroad->save(); } } - } + }*/ //check if we are adding or updating a show, and if updating //erase all the show's show_rebroadcast information first. - if ($data['add_show_id'] != -1) { + /*if ($data['add_show_id'] != -1) { CcShowHostsQuery::create()->filterByDbShow($data['add_show_id'])->delete(); - } - if (is_array($data['add_show_hosts'])) { + }*/ + /*if (is_array($data['add_show_hosts'])) { //add selected hosts to cc_show_hosts table. foreach ($data['add_show_hosts'] as $host) { $showHost = new CcShowHosts(); @@ -1279,9 +1283,9 @@ SQL; $showHost->setDbHost($host); $showHost->save(); } - } + }*/ - if ($data['add_show_id'] != -1) { + /*if ($data['add_show_id'] != -1) { $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); $con->beginTransaction(); @@ -1306,12 +1310,12 @@ SQL; Logging::info("Couldn't update schedule status."); Logging::info($e->getMessage()); } - } + }*/ - Application_Model_Show::populateShowUntil($showId); - Application_Model_RabbitMq::PushSchedule(); + /*Application_Model_Show::populateShowUntil($showId); + Application_Model_RabbitMq::PushSchedule();*/ - return $showId; + /*return $showId;*/ } /** @@ -1321,7 +1325,7 @@ SQL; * * @param int $p_showId */ - public static function populateShowUntil($p_showId) + /*public static function populateShowUntil($p_showId) { $con = Propel::getConnection(); $date = Application_Model_Preference::GetShowsPopulatedUntil(); @@ -1342,7 +1346,7 @@ SQL; foreach ($res as $showDaysRow) { Application_Model_Show::populateShow($showDaysRow, $p_populateUntilDateTime); } - } + }*/ /** * We are going to use cc_show_days as a template, to generate Show Instances. This function @@ -1355,7 +1359,7 @@ SQL; * @param DateTime $p_populateUntilDateTime * DateTime object in UTC time. */ - private static function populateShow($p_showDaysRow, $p_populateUntilDateTime) + /*private static function populateShow($p_showDaysRow, $p_populateUntilDateTime) { // TODO : use constants instead of int values here? or maybe php will // get enum types by the time somebody gets around to fix this. -- RG @@ -1369,7 +1373,7 @@ SQL; Application_Model_Show::populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, 'P1M'); } Application_Model_RabbitMq::PushSchedule(); - } + }*/ /** * Creates a single show instance. If the show is recorded, it may have multiple @@ -1382,7 +1386,7 @@ SQL; */ private static function populateNonRepeatingShow($p_showRow, $p_populateUntilDateTime) { - $show_id = $p_showRow["show_id"]; + /*$show_id = $p_showRow["show_id"]; $first_show = $p_showRow["first_show"]; //non-UTC $start_time = $p_showRow["start_time"]; //non-UTC $duration = $p_showRow["duration"]; @@ -1393,41 +1397,42 @@ SQL; //start & end UTC DateTimes for the show. list($utcStartDateTime, $utcEndDateTime) = Application_Model_Show::createUTCStartEndDateTime($start, $duration, $timezone); if ($utcStartDateTime->getTimestamp() < $p_populateUntilDateTime->getTimestamp()) { - $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + $currentUtcTimestamp = gmdate("Y-m-d H:i:s");*/ - $show = new Application_Model_Show($show_id); + /*$show = new Application_Model_Show($show_id); if ($show->hasInstance()) { $ccShowInstance = $show->getInstance(); $newInstance = false; - } else { + }*/ /*else { $ccShowInstance = new CcShowInstances(); $newInstance = true; - } + }*/ - if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp) { + /*if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp) { $ccShowInstance->setDbShowId($show_id); $ccShowInstance->setDbStarts($utcStartDateTime); $ccShowInstance->setDbEnds($utcEndDateTime); $ccShowInstance->setDbRecord($record); $ccShowInstance->save(); - } + }*/ - $show_instance_id = $ccShowInstance->getDbId(); - $showInstance = new Application_Model_ShowInstance($show_instance_id); + /* $show_instance_id = $ccShowInstance->getDbId(); + $showInstance = new Application_Model_ShowInstance($show_instance_id);*/ - if (!$newInstance) { + /*if (!$newInstance) { $showInstance->correctScheduleStartTimes(); - } + }*/ - $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; + /*$sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; $rebroadcasts = Application_Common_Database::prepareAndExecute($sql, - array( ':show_id' => $show_id ), 'all'); + array( ':show_id' => $show_id ), 'all');*/ - if ($showInstance->isRecorded()) { + /*if ($showInstance->isRecorded()) { + //only do this for editing $showInstance->deleteRebroadcasts(); self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); - } - } + }*/ + /*}*/ } /** @@ -1444,7 +1449,7 @@ SQL; */ private static function populateRepeatingShow($p_showDaysRow, $p_populateUntilDateTime, $p_interval) { - $show_id = $p_showDaysRow["show_id"]; + /*$show_id = $p_showDaysRow["show_id"]; $next_pop_date = $p_showDaysRow["next_pop_date"]; $first_show = $p_showDaysRow["first_show"]; //non-UTC $last_show = $p_showDaysRow["last_show"]; //non-UTC @@ -1464,21 +1469,23 @@ SQL; $utcStartDateTime = Application_Common_DateHelper::ConvertToUtcDateTime($start, $timezone); //convert $last_show into a UTC DateTime object, or null if there is no last show. - $utcLastShowDateTime = $last_show ? Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; + $utcLastShowDateTime = $last_show ? Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null;*/ - $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; + /*$sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; $rebroadcasts = Application_Common_Database::prepareAndExecute( $sql, array( ':show_id' => $show_id ), 'all'); - $show = new Application_Model_Show($show_id); + $show = new Application_Model_Show($show_id);*/ - while ($utcStartDateTime->getTimestamp() <= $p_populateUntilDateTime->getTimestamp() - && (is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp())){ + /*while ($utcStartDateTime->getTimestamp() <= $p_populateUntilDateTime->getTimestamp() + && (is_null($utcLastShowDateTime) || $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp())){*/ - list($utcStartDateTime, $utcEndDateTime) = self::createUTCStartEndDateTime($start, $duration, $timezone); + /*list($utcStartDateTime, $utcEndDateTime) = self::createUTCStartEndDateTime($start, $duration, $timezone);*/ - if ($show->hasInstanceOnDate($utcStartDateTime)) { + //determine if we are adding a new show + //or editing a show + /* if ($show->hasInstanceOnDate($utcStartDateTime)) { $ccShowInstance = $show->getInstanceOnDate($utcStartDateTime); if ($ccShowInstance->getDbModifiedInstance()) { @@ -1491,12 +1498,12 @@ SQL; } else { $ccShowInstance = new CcShowInstances(); $newInstance = true; - } + }*/ /* When editing the start/end time of a repeating show, we don't want to * change shows that started in the past. So check the start time. */ - if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp) { + /*if ($newInstance || $ccShowInstance->getDbStarts() > $currentUtcTimestamp) { $ccShowInstance->setDbShowId($show_id); $ccShowInstance->setDbStarts($utcStartDateTime); $ccShowInstance->setDbEnds($utcEndDateTime); @@ -1506,21 +1513,22 @@ SQL; $show_instance_id = $ccShowInstance->getDbId(); - $showInstance = new Application_Model_ShowInstance($show_instance_id); + $showInstance = new Application_Model_ShowInstance($show_instance_id);*/ /* If we are updating a show then make sure that the scheduled content within * the show is updated to the correct time. */ - if (!$newInstance) { + // don't we already do this in deletePossiblyInvalidInstances??? + /*if (!$newInstance) { $showInstance->correctScheduleStartTimes(); - } + }*/ - $showInstance->deleteRebroadcasts(); + /*$showInstance->deleteRebroadcasts(); self::createRebroadcastInstances($rebroadcasts, $currentUtcTimestamp, $show_id, $show_instance_id, $start, $duration, $timezone); - list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone); + list($start, $utcStartDateTime) = self::advanceRepeatingDate($p_interval, $start, $timezone);*/ - } + /*}*/ - Application_Model_Show::setNextPop($start, $show_id, $day); + /*Application_Model_Show::setNextPop($start, $show_id, $day);*/ } private static function advanceRepeatingDate($p_interval, $start, $timezone) @@ -1574,7 +1582,7 @@ SQL; */ private static function createUTCStartEndDateTime($p_start, $p_duration, $p_timezone=null, $p_offset=null) { - $timezone = $p_timezone ? $p_timezone : date_default_timezone_get(); + /*$timezone = $p_timezone ? $p_timezone : date_default_timezone_get(); $startDateTime = new DateTime($p_start, new DateTimeZone($timezone)); if (isset($p_offset)) { @@ -1588,7 +1596,7 @@ SQL; list($hours, $mins) = array_slice($duration, 0, 2); $endDateTime->add(new DateInterval("PT{$hours}H{$mins}M")); - return array($startDateTime, $endDateTime); + return array($startDateTime, $endDateTime);*/ } /* Create rebroadcast instances for a created show marked for recording @@ -1614,7 +1622,7 @@ SQL; { //Y-m-d //use only the date part of the show start time stamp for the offsets to work properly. - $date = explode(" ", $p_startTime); + /*$date = explode(" ", $p_startTime); $start_date = $date[0]; foreach ($p_rebroadcasts as $rebroadcast) { @@ -1636,7 +1644,7 @@ SQL; $newRebroadcastInstance->setDbOriginalShow($p_showInstanceId); $newRebroadcastInstance->save(); } - } + }*/ } /** @@ -1656,7 +1664,8 @@ SQL; $showsPopUntil = Application_Model_Preference::GetShowsPopulatedUntil(); //if application is requesting shows past our previous populated until date, generate shows up until this point. if (is_null($showsPopUntil) || $showsPopUntil->getTimestamp() < $end_timestamp->getTimestamp()) { - Application_Model_Show::populateAllShowsInRange($showsPopUntil, $end_timestamp); + $service_show = new Application_Service_ShowService(); + $ccShow = $service_show->delegateInstanceCreation(null, $end_timestamp, true); Application_Model_Preference::SetShowsPopulatedUntil($end_timestamp); } diff --git a/airtime_mvc/application/models/ShowBuilder.php b/airtime_mvc/application/models/ShowBuilder.php index 9b7c65fe9..cec8895f0 100644 --- a/airtime_mvc/application/models/ShowBuilder.php +++ b/airtime_mvc/application/models/ShowBuilder.php @@ -19,6 +19,7 @@ class Application_Model_ShowBuilder private $contentDT; private $epoch_now; private $currentShow; + private $currentShowId; private $showInstances = array(); @@ -27,6 +28,7 @@ class Application_Model_ShowBuilder "footer" => false, "empty" => false, "allowed" => false, + "linked_allowed" => true, "id" => 0, "instance" => "", "starts" => "", @@ -85,6 +87,18 @@ class Application_Model_ShowBuilder return; } + if ($this->currentShow) { + $this->currentShowId = $p_item["show_id"]; + } + + /* If any linked show instance is currently playing + * we have to disable editing, or else the times + * will not make sense for shows scheduled in the future + */ + if ($p_item["linked"] && $p_item["show_id"] == $this->currentShowId) { + $row["linked_allowed"] = false; + } + if ($this->user->canSchedule($p_item["show_id"]) == true) { $row["allowed"] = true; } @@ -174,7 +188,7 @@ class Application_Model_ShowBuilder private function makeHeaderRow($p_item) { $row = $this->defaultRowArray; - $this->isAllowed($p_item, $row); + //$this->isAllowed($p_item, $row); $this->getRowTimestamp($p_item, $row); $this->getItemColor($p_item, $row); @@ -217,6 +231,8 @@ class Application_Model_ShowBuilder $this->currentShow = false; } + $this->isAllowed($p_item, $row); + $row["header"] = true; $row["starts"] = $showStartDT->format("Y-m-d H:i"); $row["startDate"] = $showStartDT->format("Y-m-d"); diff --git a/airtime_mvc/application/models/ShowInstance.php b/airtime_mvc/application/models/ShowInstance.php index 0141e8a5a..e95b7dd01 100644 --- a/airtime_mvc/application/models/ShowInstance.php +++ b/airtime_mvc/application/models/ShowInstance.php @@ -391,7 +391,7 @@ SQL; * @param int $plId * Playlist ID. */ - public function addPlaylistToShow($pl_id, $checkUserPerm = true) + /*public function addPlaylistToShow($pl_id, $checkUserPerm = true) { $ts = intval($this->_showInstance->getDbLastScheduled("U")) ? : 0; $id = $this->_showInstance->getDbId(); @@ -401,7 +401,7 @@ SQL; array(array("id" => 0, "instance" => $id, "timestamp" => $ts)), array(array("id" => $pl_id, "type" => "playlist")) ); - } + }*/ /** * Add a media file as the last item in the show. @@ -427,12 +427,12 @@ SQL; * @param array $plIds * An array of playlist IDs. */ - public function scheduleShow($plIds) + /*public function scheduleShow($plIds) { foreach ($plIds as $plId) { $this->addPlaylistToShow($plId); } - } + }*/ public function clearShow() { diff --git a/airtime_mvc/application/models/StoredFile.php b/airtime_mvc/application/models/StoredFile.php index a85d3e602..0b743e849 100644 --- a/airtime_mvc/application/models/StoredFile.php +++ b/airtime_mvc/application/models/StoredFile.php @@ -1017,6 +1017,9 @@ SQL; Logging::info("Successfully written identification file for uploaded '$audio_stor'"); } + //if the uploaded file is not UTF-8 encoded, let's encode it. Assuming source + //encoding is ISO-8859-1 + $audio_stor = mb_detect_encoding($audio_stor, "UTF-8") == "UTF-8" ? $audio_stor : utf8_encode($audio_stor); Logging::info("copyFileToStor: moving file $audio_file to $audio_stor"); // Martin K.: changed to rename: Much less load + quicker since this is // an atomic operation diff --git a/airtime_mvc/application/models/airtime/CcShow.php b/airtime_mvc/application/models/airtime/CcShow.php index ae37d289e..5e300f00c 100644 --- a/airtime_mvc/application/models/airtime/CcShow.php +++ b/airtime_mvc/application/models/airtime/CcShow.php @@ -15,4 +15,171 @@ */ class CcShow extends BaseCcShow { + public function getCcShowDays(){ + return CcShowDaysQuery::create()->filterByDbShowId($this->getDbId())->find(); + } + + /** + * Gets an array of CcShowDays objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this CcShow is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param PropelPDO $con optional connection object + * @return PropelCollection|array CcShowDays[] List of CcShowDays objects + * @throws PropelException + */ + public function getFirstCcShowDay($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcShowDayss || null !== $criteria) { + if ($this->isNew() && null === $this->collCcShowDayss) { + // return empty collection + $this->initCcShowDayss(); + } else { + $collCcShowDayss = CcShowDaysQuery::create(null, $criteria) + ->filterByCcShow($this) + ->orderByDbFirstShow() + ->limit(1) + ->find($con); + if (null !== $criteria) { + return $collCcShowDayss; + } + $this->collCcShowDayss = $collCcShowDayss; + } + } + return $this->collCcShowDayss[0]; + } + + /** + * Gets an array of CcShowInstances objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this CcShow is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param PropelPDO $con optional connection object + * @return PropelCollection|array CcShowInstances[] List of CcShowInstances objects + * @throws PropelException + */ + public function getFutureCcShowInstancess($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcShowInstancess || null !== $criteria) { + if ($this->isNew() && null === $this->collCcShowInstancess) { + // return empty collection + $this->initCcShowInstancess(); + } else { + $collCcShowInstancess = CcShowInstancesQuery::create(null, $criteria) + ->filterByCcShow($this) + ->filterByDbStarts(gmdate("Y-m-d H:i:s"), Criteria::GREATER_THAN) + ->filterByDbModifiedInstance(false) + ->find($con); + if (null !== $criteria) { + return $collCcShowInstancess; + } + $this->collCcShowInstancess = $collCcShowInstancess; + } + } + return $this->collCcShowInstancess; + } + + public function isRecorded() + { + $ccShowInstances = CcShowInstancesQuery::create() + ->filterByDbShowId($this->getDbId()) + ->filterByDbRecord(1) + ->filterByDbModifiedInstance(false) + ->findOne(); + + return (!is_null($ccShowInstances)); + } + + public function isRebroadcast() + { + $ccShowInstances = CcShowInstancesQuery::create() + ->filterByDbShowId($this->getDbId()) + ->filterByDbRebroadcast(1) + ->filterByDbModifiedInstance(false) + ->findOne(); + + return (!is_null($ccShowInstances)); + } + + public function getRebroadcastsRelative() + { + return CcShowRebroadcastQuery::create() + ->filterByDbShowId($this->getDbId()) + ->orderByDbDayOffset() + ->find(); + } + + public function getRebroadcastsAbsolute() + { + return CcShowInstancesQuery::create() + ->filterByDbShowId($this->getDbId()) + ->filterByDbRebroadcast(1) + ->filterByDbModifiedInstance(false) + ->orderByDbStarts() + ->find(); + } + + public function isLinked() + { + return $this->getDbLinked(); + } + + public function isLinkable() + { + return $this->getDbIsLinkable(); + } + + /** + * Gets an array of CcShowInstances objects which contain a foreign key that references this object. + * + * If the $criteria is not null, it is used to always fetch the results from the database. + * Otherwise the results are fetched from the database the first time, then cached. + * Next time the same method is called without $criteria, the cached collection is returned. + * If this CcShow is new, it will return + * an empty collection or the current collection; the criteria is ignored on a new object. + * + * @param Criteria $criteria optional Criteria object to narrow the query + * @param PropelPDO $con optional connection object + * @return PropelCollection|array CcShowInstances[] List of CcShowInstances objects + * @throws PropelException + */ + public function getCcShowInstancess($criteria = null, PropelPDO $con = null) + { + if(null === $this->collCcShowInstancess || null !== $criteria) { + if ($this->isNew() && null === $this->collCcShowInstancess) { + // return empty collection + $this->initCcShowInstancess(); + } else { + $collCcShowInstancess = CcShowInstancesQuery::create(null, $criteria) + ->filterByCcShow($this) + ->filterByDbModifiedInstance(false) + ->filterByDbStarts(gmdate("Y-m-d H:i:s"), criteria::GREATER_THAN) + ->orderByDbId() + ->find($con); + if (null !== $criteria) { + return $collCcShowInstancess; + } + $this->collCcShowInstancess = $collCcShowInstancess; + } + } + return $this->collCcShowInstancess; + } + + public function getInstanceIds() { + $instanceIds = array(); + foreach ($this->getCcShowInstancess() as $ccShowInstance) { + $instanceIds[] = $ccShowInstance->getDbId(); + } + return $instanceIds; + } } // CcShow diff --git a/airtime_mvc/application/models/airtime/CcShowDays.php b/airtime_mvc/application/models/airtime/CcShowDays.php index 72df6047e..cef0b333f 100644 --- a/airtime_mvc/application/models/airtime/CcShowDays.php +++ b/airtime_mvc/application/models/airtime/CcShowDays.php @@ -15,4 +15,54 @@ */ class CcShowDays extends BaseCcShowDays { + public function isRepeating() + { + return $this->getDbRepeatType() != -1; + } + + public function getUTCStartDateAndTime() + { + $dt = new DateTime( + "{$this->getDbFirstShow()} {$this->getDbStartTime()}", + new DateTimeZone($this->getDbTimezone()) + ); + $dt->setTimezone(new DateTimeZone("UTC")); + + return $dt; + } + + public function getLocalStartDateAndTime() + { + $dt = new DateTime( + "{$this->getDbFirstShow()} {$this->getDbStartTime()}", + new DateTimeZone($this->getDbTimezone()) + ); + + return $dt; + } + + /** + * + * Enter description here ... + * @param DateTime $startDateTime first show in user's local time + */ + public function getLocalEndDateAndTime($showStart) + { + $startDateTime = clone $showStart; + $duration = explode(":", $this->getDbDuration()); + + return $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); + } + + public function isShowStartInPast() + { + return $this->getUTCStartDateAndTime()->format("Y-m-d H:i:s") < gmdate("Y-m-d H:i:s"); + } + + public function formatDuration() + { + $info = explode(':',$this->getDbDuration()); + + return str_pad(intval($info[0]),2,'0',STR_PAD_LEFT).'h '.str_pad(intval($info[1]),2,'0',STR_PAD_LEFT).'m'; + } } // CcShowDays diff --git a/airtime_mvc/application/models/airtime/CcShowInstances.php b/airtime_mvc/application/models/airtime/CcShowInstances.php index 4625d1f91..6fdaaf8a2 100644 --- a/airtime_mvc/application/models/airtime/CcShowInstances.php +++ b/airtime_mvc/application/models/airtime/CcShowInstances.php @@ -175,4 +175,20 @@ class CcShowInstances extends BaseCcShowInstances { return true; } + public function isRecorded() + { + return $this->getDbRecord() == 1 ? true : false; + } + + public function isRebroadcast() + { + return $this->getDbRebroadcast() == 1 ? true : false; + } + + public function getLocalStartDateTime() + { + $startDT = $this->getDbStarts(null); + return $startDT->setTimezone(new DateTimeZone(Application_Model_Preference::GetTimezone())); + } + } // CcShowInstances diff --git a/airtime_mvc/application/models/airtime/CcSubjs.php b/airtime_mvc/application/models/airtime/CcSubjs.php index e5fca5e27..908adf554 100644 --- a/airtime_mvc/application/models/airtime/CcSubjs.php +++ b/airtime_mvc/application/models/airtime/CcSubjs.php @@ -15,4 +15,16 @@ */ class CcSubjs extends BaseCcSubjs { + public function isAdminOrPM() + { + return $this->type === UTYPE_ADMIN || $this->type === UTYPE_PROGRAM_MANAGER; + } + + public function isHostOfShow($showId) + { + return CcShowHostsQuery::create() + ->filterByDbShow($showId) + ->filterByDbHost($this->getDbId()) + ->count() > 0; + } } // CcSubjs diff --git a/airtime_mvc/application/models/airtime/map/CcScheduleTableMap.php b/airtime_mvc/application/models/airtime/map/CcScheduleTableMap.php index 8c1d00dd2..54d25cdb8 100644 --- a/airtime_mvc/application/models/airtime/map/CcScheduleTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcScheduleTableMap.php @@ -52,6 +52,7 @@ class CcScheduleTableMap extends TableMap { $this->addForeignKey('INSTANCE_ID', 'DbInstanceId', 'INTEGER', 'cc_show_instances', 'ID', true, null, null); $this->addColumn('PLAYOUT_STATUS', 'DbPlayoutStatus', 'SMALLINT', true, null, 1); $this->addColumn('BROADCASTED', 'DbBroadcasted', 'SMALLINT', true, null, 0); + $this->addColumn('POSITION', 'DbPosition', 'INTEGER', true, null, 0); // validators } // initialize() diff --git a/airtime_mvc/application/models/airtime/map/CcShowStampTableMap.php b/airtime_mvc/application/models/airtime/map/CcShowStampTableMap.php new file mode 100644 index 000000000..b821332a8 --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcShowStampTableMap.php @@ -0,0 +1,70 @@ +setName('cc_show_stamp'); + $this->setPhpName('CcShowStamp'); + $this->setClassname('CcShowStamp'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_show_stamp_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addForeignKey('SHOW_ID', 'DbShowId', 'INTEGER', 'cc_show', 'ID', true, null, null); + $this->addForeignKey('INSTANCE_ID', 'DbInstanceId', 'INTEGER', 'cc_show_instances', 'ID', false, null, null); + $this->addForeignKey('FILE_ID', 'DbFileId', 'INTEGER', 'cc_files', 'ID', false, null, null); + $this->addForeignKey('STREAM_ID', 'DbStreamId', 'INTEGER', 'cc_webstream', 'ID', false, null, null); + $this->addForeignKey('BLOCK_ID', 'DbBlockId', 'INTEGER', 'cc_block', 'ID', false, null, null); + $this->addForeignKey('PLAYLIST_ID', 'DbPlaylistId', 'INTEGER', 'cc_playlist', 'ID', false, null, null); + $this->addColumn('POSITION', 'DbPosition', 'INTEGER', true, null, null); + $this->addColumn('CLIP_LENGTH', 'DbClipLength', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('CUE_IN', 'DbCueIn', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('CUE_OUT', 'DbCueOut', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('FADE_IN', 'DbFadeIn', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('FADE_OUT', 'DbFadeOut', 'VARCHAR', false, null, '00:00:00'); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcShow', 'CcShow', RelationMap::MANY_TO_ONE, array('show_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcShowInstances', 'CcShowInstances', RelationMap::MANY_TO_ONE, array('instance_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcFiles', 'CcFiles', RelationMap::MANY_TO_ONE, array('file_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcWebstream', 'CcWebstream', RelationMap::MANY_TO_ONE, array('stream_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcBlock', 'CcBlock', RelationMap::MANY_TO_ONE, array('block_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::MANY_TO_ONE, array('playlist_id' => 'id', ), 'CASCADE', null); + } // buildRelations() + +} // CcShowStampTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcShowTableMap.php b/airtime_mvc/application/models/airtime/map/CcShowTableMap.php index 713de40a9..8a2686670 100644 --- a/airtime_mvc/application/models/airtime/map/CcShowTableMap.php +++ b/airtime_mvc/application/models/airtime/map/CcShowTableMap.php @@ -49,6 +49,8 @@ class CcShowTableMap extends TableMap { $this->addColumn('LIVE_STREAM_USING_CUSTOM_AUTH', 'DbLiveStreamUsingCustomAuth', 'BOOLEAN', false, null, false); $this->addColumn('LIVE_STREAM_USER', 'DbLiveStreamUser', 'VARCHAR', false, 255, null); $this->addColumn('LIVE_STREAM_PASS', 'DbLiveStreamPass', 'VARCHAR', false, 255, null); + $this->addColumn('LINKED', 'DbLinked', 'BOOLEAN', true, null, false); + $this->addColumn('IS_LINKABLE', 'DbIsLinkable', 'BOOLEAN', true, null, true); // validators } // initialize() diff --git a/airtime_mvc/application/models/airtime/map/CcStampContentsTableMap.php b/airtime_mvc/application/models/airtime/map/CcStampContentsTableMap.php new file mode 100644 index 000000000..26811c472 --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcStampContentsTableMap.php @@ -0,0 +1,68 @@ +setName('cc_stamp_contents'); + $this->setPhpName('CcStampContents'); + $this->setClassname('CcStampContents'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_stamp_contents_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addForeignKey('STAMP_ID', 'DbStampId', 'INTEGER', 'cc_stamp', 'ID', true, null, null); + $this->addForeignKey('FILE_ID', 'DbFileId', 'INTEGER', 'cc_files', 'ID', false, null, null); + $this->addForeignKey('STREAM_ID', 'DbStreamId', 'INTEGER', 'cc_webstream', 'ID', false, null, null); + $this->addForeignKey('BLOCK_ID', 'DbBlockId', 'INTEGER', 'cc_block', 'ID', false, null, null); + $this->addForeignKey('PLAYLIST_ID', 'DbPlaylistId', 'INTEGER', 'cc_playlist', 'ID', false, null, null); + $this->addColumn('POSITION', 'DbPosition', 'INTEGER', false, null, null); + $this->addColumn('CLIP_LENGTH', 'DbClipLength', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('CUE_IN', 'DbCueIn', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('CUE_OUT', 'DbCueOut', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('FADE_IN', 'DbFadeIn', 'VARCHAR', false, null, '00:00:00'); + $this->addColumn('FADE_OUT', 'DbFadeOut', 'VARCHAR', false, null, '00:00:00'); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcStamp', 'CcStamp', RelationMap::MANY_TO_ONE, array('stamp_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcFiles', 'CcFiles', RelationMap::MANY_TO_ONE, array('file_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcWebstream', 'CcWebstream', RelationMap::MANY_TO_ONE, array('stream_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcBlock', 'CcBlock', RelationMap::MANY_TO_ONE, array('block_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcPlaylist', 'CcPlaylist', RelationMap::MANY_TO_ONE, array('playlist_id' => 'id', ), 'CASCADE', null); + } // buildRelations() + +} // CcStampContentsTableMap diff --git a/airtime_mvc/application/models/airtime/map/CcStampTableMap.php b/airtime_mvc/application/models/airtime/map/CcStampTableMap.php new file mode 100644 index 000000000..a353134ea --- /dev/null +++ b/airtime_mvc/application/models/airtime/map/CcStampTableMap.php @@ -0,0 +1,58 @@ +setName('cc_stamp'); + $this->setPhpName('CcStamp'); + $this->setClassname('CcStamp'); + $this->setPackage('airtime'); + $this->setUseIdGenerator(true); + $this->setPrimaryKeyMethodInfo('cc_stamp_id_seq'); + // columns + $this->addPrimaryKey('ID', 'DbId', 'INTEGER', true, null, null); + $this->addForeignKey('SHOW_ID', 'DbShowId', 'INTEGER', 'cc_show', 'ID', true, null, null); + $this->addForeignKey('INSTANCE_ID', 'DbInstanceId', 'INTEGER', 'cc_show_instances', 'ID', false, null, null); + $this->addColumn('LINKED', 'DbLinked', 'BOOLEAN', true, null, null); + // validators + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CcShow', 'CcShow', RelationMap::MANY_TO_ONE, array('show_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcShowInstances', 'CcShowInstances', RelationMap::MANY_TO_ONE, array('instance_id' => 'id', ), 'CASCADE', null); + $this->addRelation('CcStampContents', 'CcStampContents', RelationMap::ONE_TO_MANY, array('id' => 'stamp_id', ), 'CASCADE', null); + } // buildRelations() + +} // CcStampTableMap diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php b/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php index 13a15093f..ceb5008d8 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcSchedule.php @@ -114,6 +114,13 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent */ protected $broadcasted; + /** + * The value for the position field. + * Note: this column has a database default value of: 0 + * @var int + */ + protected $position; + /** * @var CcShowInstances */ @@ -162,6 +169,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->media_item_played = false; $this->playout_status = 1; $this->broadcasted = 0; + $this->position = 0; } /** @@ -406,6 +414,16 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return $this->broadcasted; } + /** + * Get the [position] column value. + * + * @return int + */ + public function getDbPosition() + { + return $this->position; + } + /** * Set the value of [id] column. * @@ -816,6 +834,26 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return $this; } // setDbBroadcasted() + /** + * Set the value of [position] column. + * + * @param int $v new value + * @return CcSchedule The current object (for fluent API support) + */ + public function setDbPosition($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->position !== $v || $this->isNew()) { + $this->position = $v; + $this->modifiedColumns[] = CcSchedulePeer::POSITION; + } + + return $this; + } // setDbPosition() + /** * Indicates whether the columns in this object are only set to default values. * @@ -850,6 +888,10 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent return false; } + if ($this->position !== 0) { + return false; + } + // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() @@ -886,6 +928,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->instance_id = ($row[$startcol + 11] !== null) ? (int) $row[$startcol + 11] : null; $this->playout_status = ($row[$startcol + 12] !== null) ? (int) $row[$startcol + 12] : null; $this->broadcasted = ($row[$startcol + 13] !== null) ? (int) $row[$startcol + 13] : null; + $this->position = ($row[$startcol + 14] !== null) ? (int) $row[$startcol + 14] : null; $this->resetModified(); $this->setNew(false); @@ -894,7 +937,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 14; // 14 = CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 15; // 15 = CcSchedulePeer::NUM_COLUMNS - CcSchedulePeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating CcSchedule object", $e); @@ -1315,6 +1358,9 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent case 13: return $this->getDbBroadcasted(); break; + case 14: + return $this->getDbPosition(); + break; default: return null; break; @@ -1353,6 +1399,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $keys[11] => $this->getDbInstanceId(), $keys[12] => $this->getDbPlayoutStatus(), $keys[13] => $this->getDbBroadcasted(), + $keys[14] => $this->getDbPosition(), ); if ($includeForeignObjects) { if (null !== $this->aCcShowInstances) { @@ -1437,6 +1484,9 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent case 13: $this->setDbBroadcasted($value); break; + case 14: + $this->setDbPosition($value); + break; } // switch() } @@ -1475,6 +1525,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent if (array_key_exists($keys[11], $arr)) $this->setDbInstanceId($arr[$keys[11]]); if (array_key_exists($keys[12], $arr)) $this->setDbPlayoutStatus($arr[$keys[12]]); if (array_key_exists($keys[13], $arr)) $this->setDbBroadcasted($arr[$keys[13]]); + if (array_key_exists($keys[14], $arr)) $this->setDbPosition($arr[$keys[14]]); } /** @@ -1500,6 +1551,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent if ($this->isColumnModified(CcSchedulePeer::INSTANCE_ID)) $criteria->add(CcSchedulePeer::INSTANCE_ID, $this->instance_id); if ($this->isColumnModified(CcSchedulePeer::PLAYOUT_STATUS)) $criteria->add(CcSchedulePeer::PLAYOUT_STATUS, $this->playout_status); if ($this->isColumnModified(CcSchedulePeer::BROADCASTED)) $criteria->add(CcSchedulePeer::BROADCASTED, $this->broadcasted); + if ($this->isColumnModified(CcSchedulePeer::POSITION)) $criteria->add(CcSchedulePeer::POSITION, $this->position); return $criteria; } @@ -1574,6 +1626,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $copyObj->setDbInstanceId($this->instance_id); $copyObj->setDbPlayoutStatus($this->playout_status); $copyObj->setDbBroadcasted($this->broadcasted); + $copyObj->setDbPosition($this->position); if ($deepCopy) { // important: temporarily setNew(false) because this affects the behavior of @@ -1906,6 +1959,7 @@ abstract class BaseCcSchedule extends BaseObject implements Persistent $this->instance_id = null; $this->playout_status = null; $this->broadcasted = null; + $this->position = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcSchedulePeer.php b/airtime_mvc/application/models/airtime/om/BaseCcSchedulePeer.php index 8cca53863..164830444 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcSchedulePeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcSchedulePeer.php @@ -26,7 +26,7 @@ abstract class BaseCcSchedulePeer { const TM_CLASS = 'CcScheduleTableMap'; /** The total number of columns. */ - const NUM_COLUMNS = 14; + const NUM_COLUMNS = 15; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -73,6 +73,9 @@ abstract class BaseCcSchedulePeer { /** the column name for the BROADCASTED field */ const BROADCASTED = 'cc_schedule.BROADCASTED'; + /** the column name for the POSITION field */ + const POSITION = 'cc_schedule.POSITION'; + /** * An identiy map to hold any loaded instances of CcSchedule objects. * This must be public so that other peer classes can access this when hydrating from JOIN @@ -89,12 +92,12 @@ abstract class BaseCcSchedulePeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbStarts', 'DbEnds', 'DbFileId', 'DbStreamId', 'DbClipLength', 'DbFadeIn', 'DbFadeOut', 'DbCueIn', 'DbCueOut', 'DbMediaItemPlayed', 'DbInstanceId', 'DbPlayoutStatus', 'DbBroadcasted', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbStarts', 'dbEnds', 'dbFileId', 'dbStreamId', 'dbClipLength', 'dbFadeIn', 'dbFadeOut', 'dbCueIn', 'dbCueOut', 'dbMediaItemPlayed', 'dbInstanceId', 'dbPlayoutStatus', 'dbBroadcasted', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::STARTS, self::ENDS, self::FILE_ID, self::STREAM_ID, self::CLIP_LENGTH, self::FADE_IN, self::FADE_OUT, self::CUE_IN, self::CUE_OUT, self::MEDIA_ITEM_PLAYED, self::INSTANCE_ID, self::PLAYOUT_STATUS, self::BROADCASTED, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'STARTS', 'ENDS', 'FILE_ID', 'STREAM_ID', 'CLIP_LENGTH', 'FADE_IN', 'FADE_OUT', 'CUE_IN', 'CUE_OUT', 'MEDIA_ITEM_PLAYED', 'INSTANCE_ID', 'PLAYOUT_STATUS', 'BROADCASTED', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'starts', 'ends', 'file_id', 'stream_id', 'clip_length', 'fade_in', 'fade_out', 'cue_in', 'cue_out', 'media_item_played', 'instance_id', 'playout_status', 'broadcasted', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbStarts', 'DbEnds', 'DbFileId', 'DbStreamId', 'DbClipLength', 'DbFadeIn', 'DbFadeOut', 'DbCueIn', 'DbCueOut', 'DbMediaItemPlayed', 'DbInstanceId', 'DbPlayoutStatus', 'DbBroadcasted', 'DbPosition', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbStarts', 'dbEnds', 'dbFileId', 'dbStreamId', 'dbClipLength', 'dbFadeIn', 'dbFadeOut', 'dbCueIn', 'dbCueOut', 'dbMediaItemPlayed', 'dbInstanceId', 'dbPlayoutStatus', 'dbBroadcasted', 'dbPosition', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::STARTS, self::ENDS, self::FILE_ID, self::STREAM_ID, self::CLIP_LENGTH, self::FADE_IN, self::FADE_OUT, self::CUE_IN, self::CUE_OUT, self::MEDIA_ITEM_PLAYED, self::INSTANCE_ID, self::PLAYOUT_STATUS, self::BROADCASTED, self::POSITION, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'STARTS', 'ENDS', 'FILE_ID', 'STREAM_ID', 'CLIP_LENGTH', 'FADE_IN', 'FADE_OUT', 'CUE_IN', 'CUE_OUT', 'MEDIA_ITEM_PLAYED', 'INSTANCE_ID', 'PLAYOUT_STATUS', 'BROADCASTED', 'POSITION', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'starts', 'ends', 'file_id', 'stream_id', 'clip_length', 'fade_in', 'fade_out', 'cue_in', 'cue_out', 'media_item_played', 'instance_id', 'playout_status', 'broadcasted', 'position', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) ); /** @@ -104,12 +107,12 @@ abstract class BaseCcSchedulePeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbStarts' => 1, 'DbEnds' => 2, 'DbFileId' => 3, 'DbStreamId' => 4, 'DbClipLength' => 5, 'DbFadeIn' => 6, 'DbFadeOut' => 7, 'DbCueIn' => 8, 'DbCueOut' => 9, 'DbMediaItemPlayed' => 10, 'DbInstanceId' => 11, 'DbPlayoutStatus' => 12, 'DbBroadcasted' => 13, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbStarts' => 1, 'dbEnds' => 2, 'dbFileId' => 3, 'dbStreamId' => 4, 'dbClipLength' => 5, 'dbFadeIn' => 6, 'dbFadeOut' => 7, 'dbCueIn' => 8, 'dbCueOut' => 9, 'dbMediaItemPlayed' => 10, 'dbInstanceId' => 11, 'dbPlayoutStatus' => 12, 'dbBroadcasted' => 13, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::STARTS => 1, self::ENDS => 2, self::FILE_ID => 3, self::STREAM_ID => 4, self::CLIP_LENGTH => 5, self::FADE_IN => 6, self::FADE_OUT => 7, self::CUE_IN => 8, self::CUE_OUT => 9, self::MEDIA_ITEM_PLAYED => 10, self::INSTANCE_ID => 11, self::PLAYOUT_STATUS => 12, self::BROADCASTED => 13, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'STARTS' => 1, 'ENDS' => 2, 'FILE_ID' => 3, 'STREAM_ID' => 4, 'CLIP_LENGTH' => 5, 'FADE_IN' => 6, 'FADE_OUT' => 7, 'CUE_IN' => 8, 'CUE_OUT' => 9, 'MEDIA_ITEM_PLAYED' => 10, 'INSTANCE_ID' => 11, 'PLAYOUT_STATUS' => 12, 'BROADCASTED' => 13, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'starts' => 1, 'ends' => 2, 'file_id' => 3, 'stream_id' => 4, 'clip_length' => 5, 'fade_in' => 6, 'fade_out' => 7, 'cue_in' => 8, 'cue_out' => 9, 'media_item_played' => 10, 'instance_id' => 11, 'playout_status' => 12, 'broadcasted' => 13, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbStarts' => 1, 'DbEnds' => 2, 'DbFileId' => 3, 'DbStreamId' => 4, 'DbClipLength' => 5, 'DbFadeIn' => 6, 'DbFadeOut' => 7, 'DbCueIn' => 8, 'DbCueOut' => 9, 'DbMediaItemPlayed' => 10, 'DbInstanceId' => 11, 'DbPlayoutStatus' => 12, 'DbBroadcasted' => 13, 'DbPosition' => 14, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbStarts' => 1, 'dbEnds' => 2, 'dbFileId' => 3, 'dbStreamId' => 4, 'dbClipLength' => 5, 'dbFadeIn' => 6, 'dbFadeOut' => 7, 'dbCueIn' => 8, 'dbCueOut' => 9, 'dbMediaItemPlayed' => 10, 'dbInstanceId' => 11, 'dbPlayoutStatus' => 12, 'dbBroadcasted' => 13, 'dbPosition' => 14, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::STARTS => 1, self::ENDS => 2, self::FILE_ID => 3, self::STREAM_ID => 4, self::CLIP_LENGTH => 5, self::FADE_IN => 6, self::FADE_OUT => 7, self::CUE_IN => 8, self::CUE_OUT => 9, self::MEDIA_ITEM_PLAYED => 10, self::INSTANCE_ID => 11, self::PLAYOUT_STATUS => 12, self::BROADCASTED => 13, self::POSITION => 14, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'STARTS' => 1, 'ENDS' => 2, 'FILE_ID' => 3, 'STREAM_ID' => 4, 'CLIP_LENGTH' => 5, 'FADE_IN' => 6, 'FADE_OUT' => 7, 'CUE_IN' => 8, 'CUE_OUT' => 9, 'MEDIA_ITEM_PLAYED' => 10, 'INSTANCE_ID' => 11, 'PLAYOUT_STATUS' => 12, 'BROADCASTED' => 13, 'POSITION' => 14, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'starts' => 1, 'ends' => 2, 'file_id' => 3, 'stream_id' => 4, 'clip_length' => 5, 'fade_in' => 6, 'fade_out' => 7, 'cue_in' => 8, 'cue_out' => 9, 'media_item_played' => 10, 'instance_id' => 11, 'playout_status' => 12, 'broadcasted' => 13, 'position' => 14, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, ) ); /** @@ -195,6 +198,7 @@ abstract class BaseCcSchedulePeer { $criteria->addSelectColumn(CcSchedulePeer::INSTANCE_ID); $criteria->addSelectColumn(CcSchedulePeer::PLAYOUT_STATUS); $criteria->addSelectColumn(CcSchedulePeer::BROADCASTED); + $criteria->addSelectColumn(CcSchedulePeer::POSITION); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.STARTS'); @@ -210,6 +214,7 @@ abstract class BaseCcSchedulePeer { $criteria->addSelectColumn($alias . '.INSTANCE_ID'); $criteria->addSelectColumn($alias . '.PLAYOUT_STATUS'); $criteria->addSelectColumn($alias . '.BROADCASTED'); + $criteria->addSelectColumn($alias . '.POSITION'); } } diff --git a/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php index 890a8cab9..45448d510 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcScheduleQuery.php @@ -20,6 +20,7 @@ * @method CcScheduleQuery orderByDbInstanceId($order = Criteria::ASC) Order by the instance_id column * @method CcScheduleQuery orderByDbPlayoutStatus($order = Criteria::ASC) Order by the playout_status column * @method CcScheduleQuery orderByDbBroadcasted($order = Criteria::ASC) Order by the broadcasted column + * @method CcScheduleQuery orderByDbPosition($order = Criteria::ASC) Order by the position column * * @method CcScheduleQuery groupByDbId() Group by the id column * @method CcScheduleQuery groupByDbStarts() Group by the starts column @@ -35,6 +36,7 @@ * @method CcScheduleQuery groupByDbInstanceId() Group by the instance_id column * @method CcScheduleQuery groupByDbPlayoutStatus() Group by the playout_status column * @method CcScheduleQuery groupByDbBroadcasted() Group by the broadcasted column + * @method CcScheduleQuery groupByDbPosition() Group by the position column * * @method CcScheduleQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method CcScheduleQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query @@ -73,6 +75,7 @@ * @method CcSchedule findOneByDbInstanceId(int $instance_id) Return the first CcSchedule filtered by the instance_id column * @method CcSchedule findOneByDbPlayoutStatus(int $playout_status) Return the first CcSchedule filtered by the playout_status column * @method CcSchedule findOneByDbBroadcasted(int $broadcasted) Return the first CcSchedule filtered by the broadcasted column + * @method CcSchedule findOneByDbPosition(int $position) Return the first CcSchedule filtered by the position column * * @method array findByDbId(int $id) Return CcSchedule objects filtered by the id column * @method array findByDbStarts(string $starts) Return CcSchedule objects filtered by the starts column @@ -88,6 +91,7 @@ * @method array findByDbInstanceId(int $instance_id) Return CcSchedule objects filtered by the instance_id column * @method array findByDbPlayoutStatus(int $playout_status) Return CcSchedule objects filtered by the playout_status column * @method array findByDbBroadcasted(int $broadcasted) Return CcSchedule objects filtered by the broadcasted column + * @method array findByDbPosition(int $position) Return CcSchedule objects filtered by the position column * * @package propel.generator.airtime.om */ @@ -576,6 +580,37 @@ abstract class BaseCcScheduleQuery extends ModelCriteria return $this->addUsingAlias(CcSchedulePeer::BROADCASTED, $dbBroadcasted, $comparison); } + /** + * Filter the query on the position column + * + * @param int|array $dbPosition The value to use as filter. + * Accepts an associative array('min' => $minValue, 'max' => $maxValue) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcScheduleQuery The current query, for fluid interface + */ + public function filterByDbPosition($dbPosition = null, $comparison = null) + { + if (is_array($dbPosition)) { + $useMinMax = false; + if (isset($dbPosition['min'])) { + $this->addUsingAlias(CcSchedulePeer::POSITION, $dbPosition['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($dbPosition['max'])) { + $this->addUsingAlias(CcSchedulePeer::POSITION, $dbPosition['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + return $this->addUsingAlias(CcSchedulePeer::POSITION, $dbPosition, $comparison); + } + /** * Filter the query by a related CcShowInstances object * diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShow.php b/airtime_mvc/application/models/airtime/om/BaseCcShow.php index 35f9798bb..3cf4dab1f 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShow.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShow.php @@ -95,6 +95,20 @@ abstract class BaseCcShow extends BaseObject implements Persistent */ protected $live_stream_pass; + /** + * The value for the linked field. + * Note: this column has a database default value of: false + * @var boolean + */ + protected $linked; + + /** + * The value for the is_linkable field. + * Note: this column has a database default value of: true + * @var boolean + */ + protected $is_linkable; + /** * @var array CcShowInstances[] Collection to store aggregation of CcShowInstances objects. */ @@ -142,6 +156,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent $this->genre = ''; $this->live_stream_using_airtime_auth = false; $this->live_stream_using_custom_auth = false; + $this->linked = false; + $this->is_linkable = true; } /** @@ -264,6 +280,26 @@ abstract class BaseCcShow extends BaseObject implements Persistent return $this->live_stream_pass; } + /** + * Get the [linked] column value. + * + * @return boolean + */ + public function getDbLinked() + { + return $this->linked; + } + + /** + * Get the [is_linkable] column value. + * + * @return boolean + */ + public function getDbIsLinkable() + { + return $this->is_linkable; + } + /** * Set the value of [id] column. * @@ -484,6 +520,46 @@ abstract class BaseCcShow extends BaseObject implements Persistent return $this; } // setDbLiveStreamPass() + /** + * Set the value of [linked] column. + * + * @param boolean $v new value + * @return CcShow The current object (for fluent API support) + */ + public function setDbLinked($v) + { + if ($v !== null) { + $v = (boolean) $v; + } + + if ($this->linked !== $v || $this->isNew()) { + $this->linked = $v; + $this->modifiedColumns[] = CcShowPeer::LINKED; + } + + return $this; + } // setDbLinked() + + /** + * Set the value of [is_linkable] column. + * + * @param boolean $v new value + * @return CcShow The current object (for fluent API support) + */ + public function setDbIsLinkable($v) + { + if ($v !== null) { + $v = (boolean) $v; + } + + if ($this->is_linkable !== $v || $this->isNew()) { + $this->is_linkable = $v; + $this->modifiedColumns[] = CcShowPeer::IS_LINKABLE; + } + + return $this; + } // setDbIsLinkable() + /** * Indicates whether the columns in this object are only set to default values. * @@ -514,6 +590,14 @@ abstract class BaseCcShow extends BaseObject implements Persistent return false; } + if ($this->linked !== false) { + return false; + } + + if ($this->is_linkable !== true) { + return false; + } + // otherwise, everything was equal, so return TRUE return true; } // hasOnlyDefaultValues() @@ -547,6 +631,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent $this->live_stream_using_custom_auth = ($row[$startcol + 8] !== null) ? (boolean) $row[$startcol + 8] : null; $this->live_stream_user = ($row[$startcol + 9] !== null) ? (string) $row[$startcol + 9] : null; $this->live_stream_pass = ($row[$startcol + 10] !== null) ? (string) $row[$startcol + 10] : null; + $this->linked = ($row[$startcol + 11] !== null) ? (boolean) $row[$startcol + 11] : null; + $this->is_linkable = ($row[$startcol + 12] !== null) ? (boolean) $row[$startcol + 12] : null; $this->resetModified(); $this->setNew(false); @@ -555,7 +641,7 @@ abstract class BaseCcShow extends BaseObject implements Persistent $this->ensureConsistency(); } - return $startcol + 11; // 11 = CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS). + return $startcol + 13; // 13 = CcShowPeer::NUM_COLUMNS - CcShowPeer::NUM_LAZY_LOAD_COLUMNS). } catch (Exception $e) { throw new PropelException("Error populating CcShow object", $e); @@ -959,6 +1045,12 @@ abstract class BaseCcShow extends BaseObject implements Persistent case 10: return $this->getDbLiveStreamPass(); break; + case 11: + return $this->getDbLinked(); + break; + case 12: + return $this->getDbIsLinkable(); + break; default: return null; break; @@ -993,6 +1085,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent $keys[8] => $this->getDbLiveStreamUsingCustomAuth(), $keys[9] => $this->getDbLiveStreamUser(), $keys[10] => $this->getDbLiveStreamPass(), + $keys[11] => $this->getDbLinked(), + $keys[12] => $this->getDbIsLinkable(), ); return $result; } @@ -1057,6 +1151,12 @@ abstract class BaseCcShow extends BaseObject implements Persistent case 10: $this->setDbLiveStreamPass($value); break; + case 11: + $this->setDbLinked($value); + break; + case 12: + $this->setDbIsLinkable($value); + break; } // switch() } @@ -1092,6 +1192,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent if (array_key_exists($keys[8], $arr)) $this->setDbLiveStreamUsingCustomAuth($arr[$keys[8]]); if (array_key_exists($keys[9], $arr)) $this->setDbLiveStreamUser($arr[$keys[9]]); if (array_key_exists($keys[10], $arr)) $this->setDbLiveStreamPass($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setDbLinked($arr[$keys[11]]); + if (array_key_exists($keys[12], $arr)) $this->setDbIsLinkable($arr[$keys[12]]); } /** @@ -1114,6 +1216,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent if ($this->isColumnModified(CcShowPeer::LIVE_STREAM_USING_CUSTOM_AUTH)) $criteria->add(CcShowPeer::LIVE_STREAM_USING_CUSTOM_AUTH, $this->live_stream_using_custom_auth); if ($this->isColumnModified(CcShowPeer::LIVE_STREAM_USER)) $criteria->add(CcShowPeer::LIVE_STREAM_USER, $this->live_stream_user); if ($this->isColumnModified(CcShowPeer::LIVE_STREAM_PASS)) $criteria->add(CcShowPeer::LIVE_STREAM_PASS, $this->live_stream_pass); + if ($this->isColumnModified(CcShowPeer::LINKED)) $criteria->add(CcShowPeer::LINKED, $this->linked); + if ($this->isColumnModified(CcShowPeer::IS_LINKABLE)) $criteria->add(CcShowPeer::IS_LINKABLE, $this->is_linkable); return $criteria; } @@ -1185,6 +1289,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent $copyObj->setDbLiveStreamUsingCustomAuth($this->live_stream_using_custom_auth); $copyObj->setDbLiveStreamUser($this->live_stream_user); $copyObj->setDbLiveStreamPass($this->live_stream_pass); + $copyObj->setDbLinked($this->linked); + $copyObj->setDbIsLinkable($this->is_linkable); if ($deepCopy) { // important: temporarily setNew(false) because this affects the behavior of @@ -1787,6 +1893,8 @@ abstract class BaseCcShow extends BaseObject implements Persistent $this->live_stream_using_custom_auth = null; $this->live_stream_user = null; $this->live_stream_pass = null; + $this->linked = null; + $this->is_linkable = null; $this->alreadyInSave = false; $this->alreadyInValidation = false; $this->clearAllReferences(); diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowPeer.php b/airtime_mvc/application/models/airtime/om/BaseCcShowPeer.php index e559e0d1a..c49ef60fb 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowPeer.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowPeer.php @@ -26,7 +26,7 @@ abstract class BaseCcShowPeer { const TM_CLASS = 'CcShowTableMap'; /** The total number of columns. */ - const NUM_COLUMNS = 11; + const NUM_COLUMNS = 13; /** The number of lazy-loaded columns. */ const NUM_LAZY_LOAD_COLUMNS = 0; @@ -64,6 +64,12 @@ abstract class BaseCcShowPeer { /** the column name for the LIVE_STREAM_PASS field */ const LIVE_STREAM_PASS = 'cc_show.LIVE_STREAM_PASS'; + /** the column name for the LINKED field */ + const LINKED = 'cc_show.LINKED'; + + /** the column name for the IS_LINKABLE field */ + const IS_LINKABLE = 'cc_show.IS_LINKABLE'; + /** * An identiy map to hold any loaded instances of CcShow objects. * This must be public so that other peer classes can access this when hydrating from JOIN @@ -80,12 +86,12 @@ abstract class BaseCcShowPeer { * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' */ private static $fieldNames = array ( - BasePeer::TYPE_PHPNAME => array ('DbId', 'DbName', 'DbUrl', 'DbGenre', 'DbDescription', 'DbColor', 'DbBackgroundColor', 'DbLiveStreamUsingAirtimeAuth', 'DbLiveStreamUsingCustomAuth', 'DbLiveStreamUser', 'DbLiveStreamPass', ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbName', 'dbUrl', 'dbGenre', 'dbDescription', 'dbColor', 'dbBackgroundColor', 'dbLiveStreamUsingAirtimeAuth', 'dbLiveStreamUsingCustomAuth', 'dbLiveStreamUser', 'dbLiveStreamPass', ), - BasePeer::TYPE_COLNAME => array (self::ID, self::NAME, self::URL, self::GENRE, self::DESCRIPTION, self::COLOR, self::BACKGROUND_COLOR, self::LIVE_STREAM_USING_AIRTIME_AUTH, self::LIVE_STREAM_USING_CUSTOM_AUTH, self::LIVE_STREAM_USER, self::LIVE_STREAM_PASS, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID', 'NAME', 'URL', 'GENRE', 'DESCRIPTION', 'COLOR', 'BACKGROUND_COLOR', 'LIVE_STREAM_USING_AIRTIME_AUTH', 'LIVE_STREAM_USING_CUSTOM_AUTH', 'LIVE_STREAM_USER', 'LIVE_STREAM_PASS', ), - BasePeer::TYPE_FIELDNAME => array ('id', 'name', 'url', 'genre', 'description', 'color', 'background_color', 'live_stream_using_airtime_auth', 'live_stream_using_custom_auth', 'live_stream_user', 'live_stream_pass', ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) + BasePeer::TYPE_PHPNAME => array ('DbId', 'DbName', 'DbUrl', 'DbGenre', 'DbDescription', 'DbColor', 'DbBackgroundColor', 'DbLiveStreamUsingAirtimeAuth', 'DbLiveStreamUsingCustomAuth', 'DbLiveStreamUser', 'DbLiveStreamPass', 'DbLinked', 'DbIsLinkable', ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId', 'dbName', 'dbUrl', 'dbGenre', 'dbDescription', 'dbColor', 'dbBackgroundColor', 'dbLiveStreamUsingAirtimeAuth', 'dbLiveStreamUsingCustomAuth', 'dbLiveStreamUser', 'dbLiveStreamPass', 'dbLinked', 'dbIsLinkable', ), + BasePeer::TYPE_COLNAME => array (self::ID, self::NAME, self::URL, self::GENRE, self::DESCRIPTION, self::COLOR, self::BACKGROUND_COLOR, self::LIVE_STREAM_USING_AIRTIME_AUTH, self::LIVE_STREAM_USING_CUSTOM_AUTH, self::LIVE_STREAM_USER, self::LIVE_STREAM_PASS, self::LINKED, self::IS_LINKABLE, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID', 'NAME', 'URL', 'GENRE', 'DESCRIPTION', 'COLOR', 'BACKGROUND_COLOR', 'LIVE_STREAM_USING_AIRTIME_AUTH', 'LIVE_STREAM_USING_CUSTOM_AUTH', 'LIVE_STREAM_USER', 'LIVE_STREAM_PASS', 'LINKED', 'IS_LINKABLE', ), + BasePeer::TYPE_FIELDNAME => array ('id', 'name', 'url', 'genre', 'description', 'color', 'background_color', 'live_stream_using_airtime_auth', 'live_stream_using_custom_auth', 'live_stream_user', 'live_stream_pass', 'linked', 'is_linkable', ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ) ); /** @@ -95,12 +101,12 @@ abstract class BaseCcShowPeer { * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 */ private static $fieldKeys = array ( - BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbName' => 1, 'DbUrl' => 2, 'DbGenre' => 3, 'DbDescription' => 4, 'DbColor' => 5, 'DbBackgroundColor' => 6, 'DbLiveStreamUsingAirtimeAuth' => 7, 'DbLiveStreamUsingCustomAuth' => 8, 'DbLiveStreamUser' => 9, 'DbLiveStreamPass' => 10, ), - BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbName' => 1, 'dbUrl' => 2, 'dbGenre' => 3, 'dbDescription' => 4, 'dbColor' => 5, 'dbBackgroundColor' => 6, 'dbLiveStreamUsingAirtimeAuth' => 7, 'dbLiveStreamUsingCustomAuth' => 8, 'dbLiveStreamUser' => 9, 'dbLiveStreamPass' => 10, ), - BasePeer::TYPE_COLNAME => array (self::ID => 0, self::NAME => 1, self::URL => 2, self::GENRE => 3, self::DESCRIPTION => 4, self::COLOR => 5, self::BACKGROUND_COLOR => 6, self::LIVE_STREAM_USING_AIRTIME_AUTH => 7, self::LIVE_STREAM_USING_CUSTOM_AUTH => 8, self::LIVE_STREAM_USER => 9, self::LIVE_STREAM_PASS => 10, ), - BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'NAME' => 1, 'URL' => 2, 'GENRE' => 3, 'DESCRIPTION' => 4, 'COLOR' => 5, 'BACKGROUND_COLOR' => 6, 'LIVE_STREAM_USING_AIRTIME_AUTH' => 7, 'LIVE_STREAM_USING_CUSTOM_AUTH' => 8, 'LIVE_STREAM_USER' => 9, 'LIVE_STREAM_PASS' => 10, ), - BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'name' => 1, 'url' => 2, 'genre' => 3, 'description' => 4, 'color' => 5, 'background_color' => 6, 'live_stream_using_airtime_auth' => 7, 'live_stream_using_custom_auth' => 8, 'live_stream_user' => 9, 'live_stream_pass' => 10, ), - BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ) + BasePeer::TYPE_PHPNAME => array ('DbId' => 0, 'DbName' => 1, 'DbUrl' => 2, 'DbGenre' => 3, 'DbDescription' => 4, 'DbColor' => 5, 'DbBackgroundColor' => 6, 'DbLiveStreamUsingAirtimeAuth' => 7, 'DbLiveStreamUsingCustomAuth' => 8, 'DbLiveStreamUser' => 9, 'DbLiveStreamPass' => 10, 'DbLinked' => 11, 'DbIsLinkable' => 12, ), + BasePeer::TYPE_STUDLYPHPNAME => array ('dbId' => 0, 'dbName' => 1, 'dbUrl' => 2, 'dbGenre' => 3, 'dbDescription' => 4, 'dbColor' => 5, 'dbBackgroundColor' => 6, 'dbLiveStreamUsingAirtimeAuth' => 7, 'dbLiveStreamUsingCustomAuth' => 8, 'dbLiveStreamUser' => 9, 'dbLiveStreamPass' => 10, 'dbLinked' => 11, 'dbIsLinkable' => 12, ), + BasePeer::TYPE_COLNAME => array (self::ID => 0, self::NAME => 1, self::URL => 2, self::GENRE => 3, self::DESCRIPTION => 4, self::COLOR => 5, self::BACKGROUND_COLOR => 6, self::LIVE_STREAM_USING_AIRTIME_AUTH => 7, self::LIVE_STREAM_USING_CUSTOM_AUTH => 8, self::LIVE_STREAM_USER => 9, self::LIVE_STREAM_PASS => 10, self::LINKED => 11, self::IS_LINKABLE => 12, ), + BasePeer::TYPE_RAW_COLNAME => array ('ID' => 0, 'NAME' => 1, 'URL' => 2, 'GENRE' => 3, 'DESCRIPTION' => 4, 'COLOR' => 5, 'BACKGROUND_COLOR' => 6, 'LIVE_STREAM_USING_AIRTIME_AUTH' => 7, 'LIVE_STREAM_USING_CUSTOM_AUTH' => 8, 'LIVE_STREAM_USER' => 9, 'LIVE_STREAM_PASS' => 10, 'LINKED' => 11, 'IS_LINKABLE' => 12, ), + BasePeer::TYPE_FIELDNAME => array ('id' => 0, 'name' => 1, 'url' => 2, 'genre' => 3, 'description' => 4, 'color' => 5, 'background_color' => 6, 'live_stream_using_airtime_auth' => 7, 'live_stream_using_custom_auth' => 8, 'live_stream_user' => 9, 'live_stream_pass' => 10, 'linked' => 11, 'is_linkable' => 12, ), + BasePeer::TYPE_NUM => array (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ) ); /** @@ -183,6 +189,8 @@ abstract class BaseCcShowPeer { $criteria->addSelectColumn(CcShowPeer::LIVE_STREAM_USING_CUSTOM_AUTH); $criteria->addSelectColumn(CcShowPeer::LIVE_STREAM_USER); $criteria->addSelectColumn(CcShowPeer::LIVE_STREAM_PASS); + $criteria->addSelectColumn(CcShowPeer::LINKED); + $criteria->addSelectColumn(CcShowPeer::IS_LINKABLE); } else { $criteria->addSelectColumn($alias . '.ID'); $criteria->addSelectColumn($alias . '.NAME'); @@ -195,6 +203,8 @@ abstract class BaseCcShowPeer { $criteria->addSelectColumn($alias . '.LIVE_STREAM_USING_CUSTOM_AUTH'); $criteria->addSelectColumn($alias . '.LIVE_STREAM_USER'); $criteria->addSelectColumn($alias . '.LIVE_STREAM_PASS'); + $criteria->addSelectColumn($alias . '.LINKED'); + $criteria->addSelectColumn($alias . '.IS_LINKABLE'); } } diff --git a/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php b/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php index 580a7b1ad..687335e03 100644 --- a/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php +++ b/airtime_mvc/application/models/airtime/om/BaseCcShowQuery.php @@ -17,6 +17,8 @@ * @method CcShowQuery orderByDbLiveStreamUsingCustomAuth($order = Criteria::ASC) Order by the live_stream_using_custom_auth column * @method CcShowQuery orderByDbLiveStreamUser($order = Criteria::ASC) Order by the live_stream_user column * @method CcShowQuery orderByDbLiveStreamPass($order = Criteria::ASC) Order by the live_stream_pass column + * @method CcShowQuery orderByDbLinked($order = Criteria::ASC) Order by the linked column + * @method CcShowQuery orderByDbIsLinkable($order = Criteria::ASC) Order by the is_linkable column * * @method CcShowQuery groupByDbId() Group by the id column * @method CcShowQuery groupByDbName() Group by the name column @@ -29,6 +31,8 @@ * @method CcShowQuery groupByDbLiveStreamUsingCustomAuth() Group by the live_stream_using_custom_auth column * @method CcShowQuery groupByDbLiveStreamUser() Group by the live_stream_user column * @method CcShowQuery groupByDbLiveStreamPass() Group by the live_stream_pass column + * @method CcShowQuery groupByDbLinked() Group by the linked column + * @method CcShowQuery groupByDbIsLinkable() Group by the is_linkable column * * @method CcShowQuery leftJoin($relation) Adds a LEFT JOIN clause to the query * @method CcShowQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query @@ -64,6 +68,8 @@ * @method CcShow findOneByDbLiveStreamUsingCustomAuth(boolean $live_stream_using_custom_auth) Return the first CcShow filtered by the live_stream_using_custom_auth column * @method CcShow findOneByDbLiveStreamUser(string $live_stream_user) Return the first CcShow filtered by the live_stream_user column * @method CcShow findOneByDbLiveStreamPass(string $live_stream_pass) Return the first CcShow filtered by the live_stream_pass column + * @method CcShow findOneByDbLinked(boolean $linked) Return the first CcShow filtered by the linked column + * @method CcShow findOneByDbIsLinkable(boolean $is_linkable) Return the first CcShow filtered by the is_linkable column * * @method array findByDbId(int $id) Return CcShow objects filtered by the id column * @method array findByDbName(string $name) Return CcShow objects filtered by the name column @@ -76,6 +82,8 @@ * @method array findByDbLiveStreamUsingCustomAuth(boolean $live_stream_using_custom_auth) Return CcShow objects filtered by the live_stream_using_custom_auth column * @method array findByDbLiveStreamUser(string $live_stream_user) Return CcShow objects filtered by the live_stream_user column * @method array findByDbLiveStreamPass(string $live_stream_pass) Return CcShow objects filtered by the live_stream_pass column + * @method array findByDbLinked(boolean $linked) Return CcShow objects filtered by the linked column + * @method array findByDbIsLinkable(boolean $is_linkable) Return CcShow objects filtered by the is_linkable column * * @package propel.generator.airtime.om */ @@ -412,6 +420,40 @@ abstract class BaseCcShowQuery extends ModelCriteria return $this->addUsingAlias(CcShowPeer::LIVE_STREAM_PASS, $dbLiveStreamPass, $comparison); } + /** + * Filter the query on the linked column + * + * @param boolean|string $dbLinked The value to use as filter. + * Accepts strings ('false', 'off', '-', 'no', 'n', and '0' are false, the rest is true) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowQuery The current query, for fluid interface + */ + public function filterByDbLinked($dbLinked = null, $comparison = null) + { + if (is_string($dbLinked)) { + $linked = in_array(strtolower($dbLinked), array('false', 'off', '-', 'no', 'n', '0')) ? false : true; + } + return $this->addUsingAlias(CcShowPeer::LINKED, $dbLinked, $comparison); + } + + /** + * Filter the query on the is_linkable column + * + * @param boolean|string $dbIsLinkable The value to use as filter. + * Accepts strings ('false', 'off', '-', 'no', 'n', and '0' are false, the rest is true) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return CcShowQuery The current query, for fluid interface + */ + public function filterByDbIsLinkable($dbIsLinkable = null, $comparison = null) + { + if (is_string($dbIsLinkable)) { + $is_linkable = in_array(strtolower($dbIsLinkable), array('false', 'off', '-', 'no', 'n', '0')) ? false : true; + } + return $this->addUsingAlias(CcShowPeer::IS_LINKABLE, $dbIsLinkable, $comparison); + } + /** * Filter the query by a related CcShowInstances object * diff --git a/airtime_mvc/application/services/CalendarService.php b/airtime_mvc/application/services/CalendarService.php new file mode 100644 index 000000000..1c963fc45 --- /dev/null +++ b/airtime_mvc/application/services/CalendarService.php @@ -0,0 +1,326 @@ +ccShowInstance = CcShowInstancesQuery::create()->findPk($instanceId); + if (is_null($this->ccShowInstance)) { + throw new Exception("Instance does not exist"); + } + $this->ccShow = $this->ccShowInstance->getCcShow(); + } + + $service_user = new Application_Service_UserService(); + $this->currentUser = $service_user->getCurrentUser(); + } + + /** + * + * Enter description here ... + */ + public function makeContextMenu() + { + $menu = array(); + $now = time(); + $baseUrl = Application_Common_OsPath::getBaseDir(); + $isAdminOrPM = $this->currentUser->isAdminOrPM(); + $isHostOfShow = $this->currentUser->isHostOfShow($this->ccShow->getDbId()); + + //DateTime objects in UTC + $startDT = $this->ccShowInstance->getDbStarts(null); + $endDT = $this->ccShowInstance->getDbEnds(null); + + //timestamps + $start = $startDT->getTimestamp(); + $end = $endDT->getTimestamp(); + + //show has ended + if ($now > $end) { + if ($this->ccShowInstance->isRecorded()) { + + $ccFile = $this->ccShowInstance->getCcFiles(); + + $menu["view_recorded"] = array( + "name" => _("View Recorded File Metadata"), + "icon" => "overview", + "url" => $baseUrl."library/edit-file-md/id/".$ccFile->getDbId()); + + //recorded show can be uploaded to soundcloud + if (Application_Model_Preference::GetUploadToSoundcloudOption()) { + $scid = $ccFile->getDbSoundcloudId(); + + if ($scid > 0) { + $menu["soundcloud_view"] = array( + "name" => _("View on Soundcloud"), + "icon" => "soundcloud", + "url" => $ccFile->getDbSoundcloudLinkToFile()); + } + + $text = is_null($scid) ? _('Upload to SoundCloud') : _('Re-upload to SoundCloud'); + $menu["soundcloud_upload"] = array( + "name"=> $text, + "icon" => "soundcloud"); + } + } + } else { + //Show content can be modified from the calendar if: + // the show has not started, + // the user is admin or hosting the show, + // the show is not recorded or rebroadcasted + if ($now < $start && ($isAdminOrPM || $isHostOfShow) && + !$this->ccShowInstance->isRecorded() && !$this->ccShowInstance->isRebroadcast()) { + + $menu["schedule"] = array( + "name"=> _("Add / Remove Content"), + "icon" => "add-remove-content", + "url" => $baseUrl."showbuilder/builder-dialog/"); + + $menu["clear"] = array( + "name"=> _("Remove All Content"), + "icon" => "remove-all-content", + "url" => $baseUrl."schedule/clear-show"); + } + + //"Show Content" should be a menu item at all times except when + //the show is recorded + if (!$this->ccShowInstance->isRecorded()) { + + $menu["content"] = array( + "name"=> _("Show Content"), + "icon" => "overview", + "url" => $baseUrl."schedule/show-content-dialog"); + } + + //show is currently playing and user is admin + if ($start <= $now && $now < $end && $isAdminOrPM) { + + if ($this->ccShowInstance->isRecorded()) { + $menu["cancel_recorded"] = array( + "name"=> _("Cancel Current Show"), + "icon" => "delete"); + } else { + $menu["cancel"] = array( + "name"=> _("Cancel Current Show"), + "icon" => "delete"); + } + } + + $isRepeating = $this->ccShow->getFirstCcShowDay()->isRepeating(); + if (!$this->ccShowInstance->isRebroadcast()) { + if ($isRepeating) { + $menu["edit"] = array( + "name" => _("Edit"), + "icon" => "edit", + "items" => array()); + + $menu["edit"]["items"]["all"] = array( + "name" => _("Edit Show"), + "icon" => "edit", + "url" => $baseUrl."Schedule/populate-show-form"); + + $menu["edit"]["items"]["instance"] = array( + "name" => _("Edit This Instance"), + "icon" => "edit", + "url" => $baseUrl."Schedule/populate-repeating-show-instance-form"); + } else { + $menu["edit"] = array( + "name"=> _("Edit Show"), + "icon" => "edit", + "_type"=>"all", + "url" => $baseUrl."Schedule/populate-show-form"); + } + } + + //show hasn't started yet and user is admin + if ($now < $start && $isAdminOrPM) { + //show is repeating so give user the option to delete all + //repeating instances or just the one + if ($isRepeating) { + $menu["del"] = array( + "name"=> _("Delete"), + "icon" => "delete", + "items" => array()); + + $menu["del"]["items"]["single"] = array( + "name"=> _("Delete This Instance"), + "icon" => "delete", + "url" => $baseUrl."schedule/delete-show-instance"); + + $menu["del"]["items"]["following"] = array( + "name"=> _("Delete This Instance and All Following"), + "icon" => "delete", + "url" => $baseUrl."schedule/delete-show"); + } else { + $menu["del"] = array( + "name"=> _("Delete"), + "icon" => "delete", + "url" => $baseUrl."schedule/delete-show"); + } + } + } + return $menu; + } + + /** + * + * Enter description here ... + * @param DateTime $dateTime object to add deltas to + * @param int $deltaDay delta days show moved + * @param int $deltaMin delta minutes show moved + */ + public static function addDeltas($dateTime, $deltaDay, $deltaMin) + { + $newDateTime = clone $dateTime; + + $days = abs($deltaDay); + $mins = abs($deltaMin); + + $dayInterval = new DateInterval("P{$days}D"); + $minInterval = new DateInterval("PT{$mins}M"); + + if ($deltaDay > 0) { + $newDateTime->add($dayInterval); + } elseif ($deltaDay < 0) { + $newDateTime->sub($dayInterval); + } + + if ($deltaMin > 0) { + $newDateTime->add($minInterval); + } elseif ($deltaMin < 0) { + $newDateTime->sub($minInterval); + } + + return $newDateTime; + } + + private function validateShowMove($deltaDay, $deltaMin) + { + if (!$this->currentUser->isAdminOrPM()) { + throw new Exception(_("Permission denied")); + } + + if ($this->ccShow->getFirstCcShowDay()->isRepeating()) { + throw new Exception(_("Can't drag and drop repeating shows")); + } + + $today_timestamp = time(); + + $startsDateTime = new DateTime($this->ccShowInstance->getDbStarts(), new DateTimeZone("UTC")); + $endsDateTime = new DateTime($this->ccShowInstance->getDbEnds(), new DateTimeZone("UTC")); + + if ($today_timestamp > $startsDateTime->getTimestamp()) { + throw new Exception(_("Can't move a past show")); + } + + //the user is moving the show on the calendar from the perspective of local time. + //incase a show is moved across a time change border offsets should be added to the localtime + //stamp and then converted back to UTC to avoid show time changes! + $localTimezone = Application_Model_Preference::GetTimezone(); + $startsDateTime->setTimezone(new DateTimeZone($localTimezone)); + $endsDateTime->setTimezone(new DateTimeZone($localTimezone)); + + $newStartsDateTime = self::addDeltas($startsDateTime, $deltaDay, $deltaMin); + $newEndsDateTime = self::addDeltas($endsDateTime, $deltaDay, $deltaMin); + + //convert our new starts/ends to UTC. + $newStartsDateTime->setTimezone(new DateTimeZone("UTC")); + $newEndsDateTime->setTimezone(new DateTimeZone("UTC")); + + if ($today_timestamp > $newStartsDateTime->getTimestamp()) { + throw new Exception(_("Can't move show into past")); + } + + //check if show is overlapping + $overlapping = Application_Model_Schedule::checkOverlappingShows( + $newStartsDateTime, $newEndsDateTime, true, $this->ccShowInstance->getDbId()); + if ($overlapping) { + throw new Exception(_("Cannot schedule overlapping shows")); + } + + if ($this->ccShow->isRecorded()) { + //rebroadcasts should start at max 1 hour after a recorded show has ended. + $minRebroadcastStart = self::addDeltas($newEndsDateTime, 0, 60); + //check if we are moving a recorded show less than 1 hour before any of its own rebroadcasts. + $rebroadcasts = CcShowInstancesQuery::create() + ->filterByDbOriginalShow($this->_instanceId) + ->filterByDbStarts($minRebroadcastStart->format('Y-m-d H:i:s'), Criteria::LESS_THAN) + ->find(); + + if (count($rebroadcasts) > 0) { + throw new Exception(_("Can't move a recorded show less than 1 hour before its rebroadcasts.")); + } + } + + if ($this->ccShow->isRebroadcast()) { + $recordedShow = CcShowInstancesQuery::create()->findPk( + $this->ccShowInstance->getDbOriginalShow()); + if (is_null($recordedShow)) { + $this->ccShowInstance->delete(); + throw new Exception(_("Show was deleted because recorded show does not exist!")); + } + + $recordEndDateTime = new DateTime($recordedShow->getDbEnds(), new DateTimeZone("UTC")); + $newRecordEndDateTime = self::addDeltas($recordEndDateTime, 0, 60); + + if ($newStartsDateTime->getTimestamp() < $newRecordEndDateTime->getTimestamp()) { + throw new Exception(_("Must wait 1 hour to rebroadcast.")); + } + } + return array($newStartsDateTime, $newEndsDateTime); + } + + public function moveShow($deltaDay, $deltaMin) + { + try { + $con = Propel::getConnection(); + $con->beginTransaction(); + + list($newStartsDateTime, $newEndsDateTime) = $this->validateShowMove( + $deltaDay, $deltaMin); + + $this->ccShowInstance + ->setDbStarts($newStartsDateTime) + ->setDbEnds($newEndsDateTime) + ->save(); + + if (!$this->ccShowInstance->getCcShow()->isRebroadcast()) { + //we can get the first show day because we know the show is + //not repeating, and therefore will only have one show day entry + $ccShowDay = $this->ccShow->getFirstCcShowDay(); + $ccShowDay + ->setDbFirstShow($newStartsDateTime) + ->setDbLastShow($newEndsDateTime) + ->save(); + } + + Application_Service_SchedulerService::updateScheduleStartTime( + array($this->ccShowInstance->getDbId()), null, $newStartsDateTime); + + $con->commit(); + Application_Model_RabbitMq::PushSchedule(); + } catch (Exception $e) { + $con->rollback(); + return $e->getMessage(); + } + } + + public function resizeShow($deltaDay, $deltaMin) + { + try { + $con = Propel::getConnection(); + $con->beginTransaction(); + + $con->commit(); + Application_Model_RabbitMq::PushSchedule(); + } catch (Exception $e) { + return $e->getMessage(); + } + } + +} \ No newline at end of file diff --git a/airtime_mvc/application/services/SchedulerService.php b/airtime_mvc/application/services/SchedulerService.php new file mode 100644 index 000000000..b8086e4a2 --- /dev/null +++ b/airtime_mvc/application/services/SchedulerService.php @@ -0,0 +1,207 @@ + "", + "cliplength" => "", + "cuein" => "00:00:00", + "cueout" => "00:00:00", + "fadein" => "00:00:00", + "fadeout" => "00:00:00", + "sched_id" => null, + "type" => 0 //default type of '0' to represent files. type '1' represents a webstream + ); + + private $epochNow; + private $nowDT; + private $currentUser; + private $checkUserPermissions = true; + + public function __construct() + { + $this->con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + + //subtracting one because sometimes when we cancel a track, we set its end time + //to epochNow and then send the new schedule to pypo. Sometimes the currently cancelled + //track can still be included in the new schedule because it may have a few ms left to play. + //subtracting 1 second from epochNow resolves this issue. + $this->epochNow = microtime(true)-1; + $this->nowDT = DateTime::createFromFormat("U.u", $this->epochNow, new DateTimeZone("UTC")); + + if ($this->nowDT === false) { + // DateTime::createFromFormat does not support millisecond string formatting in PHP 5.3.2 (Ubuntu 10.04). + // In PHP 5.3.3 (Ubuntu 10.10), this has been fixed. + $this->nowDT = DateTime::createFromFormat("U", time(), new DateTimeZone("UTC")); + } + + $user_service = new Application_Service_UserService(); + $this->currentUser = $user_service->getCurrentUser(); + } + + /** + * + * Enter description here ... + * @param array $instanceIds + */ + public static function updateScheduleStartTime($instanceIds, $diff=null, $newStart=null) + { + $con = Propel::getConnection(); + if (count($instanceIds) > 0) { + $showIdList = implode(",", $instanceIds); + + if (is_null($diff)) { + $ccSchedule = CcScheduleQuery::create() + ->filterByDbInstanceId($instanceIds, Criteria::IN) + ->orderByDbStarts() + ->limit(1) + ->findOne(); + + if (!is_null($ccSchedule)) { + $scheduleStartsEpoch = strtotime($ccSchedule->getDbStarts()); + $showStartsEpoch = strtotime($newStart->format("Y-m-d H:i:s")); + + $diff = $showStartsEpoch - $scheduleStartsEpoch; + } + } + + $ccSchedules = CcScheduleQuery::create() + ->filterByDbInstanceId($instanceIds, Criteria::IN) + ->find(); + foreach ($ccSchedules as $ccSchedule) { + $interval = new DateInterval("PT".$diff."S"); + $start = new DateTime($ccSchedule->getDbStarts()); + $newStart = $start->add($interval); + $end = new DateTime($ccSchedule->getDbEnds()); + $newEnd = $end->add($interval); + $ccSchedule + ->setDbStarts($newStart->format("Y-m-d H:i:s")) + ->setDbEnds($newEnd->format("Y-m-d H:i:s")) + ->save(); + } + } + } + + /** + * + * Removes any time gaps in shows + * + * @param array $schedIds schedule ids to exclude + */ + public function removeGaps($showId, $schedIds=null) + { + $ccShowInstances = CcShowInstancesQuery::create()->filterByDbShowId($showId)->find(); + + foreach ($ccShowInstances as $instance) { + Logging::info("Removing gaps from show instance #".$instance->getDbId()); + //DateTime object + $itemStart = $instance->getDbStarts(null); + + $ccScheduleItems = CcScheduleQuery::create() + ->filterByDbInstanceId($instance->getDbId()) + ->filterByDbId($schedIds, Criteria::NOT_IN) + ->orderByDbStarts() + ->find(); + + foreach ($ccScheduleItems as $ccSchedule) { + //DateTime object + $itemEnd = $this->findEndTime($itemStart, $ccSchedule->getDbClipLength()); + + $ccSchedule->setDbStarts($itemStart) + ->setDbEnds($itemEnd); + + $itemStart = $itemEnd; + } + $ccScheduleItems->save(); + } + } + + /** + * + * Enter description here ... + * @param DateTime $instanceStart + * @param string $clipLength + */ + private static function findEndTime($instanceStart, $clipLength) + { + $startEpoch = $instanceStart->format("U.u"); + $durationSeconds = Application_Common_DateHelper::playlistTimeToSeconds($clipLength); + + //add two float numbers to 6 subsecond precision + //DateTime::createFromFormat("U.u") will have a problem if there is no decimal in the resulting number. + $endEpoch = bcadd($startEpoch , (string) $durationSeconds, 6); + + $dt = DateTime::createFromFormat("U.u", $endEpoch, new DateTimeZone("UTC")); + + if ($dt === false) { + //PHP 5.3.2 problem + $dt = DateTime::createFromFormat("U", intval($endEpoch), new DateTimeZone("UTC")); + } + + return $dt; + } + + public static function fillLinkedShows($ccShow) + { + if ($ccShow->isLinked()) { + /* First check if any linked instances have content + * If all instances are empty then we don't need to fill + * any other instances with content + */ + $instanceIds = $ccShow->getInstanceIds(); + $ccSchedules = CcScheduleQuery::create() + ->filterByDbInstanceId($instanceIds, Criteria::IN) + ->find(); + if (!$ccSchedules->isEmpty()) { + /* Find the show contents of just one of the instances. It doesn't + * matter which instance we use since all the content is the same + */ + $ccSchedule = $ccSchedules->getFirst(); + $showStamp = CcScheduleQuery::create() + ->filterByDbInstanceId($ccSchedule->getDbInstanceId()) + ->orderByDbStarts() + ->find(); + + //get time_filled so we can update cc_show_instances + $timeFilled = $ccSchedule->getCcShowInstances()->getDbTimeFilled(); + + //need to find out which linked instances are empty + foreach ($ccShow->getCcShowInstancess() as $ccShowInstance) { + $ccSchedules = CcScheduleQuery::create() + ->filterByDbInstanceId($ccShowInstance->getDbId()) + ->find(); + if ($ccSchedules->isEmpty()) { + $nextStartDT = $ccShowInstance->getDbStarts(null); + + foreach ($showStamp as $item) { + $endTimeDT = self::findEndTime($nextStartDT, $item->getDbClipLength()); + + $ccSchedule = new CcSchedule(); + $ccSchedule + ->setDbStarts($nextStartDT) + ->setDbEnds($endTimeDT) + ->setDbFileId($item->getDbFileId()) + ->setDbStreamId($item->getDbStreamId()) + ->setDbClipLength($item->getDbClipLength()) + ->setDbFadeIn($item->getDbFadeIn()) + ->setDbFadeOut($item->getDbFadeOut()) + ->setDbCuein($item->getDbCueIn()) + ->setDbCueOut($item->getDbCueOut()) + ->setDbInstanceId($ccShowInstance->getDbId()) + ->setDbPosition($item->getDbPosition()) + ->save(); + + $nextStartDT = $endTimeDT; + } //foreach show item + + //update time_filled in cc_show_instances + $ccShowInstance + ->setDbTimeFilled($timeFilled) + ->setDbLastScheduled(gmdate("Y-m-d H:i:s")) + ->save(); + } + } //foreach linked instance + } //if at least one linked instance has content + } + } +} \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowFormService.php b/airtime_mvc/application/services/ShowFormService.php new file mode 100644 index 000000000..e9cb8c5ea --- /dev/null +++ b/airtime_mvc/application/services/ShowFormService.php @@ -0,0 +1,449 @@ +ccShow = CcShowQuery::create()->findPk($showId); + } + $this->instanceId = $instanceId; + } + + /** + * + * @return array of show forms + */ + public function createShowForms() + { + $formWhat = new Application_Form_AddShowWhat(); + $formWho = new Application_Form_AddShowWho(); + $formWhen = new Application_Form_AddShowWhen(); + $formRepeats = new Application_Form_AddShowRepeats(); + $formStyle = new Application_Form_AddShowStyle(); + $formLive = new Application_Form_AddShowLiveStream(); + $formRecord = new Application_Form_AddShowRR(); + $formAbsoluteRebroadcast = new Application_Form_AddShowAbsoluteRebroadcastDates(); + $formRebroadcast = new Application_Form_AddShowRebroadcastDates(); + + $formWhat->removeDecorator('DtDdWrapper'); + $formWho->removeDecorator('DtDdWrapper'); + $formWhen->removeDecorator('DtDdWrapper'); + $formRepeats->removeDecorator('DtDdWrapper'); + $formStyle->removeDecorator('DtDdWrapper'); + $formLive->removeDecorator('DtDdWrapper'); + $formRecord->removeDecorator('DtDdWrapper'); + $formAbsoluteRebroadcast->removeDecorator('DtDdWrapper'); + $formRebroadcast->removeDecorator('DtDdWrapper'); + + $forms = array(); + $forms["what"] = $formWhat; + $forms["who"] = $formWho; + $forms["when"] = $formWhen; + $forms["repeats"] = $formRepeats; + $forms["style"] = $formStyle; + $forms["live"] = $formLive; + $forms["record"] = $formRecord; + $forms["abs_rebroadcast"] = $formAbsoluteRebroadcast; + $forms["rebroadcast"] = $formRebroadcast; + + return $forms; + } + + /** + * + * Popluates the what, when, and repeat forms + * with default values + */ + public function populateNewShowForms($formWhat, $formWhen, $formRepeats) + { + $formWhat->populate( + array('add_show_id' => '-1', + 'add_show_instance_id' => '-1')); + + $formWhen->populate( + array('add_show_start_date' => date("Y-m-d"), + 'add_show_start_time' => '00:00', + 'add_show_end_date_no_repeate' => date("Y-m-d"), + 'add_show_end_time' => '01:00', + 'add_show_duration' => '01h 00m')); + + $formRepeats->populate(array('add_show_end_date' => date("Y-m-d"))); + } + + public function delegateShowInstanceFormPopulation($forms) + { + $this->populateFormWhat($forms["what"]); + $this->populateInstanceFormWhen($forms["when"]); + $this->populateFormWho($forms["who"]); + $this->populateFormLive($forms["live"]); + $this->populateFormStyle($forms["style"]); + + //no need to populate these forms since the user won't + //be able to see them + $forms["repeats"]->disable(); + $forms["record"]->disable(); + $forms["rebroadcast"]->disable(); + $forms["abs_rebroadcast"]->disable(); + } + + /** + * + * Delegates populating each show form with the appropriate + * data of the current show being edited + * + * @param $forms + */ + public function delegateShowFormPopulation($forms) + { + $this->populateFormWhat($forms["what"]); + $this->populateFormWhen($forms["when"]); + $this->populateFormRepeats($forms["repeats"]); + $this->populateFormWho($forms["who"]); + $this->populateFormStyle($forms["style"]); + $this->populateFormLive($forms["live"]); + $this->populateFormRecord($forms["record"]); + $this->populateFormRebroadcastRelative($forms["rebroadcast"]); + $this->populateFormRebroadcastAbsolute($forms["abs_rebroadcast"]); + } + + private function populateFormWhat($form) + { + $form->populate( + array( + 'add_show_instance_id' => $this->instanceId, + 'add_show_id' => $this->ccShow->getDbId(), + 'add_show_name' => $this->ccShow->getDbName(), + 'add_show_url' => $this->ccShow->getDbUrl(), + 'add_show_genre' => $this->ccShow->getDbGenre(), + 'add_show_description' => $this->ccShow->getDbDescription())); + } + + private function populateFormWhen($form) + { + $ccShowDay = $this->ccShow->getFirstCcShowDay(); + + $showStart = $ccShowDay->getLocalStartDateAndTime(); + $showEnd = $ccShowDay->getLocalEndDateAndTime($showStart); + + //check if the first show is in the past + if ($ccShowDay->isShowStartInPast()) { + //for a non-repeating show, we should never allow user to change the start time. + //for a repeating show, we should allow because the form works as repeating template form + if (!$ccShowDay->isRepeating()) { + $form->disableStartDateAndTime(); + } else { + list($showStart, $showEnd) = $this->getNextFutureRepeatShowTime(); + } + } + + $form->populate( + array( + 'add_show_start_date' => $showStart->format("Y-m-d"), + 'add_show_start_time' => $showStart->format("H:i"), + 'add_show_end_date_no_repeat' => $showEnd->format("Y-m-d"), + 'add_show_end_time' => $showEnd->format("H:i"), + 'add_show_duration' => $ccShowDay->formatDuration(true), + 'add_show_repeats' => $ccShowDay->isRepeating() ? 1 : 0)); + } + + private function populateInstanceFormWhen($form) + { + $ccShowInstance = CcShowInstancesQuery::create()->findPk($this->instanceId); + + $timezone = new DateTimeZone(Application_Model_Preference::GetTimezone()); + //DateTime object in UTC + $showStart = $ccShowInstance->getDbStarts(null); + $showStart->setTimezone($timezone); + + $showEnd = $ccShowInstance->getDbEnds(null); + $showEnd->setTimezone($timezone); + + //if the show has started, do not allow editing on the start time + if ($showStart->getTimestamp() <= time()) { + $form->disableStartDateAndTime(); + } + + $form->populate( + array( + 'add_show_start_date' => $showStart->format("Y-m-d"), + 'add_show_start_time' => $showStart->format("H:i"), + 'add_show_end_date_no_repeat' => $showEnd->format("Y-m-d"), + 'add_show_end_time' => $showEnd->format("H:i"), + 'add_show_duration' => $this->calculateDuration( + $showStart->format("Y-m-d H:i:s"), $showEnd->format("Y-m-d H:i:s")), + 'add_show_repeats' => 0)); + + $form->getElement('add_show_repeats')->setOptions(array("disabled" => true)); + } + + private function populateFormRepeats($form) + { + $ccShowDays = $this->ccShow->getCcShowDays(); + + $days = array(); + foreach ($ccShowDays as $ccShowDay) { + $showStart = $ccShowDay->getLocalStartDateAndTime(); + array_push($days, $showStart->format("w")); + } + + $service_show = new Application_Service_ShowService($this->ccShow->getDbId()); + $repeatEndDate = new DateTime($service_show->getRepeatingEndDate(), new DateTimeZone( + $ccShowDays[0]->getDbTimezone())); + //end dates are stored non-inclusively so we need to + //subtract one day + $repeatEndDate->sub(new DateInterval("P1D")); + + //default monthly repeat type + $monthlyRepeatType = 2; + $repeatType = $ccShowDays[0]->getDbRepeatType(); + if ($repeatType == REPEAT_MONTHLY_WEEKLY) { + $monthlyRepeatType = $repeatType; + //a repeat type of 2 means the show is repeating monthly + $repeatType = 2; + } elseif ($repeatType == REPEAT_MONTHLY_MONTHLY) { + $monthlyRepeatType = $repeatType; + } + + $form->populate( + array( + 'add_show_linked' => $this->ccShow->getDbLinked(), + 'add_show_repeat_type' => $repeatType, + 'add_show_day_check' => $days, + 'add_show_end_date' => $repeatEndDate->format("Y-m-d"), + 'add_show_no_end' => (!$service_show->getRepeatingEndDate()), + 'add_show_monthly_repeat_type' => $monthlyRepeatType)); + + if (!$this->ccShow->isLinkable()) { + $form->getElement('add_show_linked')->setOptions(array('disabled' => true)); + } + } + + private function populateFormWho($form) + { + $ccShowHosts = $this->ccShow->getCcShowHostss(); + + $hosts = array(); + foreach ($ccShowHosts as $ccShowHost) { + array_push($hosts, $ccShowHost->getDbHost()); + } + + $form->populate(array('add_show_hosts' => $hosts)); + } + + private function populateFormStyle($form) + { + $form->populate( + array( + 'add_show_background_color' => $this->ccShow->getDbBackgroundColor(), + 'add_show_color' => $this->ccShow->getDbColor())); + } + + private function populateFormLive($form) + { + $form->populate( + array( + "cb_airtime_auth" => $this->ccShow->getDbLiveStreamUsingAirtimeAuth(), + "cb_custom_auth" => $this->ccShow->getDbLiveStreamUsingCustomAuth(), + "custom_username" => $this->ccShow->getDbLiveStreamUser(), + "custom_password" => $this->ccShow->getDbLiveStreamPass())); + } + + private function populateFormRecord($form) + { + $form->populate( + array( + 'add_show_record' => $this->ccShow->isRecorded(), + 'add_show_rebroadcast' => $this->ccShow->isRebroadcast())); + + $form->getElement('add_show_record')->setOptions(array('disabled' => true)); + } + + private function populateFormRebroadcastRelative($form) + { + $relativeRebroadcasts = $this->ccShow->getRebroadcastsRelative(); + + $formValues = array(); + $i = 1; + foreach ($relativeRebroadcasts as $rr) { + $formValues["add_show_rebroadcast_date_$i"] = $rr->getDbDayOffset(); + $formValues["add_show_rebroadcast_time_$i"] = Application_Common_DateHelper::removeSecondsFromTime( + $rr->getDbStartTime()); + $i++; + } + + $form->populate($formValues); + } + + private function populateFormRebroadcastAbsolute($form) + { + $absolutRebroadcasts = $this->ccShow->getRebroadcastsAbsolute(); + + $formValues = array(); + $i = 1; + foreach ($absolutRebroadcasts as $ar) { + //convert dates to user's local time + $start = new DateTime($ar->getDbStarts(), new DateTimeZone("UTC")); + $start->setTimezone(new DateTimeZone(Application_Model_Preference::GetTimezone())); + $formValues["add_show_rebroadcast_date_absolute_$i"] = $start->format("Y-m-d"); + $formValues["add_show_rebroadcast_time_absolute_$i"] = $start->format("H:i"); + $i++; + } + + $form->populate($formValues); + } + + /** + * + * Before we send the form data in for validation, there + * are a few fields we may need to adjust first + * @param $formData + */ + public function preEditShowValidationCheck($formData) + { + $validateStartDate = true; + $validateStartTime = true; + + //CcShowDays object of the show currently being edited + $currentShowDay = $this->ccShow->getFirstCcShowDay(); + + //DateTime object + $dt = $currentShowDay->getLocalStartDateAndTime(); + + if (!array_key_exists('add_show_start_date', $formData)) { + //Changing the start date was disabled, since the + //array key does not exist. We need to repopulate this entry from the db. + $formData['add_show_start_date'] = $dt->format("Y-m-d"); + + if (!array_key_exists('add_show_start_time', $formData)) { + $formData['add_show_start_time'] = $dt->format("H:i"); + $validateStartTime = false; + } + $validateStartDate = false; + } + $formData['add_show_record'] = $currentShowDay->getDbRecord(); + + //if the show is repeating, set the start date to the next + //repeating instance in the future + if ($currentShowDay->isRepeating()) { + list($originalShowStartDateTime,) = $this->getNextFutureRepeatShowTime(); + } else { + $originalShowStartDateTime = $dt; + } + + return array($formData, $validateStartDate, $validateStartTime, $originalShowStartDateTime); + } + + /** + * + * Returns 2 DateTime objects, in the user's local time, + * of the next future repeat show instance start and end time + */ + public function getNextFutureRepeatShowTime() + { + $ccShowInstance = CcShowInstancesQuery::create() + ->filterByDbShowId($this->ccShow->getDbId()) + ->filterByDbModifiedInstance(false) + ->filterByDbEnds(gmdate("Y-m-d H:i:s"), Criteria::GREATER_THAN) + ->orderByDbStarts() + ->limit(1) + ->findOne(); + + $starts = new DateTime($ccShowInstance->getDbStarts(), new DateTimeZone("UTC")); + $ends = new DateTime($ccShowInstance->getDbEnds(), new DateTimeZone("UTC")); + $userTimezone = Application_Model_Preference::GetTimezone(); + + $starts->setTimezone(new DateTimeZone($userTimezone)); + $ends->setTimezone(new DateTimeZone($userTimezone)); + + return array($starts, $ends); + } + + /** + * + * Validates show forms + * + * @return boolean + */ + public function validateShowForms($forms, $formData, $validateStartDate = true, + $originalStartDate=null, $editShow=false, $instanceId=null) + { + $what = $forms["what"]->isValid($formData); + $live = $forms["live"]->isValid($formData); + $record = $forms["record"]->isValid($formData); + $who = $forms["who"]->isValid($formData); + $style = $forms["style"]->isValid($formData); + $when = $forms["when"]->isWhenFormValid($formData, $validateStartDate, + $originalStartDate, $editShow, $instanceId); + + $repeats = true; + if ($formData["add_show_repeats"]) { + $repeats = $forms["repeats"]->isValid($formData); + + /* + * Make the absolute rebroadcast form valid since + * it does not get used if the show is repeating + */ + $forms["abs_rebroadcast"]->reset(); + $absRebroadcast = true; + + $rebroadcast = true; + if ($formData["add_show_rebroadcast"]) { + $formData["add_show_duration"] = Application_Service_ShowService::formatShowDuration( + $formData["add_show_duration"]); + $rebroadcast = $forms["rebroadcast"]->isValid($formData); + } + } else { + /* + * Make the rebroadcast form valid since it does + * not get used if the show is not repeating. + * Instead, we use the absolute rebroadcast form + */ + $forms["rebroadcast"]->reset(); + $rebroadcast = true; + + $absRebroadcast = true; + if ($formData["add_show_rebroadcast"]) { + $formData["add_show_duration"] = Application_Service_ShowService::formatShowDuration( + $formData["add_show_duration"]); + $absRebroadcast = $forms["abs_rebroadcast"]->isValid($formData); + } + } + + if ($what && $live && $record && $who && $style && $when && + $repeats && $absRebroadcast && $rebroadcast) { + return true; + } else { + return false; + } + } + + public function calculateDuration($start, $end) + { + try { + $startDateTime = new DateTime($start); + $endDateTime = new DateTime($end); + + $UTCStartDateTime = $startDateTime->setTimezone(new DateTimeZone('UTC')); + $UTCEndDateTime = $endDateTime->setTimezone(new DateTimeZone('UTC')); + + $duration = $UTCEndDateTime->diff($UTCStartDateTime); + + $day = intval($duration->format('%d')); + if ($day > 0) { + $hour = intval($duration->format('%h')); + $min = intval($duration->format('%i')); + $hour += $day * 24; + $hour = min($hour, 99); + $sign = $duration->format('%r'); + return sprintf('%s%02dh %02dm', $sign, $hour, $min); + } else { + return $duration->format('%Hh %Im'); + } + } catch (Exception $e) { + return "Invalid Date"; + } + } +} \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php new file mode 100644 index 000000000..b5806a638 --- /dev/null +++ b/airtime_mvc/application/services/ShowService.php @@ -0,0 +1,1393 @@ +ccShow = CcShowQuery::create()->findPk($showId); + } + + if (isset($showData["add_show_repeats"]) && $showData["add_show_repeats"]) { + $this->repeatType = $showData["add_show_repeat_type"]; + if ($showData["add_show_repeat_type"] == 2) { + $this->repeatType = $showData["add_show_monthly_repeat_type"]; + } + } else { + $this->repeatType = -1; + } + $this->isRecorded = (isset($showData['add_show_record']) && $showData['add_show_record']) ? 1 : 0; + $this->isRebroadcast = (isset($showData['add_show_rebroadcast']) && $showData['add_show_rebroadcast']) ? 1 : 0; + $this->isUpdate = $isUpdate; + } + + public function createShowFromRepeatingInstance($showData) { + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); + + $showData["add_show_duration"] = $this->formatShowDuration( + $showData["add_show_duration"]); + + $con = Propel::getConnection(); + $con->beginTransaction(); + try { + if (!$currentUser->isAdminOrPM()) { + throw new Exception("Permission denied"); + } + + /****** UPDATE SCHEDULE START TIME ******/ + //get the ccShow object to which this instance belongs + //so we can get the original start date and time + $oldCcShow = CcShowQuery::create() + ->findPk($showData["add_show_id"]); + + //DateTime in user's local time + $newStartDateTime = new DateTime($showData["add_show_start_date"]." ". + $showData["add_show_start_time"], + new DateTimeZone(Application_Model_Preference::GetTimezone())); + + $ccShowInstanceOrig = CcShowInstancesQuery::create() + ->findPk($showData["add_show_instance_id"]); + $diff = $this->calculateShowStartDiff($newStartDateTime, + $ccShowInstanceOrig->getLocalStartDateTime()); + + if ($diff > 0) { + Application_Service_SchedulerService::updateScheduleStartTime( + array($showData["add_show_instance_id"]), $diff); + } + /****** UPDATE SCHEDULE START TIME ENDS******/ + + $this->setCcShow($showData); + $this->setCcShowDays($showData); + $this->setCcShowHosts($showData); + $this->delegateInstanceCreation(); + + //get the new instance id + $ccShowInstance = CcShowInstancesQuery::create() + ->filterByDbShowId($this->ccShow->getDbId()) + ->findOne(); + + $newInstanceId = $ccShowInstance->getDbId(); + + //update cc_schedule with the new instance id + $ccSchedules = CcScheduleQuery::create() + ->filterByDbInstanceId($showData["add_show_instance_id"]) + ->find(); + + foreach ($ccSchedules as $ccSchedule) { + $ccSchedule->setDbInstanceId($newInstanceId); + $ccSchedule->save(); + } + + $con = Propel::getConnection(CcShowInstancesPeer::DATABASE_NAME); + $ccShowInstance->updateDbTimeFilled($con); + + //delete the edited instance from the repeating sequence + $ccShowInstanceOrig->setDbModifiedInstance(true)->save(); + + $service_showForm = new Application_Service_ShowFormService($showData["add_show_id"]); + list($start, $end) = $service_showForm->getNextFutureRepeatShowTime(); + $oldCcShowDay = $oldCcShow->getFirstCcShowDay(); + $oldCcShowDay + ->setDbFirstShow($start->setTimezone(new DateTimeZone("UTC"))->format("Y-m-d")) + ->save(); + + $con->commit(); + Application_Model_RabbitMq::PushSchedule(); + } catch (Exception $e) { + $con->rollback(); + Logging::info("EXCEPTION: Show update failed."); + Logging::info($e->getMessage()); + } + } + + public function addUpdateShow($showData) + { + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); + + $showData["add_show_duration"] = $this->formatShowDuration( + $showData["add_show_duration"]); + + $con = Propel::getConnection(); + $con->beginTransaction(); + try { + if (!$currentUser->isAdminOrPM()) { + throw new Exception("Permission denied"); + } + //update ccShow + $this->setCcShow($showData); + + $daysAdded = array(); + if ($this->isUpdate) { + $daysAdded = $this->delegateInstanceCleanup($showData); + // updates cc_show_instances start/end times, and updates + // schedule start/end times + $this->applyShowStartEndDifference($showData); + $this->deleteRebroadcastInstances(); + $this->deleteCcShowDays(); + $this->deleteCcShowHosts(); + if ($this->isRebroadcast) { + //delete entry in cc_show_rebroadcast + $this->deleteCcShowRebroadcasts(); + } + } + + //update ccShowDays + $this->setCcShowDays($showData); + + //update ccShowRebroadcasts + $this->setCcShowRebroadcasts($showData); + + //update ccShowHosts + $this->setCcShowHosts($showData); + + //create new ccShowInstances + $this->delegateInstanceCreation($daysAdded); + + if ($this->isUpdate) { + $service_scheduler = new Application_Service_SchedulerService(); + $service_scheduler->removeGaps($this->ccShow->getDbId()); + } + + $con->commit(); + Application_Model_RabbitMq::PushSchedule(); + } catch (Exception $e) { + $con->rollback(); + $this->isUpdate ? $action = "update" : $action = "creation"; + Logging::info("EXCEPTION: Show ".$action." failed."); + Logging::info($e->getMessage()); + } + } + + /** + * + * Receives a cc_show id and determines whether to create a + * single show instance or repeating show instances + */ + public function delegateInstanceCreation($daysAdded=null, $end=null, $fillInstances=false) + { + $populateUntil = $this->getPopulateShowUntilDateTIme(); + + if (is_null($this->ccShow)) { + $ccShowDays = $this->getShowDaysInRange($populateUntil, $end); + } else { + $ccShowDays = $this->ccShow->getCcShowDays(); + } + + if (!is_null($end)) { + $populateUntil = $end; + } + + foreach ($ccShowDays as $day) { + switch ($day->getDbRepeatType()) { + case NO_REPEAT: + $this->createNonRepeatingInstance($day, $populateUntil); + break; + case REPEAT_WEEKLY: + $this->createRepeatingInstances($day, $populateUntil, REPEAT_WEEKLY, + new DateInterval("P7D"), $daysAdded, $fillInstances); + break; + case REPEAT_BI_WEEKLY: + $this->createRepeatingInstances($day, $populateUntil, REPEAT_BI_WEEKLY, + new DateInterval("P14D"), $daysAdded, $fillInstances); + break; + case REPEAT_MONTHLY_MONTHLY: + $this->createMonthlyMonthlyRepeatInstances($day, $populateUntil, $fillInstances); + break; + case REPEAT_MONTHLY_WEEKLY: + $this->createRepeatingInstances($day, $populateUntil, REPEAT_MONTHLY_WEEKLY, + null, $daysAdded, $fillInstances); + break; + } + } + + return $this->ccShow; + } + + private function getShowDaysInRange($start, $end) + { + $endTimeString = $end->format("Y-m-d H:i:s"); + if (!is_null($start)) { + $startTimeString = $start->format("Y-m-d H:i:s"); + } else { + $today_timestamp = new DateTime("now", new DateTimeZone("UTC")); + $startTimeString = $today_timestamp->format("Y-m-d H:i:s"); + } + + $c = new Criteria(); + $c->add(CcShowDaysPeer::FIRST_SHOW, $endTimeString, Criteria::LESS_THAN); + $c->addAnd(CcShowDaysPeer::LAST_SHOW, $startTimeString, Criteria::GREATER_THAN); + $c->addOr(CcShowDaysPeer::LAST_SHOW, null, Criteria::ISNULL); + + return CcShowDaysPeer::doSelect($c); + } + + public static function formatShowDuration($duration) + { + $hPos = strpos($duration, 'h'); + $mPos = strpos($duration, 'm'); + + $hValue = 0; + $mValue = 0; + + if ($hPos !== false) { + $hValue = trim(substr($duration, 0, $hPos)); + } + if ($mPos !== false) { + $hPos = $hPos === false ? 0 : $hPos+1; + $mValue = trim(substr($duration, $hPos, -1 )); + } + + return $hValue.":".$mValue; + } + + /** + * + * Deletes all the cc_show_days entries for a specific show + * that is currently being edited. They will get recreated with + * the new show day specs + */ + private function deleteCcShowDays() + { + CcShowDaysQuery::create()->filterByDbShowId($this->ccShow->getDbId())->delete(); + } + + private function deleteRebroadcastInstances() + { + $sql = << :timestamp::TIMESTAMP +AND show_id = :showId +AND rebroadcast = 1; +SQL; + Application_Common_Database::prepareAndExecute( $sql, array( + ':showId' => $this->ccShow->getDbId(), + ':timestamp' => gmdate("Y-m-d H:i:s")), 'execute'); + } + + /** + * TODO: This function is messy. Needs refactoring + * + * When editing a show we may need to perform some actions to reflect the new specs: + * - Delete some show instances + * - Update duration + * - Update start and end time + * + * @param $showData edit show form values in raw form + * @param $isRecorded value computed from the edit show form + * @param $repeatType value computed from the edit show form + */ + private function delegateInstanceCleanup($showData) + { + $showId = $this->ccShow->getDbId(); + + $daysAdded = array(); + + //CcShowDay object + $currentShowDay = $this->ccShow->getFirstCcShowDay(); + + //new end date in users' local time + $endDateTime = $this->calculateEndDate($showData); + if (!is_null($endDateTime)) { + $endDate = $endDateTime->format("Y-m-d"); + } else { + $endDate = $endDateTime; + } + + //repeat option was toggled + if ($showData['add_show_repeats'] != $currentShowDay->isRepeating()) { + $this->deleteAllRepeatInstances($currentShowDay, $showId); + //if repeat option was checked we need to treat the current show day + //as a new show day so the repeat instances get created properly + //in createRepeatingInstances() + if ($showData['add_show_repeats']) { + array_push($daysAdded, $currentShowDay->getDbDay()); + } + } + + if ($showData['add_show_repeats']) { + + $localShowStart = $currentShowDay->getLocalStartDateAndTime(); + + //if the start date changes, these are the repeat types + //that require show instance deletion + $deleteRepeatTypes = array(REPEAT_BI_WEEKLY, REPEAT_MONTHLY_MONTHLY, + REPEAT_MONTHLY_WEEKLY); + + if (in_array($this->repeatType, $deleteRepeatTypes) && + $showData["add_show_start_date"] != $localShowStart->format("Y-m-d")) { + + //Start date has changed when repeat type is bi-weekly or monthly. + //This screws up the repeating positions of show instances, so + //we need to delete them (CC-2351) + $this->deleteAllInstances($showId); + } + + $currentRepeatType = $currentShowDay->getDbRepeatType(); + //only delete instances if the show being edited was already repeating + //and the repeat type changed + if ($currentRepeatType != -1 && $this->repeatType != $currentRepeatType) { + $this->deleteAllInstances($showId); + } else { + //repeat type is the same, check if the days of the week are the same + $repeatingDaysChanged = false; + + $ccShowDays = $this->ccShow->getCcShowDays(); + $showDays = array(); + foreach ($ccShowDays as $day) { + $showDays[] = $day->getDbDay(); + } + + if (count($showData['add_show_day_check']) == count($showDays)) { + //same number of days checked, lets see if they are the same numbers + $intersect = array_intersect($showData['add_show_day_check'], $showDays); + if (count($intersect) != count($showData['add_show_day_check'])) { + $repeatingDaysChanged = true; + } + } else { + $repeatingDaysChanged = true; + } + + if ($repeatingDaysChanged) { + $daysRemoved = array_diff($showDays, $showData['add_show_day_check']); + $newDays = array_diff($showData["add_show_day_check"], $showDays); + foreach ($newDays as $newDay) { + array_push($daysAdded, $newDay); + } + + if (count($daysRemoved) > 0) { + //delete repeating show instances for the repeating + //days that were removed + $this->deleteRemovedShowDayInstances($daysRemoved, + $ccShowDays, $showId); + } + } + + if ($showData['add_show_start_date'] != $localShowStart->format("Y-m-d") + || $showData['add_show_start_time'] != $localShowStart->format("H:i")) { + + //start date has been pushed forward so we need to delete + //any instances of this show scheduled before the new start date + if ($showData['add_show_start_date'] > $localShowStart->format("Y-m-d")) { + $this->deleteInstancesBeforeDate($showData['add_show_start_date'], $showId); + } + + + } + } + + $currentShowEndDate = $this->getRepeatingEndDate(); + //check if "no end" option has changed + if ($currentShowEndDate != $showData['add_show_no_end']) { + //show "No End" option was toggled + if (!$showData['add_show_no_end']) { + //"No End" option was unchecked so we need to delete the + //repeat instances that are scheduled after the new end date + $this->deleteInstancesFromDate($endDate, $showId); + } + } + + if ($currentShowEndDate != $showData['add_show_end_date']) { + //end date was changed + $newEndDate = strtotime($showData['add_show_end_date']); + $oldEndDate = strtotime($currentShowEndDate); + if ($newEndDate < $oldEndDate) { + //end date was pushed back so we have to delete any + //instances of this show scheduled after the new end date + $this->deleteInstancesFromDate($endDate, $showId); + } + } + }//if repeats + + return $daysAdded; + } + + public function getRepeatingEndDate() + { + $sql = << $this->ccShow->getDbId() ), 'column' ); + + return ($query !== false) ? $query : false; + } + + private function deleteInstancesFromDate($endDate, $showId) + { + $sql = <<= :endDate::DATE + AND starts > :timestamp::TIMESTAMP + AND show_id = :showId +SQL; + Application_Common_Database::prepareAndExecute($sql, array( + ':endDate' => $endDate, ':timestamp' => gmdate("Y-m-d H:i:s"), + ':showId' => $showId), 'execute'); + } + + private function deleteInstancesBeforeDate($newStartDate, $showId) + { + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId +SQL; + + Application_Common_Database::prepareAndExecute($sql, array( + ":newStartDate" => $newStartDate, ":timestamp" => gmdate("Y-m-d H:i:s"), + ":showId" => $showId), "execute"); + } + + /** + * + * Enter description here ... + * @param $daysRemoved array of days (days of the week) removed + * (days of the week are represented numerically + * 0=>sunday, 1=>monday, 2=>tuesday, etc.) + * @param $showDays array of ccShowDays objects + * @param $showId + */ + private function deleteRemovedShowDayInstances($daysRemoved, $showDays, $showId) + { + $daysRemovedUTC = array(); + + //convert the start day of the week to UTC + foreach ($showDays as $showDay) { + if (in_array($showDay->getDbDay(), $daysRemoved)) { + $showDay->reload(); + $startDay = $showDay->getUTCStartDateAndTime(); + $daysRemovedUTC[] = $startDay->format('w'); + } + } + + foreach ($daysRemoved as $day) { + //delete the cc_show_day entries as well + CcShowDaysQuery::create() + ->filterByDbShowId($showId) + ->filterByDbDay($day) + ->delete(); + } + + $uncheckedDays = pg_escape_string(implode(",", $daysRemovedUTC)); + + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId +SQL; + + Application_Common_Database::prepareAndExecute( $sql, array( + ":timestamp" => gmdate("Y-m-d H:i:s"), ":showId" => $showId), + "execute"); + + } + + public function deleteShow($instanceId, $singleInstance=false) + { + $service_user = new Application_Service_UserService(); + $currentUser = $service_user->getCurrentUser(); + + $con = Propel::getConnection(); + $con->beginTransaction(); + try { + if (!$currentUser->isAdminOrPM()) { + throw new Exception("Permission denied"); + } + + $ccShowInstance = CcShowInstancesQuery::create() + ->findPk($instanceId); + if (!$ccShowInstance) { + throw new Exception("Could not find show instance"); + } + + $showId = $ccShowInstance->getDbShowId(); + if ($singleInstance) { + $ccShowInstances = CcShowInstancesQuery::create() + ->filterByDbShowId($showId) + ->filterByDbStarts($ccShowInstance->getDbStarts(), Criteria::GREATER_EQUAL) + ->filterByDbEnds($ccShowInstance->getDbEnds(), Criteria::LESS_EQUAL) + ->find(); + } else { + $ccShowInstances = CcShowInstancesQuery::create() + ->filterByDbShowId($showId) + ->filterByDbStarts($ccShowInstance->getDbStarts(), Criteria::GREATER_EQUAL) + ->find(); + } + + if (gmdate("Y-m-d H:i:s") <= $ccShowInstance->getDbEnds()) { + $this->deleteShowInstances($ccShowInstances, $ccShowInstance->getDbShowId()); + } + + Application_Model_RabbitMq::PushSchedule(); + + $con->commit(); + return $showId; + } catch (Exception $e) { + $con->rollback(); + Logging::info("Delete show instance failed"); + Logging::info($e->getMessage()); + return false; + } + } + + public function deleteShowInstances($ccShowInstances, $showId) + { + foreach ($ccShowInstances as $ccShowInstance) { + $instanceId = $ccShowInstance->getDbId(); + + $ccShowInstance + ->setDbModifiedInstance(true) + ->save(); + + //delete the rebroadcasts of the removed recorded show + if ($ccShowInstance->isRecorded()) { + CcShowInstancesQuery::create() + ->filterByDbOriginalShow($instanceId) + ->delete(); + } + + //delete all files scheduled in cc_schedules table + CcScheduleQuery::create() + ->filterByDbInstanceId($instanceId) + ->delete(); + } + + if ($this->checkToDeleteCcShow($showId)) { + CcShowQuery::create() + ->filterByDbId($showId) + ->delete(); + } + } + + private function checkToDeleteCcShow($showId) + { + // check if there are any non deleted show instances remaining. + $ccShowInstances = CcShowInstancesQuery::create() + ->filterByDbShowId($showId) + ->filterByDbModifiedInstance(false) + ->filterByDbRebroadcast(0) + ->find(); + + if ($ccShowInstances->isEmpty()) { + return true; + } + //only 1 show instance left of the show, make it non repeating. + else if (count($ccShowInstances) === 1) { + $ccShowInstance = $ccShowInstances[0]; + + $ccShowDay = CcShowDaysQuery::create() + ->filterByDbShowId($showId) + ->findOne(); + $tz = $ccShowDay->getDbTimezone(); + + $startDate = new DateTime($ccShowInstance->getDbStarts(), new DateTimeZone("UTC")); + $startDate->setTimeZone(new DateTimeZone($tz)); + $endDate = Application_Service_CalendarService::addDeltas($startDate, 1, 0); + + $ccShowDay->setDbFirstShow($startDate->format("Y-m-d")); + $ccShowDay->setDbLastShow($endDate->format("Y-m-d")); + $ccShowDay->setDbStartTime($startDate->format("H:i:s")); + $ccShowDay->setDbRepeatType(-1); + $ccShowDay->save(); + + //remove the old repeating deleted instances. + CcShowInstancesQuery::create() + ->filterByDbShowId($showId) + ->filterByDbModifiedInstance(true) + ->delete(); + } + + return false; + } + + private function deleteAllInstances($showId) + { + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId +SQL; + Application_Common_Database::prepareAndExecute( $sql, + array( ':timestamp' => gmdate("Y-m-d H:i:s"), + ':showId' => $showId), 'execute'); + } + + private function deleteAllRepeatInstances($currentShowDay, $showId) + { + $firstShow = $currentShowDay->getUTCStartDateAndTime(); + + $sql = << :timestamp::TIMESTAMP + AND show_id = :showId + AND starts != :firstShow +SQL; + Application_Common_Database::prepareAndExecute( $sql, + array( ':timestamp' => gmdate("Y-m-d H:i:s"), + ':showId' => $showId, + ':firstShow' => $firstShow->format("Y-m-d H:i:s")), 'execute'); + } + + /** + * + * Determines what the show end date should be based on + * the form data + * + * @param $showData add/edit show form data + * @return DateTime object in user's local timezone + */ + private function calculateEndDate($showData) + { + if ($showData['add_show_no_end']) { + $endDate = NULL; + } elseif ($showData['add_show_repeats']) { + $endDate = new DateTime($showData['add_show_end_date']); + $endDate->add(new DateInterval("P1D")); + } else { + $endDate = new DateTime($showData['add_show_start_date']); + $endDate->add(new DateInterval("P1D")); + } + + return $endDate; + } + + private function applyShowStartEndDifference($showData) + { + $showId = $this->ccShow->getDbId(); + //CcShowDay object + $currentShowDay = $this->ccShow->getFirstCcShowDay(); + + //DateTime in user's local time + $newStartDateTime = new DateTime($showData["add_show_start_date"]." ". + $showData["add_show_start_time"], + new DateTimeZone(Application_Model_Preference::GetTimezone())); + + $diff = $this->calculateShowStartDiff($newStartDateTime, + $currentShowDay->getLocalStartDateAndTime()); + + $this->updateInstanceStartEndTime($diff); + $ccShowInstances = $this->ccShow->getFutureCcShowInstancess(); + $instanceIds = array(); + foreach ($ccShowInstances as $ccShowInstance) { + array_push($instanceIds, $ccShowInstance->getDbId()); + } + Application_Service_SchedulerService::updateScheduleStartTime($instanceIds, $diff); + } + + /** + * + * Returns the difference in seconds between a show's new and + * old start time + * + * @param $newStartDateTime DateTime object + * @param $oldStartDateTime DateTime object + */ + private function calculateShowStartDiff($newStartDateTime, $oldStartDateTime) + { + return $newStartDateTime->getTimestamp() - $oldStartDateTime->getTimestamp(); + } + + /** + * + * Updates the start and end time for cc_show_instances + * + * @param $showData edit show form data + */ + private function updateInstanceStartEndTime($diff) + { + $sql = << :timestamp::TIMESTAMP +SQL; + + Application_Common_Database::prepareAndExecute($sql, + array(':diff1' => $diff, ':diff2' => $diff, + ':showId' => $this->ccShow->getDbId(), ':timestamp' => gmdate("Y-m-d H:i:s")), + 'execute'); + } + + /** + * + * Enter description here ... + * @param ccShowDays $showDay + * @param DateTime $showStartDate user's local time + * @param $instanceId + */ + private function createRebroadcastInstances($showDay, $showStartDate, $instanceId) + { + $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); + $showId = $this->ccShow->getDbId(); + + $sql = "SELECT * FROM cc_show_rebroadcast WHERE show_id=:show_id"; + $rebroadcasts = Application_Common_Database::prepareAndExecute($sql, + array( ':show_id' => $showId ), 'all'); + + foreach ($rebroadcasts as $rebroadcast) { + $days = explode(" ", $rebroadcast["day_offset"]); + $time = explode(":", $rebroadcast["start_time"]); + $offset = array("days"=>$days[0], "hours"=>$time[0], "mins"=>$time[1]); + + list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime( + $showStartDate, $showDay->getDbDuration(), $offset); + + if ($utcStartDateTime->format("Y-m-d H:i:s") > $currentUtcTimestamp) { + $ccShowInstance = new CcShowInstances(); + $ccShowInstance->setDbShowId($showId); + $ccShowInstance->setDbStarts($utcStartDateTime); + $ccShowInstance->setDbEnds($utcEndDateTime); + $ccShowInstance->setDbRecord(0); + $ccShowInstance->setDbRebroadcast(1); + $ccShowInstance->setDbOriginalShow($instanceId); + $ccShowInstance->save(); + } + } + } + + /** + * + * Sets a single cc_show_instance table row + * @param $showDay + * @param $populateUntil + */ + private function createNonRepeatingInstance($showDay, $populateUntil) + { + //DateTime object + $start = $showDay->getLocalStartDateAndTime(); + + list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime( + $start, $showDay->getDbDuration()); + + if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { + $ccShowInstance = new CcShowInstances(); + if ($this->isUpdate) { + $ccShowInstance = $this->getInstance($utcStartDateTime); + } + $ccShowInstance->setDbShowId($this->ccShow->getDbId()); + $ccShowInstance->setDbStarts($utcStartDateTime); + $ccShowInstance->setDbEnds($utcEndDateTime); + $ccShowInstance->setDbRecord($showDay->getDbRecord()); + $ccShowInstance->save(); + + if ($this->isUpdate) { + $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $ccShowInstance->updateScheduleStatus($con); + } + + if ($this->isRebroadcast) { + $this->createRebroadcastInstances($showDay, $start, $ccShowInstance->getDbId()); + } + } + } + + /** + * + * Sets multiple cc_show_instances table rows + * @param unknown_type $showDay + * @param unknown_type $populateUntil + * @param unknown_type $repeatInterval + * @param unknown_type $isRebroadcast + */ + private function createRepeatingInstances($showDay, $populateUntil, + $repeatType, $repeatInterval, $daysAdded=null, $fillInstances) + { + $show_id = $showDay->getDbShowId(); + $first_show = $showDay->getDbFirstShow(); //non-UTC + $last_show = $showDay->getDbLastShow(); //non-UTC + $duration = $showDay->getDbDuration(); + $day = $showDay->getDbDay(); + $record = $showDay->getDbRecord(); + $timezone = $showDay->getDbTimezone(); + + //DateTime local + $start = $this->getNextRepeatingPopulateStartDateTime($showDay); + + if (is_null($repeatInterval)&& $repeatType == REPEAT_MONTHLY_WEEKLY) { + $repeatInterval = $this->getMonthlyWeeklyRepeatInterval($start, $timezone); + } + + //DatePeriod in user's local time + $datePeriod = $this->getDatePeriod($start, $timezone, $last_show, + $repeatInterval, $populateUntil); + + $utcLastShowDateTime = $last_show ? + Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; + + $utcStartDateTime = new DateTime("now"); + foreach ($datePeriod as $date) { + list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime( + $date, $duration); + /* + * Make sure start date is less than populate until date AND + * last show date is null OR start date is less than last show date + */ + if ($utcStartDateTime->getTimestamp() <= $populateUntil->getTimestamp() && + ( is_null($utcLastShowDateTime) || + $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp()) ) { + + /* There may not always be an instance when editing a show + * This will be the case when we are adding a new show day to + * a repeating show + */ + if ($this->isUpdate) { + if ($this->hasInstance($utcStartDateTime)) { + $ccShowInstance = $this->getInstance($utcStartDateTime); + $newInstance = false; + $updateScheduleStatus = true; + } else { + $newInstance = true; + $ccShowInstance = new CcShowInstances(); + $updateScheduleStatus = false; + } + } else { + $newInstance = true; + $ccShowInstance = new CcShowInstances(); + $updateScheduleStatus = false; + } + + /* When editing the start/end time of a repeating show, we don't want to + * change shows that started in the past. So check the start time. + */ + if ($newInstance || $ccShowInstance->getDbStarts() > gmdate("Y-m-d H:i:s")) { + $ccShowInstance->setDbShowId($show_id); + $ccShowInstance->setDbStarts($utcStartDateTime); + $ccShowInstance->setDbEnds($utcEndDateTime); + $ccShowInstance->setDbRecord($record); + $ccShowInstance->save(); + + if ($updateScheduleStatus) { + $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $ccShowInstance->updateScheduleStatus($con); + } + } + + if ($this->isRebroadcast) { + $this->createRebroadcastInstances($showDay, $date, $ccShowInstance->getDbId()); + } + } + } + + /* Set UTC to local time before setting the next repeat date. If we don't + * the next repeat date might be scheduled for the following day + */ + $utcStartDateTime->setTimezone(new DateTimeZone(Application_Model_Preference::GetTimezone())); + $nextDate = $utcStartDateTime->add($repeatInterval); + $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day, $show_id); + + if ($fillInstances) { + Application_Service_SchedulerService::fillLinkedShows( + $showDay->getCcShow()); + } + } + + private function createMonthlyMonthlyRepeatInstances($showDay, $populateUntil) + { + $show_id = $showDay->getDbShowId(); + $first_show = $showDay->getDbFirstShow(); //non-UTC + $last_show = $showDay->getDbLastShow(); //non-UTC + $duration = $showDay->getDbDuration(); + $day = $showDay->getDbDay(); + $record = $showDay->getDbRecord(); + $timezone = $showDay->getDbTimezone(); + + //DateTime local + $start = $this->getNextRepeatingPopulateStartDateTime($showDay); + if (isset($last_show)) { + $end = new DateTime($last_show, new DateTimeZone($timezone)); + } else { + $end = $populateUntil; + } + + $utcLastShowDateTime = $last_show ? + Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; + + while ($start->getTimestamp() < $end->getTimestamp()) { + list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime( + $start, $duration); + /* + * Make sure start date is less than populate until date AND + * last show date is null OR start date is less than last show date + */ + if ($utcStartDateTime->getTimestamp() <= $populateUntil->getTimestamp() && + ( is_null($utcLastShowDateTime) || + $utcStartDateTime->getTimestamp() < $utcLastShowDateTime->getTimestamp()) ) { + + /* There may not always be an instance when editing a show + * This will be the case when we are adding a new show day to + * a repeating show + */ + if ($this->isUpdate && $this->hasInstance($utcStartDateTime)) { + $ccShowInstance = $this->getInstance($utcStartDateTime); + $newInstance = false; + $updateScheduleStatus = true; + } else { + $newInstance = true; + $ccShowInstance = new CcShowInstances(); + $updateScheduleStatus = false; + } + + /* When editing the start/end time of a repeating show, we don't want to + * change shows that started in the past. So check the start time. + */ + if ($newInstance || $ccShowInstance->getDbStarts() > gmdate("Y-m-d H:i:s")) { + $ccShowInstance->setDbShowId($show_id); + $ccShowInstance->setDbStarts($utcStartDateTime); + $ccShowInstance->setDbEnds($utcEndDateTime); + $ccShowInstance->setDbRecord($record); + $ccShowInstance->save(); + + if ($updateScheduleStatus) { + $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $ccShowInstance->updateScheduleStatus($con); + } + } + + if ($this->isRebroadcast) { + $this->createRebroadcastInstances($showDay, $date, $ccShowInstance->getDbId()); + } + } + $start = $this->getNextMonthlyMonthlyRepeatDate($start, $timezone); + } + $this->setNextRepeatingShowDate($start->format("Y-m-d"), $day, $show_id); + } + + /** + * + * i.e. last thursday of each month + * i.e. second monday of each month + * + * @param string $showStart + * @param string $timezone user's local timezone + */ + private function getMonthlyWeeklyRepeatInterval($showStart) + { + $start = clone $showStart; + + $dayOfMonth = $start->format("j"); + $dayOfWeek = $start->format("l"); + $yearAndMonth = $start->format("Y-m"); + $firstDayOfWeek = strtotime($dayOfWeek." ".$yearAndMonth); + // if $dayOfWeek is Friday, what number of the month does + // the first Friday fall on + $numberOfFirstDayOfWeek = date("j", $firstDayOfWeek); + + $weekCount = 0; + while ($dayOfMonth >= $numberOfFirstDayOfWeek) { + $weekCount++; + $dayOfMonth -= 7; + } + + switch ($weekCount) { + case 1: + $weekNumberOfMonth = "first"; + break; + case 2: + $weekNumberOfMonth = "second"; + break; + case 3: + $weekNumberOfMonth = "third"; + break; + case 4: + $weekNumberOfMonth = "fourth"; + break; + case 5: + $weekNumberOfMonth = "last"; + break; + } + + return DateInterval::createFromDateString( + $weekNumberOfMonth." ".$dayOfWeek." of next month"); + } + + /** + * + * Enter description here ... + * @param $start + */ + private function getNextMonthlyMonthlyRepeatDate($start, $timezone) + { + $dt = new DateTime($start->format("Y-m"), new DateTimeZone($timezone)); + do { + $dt->add(new DateInterval("P1M")); + } while (!checkdate($dt->format("m"), $start->format("d"), $dt->format("Y"))); + + $dt->setDate($dt->format("Y"), $dt->format("m"), $start->format("d")); + return $dt; + } + + private function getNextRepeatingPopulateStartDateTime($showDay) + { + $nextPopDate = $showDay->getDbNextPopDate(); + $startTime = $showDay->getDbStartTime(); + + if (isset($nextPopDate)) { + return new DateTime($nextPopDate." ".$startTime, new DateTimeZone($showDay->getDbTimezone())); + } else { + return new DateTime($showDay->getDbFirstShow()." ".$startTime, new DateTimeZone($showDay->getDbTimezone())); + } + } + + /** + * + * Create a DatePeriod object in the user's local time + * It will get converted to UTC before the show instance gets created + */ + private function getDatePeriod($start, $timezone, $lastShow, $repeatInterval, $populateUntil) + { + if (isset($lastShow)) { + $endDatePeriod = new DateTime($lastShow, new DateTimeZone($timezone)); + } else { + $endDatePeriod = $populateUntil; + } + + return new DatePeriod($start, $repeatInterval, $endDatePeriod); + } + + private function hasInstance($starts) + { + return $this->getInstance($starts) ? true : false; + } + + /** + * + * Attempts to retrieve the cc_show_instance belonging to a cc_show + * that starts at $starts. We have to pass in the start + * time in case the show is repeating + * + * Returns the instance if one was found (one that is not a recording + * and modified instance is false (has not been deleted)) + */ + private function getInstance($starts) + { + $ccShowInstance = CcShowInstancesQuery::create() + ->filterByDbStarts($starts->format("Y-m-d H:i:s"), Criteria::EQUAL) + ->filterByDbShowId($this->ccShow->getDbId(), Criteria::EQUAL) + ->filterByDbModifiedInstance(false, Criteria::EQUAL) + ->filterByDbRebroadcast(0, Criteria::EQUAL) + ->limit(1) + ->find(); + + if ($ccShowInstance->isEmpty()) { + return false; + } else { + return $ccShowInstance[0]; + } + } + + private function hasCcShowDay($repeatType, $day) + { + return $this->getCcShowDay($repeatType, $day) ? true : false; + } + + private function getCcShowDay($repeatType, $day) + { + $ccShowDay = CcShowDaysQuery::create() + ->filterByDbShowId($this->ccShow->getDbId()) + ->filterByDbDay($day) + ->filterByDbRepeatType($repeatType) + ->limit(1) + ->find(); + + if ($ccShowDay->isEmpty()) { + return false; + } else { + return $ccShowDay[0]; + } + } + + /** + * + * Sets the fields for a cc_show table row + * @param $ccShow + * @param $showData + */ + private function setCcShow($showData) + { + if (!$this->isUpdate) { + $ccShow = new CcShow(); + } else { + $ccShow = CcShowQuery::create()->findPk($showData["add_show_id"]); + } + + $ccShow->setDbName($showData['add_show_name']); + $ccShow->setDbDescription($showData['add_show_description']); + $ccShow->setDbUrl($showData['add_show_url']); + $ccShow->setDbGenre($showData['add_show_genre']); + $ccShow->setDbColor($showData['add_show_color']); + $ccShow->setDbBackgroundColor($showData['add_show_background_color']); + $ccShow->setDbLiveStreamUsingAirtimeAuth($showData['cb_airtime_auth'] == 1); + $ccShow->setDbLiveStreamUsingCustomAuth($showData['cb_custom_auth'] == 1); + $ccShow->setDbLiveStreamUser($showData['custom_username']); + $ccShow->setDbLiveStreamPass($showData['custom_password']); + + // Once a show is unlinked it cannot be linked again + if ($ccShow->getDbLinked() && !$showData["add_show_linked"]) { + $ccShow->setDbIsLinkable(false); + } + $ccShow->setDbLinked($showData["add_show_linked"]); + + $ccShow->save(); + $this->ccShow = $ccShow; + } + + /** + * + * Sets the fields for a cc_show_days table row + * @param $showData + * @param $showId + * @param $userId + * @param $repeatType + * @param $isRecorded + * @param $showDay ccShowDay object we are setting values on + */ + private function setCcShowDays($showData) + { + $showId = $this->ccShow->getDbId(); + + $startDateTime = new DateTime($showData['add_show_start_date']." ".$showData['add_show_start_time']); + + $endDateTime = $this->calculateEndDate($showData); + if (!is_null($endDateTime)) { + $endDate = $endDateTime->format("Y-m-d"); + } else { + $endDate = $endDateTime; + } + + /* What we are doing here is checking if the show repeats or if + * any repeating days have been checked. If not, then by default + * the "selected" DOW is the initial day. + * DOW in local time. + */ + $startDow = date("w", $startDateTime->getTimestamp()); + if (!$showData['add_show_repeats']) { + $showData['add_show_day_check'] = array($startDow); + } elseif ($showData['add_show_repeats'] && $showData['add_show_day_check'] == "") { + $showData['add_show_day_check'] = array($startDow); + } + + // Don't set day for monthly repeat type, it's invalid + if ($showData['add_show_repeats'] && $showData['add_show_repeat_type'] == 2) { + $showDay = new CcShowDays(); + $showDay->setDbFirstShow($startDateTime->format("Y-m-d")); + $showDay->setDbLastShow($endDate); + $showDay->setDbStartTime($startDateTime->format("H:i:s")); + $showDay->setDbTimezone(Application_Model_Preference::GetTimezone()); + $showDay->setDbDuration($showData['add_show_duration']); + $showDay->setDbRepeatType($this->repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($this->isRecorded); + //in case we are editing a show we need to set this to the first show + //so when editing, the date period iterator will start from the beginning + $showDay->setDbNextPopDate($startDateTime->format("Y-m-d")); + $showDay->save(); + } else { + foreach ($showData['add_show_day_check'] as $day) { + $daysAdd=0; + $startDateTimeClone = clone $startDateTime; + if ($startDow !== $day) { + if ($startDow > $day) + $daysAdd = 6 - $startDow + 1 + $day; + else + $daysAdd = $day - $startDow; + + $startDateTimeClone->add(new DateInterval("P".$daysAdd."D")); + } + if (is_null($endDate) || $startDateTimeClone->getTimestamp() <= $endDateTime->getTimestamp()) { + $showDay = new CcShowDays(); + $showDay->setDbFirstShow($startDateTimeClone->format("Y-m-d")); + $showDay->setDbLastShow($endDate); + $showDay->setDbStartTime($startDateTimeClone->format("H:i")); + $showDay->setDbTimezone(Application_Model_Preference::GetTimezone()); + $showDay->setDbDuration($showData['add_show_duration']); + $showDay->setDbDay($day); + $showDay->setDbRepeatType($this->repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($this->isRecorded); + //in case we are editing a show we need to set this to the first show + //so when editing, the date period iterator will start from the beginning + $showDay->setDbNextPopDate($startDateTimeClone->format("Y-m-d")); + $showDay->save(); + } + } + } + } + + /** + * + * Deletes all the cc_show_rebroadcast entries for a specific show + * that is currently being edited. They will get recreated with + * the new show specs + */ + private function deleteCcShowRebroadcasts() + { + CcShowRebroadcastQuery::create()->filterByDbShowId($this->ccShow->getDbId())->delete(); + } + + /** + * + * Sets the fields for a cc_show_rebroadcast table row + * @param $showData + * @param $showId + * @param $repeatType + * @param $isRecorded + */ + private function setCcShowRebroadcasts($showData) + { + $showId = $this->ccShow->getDbId(); + + if (($this->isRecorded && $showData['add_show_rebroadcast']) && ($this->repeatType != -1)) { + for ($i = 1; $i <= MAX_REBROADCAST_DATES; $i++) { + if ($showData['add_show_rebroadcast_date_'.$i]) { + $showRebroad = new CcShowRebroadcast(); + $showRebroad->setDbDayOffset($showData['add_show_rebroadcast_date_'.$i]); + $showRebroad->setDbStartTime($showData['add_show_rebroadcast_time_'.$i]); + $showRebroad->setDbShowId($showId); + $showRebroad->save(); + } + } + } elseif ($this->isRecorded && $showData['add_show_rebroadcast'] && ($this->repeatType == -1)) { + for ($i = 1; $i <= MAX_REBROADCAST_DATES; $i++) { + if ($showData['add_show_rebroadcast_date_absolute_'.$i]) { + $rebroadcastDate = new DateTime($showData["add_show_rebroadcast_date_absolute_$i"]); + $startDate = new DateTime($showData['add_show_start_date']); + $offsetDays = $startDate->diff($rebroadcastDate); + + $showRebroad = new CcShowRebroadcast(); + $showRebroad->setDbDayOffset($offsetDays->format("%a days")); + $showRebroad->setDbStartTime($showData['add_show_rebroadcast_time_absolute_'.$i]); + $showRebroad->setDbShowId($showId); + $showRebroad->save(); + } + } + } + } + + /** + * + * Deletes all the cc_show_hosts entries for a specific show + * that is currently being edited. They will get recreated with + * the new show specs + */ + private function deleteCcShowHosts() + { + CcShowHostsQuery::create()->filterByDbShow($this->ccShow->getDbId())->delete(); + } + + /** + * + * Sets the fields for a cc_show_hosts table row + * @param $showData + * @param $showId + */ + private function setCcShowHosts($showData) + { + if (is_array($showData['add_show_hosts'])) { + foreach ($showData['add_show_hosts'] as $host) { + $showHost = new CcShowHosts(); + $showHost->setDbShow($this->ccShow->getDbId()); + $showHost->setDbHost($host); + $showHost->save(); + } + } + } + + /** + * + * Gets the date and time shows (particularly repeating shows) + * can be populated until. + * + * @return DateTime object + */ + private static function getPopulateShowUntilDateTIme() + { + $populateUntil = Application_Model_Preference::GetShowsPopulatedUntil(); + + if (is_null($populateUntil)) { + $populateUntil = new DateTime("now", new DateTimeZone('UTC')); + Application_Model_Preference::SetShowsPopulatedUntil($populateUntil); + } + return $populateUntil; + } + + /** + * + * Enter description here ... + * @param DateTime $showStart user's local time + * @param string $duration time interval (h)h:(m)m(:ss) + * @param string $timezone "Europe/Prague" + * @param array $offset (days, hours, mins) used for rebroadcast shows + * + * @return array of 2 DateTime objects, start/end time of the show in UTC + */ + private function createUTCStartEndDateTime($showStart, $duration, $offset=null) + { + $startDateTime = clone $showStart; + + if (isset($offset)) { + //$offset["hours"] and $offset["mins"] represents the start time + //of a rebroadcast show + $startDateTime = new DateTime($startDateTime->format("Y-m-d")." ". + $offset["hours"].":".$offset["mins"]); + $startDateTime->add(new DateInterval("P{$offset["days"]}D")); + } + //convert time to UTC + $startDateTime->setTimezone(new DateTimeZone('UTC')); + + $endDateTime = clone $startDateTime; + $duration = explode(":", $duration); + list($hours, $mins) = array_slice($duration, 0, 2); + $endDateTime->add(new DateInterval("PT{$hours}H{$mins}M")); + + return array($startDateTime, $endDateTime); + } + + /** + * + * Show instances for repeating shows only get created up + * until what is visible on the calendar. We need to set the + * date for when the next repeating show instance should be created + * as the user browses the calendar further. + * + * @param $nextDate + * @param $showId + * @param $day + */ + private function setNextRepeatingShowDate($nextDate, $day, $showId) + { + $nextInfo = explode(" ", $nextDate); + + $repeatInfo = CcShowDaysQuery::create() + ->filterByDbShowId($showId) + ->filterByDbDay($day) + ->findOne(); + + $repeatInfo->setDbNextPopDate($nextInfo[0]) + ->save(); + } +} \ No newline at end of file diff --git a/airtime_mvc/application/services/UserService.php b/airtime_mvc/application/services/UserService.php new file mode 100644 index 000000000..879ba4d48 --- /dev/null +++ b/airtime_mvc/application/services/UserService.php @@ -0,0 +1,33 @@ +getStorage()->read(); + if (!is_null($userInfo->id)) { + $this->currentUser = CcSubjsQuery::create()->findPK($userInfo->id); + } + } + + /** + * + * Returns a CcSubjs object + */ + public function getCurrentUser() + { + if (is_null($this->currentUser)) { + throw new Exception(); + } + + return $this->currentUser; + } + +} \ No newline at end of file diff --git a/airtime_mvc/build/schema.xml b/airtime_mvc/build/schema.xml index b9a8a6951..c0ec104dd 100644 --- a/airtime_mvc/build/schema.xml +++ b/airtime_mvc/build/schema.xml @@ -132,6 +132,10 @@ + + + @@ -322,6 +326,11 @@ + +