From a7601d290ff07ea344b9c15bf47bab910017968b Mon Sep 17 00:00:00 2001 From: denise Date: Thu, 21 Mar 2013 10:05:11 -0400 Subject: [PATCH] CC-4961: Show linking Refactored services Removed ShowDaysService and ShowInstanceService Combined all show actions into one ShowService --- .../controllers/ScheduleController.php | 174 ++-- .../application/models/airtime/CcShow.php | 104 +++ .../application/models/airtime/CcShowDays.php | 24 + .../application/models/airtime/CcSubjs.php | 8 + .../application/services/CalendarService.php | 271 +----- .../application/services/ShowDaysService.php | 181 ---- .../application/services/ShowFormService.php | 334 ++++++++ .../services/ShowInstanceService.php | 614 -------------- .../application/services/ShowService.php | 800 +++++++++++++++++- .../public/js/airtime/schedule/schedule.js | 4 +- 10 files changed, 1308 insertions(+), 1206 deletions(-) delete mode 100644 airtime_mvc/application/services/ShowDaysService.php create mode 100644 airtime_mvc/application/services/ShowFormService.php delete mode 100644 airtime_mvc/application/services/ShowInstanceService.php diff --git a/airtime_mvc/application/controllers/ScheduleController.php b/airtime_mvc/application/controllers/ScheduleController.php index 87e3c4c4e..7f53fe798 100644 --- a/airtime_mvc/application/controllers/ScheduleController.php +++ b/airtime_mvc/application/controllers/ScheduleController.php @@ -5,7 +5,6 @@ class ScheduleController extends Zend_Controller_Action protected $sched_sess = null; - private $service_calendar; private $currentUser; public function init() @@ -42,8 +41,6 @@ class ScheduleController extends Zend_Controller_Action $this->sched_sess = new Zend_Session_Namespace("schedule"); - $this->service_calendar = new Application_Service_CalendarService(); - $service_user = new Application_Service_UserService(); $this->currentUser = $service_user->getCurrentUser(); } @@ -534,65 +531,35 @@ class ScheduleController extends Zend_Controller_Action public function populateShowFormAction() { - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - - $showInstanceId = $this->_getParam('id'); + $showId = $this->_getParam('showId'); + $instanceId = $this->_getParam('instanceId'); + $service_showForm = new Application_Service_ShowFormService($showId, $instanceId); $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; - } + $isAdminOrPM = $this->currentUser->isAdminOrPM(); + $isHostOfShow = $this->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'); + $service_showForm->delegateFormPopulation($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; - - $show = new Application_Model_Show($showInstance->getShowId()); + /*$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())); + 'add_show_description' => $show->getDescription()));*/ - $startsDateTime = new DateTime($show->getStartDate()." ".$show->getStartTime(), new DateTimeZone("UTC")); + /*$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())); @@ -617,10 +584,10 @@ class ScheduleController extends Zend_Controller_Action $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(); + /*$days = array(); $showDays = CcShowDaysQuery::create()->filterByDbShowId($showInstance->getShowId())->find(); foreach ($showDays as $showDay) { $showStartDay = new DateTime($showDay->getDbFirstShow(), new DateTimeZone($showDay->getDbTimezone())); @@ -635,70 +602,53 @@ class ScheduleController extends Zend_Controller_Action $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() == ''))); + 'add_show_no_end' => ($show->getRepeatingEndDate() == '')));*/ - $hosts = array(); + /*$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(), + $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->populate(array('add_show_record' => $show->isRecorded(), + 'add_show_rebroadcast' => $show->isRebroadcast())); - $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)); + $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(); - } + /*$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) { - $formWhat->disable(); - $formWho->disable(); - $formWhen->disable(); - $formRepeats->disable(); - $formStyle->disable(); - } + foreach ($forms as $form) { + $form->disable(); + } + }*/ $this->view->newForm = $this->view->render('schedule/add-show-form.phtml'); $this->view->entries = 5; @@ -761,6 +711,10 @@ class ScheduleController extends Zend_Controller_Action $data[$j["name"]] = $j["value"]; } + $service_showForm = new Application_Service_ShowFormService( + $data["add_show_id"]); + $service_show = new Application_Service_ShowService(); + //TODO: move this to js $data['add_show_hosts'] = $this->_getParam('hosts'); $data['add_show_day_check'] = $this->_getParam('days'); @@ -772,13 +726,13 @@ class ScheduleController extends Zend_Controller_Action $forms = $this->createShowFormAction(); list($data, $validateStartDate, $validateStartTime, $originalShowStartDateTime) = - $this->service_calendar->preEditShowValidationCheck($data); + $service_showForm->preEditShowValidationCheck($data); - if ($this->service_calendar->validateShowForms($forms, $data, $validateStartDate, + if ($service_showForm->validateShowForms($forms, $data, $validateStartDate, $originalShowStartDateTime, true, $data["add_show_instance_id"])) { //pass in true to indicate we are updating a show - $this->service_calendar->addUpdateShow($data, true); + $service_show->addUpdateShow($data, true); $scheduler = new Application_Model_Scheduler(); $showInstances = CcShowInstancesQuery::create()->filterByDbShowId($data['add_show_id'])->find(); @@ -803,6 +757,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(); @@ -823,8 +780,8 @@ class ScheduleController extends Zend_Controller_Action $this->view->addNewShow = true; - if ($this->service_calendar->validateShowForms($forms, $data)) { - $this->service_calendar->addUpdateShow($data); + 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 @@ -837,13 +794,16 @@ class ScheduleController extends Zend_Controller_Action } } - public function createShowFormAction($populate=false) + public function createShowFormAction($populateDefaults=false) { - $forms = $this->service_calendar->createShowForms(); + $service_showForm = new Application_Service_ShowFormService(); + + $forms = $service_showForm->createShowForms(); // populate forms with default values - if ($populate) { - $this->populateNewShowFormsAction($forms); + if ($populateDefaults) { + $service_showForm->populateNewShowForms( + $forms["what"], $forms["when"], $forms["repeats"]); } $this->view->what = $forms["what"]; @@ -859,12 +819,6 @@ class ScheduleController extends Zend_Controller_Action return $forms; } - public function populateNewShowFormsAction($forms) - { - $this->service_calendar->populateNewShowForms( - $forms["what"], $forms["when"], $forms["repeats"]); - } - public function cancelShowAction() { $user = Application_Model_User::getCurrentUser(); diff --git a/airtime_mvc/application/models/airtime/CcShow.php b/airtime_mvc/application/models/airtime/CcShow.php index ae37d289e..8100f455c 100644 --- a/airtime_mvc/application/models/airtime/CcShow.php +++ b/airtime_mvc/application/models/airtime/CcShow.php @@ -15,4 +15,108 @@ */ 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(); + } } // CcShow diff --git a/airtime_mvc/application/models/airtime/CcShowDays.php b/airtime_mvc/application/models/airtime/CcShowDays.php index 7dc9d98bd..4ed9bd6bc 100644 --- a/airtime_mvc/application/models/airtime/CcShowDays.php +++ b/airtime_mvc/application/models/airtime/CcShowDays.php @@ -40,4 +40,28 @@ class CcShowDays extends BaseCcShowDays { return $dt; } + + /** + * + * Enter description here ... + * @param DateTime $startDateTime first show in user's local time + */ + public function getLocalEndDateAndTime($startDateTime) + { + $duration = explode(":", $this->getDbDuration()); + + return $startDateTime->add(new DateInterval('PT'.$duration[0].'H'.$duration[1].'M')); + } + + public function isShowStartInPast() + { + return $this->getUTCStartDateAndTime() > 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/CcSubjs.php b/airtime_mvc/application/models/airtime/CcSubjs.php index c274e35c4..908adf554 100644 --- a/airtime_mvc/application/models/airtime/CcSubjs.php +++ b/airtime_mvc/application/models/airtime/CcSubjs.php @@ -19,4 +19,12 @@ class CcSubjs extends BaseCcSubjs { { 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/services/CalendarService.php b/airtime_mvc/application/services/CalendarService.php index 9988c149b..0541ed57b 100644 --- a/airtime_mvc/application/services/CalendarService.php +++ b/airtime_mvc/application/services/CalendarService.php @@ -2,278 +2,9 @@ class Application_Service_CalendarService { - private $service_show; - private $service_showDays; - private $service_showInstances; - private $service_user; - public function __construct() { - $this->service_show = new Application_Service_ShowService(); - $this->service_showInstances = new Application_Service_ShowInstanceService(); - $this->service_user = new Application_Service_UserService(); - } -/* - * Form stuff begins here - * Typically I would keep form creation and validation - * in the controller but since shows require 9 forms, - * the controller will become too fat. - * Maybe we should create a special form show service? - */ - /** - * - * @return array of schedule 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 populateForm($form, $values) - { - $form->populate($values); - } - - /** - * - * 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"] = $this->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"] = $this->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; - } - } -/* - * Form stuff ends - */ - - public 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; - } - - public function addUpdateShow($showData, $isUpdate=false) - { - //CcSubj object - $currentUser = $this->service_user->getCurrentUser(); - - $repeatType = ($showData['add_show_repeats']) ? $showData['add_show_repeat_type'] : -1; - $isRecorded = (isset($showData['add_show_record']) && $showData['add_show_record']) ? 1 : 0; - $isRebroadcast = (isset($showData['add_show_rebroadcast']) && $showData['add_show_rebroadcast']) ? 1 : 0; - - $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 - $ccShow = $this->service_show->setShow($showData, $isUpdate); - $showId = $ccShow->getDbId(); - - if ($isUpdate) { - $this->service_showInstances->deleteInvalidInstances($showData, $isRecorded, $repeatType); - // updates cc_show_instances start/end times, and updates - // schedule start/end times - $this->service_showInstances->applyShowStartEndDifference($showData, $showId); - $this->service_showInstances->deleteRebroadcastInstances($showId); - $this->service_showDays->deleteShowDays(); - $this->service_show->deleteShowHosts($showId); - if ($isRebroadcast) { - //delete entry in cc_show_rebroadcast - $this->service_show->deleteShowRebroadcasts($showId); - } - } - - //update ccShowDays - $this->service_showDays = new Application_Service_ShowDaysService($showId); - $this->service_showDays->setShowDays($showData, $repeatType, $isRecorded); - - //update ccShowRebroadcasts - $this->service_show->setShowRebroadcasts($showData, $showId, $repeatType, $isRecorded); - - //update ccShowHosts - $this->service_show->setShowHosts($showData, $showId); - - //create new ccShowInstances - $this->service_showInstances->delegateShowInstanceCreation($showId, $isRebroadcast, $isUpdate); - - //after all instances have been deleted/updated, we need to update - //the schedule playout status - if ($isUpdate) { - $this->service_showInstances->updateScheduleStatus($showId); - } - - $con->commit(); - Application_Model_RabbitMq::PushSchedule(); - } catch (Exception $e) { - $con->rollback(); - $isUpdate ? $action = "update" : $action = "creation"; - Logging::info("EXCEPTION: Show ".$action." failed."); - Logging::info($e->getMessage()); - } - } - - /** - * - * 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; - $this->service_showDays = new Application_Service_ShowDaysService( - $formData["add_show_id"]); - - //CcShowDays object of the show currently being edited - $currentShowDay = $this->service_showDays->getCurrentShowDay(); - - 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. - //The start date will be returned in UTC time, so lets convert it to local time. - $dt = Application_Common_DateHelper::ConvertToLocalDateTime( - $this->service_showDays->getStartDateAndTime()); - $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()) { - $nextFutureRepeatShow = $this->service_showInstances - ->getNextFutureRepeatShowTime($formData["add_show_id"]); - $originalShowStartDateTime = $nextFutureRepeatShow["starts"]; - } else { - $originalShowStartDateTime = Application_Common_DateHelper::ConvertToLocalDateTime( - $this->service_showDays->getStartDateAndTime()); - } - - return array($formData, $validateStartDate, $validateStartTime, $originalShowStartDateTime); + } } \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowDaysService.php b/airtime_mvc/application/services/ShowDaysService.php deleted file mode 100644 index 07616b552..000000000 --- a/airtime_mvc/application/services/ShowDaysService.php +++ /dev/null @@ -1,181 +0,0 @@ -showId = $id; - } - - /** - * - * 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 - */ - public function deleteShowDays() - { - CcShowDaysQuery::create()->filterByDbShowId($this->showId)->delete(); - } - - /** - * - * 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 - */ - public 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; - } - - /** - * - * 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 - */ - public function setShowDays($showData, $repeatType, $isRecorded) - { - $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($repeatType); - $showDay->setDbShowId($this->showId); - $showDay->setDbRecord($isRecorded); - $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($repeatType); - $showDay->setDbShowId($this->showId); - $showDay->setDbRecord($isRecorded); - $showDay->save(); - } - } - } - } - - /** - * - * Gets the cc_show_days entries for a specific show - * - * @return array of ccShowDays objects - */ - public function getShowDays() - { - return CcShowDaysQuery::create()->filterByDbShowId( - $this->showId)->find(); - } - - public function getStartDateAndTime() - { - //CcShowDays object - $showDay = $this->getCurrentShowDay(); - - $dt = new DateTime($showDay->getDbFirstShow()." ".$showDay->getDbStartTime(), - new DateTimeZone($showDay->getDbTimezone())); - $dt->setTimezone(new DateTimeZone("UTC")); - - return $dt->format("Y-m-d H:i"); - } - - /** - * - * Returns a CcShowDays object of the show that - * is currently being edited. - */ - public function getCurrentShowDay() - { - return CcShowDaysQuery::create()->filterByDbShowId($this->showId) - ->findOne(); - } - - public function getRepeatingEndDate() - { - $sql = << $this->showId ), 'column' ); - - return ($query !== false) ? $query : false; - } - - public function getNextStartDateTime($showDay) - { - $nextPopDate = $showDay->getDbNextPopDate(); - $startTime = $showDay->getDbStartTime(); - - if (isset($nextPopDate)) { - return $nextPopDate." ".$startTime; - } else { - return $showDay->getDbFirstShow()." ".$startTime; - } - } -} \ 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..38f4129ff --- /dev/null +++ b/airtime_mvc/application/services/ShowFormService.php @@ -0,0 +1,334 @@ +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"))); + } + + /** + * + * Delegates populating each show form with the appropriate + * data of the current show being edited + * + * @param $forms + */ + public function delegateFormPopulation($forms) + { + $this->populateFormWhat($forms["what"]); + $this->populateFormWhen($forms["when"]); + $this->populateFormRepeats($forms["repeats"]); + $this->populateFormWho($forms["who"]); + $this->populateFormStyle($forms["style"]); + $this->populateFormRecord($forms["record"]); + $this->populateFormRebroadcastRelative($forms["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 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")); + + $form->populate( + array( + 'add_show_repeat_type' => $ccShowDays[0]->getDbRepeatType(), + 'add_show_day_check' => $days, + 'add_show_end_date' => $repeatEndDate->format("Y-m-d"), + 'add_show_no_end' => (!$service_show->getRepeatingEndDate()))); + } + + 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 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)); + } + + public 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); + } + + /** + * + * 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 + */ + private function getNextFutureRepeatShowTime() + { + $sql = << now() at time zone 'UTC' +AND show_id = :showId +ORDER BY starts +LIMIT 1 +SQL; + $result = Application_Common_Database::prepareAndExecute( $sql, + array( 'showId' => $this->ccShow->getDbId() ), 'all' ); + + foreach ($result as $r) { + $starts = new DateTime($r["starts"], new DateTimeZone('UTC')); + $ends = new DateTime($r["ends"], 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; + } + } +} \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowInstanceService.php b/airtime_mvc/application/services/ShowInstanceService.php deleted file mode 100644 index bf9d2b392..000000000 --- a/airtime_mvc/application/services/ShowInstanceService.php +++ /dev/null @@ -1,614 +0,0 @@ -service_show = new Application_Service_ShowService(); - $this->service_user = new Application_Service_UserService(); - } - - /** - * - * Receives a cc_show id and determines whether to create a - * single show instance or repeating show instances - */ - public function delegateShowInstanceCreation($showId, $isRebroadcast, $isUpdate) - { - $populateUntil = $this->service_show->getPopulateShowUntilDateTIme(); - - $this->service_showDays = new Application_Service_ShowDaysService($showId); - $showDays = $this->service_showDays->getShowDays(); - - foreach ($showDays as $day) { - switch ($day->getDbRepeatType()) { - case NO_REPEAT: - $this->createNonRepeatingShowInstance($day, $populateUntil, $isRebroadcast, $isUpdate); - break; - case REPEAT_WEEKLY: - $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P7D", $isRebroadcast, $isUpdate); - break; - case REPEAT_BI_WEEKLY: - $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P14D", $isRebroadcast); - break; - case REPEAT_MONTHLY_MONTHLY: - $this->createMonthlyRepeatingShowInstances($day, $populateUntil, "P1M", $isRebroadcast); - break; - case REPEAT_MONTHLY_WEEKLY: - // do something here - break; - } - } - Application_Model_RabbitMq::PushSchedule(); - } - - /** - * - * Sets a single cc_show_instance table row - * @param $showDay - * @param $populateUntil - */ - private function createNonRepeatingShowInstance($showDay, $populateUntil, $isRebroadcast, $isUpdate) - { - $start = $showDay->getDbFirstShow()." ".$showDay->getDbStartTime(); - - list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( - $start, $showDay->getDbDuration(), $showDay->getDbTimezone()); - - if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { - $ccShowInstance = new CcShowInstances(); - if ($isUpdate) { - $ccShowInstance = $this->getInstance($utcStartDateTime, $showDay->getDbShowId()); - } - $ccShowInstance->setDbShowId($showDay->getDbShowId()); - $ccShowInstance->setDbStarts($utcStartDateTime); - $ccShowInstance->setDbEnds($utcEndDateTime); - $ccShowInstance->setDbRecord($showDay->getDbRecord()); - $ccShowInstance->save(); - - if ($isRebroadcast) { - $this->createRebroadcastShowInstances($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 createWeeklyRepeatingShowInstances($showDay, $populateUntil, - $repeatInterval, $isRebroadcast, $isUpdate) - { - $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(); - - $start = $this->service_showDays->getNextStartDateTime($showDay); - - $datePeriod = $this->getDatePeriod($start, $timezone, $last_show, - $repeatInterval, $populateUntil); - - $utcLastShowDateTime = $last_show ? - Application_Common_DateHelper::ConvertToUtcDateTime($last_show, $timezone) : null; - - $utcEndDateTime = null; - foreach ($datePeriod as $date) { - list($utcStartDateTime, $utcEndDateTime) = $this->service_show->createUTCStartEndDateTime( - $date->format("Y-m-d H:i:s"), $duration, $timezone); - /* - * 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 ($isUpdate && $this->hasInstance($utcStartDateTime, $show_id)) { - $ccShowInstance = $this->getInstance($utcStartDateTime, $show_id); - $newInstance = false; - } else { - $newInstance = true; - $ccShowInstance = new CcShowInstances(); - } - - /* 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 ($isRebroadcast) { - $this->createRebroadcastInstances($showDay, $date->format("Y-m-d"), $ccShowInstance->getDbId()); - } - } - } - $nextDate = $utcEndDateTime->add(new DateInterval($repeatInterval)); - $this->service_show->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $show_id, $day); - } - - /** - * - * Enter description here ... - * @param $showDay - */ - private function createRebroadcastInstances($showDay, $showStartDate, $instanceId) - { - $currentUtcTimestamp = gmdate("Y-m-d H:i:s"); - $showId = $showDay->getDbShowId(); - - $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->service_show->createUTCStartEndDateTime( - $showStartDate, $showDay->getDbDuration(), $showDay->getDbTimezone(), $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(); - } - } - } - - public function updateScheduleStatus($showId) - { - $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); - $instances = CcShowInstancesQuery::create() - ->filterByDbEnds(gmdate("Y-m-d H:i:s"), Criteria::GREATER_THAN) - ->filterByDbShowId($showId) - ->find(); - - foreach ($instances as $instance) { - $instance->updateScheduleStatus($con); - } - } - - public function deleteRebroadcastInstances($showId) - { - $sql = << :timestamp::TIMESTAMP -AND show_id = :showId -AND rebroadcast = 1; -SQL; - Application_Common_Database::prepareAndExecute( $sql, array( - ':showId' => $showId, - ':timestamp' => gmdate("Y-m-d H:i:s")), 'execute'); - } - - /** - * - * 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(new DateTime($start, new DateTimeZone($timezone)), - new DateInterval($repeatInterval), $endDatePeriod); - } - - /** - * - * Returns 2 DateTime objects, in the user's local time, - * of the next future repeat show instance start and end time - */ - public function getNextFutureRepeatShowTime($showId) - { - $sql = << now() at time zone 'UTC' -AND show_id = :showId -ORDER BY starts -LIMIT 1 -SQL; - $result = Application_Common_Database::prepareAndExecute( $sql, - array( 'showId' => $showId ), 'all' ); - - foreach ($result as $r) { - $show["starts"] = new DateTime($r["starts"], new DateTimeZone('UTC')); - $show["ends"] = new DateTime($r["ends"], new DateTimeZone('UTC')); - } - - $userTimezone = Application_Model_Preference::GetUserTimezone( - $this->service_user->getCurrentUser()->getDbId()); - - $show["starts"]->setTimezone(new DateTimeZone($userTimezone)); - $show["ends"]->setTimezone(new DateTimeZone($userTimezone)); - - return $show; - } - - /** - * - * Returns all the show instances of the show currently - * being edited. - * @param $showId - */ - public function getCurrentInstances($showId) - { - return CcShowInstancesQuery::create() - ->filterByDbShowId($showId) - ->filterByDbModifiedInstance(false) - ->orderBy("starts"); - } - - /** - * - * 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)) - */ - public function getInstance($starts, $showId) - { - $ccShowInstance = CcShowInstancesQuery::create() - ->filterByDbStarts($starts->format("Y-m-d H:i:s"), Criteria::EQUAL) - ->filterByDbShowId($showId, Criteria::EQUAL) - ->filterByDbModifiedInstance(false, Criteria::EQUAL) - ->filterByDbRebroadcast(0, Criteria::EQUAL) - ->limit(1) - ->find(); - - if ($ccShowInstance->isEmpty()) { - return false; - } else { - return $ccShowInstance[0]; - } - } - - public function hasInstance($starts, $showId) - { - return $this->getInstance($starts, $showId) ? true : false; - } - - public function getAllFutureInstanceIds($showId) - { - $sql = << :timestamp::TIMESTAMP - AND modified_instance != TRUE -SQL; - $rows = Application_Common_Database::prepareAndExecute($sql, - array( ':showId' => $showId, - ':timestamp' => gmdate("Y-m-d H:i:s")), "all"); - - $ids = array(); - foreach ($ids as $id) { - $ids[] = $id['id']; - } - return $ids; - } - - /** - * - * Returns the difference in seconds between a show's new and - * old start time - * - * @param $newStartDateTime DateTime object - * @param $oldStartDateTime DateTime object - */ - public function calculateShowStartDiff($newStartDateTime, $oldStartDateTime) - { - return $newStartDateTime->getTimestamp() - $oldStartDateTime->getTimestamp(); - } - - /** - * 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 - */ - public function deleteInvalidInstances($showData, $isRecorded, $repeatType) - { - $showId = $showData["add_show_id"]; - - $this->service_showDays = new Application_Service_ShowDaysService($showId); - //ccShowDays object of the show being edited - $currentShowDay = $this->service_showDays->getCurrentShowDay(); - - //new end date in users' local time - $endDateTime = $this->service_showDays->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 ($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($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 && $repeatType != $currentRepeatType) { - //repeat type changed - $this->deleteAllInstances($showId); - } else { - //repeat type is the same, check if the days of the week are the same - $repeatingDaysChanged = false; - - $ccShowDays = $this->service_showDays->getShowDays(); - $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']); - - 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->service_showDays->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 - } - - public function applyShowStartEndDifference($showData, $showId) - { - $currentShowDay = $this->service_showDays->getCurrentShowDay(); - - $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($showId, $diff); - $instanceIds = $this->getAllFutureInstanceIds($showId); - Application_Service_ScheduleService::updateScheduleStartTime($instanceIds, $diff); - } - - /** - * - * Updates the start and end time for cc_show_instances - * - * @param $showData edit show form data - */ - public function updateInstanceStartEndTime($showId, $diff) - { - $sql = << :timestamp::TIMESTAMP -SQL; - - Application_Common_Database::prepareAndExecute($sql, - array(':diff1' => $diff, ':diff2' => $diff, - ':showId' => $showId, ':timestamp' => gmdate("Y-m-d H:i:s")), - 'execute'); - } - - public 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'); - } - - public 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'); - } - - /** - * - * 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 - */ - public 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'); - } - } - - $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 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"); - } - - public 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'); - } - -/* public function updateInstanceDuration($showData) - { - $sql = << :timestamp::TIMESTAMP -SQL; - - Application_Common_Database::prepareAndExecute( $sql, array( - ':add_show_duration' => $showData['add_show_duration'], - ':show_id' => $showData['add_show_id'], - ':timestamp' => gmdate("Y-m-d H:i:s")), "execute"); - }*/ -} \ No newline at end of file diff --git a/airtime_mvc/application/services/ShowService.php b/airtime_mvc/application/services/ShowService.php index 7747a32af..746264bdf 100644 --- a/airtime_mvc/application/services/ShowService.php +++ b/airtime_mvc/application/services/ShowService.php @@ -1,8 +1,681 @@ ccShow = CcShowQuery::create()->findPk($showId); + } + + $service_user = new Application_Service_UserService(); + $this->currentUser = $service_user->getCurrentUser(); + } + + public function addUpdateShow($showData, $isUpdate=false) + { + $repeatType = ($showData['add_show_repeats']) ? $showData['add_show_repeat_type'] : -1; + $isRecorded = (isset($showData['add_show_record']) && $showData['add_show_record']) ? 1 : 0; + $isRebroadcast = (isset($showData['add_show_rebroadcast']) && $showData['add_show_rebroadcast']) ? 1 : 0; + + $showData["add_show_duration"] = $this->formatShowDuration( + $showData["add_show_duration"]); + + $con = Propel::getConnection(); + $con->beginTransaction(); + try { + if (!$this->currentUser->isAdminOrPM()) { + throw new Exception("Permission denied"); + } + //update ccShow + $this->setCcShow($showData, $isUpdate); + + if ($isUpdate) { + $this->delegateInstanceCleanup($showData, $isRecorded, $repeatType); + // updates cc_show_instances start/end times, and updates + // schedule start/end times + $this->applyShowStartEndDifference($showData); + $this->deleteRebroadcastInstances(); + $this->deleteCcShowDays(); + $this->deleteCcShowHosts(); + if ($isRebroadcast) { + //delete entry in cc_show_rebroadcast + $this->deleteCcShowRebroadcasts(); + } + } + + //update ccShowDays + $this->setCcShowDays($showData, $repeatType, $isRecorded); + + //update ccShowRebroadcasts + $this->setCcShowRebroadcasts($showData, $repeatType, $isRecorded); + + //update ccShowHosts + $this->setCcShowHosts($showData); + + //create new ccShowInstances + $this->delegateInstanceCreation($isRebroadcast, $isUpdate); + + $con->commit(); + Application_Model_RabbitMq::PushSchedule(); + } catch (Exception $e) { + $con->rollback(); + $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 + */ + private function delegateInstanceCreation($isRebroadcast, $isUpdate) + { + $populateUntil = $this->getPopulateShowUntilDateTIme(); + + $ccShowDays = $this->ccShow->getCcShowDays(); + + foreach ($ccShowDays as $day) { + switch ($day->getDbRepeatType()) { + case NO_REPEAT: + $this->createNonRepeatingShowInstance($day, $populateUntil, $isRebroadcast, $isUpdate); + break; + case REPEAT_WEEKLY: + $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P7D", $isRebroadcast, $isUpdate); + break; + case REPEAT_BI_WEEKLY: + $this->createWeeklyRepeatingShowInstances($day, $populateUntil, "P14D", $isRebroadcast, $isUpdate); + break; + case REPEAT_MONTHLY_MONTHLY: + $this->createMonthlyRepeatingShowInstances($day, $populateUntil, "P1M", $isRebroadcast); + break; + case REPEAT_MONTHLY_WEEKLY: + // do something here + break; + } + } + } + + 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, $isRecorded, $repeatType) + { + $showId = $this->ccShow->getDbId(); + + //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 ($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($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 && $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']); + + 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 + } + + 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'); + } + } + + $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"); + } + + 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_ScheduleService::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 createNonRepeatingShowInstance($showDay, $populateUntil, $isRebroadcast, $isUpdate) + { + //DateTime object + $start = $showDay->getLocalStartDateAndTime(); + + list($utcStartDateTime, $utcEndDateTime) = $this->createUTCStartEndDateTime( + $start, $showDay->getDbDuration()); + + if ($utcStartDateTime->getTimestamp() < $populateUntil->getTimestamp()) { + $ccShowInstance = new CcShowInstances(); + if ($isUpdate) { + $ccShowInstance = $this->getInstance($utcStartDateTime); + } + $ccShowInstance->setDbShowId($this->ccShow->getDbId()); + $ccShowInstance->setDbStarts($utcStartDateTime); + $ccShowInstance->setDbEnds($utcEndDateTime); + $ccShowInstance->setDbRecord($showDay->getDbRecord()); + $ccShowInstance->save(); + + if ($isUpdate) { + $con = Propel::getConnection(CcSchedulePeer::DATABASE_NAME); + $ccShowInstance->updateScheduleStatus($con); + } + + if ($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 createWeeklyRepeatingShowInstances($showDay, $populateUntil, + $repeatInterval, $isRebroadcast, $isUpdate) + { + $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(); + + //string + $start = $this->getNextRepeatingPopulateStartDateTime($showDay); + + //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; + + $utcEndDateTime = null; + 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 ($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 ($isRebroadcast) { + $this->createRebroadcastInstances($showDay, $date, $ccShowInstance->getDbId()); + } + } + } + $nextDate = $utcEndDateTime->add(new DateInterval($repeatInterval)); + $this->setNextRepeatingShowDate($nextDate->format("Y-m-d"), $day); + } + + private function getNextRepeatingPopulateStartDateTime($showDay) + { + $nextPopDate = $showDay->getDbNextPopDate(); + $startTime = $showDay->getDbStartTime(); + + if (isset($nextPopDate)) { + return $nextPopDate." ".$startTime; + } else { + return $showDay->getDbFirstShow()." ".$startTime; + } + } + + /** + * + * 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(new DateTime($start, new DateTimeZone($timezone)), + new DateInterval($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]; + } + } /** * @@ -10,7 +683,7 @@ class Application_Service_ShowService * @param $ccShow * @param $showData */ - public function setShow($showData, $isUpdate) + private function setCcShow($showData, $isUpdate) { if (!$isUpdate) { $ccShow = new CcShow(); @@ -30,7 +703,83 @@ class Application_Service_ShowService $ccShow->setDbLiveStreamPass($showData['custom_password']); $ccShow->save(); - return $ccShow; + $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, $repeatType, $isRecorded) + { + $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($repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($isRecorded); + $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($repeatType); + $showDay->setDbShowId($showId); + $showDay->setDbRecord($isRecorded); + $showDay->save(); + } + } + } } /** @@ -39,9 +788,9 @@ class Application_Service_ShowService * that is currently being edited. They will get recreated with * the new show specs */ - public function deleteShowRebroadcasts($showId) + private function deleteCcShowRebroadcasts() { - CcShowRebroadcastQuery::create()->filterByDbShowId($showId)>delete(); + CcShowRebroadcastQuery::create()->filterByDbShowId($this->ccShow->getDbId())->delete(); } /** @@ -52,10 +801,12 @@ class Application_Service_ShowService * @param $repeatType * @param $isRecorded */ - public function setShowRebroadcasts($showData, $showId, $repeatType, $isRecorded) + private function setCcShowRebroadcasts($showData, $repeatType, $isRecorded) { + $showId = $this->ccShow->getDbId(); + if (($isRecorded && $showData['add_show_rebroadcast']) && ($repeatType != -1)) { - for ($i=1; $i<=self::MAX_REBROADCAST_DATES; $i++) { + 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]); @@ -65,7 +816,7 @@ class Application_Service_ShowService } } } elseif ($isRecorded && $showData['add_show_rebroadcast'] && ($repeatType == -1)) { - for ($i=1; $i<=self::MAX_REBROADCAST_DATES; $i++) { + 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']); @@ -87,9 +838,9 @@ class Application_Service_ShowService * that is currently being edited. They will get recreated with * the new show specs */ - public function deleteShowHosts($showId) + private function deleteCcShowHosts() { - CcShowHostsQuery::create()->filterByDbShow($showId)->delete(); + CcShowHostsQuery::create()->filterByDbShow($this->ccShow->getDbId())->delete(); } /** @@ -98,12 +849,12 @@ class Application_Service_ShowService * @param $showData * @param $showId */ - public function setShowHosts($showData, $showId) + private function setCcShowHosts($showData) { if (is_array($showData['add_show_hosts'])) { foreach ($showData['add_show_hosts'] as $host) { $showHost = new CcShowHosts(); - $showHost->setDbShow($showId); + $showHost->setDbShow($this->ccShow->getDbId()); $showHost->setDbHost($host); $showHost->save(); } @@ -117,7 +868,7 @@ class Application_Service_ShowService * * @return DateTime object */ - public function getPopulateShowUntilDateTIme() + private function getPopulateShowUntilDateTIme() { $populateUntil = Application_Model_Preference::GetShowsPopulatedUntil(); @@ -131,24 +882,15 @@ class Application_Service_ShowService /** * * Enter description here ... - * @param $localStart timestring format "Y-m-d H:i:s" (not UTC) - * @param $duration string time interval (h)h:(m)m(:ss) - * @param $timezone string "Europe/Prague" - * @param $offset array (days, hours, mins) used for rebroadcast shows + * @param DateTime $startDateTime 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 */ - public function createUTCStartEndDateTime($localStart, $duration, $timezone=null, $offset=null) + private function createUTCStartEndDateTime($startDateTime, $duration, $offset=null) { - $userInfo = Zend_Auth::getInstance()->getStorage()->read(); - $user = new Application_Model_User($userInfo->id); - $isAdminOrPM = $user->isUserType(array(UTYPE_ADMIN, UTYPE_PROGRAM_MANAGER)); - - if (!isset($timezone)) { - $timezone = Application_Model_Preference::GetUserTimezone($user->getId()); - } - - $startDateTime = new DateTime($localStart, new DateTimeZone($timezone)); if (isset($offset)) { $startDateTime->add(new DateInterval("P{$offset["days"]}DT{$offset["hours"]}H{$offset["mins"]}M")); } @@ -174,12 +916,12 @@ class Application_Service_ShowService * @param $showId * @param $day */ - public function setNextRepeatingShowDate($nextDate, $showId, $day) + private function setNextRepeatingShowDate($nextDate, $day) { $nextInfo = explode(" ", $nextDate); $repeatInfo = CcShowDaysQuery::create() - ->filterByDbShowId($showId) + ->filterByDbShowId($this->ccShow->getDbId()) ->filterByDbDay($day) ->findOne(); diff --git a/airtime_mvc/public/js/airtime/schedule/schedule.js b/airtime_mvc/public/js/airtime/schedule/schedule.js index 57dc8def5..a4fd1851e 100644 --- a/airtime_mvc/public/js/airtime/schedule/schedule.js +++ b/airtime_mvc/public/js/airtime/schedule/schedule.js @@ -387,14 +387,14 @@ $(document).ready(function() { //edit this instance and all callback = function() { - $.get(edit.all.url, {format: "json", id: data.id, type: "all"}, function(json){ + $.get(edit.all.url, {format: "json", showId: data.showId, instanceId: data.id, type: "all"}, function(json){ beginEditShow(json); }); }; edit.all.callback = callback; }else{ callback = function() { - $.get(oItems.edit.url, {format: "json", id: data.id, type: oItems.edit._type}, function(json){ + $.get(oItems.edit.url, {format: "json", showId: data.showId, instanceId: data.id, type: oItems.edit._type}, function(json){ beginEditShow(json); }); };